diff --git a/.github/workflows/preflight-cli-platforms.yml b/.github/workflows/preflight-cli-platforms.yml index 566c3a27418..7d7fc9743bd 100644 --- a/.github/workflows/preflight-cli-platforms.yml +++ b/.github/workflows/preflight-cli-platforms.yml @@ -47,7 +47,6 @@ jobs: src/main/ipc/preflight-runnable-local-cli.test.ts src/main/ipc/preflight-wsl-agent-detection.test.ts src/main/ipc/preflight-windows-path-refresh.repro.test.ts - src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts src/main/startup/shell-environment/login-shell-environment.test.ts src/packages/process-host/src/process-tree-termination.test.ts src/packages/process-host/src/run-process.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 1f14decb770..abb87cb5770 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -397,7 +397,6 @@ 2 test-no-wall-clock:src/main/external-conversations/external-conversation-cancel-settlement.test.ts 3 test-no-wall-clock:src/main/external-conversations/external-conversation-cancel.test.ts 2 test-no-wall-clock:src/main/git/command-runner/host-routing/git-command-resolution-windows-checkout.test.ts -1 test-no-wall-clock:src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts 1 test-no-wall-clock:src/main/git/refs/maintenance/pack-refs-lock-ownership.test.ts 2 test-no-wall-clock:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts 1 test-no-wall-clock:src/main/git/source-control/diffs/blob-absence-real-git.test.ts @@ -500,9 +499,7 @@ 1 test-no-wall-clock:src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx 2 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/removal/use-workspace-cleanup-removal.agent-stop.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts -1 test-no-wall-clock:src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts 1 test-no-wall-clock:src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts -2 test-no-wall-clock:src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts 5 test-no-wall-clock:src/renderer/src/store/slices/worktrees/metadata/worktree-meta-hosted-review.test.ts 1 test-no-wall-clock:src/shared/__tests__/process-host/windows-cmd-shim-resolution.test.ts 7 test-no-wall-clock:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index ce456df31ec..c38bf65d136 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2255,13 +2255,13 @@ "providers": ["local", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. The integrated mobile markdown close/frame-settlement case remains unchanged and is narrower. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 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): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. 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. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. Audit5612 retires the remaining integrated mobile markdown close/frame-settlement suite, accepting loss of its closed-editor snapshot republishing alarm without replacement or fresh validation. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 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): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. 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. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4965", "https://github.com/stablyai/orca/pull/15371" ], "invariant": "Candidate identity is the tuple of execution-host identity and worktree identity: same-id sibling hosts retain separate correct browser, simulator, and workspace tabs, each tab appears exactly once, and selection activates its owning host.", - "oracle": "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. The integrated mobile markdown close/frame-settlement case remains unchanged and is narrower. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior 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: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", + "oracle": "Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. Audit5612 retires the remaining integrated mobile markdown close/frame-settlement suite, accepting loss of its closed-editor snapshot republishing alarm without replacement or fresh validation. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior 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: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", @@ -5880,7 +5880,7 @@ "providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon"], - "coverageNotes": "Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. 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): Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", + "coverageNotes": "Audit5605 retires complete low-value suites src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts. Intentionally lose live/future pane authority transfer and detached-pane non-stealing alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. 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): Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/11757", "https://github.com/stablyai/orca/pull/11726" @@ -5888,14 +5888,13 @@ "invariant": "Within one terminal tab, each PTY has at most one layout leaf, pane manager surface, and xterm renderer owner. Restore and remote mirroring must normalize duplicate ownership before replay while retaining active-leaf focus, scrollback, pane authority, agent metadata, and distinct sibling PTYs.", "oracle": "Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. 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): Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Component contracts cover persisted replay, rootless and repeated-leaf layouts, metadata repair, and deeply nested input. Retained store contracts cover live/future authority transfer onto a retained leaf and preservation of a prior detach destination.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts", "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts", - "src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts", "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts" ], "assertionRefs": [ @@ -5907,13 +5906,6 @@ "file": "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts", "assertions": ["keeps the active leaf and prunes the stale surface plus its metadata"] }, - { - "file": "src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts", - "assertions": [ - "moves live and future pane authority onto the retained PTY leaf", - "does not steal authority from a pane that was already detached to another tab" - ] - }, { "file": "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts", "assertions": ["repairs duplicate persisted PTY renderers before streaming tab reveal"] @@ -5960,7 +5952,9 @@ "The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage.", "The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage.", "The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", - "Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. 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. Exact retired authored alarms: 'keeps the first layout leaf when focus belongs to another PTY'; 'repairs rootless duplicate ownership in one idempotent pass'; 'repairs dangling rooted selection during direct ownership normalization'; 'preserves PTY ownership while collapsing repeated live leaf ids'; 'preserves valid split layouts by identity'." + "Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. 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. Exact retired authored alarms: 'keeps the first layout leaf when focus belongs to another PTY'; 'repairs rootless duplicate ownership in one idempotent pass'; 'repairs dangling rooted selection during direct ownership normalization'; 'preserves PTY ownership while collapsing repeated live leaf ids'; 'preserves valid split layouts by identity'.", + "Audit5605 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts --reporter=dot", + "Audit5605 removed assertion references: [{\"file\":\"src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts\",\"assertions\":[\"moves live and future pane authority onto the retained PTY leaf\",\"does not steal authority from a pane that was already detached to another tab\"]}]" ], "demotionRule": "Keep experimental or demote if ownership cardinality flakes, duplicate replay reaches a second renderer, active metadata or authority moves to the wrong leaf, deep normalization regresses, or a supported provider bypasses normalization." }, @@ -6113,7 +6107,7 @@ "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "Audit5583 removes the entire src/renderer/src/store/terminals/retirement/terminal-tab-retirement-store.test.ts suite and its active selectors. Intentionally lose mocked terminal tab retirement choreography alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. 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. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. 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. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. 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. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. 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): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: 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: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence 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. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. 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.", + "coverageNotes": "Audit5611 retires complete low-value suites src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts. Intentionally lose pane restoration, closed-tab refusal and round-trip status alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit5583 removes the entire src/renderer/src/store/terminals/retirement/terminal-tab-retirement-store.test.ts suite and its active selectors. Intentionally lose mocked terminal tab retirement choreography alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. 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. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. 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. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. 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. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. 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): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: 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: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence 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. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. 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.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4327", "https://github.com/stablyai/orca/pull/14590", @@ -6126,7 +6120,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1", @@ -6145,7 +6139,6 @@ "src/main/daemon/terminal-host/testing/terminal-host.test.ts", "src/main/providers/local-pty/local-pty-provider-shutdown.test.ts", "src/main/runtime/workspaces/removal/worktree-teardown.test.ts", - "src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts", "src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts", "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "tests/e2e/terminal-tab-close-restart-persistence.spec.ts", @@ -6310,7 +6303,9 @@ "Audit3437 complete prior testFiles before completed-worker-retirement-resume retirement: [\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts\",\"src/main/ipc/agent-hooks.test.ts\",\"src/main/ipc/agent-pane-authority-ownership.test.ts\",\"src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts\",\"src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts\",\"src/main/pty/process-retirement/pty-descendant-termination.test.ts\",\"src/main/daemon/sessions/testing/session.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/providers/local-pty/local-pty-provider-shutdown.test.ts\",\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts\",\"src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts\",\"src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts\",\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\"tests/e2e/terminal-parked-close-retirement.spec.ts\",\"tests/e2e/agent-descendant-process-kill.spec.ts\",\"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\"]", "Audit3437 complete prior assertionRefs before completed-worker-retirement-resume retirement: [{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"assertions\":[\"final-pane terminal.close remains pending until one renderer durability acknowledgement retires the persisted tab and layout\",\"final-pane externally owned teardown commits session retirement before PTY stop, tolerates duplicate exit retirement, and preserves an unrelated live canary\",\"post-ack workspace-session loss falls back to renderer cleanup and verified PTY teardown while every pre-ack retirement error remains non-destructive\",\"renderer reload with the same provider-attested PTY incarnation preserves the exact handle\",\"same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale\",\"hard graph loss and preallocated-handle supersession make the retained renderer handle deterministically stale\"]},{\"file\":\"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\"assertions\":[\"a durability-acknowledged whole-tab close leaves zero terminal tabs and provider sessions after restart\"]},{\"file\":\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"assertions\":[\"explicit close revokes the exact live recovery record both before and after PTY exit removes the tab, while PTY exit alone preserves interrupted-session recovery\"]},{\"file\":\"tests/e2e/terminal-parked-close-retirement.spec.ts\",\"assertions\":[\"a long-lived exact PTY remains alive after its terminal view is parked\",\"closing the parked tab removes the exact PTY from the provider inventory and the visible tab model\"]},{\"file\":\"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\"assertions\":[\"an attached-window desktop host publishes the CLI-created terminal under the renderer publication epoch it inherits, proving the vulnerable classification path was taken rather than a headless or serve/SSH-shaped one\",\"with the target as the first host-created terminal, a renderer graph sync leaves the `terminal.create` tab in the host session inventory still naming its original daemon PTY\",\"the original fixture process answers a write through that handle with its own pid and a single READY line, so a respawned replacement cannot pass as a survivor\",\"the paired client applied that same sync and kept the tab with no replacement or resume tab appended\",\"an unrelated workspace keeps its own CLI terminal and PTY, and the client raises no direct local connection attempt or uncaught renderer error\"]},{\"file\":\"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\",\"assertions\":[\"a windowless serve host publishes host-created terminals under a headless epoch, never a renderer one, which is why it cannot reach the window-conditioned prune the desktop arm reproduces\",\"a later CLI dispatch leaves the earlier host-created terminal in the serve-host inventory still bound to its original PTY\",\"both original fixture processes answer writes through their own handles after the later dispatch\",\"the paired client mirrors exactly those two tabs with no replacement or resume tab appended, no direct local connection attempt, and no uncaught renderer error\"]},{\"file\":\"src/main/ipc/agent-pane-authority-ownership.test.ts\",\"assertions\":[\"pane authority transfer accepts only the canonical legacy/scoped runtime handle bound to the authoritative pane\"]},{\"file\":\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"assertions\":[\"owned provider shutdowns start together so process-table snapshots can coalesce within a batch\",\"inventories above 32 sessions never exceed 32 concurrent provider shutdowns\"]},{\"file\":\"tests/e2e/agent-descendant-process-kill.spec.ts\",\"assertions\":[\"a detached-pgid descendant is alive before agent PTY kill and absent afterward\"]}]", "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.", - "Audit5583 exact prior command before retired suite selector removal: pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/retirement/terminal-tab-retirement-store.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts" + "Audit5583 exact prior command before retired suite selector removal: pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/retirement/terminal-tab-retirement-store.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "Audit5611 exact prior command before retired suite selector removal: pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "Audit5611 removed assertion references: []" ], "demotionRule": "Keep experimental or demote to protection none if exact PTY disappearance flakes, a sibling/detached pane is retired, late hooks can recreate closed authority, or a renderer graph sync retires a host-created tab that no explicit close retired." }, @@ -6986,7 +6981,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coverageNotes": "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. Audit4352 deletes the whole mocked daemon router, session-owner resolver, degraded-provider, terminal-host CWD-readability and foreground-inspection suites plus the native-process-CWD fixture suite; recovery retains only public multi-pane proactive socket-death notification/remount. Intentionally lose retirement admission, stale-inventory/fenced-kill authority, attach-only re-resolution/absence, fast-exit routing, sleep CWD checkpoint/wake, diagnostic cancellation/shutdown and foreground census/session-change alarms. No equivalent replacement or fresh gate execution is claimed. Historical prior account (preserved verbatim): 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. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. 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. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): 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): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. 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): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: 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): Audits1301 and1308 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 macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. 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. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.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. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit5605 retires complete low-value suites src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts. Intentionally lose serialization of newer convergence after an in-flight adoption conflict alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. 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. Audit4352 deletes the whole mocked daemon router, session-owner resolver, degraded-provider, terminal-host CWD-readability and foreground-inspection suites plus the native-process-CWD fixture suite; recovery retains only public multi-pane proactive socket-death notification/remount. Intentionally lose retirement admission, stale-inventory/fenced-kill authority, attach-only re-resolution/absence, fast-exit routing, sleep CWD checkpoint/wake, diagnostic cancellation/shutdown and foreground census/session-change alarms. No equivalent replacement or fresh gate execution is claimed. Historical prior account (preserved verbatim): 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. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. 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. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): 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): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. 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): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: 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): Audits1301 and1308 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 macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. 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. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.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. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8878", "https://github.com/stablyai/orca/issues/9151", @@ -7007,7 +7002,7 @@ "VITE_EXPOSE_STORE=true pnpm run build:web", "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", "Manual headed paired-server journey: isolated Orca desktop host + separate paired web client + real Codex process + 20-second WebSocket fault + reconnect + explicit stop", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts", "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts" ], @@ -7027,7 +7022,6 @@ "config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs", "tests/e2e/remote-terminal-tab-retirement.unit.test.ts", - "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts", "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts", "src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts" ], @@ -7102,12 +7096,6 @@ { "file": "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts", "assertions": ["mirrors a new CLI tab after old-host recovery when $name"] - }, - { - "file": "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts", - "assertions": [ - "serializes a newer convergence snapshot after an in-flight adoption conflict" - ] } ], "evidenceRuns": [ @@ -7258,7 +7246,9 @@ "Complete prior testFiles before exact deleted selectors were pruned: [\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/daemon/providers/routing/testing/daemon-pty-router.test.ts\",\"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\"src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts\",\"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\",\"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts\",\"src/shared/claimed-agent-pty-owner.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts\",\"src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts\",\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\"tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\",\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\"]", "Complete prior assertionRefs before exact deleted selectors were pruned: [{\"file\":\"src/main/daemon/providers/routing/testing/degraded-daemon-pty-provider.test.ts\",\"assertions\":[\"completion inspection rejects an unmapped session instead of borrowing the local fallback\"]},{\"file\":\"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\"assertions\":[\"transport loss remains unknown through reconnect and cannot dispatch completion\",\"returned unavailability or a thrown transport failure interrupts consecutive-idle proof and requires two fresh authoritative idle samples\",\"explicit stop, real exit status, and genuine successful completion remain distinct\"]},{\"file\":\"src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts\",\"assertions\":[\"one unreachable pane cannot suppress restart notices for another authoritatively confirmed Codex pane\"]},{\"file\":\"src/shared/claimed-agent-pty-owner.test.ts\",\"assertions\":[\"concurrent exact claims spawn once and later callers adopt the canonical owner\",\"same identity in another worktree conflicts and cannot be found as the current scope's owner\",\"generation-guarded exit and authoritative reconciliation cannot retire a replacement owner\"]},{\"file\":\"src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts\",\"assertions\":[\"independent runtime clients converge on one canonical live agent-session owner\",\"retries and concurrent requests cannot create a second physical PTY\"]},{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"assertions\":[\"an exact PTY exit retires host membership and stale topology cannot recreate the surface\",\"incarnation fencing prevents an old delayed exit from retiring a replacement PTY\"]},{\"file\":\"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\"assertions\":[\"headed desktop host remains unfocused while the paired requester alone follows active fresh/resume sessions and inactive rows preserve exact client/DOM focus\",\"legacy afterTabId placement is exact in authoritative, mirrored, and rendered order with a pre-existing successor\",\"host PTY inventory plus writable agent/unrelated shell markers prove liveness, unrelated survival, and exact terminal/tab/PTY/process cleanup\"]},{\"file\":\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"assertions\":[\"headless focused fresh/resume requests create background host surfaces without a renderer window\",\"dropped committed responses replay the same operation identity without another tokened agent spawn\",\"exact terminal/tab/process identity survives retries and stale-write rejection, then retires without restart resurrection while unrelated shells survive until scoped cleanup\"]},{\"file\":\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\"assertions\":[\"isolated daemon roots and captured descendants are verified dead before profile PID records are removed\"]},{\"file\":\"tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"assertions\":[\"a durable host exit removes the terminal from two independent viewer mirrors instead of publishing a handle-less phantom\",\"one exact exit produces one same-epoch higher-version host publication and one durable persistence flush\",\"same-epoch stale publications cannot resurrect the retired surface after reconnect\"]},{\"file\":\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\",\"assertions\":[\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\",\"retains exact-leaf focus intent when a split sibling publishes first\"]},{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\",\"assertions\":[\"mirrors a new CLI tab after old-host recovery when $name\"]},{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"assertions\":[\"serializes a newer convergence snapshot after an in-flight adoption conflict\"]}]", "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.", - "Audit4960 removes the mock-boundary notification-settings factory from the completion wrapper. Settings/inspection race, completion-over-bell priority and bell fallback alarms are intentionally lost without replacement; dated receipts keep their original scope and do not validate this reduced factory set." + "Audit4960 removes the mock-boundary notification-settings factory from the completion wrapper. Settings/inspection race, completion-over-bell priority and bell fallback alarms are intentionally lost without replacement; dated receipts keep their original scope and do not validate this reduced factory set.", + "Audit5605 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1", + "Audit5605 removed assertion references: [{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"assertions\":[\"serializes a newer convergence snapshot after an in-flight adoption conflict\"]}]" ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if a retry can physically spawn twice, if a stale exit/publication can replace or resurrect a terminal, or if mixed-version fallback occurs after an authority side effect." }, @@ -13442,7 +13432,7 @@ "providers": ["local-daemon", "ssh-daemon", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon", "paired-runtime"], - "coverageNotes": "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. 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): Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: 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): Deterministic policy and multiplex tests separate renderer parking from authoritative stream liveness, while runtime-graph tests cover exact parked leaf, pane runtime ID, title, multi-pane active-leaf, disposal behavior, and queued split routing to an exact cold-parked tab. A real Electron journey runs the shipped dev CLI against the app's isolated profile, proves the exact parked target alone remounts under a bounded lease, completes before the historical 10-second timeout without stealing active tab or focus, re-parks, then reveals two stable-identity panes with independent keyboard/output round trips. Focused mirror-recovery tests preserve a verified binding across pending-handle snapshots, quarantine positive PTY-identity mismatches, accept authoritative ready replacement or removal, and fence recovery to the pairing revision. Daemon attach-only tests prove a replacement runtime re-registers one active session and one history writer. Headed cold-park and headless runtime-restart paired journeys prove rendered output, input, resize convergence, process identity, authoritative close, checkpoint continuity, and post-restart history append against real daemon PTYs. The parked-leaf graph fixture now retains only PTY exit during the park handoff gap. Its standalone exact leaf/title, multi-pane active-leaf and disposal assertions were removed. web-runtime-session.test.ts no longer supplies the eager worktree-switch/post-create recovery assertion. Those alarms are lost; the remaining cold-park and recovery journeys do not establish equivalent replacement coverage. Recovery references retain old-host-to-new-tab mirroring, adoption/list recovery, blocked local ownership changes, coalescing/overtaking/global concurrency, adoption-conflict serialization and pane-resolution retries. Stable unsupported/malformed adoption tables, supplied inventory/topology/identity and verified-binding shape examples were removed. Their separate alarms are lost; remaining compositions are not equivalent coverage. Historical executed commands and results remain historical. The separate Unsubscribe-to-raw-subscriber-veto-clear sample was removed. Its exact raw-presence transition alarm is lost; remaining fake-provider streaming/attachment checks and real paired journeys do not establish equivalent replacement coverage. The deterministic second subscription is a second live connection, not a disconnect/reconnect proof. Audit1292: The entire orphan-inventory retry suite is removed. Unchanged-snapshot retry for temporarily absent, pending or attached PTYs, live-binding preservation, and consecutive-absence confirmation reset after a ready frame are lost. Mock adoption/list behavior and assembled snapshot handling did not establish actual orphan adoption or equivalent replacement coverage. Audit1342: src/renderer/src/runtime/web-session-terminal-orphan-recovery-regressions.test.ts reduced. Exact global RPC concurrency4/counts for fabricated worktrees. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit5605 retires complete low-value suites src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts. Intentionally lose serialization of newer convergence after an in-flight adoption conflict alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. 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): Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: 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): Deterministic policy and multiplex tests separate renderer parking from authoritative stream liveness, while runtime-graph tests cover exact parked leaf, pane runtime ID, title, multi-pane active-leaf, disposal behavior, and queued split routing to an exact cold-parked tab. A real Electron journey runs the shipped dev CLI against the app's isolated profile, proves the exact parked target alone remounts under a bounded lease, completes before the historical 10-second timeout without stealing active tab or focus, re-parks, then reveals two stable-identity panes with independent keyboard/output round trips. Focused mirror-recovery tests preserve a verified binding across pending-handle snapshots, quarantine positive PTY-identity mismatches, accept authoritative ready replacement or removal, and fence recovery to the pairing revision. Daemon attach-only tests prove a replacement runtime re-registers one active session and one history writer. Headed cold-park and headless runtime-restart paired journeys prove rendered output, input, resize convergence, process identity, authoritative close, checkpoint continuity, and post-restart history append against real daemon PTYs. The parked-leaf graph fixture now retains only PTY exit during the park handoff gap. Its standalone exact leaf/title, multi-pane active-leaf and disposal assertions were removed. web-runtime-session.test.ts no longer supplies the eager worktree-switch/post-create recovery assertion. Those alarms are lost; the remaining cold-park and recovery journeys do not establish equivalent replacement coverage. Recovery references retain old-host-to-new-tab mirroring, adoption/list recovery, blocked local ownership changes, coalescing/overtaking/global concurrency, adoption-conflict serialization and pane-resolution retries. Stable unsupported/malformed adoption tables, supplied inventory/topology/identity and verified-binding shape examples were removed. Their separate alarms are lost; remaining compositions are not equivalent coverage. Historical executed commands and results remain historical. The separate Unsubscribe-to-raw-subscriber-veto-clear sample was removed. Its exact raw-presence transition alarm is lost; remaining fake-provider streaming/attachment checks and real paired journeys do not establish equivalent replacement coverage. The deterministic second subscription is a second live connection, not a disconnect/reconnect proof. Audit1292: The entire orphan-inventory retry suite is removed. Unchanged-snapshot retry for temporarily absent, pending or attached PTYs, live-binding preservation, and consecutive-absence confirmation reset after a ready frame are lost. Mock adoption/list behavior and assembled snapshot handling did not establish actual orphan adoption or equivalent replacement coverage. Audit1342: src/renderer/src/runtime/web-session-terminal-orphan-recovery-regressions.test.ts reduced. Exact global RPC concurrency4/counts for fabricated worktrees. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-2854", "https://github.com/stablyai/orca/pull/15514", @@ -13452,7 +13442,7 @@ "invariant": "Cold parking or restarting a host renderer/runtime never retires a live PTY's runtime-graph leaf, erases a paired viewer's last verified leaf binding merely because the host temporarily publishes pending-handle, or drops the surviving PTY's history writer. A split request for a cold-parked tab replays against its stable source leaf after exact-tab remount without switching workspaces or focusing the tab. The paired stream, input, resize, pane identity, multi-pane routing, checkpoint, and output log converge to the authoritative ready handle; the binding clears only after positive replacement, mismatch, or two consecutive authoritative absence observations without an intervening ready surface.", "oracle": "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. 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): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Cold-park a host-owned pane while a paired client actively views it, require the host manager to unmount, then type through the client and require the same PTY to receive and echo the token without any disconnected sample. Restart a real pinned-port headless runtime while its daemon PTY survives, observe a pending-handle snapshot, require the viewer binding never to become empty, then require rendered output, focused keyboard input, a post-recovery window resize, the pre-restart checkpoint, and post-restart output-log append to reach the same PTY and process before authoritative close clears the binding. Invoke the real `orca-dev terminal split` against a cold-parked renderer-owned tab, require only that tab to acquire and release the existing background-mount lease, complete before the historical timeout, preserve the active worktree/tab/focus, then reveal two rendered panes and type through each while retaining the stable source leaf and PTY. Deterministically require synchronous stable-leaf replay after lifecycle registration and fail closed for a missing or stale leaf. Separately publish multi-pane parked leaves with exact pane runtime IDs and require per-PTY disposal to remove only the retired leaf.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts --reporter=dot", "pnpm exec playwright test tests/e2e/host-parked-pane-remote-viewer.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -13466,7 +13456,6 @@ "src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts", "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts", "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts", - "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts", "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts", "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts", "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts", @@ -13525,12 +13514,6 @@ "file": "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts", "assertions": ["mirrors a new CLI tab after old-host recovery when $name"] }, - { - "file": "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts", - "assertions": [ - "serializes a newer convergence snapshot after an in-flight adoption conflict" - ] - }, { "file": "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts", "assertions": [ @@ -13602,7 +13585,9 @@ "Audit3362 historical original commands object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-adoption-regressions.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot\"", "Audit3362 historical original testFiles object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n\"src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-adoption-regressions.test.ts\"", "Audit3362 historical original assertionRefs object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-adoption-regressions.test.ts\",\n \"assertions\": [\n \"retries a transient thrown adoption on an unchanged semantic frame\",\n \"retains the client epoch and retries when the post-adoption list has $failure\",\n \"preserves prior terminal bindings after a post-adoption $failure and retries\",\n \"merges host-projected $verdict sibling state after adoption without treating pending as exited\",\n \"does not apply an adoption result after the local tab closes while adoption is blocked\",\n \"does not apply an adoption result after the local tab moves groups while adoption is blocked\"\n ]\n }", - "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. All prior notes and archived receipts retain original scopes." + "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. All prior notes and archived receipts retain original scopes.", + "Audit5605 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-parked-leaf.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot", + "Audit5605 removed assertion references: [{\"file\":\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts\",\"assertions\":[\"serializes a newer convergence snapshot after an in-flight adoption conflict\"]}]" ], "demotionRule": "Demote if a live parked/restarting PTY loses its exact graph leaf or verified viewer binding, a retired PTY remains published, multi-pane identity drifts, or either routed client round trip flakes without a diagnosed cause." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 3f9ea7a32a4..f72fdc5b6f7 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -879,7 +879,6 @@ "src/main/claude-accounts/sign-in/claude-account-folder.test.ts": 153, "src/main/claude-accounts/claude-account-service.test.ts": 1207, "src/main/claude-accounts/sign-in/claude-login-session.test.ts": 1048, - "src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts": 238, "src/main/claude-accounts/profiles/setup/claude-profile-history-windows.test.ts": 121, "src/main/claude-accounts/profiles/setup/claude-profile-history.test.ts": 173, "src/main/claude-accounts/profiles/claude-profile-paths.test.ts": 82, @@ -1507,7 +1506,6 @@ "src/main/git/refs/resolution/repo-branch-conflict-real-git.test.ts": 348, "src/main/git/repositories/discovery/repo-detection-async.test.ts": 612, "src/main/git/repositories/discovery/repo-detection-batching.test.ts": 494, - "src/main/git/repositories/discovery/repo-detection-command.test.ts": 49, "src/main/git/repositories/discovery/repo-detection.test.ts": 842, "src/main/git/refs/maintenance/repo-maintenance-admission.test.ts": 757, "src/main/git/refs/maintenance/repo-pack-index-maintenance.test.ts": 152, @@ -1519,7 +1517,6 @@ "src/main/git/refs/resolution/repo.test.ts": 2318, "src/main/git/command-runner/runner-buffer-cancellation.test.ts": 318, "src/main/git/command-runner/runner-buffer-stdin.test.ts": 229, - "src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts": 246, "src/main/git/command-runner/hosted-cli/runner-gh-rate-limit-breaker.test.ts": 261, "src/main/git/command-runner/git-environment/runner-network-ssh-policy.test.ts": 283, "src/main/git/command-runner/host-routing/runner-windows-host-environment.test.ts": 322, @@ -1854,7 +1851,6 @@ "src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts": 2529, "src/main/ipc/repos/repo-ipc-wsl-move-fence.test.ts": 2655, "src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts": 827, - "src/main/ipc/runtime-environments/runtime-environment-capability-evidence.test.ts": 46, "src/main/ipc/runtime-environments/runtime-environment-cli-removal-routing.test.ts": 891, "src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts": 804, "src/main/ipc/runtime-environments/runtime-environment-preference.test.ts": 1253, @@ -1915,7 +1911,6 @@ "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, - "src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts": 111, "src/main/ipc/wsl/wsl-host-automation-wake-launch.test.ts": 939, "src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts": 772, "src/main/ipc/wsl/wsl-move-handlers-setting-off.test.ts": 724, @@ -2054,7 +2049,6 @@ "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, - "src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts": 375, "src/main/native-chat/agent-session-wire/observations/testing/agent-session-current-requests.test.ts": 271, "src/main/native-chat/agent-session-wire/publication/subscribers/testing/agent-session-delta-coalescer-protected.test.ts": 68, "src/main/native-chat/agent-session-wire/publication/subscribers/testing/agent-session-delta-coalescer.test.ts": 61, @@ -2172,10 +2166,7 @@ "src/main/opencode/status-hooks/hook-service-startup-refresh.test.ts": 111, "src/main/opencode/status-hooks/hook-service.test.ts": 262, "src/main/opencode/model-launch/opencode-launch-model-context-supervision.test.ts": 2290, - "src/main/opencode/session-correlation/opencode-session-binder.test.ts": 132, - "src/main/opencode/startup-prompts/opencode-startup-prompt-claims.test.ts": 60, "src/main/opencode/startup-prompts/opencode-startup-prompt-installer.test.ts": 195, - "src/main/opencode/accounts/opencode-structured-account-home.test.ts": 144, "src/main/opencode/status-hooks/overlay-dir-gc.test.ts": 141, "src/main/opencode/status-hooks/overlay-source-ownership.test.ts": 60, "src/main/opencode2/status-plugin-setup-lifetime.test.ts": 108, @@ -2188,14 +2179,12 @@ "src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts": 1642, "src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts": 1456, "src/main/orca-profiles/profile-telemetry-consent-seed.test.ts": 536, - "src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts": 152, "src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts": 185, "src/main/orcad/native-runtime/node-pty-precondition.test.ts": 477, "src/main/orcad/host-runtime/orcad-app-paths.test.ts": 45, "src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts": 301, "src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts": 1129, "src/main/orcad/orcad-bind-address.test.ts": 41, - "src/main/orcad/browser-providers/orcad-browser-provider.test.ts": 479, "src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts": 3555, "src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts": 390, "src/main/orcad/serve-startup/orcad-cli-launcher.test.ts": 232, @@ -2204,7 +2193,6 @@ "src/main/orcad/instance-lock/orcad-instance-lock.test.ts": 315, "src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts": 617, "src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts": 407, - "src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts": 180, "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts": 218, "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts": 285, "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts": 270, @@ -2390,7 +2378,6 @@ "src/main/plugins/contributions/plugin-syntax-registry.test.ts": 221, "src/main/plugins/contributions/plugin-theme-registries.test.ts": 250, "src/main/plugins/hooks/plugin-hook-warming.test.ts": 472, - "src/main/plugins/installation/plugin-atomic-file-write.test.ts": 2051, "src/main/plugins/installation/plugin-catalog-install-guard.test.ts": 475, "src/main/plugins/installation/plugin-derived-publisher.test.ts": 620, "src/main/plugins/installation/plugin-git-ref-resolution.integration.test.ts": 608, @@ -2404,7 +2391,6 @@ "src/main/plugins/panels/plugin-frame-integrity.test.ts": 65, "src/main/plugins/panels/plugin-frame-module-transform.test.ts": 197, "src/main/plugins/panels/plugin-frame-protocol-source-modules.test.ts": 538, - "src/main/plugins/panels/plugin-frame-request-policy.test.ts": 51, "src/main/plugins/panels/plugin-frame-source-map-location.test.ts": 208, "src/main/plugins/panels/plugin-panel-bridge-replay.test.ts": 3287, "src/main/plugins/panels/plugin-panel-bridge.test.ts": 2599, @@ -2421,14 +2407,12 @@ "src/main/plugins/plugin-content-safety.test.ts": 3933, "src/main/plugins/plugin-declared-settings.test.ts": 218, "src/main/plugins/plugin-dev-folders.test.ts": 251, - "src/main/plugins/plugin-dev-revision.test.ts": 129, "src/main/plugins/plugin-dev-watcher-ignore.test.ts": 122, "src/main/plugins/plugin-dev-watcher.test.ts": 514, "src/main/plugins/plugin-discovery.test.ts": 306, "src/main/plugins/plugin-example-gleam-syntax.test.ts": 346, "src/main/plugins/plugin-host-call-revocation.test.ts": 3175, "src/main/plugins/plugin-image-artifact-validation.test.ts": 236, - "src/main/plugins/plugin-image-cache.test.ts": 56, "src/main/plugins/plugin-launch-content.test.ts": 603, "src/main/plugins/plugin-log-buffer.test.ts": 40, "src/main/plugins/plugin-runtime-binding.test.ts": 2518, @@ -2542,7 +2526,6 @@ "src/main/rate-limits/zcode-usage-fetcher.test.ts": 143, "src/main/pty/process-retirement/refused-tree-kill-root-termination.test.ts": 96, "src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.test.ts": 1821, - "src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts": 1916, "src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts": 1960, "src/main/workspaces/catalog/repo-git-enrichment-wsl-stopped-distro.test.ts": 785, "src/main/workspaces/catalog/repo-git-remote-avatar-refresh.test.ts": 767, @@ -2673,7 +2656,6 @@ "src/main/runtime/terminal/output/headless-terminal-dispose-write-ordering.test.ts": 4309, "src/main/runtime/terminal/recovery/held-pane-reopen-layout-owner.test.ts": 5093, "src/main/runtime/terminal/wait/hermes-slash-readiness-transcript.test.ts": 4931, - "src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts": 68, "src/main/runtime/hosts/platform-probe/host-descriptor.test.ts": 207, "src/main/runtime/terminal/surface/host-pane-remount-terminal-handle.test.ts": 5293, "src/main/runtime/session-tabs/host-terminal-close-persistence-durability.test.ts": 1953, @@ -2690,12 +2672,10 @@ "src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts": 48, "src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts": 408, "src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts": 580, - "src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts": 1013, "src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts": 701, "src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts": 147, "src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts": 122, "src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts": 175, - "src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts": 253, "src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts": 73, "src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts": 804, "src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.integration.test.ts": 11377, @@ -3313,7 +3293,6 @@ "src/main/runtime/terminal/query/terminal-identity-read-context.test.ts": 5310, "src/main/runtime/terminal/stop/exact-terminal-stop-liveness.test.ts": 4321, "src/main/runtime/terminal/stop/terminal-update-admission.test.ts": 48, - "src/main/runtime/terminal/surface/closed-pane-exit-cleanup-main.test.ts": 4281, "src/main/runtime/terminal/surface/terminal-surface-replies-main.test.ts": 4324, "src/main/runtime/terminal/wait/tui-idle-codex-plan-menu.test.ts": 4441, "src/main/runtime/terminal/wait/tui-idle-command-paint.test.ts": 4148, @@ -3536,11 +3515,9 @@ "src/main/startup/first-window-startup-services.test.ts": 54, "src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts": 641, "src/main/startup/headless-serve-x11-reexec.test.ts": 76, - "src/main/startup/hydrate-shell-path.windows.test.ts": 426, "src/main/startup/legacy-worker-renderer-recovery.test.ts": 47, "src/main/startup/login-shell-environment-cache.test.ts": 136, "src/main/startup/login-shell-environment.test.ts": 103, - "src/main/startup/main-process-error-guards.test.ts": 109, "src/main/startup/main-process-quit-pending-writer.test.ts": 328, "src/main/startup/main-process-quit-update-veto.test.ts": 1714, "src/main/startup/main-process-ready-activation-failure.test.ts": 313, @@ -3670,11 +3647,9 @@ "src/main/window/project-move-pause.test.ts": 130, "src/main/window/renderer-document-navigation.test.ts": 60, "src/main/window/renderer-launch-failure-probe.test.ts": 60, - "src/main/window/renderer-liveness-at-death.test.ts": 50, "src/main/window/renderer-publication-throttle.electron.test.ts": 5163, "src/main/window/renderer-recovery-reload-watchdog.test.ts": 69, "src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts": 100, - "src/main/window/session-tab-close-request-relay.test.ts": 74, "src/main/window/terminal-tab-close-request-relay.test.ts": 64, "src/main/window/updater-package-recovery-ipc.test.ts": 169, "src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts": 76, @@ -3733,7 +3708,6 @@ "src/main/wsl/filesystem/wsl-shell-cwd-report.test.ts": 111, "src/main/wsl/filesystem/wsl-unc-delete.wsl.test.ts": 93, "src/main/wsl/discovery/distro-catalog.test.ts": 148, - "src/main/wsl/filesystem/wsl-automount-root.test.ts": 108, "src/main/wsl/discovery/wsl-background-exec-gate.test.ts": 69, "src/main/wsl/execution/wsl-command-channel.test.ts": 57, "src/main/wsl/execution/wsl-command-loop.test.ts": 6057, @@ -3872,7 +3846,6 @@ "src/renderer/src/components/automations/automation-list-view.test.ts": 257, "src/renderer/src/components/automations/automation-run-output-snapshot-equivalence.test.ts": 158, "src/renderer/src/components/automations/automation-run-output-snapshot.test.ts": 96, - "src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts": 58, "src/renderer/src/components/automations/automation-usage-model.test.ts": 200, "src/renderer/src/components/automations/external-automation-list-entries.test.ts": 57, "src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts": 67, @@ -3907,7 +3880,6 @@ "src/renderer/src/components/browser-pane/host-guest/browser-page-evicted-guest-recovery.test.ts": 1839, "src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts": 515, "src/renderer/src/components/browser-pane/host-guest/browser-page-registration-ownership.test.ts": 2197, - "src/renderer/src/components/browser-pane/host-guest/browser-page-viewport.test.ts": 242, "src/renderer/src/components/browser-pane/host-guest/use-browser-page-keyboard-shortcuts.split.test.tsx": 2098, "src/renderer/src/components/browser-pane/host-guest/use-browser-page-webview-partition.test.ts": 1985, "src/renderer/src/components/browser-pane/host-guest/webview-registry.test.ts": 103, @@ -3975,7 +3947,6 @@ "src/renderer/src/components/editor/EditorPanel.custom-editor-flush.test.tsx": 2478, "src/renderer/src/components/editor/EditorPanel.diff-rich-owner.test.tsx": 2823, "src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx": 1660, - "src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx": 736, "src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx": 641, "src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.focus-leave.test.tsx": 4927, "src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx": 1899, @@ -3989,7 +3960,6 @@ "src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache-body-budget.test.ts": 116, "src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache.test.ts": 45, "src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-draft-retention.test.ts": 54, - "src/renderer/src/components/editor/combined-diff/resolve-changes/combined-diff-entries.test.ts": 54, "src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx": 2383, "src/renderer/src/components/editor/conflict-review-file-tree-windowing.test.tsx": 1487, "src/renderer/src/components/editor/csv/CsvViewer.delimiter.test.tsx": 2923, @@ -4102,7 +4072,6 @@ "src/renderer/src/components/editor/rich-markdown/review/rich-markdown-range-bounds.test.ts": 70, "src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-text-ranges.test.ts": 53, "src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.adversarial.test.ts": 301, - "src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.test.ts": 238, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-signed-images.test.ts": 2230, "src/renderer/src/components/editor/rich-markdown/document/rich-markdown-source-eol-allocation.test.ts": 73, "src/renderer/src/components/editor/rich-markdown/document/rich-markdown-source-reconcile.test.ts": 2239, @@ -4127,7 +4096,6 @@ "src/renderer/src/components/editor/rich-markdown/links/useLinkBubble.test.tsx": 493, "src/renderer/src/components/editor/rich-markdown/images/useLocalImagePick.test.tsx": 1319, "src/renderer/src/components/editor/document-images/useLocalImageSrc.test.ts": 736, - "src/renderer/src/components/editor/useLocalLogTail.test.tsx": 436, "src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.navigation.test.ts": 2101, "src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ownership.test.tsx": 2448, "src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts": 799, @@ -4147,7 +4115,6 @@ "src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx": 408, "src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx": 1968, "src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.test.tsx": 1093, - "src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts": 466, "src/renderer/src/components/github-checks-tab-state.test.ts": 52, "src/renderer/src/components/github-item-dialog/land-pull-request/pr-reviewers-request-actions.test.ts": 1976, "src/renderer/src/components/github-item-dialog/load-item-details/use-github-item-dialog-details.test.tsx": 2850, @@ -4182,10 +4149,8 @@ "src/renderer/src/components/mobile/WindowsFirewallNotice.test.tsx": 691, "src/renderer/src/components/mobile/paired-mobile-devices.test.ts": 192, "src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts": 475, - "src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts": 1954, "src/renderer/src/components/native-chat/markdown/code/NativeChatCodeBlock.test.tsx": 2775, "src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.test.tsx": 781, - "src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx": 2818, "src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.link-placement.test.tsx": 2477, "src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx": 2881, "src/renderer/src/components/native-chat/viewport/scroll/NativeChatJumpToLatest.test.tsx": 477, @@ -4352,7 +4317,6 @@ "src/renderer/src/components/plugins/view/plugin-view-editor-shot-cleanup.test.ts": 59, "src/renderer/src/components/plugins/view/plugin-view-panel-settle.test.ts": 206, "src/renderer/src/components/plugins/view/plugin-view-request-handler-workspace.test.ts": 2307, - "src/renderer/src/components/plugins/view/plugin-view-request-handler.test.ts": 2849, "src/renderer/src/components/ports/WorkspacePortScanner.test.tsx": 2474, "src/renderer/src/components/pull-request-page/actions/merge-actions.test.ts": 383, "src/renderer/src/components/pull-request-page/cache/file-content.test.ts": 344, @@ -4384,8 +4348,6 @@ "src/renderer/src/components/right-sidebar/ai-vault/scope/ai-vault-host-scope.test.ts": 1870, "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/search/ai-vault-search-session.test.ts": 201, - "src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-session-account-render.test.tsx": 2885, "src/renderer/src/components/right-sidebar/ai-vault/session-list/ai-vault-session-filters.test.ts": 105, "src/renderer/src/components/right-sidebar/ai-vault/scope/ai-vault-session-projects.test.ts": 117, "src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-refresh.test.ts": 2034, @@ -4393,7 +4355,6 @@ "src/renderer/src/components/right-sidebar/ai-vault/session-list/ai-vault-session-worktree.test.ts": 307, "src/renderer/src/components/right-sidebar/checks-panel/logs/check-log-initial-diagnostic-position.test.ts": 242, "src/renderer/src/components/right-sidebar/checks-panel/checks-list-expanded-details.test.tsx": 1549, - "src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-review-creation.test.ts": 69, "src/renderer/src/components/right-sidebar/checks-panel/checks-panel-review-lookup-authority.test.ts": 54, "src/renderer/src/components/right-sidebar/checks-panel/comments/review-comment-markdown.test.tsx": 2171, "src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh-recovery.test.tsx": 2909, @@ -4416,7 +4377,6 @@ "src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-list-selection.test.tsx": 3290, "src/renderer/src/components/right-sidebar/source-control/ai/runSourceControlAgentActionStart.test.ts": 1917, "src/renderer/src/components/right-sidebar/source-control/review/source-control-create-pr-intent-flow.test.ts": 71, - "src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts": 77, "src/renderer/src/components/right-sidebar/source-control/commit/rename-mutation-paths.test.ts": 49, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts": 486, "src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.cancel.test.ts": 1992, @@ -4424,12 +4384,10 @@ "src/renderer/src/components/right-sidebar/source-control/listing/use-file-projection-work.test.tsx": 703, "src/renderer/src/components/right-sidebar/source-control/review/create-pr-intent-operation-target.test.ts": 1735, "src/renderer/src/components/right-sidebar/source-control/review/use-create-pr-intent-jira-title.test.tsx": 1956, - "src/renderer/src/components/right-sidebar/source-control/review/use-pull-request-generation.test.tsx": 2720, "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/file-explorer/panel/use-file-explorer-name-filter.runtime-listing.test.tsx": 2153, - "src/renderer/src/components/right-sidebar/hosted-review/creation/use-generate-before-create-pull-request-context.test.tsx": 2246, "src/renderer/src/components/right-sidebar/hosted-review/provider-actions/use-hosted-review-actions.test.tsx": 628, "src/renderer/src/components/right-sidebar/plugin-panels/health/use-plugin-panel-draw-report.test.tsx": 204, "src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-branch-compare.test.tsx": 712, @@ -4477,7 +4435,6 @@ "src/renderer/src/lib/agent-session/launch/agent-settings-update-queue.test.ts": 249, "src/renderer/src/components/agent/launch-settings/agent-default-env-draft.test.ts": 54, "src/renderer/src/components/integrations/source-control/bitbucket-integration-card.test.tsx": 619, - "src/renderer/src/components/settings/chat/chat-naming-persistence.test.tsx": 5499, "src/renderer/src/components/settings/developer-permissions/developer-permissions-search.test.ts": 308, "src/renderer/src/components/settings/shortcuts/keybinding-diagnostic-text.test.ts": 522, "src/renderer/src/components/settings/shortcuts/keybinding-title-copy.test.ts": 227, @@ -4555,7 +4512,6 @@ "src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-refresh-targets.test.ts": 945, "src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.test.ts": 577, "src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-orchestration-index.test.ts": 443, - "src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts": 1133, "src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.test.ts": 376, "src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-status-inputs.test.ts": 55, "src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.test.ts": 200, @@ -4564,8 +4520,6 @@ "src/renderer/src/components/sidebar/worktree-list/grouping/worktree-list-groups-project-host-setups.test.ts": 280, "src/renderer/src/components/sidebar/worktree-list/grouping/worktree-list-groups-project-order.test.ts": 1861, "src/renderer/src/components/sidebar/worktree-list/drag/pointer-flush.test.ts": 517, - "src/renderer/src/components/sidebar/worktree-list/grouping/cross-project-lineage.test.ts": 248, - "src/renderer/src/components/sidebar/worktree-list/grouping/recent-project-rank-scan-budget.test.ts": 183, "src/renderer/src/components/sidebar/worktree-list/listing/host-status-isolation.test.tsx": 3404, "src/renderer/src/components/sidebar/worktree-list/listing/pending-worktree-creation-keys.test.ts": 42, "src/renderer/src/components/sidebar/worktree-list/listing/use-sort-order.test.tsx": 2239, @@ -4576,7 +4530,6 @@ "src/renderer/src/components/sidebar/worktree-list/rows/option-dom-host-collision.test.ts": 186, "src/renderer/src/components/sidebar/worktree-list/rows/repo-header-ssh-isolation.test.tsx": 2945, "src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx": 2393, - "src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.ts": 293, "src/renderer/src/components/sidebar/worktree-list/drag/worktree-manual-order-store-write.test.ts": 2144, "src/renderer/src/components/sidebar/worktree-list/drag/worktree-manual-order.test.ts": 332, "src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-eligibility.test.ts": 68, @@ -4758,7 +4711,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-snapshot-replay.test.ts": 1717, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-spawn-intent.test.ts": 2215, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stale-handle-recovery.test.ts": 1882, - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stopped-host-reopen.test.ts": 1083, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts": 4148, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-subscribe-ack-input.test.ts": 2565, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unmounted-host-pane.test.ts": 626, @@ -4919,7 +4871,6 @@ "src/renderer/src/hooks/ipc-events/direct-ssh-hydration-target-metadata.test.ts": 1875, "src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts": 1764, "src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.test.ts": 2200, - "src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts": 280, "src/renderer/src/hooks/ipc-events/quit-and-stop-all-sessions-ipc-bridge.test.ts": 398, "src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts": 2068, "src/renderer/src/hooks/ipc-events/runtime-file-position.test.ts": 2318, @@ -4945,7 +4896,6 @@ "src/renderer/src/hooks/use-window-stream-visibility.test.ts": 289, "src/renderer/src/hooks/useAutomationDispatchEvents.test.ts": 788, "src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts": 95, - "src/renderer/src/hooks/useComposerState.integration.test.ts": 4419, "src/renderer/src/hooks/useDetectedAgents.host-reconnect.test.tsx": 2044, "src/renderer/src/hooks/useDetectedAgents.local-invalidation.test.tsx": 2246, "src/renderer/src/hooks/useDetectedAgents.re-pair.test.tsx": 1959, @@ -4996,7 +4946,6 @@ "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts": 41, "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts": 341, "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts": 1914, - "src/renderer/src/lib/agent-session/launch/pane/agent-launch-pane-verdict-application.test.ts": 1869, "src/renderer/src/lib/agent-session/launch/routing/agent-launch-route-input.test.ts": 1659, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-tab-main-written.test.ts": 2084, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-tab-publication.test.ts": 1855, @@ -5083,7 +5032,6 @@ "src/renderer/src/lib/renderer-agent-status-observation-ingress.test.ts": 81, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-deferred-pane.test.ts": 1747, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-direct-ssh-hydration-gap.test.ts": 1654, - "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-execution-host-scope.test.ts": 1924, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-live-ssh-dedupe.test.ts": 2059, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-provider-claim.test.ts": 1789, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-replay.test.ts": 1946, @@ -5114,7 +5062,6 @@ "src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts": 2066, "src/renderer/src/lib/workspace/activation/worktree-activation-automation-filter.test.ts": 2431, "src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts": 2295, - "src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts": 3630, "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, @@ -5157,7 +5104,6 @@ "src/renderer/src/runtime/files/reads/runtime-file-range-client.test.ts": 444, "src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.test.ts": 478, "src/renderer/src/runtime/source-control/git/runtime-git-client.test.ts": 513, - "src/renderer/src/runtime/hosts/connections/runtime-host-contact-regained.test.ts": 413, "src/renderer/src/runtime/jira/runtime-jira-image-client.test.ts": 214, "src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts": 192, "src/renderer/src/runtime/files/reads/runtime-paged-file-read.test.ts": 1705, @@ -5168,8 +5114,6 @@ "src/renderer/src/runtime/workspace-layout/server/server-layout-editor-handover.test.ts": 5075, "src/renderer/src/runtime/workspace-layout/server/server-layout-frames-handover.test.ts": 1991, "src/renderer/src/runtime/workspace-layout/server/server-layout-frames.test.ts": 2053, - "src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed-lifecycle.test.ts": 62, - "src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed.test.ts": 82, "src/renderer/src/runtime/native-chat/host-capabilities/structured-chat-host-permission.test.ts": 523, "src/renderer/src/runtime/web-session-tabs-sync/placement/structured-conversation-tab-replacement.test.ts": 2029, "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-chat-tab-order.test.ts": 529, @@ -5205,7 +5149,6 @@ "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts": 923, "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts": 1029, "src/renderer/src/runtime/hosted-terminals/recovery/surfaces/web-session-terminal-orphan-recovery-topology-fence.test.ts": 868, - "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts": 895, "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts": 723, "src/renderer/src/runtime/hosted-terminals/recovery/evidence/web-session-terminal-retirement-proof-ledger.test.ts": 685, "src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking-stream-end.test.ts": 225, @@ -5214,15 +5157,12 @@ "src/renderer/src/startup/startup-degraded-recovery.test.ts": 574, "src/renderer/src/startup/startup-ssh-connection-restore.test.ts": 71, "src/renderer/src/store/slices/editor/buffers/editor-buffer-record-lifecycle.test.ts": 1794, - "src/renderer/src/store/folder-workspaces/folder-path-status-ownership.test.ts": 1809, "src/renderer/src/store/github/checks/check-details-failure-mapping.test.ts": 887, "src/renderer/src/store/github/projects/project-field-mutations.test.ts": 2100, "src/renderer/src/store/github/requests/provider-request-coalescing.test.ts": 969, "src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts": 97, "src/renderer/src/store/github/repositories/wsl-stopped-distro-poll-refusal.test.ts": 696, - "src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts": 435, "src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377, - "src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts": 5216, "src/renderer/src/store/projects/project-catalog-null-field-ingest.test.ts": 309, "src/renderer/src/store/repos/dropped-repo-worktree-rows.test.ts": 1738, "src/renderer/src/store/repos/repo-removal.test.ts": 799, @@ -5230,7 +5170,6 @@ "src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts": 2920, "src/renderer/src/store/slices/runtime-status/views/runtime-status-subscriptions.test.ts": 182, "src/renderer/src/store/slices/editor/focus/active-selection-owner-scoping.test.ts": 1909, - "src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts": 1756, "src/renderer/src/store/slices/agent-status/agent-status-pane-owner-reclaim.test.ts": 1899, "src/renderer/src/store/slices/agent-status/agent-status-ack-cleanup.test.ts": 1776, "src/renderer/src/store/slices/agent-status/agent-status-batch.test.ts": 1933, @@ -5244,7 +5183,6 @@ "src/renderer/src/store/slices/agent-status/agent-status-quit-capture.test.ts": 1748, "src/renderer/src/store/slices/agent-status/agent-status-retention-prefix-sweep.test.ts": 2539, "src/renderer/src/store/slices/agent-status/agent-status-row-order-origin.test.ts": 2205, - "src/renderer/src/store/slices/agent-status/agent-status-runtime-orchestration.test.ts": 1867, "src/renderer/src/store/slices/agent-status/agent-status-ssh-connection-clear.test.ts": 1681, "src/renderer/src/store/slices/agent-status/agent-status-worktree-purge-leak.test.ts": 1744, "src/renderer/src/store/slices/agent-status/agent-status.test.ts": 2129, @@ -5264,7 +5202,6 @@ "src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts": 643, "src/renderer/src/store/slices/diff-comments/diff-comments-host-twins.test.ts": 1887, "src/renderer/src/store/slices/diff-comments/diffComments.test.ts": 1896, - "src/renderer/src/store/slices/editor/git/editor-branch-line-total.test.ts": 892, "src/renderer/src/store/slices/editor/checks/editor-check-details-reading.test.ts": 945, "src/renderer/src/store/slices/editor/checks/editor-check-details-tab-owner.test.ts": 1103, "src/renderer/src/store/slices/editor/closing/editor-close-background-file.test.ts": 893, @@ -5279,7 +5216,6 @@ "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/git/editor-remote-branch-actions.test.ts": 935, "src/renderer/src/store/slices/editor/focus/editor-set-active-file-guard.test.ts": 895, "src/renderer/src/store/slices/editor/tabs/editor-tab-layout-owner.test.ts": 1883, "src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-identity.test.ts": 1775, @@ -5294,7 +5230,6 @@ "src/renderer/src/store/github/pull-requests/github-linked-review-clear-ownership.test.ts": 891, "src/renderer/src/store/slices/editor/git/github-post-operation-owner.test.ts": 2062, "src/renderer/src/store/github/pull-requests/github-pr-branch-direct-refresh-scope.test.ts": 667, - "src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts": 662, "src/renderer/src/store/github/comments/github-pr-comment-read-order.test.ts": 570, "src/renderer/src/store/github/comments/github-pr-comments.test.ts": 746, "src/renderer/src/store/github/refresh/github-pr-refresh-states-leak.test.ts": 1327, @@ -5306,7 +5241,6 @@ "src/renderer/src/store/github/work-items/github-work-items-runtime-routing.test.ts": 1891, "src/renderer/src/store/github/work-items/github-work-items-twin-cache-host.test.ts": 672, "src/renderer/src/store/slices/hosted-review/hosted-review-request-lifetime.test.ts": 110, - "src/renderer/src/store/slices/hosted-review/hosted-review.test.ts": 320, "src/renderer/src/store/slices/jira/jira-status-filter-cache.test.ts": 1770, "src/renderer/src/store/slices/jira/jira.test.ts": 312, "src/renderer/src/store/slices/linear/linear-invalidation.test.ts": 117, @@ -5319,15 +5253,11 @@ "src/renderer/src/store/repos/project-removal-runtime-terminal-order.test.ts": 1769, "src/renderer/src/store/repos/project-removal-unreachable-server.test.ts": 2292, "src/renderer/src/store/slices/worktrees/teardown/purge-stale-runtime-host-ownership.test.ts": 1767, - "src/renderer/src/store/slices/worktrees/teardown/removed-worktree-diff-memory.test.ts": 2981, "src/renderer/src/store/repos/repos-add-races.test.ts": 1731, "src/renderer/src/store/repos/repos-all-hosts-generation.test.ts": 1908, - "src/renderer/src/store/repos/repos-catalog-connection-fence.test.ts": 1821, "src/renderer/src/store/repos/repos-catalog-request-coordination.test.ts": 1602, "src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts": 2459, "src/renderer/src/store/repos/repos-host-identity-routing.test.ts": 1700, - "src/renderer/src/store/project-groups/repos-project-group-cross-host-move.test.ts": 1704, - "src/renderer/src/store/repos/repos-remove-missing-remote-project.test.ts": 1686, "src/renderer/src/store/repos/repos-selected-owner-routing.test.ts": 2067, "src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts": 1891, "src/renderer/src/store/repos/repos.runtime-fallback.test.ts": 1808, @@ -5335,8 +5265,6 @@ "src/renderer/src/store/slices/editor/tabs/restored-editor-owner-layout-owner.test.ts": 1879, "src/renderer/src/store/slices/editor/hydration/restored-editor-owner-reparent.test.ts": 2423, "src/renderer/src/store/slices/editor/hydration/restored-editor-owner-restart.test.ts": 2138, - "src/renderer/src/store/repos/runtime-catalog-merge-removed-env-guard.test.ts": 1787, - "src/renderer/src/store/slices/agent-inventory/runtime-detected-agents-pairing.test.ts": 608, "src/renderer/src/store/slices/runtime-status/runtime-managed-repair-keeps-workspaces.test.ts": 1776, "src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts": 410, "src/renderer/src/store/slices/runtime-status/runtime-status.test.ts": 746, @@ -5349,20 +5277,14 @@ "src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts": 1867, "src/renderer/src/store/terminals/store-create-tab-start-in-main.test.ts": 1801, "src/renderer/src/store/slices/tabs/store-open-to-side-layout-owner.test.ts": 1919, - "src/renderer/src/store/repos/store-session-cascades.test.ts": 1775, "src/renderer/src/store/terminals/store-sleep-exact-runtime-stop.test.ts": 1842, "src/renderer/src/store/terminals/store-sleep-pane-hibernation.test.ts": 1932, - "src/renderer/src/store/terminals/store-sleep-runtime-convergence.test.ts": 1767, - "src/renderer/src/store/slices/worktrees/teardown/store-worktree-removal-cascade.test.ts": 1786, "src/renderer/src/store/slices/worktrees/teardown/tab-worktree-orphan-map-purge-leak.test.ts": 1936, "src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts": 1849, "src/renderer/src/store/slices/tabs/tabs-hydration-group-validation.test.ts": 249, - "src/renderer/src/store/slices/tabs/tabs-label-and-pin-state.test.ts": 1921, - "src/renderer/src/store/slices/tabs/tabs-open-close-lifecycle.test.ts": 2140, "src/renderer/src/store/slices/tabs/tabs-unread-and-focus.test.ts": 1801, "src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts": 1866, "src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703, - "src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts": 1734, "src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts": 1627, "src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts": 1751, "src/renderer/src/store/terminals/terminal-quick-command-hosts.test.ts": 1759, @@ -5377,7 +5299,6 @@ "src/renderer/src/store/slices/workspace-attention/workspace-unread-screen-moves-characterization.test.ts": 1884, "src/renderer/src/store/slices/worktrees/teardown/workspace-chat-draft-removal.test.ts": 1896, "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-browse.test.ts": 69, - "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-cache-hydration.test.ts": 815, "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-enrichment-performance.test.ts": 995, "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts": 750, "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-scan-progress.test.ts": 1207, @@ -5399,15 +5320,12 @@ "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/metadata/worktrees-git-identity-review-clear-persistence.test.ts": 1678, - "src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-twin-host.test.ts": 1342, "src/renderer/src/store/slices/worktrees/listing/worktrees-hydration-purge.test.ts": 1274, "src/renderer/src/store/slices/worktrees/session/worktrees-identity-migration.test.ts": 1412, "src/renderer/src/store/slices/worktrees/metadata/worktrees-linked-review-push-target.test.ts": 1186, "src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts": 1132, - "src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts": 1229, "src/renderer/src/store/slices/worktrees/listing/worktrees-runtime-connection-generation-fence.test.ts": 1240, "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-pr-exact-observation.test.ts": 1201, - "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-pr-url-linking.test.ts": 1786, "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-admission.test.ts": 1863, "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-origins.test.ts": 1218, "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-source-race.test.ts": 1063, @@ -6303,7 +6221,6 @@ "src/main/skills/discovery/skill-discovery-wsl-bash-filter.test.ts": 2105, "src/main/skills/discovery/skill-discovery-wsl-script-roundtrip.test.ts": 136, "src/main/skills/discovery/skill-discovery-wsl-observation.test.ts": 104, - "src/main/skills/install/skill-install-discovery-verification.test.ts": 143, "src/main/skills/transaction-state/skill-install-lock.test.ts": 354, "src/main/skills/install/skill-install-recovery.test.ts": 454, "src/main/skills/install/skill-install-request.test.ts": 508, diff --git a/src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts b/src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts deleted file mode 100644 index b09dc864f2e..00000000000 --- a/src/main/claude-accounts/sign-in/claude-pasted-code-login.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { mkdtempSync, readdirSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HostAccountSignInChannel } from '../../../shared/host-account-sign-in-types' -import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' -import { - parseClaudePastedCodeSignInLink, - runClaudePastedCodeLogin -} from './claude-pasted-code-login' - -// Captured from `claude auth login --claudeai` 2.1.306 with piped stdin (challenge and state -// replaced). It prints the pasted-code link twice: inside an OSC 8 hyperlink and as its text. -const PASTE_LINK = - 'https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a-e61b-44d9-88ed-5944d1962f5e&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&scope=user%3Ainference&code_challenge=CHALLENGE&code_challenge_method=S256&state=STATE' -const TRANSCRIPT = `Opening browser to sign in…\nIf the browser didn't open, visit: \u001b]8;;${PASTE_LINK}\u0007${PASTE_LINK}\u001b]8;;\u0007\nPaste code here if prompted > ` -const LOCAL_LINK = - 'https://claude.com/cai/oauth/authorize?code=true&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fcallback&state=s' - -type RunCommand = ( - args: string[], - config: ClaudeCommandConfig, - timeoutMs: number, - options?: ClaudeCommandOptions -) => Promise - -const roots: string[] = [] -afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))) - -function hostFolder(): ClaudeCommandConfig { - const windowsPath = mkdtempSync(join(tmpdir(), 'claude-pasted-code-')) - roots.push(windowsPath) - return { windowsPath, linuxPath: null, wslDistro: null } -} - -function channel(code = new Promise(() => {})) { - const controller = new AbortController() - const value: HostAccountSignInChannel = { - signal: controller.signal, - onPrompt: vi.fn(), - nextCode: () => code - } - return { value, controller } -} - -describe('parseClaudePastedCodeSignInLink', () => { - it('waits for the whole link and ignores a localhost-callback one', () => { - expect(parseClaudePastedCodeSignInLink(`visit: ${PASTE_LINK.slice(0, 80)}`)).toBeNull() - expect(parseClaudePastedCodeSignInLink(`visit: ${LOCAL_LINK}\n`)).toBeNull() - expect(parseClaudePastedCodeSignInLink('see https://example.com/?code=true \n')).toBeNull() - }) -}) - -describe('runClaudePastedCodeLogin', () => { - it('publishes the link, writes the pasted code to stdin, and removes its BROWSER stand-in', async () => { - const folder = hostFolder() - const written: string[] = [] - const { value } = channel(Promise.resolve('the-code#state')) - const runCommand = vi.fn(async (_args, _config, _timeout, options) => { - options?.onStdin?.((text) => written.push(text)) - options?.onStdout?.(TRANSCRIPT.slice(0, 200)) - options?.onStdout?.(TRANSCRIPT.slice(200)) - await vi.waitFor(() => expect(written).toEqual(['the-code#state\n'])) - return '' - }) - await runClaudePastedCodeLogin(folder, runCommand, value, vi.fn()) - expect(runCommand.mock.calls[0][0]).toEqual(['auth', 'login', '--claudeai']) - expect(runCommand.mock.calls[0][3]).toMatchObject({ - keepStdinOpen: true, - browser: join(folder.windowsPath, '.orca-sign-in-browser') - }) - expect(value.onPrompt).toHaveBeenCalledExactlyOnceWith({ - url: new URL(PASTE_LINK).toString(), - userCode: null, - needsCode: true - }) - expect(readdirSync(folder.windowsPath)).toEqual([]) - }) - - it('stops the login when the flow is cancelled, and spawns none once already cancelled', async () => { - const { value, controller } = channel() - let signal: AbortSignal | undefined - const runCommand = vi.fn(async (_args, _config, _timeout, options) => { - signal = options?.signal - await new Promise((_resolve, reject) => - options?.signal?.addEventListener('abort', () => - reject(new Error('Claude sign-in was cancelled.')) - ) - ) - return '' - }) - const running = runClaudePastedCodeLogin(hostFolder(), runCommand, value, vi.fn()) - await vi.waitFor(() => expect(runCommand).toHaveBeenCalledOnce()) - controller.abort() - await expect(running).rejects.toThrow('Claude sign-in was cancelled.') - expect(signal?.aborted).toBe(true) - - const second = vi.fn() - await expect(runClaudePastedCodeLogin(hostFolder(), second, value, vi.fn())).rejects.toThrow( - 'Claude sign-in was cancelled.' - ) - expect(second).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/daemon/permissions/testing/tcc-denial-folder-state.test.ts b/src/main/daemon/permissions/testing/tcc-denial-folder-state.test.ts deleted file mode 100644 index ff8c7a9aed5..00000000000 --- a/src/main/daemon/permissions/testing/tcc-denial-folder-state.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - classifyIcloudSetting, - classifyStatFlags, - classifyVolumeType -} from '../tcc-denial-folder-state' - -function ok(stdout: string, code = 0, stderr = '') { - return { code, timedOut: false, stdout, stderr } -} - -describe('folder state enums', () => { - it('reads SF_DATALESS from `stat -f %Xf`', () => { - expect(classifyStatFlags(ok('40000000\n'))).toBe('yes') - expect(classifyStatFlags(ok('40000040\n'))).toBe('yes') - expect(classifyStatFlags(ok('0\n'))).toBe('no') - expect(classifyStatFlags(ok('', 1))).toBe('unknown') - }) - - it('treats a never-written Finder key as iCloud off', () => { - expect(classifyIcloudSetting(ok('1\n'))).toBe('yes') - expect(classifyIcloudSetting(ok('0\n'))).toBe('no') - expect( - classifyIcloudSetting( - ok( - '', - 1, - 'The domain/default pair of (com.apple.finder, FXICloudDriveDesktop) does not exist' - ) - ) - ).toBe('no') - expect(classifyIcloudSetting({ ...ok(''), timedOut: true })).toBe('unknown') - }) - - it('picks the longest mount point that contains the folder', () => { - const mounts = ok( - [ - '/dev/disk3s1s1 on / (apfs, sealed, local, read-only, journaled)', - '/dev/disk3s5 on /System/Volumes/Data (apfs, local, journaled, nobrowse, protect, root data)', - '//user@nas/home on /Volumes/home (smbfs, nodev, nosuid, mounted by user)', - '/dev/disk5s1 on /Volumes/home backup (exfat, local, nodev, nosuid, noowners)' - ].join('\n') - ) - expect(classifyVolumeType(mounts, '/Volumes/home/Documents')).toBe('smbfs') - expect(classifyVolumeType(mounts, '/Volumes/home backup/Documents')).toBe('exfat') - expect(classifyVolumeType(mounts, '/Users/user/Documents')).toBe('apfs') - expect( - classifyVolumeType(ok('map auto_home on /System/Volumes/Data/home (autofs)'), '/x') - ).toBe('unknown') - }) -}) diff --git a/src/main/daemon/permissions/testing/tcc-denial-signature-checks.test.ts b/src/main/daemon/permissions/testing/tcc-denial-signature-checks.test.ts deleted file mode 100644 index 4117127930d..00000000000 --- a/src/main/daemon/permissions/testing/tcc-denial-signature-checks.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { runProcess } from '@orca/process-host' - -type ProcessSpec = Parameters[0] -type ProcessResult = Awaited> -import { - checkHelperSignatures, - resetHelperSignatureChecksForTests -} from '../tcc-denial-signature-checks' - -const APP_REQUIREMENT = - 'identifier "com.stablyai.orca" and anchor apple generic and certificate leaf[subject.OU] = "6CX3WHS9HZ"' -const HELPER = - '/Users/user/Library/Application Support/orca/daemon-host/macos/terminal-host-1/app.noindex/Orca Terminal Host.app/Contents/MacOS/orca-terminal-host' - -function result(code: number | null, stdout = '', stderr = '', timedOut = false): ProcessResult { - return { code, signal: null, stdout, stderr, timedOut } -} - -type Replies = { liveVerify: ProcessResult; liveRequirement: string; diskVerify: ProcessResult } - -function codesignFake(replies: Replies) { - return vi.fn(async (spec: ProcessSpec): Promise => { - const args = spec.args ?? [] - const target = args.at(-1) ?? '' - if (args[0] === '--display') { - return target.startsWith('+') - ? result(0, `designated => ${replies.liveRequirement}\n`) - : result(0, `designated => ${APP_REQUIREMENT}\n`) - } - return target.startsWith('+') ? replies.liveVerify : replies.diskVerify - }) -} - -beforeEach(() => { - resetHelperSignatureChecksForTests() - vi.spyOn(process, 'execPath', 'get').mockReturnValue('/Applications/Orca.app/Contents/MacOS/Orca') -}) - -describe('checkHelperSignatures', () => { - it('passes a live helper carrying the app requirement and verifies the copy bundle', async () => { - const run = codesignFake({ - liveVerify: result(0), - liveRequirement: APP_REQUIREMENT, - diskVerify: result(1, '', 'a sealed resource is missing or invalid') - }) - expect(await checkHelperSignatures(1206, HELPER, run)).toEqual({ - live: 'pass', - diskCopy: 'fail' - }) - expect(run).toHaveBeenCalledWith( - expect.objectContaining({ - args: [ - '--verify', - '--strict', - '/Users/user/Library/Application Support/orca/daemon-host/macos/terminal-host-1/app.noindex/Orca Terminal Host.app' - ] - }) - ) - }) - - it('fails a live helper whose requirement differs from the app', async () => { - const run = codesignFake({ - liveVerify: result(0), - liveRequirement: 'identifier "com.stablyai.orca" and anchor apple generic', - diskVerify: result(0) - }) - expect((await checkHelperSignatures(1206, HELPER, run)).live).toBe('fail') - }) - - it('reports error, not fail, for a gone pid, a timeout or a missing path', async () => { - const gone = codesignFake({ - liveVerify: result(1, '', '+1206: host has no guest with the requested attributes'), - liveRequirement: APP_REQUIREMENT, - diskVerify: result(null, '', '', true) - }) - expect(await checkHelperSignatures(1206, HELPER, gone)).toEqual({ - live: 'error', - diskCopy: 'error' - }) - const noPath = codesignFake({ - liveVerify: result(0), - liveRequirement: APP_REQUIREMENT, - diskVerify: result(0) - }) - expect((await checkHelperSignatures(1206, null, noPath)).diskCopy).toBe('error') - }) -}) diff --git a/src/main/daemon/terminal-host/testing/terminal-host-session-exit-log.test.ts b/src/main/daemon/terminal-host/testing/terminal-host-session-exit-log.test.ts deleted file mode 100644 index de1ef227bf4..00000000000 --- a/src/main/daemon/terminal-host/testing/terminal-host-session-exit-log.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { TerminalExitCause } from '../../../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import { recordTerminalHostSessionExit } from '../terminal-host-session-exit' - -function logUnattachedExit(exitCause: TerminalExitCause): unknown { - const log = vi.fn() - recordTerminalHostSessionExit( - 'pane-1', - { - hasAttachedClients: false, - exitCode: 0, - exitCause, - incarnationId: '00000000-0000-4000-8000-000000000001', - wslDistro: null - }, - new Map(), - log - ) - expect(log).toHaveBeenCalledTimes(1) - return log.mock.calls[0] -} - -// #42383: node-pty reports code 0 for signal deaths, which made an OS restart read as clean exits. -describe('unattached session-exited log line', () => { - it('names the signal that killed the session', () => { - expect(logUnattachedExit({ kind: 'signaled', signal: 15 })).toEqual([ - 'session-exited', - { sessionId: 'pane-1', code: 0, cause: 'signaled', signal: 15, attached: false } - ]) - }) - - it('marks daemon-initiated teardown apart from a shell exit', () => { - expect(logUnattachedExit({ kind: 'operator_close' })).toEqual([ - 'session-exited', - { sessionId: 'pane-1', code: 0, cause: 'operator_close', attached: false } - ]) - }) - - it('keeps why the cause is unknown when the host cannot report it', () => { - expect(logUnattachedExit({ kind: 'unknown', reason: 'host_status_unavailable' })).toEqual([ - 'session-exited', - { - sessionId: 'pane-1', - code: 0, - cause: 'unknown', - reason: 'host_status_unavailable', - attached: false - } - ]) - }) -}) diff --git a/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts b/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts deleted file mode 100644 index db8f2f7a331..00000000000 --- a/src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type * as GhAccountTokenModule from '../../../github/accounts/gh-account-token' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - spawnMock, - resolveGhAccountTokenMock, - buildBoundGhChildEnvMock, - createGhBoundAccountHostMismatchErrorMock -} = vi.hoisted(() => ({ - spawnMock: vi.fn(), - resolveGhAccountTokenMock: vi.fn(), - buildBoundGhChildEnvMock: vi.fn(), - createGhBoundAccountHostMismatchErrorMock: vi.fn( - (binding: { host: string; user: string }, host?: string) => - Object.assign( - new Error( - host - ? `host mismatch ${binding.host} vs ${host}` - : `host required for ${binding.user}@${binding.host}` - ), - { code: 'gh_bound_account_host_mismatch', stderr: 'host mismatch' } - ) - ) -})) - -vi.mock('node:child_process', async (importOriginal) => ({ - ...(await importOriginal()), - spawn: spawnMock -})) - -vi.mock('../../../github/accounts/gh-account-token', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - resolveGhAccountToken: resolveGhAccountTokenMock, - buildBoundGhChildEnv: buildBoundGhChildEnvMock, - createGhBoundAccountHostMismatchError: createGhBoundAccountHostMismatchErrorMock - } -}) - -import { ghExecFileAsync } from './gh-exec-file' -import { _resetGhRateLimitBreaker, recordGhPrimaryRateLimit } from './gh-rate-limit-breaker' - -/** Spawns a child that settles with `stdout`, capturing the env the runner handed it. */ - -describe('ghExecFileAsync account binding', () => { - beforeEach(() => { - spawnMock.mockReset() - resolveGhAccountTokenMock.mockReset() - buildBoundGhChildEnvMock.mockReset() - createGhBoundAccountHostMismatchErrorMock.mockClear() - _resetGhRateLimitBreaker() - resolveGhAccountTokenMock.mockResolvedValue('bound-token') - buildBoundGhChildEnvMock.mockImplementation( - ({ - baseEnv, - binding, - token - }: { - baseEnv?: NodeJS.ProcessEnv - binding: { host: string; user: string } - token: string - }) => ({ - ...(baseEnv ?? process.env), - GH_PROMPT_DISABLED: '1', - GH_TOKEN: binding.host === 'github.com' ? token : undefined, - GH_ENTERPRISE_TOKEN: binding.host === 'github.com' ? undefined : token - }) - ) - }) - - afterEach(() => { - _resetGhRateLimitBreaker() - }) - - it('fails closed when argv host signals disagree with the binding', async () => { - await expect( - ghExecFileAsync(['pr', 'list', '--repo', 'github.acme.com/a/b'], { - host: 'github.com', - ghAccount: { host: 'github.com', user: 'Alice' } - }) - ).rejects.toMatchObject({ code: 'gh_bound_account_host_mismatch' }) - expect(spawnMock).not.toHaveBeenCalled() - }) - - it.each(['-Rgithub.acme.com/a/b', '-R=github.acme.com/a/b'])( - 'fails closed for the attached %s host form', - async (attached) => { - await expect( - ghExecFileAsync(['pr', 'list', attached], { - host: 'github.com', - ghAccount: { host: 'github.com', user: 'Alice' } - }) - ).rejects.toMatchObject({ code: 'gh_bound_account_host_mismatch' }) - expect(spawnMock).not.toHaveBeenCalled() - } - ) - - it('fails a bound API call fast on a blocked bucket without resolving a token', async () => { - recordGhPrimaryRateLimit('core', Date.now() + 60_000, 'native:github.com') - - await expect( - ghExecFileAsync(['api', 'user'], { - host: 'github.com', - ghAccount: { host: 'github.com', user: 'Alice' } - }) - ).rejects.toMatchObject({ ghRateLimitBlocked: true }) - expect(resolveGhAccountTokenMock).not.toHaveBeenCalled() - expect(spawnMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/git/repositories/discovery/repo-detection-command.test.ts b/src/main/git/repositories/discovery/repo-detection-command.test.ts deleted file mode 100644 index 2c18ee757b6..00000000000 --- a/src/main/git/repositories/discovery/repo-detection-command.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { gitExecFileSync } from '../../command-runner/git-exec-file-sync' -import { gitRepoOutput, runGitRepoCommands, runGitRepoCommandsSync } from './repo-detection-command' - -vi.mock('../../command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: vi.fn() -})) - -vi.mock('../../command-runner/git-exec-file-sync', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileSync: vi.fn() -})) -afterEach(() => vi.resetAllMocks()) - -describe('repository command execution', () => { - it('delivers command failures to the shared decision tree in both execution modes', async () => { - function* withFallback() { - try { - return yield* gitRepoOutput(['rev-parse'], { cwd: '/repo' }) - } catch { - return 'marker fallback' - } - } - vi.mocked(gitExecFileAsync).mockRejectedValue(new Error('Git unavailable')) - vi.mocked(gitExecFileSync).mockImplementation(() => { - throw new Error('Git unavailable') - }) - expect(await runGitRepoCommands(withFallback())).toBe('marker fallback') - expect(runGitRepoCommandsSync(withFallback())).toBe('marker fallback') - }) - - it('preserves an exception from decision logic after a successful command', async () => { - const error = new Error('decision failed') - function* decisionFailure() { - yield* gitRepoOutput(['first'], { cwd: '/repo' }) - throw error - } - vi.mocked(gitExecFileAsync).mockResolvedValue({ stdout: 'result', stderr: '' }) - vi.mocked(gitExecFileSync).mockReturnValue('result') - await expect(runGitRepoCommands(decisionFailure())).rejects.toBe(error) - expect(() => runGitRepoCommandsSync(decisionFailure())).toThrow(error) - }) - - it('executes a fallback command yielded while handling a rejected command', async () => { - function* withFallbackCommand() { - try { - return yield* gitRepoOutput(['first'], { cwd: '/repo' }) - } catch { - return yield* gitRepoOutput(['second'], { cwd: '/repo' }) - } - } - vi.mocked(gitExecFileAsync) - .mockRejectedValueOnce(new Error('first failed')) - .mockResolvedValueOnce({ stdout: 'fallback', stderr: '' }) - vi.mocked(gitExecFileSync) - .mockImplementationOnce(() => { - throw new Error('first failed') - }) - .mockReturnValueOnce('fallback') - expect(await runGitRepoCommands(withFallbackCommand())).toBe('fallback') - expect(runGitRepoCommandsSync(withFallbackCommand())).toBe('fallback') - expect(vi.mocked(gitExecFileAsync).mock.calls.map(([args]) => args)).toEqual([ - ['first'], - ['second'] - ]) - expect(vi.mocked(gitExecFileSync).mock.calls.map(([args]) => args)).toEqual([ - ['first'], - ['second'] - ]) - }) -}) diff --git a/src/main/git/worktrees/creation/worktree-create-admission-real-git.test.ts b/src/main/git/worktrees/creation/worktree-create-admission-real-git.test.ts deleted file mode 100644 index ddb7d568c19..00000000000 --- a/src/main/git/worktrees/creation/worktree-create-admission-real-git.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { GitAdmissionScheduler } from '../../../../shared/git/admission/git-admission-scheduler' -import type { GitAdmissionGrant } from '../../../../shared/git/admission/git-admission-state' -import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification' -import { createWorktreePreparationLockReason } from '../../../../shared/worktree/creation/create-preparation' -import { _resetGitAdmissionForTests } from '../../command-runner/admission/git-subprocess-admission' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { addWorktree } from './worktree-add' -import { addSparseWorktree } from './worktree-sparse-add' -import { - finalizePreparedWorktree, - prepareWorktreeCreateCheckout -} from './worktree-create-preparation' -import { refreshPreparedWorktreeTip } from './worktree-preparation-tip-refresh' -import { refreshLocalBaseRefForWorktreeCreate } from './worktree-base-refresh' - -let root: string -let repo: string -let admission: GitAdmissionScheduler - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-create-admission-')) - repo = join(root, 'repo') - admission = new GitAdmissionScheduler() - _resetGitAdmissionForTests(admission) - await gitExecFileAsync(['init', '-q', repo], { cwd: root }) - await gitExecFileAsync(['symbolic-ref', 'HEAD', 'refs/heads/main'], { cwd: repo }) - await mkdir(join(repo, 'included')) - await writeFile(join(repo, 'included', 'file.txt'), 'one\n') - await gitExecFileAsync(['add', '.'], { cwd: repo }) - await gitExecFileAsync( - ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture'], - { cwd: repo } - ) -}) - -afterEach(async () => { - vi.restoreAllMocks() - _resetGitAdmissionForTests() - await rm(root, { recursive: true, force: true }) -}) - -async function behindCheckoutBudget(command: string, run: () => Promise): Promise { - let held: GitAdmissionGrant[] = [] - const requested = Promise.withResolvers() - let admitted = false - const acquire = admission.acquire.bind(admission) - const spy = vi.spyOn(admission, 'acquire').mockImplementation(async (request) => { - if (request.args[findGitSubcommandIndex(request.args)] === command) { - held = await Promise.all( - Array.from({ length: 3 }, () => - acquire({ - args: ['worktree', 'add'], - cwd: repo, - admissionClass: 'checkout', - tier: 'interactive' - }) - ) - ) - const grant = acquire(request) - requested.resolve() - void grant.then(() => { - admitted = true - }) - return grant - } - return acquire(request) - }) - const operation = run() - try { - await requested.promise - const read = await gitExecFileAsync(['rev-parse', '--verify', 'HEAD'], { cwd: repo }) - expect(read.stdout.trim()).toMatch(/^[0-9a-f]{40}$/) - expect(admitted).toBe(false) - } finally { - held.forEach((grant) => grant.release()) - await operation - spy.mockRestore() - } -} - -it('isolates ordinary and sparse creates while honoring the execution host checkout config', async () => { - const { stdout } = await gitExecFileAsync(['--version'], { cwd: repo }) - const version = stdout.match(/git version (\d+)\.(\d+)/) - if (Number(version?.[1]) > 2 || (Number(version?.[1]) === 2 && Number(version?.[2]) >= 32)) { - await gitExecFileAsync(['config', 'checkout.workers', 'not-an-integer'], { cwd: repo }) - await expect(addWorktree(repo, join(root, 'invalid'), 'invalid', 'main')).rejects.toThrow() - } - await gitExecFileAsync(['config', 'checkout.workers', '0'], { cwd: repo }) - const ordinary = join(root, 'ordinary') - await behindCheckoutBudget('worktree', () => addWorktree(repo, ordinary, 'ordinary', 'main')) - expect(await readFile(join(ordinary, 'included', 'file.txt'), 'utf8')).toBe('one\n') - await gitExecFileAsync(['config', '--unset', 'checkout.workers'], { cwd: repo }) - const sparse = join(root, 'sparse') - await behindCheckoutBudget('checkout', () => - addSparseWorktree(repo, sparse, 'sparse', ['included'], 'main') - ) - expect(await readFile(join(sparse, 'included', 'file.txt'), 'utf8')).toBe('one\n') -}) - -it('isolates preparation, fetched-tip refresh and changed-head finalization materializations', async () => { - const prepared = join(root, 'prepared') - const reason = createWorktreePreparationLockReason('admission') - await behindCheckoutBudget('reset', () => - prepareWorktreeCreateCheckout(repo, prepared, 'main', reason) - ) - await writeFile(join(repo, 'included', 'file.txt'), 'two\n') - await gitExecFileAsync(['commit', '-qam', 'next', '--author=Test '], { - cwd: repo, - env: { ...process.env, GIT_COMMITTER_NAME: 'Test', GIT_COMMITTER_EMAIL: 'test@example.invalid' } - }) - await behindCheckoutBudget('reset', () => - refreshPreparedWorktreeTip(repo, prepared, 'main', reason) - ) - expect(await readFile(join(prepared, 'included', 'file.txt'), 'utf8')).toBe('two\n') - await writeFile(join(repo, 'included', 'file.txt'), 'three\n') - await gitExecFileAsync( - ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qam', 'third'], - { cwd: repo } - ) - const target = join(root, 'finalized') - await behindCheckoutBudget('reset', () => - finalizePreparedWorktree(repo, prepared, target, 'finalized', 'main', false, {}, reason) - ) - expect(await readFile(join(target, 'included', 'file.txt'), 'utf8')).toBe('three\n') -}) - -it('isolates the production base fast-forward with its leading Git config arguments', async () => { - const newer = join(root, 'newer') - await addWorktree(repo, newer, 'newer', 'main') - await writeFile(join(newer, 'included', 'file.txt'), 'remote\n') - await gitExecFileAsync( - ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qam', 'remote'], - { cwd: newer } - ) - const { stdout } = await gitExecFileAsync(['rev-parse', 'HEAD'], { cwd: newer }) - await gitExecFileAsync(['update-ref', 'refs/remotes/origin/main', stdout.trim()], { cwd: repo }) - await behindCheckoutBudget('merge', () => - refreshLocalBaseRefForWorktreeCreate(repo, 'origin/main', 'refs/remotes/origin/main') - ) - expect(await readFile(join(repo, 'included', 'file.txt'), 'utf8')).toBe('remote\n') -}) diff --git a/src/main/github/client/check/get-pr-check-details.test.ts b/src/main/github/client/check/get-pr-check-details.test.ts deleted file mode 100644 index 91ee402477b..00000000000 --- a/src/main/github/client/check/get-pr-check-details.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' -import type * as GithubEnterpriseRepositoryModule from '../../repositories/github-enterprise-repository' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { ghExecFileAsyncMock, getOwnerRepoMock, rateLimitGuardMock } = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - rateLimitGuardMock: vi.fn(() => ({ blocked: false })) -})) - -vi.mock('../../execution/github-legacy-command', () => ({ - execFileAsync: vi.fn() -})) - -vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ - ghExecFileAsync: ghExecFileAsyncMock -})) - -vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ - ...(await importOriginal()), - githubRepoContext: (repoPath: string, connectionId?: string | null) => ({ - repoPath, - connectionId: connectionId ?? null - }), - ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }), - getOwnerRepoForRemote: ( - repoPath: string, - remoteName: string, - connectionId?: string | null, - localGitOptions?: unknown - ) => - remoteName === 'origin' - ? getOwnerRepoMock(repoPath, connectionId, localGitOptions) - : Promise.resolve(null), - _resetOwnerRepoCache: vi.fn() -})) - -vi.mock('../../repositories/github-owner-repo-selection', () => ({ - getOwnerRepo: getOwnerRepoMock -})) - -vi.mock('../../execution/github-operation-slots', () => ({ - acquire: vi.fn(), - release: vi.fn() -})) - -vi.mock('../../../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: vi.fn() -})) - -vi.mock('../../repositories/github-enterprise-repository', async (importOriginal) => ({ - ...(await importOriginal()), - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('../../api/rate-limit', () => ({ - rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: vi.fn(), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn(), - spendsSharedGitHubComQuota: vi.fn(() => true) -})) - -import { getPRCheckDetails } from './get-pr-check-details' -import { _resetOwnerRepoCache } from '../../repositories/github-repository-identity' - -describe('getPRCheckDetails', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - rateLimitGuardMock.mockReset() - rateLimitGuardMock.mockReturnValue({ blocked: false }) - _resetOwnerRepoCache() - }) - - it('aborts host work at the cumulative check-details deadline', async () => { - vi.useFakeTimers() - try { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) - ghExecFileAsyncMock.mockImplementation( - (_args: string[], options: { signal?: AbortSignal }) => - new Promise((_resolve, reject) => { - options.signal?.addEventListener( - 'abort', - () => { - const error = new Error('aborted') - error.name = 'AbortError' - reject(error) - }, - { once: true } - ) - }) - ) - const request = getPRCheckDetails('/repo-root', { checkRunId: 88 }) - const rejection = expect(request).rejects.toThrow('Timed out loading check details.') - - await vi.advanceTimersByTimeAsync(25_000) - - await rejection - } finally { - vi.useRealTimers() - } - }) - - it('stops waiting for shared repository resolution at the host deadline', async () => { - vi.useFakeTimers() - try { - getOwnerRepoMock.mockImplementationOnce(() => new Promise(() => {})) - const request = getPRCheckDetails('/repo-root', { checkRunId: 88 }) - const rejection = expect(request).rejects.toThrow('Timed out loading check details.') - - await vi.advanceTimersByTimeAsync(25_000) - - await rejection - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - - it('reads a fine-grained token check from its Actions job when the check run is refused', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) - const job = { - id: 71, - run_id: 7, - name: 'pytest', - status: 'completed', - conclusion: 'success', - html_url: 'https://github.com/acme/widgets/actions/runs/7/job/71', - started_at: '2026-11-10T10:00:00Z', - completed_at: '2026-11-10T10:05:00Z', - steps: [] - } - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - const path = args.at(-1) ?? '' - if (path.includes('/check-runs/71')) { - throw Object.assign(new Error(`Command failed: gh api ${path}`), { - stderr: 'gh: Resource not accessible by personal access token (HTTP 403)\n', - stdout: '' - }) - } - if (path.endsWith('/actions/jobs/71')) { - return { stdout: JSON.stringify(job), stderr: '' } - } - if (path.includes('/actions/runs/7/jobs')) { - return { stdout: JSON.stringify({ jobs: [job] }), stderr: '' } - } - throw new Error(`unexpected ${path}`) - }) - - const details = await getPRCheckDetails('/repo-root', { - checkRunId: 71, - workflowRunId: 7, - checkName: 'pytest' - }) - - expect(details).toMatchObject({ - name: 'pytest', - status: 'completed', - conclusion: 'success', - url: 'https://github.com/acme/widgets/actions/runs/7/job/71', - startedAt: '2026-11-10T10:00:00Z', - completedAt: '2026-11-10T10:05:00Z', - jobs: [{ id: 71, name: 'pytest', status: 'completed', conclusion: 'success' }] - }) - }) -}) diff --git a/src/main/github/project-view/project-view-reference.test.ts b/src/main/github/project-view/project-view-reference.test.ts deleted file mode 100644 index b6b9f5809da..00000000000 --- a/src/main/github/project-view/project-view-reference.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - GITHUB_PROJECT_REF_INPUT_MAX_BYTES, - GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR -} from '../../../shared/github/projects/project-ref-input' -import { - _getProjectViewCacheSizesForTests, - _getProjectViewOwnerTypeForTests, - _hasProjectViewParentFieldRetriedForTests, - _hasProjectViewParentFieldWarningLoggedForTests, - _markProjectViewParentFieldRetriedForTests, - _markProjectViewParentFieldWarningLoggedForTests, - _rememberProjectViewOwnerTypeForTests, - _resetProjectViewCachesForTests -} from './project-view-cache' -import { parseProjectPaste, resolveProjectRef } from './project-view-reference' - -describe('parseProjectPaste', () => { - it('accepts enterprise-host URLs only when that host is provided (GHES)', () => { - const url = 'https://github.corp.example/orgs/acme/projects/7/views/2' - expect(parseProjectPaste(url, 'github.corp.example')).toEqual({ - kind: 'org', - owner: 'acme', - number: 7, - host: 'github.corp.example', - viewNumber: 2 - }) - expect(parseProjectPaste(url)).toBeNull() - expect( - parseProjectPaste('https://github.com/orgs/acme/projects/7', 'github.corp.example') - ).toEqual({ kind: 'org', owner: 'acme', number: 7, host: 'github.com' }) - }) - - it('rejects credentials and paths that only begin like a Project URL', () => { - expect(parseProjectPaste('https://user:token@github.com/orgs/acme/projects/1')).toBeNull() - expect(parseProjectPaste('https://github.com/orgs/acme/projects/1evil')).toBeNull() - expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/views/2evil')).toBeNull() - expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/files')).toBeNull() - }) -}) - -describe('resolveProjectRef', () => { - it('rejects oversized project refs with a metadata-only validation error', async () => { - const secret = 'project-url-secret' - const input = [ - 'https://github.com/orgs/acme/projects/42?', - secret, - 'x'.repeat(GITHUB_PROJECT_REF_INPUT_MAX_BYTES) - ].join('') - - await expect(resolveProjectRef({ input })).resolves.toEqual({ - ok: false, - error: { - type: 'validation_error', - message: GITHUB_PROJECT_REF_INPUT_TOO_LARGE_ERROR, - reason: 'input_too_large' - } - }) - await expect(resolveProjectRef({ input })).resolves.not.toMatchObject({ - error: { message: expect.stringContaining(secret) } - }) - }) -}) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts deleted file mode 100644 index 830cb2b2295..00000000000 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-cache-follow-up.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const mocks = vi.hoisted(() => ({ resolve: vi.fn(), send: vi.fn(), selection: 0 })) -vi.mock('../../client/lookup/branch-lookup-resolution', () => ({ - resolvePRForBranchOutcome: mocks.resolve -})) -vi.mock('../../accounts/github-project-account', () => ({ - githubPRPolicyProjects: () => ({ source: null, selection: mocks.selection }), - resolveGitHubProjectAccount: () => null -})) -vi.mock('../../execution/github-operation-slots', () => ({ - acquire: async () => {}, - release: () => {} -})) -vi.mock('./pr-refresh-rate-limit-gate', () => ({ prRefreshRateLimitPausedUntil: async () => null })) -vi.mock('./pr-refresh-renderer-port', () => ({ - prRefreshRenderers: () => ({ isRendererOpen: () => true, sendToTrustedUI: mocks.send }) -})) - -beforeEach(() => { - vi.resetModules() - vi.useFakeTimers() - vi.setSystemTime(1_000) - mocks.selection = 0 - mocks.resolve.mockReset() - mocks.send.mockReset() -}) -afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() -}) - -function found(overrides: Parameters[0] = {}): PRRefreshOutcome { - return { - kind: 'found', - fetchedAt: Date.now(), - pr: makePR({ - checksStatus: 'success', - checksReadComplete: true, - checksFinal: true, - autoMergeEnabled: false, - mergeQueueRequired: false, - ...overrides - }) - } -} - -it('delivers a real refresh after quiet evidence retires without repeating the cached follow-up', async () => { - mocks.resolve.mockImplementation(async () => found()) - const coordinator = await import('./pr-refresh-coordinator') - const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') - const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) - const seed = () => - coordinator.runHostedPRRead(candidate, () => - getPRForBranchOutcome('/repo', candidate.branch, null, null, null, { - currentHeadOid: 'head-sha' - }) - ) - await seed() - vi.setSystemTime(2_000) - await seed() - const visible = { - ...candidate, - cachedFetchedAt: 2_000, - cachedHeadOid: 'head-sha', - cachedHasPR: true, - cachedPRState: 'open' as const, - cachedChecksStatus: 'success' as const - } - coordinator.reportVisiblePRRefreshCandidates([visible], 1, 1) - await vi.advanceTimersByTimeAsync(0) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - vi.setSystemTime(132_001) - mocks.selection++ - mocks.resolve.mockImplementation(async () => found({ title: 'updated' })) - mocks.send.mockClear() - mocks.send.mockImplementation(() => { - // Bound the unfixed synchronous loop even though its fake clock would otherwise never advance. - if (mocks.send.mock.calls.length === 8) { - vi.setSystemTime(1_000_000) - } - }) - coordinator.reportVisiblePRRefreshCandidates([visible], 2, 1) - await vi.advanceTimersByTimeAsync(0) - expect(mocks.resolve).toHaveBeenCalledTimes(3) - expect(mocks.send.mock.calls.length).toBeLessThanOrEqual(2) - expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ - outcome: { fetchedAt: 132_001, pr: { title: 'updated' } } - }) - await vi.advanceTimersByTimeAsync(120_001) - expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ - outcome: { fetchedAt: 252_001, pr: { title: 'updated' } } - }) -}) - -it('rereads unresolved manual mergeability at its forced follow-up despite the timed cache', async () => { - mocks.resolve - .mockImplementationOnce(async () => - found({ mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' }) - ) - .mockImplementation(async () => found({ mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN' })) - const coordinator = await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - expect(await coordinator.refreshPRNow(candidate)).toMatchObject({ - pr: { mergeable: 'UNKNOWN' } - }) - await vi.advanceTimersByTimeAsync(2_501) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ - outcome: { pr: { mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN' } } - }) -}) - -it.each([false, true])( - 'refreshes a settled row on re-exposure and shares a newer exact answer (refreshed while queued: %s)', - async (refreshedWhileQueued) => { - mocks.resolve.mockImplementation(async () => found({ state: 'merged' })) - const coordinator = await import('./pr-refresh-coordinator') - const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') - const candidate = makeCandidate({ currentHeadOid: 'head-sha', linkedPRNumber: 12 }) - const seed = () => - coordinator.runHostedPRRead(candidate, () => - getPRForBranchOutcome('/repo', candidate.branch, 12, null, null, { - currentHeadOid: 'head-sha', - userRefresh: true - }) - ) - await seed() - const visible = { - ...candidate, - cachedFetchedAt: 1_000, - cachedHeadOid: 'head-sha', - cachedHasPR: true, - cachedPRState: 'merged' as const, - cachedChecksStatus: 'success' as const - } - coordinator.reportVisiblePRRefreshCandidates([visible], 1, 1) - coordinator.reportVisiblePRRefreshCandidates([], 2, 1) - vi.setSystemTime(2_000) - coordinator.reportVisiblePRRefreshCandidates([visible], 3, 1) - await vi.advanceTimersByTimeAsync(0) - expect(mocks.resolve).toHaveBeenCalledTimes(1) - coordinator.reportVisiblePRRefreshCandidates([], 4, 1) - vi.setSystemTime(21_000) - mocks.resolve.mockImplementation(async () => found({ state: 'merged', title: 'updated' })) - mocks.send.mockClear() - coordinator.reportVisiblePRRefreshCandidates([visible], 5, 1) - if (refreshedWhileQueued) { - await seed() - } - await vi.advanceTimersByTimeAsync(0) - expect(mocks.send.mock.calls.at(-1)?.[1]).toMatchObject({ - outcome: { fetchedAt: 21_000, pr: { state: 'merged', title: 'updated' } } - }) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(600_000) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - } -) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts deleted file mode 100644 index b0f969a983f..00000000000 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) -// Only the provider is faked: the read, its exact cached result and the queue are the real ones. -const provider = vi.hoisted(() => ({ resolve: vi.fn() })) -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./pr-refresh-rate-limit-gate', () => ({ - prRefreshRateLimitPausedUntil: async () => null -})) -vi.mock('../../client/lookup/branch-lookup-resolution', () => ({ - resolvePRForBranchOutcome: provider.resolve -})) -vi.mock('../../execution/github-operation-slots', () => ({ - acquire: async () => {}, - release: () => {} -})) - -beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - provider.resolve.mockReset().mockImplementation(async () => ({ - kind: 'found', - // ast-grep-ignore: test-no-wall-clock -- resetPRRefreshCoordinatorMocks installs fake timers - fetchedAt: Date.now(), - pr: makePR({ checksStatus: 'pending' }) - })) -}) -afterEach(() => vi.useRealTimers()) - -it.each(['default', 'reduced', 'off'] as const)( - 'a return to a PR whose data is past the Default interval reads it under %s, then follows the timers', - async (cadence) => { - const policy = await import('../../../../shared/review-refresh-policy') - policy.setPRAutoRefreshCadence(cadence) - const coordinator = await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ isSelected: true, currentHeadOid: 'head-sha' }) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - expect(provider.resolve).toHaveBeenCalledTimes(1) - - coordinator.clearVisiblePRRefreshWindow(1) - await vi.advanceTimersByTimeAsync(90_000) - coordinator.reportVisiblePRRefreshCandidates( - [ - { - ...candidate, - cachedFetchedAt: 1_000, - cachedHeadOid: 'head-sha', - cachedHasPR: true, - cachedPRState: 'open', - cachedChecksStatus: 'pending' - } - ], - 2, - 1 - ) - await vi.advanceTimersByTimeAsync(0) - expect(provider.resolve).toHaveBeenCalledTimes(2) - - // Default keeps its one-minute timer; Reduced waits five minutes and Off has none. - await vi.advanceTimersByTimeAsync(4 * 60_000) - expect(provider.resolve.mock.calls.length > 2).toBe(cadence === 'default') - } -) - -it.each([ - ['default', 5_000, 21_000], - ['reduced', 31_000, 91_000], - ['off', 31_000, 91_000] -] as const)( - 'a settled PR shown again under %s reads only once past its settled age, and delivers the change without a timer after', - async (cadence, earlyAt, dueAt) => { - const policy = await import('../../../../shared/review-refresh-policy') - policy.setPRAutoRefreshCadence(cadence) - const coordinator = await import('./pr-refresh-coordinator') - const settled = (title: string) => async () => ({ - kind: 'found', - // ast-grep-ignore: test-no-wall-clock -- resetPRRefreshCoordinatorMocks installs fake timers - fetchedAt: Date.now(), - pr: makePR({ title, state: 'merged', checksStatus: 'success' }) - }) - provider.resolve.mockImplementation(settled('merged')) - const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - expect(provider.resolve).toHaveBeenCalledTimes(1) - const shownAgain = { - ...candidate, - cachedFetchedAt: 1_000, - cachedHeadOid: 'head-sha', - cachedHasPR: true, - cachedPRState: 'merged' as const, - cachedChecksStatus: 'success' as const - } - - // Shown again inside the settled age (10 s on Default, a minute otherwise): nothing is read. - coordinator.clearVisiblePRRefreshWindow(1) - await vi.advanceTimersByTimeAsync(earlyAt - 1_000) - coordinator.reportVisiblePRRefreshCandidates([shownAgain], 2, 1) - await vi.advanceTimersByTimeAsync(0) - expect(provider.resolve).toHaveBeenCalledTimes(1) - - // Shown again past it: the cached answer cannot satisfy the earned read, the change arrives. - coordinator.clearVisiblePRRefreshWindow(1) - await vi.advanceTimersByTimeAsync(dueAt - earlyAt) - provider.resolve.mockImplementation(settled('changed')) - coordinator.reportVisiblePRRefreshCandidates([shownAgain], 3, 1) - await vi.advanceTimersByTimeAsync(0) - expect(provider.resolve).toHaveBeenCalledTimes(2) - expect(coordinatorMocks.sendToTrustedUIRendererMock.mock.calls.at(-1)?.[1]).toMatchObject({ - outcome: { pr: { title: 'changed' } } - }) - await vi.advanceTimersByTimeAsync(60 * 60_000) - expect(provider.resolve).toHaveBeenCalledTimes(2) - } -) - -it('a settled PR shown again takes the answer another reader just fetched instead of reading again', async () => { - const coordinator = await import('./pr-refresh-coordinator') - const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') - const { hostedReviewOptionArgs } = await import('./pr-refresh-candidate-policy') - const settled = (title: string) => async () => ({ - kind: 'found', - // ast-grep-ignore: test-no-wall-clock -- resetPRRefreshCoordinatorMocks installs fake timers - fetchedAt: Date.now(), - pr: makePR({ title, state: 'merged', checksStatus: 'success' }) - }) - provider.resolve.mockImplementation(settled('merged')) - const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - coordinator.clearVisiblePRRefreshWindow(1) - await vi.advanceTimersByTimeAsync(20_000) - - // Another reader of the same request reads it just before the row is shown again. - provider.resolve.mockImplementation(settled('shared')) - await coordinator.runHostedPRRead(candidate, () => - getPRForBranchOutcome( - candidate.repoPath, - candidate.branch, - null, - null, - null, - hostedReviewOptionArgs(candidate, 'visible')[0] ?? {} - ) - ) - expect(provider.resolve).toHaveBeenCalledTimes(2) - coordinator.reportVisiblePRRefreshCandidates( - [ - { - ...candidate, - cachedFetchedAt: 1_000, - cachedHeadOid: 'head-sha', - cachedHasPR: true, - cachedPRState: 'merged', - cachedChecksStatus: 'success' - } - ], - 2, - 1 - ) - await vi.advanceTimersByTimeAsync(0) - expect(provider.resolve).toHaveBeenCalledTimes(2) - expect(coordinatorMocks.sendToTrustedUIRendererMock.mock.calls.at(-1)?.[1]).toMatchObject({ - outcome: { pr: { title: 'shared' } } - }) -}) diff --git a/src/main/github/repositories/github-repository-identity-cache.test.ts b/src/main/github/repositories/github-repository-identity-cache.test.ts deleted file mode 100644 index 63bba89f548..00000000000 --- a/src/main/github/repositories/github-repository-identity-cache.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn() -})) - -vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', async (importOriginal) => ({ - ...(await importOriginal>()), - ghExecFileAsync: vi.fn() -})) - -import { _resetRemoteNameListingCache } from '../../git/remotes/remote-name-listing' -import { - _getOwnerRepoCacheSize, - _resetOwnerRepoCache, - getOwnerRepoForRemote -} from './github-repository-identity' -import { getOwnerRepo } from './github-owner-repo-selection' -import { __resetLocalGitConfigSignatureCacheForTests } from './local-git-config-signature' - -function gitRemoteGetUrlCalls(remoteName: string): unknown[][] { - return gitExecFileAsyncMock.mock.calls.filter( - ([args]) => - Array.isArray(args) && args[0] === 'remote' && args[1] === 'get-url' && args[2] === remoteName - ) -} - -describe('github owner/repo resolution', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - _resetOwnerRepoCache() - _resetRemoteNameListingCache() - __resetLocalGitConfigSignatureCacheForTests() - }) - - it('keeps local host and local WSL owner/repo cache entries separate for the same path', async () => { - gitExecFileAsyncMock.mockImplementation( - async (args: string[], options: { wslDistro?: string } = {}) => { - if (args[0] === 'remote' && args[1] !== 'get-url') { - return { stdout: 'origin\n' } - } - if (args[2] === 'upstream') { - throw new Error("fatal: No such remote 'upstream'") - } - return { - stdout: options.wslDistro - ? 'git@github.com:wsl/orca.git\n' - : 'git@github.com:host/orca.git\n' - } - } - ) - - await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'host', repo: 'orca' }) - await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({ - owner: 'wsl', - repo: 'orca' - }) - await expect(getOwnerRepo('/repo', null, { wslDistro: 'Ubuntu' })).resolves.toEqual({ - owner: 'wsl', - repo: 'orca' - }) - - // 2 runtimes x (1 remote list + 1 origin hit); repeat WSL call is cached. - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(4) - expect(gitRemoteGetUrlCalls('upstream')).toHaveLength(0) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo', - timeout: 30_000 - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo', - timeout: 30_000, - wslDistro: 'Ubuntu' - }) - }) - - it('does not apply the long negative TTL when git remote get-url fails transiently', async () => { - const repoPath = await mkdtemp(join(tmpdir(), 'orca-gh-utils-')) - await mkdir(join(repoPath, '.git')) - await writeFile(join(repoPath, '.git', 'config'), '[core]\n\trepositoryformatversion = 0\n') - try { - gitExecFileAsyncMock - .mockRejectedValueOnce(new Error('fatal: cannot lock ref')) - .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) - - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toBeNull() - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toEqual({ - owner: 'acme', - repo: 'widgets' - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) - } finally { - await rm(repoPath, { recursive: true, force: true }) - } - }) - - it('invalidates a cached local missing remote when an included git config changes', async () => { - const repoPath = await mkdtemp(join(tmpdir(), 'orca-gh-utils-')) - await mkdir(join(repoPath, '.git')) - const includedConfigPath = join(repoPath, 'remote.inc') - await writeFile( - join(repoPath, '.git', 'config'), - `[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = ${includedConfigPath}\n` - ) - await writeFile(includedConfigPath, '') - vi.useFakeTimers() - try { - vi.setSystemTime(1_000) - gitExecFileAsyncMock - .mockRejectedValueOnce(new Error("error: No such remote 'origin'")) - .mockResolvedValueOnce({ stdout: 'git@github.com:acme/widgets.git\n' }) - - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toBeNull() - await writeFile( - includedConfigPath, - '[remote "origin"]\n\turl = git@github.com:acme/widgets.git\n' - ) - vi.setSystemTime(32_000) - - await expect(getOwnerRepoForRemote(repoPath, 'origin')).resolves.toEqual({ - owner: 'acme', - repo: 'widgets' - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) - } finally { - vi.useRealTimers() - await rm(repoPath, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/hang-watchdog/main-js-hang-capture.test.ts b/src/main/hang-watchdog/main-js-hang-capture.test.ts deleted file mode 100644 index 5f52c1a1eb2..00000000000 --- a/src/main/hang-watchdog/main-js-hang-capture.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { captureMainJsHang } from './main-js-hang-capture' -import type { MainJsCapture } from './hang-stacks' - -function fixture() { - let callback: ((error: Error | null, result?: unknown) => void) | undefined - const commands: string[] = [] - const disconnect = vi.fn() - let finishDrain: (() => void) | undefined - const records: MainJsCapture[] = [] - const capture = captureMainJsHang({ - session: { - connectToMainThread: () => {}, - disconnect, - post: (method, _params, response) => { - commands.push(method) - callback = response - } - }, - detectedAt: 0, - now: () => 100, - publish: (record) => records.push(record), - drain: () => - new Promise((resolve) => { - finishDrain = resolve - }) - }) - const acknowledge = async (result?: unknown, error: Error | null = null): Promise => { - const response = callback - callback = undefined - response?.(error, result) - await Promise.resolve() - await Promise.resolve() - } - return { capture, commands, disconnect, records, acknowledge, drain: () => finishDrain?.() } -} - -it('does not start after recovery while enable is pending, and drains only after disable acknowledgement', async () => { - const f = fixture() - f.capture.stop('recovery') - expect(f.disconnect).not.toHaveBeenCalled() - await f.acknowledge() - expect(f.commands).toEqual(['Profiler.enable', 'Profiler.disable']) - expect(f.disconnect).not.toHaveBeenCalled() - await f.acknowledge() - expect(f.disconnect).toHaveBeenCalledOnce() - expect(f.records.at(-1)?.cleanup).toBe('pending') - f.drain() - await f.capture.done - expect(f.records.at(-1)).toMatchObject({ - state: 'not-started', - cleanup: 'drain-complete', - stopReason: 'recovery' - }) -}) - -it('owns a posted start and its stop through shutdown without racing disconnect', async () => { - const f = fixture() - await f.acknowledge() - await f.acknowledge() - expect(f.commands).toEqual(['Profiler.enable', 'Profiler.setSamplingInterval', 'Profiler.start']) - f.capture.stop('shutdown') - await f.acknowledge() - expect(f.commands.at(-1)).toBe('Profiler.stop') - expect(f.disconnect).not.toHaveBeenCalled() - await f.acknowledge({ profile: { nodes: [], samples: [], startTime: 1000, endTime: 3000 } }) - expect(f.commands.at(-1)).toBe('Profiler.disable') - expect(f.disconnect).not.toHaveBeenCalled() - await f.acknowledge() - f.drain() - await f.capture.done - expect(f.records.at(-1)).toMatchObject({ - state: 'completed', - profileDurationMs: 2, - cleanup: 'drain-complete', - stopReason: 'shutdown' - }) -}) - -it('does not disconnect or release an owner after stop fails', async () => { - const f = fixture() - await f.acknowledge() - await f.acknowledge() - await f.acknowledge() - f.capture.stop('recovery') - await Promise.resolve() - await f.acknowledge(undefined, new Error('stop rejected')) - expect(f.commands.at(-1)).toBe('Profiler.stop') - expect(f.disconnect).not.toHaveBeenCalled() - expect(f.records.at(-1)).toMatchObject({ state: 'failed', cleanup: 'pending' }) -}) diff --git a/src/main/hang-watchdog/renderer-hang-capture.test.ts b/src/main/hang-watchdog/renderer-hang-capture.test.ts deleted file mode 100644 index 8fee90d754b..00000000000 --- a/src/main/hang-watchdog/renderer-hang-capture.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { BrowserWindow } from 'electron' - -const state = vi.hoisted(() => ({ - contents: new Map(), - metrics: [{ pid: 50, creationTime: 100 }], - records: new Array(), - publication: Promise.resolve() -})) -vi.mock('electron', async () => { - const { EventEmitter } = await import('node:events') - return { - app: Object.assign(new EventEmitter(), { getAppMetrics: () => state.metrics }), - webContents: { fromId: (id: number) => state.contents.get(id) } - } -}) -vi.mock('../observability', () => ({ - resolveObservabilityConsent: () => ({ localFileEnabled: true }) -})) -vi.mock('../persistence/loading-store/user-data-path', () => ({ - getCanonicalUserDataPath: () => '/qa' -})) -vi.mock('./renderer-hang-records', () => ({ - publishRendererHang: (_path: string, record: unknown) => { - state.records.push(structuredClone(record)) - return state.publication - } -})) -import { startRendererHangCapture } from './renderer-hang-capture' - -const handles: { stop: () => void }[] = [] -const responses: (() => void)[] = [] -beforeEach(() => { - state.contents.clear() - state.records = [] - state.publication = Promise.resolve() - state.metrics = [{ pid: 50, creationTime: 100 }] - vi.useFakeTimers() - vi.setSystemTime(1000) -}) -afterEach(async () => { - for (const handle of handles.splice(0)) { - handle.stop() - } - for (const respond of responses.splice(0)) { - respond() - } - await Promise.resolve() - vi.clearAllTimers() - vi.useRealTimers() -}) -function window(id: number, pid = 50) { - let reply: (stack: string) => void = () => {} - let requested = false - const frame = { - processId: 7, - osProcessId: pid, - collectJavaScriptCallStack: () => { - requested = true - return new Promise((resolve) => { - reply = resolve - responses.push(() => resolve('')) - }) - } - } - const contents = { id, mainFrame: frame, isDestroyed: () => false, isDevToolsOpened: () => false } - state.contents.set(id, contents) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this Electron test double supplies the members used by the collector; unused native members are never accessed. - const target = { id, webContents: contents, isDestroyed: () => false } as unknown as BrowserWindow - return { - requested: () => requested, - start: async () => { - const handle = startRendererHangCapture(target) - if (handle) { - handles.push(handle) - } - await Promise.resolve() - return handle - }, - reply: async () => { - reply('at busy (file:///private/qa/app.js:7:3)') - await Promise.resolve() - await Promise.resolve() - } - } -} - -it('keeps a shared-process request owned across window death and drops its stale result', async () => { - const old = window(1) - ;(await old.start())?.stop() - state.contents.delete(1) - const replacement = window(2) - await replacement.start() - expect(state.records.at(-1)).toMatchObject({ - windowId: 2, - status: 'process-capture-pending', - stacks: [] - }) - await old.reply() - expect( - state.records.some( - (record) => - record !== null && - typeof record === 'object' && - 'status' in record && - record.status === 'captured' - ) - ).toBe(false) - vi.setSystemTime(2000) - await replacement.start() - await replacement.reply() - expect(state.records.at(-1)).toMatchObject({ - windowId: 2, - status: 'captured', - stacks: [{ frames: [{ name: 'busy', module: 'app.js', line: 7, column: 3 }], count: 1 }] - }) -}) - -it('reconciles a dead generation before admission and an old reply cannot clear its successor', async () => { - const old = window(3) - ;(await old.start())?.stop() - state.contents.delete(3) - state.metrics = [{ pid: 50, creationTime: 200 }] - const successor = window(4) - await successor.start() - await old.reply() - const shared = window(5) - await shared.start() - expect(state.records.at(-1)).toMatchObject({ windowId: 5, status: 'process-capture-pending' }) - await successor.reply() - expect(state.records.at(-1)).toMatchObject({ windowId: 4, status: 'captured' }) -}) - -it('awaits baseline publication before requesting a stack and cannot start after cancellation during the write', async () => { - let finishPublication: () => void = () => {} - state.publication = new Promise((resolve) => { - finishPublication = resolve - }) - const cancelled = window(8) - const handle = await cancelled.start() - expect(cancelled.requested()).toBe(false) - handle?.stop() - finishPublication() - await Promise.resolve() - expect(cancelled.requested()).toBe(false) - - state.publication = new Promise((resolve) => { - finishPublication = resolve - }) - const live = window(9) - await live.start() - expect(live.requested()).toBe(false) - finishPublication() - await Promise.resolve() - expect(live.requested()).toBe(true) - await live.reply() - expect(state.records.at(-1)).toMatchObject({ windowId: 9, status: 'captured' }) -}) diff --git a/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.test.ts b/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.test.ts deleted file mode 100644 index 205297c751d..00000000000 --- a/src/main/ipc/runtime-environments/connections/runtime-environment-capability-evidence.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' -import { beforeEach, describe, expect, it } from 'vitest' -import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { - advanceRuntimeEnvironmentCapabilityIncarnation, - applyRuntimeEnvironmentCapabilityVerdict, - captureRuntimeEnvironmentCapabilityEvidence, - getAcceptedRuntimeEnvironmentCapabilityOutcome, - isRuntimeEnvironmentCapabilityOutcomeCurrent, - isRuntimeEnvironmentCapabilityPaused, - resetRuntimeEnvironmentCapabilityEvidence, - runtimeEnvironmentCapabilityOutcome -} from './runtime-environment-capability-evidence' - -beforeEach(resetRuntimeEnvironmentCapabilityEvidence) - -describe('runtime environment capability evidence', () => { - it('accepts evidence by dispatch order instead of completion order', () => { - const older = captureRuntimeEnvironmentCapabilityEvidence( - 'env', - pairedRuntimeConnectionFromOffer(pairing()) - ) - const newer = captureRuntimeEnvironmentCapabilityEvidence( - 'env', - pairedRuntimeConnectionFromOffer(pairing()) - ) - - expect( - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: newer, - verdict: 'capable', - runtimeId: 'runtime-new' - }) - ).toBe(true) - expect( - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: older, - verdict: 'absent', - runtimeId: 'runtime-old' - }) - ).toBe(false) - - expect(isRuntimeEnvironmentCapabilityPaused('env')).toBe(false) - }) - - it('rejects every pre-invalidation completion, including a same-pairing cycle', () => { - const evidence = captureRuntimeEnvironmentCapabilityEvidence( - 'env', - pairedRuntimeConnectionFromOffer(pairing()) - ) - advanceRuntimeEnvironmentCapabilityIncarnation('env') - - expect( - applyRuntimeEnvironmentCapabilityVerdict({ - evidence, - verdict: 'capable', - runtimeId: 'runtime-old' - }) - ).toBe(false) - expect( - isRuntimeEnvironmentCapabilityOutcomeCurrent( - runtimeEnvironmentCapabilityOutcome(evidence, 'capable', 'runtime-old') - ) - ).toBe(false) - }) - - it('invalidates cached outcomes symmetrically on contradictory evidence', () => { - const supportedEvidence = captureRuntimeEnvironmentCapabilityEvidence( - 'env', - pairedRuntimeConnectionFromOffer(pairing()) - ) - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: supportedEvidence, - verdict: 'capable', - runtimeId: 'runtime' - }) - const supported = runtimeEnvironmentCapabilityOutcome(supportedEvidence, 'capable', 'runtime') - const absentEvidence = captureRuntimeEnvironmentCapabilityEvidence( - 'env', - pairedRuntimeConnectionFromOffer(pairing()) - ) - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: absentEvidence, - verdict: 'absent', - runtimeId: 'runtime' - }) - - expect(isRuntimeEnvironmentCapabilityOutcomeCurrent(supported)).toBe(false) - expect(isRuntimeEnvironmentCapabilityPaused('env')).toBe(true) - expect( - getAcceptedRuntimeEnvironmentCapabilityOutcome( - 'env', - pairedRuntimeConnectionFromOffer(pairing()), - 'runtime' - ) - ).toMatchObject({ - kind: 'unsupported' - }) - - const recoveredEvidence = captureRuntimeEnvironmentCapabilityEvidence( - 'env', - pairedRuntimeConnectionFromOffer(pairing()) - ) - applyRuntimeEnvironmentCapabilityVerdict({ - evidence: recoveredEvidence, - verdict: 'capable', - runtimeId: 'runtime' - }) - expect( - isRuntimeEnvironmentCapabilityOutcomeCurrent( - runtimeEnvironmentCapabilityOutcome(absentEvidence, 'absent', 'runtime') - ) - ).toBe(false) - expect( - getAcceptedRuntimeEnvironmentCapabilityOutcome( - 'env', - pairedRuntimeConnectionFromOffer(pairing()), - 'runtime' - ) - ).toMatchObject({ - kind: 'supported' - }) - }) -}) - -function pairing(): PairingOffer { - return { - v: 2, - endpoint: 'ws://host', - deviceToken: 'token', - publicKeyB64: 'key' - } -} diff --git a/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.test.ts b/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.test.ts deleted file mode 100644 index 864b78df3ea..00000000000 --- a/src/main/ipc/runtime-environments/requests/runtime-environment-request-preparation.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -// #36923: opening a sleeping paired recipe VM wakes it, and the wake re-pairs its server. The -// opening request is held to its caller's pairing as of before that wake, then to the pairing the -// wake made; any other change still refuses it. -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const BEFORE = { id: 'env-vm', pairingRevision: 1, runtimeId: 'before', createdAt: 0 } -const AFTER_WAKE = { id: 'env-vm', pairingRevision: 2, runtimeId: 'after', createdAt: 0 } - -type Prepared = { - environment: Record - before: Record - wokenPairingRevision: number | null -} -const prepared = vi.hoisted((): { current: Prepared | null } => ({ current: null })) -const prepare = vi.hoisted(() => vi.fn(async () => prepared.current)) -vi.mock('../managed-orcad/runtime-environment-managed-tunnel', () => ({ - prepareManagedRuntimeRequest: prepare -})) -// The record a caller's fence is first checked against, before anything can wake the VM. -vi.mock('../../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: () => prepared.current?.before -})) - -import { prepareFencedRuntimeRequest } from './runtime-environment-request-preparation' - -function fence(pairingRevision: number, runtimeId: string) { - return prepareFencedRuntimeRequest('/user-data', 'env-vm', 'worktree.activate', undefined, { - pairingRevision, - runtimeId - }) -} - -describe('a request whose own recipe VM wake re-paired its server', () => { - beforeEach(() => { - prepare.mockClear() - prepared.current = { environment: AFTER_WAKE, before: BEFORE, wokenPairingRevision: 2 } - }) - - it('passes the fence its caller set before the wake, then expects the new pairing', async () => { - await expect(fence(1, 'before')).resolves.toMatchObject({ - failure: null, - expected: { pairingRevision: 2, runtimeId: undefined } - }) - }) - - it('refuses a stale caller before its request can wake the VM', async () => { - const result = await fence(0, 'before') - expect(result.failure).toMatchObject({ ok: false }) - }) - - it('refuses an unrelated re-pair after its own wake', async () => { - prepared.current = { - environment: { ...AFTER_WAKE, pairingRevision: 3 }, - before: BEFORE, - wokenPairingRevision: 2 - } - expect((await fence(1, 'before')).failure).toMatchObject({ ok: false }) - }) -}) diff --git a/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts b/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts deleted file mode 100644 index 810266e9496..00000000000 --- a/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import type { - AgentJournalRenderItem, - AgentJournalSnapshot -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { readAgentSessionConversationOutline } from '../agent-session-conversation-outline' -import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from '../agent-session-history-page-bounds' - -function prompt(sequence: number, text: string): AgentJournalRenderItem { - return { - itemId: `user-${sequence}`, - revision: 1, - sequence, - observedAt: sequence, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } -} - -function snapshot(items: AgentJournalRenderItem[]): AgentJournalSnapshot { - return { - sessionId: 'session-1', - cursor: { epoch: 'epoch-1', sequence: items.at(-1)?.sequence ?? 0 }, - items, - submissions: [] - } -} - -function replyBytes(value: unknown): number { - return Buffer.byteLength(JSON.stringify(value), 'utf8') -} - -describe('conversation outline read', () => { - it('stays inside the history page budget for a journal far past it', () => { - const items = Array.from({ length: 10_000 }, (_, index) => - prompt(index + 1, `${index} ${'y'.repeat(1_000)}`) - ) - const outline = readAgentSessionConversationOutline(snapshot(items)) - expect(replyBytes(outline)).toBeLessThanOrEqual(HISTORY_PAGE_CONTENT_BUDGET_BYTES) - expect(outline.entries.at(-1)?.itemId).toBe('user-10000') - }) - - // Newer clients ignore an unmarked outline, which older hosts may fill with agent-written inputs. - it('marks its outline as listing only messages a person wrote', () => { - expect(readAgentSessionConversationOutline(snapshot([]))).toEqual({ - sessionId: 'session-1', - humanMessagesOnly: true, - cursor: { epoch: 'epoch-1', sequence: 0 }, - entries: [], - omittedEntries: 0 - }) - }) - - it('omits sent [Image #N] markers from user message outline previews', () => { - const outline = readAgentSessionConversationOutline( - snapshot([ - { - itemId: 'user-1', - revision: 1, - sequence: 1, - observedAt: 1, - body: { - kind: 'message', - role: 'user', - blocks: [ - { type: 'text', text: 'Compare [Image #1] with baseline' }, - { type: 'image-ref', path: '/tmp/shot.png' } - ] - } - } - ]) - ) - expect(outline.entries).toEqual([ - { - itemId: 'user-1', - sequence: 1, - preview: 'Compare with baseline', - imageCount: 1 - } - ]) - }) -}) diff --git a/src/main/opencode/accounts/opencode-structured-account-home.test.ts b/src/main/opencode/accounts/opencode-structured-account-home.test.ts deleted file mode 100644 index 8bc2f4fe492..00000000000 --- a/src/main/opencode/accounts/opencode-structured-account-home.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ManagedDataAccountsState } from '../../../shared/managed-account-types' -import { restoreManagedDataAccountEnvironment } from '../../../shared/managed-data-account-environment' -import { - environmentForStructuredOpenCodeAccountHome, - resolveStructuredOpenCodeAccountHome -} from './opencode-structured-account-home' - -const first = '123e4567-e89b-42d3-a456-426614174000' -const second = '123e4567-e89b-42d3-a456-426614174001' - -function managedAccounts() { - let activeAccountId: string | null = first - let available = new Set([first, second]) - return { - list: (): ManagedDataAccountsState => ({ - accounts: [...available].map((id) => ({ id, label: id, integrations: [], createdAt: 0 })), - activeAccountId - }), - restoreOriginalEnvironment: (environment: Record) => - restoreManagedDataAccountEnvironment(environment), - environmentForAccount: (_provider: 'opencode' | 'devin', id: string) => { - if (!available.has(id)) { - throw new Error('Managed account not found.') - } - return { - XDG_DATA_HOME: `/profiles/${id}/data`, - XDG_STATE_HOME: `/profiles/${id}/state`, - OPENCODE_DB: 'opencode.db', - OPENCODE_AUTH_CONTENT: '' - } - }, - select: (id: string | null) => { - activeAccountId = id - }, - remove: (id: string) => { - available = new Set([...available].filter((entry) => entry !== id)) - } - } -} - -describe('structured OpenCode account binding', () => { - it('uses the pinned managed profile after selection changes and refuses removal', () => { - const accounts = managedAccounts() - const binding = resolveStructuredOpenCodeAccountHome({ managedAccounts: accounts }) - accounts.select(second) - const environment = environmentForStructuredOpenCodeAccountHome(binding, { - managedAccounts: accounts, - baseEnvironment: { PATH: '/bin', XDG_DATA_HOME: '/settings/data', OPENCODE_DB: 'work.db' } - }) - expect(environment.XDG_DATA_HOME).toBe(`/profiles/${first}/data`) - expect(environment.OPENCODE_DB).toBe('opencode.db') - expect(resolveStructuredOpenCodeAccountHome({ managedAccounts: accounts }).locator).toEqual({ - kind: 'managed', - managedProfileId: second - }) - accounts.remove(first) - expect(() => - environmentForStructuredOpenCodeAccountHome(binding, { - managedAccounts: accounts, - baseEnvironment: {} - }) - ).toThrow('Managed account not found.') - }) - - it("passes the user's inline credentials, relative paths and database through unchanged", () => { - const accounts = managedAccounts() - accounts.select(null) - const baseEnvironment = { - PATH: '/bin', - HOME: 'relative/home', - XDG_DATA_HOME: 'relative/data', - XDG_STATE_HOME: 'relative/state', - OPENCODE_DB: 'custom.db', - OPENCODE_AUTH_CONTENT: '{"provider":{"type":"api","key":"inline"}}' - } - const binding = resolveStructuredOpenCodeAccountHome({ managedAccounts: accounts }) - expect( - environmentForStructuredOpenCodeAccountHome(binding, { - managedAccounts: accounts, - baseEnvironment - }) - ).toEqual(baseEnvironment) - }) - - it("undoes Orca's inherited managed overlay before passing the environment through", () => { - const accounts = managedAccounts() - accounts.select(null) - const environment = environmentForStructuredOpenCodeAccountHome( - { kind: 'opencode', locator: { kind: 'unmanaged' } }, - { - managedAccounts: accounts, - baseEnvironment: { - ORCA_DATA_ACCOUNT_PROVIDER: 'opencode', - ORCA_DATA_ACCOUNT_DATA_HOME: '/old/data', - ORCA_DATA_ACCOUNT_STATE_HOME: '/old/state', - ORCA_DATA_ACCOUNT_ORIGINAL_ENV: JSON.stringify({ - XDG_DATA_HOME: '/original/data', - XDG_STATE_HOME: null, - OPENCODE_DB: 'original.db', - OPENCODE_AUTH_CONTENT: null - }), - XDG_DATA_HOME: '/old/data', - XDG_STATE_HOME: '/old/state', - OPENCODE_DB: 'opencode.db', - OPENCODE_AUTH_CONTENT: '', - PATH: '/bin' - } - } - ) - expect(environment).toEqual({ - XDG_DATA_HOME: '/original/data', - OPENCODE_DB: 'original.db', - PATH: '/bin' - }) - }) -}) diff --git a/src/main/opencode/session-correlation/opencode-session-binder.test.ts b/src/main/opencode/session-correlation/opencode-session-binder.test.ts deleted file mode 100644 index ae2518eb624..00000000000 --- a/src/main/opencode/session-correlation/opencode-session-binder.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createHookListenerState } from '../../../shared/agent-hook-listener/listener-state' -import { lookupOpenCodeSessionPane } from '../../../shared/agent-hook-listener/opencode-session-registry' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { ProcessIdentityRow } from './opencode-client-sweep' -import { - applyBinderOwnerships, - runOpenCodeBinderRound, - type BinderPaneSnapshot -} from './opencode-session-binder' - -const NOW = 1_700_000_100_000 -const DIR = '/Users/jin/work/mocitec' -const PANE_A = makePaneKey('tab-a', 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa') -const PANE_B = makePaneKey('tab-b', 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb') - -function proc( - pid: number, - ppid: number, - argv: string[], - startedAtMs = NOW - 120_000 -): ProcessIdentityRow { - return { pid, ppid, startedAtMs, executable: argv[0] ?? '', argv } -} - -function pane(paneKey: string, shellPid: number | null): BinderPaneSnapshot { - return { paneKey, directory: DIR, worktreeId: 'repo::/Users/jin/work/mocitec', shellPid } -} - -describe('runOpenCodeBinderRound', () => { - it('attributes a client to its pane subtree and binds the session', () => { - const { ownerships } = runOpenCodeBinderRound({ - nowMs: NOW, - sessions: [{ id: 'ses_1', directory: DIR, createdAtMs: NOW - 60_000, parentId: null }], - panes: [pane(PANE_A, 100), pane(PANE_B, 200)], - processes: [ - proc(100, 1, ['zsh']), - proc(200, 1, ['zsh']), - proc(210, 200, ['opencode'], NOW - 90_000) - ], - knownOwners: new Map(), - parentBySessionId: new Map() - }) - expect(ownerships).toEqual([ - { sessionId: 'ses_1', paneKey: PANE_B, basis: 'creation-correlation' } - ]) - }) - - it('inherits a root owner across the watermark via the parent map', () => { - const { ownerships } = runOpenCodeBinderRound({ - nowMs: NOW, - sessions: [ - { id: 'ses_child', directory: DIR, createdAtMs: NOW - 30_000, parentId: 'ses_root' } - ], - panes: [pane(PANE_A, 100)], - processes: [proc(100, 1, ['zsh']), proc(101, 100, ['opencode'], NOW - 3_600_000)], - knownOwners: new Map([['ses_root', PANE_A]]), - parentBySessionId: new Map([['ses_child', 'ses_root']]) - }) - expect(ownerships).toEqual([ - { sessionId: 'ses_child', paneKey: PANE_A, basis: 'creation-correlation' } - ]) - }) -}) - -describe('applyBinderOwnerships', () => { - it('takes the newest row worktree when a pane remints', () => { - const state = createHookListenerState() - // Insert stale first so a reminted pane’s newer worktree must win. - const applied = applyBinderOwnerships( - state, - [ - { paneKey: PANE_A, directory: '/elsewhere', worktreeId: 'repo::/elsewhere', shellPid: 100 }, - { ...pane(PANE_A, 101) } - ], - [{ sessionId: 'ses_1', paneKey: PANE_A, basis: 'argv' }], - NOW - ) - expect(applied).toBe(1) - expect(lookupOpenCodeSessionPane(state, 'ses_1')).toMatchObject({ - paneKey: PANE_A, - worktreeId: 'repo::/Users/jin/work/mocitec' - }) - }) -}) diff --git a/src/main/opencode/startup-prompts/opencode-startup-prompt-claims.test.ts b/src/main/opencode/startup-prompts/opencode-startup-prompt-claims.test.ts deleted file mode 100644 index 230d8e43b5b..00000000000 --- a/src/main/opencode/startup-prompts/opencode-startup-prompt-claims.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { TerminalRunFacts } from '../../runtime/terminal/lifecycle/terminal-run-facts' -import { OpenCodeStartupPromptClaims } from './opencode-startup-prompt-claims' - -describe('execution-owned startup prompt claims', () => { - it('consumes each nonce once and checks owner facts at claim time', () => { - const claims = new OpenCodeStartupPromptClaims() - let facts: TerminalRunFacts | null = { freshSpawn: true, firstUserInputAt: null } - claims.register('first', 'hash', () => facts) - facts.firstUserInputAt = 1 - expect(claims.claim({ nonce: 'first', digest: 'hash' })).toBe(false) - facts.firstUserInputAt = null - expect(claims.claim({ nonce: 'first', digest: 'hash' })).toBe(false) - claims.register('second', 'hash', () => facts) - expect(claims.claim({ nonce: 'second', digest: 'hash' })).toBe(true) - expect(claims.claim({ nonce: 'second', digest: 'hash' })).toBe(false) - claims.register('missing', 'hash', () => facts) - facts = null - expect(claims.claim({ nonce: 'missing', digest: 'hash' })).toBe(false) - }) - - it('keeps pending admission bounded and never recreates canceled or consumed claims', () => { - let now = 0 - const claims = new OpenCodeStartupPromptClaims(() => now) - claims.register('waiting', 'hash', () => 'pending') - expect(claims.claim({ nonce: 'waiting', digest: 'hash' })).toBe('pending') - expect(claims.claim({ nonce: 'waiting', digest: 'hash' })).toBe('pending') - expect(claims.admit('waiting', () => ({ freshSpawn: true, firstUserInputAt: null }))).toBe(true) - expect(claims.claim({ nonce: 'waiting', digest: 'hash' })).toBe(true) - expect(claims.admit('waiting', () => ({ freshSpawn: true, firstUserInputAt: null }))).toBe( - false - ) - claims.register('canceled', 'hash', () => 'pending') - claims.cancel('canceled') - expect(claims.admit('canceled', () => ({ freshSpawn: true, firstUserInputAt: null }))).toBe( - false - ) - claims.register('expired', 'hash', () => 'pending') - now = 20000 - expect(claims.claim({ nonce: 'expired', digest: 'hash' })).toBe(false) - expect(claims.admit('expired', () => ({ freshSpawn: true, firstUserInputAt: null }))).toBe( - false - ) - claims.clear() - }) - - it('replays only the same operation while execution facts remain authorized', () => { - let now = 0 - const claims = new OpenCodeStartupPromptClaims(() => now) - let facts: TerminalRunFacts | null = { freshSpawn: true, firstUserInputAt: null } - const cleanup = vi.fn() - claims.register('retry', 'hash', () => facts, cleanup) - const body = { nonce: 'retry', digest: 'hash', requestId: 'stable-operation' } - expect(claims.claim(body)).toBe(true) - expect(claims.claim(body)).toBe(true) - expect(claims.claim({ ...body, requestId: 'another-operation' })).toBe(false) - expect(claims.claim({ nonce: 'retry', digest: 'hash' })).toBe(false) - expect(cleanup).not.toHaveBeenCalled() - expect(claims.claim(body)).toBe(true) - facts.firstUserInputAt = 1 - expect(claims.claim(body)).toBe(false) - expect(cleanup).toHaveBeenCalledTimes(1) - facts = { freshSpawn: true, firstUserInputAt: null } - expect(claims.claim(body)).toBe(false) - claims.register('expires', 'hash', () => facts, cleanup) - expect(claims.claim({ ...body, nonce: 'expires' })).toBe(true) - now = 20000 - expect(claims.claim({ ...body, nonce: 'expires' })).toBe(false) - expect(cleanup).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts deleted file mode 100644 index a25b07c0164..00000000000 --- a/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdir } from 'node:fs/promises' -import { join } from 'node:path' - -const runProcessMock = vi.fn<(spec: Spec) => Promise>() -vi.mock('@orca/process-host', () => ({ - runProcess: (spec: Spec) => runProcessMock(spec) -})) -vi.mock('node:fs/promises', () => ({ - mkdir: vi.fn(async () => undefined), - chmod: vi.fn(async () => undefined), - readFile: vi.fn(async () => Buffer.from('')), - realpath: vi.fn(async (path: string) => path), - access: vi.fn(async () => undefined), - rm: vi.fn(async () => undefined), - writeFile: vi.fn(async () => undefined) -})) - -import { ExternalChromiumBrowserSession } from './external-chromium-browser-session' -import { agentBrowserCommandOf } from '../../../browser/agent-browser/testing/agent-browser-bridge-test-harness' - -const BASE = { - executablePath: '/opt/orca/chromium', - profilePath: '/state/browser-chromium', - sessionName: 'orca-orcad-0123456789abcdef' -} - -type Spec = { - args?: readonly string[] - input?: string - env?: NodeJS.ProcessEnv - signal?: AbortSignal -} - -function commandOf(spec: Spec): string[] { - return agentBrowserCommandOf(spec.args ?? [], spec.input) -} - -describe('orcad external-chromium agent-browser environment', () => { - beforeEach(() => { - runProcessMock.mockReset() - vi.mocked(mkdir).mockClear() - }) - - it('launches headless with only Orca agent-browser settings', async () => { - runProcessMock.mockResolvedValue({ - code: 0, - signal: null, - stdout: JSON.stringify([{ success: true, result: { url: 'about:blank' } }]), - stderr: '', - timedOut: false - }) - vi.stubEnv('AGENT_BROWSER_HEADED', '1') - vi.stubEnv('agent_browser_extensions', '/ext') - vi.stubEnv('AGENT_BROWSER_SOCKET_DIR', '/tmp/ab-sockets') - try { - await new ExternalChromiumBrowserSession( - '/opt/orca/agent-browser', - { executablePath: BASE.executablePath, provider: 'chromium' }, - '/state' - ).run(['get', 'url']) - } finally { - vi.unstubAllEnvs() - } - const [spec] = runProcessMock.mock.calls[0] - const headed = spec.args?.indexOf('--headed') ?? -1 - expect(spec.args?.slice(headed, headed + 2)).toEqual(['--headed', 'false']) - expect(spec.env).toMatchObject({ - AGENT_BROWSER_SOCKET_DIR: '/tmp/ab-sockets', - AGENT_BROWSER_CONFIG: join('/state', 'agent-browser-config.json') - }) - expect(spec.env).not.toHaveProperty('AGENT_BROWSER_HEADED') - expect(spec.env).not.toHaveProperty('agent_browser_extensions') - }) - - it('reports a ref whose element is gone as stale', async () => { - runProcessMock.mockResolvedValue({ - code: 1, - signal: null, - stdout: JSON.stringify({ - success: false, - error: - 'Stale ref for role=button name=Approve cannot be recovered: several elements now match.' - }), - stderr: '', - timedOut: false - }) - const session = new ExternalChromiumBrowserSession( - '/opt/orca/agent-browser', - { executablePath: BASE.executablePath, provider: 'chromium' }, - '/state' - ) - await expect(session.run(['click', '@e2'])).rejects.toMatchObject({ code: 'browser_stale_ref' }) - }) - - function startFailingOpen(error: string): Promise { - runProcessMock.mockImplementation((spec: Spec) => - Promise.resolve({ - code: 0, - signal: null, - stdout: JSON.stringify( - commandOf(spec)[0] === 'open' - ? { success: false, error } - : { success: true, data: { tabs: [] } } - ), - stderr: '', - timedOut: false - }) - ) - return new ExternalChromiumBrowserSession( - '/opt/orca/agent-browser', - { executablePath: BASE.executablePath, provider: 'chromium' }, - '/state' - ).start() - } - - it('names the unwritable profile instead of the driver sandbox hint', async () => { - const failure = startFailingOpen( - 'Chrome exited early (exit code: 21) without writing DevToolsActivePort\n' + - 'ERROR: Failed to create /state/browser-chromium/SingletonLock: Permission denied (13)\n' + - 'Failed to create a ProcessSingleton for your profile directory.\n' + - 'Hint: try --args "--no-sandbox"' - ) - await expect(failure).rejects.toMatchObject({ - code: 'browser_unavailable', - message: expect.stringContaining(join('/state', 'browser-chromium')) - }) - await expect(failure).rejects.toMatchObject({ - message: expect.stringContaining('SingletonLock: Permission denied (13)') - }) - await expect(failure).rejects.not.toMatchObject({ - message: expect.stringContaining('--no-sandbox') - }) - }) -}) diff --git a/src/main/orcad/browser-providers/orcad-browser-provider.test.ts b/src/main/orcad/browser-providers/orcad-browser-provider.test.ts deleted file mode 100644 index 7a503fd5ef6..00000000000 --- a/src/main/orcad/browser-providers/orcad-browser-provider.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { runProcess, spawnProcess } from '@orca/process-host' -import { agentBrowserCommandOf } from '../../browser/agent-browser/testing/agent-browser-bridge-test-harness' -import { - resolveInstalledElectronExecutable, - resolveOrcadBrowserProvider -} from './orcad-browser-provider' -import { - runtimeBrowserUnavailableCause, - setRuntimeBrowserUnavailableCause -} from '../../runtime/browser/installation/runtime-browser-commands-factory' - -vi.mock('@orca/process-host', () => ({ - runProcess: vi.fn(), - spawnProcess: vi.fn() -})) - -type BrowserState = { - activeTabId: string - tabs: { active: boolean; tabId: string; title: string; url: string }[] -} - -const runProcessMock = vi.mocked(runProcess) -const spawnProcessMock = vi.mocked(spawnProcess) -let root: string -let screenshotPath: string -let browserState: BrowserState - -function success(data: unknown) { - return Promise.resolve({ - code: 0, - signal: null, - stdout: JSON.stringify({ success: true, data, error: null }), - stderr: '', - timedOut: false - }) -} - -function installAgentBrowserMock(): void { - runProcessMock.mockImplementation(async (spec) => { - const command = agentBrowserCommandOf(spec.args ?? [], spec.input) - if (command[0] === 'open') { - const active = browserState.tabs.find((tab) => tab.tabId === browserState.activeTabId)! - active.url = command[1] - active.title = command[1] === 'about:blank' ? '' : 'Fixture page' - return success({ url: active.url, title: active.title }) - } - if (command[0] === 'tab' && command.length === 1) { - return success({ - tabs: browserState.tabs.map((tab) => ({ - ...tab, - active: tab.tabId === browserState.activeTabId - })) - }) - } - if (command[0] === 'tab' && command.length === 2) { - browserState.activeTabId = command[1] - return success({ tabId: command[1] }) - } - if (command[0] === 'eval') { - return success({ result: 'Fixture page', origin: 'https://fixture.test/' }) - } - if (command[0] === 'screenshot') { - return success({ path: screenshotPath }) - } - if (command.join(' ') === 'snapshot -i --delta') { - return success({ snapshot: { kind: 'unchanged', revision: 2, baseRevision: 1 } }) - } - if (command[0] === 'close') { - return success({ closed: true }) - } - throw new Error(`Unexpected agent-browser command: ${command.join(' ')}`) - }) -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orcad-browser-provider-')) - screenshotPath = join(root, 'fixture.png') - await writeFile(screenshotPath, Buffer.from('fixture-image')) - browserState = { - activeTabId: 't1', - tabs: [{ active: true, tabId: 't1', title: '', url: 'about:blank' }] - } - runProcessMock.mockReset() - spawnProcessMock.mockReset() - installAgentBrowserMock() - setRuntimeBrowserUnavailableCause(null) -}) - -afterEach(async () => { - await rm(root, { recursive: true, force: true }) -}) - -describe.skipIf(process.platform === 'win32')('resolveInstalledElectronExecutable', () => { - async function writeExecutable(path: string, content: Buffer | string): Promise { - await mkdir(join(path, '..'), { recursive: true }) - await writeFile(path, content) - await chmod(path, 0o755) - } - - it('rejects a symlink to the bash CLI shim and picks the install-dir binary', async () => { - const shim = join(root, 'share', 'orca-ide-shim') - const link = join(root, 'bin', 'orca-ide') - const electron = join(root, 'opt', 'Orca', 'orca-ide') - await writeExecutable(shim, '#!/usr/bin/env bash\nexec true\n') - await mkdir(join(link, '..'), { recursive: true }) - await symlink(shim, link) - await writeExecutable(electron, Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0])) - - await expect(resolveInstalledElectronExecutable([link, electron])).resolves.toBe(electron) - await expect(resolveInstalledElectronExecutable([link])).resolves.toBeNull() - }) -}) - -describe('resolveOrcadBrowserProvider', () => { - it('reports an ORCA_BROWSER_EXECUTABLE path that does not exist', async () => { - const missing = join(root, 'absent-chromium') - - await expect( - resolveOrcadBrowserProvider({ - userDataPath: root, - environment: { ORCA_BROWSER_EXECUTABLE: missing }, - resolveInstalledElectronExecutable: async () => null, - resolveAgentBrowserBinary: () => '/agent-browser' - }) - ).resolves.toBeNull() - expect(runtimeBrowserUnavailableCause()).toEqual({ - reason: 'executable_not_found', - detail: missing - }) - }) - - it.skipIf(process.platform === 'win32')( - 'separates a non-executable ORCA_BROWSER_EXECUTABLE from a missing one', - async () => { - const executable = join(root, 'unchmodded-chromium') - await writeFile(executable, '') - await chmod(executable, 0o644) - - await expect( - resolveOrcadBrowserProvider({ - userDataPath: root, - environment: { ORCA_BROWSER_EXECUTABLE: executable }, - resolveInstalledElectronExecutable: async () => null, - resolveAgentBrowserBinary: () => '/agent-browser' - }) - ).resolves.toBeNull() - expect(runtimeBrowserUnavailableCause()).toEqual({ - reason: 'executable_not_executable', - detail: executable - }) - } - ) -}) diff --git a/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts deleted file mode 100644 index f5e68538977..00000000000 --- a/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { - activationFenceExists, - createOrcadIdleProbes, - type OrcadManagedIdleExitPorts -} from './orcad-managed-idle-exit' - -const config = { timeoutMs: 1_000, activationRoot: '/home/u/.orca-remote/.fence' } - -function idlePorts(): OrcadManagedIdleExitPorts { - return { - readClientActivity: () => ({ openConnections: 0, requestsInFlight: 0, lastRequestAt: 0 }), - listTerminals: async () => [], - countDaemonSessions: async () => 0, - hasDaemon: () => true, - agentStates: () => [{ state: 'done' }], - hasChatProviders: () => false, - hasStagedMigration: () => false, - automationsBusy: () => false, - emulatorsBusy: async () => false, - activationFenceExists: async () => false - } -} - -async function verdicts(ports: OrcadManagedIdleExitPorts): Promise> { - const entries = await Promise.all( - createOrcadIdleProbes(config, ports).map(async (probe) => [probe.name, await probe.read()]) - ) - return Object.fromEntries(entries) -} - -describe('createOrcadIdleProbes', () => { - it('treats a daemon that did not answer as unverifiable, not as no terminals', async () => { - const result = await verdicts({ ...idlePorts(), countDaemonSessions: async () => null }) - expect(result.terminals).toBe('unverifiable') - }) - - it('needs only the provider census when this orcad runs without a daemon', async () => { - const result = await verdicts({ - ...idlePorts(), - hasDaemon: () => false, - countDaemonSessions: async () => null - }) - expect(result.terminals).toBe('idle') - }) -}) - -describe('activationFenceExists', () => { - let root: string | null = null - afterEach(() => { - if (root) { - rmSync(root, { recursive: true, force: true }) - } - }) - - it('follows the lock a client holds during an update, not a root an aborted acquire left', async () => { - root = mkdtempSync(join(tmpdir(), 'orcad-fence-')) - const fence = join(root, '.orcad-activation-transaction') - expect(await activationFenceExists(fence)).toBe(false) - mkdirSync(fence) - expect(await activationFenceExists(fence)).toBe(false) - mkdirSync(join(fence, '.install-lock')) - expect(await activationFenceExists(fence)).toBe(true) - }) -}) diff --git a/src/main/plugins/development/plugin-dev-revision.test.ts b/src/main/plugins/development/plugin-dev-revision.test.ts deleted file mode 100644 index 830a24028ad..00000000000 --- a/src/main/plugins/development/plugin-dev-revision.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { PluginDevWatcher } from './plugin-dev-watcher' -import { - bumpPluginDevRevision, - pluginDevChangeCount, - pluginDevRevision -} from './plugin-dev-revision' -import type { subscribeViaWatcherProcess } from '../../ipc/filesystem/watcher-process/parcel-watcher-process' - -type Callback = Parameters[1] - -describe('plugin dev revision', () => { - it('counts per root, under any spelling of the path', () => { - const root = join(tmpdir(), 'orca-dev-revision-a') - const before = pluginDevRevision(root) - expect(before).toMatch(/^dev-[0-9a-f]{8}-\d+$/) - bumpPluginDevRevision(`${root}/./`) - expect(pluginDevRevision(root)).not.toBe(before) - expect(pluginDevRevision(join(tmpdir(), 'orca-dev-revision-b'))).toMatch(/-0$/) - }) - - it('is bumped by the dev watcher for each change it reports under the root', async () => { - const root = mkdtempSync(join(tmpdir(), 'orca-dev-revision-watch-')) - const callbacks = new Map() - const subscribe = vi.fn(async (path: string, callback: Callback) => { - callbacks.set(path, callback) - return { unsubscribe: async () => {} } - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the watcher uses only the callback and unsubscribe of what the fake returns. - const watcher = new PluginDevWatcher(subscribe as never) - watcher.start([root], () => {}) - await vi.waitFor(() => expect(callbacks.has(root)).toBe(true)) - const subscribed = pluginDevRevision(root) - callbacks.get(root)?.(null, [{ type: 'update', path: join(root, 'panel.js') }]) - expect(pluginDevRevision(root)).not.toBe(subscribed) - watcher.dispose() - }) - - it('counts changed files from watcher events but not setup catch-ups', async () => { - const root = mkdtempSync(join(tmpdir(), 'orca-dev-change-count-')) - const callbacks = new Map() - const subscribe = vi.fn(async (path: string, callback: Callback) => { - callbacks.set(path, callback) - return { unsubscribe: async () => {} } - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the watcher uses only the callback and unsubscribe of what the fake returns. - const watcher = new PluginDevWatcher(subscribe as never) - watcher.start([root], () => {}) - await vi.waitFor(() => expect(callbacks.has(root)).toBe(true)) - expect(pluginDevChangeCount(root)).toBe(0) - callbacks.get(root)?.(null, [ - { type: 'update', path: join(root, 'panel.tsx') }, - { type: 'update', path: join(root, 'panel.tsx') }, - { type: 'create', path: join(root, 'style.css') } - ]) - expect(pluginDevChangeCount(root)).toBe(2) - watcher.dispose() - }) -}) diff --git a/src/main/plugins/installation/plugin-atomic-file-write.test.ts b/src/main/plugins/installation/plugin-atomic-file-write.test.ts deleted file mode 100644 index 515afc6fc02..00000000000 --- a/src/main/plugins/installation/plugin-atomic-file-write.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as FsPromises from 'node:fs/promises' -import { writePluginFileAtomically } from './plugin-atomic-file-write' - -// Windows AV/indexer locks cannot be provoked on CI, so queue the errno codes instead. -const locks = vi.hoisted(() => ({ codes: [] as string[] })) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - rename: async (source: string, target: string) => { - const code = locks.codes.shift() - if (!code) { - return actual.rename(source, target) - } - throw Object.assign(new Error(`simulated ${code}`), { code }) - } - } -}) - -function withPlatform(platform: string): () => void { - const original = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) - return () => { - if (original) { - Object.defineProperty(process, 'platform', original) - } - } -} - -describe('writePluginFileAtomically', () => { - let dir: string - - beforeEach(async () => { - dir = await mkdtemp(join(tmpdir(), 'orca-plugin-atomic-')) - }) - - afterEach(async () => { - await rm(dir, { recursive: true, force: true }) - }) - - it('applies the requested mode', async () => { - const target = join(dir, 'provenance.json') - await writePluginFileAtomically(target, '{}', { mode: 0o600 }) - const mode = (await stat(target)).mode & 0o777 - // Windows does not model POSIX permission bits. - if (process.platform !== 'win32') { - expect(mode).toBe(0o600) - } - }) - - it('cleans up the temp file when the rename gives up', async () => { - const restorePlatform = withPlatform('win32') - locks.codes = Array.from({ length: 6 }, () => 'EPERM') - try { - await expect(writePluginFileAtomically(join(dir, 'current'), 'v')).rejects.toMatchObject({ - code: 'EPERM' - }) - expect(await readdir(dir)).toEqual([]) - } finally { - restorePlatform() - locks.codes = [] - } - }) - - it('runs concurrent writers to one target without leaking temp files', async () => { - const target = join(dir, 'sources.json') - await Promise.all( - Array.from({ length: 8 }, (_unused, index) => - writePluginFileAtomically(target, `value-${index}`) - ) - ) - expect(await readdir(dir)).toEqual(['sources.json']) - expect(await readFile(target, 'utf8')).toMatch(/^value-\d$/) - }) -}) diff --git a/src/main/plugins/media/plugin-image-cache.test.ts b/src/main/plugins/media/plugin-image-cache.test.ts deleted file mode 100644 index 4f2d5f2e3e7..00000000000 --- a/src/main/plugins/media/plugin-image-cache.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { createHash } from 'node:crypto' -import * as fs from 'node:fs/promises' -import { mkdtemp, readdir, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { PluginImageCache } from './plugin-image-cache' - -const renameHook = vi.hoisted((): { before: null | (() => Promise) } => ({ before: null })) -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - rename: async (from: string, to: string) => { - await renameHook.before?.() - return actual.rename(from, to) - } - } -}) - -const be32 = (n: number) => [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255] -function png(width: number, height: number): Buffer { - const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] - const ihdr = [0, 0, 0, 13, ...Buffer.from('IHDR'), ...be32(width), ...be32(height), 8, 6, 0, 0, 0] - return Buffer.from([...signature, ...ihdr, 0, 0, 0, 0]) -} -const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex') - -const roots: string[] = [] -async function temp(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-plugin-image-cache-')) - roots.push(root) - return root -} - -afterEach(async () => { - renameHook.before = null - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('PluginImageCache.put', () => { - it('lets concurrent saves of the same image all succeed', async () => { - const dir = await temp() - const cache = new PluginImageCache(dir) - const bytes = png(4, 4) - const results = await Promise.all(Array.from({ length: 8 }, () => cache.put(bytes))) - expect(results).toEqual(Array.from({ length: 8 }, () => sha(bytes))) - expect(await readdir(dir)).toEqual([sha(bytes)]) - expect((await cache.get(sha(bytes)))?.bytes.equals(bytes)).toBe(true) - }) - - it('treats a rename failure as success when another writer already produced the file', async () => { - const dir = await temp() - const cache = new PluginImageCache(dir) - const bytes = png(2, 2) - renameHook.before = async () => { - renameHook.before = null - await fs.writeFile(join(dir, sha(bytes)), bytes) - throw Object.assign(new Error('rename failed'), { code: 'EPERM' }) - } - await expect(cache.put(bytes)).resolves.toBe(sha(bytes)) - expect(await readdir(dir)).toEqual([sha(bytes)]) - }) - - it('still rejects when the rename fails and no valid file exists', async () => { - const dir = await temp() - const cache = new PluginImageCache(dir) - renameHook.before = async () => { - throw Object.assign(new Error('rename failed'), { code: 'ENOENT' }) - } - await expect(cache.put(png(2, 2))).rejects.toThrow('rename failed') - expect(await readdir(dir)).toEqual([]) - }) -}) diff --git a/src/main/plugins/panels/guest-isolation/plugin-frame-request-policy.test.ts b/src/main/plugins/panels/guest-isolation/plugin-frame-request-policy.test.ts deleted file mode 100644 index ae1f6748ba8..00000000000 --- a/src/main/plugins/panels/guest-isolation/plugin-frame-request-policy.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { pluginFrameKey } from '../../../../shared/plugins/frames/plugin-frame-guest' -import { - isAllowedPluginFrameNavigation, - isAllowedPluginFrameRequestUrl, - pluginFrameAttachKey -} from './plugin-frame-request-policy' - -const KEY = pluginFrameKey('acme.charts') -const OTHER = pluginFrameKey('acme.other') - -describe('plugin frame session request policy', () => { - it.each([ - [`orca-plugin-frame://${KEY}/panel.html`, true], - [`orca-plugin-frame://${KEY}/lib/app.wasm`, true], - ['data:text/plain,hi', true], - [`blob:orca-plugin-frame://${KEY}/0b1c`, true], - ['devtools://devtools/bundled/inspector.html', true], - [`orca-plugin-frame://${OTHER}/panel.html`, false], - [`orca-plugin-frame://${KEY}`, false], - ['http://127.0.0.1:8080/', false], - ['https://example.com/beacon.gif', false], - ['ws://127.0.0.1:9/', false], - ['file:///etc/passwd', false], - ['orca-plugin-image://sha/abc', false] - ])('%s → %s', (url, allowed) => { - expect(isAllowedPluginFrameRequestUrl(url, KEY)).toBe(allowed) - }) - - it('keeps top-level navigation on the plugin origin and lets subframes be inert', () => { - expect(isAllowedPluginFrameNavigation(`orca-plugin-frame://${KEY}/b.html`, KEY, true)).toBe( - true - ) - expect(isAllowedPluginFrameNavigation(`orca-plugin-frame://${OTHER}/b.html`, KEY, true)).toBe( - false - ) - expect(isAllowedPluginFrameNavigation('https://example.com/', KEY, true)).toBe(false) - expect(isAllowedPluginFrameNavigation('about:blank', KEY, true)).toBe(false) - expect(isAllowedPluginFrameNavigation(`blob:orca-plugin-frame://${KEY}/x`, KEY, true)).toBe( - false - ) - expect(isAllowedPluginFrameNavigation('data:text/html,x', KEY, false)).toBe(false) - expect(isAllowedPluginFrameNavigation('about:srcdoc', KEY, false)).toBe(true) - }) - - it('admits a webview only when its partition key is the key of its origin', () => { - expect(pluginFrameAttachKey(KEY, `orca-plugin-frame://${KEY}/panel.html`)).toBe(KEY) - expect(pluginFrameAttachKey(KEY, `orca-plugin-frame://${OTHER}/panel.html`)).toBeNull() - expect(pluginFrameAttachKey(KEY, 'https://example.com/')).toBeNull() - expect(pluginFrameAttachKey(null, `orca-plugin-frame://${KEY}/panel.html`)).toBeNull() - }) -}) diff --git a/src/main/power/awake-clock.test.ts b/src/main/power/awake-clock.test.ts deleted file mode 100644 index a219521c127..00000000000 --- a/src/main/power/awake-clock.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { AWAKE_CLOCK_HEARTBEAT_MS, createAwakeClock } from './awake-clock' - -type CounterModel = 'counts sleep (macOS/Windows Node)' | 'stops in sleep (Linux)' - -/** Wall and monotonic clocks the test moves. Awake time fires the heartbeat (an overdue beat fires - * on wake); sleep fires nothing, and advances the monotonic counter only where that runtime's - * counter counts sleep. */ -function testClocks(model: CounterModel) { - const time = { wall: 1_794_244_112_215, monotonic: 0 } - let pending: (() => void) | null = null - let beatOverdue = false - const beat = (): void => { - const due = pending - pending = null - due?.() - } - return { - time, - sources: { - wallNow: () => time.wall, - monotonicNow: () => time.monotonic, - after: (onBeat: () => void) => { - pending = onBeat - } - }, - awake(ms: number) { - if (beatOverdue) { - beatOverdue = false - beat() - } - for (let left = ms; left > 0; left -= AWAKE_CLOCK_HEARTBEAT_MS) { - const step = Math.min(left, AWAKE_CLOCK_HEARTBEAT_MS) - time.wall += step - time.monotonic += step - if (step === AWAKE_CLOCK_HEARTBEAT_MS) { - beat() - } - } - }, - asleep(ms: number) { - beatOverdue = true - time.wall += ms - if (model === 'counts sleep (macOS/Windows Node)') { - time.monotonic += ms - } - } - } -} - -const MODELS: CounterModel[] = ['counts sleep (macOS/Windows Node)', 'stops in sleep (Linux)'] -const SETTLE = 120_000 - -describe.each(MODELS)('awake clock on a monotonic counter that %s', (model) => { - it('does not count the time between suspend and resume', () => { - const clocks = testClocks(model) - const clock = createAwakeClock(clocks.sources) - const start = clock.now() - clocks.awake(2_000) - clock.suspend() - clocks.asleep(665_000) - // A timer that fires on wake before the resume event is delivered still reads the frozen clock. - expect(clock.now() - start).toBe(2_000) - clock.resume() - clocks.awake(3_000) - expect(clock.now() - start).toBe(5_000) - }) - - it('does not count a sleep that no power event reported', () => { - const clocks = testClocks(model) - const clock = createAwakeClock(clocks.sources) - const start = clock.now() - clocks.awake(AWAKE_CLOCK_HEARTBEAT_MS) - clocks.asleep(600_000) - clocks.awake(2_000) - expect(clock.now() - start).toBe(AWAKE_CLOCK_HEARTBEAT_MS + 2_000) - }) - - it('resumes by itself once the process has run for minutes after a lost resume event', () => { - const clocks = testClocks(model) - const clock = createAwakeClock(clocks.sources) - clock.suspend() - clocks.asleep(600_000) - const frozen = clock.now() - clocks.awake(100_000) - expect(clock.now()).toBe(frozen) - expect(clock.settled(SETTLE)).toBe(false) - clocks.awake(20_000) - // The two minutes it ran count as awake; the sleep before them does not. - expect(clock.now()).toBe(frozen + 120_000) - expect(clock.settled(SETTLE)).toBe(true) - }) -}) - -describe.each(MODELS)('awake clock settling on a monotonic counter that %s', (model) => { - it('settles on schedule when the wall clock is corrected backward after a resume', () => { - const clocks = testClocks(model) - const clock = createAwakeClock(clocks.sources) - clock.suspend() - clocks.asleep(600_000) - clock.resume() - clocks.awake(30_000) - clocks.time.wall -= 60 * 60_000 - clocks.awake(80_000) - expect(clock.settled(SETTLE)).toBe(false) - clocks.awake(10_000) - expect(clock.settled(SETTLE)).toBe(true) - }) -}) diff --git a/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts b/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts deleted file mode 100644 index 13cc2c88d63..00000000000 --- a/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { RemoteLayoutSnapshot } from '../../shared/remote-layout-snapshot' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' - -import { - recordRemoteLayoutFrame, - type RemoteLayoutSnapshotStore -} from './remote-layout-snapshot-recorder' - -const METHOD = 'session.tabs.subscribeAll' - -function memoryStore() { - const snapshots = new Map() - const saves: ('now' | 'later')[] = [] - const store: RemoteLayoutSnapshotStore = { - getRemoteLayoutSnapshotWorkspace: (environmentId, worktreeId) => - snapshots.get(environmentId)?.workspaces[worktreeId], - setRemoteLayoutSnapshotWorkspace: (environmentId, worktreeId, workspace, save) => { - saves.push(save) - const snapshot = snapshots.get(environmentId) ?? { workspaces: {} } - if (workspace) { - snapshot.workspaces[worktreeId] = workspace - } else { - delete snapshot.workspaces[worktreeId] - } - snapshots.set(environmentId, snapshot) - }, - setRemoteLayoutSnapshot: (environmentId, snapshot, save) => { - saves.push(save) - if (snapshot) { - snapshots.set(environmentId, snapshot) - } else { - snapshots.delete(environmentId) - } - } - } - return { store, snapshots, saves } -} - -function tabs(worktree: string, title = 'shell') { - return { - worktree, - publicationEpoch: 'epoch', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [{ type: 'terminal', id: `${worktree}-tab`, title }] - } -} - -function frame(result: unknown, runtimeId = 'server-1'): RuntimeRpcResponse { - return { id: 'stream', ok: true, result, _meta: { runtimeId } } -} - -function workspacesOf(snapshots: Map, environmentId = 'env') { - return snapshots.get(environmentId)?.workspaces -} - -describe('remote layout snapshot recorder', () => { - it('replaces the whole entry on each census, dropping worktrees it no longer lists', () => { - const { store, snapshots } = memoryStore() - recordRemoteLayoutFrame( - store, - 'env', - METHOD, - frame({ type: 'snapshots', snapshots: [tabs('a'), tabs('b')] }) - ) - recordRemoteLayoutFrame( - store, - 'env', - METHOD, - frame({ type: 'snapshots', snapshots: [tabs('b', 'renamed')] }, 'server-2') - ) - - expect(snapshots.get('env')).toEqual({ workspaces: { b: tabs('b', 'renamed') } }) - }) - - it('replaces one worktree on an update and drops it on a removal', () => { - const { store, snapshots } = memoryStore() - recordRemoteLayoutFrame( - store, - 'env', - METHOD, - frame({ type: 'snapshots', snapshots: [tabs('a'), tabs('b')] }) - ) - recordRemoteLayoutFrame(store, 'env', METHOD, frame({ type: 'updated', ...tabs('a', 'vim') })) - expect(workspacesOf(snapshots)).toEqual({ a: tabs('a', 'vim'), b: tabs('b') }) - - recordRemoteLayoutFrame( - store, - 'env', - METHOD, - frame({ type: 'updated', ...tabs('b'), tabs: [], removed: true }) - ) - expect(workspacesOf(snapshots)).toEqual({ a: tabs('a', 'vim') }) - }) - - it('keeps neither retirement proofs nor one-shot navigation', () => { - const { store, snapshots } = memoryStore() - const proof = { parentTabId: 'a-tab', leafId: 'leaf', ptyId: 'pty', terminal: 'term' } - recordRemoteLayoutFrame( - store, - 'env', - METHOD, - frame({ type: 'snapshots', snapshots: [{ ...tabs('a'), retiredTerminalSurfaces: [proof] }] }) - ) - expect(workspacesOf(snapshots)).toEqual({ a: tabs('a') }) - - // A capable client is sent only new proofs, so an update's list is a delta, here empty. - recordRemoteLayoutFrame( - store, - 'env', - METHOD, - frame({ - type: 'updated', - ...tabs('a', 'vim'), - retiredTerminalSurfaces: [], - navigationIntent: 'follow' - }) - ) - expect(workspacesOf(snapshots)).toEqual({ a: tabs('a', 'vim') }) - }) -}) diff --git a/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts b/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts deleted file mode 100644 index d88e0aa256b..00000000000 --- a/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HostAccountSignInChannel } from '../../../../shared/host-account-sign-in-types' -import { HostAccountSignInFlows, type HostAccountSignInRunner } from './host-account-sign-in-flows' - -const CLAUDE_STATE = { accounts: [], activeAccountId: null } - -function controllableRunner() { - let channel: HostAccountSignInChannel | null = null - const finish = Promise.withResolvers() - const run = vi.fn(async (_provider, received) => { - channel = received - received.signal.addEventListener('abort', () => - finish.reject(new Error('Claude sign-in was cancelled.')) - ) - await finish.promise - return { claude: CLAUDE_STATE } - }) - return { - run, - channel: () => { - if (!channel) { - throw new Error('runner not started') - } - return channel - }, - finish - } -} - -afterEach(() => { - vi.useRealTimers() -}) - -describe('HostAccountSignInFlows', () => { - it('keeps one client from reading, answering or cancelling another client’s sign-in', async () => { - const runner = controllableRunner() - const flows = new HostAccountSignInFlows(runner.run, 'linux') - const { flowId } = flows.start('device-a', 'claude') - expect(() => flows.start('device-b', 'codex')).toThrow('already running on this host') - await expect(flows.wait('device-b', flowId, 0)).rejects.toThrow('no longer active') - expect(() => flows.submitCode('device-b', flowId, 'x')).toThrow('no longer active') - await expect(flows.cancel('device-b', flowId)).rejects.toThrow('no longer active') - expect(flows.start('device-a', 'claude').flowId).toBe(flowId) - expect(runner.run).toHaveBeenCalledOnce() - await flows.cancel('device-a', flowId) - }) - - it('cancels the login and reports cancelled, not the login’s own failure', async () => { - const runner = controllableRunner() - const flows = new HostAccountSignInFlows(runner.run, 'linux') - const { flowId } = flows.start('device-a', 'claude') - expect(runner.run).toHaveBeenCalledOnce() - expect((await flows.cancel('device-a', flowId)).phase).toBe('cancelled') - expect(runner.channel().signal.aborted).toBe(true) - await expect(runner.channel().nextCode()).rejects.toThrow() - expect(flows.start('device-a', 'codex').phase).toBe('starting') - expect((await flows.wait('device-a', flowId, 0).catch((error) => error)).message).toMatch( - 'no longer active' - ) - }) - - it('reports the account a login added after it refused a late cancel', async () => { - const flows = new HostAccountSignInFlows(async (_provider, channel) => { - // Once Codex commits login, cancel can be refused and registration still completes. - await new Promise((resolve) => channel.signal.addEventListener('abort', resolve)) - return { claude: CLAUDE_STATE } - }, 'linux') - const { flowId } = flows.start('device-a', 'codex') - expect(await flows.cancel('device-a', flowId)).toMatchObject({ - phase: 'signedIn', - claude: CLAUDE_STATE - }) - }) - - it('ends a sign-in whose client stopped asking about it', async () => { - vi.useFakeTimers() - const runner = controllableRunner() - const flows = new HostAccountSignInFlows(runner.run, 'linux') - const { flowId } = flows.start('device-a', 'claude') - await vi.advanceTimersByTimeAsync(91_000) - expect(runner.channel().signal.aborted).toBe(true) - const status = await flows.wait('device-a', flowId, 0) - expect(status).toMatchObject({ phase: 'failed', error: expect.stringContaining('stopped') }) - }) -}) diff --git a/src/main/runtime/browser/client-pages/client-page-recovery-cancellation.test.ts b/src/main/runtime/browser/client-pages/client-page-recovery-cancellation.test.ts deleted file mode 100644 index 27b7e5c6a17..00000000000 --- a/src/main/runtime/browser/client-pages/client-page-recovery-cancellation.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { BrowserHostCommandLedger } from '../../browser-host/commands/browser-host-command-ledger' -import { expect, it, vi } from 'vitest' -import { createRecoveryLoop } from './client-page-recovery-loop-test-harness' -import { retireRuntimeBrowserClientPage } from './browser-client-page-close' - -it.each(['create', 'gap', 'navigate', 'publication'])( - 'logical close during %s retires the exact initialization without a late saved row', - async (phase) => { - const h = createRecoveryLoop(['slow', 'fast']) - const closed = Promise.withResolvers() - const close = () => { - const page = h.pages.getPage('slow') - if (!page) { - return - } - void retireRuntimeBrowserClientPage( - { - getBrowserHostLeaseRegistry: () => h.authority, - notifyHeadlessBrowserSessionTabsChanged: (id) => - h.hostRuntime.notifyMobileSessionTabsChanged(id), - getRuntimeBrowserPageRegistry: () => h.pages, - resolveBrowserWorkspace: async () => ({ id: 'workspace' }) - }, - page - ).then(() => closed.resolve(), closed.reject) - } - if (phase === 'gap') { - h.hooks.onResult = (event) => { - if (event.browserPageId === 'slow' && event.command.type === 'createPage') { - close() - } - } - } - if (phase === 'publication') { - h.hooks.onNotify = () => { - if (h.pages.getPage('slow')?.placement.pageHostGeneration) { - close() - } - } - } - try { - const mount = phase === 'create' ? h.holdMount('slow') : undefined - const navigating = phase === 'navigate' ? h.hold('slow') : undefined - const attached = h.attach() - if (mount) { - await mount.started - close() - mount.release() - } - if (navigating) { - await navigating - close() - } - await closed.promise - await h.published('fast') - await vi.waitFor(() => - expect(h.executor.snapshotPageInventory().map((page) => page.browserPageId)).toEqual([ - 'fast' - ]) - ) - expect(h.pages.getPage('slow')).toBeUndefined() - expect(h.authority.getPlacement('slow')).toBeUndefined() - expect(h.authority.getClientPageExecutionHostKey('slow')).toBeUndefined() - expect(h.authority.getClientPageExecutionHostKey('fast')).toBe('execution-host-a') - expect( - h.profile.session.clientHostedBrowserPagesByWorktree?.['repo-1::/tmp/worktree-a']?.map( - (page) => page.browserPageId - ) - ).toEqual(['fast']) - expect(h.results.findLast((result) => result.id === 'slow')).toMatchObject({ - type: 'closePage', - status: 'completed' - }) - attached.abort() - await attached.completion - } finally { - await h.close() - } - } -) - -it.each([false, true])( - 'a transport exception after delivery=%s retains exact uncertainty until fresh inventory', - async (received) => { - const h = createRecoveryLoop(['slow']) - const attempted = Promise.withResolvers() - h.hooks.delivery = (event, dispatch) => { - if (event.command.type === 'createPage') { - if (received) { - dispatch() - } - attempted.resolve() - throw new Error('transport-lost') - } - dispatch() - } - try { - const first = h.attach() - await attempted.promise - await first.completion - expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow') - expect(h.authority.getClientPageExecutionHostKey('slow')).toBeUndefined() - h.hooks.delivery = undefined - const next = h.attach() - await h.published('slow') - expect(h.executor.snapshotPageInventory()).toHaveLength(1) - expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow') - expect(h.authority.getClientPageExecutionHostKey('slow')).toBe('execution-host-a') - next.abort() - await next.completion - } finally { - await h.close() - } - } -) - -it('a real ledger rejection before admission creates no native cleanup obligation', async () => { - const h = createRecoveryLoop(['slow']) - const rejected = Promise.withResolvers() - const issue = BrowserHostCommandLedger.prototype.issue - let admissions = 0 - let rejectFirst = true - const observed = vi - .spyOn(BrowserHostCommandLedger.prototype, 'issue') - .mockImplementation(function (this: BrowserHostCommandLedger, input, onAdmitted) { - if (rejectFirst && input.command.type === 'createPage') { - rejectFirst = false - this.detachDelivery() - try { - return issue.call(this, input, () => { - admissions += 1 - onAdmitted?.() - }) - } catch (error) { - rejected.resolve() - throw error - } - } - return issue.call(this, input, onAdmitted) - }) - try { - const first = h.attach() - await rejected.promise - expect(admissions).toBe(0) - expect(h.commands).toEqual([]) - expect(h.executor.snapshotPageInventory()).toEqual([]) - expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow') - first.abort() - await first.completion - const next = h.attach() - await h.published('slow') - expect(h.commands.filter((event) => event.command.type === 'closePage')).toEqual([]) - expect(h.authority.getClientPageExecutionHostKey('slow')).toBe('execution-host-a') - expect(h.executor.snapshotPageInventory()).toHaveLength(1) - next.abort() - await next.completion - } finally { - observed.mockRestore() - await h.close() - } -}) diff --git a/src/main/runtime/browser/client-pages/client-page-recovery-partition-preparation.test.ts b/src/main/runtime/browser/client-pages/client-page-recovery-partition-preparation.test.ts deleted file mode 100644 index e48ea37bb7a..00000000000 --- a/src/main/runtime/browser/client-pages/client-page-recovery-partition-preparation.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { retireRuntimeBrowserClientPage } from './browser-client-page-close' -import { createRecoveryLoop } from './client-page-recovery-loop-test-harness' -import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' - -const WORKSPACE = 'repo-1::/tmp/worktree-a' -const IDS = ['slow', 'fast', 'third', 'fourth', 'fifth', 'sixth'] - -it('joins all six exact predecessors before retargeting their partition, without holding fast pages behind slow navigation', async () => { - const h = createRecoveryLoop(IDS) - const key = browserNetworkExecutionHostKey({ - kind: 'native', - runtimeId: 'runtime-a', - revision: 1 - }) - h.native.dependencies.retainNetworkRoute.mockImplementation(async (requested) => ({ - ...h.native.route, - key: requested - })) - h.hostRuntime.resolveBrowserExecutionHostKeyForWorkspace = async () => ({ - status: 'resolved', - executionHostKey: key - }) - try { - await h.seedNative(IDS) - const predecessor = h.executor.snapshotPageInventory() - const cleanup = h.holdRetirement('sixth') - const started = h.hold('slow') - h.native.dependencies.routeSessions.preparePage.mockImplementation(async () => { - // A shared-session proxy may change only after every old page's native join. - expect( - h.executor.snapshotPageInventory().filter((p) => p.authorityRuntimeId === 'runtime-old') - ).toEqual([]) - return h.native.routeSession - }) - h.attach() - await cleanup.started - const lease = h.authority.select('client-a') - const ordinary = h.authority.createClientPage({ - browserPageId: 'ordinary', - browserHostClientId: 'client-a', - pairedDeviceId: 'device-a', - browserProfileId: 'profile-a', - executionHostKey: key, - workspaceId: WORKSPACE - }) - expect( - h.hostRuntime - .snapshotForClient(WORKSPACE, 'device-a') - .tabs.filter((t) => t.type === 'browser') - .map((t) => t.initializationState) - ).toEqual(['pending', 'pending', 'pending', 'pending', 'pending', 'pending']) - // No replacement may be visible while one native predecessor has not joined. - expect(h.commands.some((c) => c.command.type === 'createPage')).toBe(false) - cleanup.release() - await started - await Promise.all(IDS.slice(1).map((id) => h.published(id))) - await ordinary - expect(h.results.filter((r) => r.type === 'closePage' && IDS.includes(r.id))).toEqual( - expect.arrayContaining(IDS.map((id) => ({ type: 'closePage', id, status: 'completed' }))) - ) - expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow') - expect(h.pages.getPage('slow')?.placement.pageHostGeneration).toBe(0) - expect( - h.authority.clientPageInitializations.status('slow', h.pages.getPage('slow')!.placement) - ).toBe('pending') - h.release('slow', 'https://example.internal/redirected') - await h.published('slow') - expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/redirected') - expect( - h.authority.clientPageInitializations.status('slow', h.pages.getPage('slow')!.placement) - ).toBeUndefined() - expect( - h.executor - .snapshotPageInventory() - .filter((p) => IDS.includes(p.browserPageId)) - .every((p) => p.state === 'active') - ).toBe(true) - expect( - h.executor - .snapshotPageInventory() - .some((p) => predecessor.some((old) => old.authorityRuntimeId === p.authorityRuntimeId)) - ).toBe(false) - expect(h.errors).toEqual([]) - h.authority.requireLease(lease) - } finally { - await h.close() - } -}) - -it('lets another profile create while an exact predecessor join is held', async () => { - const h = createRecoveryLoop(['slow']) - try { - await h.seedNative(['slow']) - const cleanup = h.holdRetirement('slow') - h.attach() - await cleanup.started - const independent = await h.authority.createClientPage({ - browserPageId: 'independent', - browserHostClientId: 'client-a', - pairedDeviceId: 'device-a', - browserProfileId: 'profile-b', - executionHostKey: 'execution-host-a', - workspaceId: WORKSPACE - }) - expect(independent.pageHostGeneration).toBeGreaterThan(0) - expect( - h.executor - .snapshotPageInventory() - .map((p) => p.browserPageId) - .sort() - ).toEqual(['independent', 'slow']) - expect( - h.commands.some((c) => c.browserPageId === 'slow' && c.command.type === 'createPage') - ).toBe(false) - cleanup.release() - await h.published('slow') - expect(h.errors).toEqual([]) - } finally { - await h.close() - } -}) - -it('keeps a closed queued cohort member in exact cleanup and resumes the surviving cohort on successor attach', async () => { - const h = createRecoveryLoop(IDS) - try { - await h.seedNative(IDS) - const held = IDS.slice(0, 4).map((id) => h.holdRetirement(id)) - const first = h.attach() - await Promise.all(held.map((h) => h.started)) - const closed = h.pages.getPage('sixth')! - await retireRuntimeBrowserClientPage( - { - getBrowserHostLeaseRegistry: () => h.authority, - getRuntimeBrowserPageRegistry: () => h.pages, - resolveBrowserWorkspace: async () => ({ id: WORKSPACE }), - notifyHeadlessBrowserSessionTabsChanged: (id) => - h.hostRuntime.notifyMobileSessionTabsChanged(id) - }, - closed - ) - expect(h.pages.getPage('sixth')).toBeUndefined() - expect(h.executor.snapshotPageInventory().some((p) => p.browserPageId === 'sixth')).toBe(true) - const next = h.attach() - first.abort() - await first.completion - for (const cleanup of held) { - cleanup.release() - } - await Promise.all(IDS.slice(0, 5).map((id) => h.published(id))) - await vi.waitFor(() => - expect( - h.executor - .snapshotPageInventory() - .map((p) => p.browserPageId) - .sort() - ).toEqual(['fast', 'fifth', 'fourth', 'slow', 'third']) - ) - expect( - h.results.some((r) => r.id === 'sixth' && r.type === 'closePage' && r.status === 'completed') - ).toBe(true) - expect( - h.commands.some((c) => c.browserPageId === 'sixth' && c.command.type === 'createPage') - ).toBe(false) - next.abort() - await next.completion - } finally { - await h.close() - } -}) diff --git a/src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts b/src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts deleted file mode 100644 index 77b534bcec8..00000000000 --- a/src/main/runtime/integrations/reviews/hosted-pr-selected-demand.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { found, mocks, read, rpcRead } from './runtime-hosted-pr-snapshot-test-harness' -import { PrForBranch } from '../../../../shared/rpc-contract/github/github-pull-request-params' - -it('keeps selected preference optional for old snapshot request parsers', () => { - const params = { repo: 'repo', branch: 'main', reason: 'swr', selected: true } - expect(PrForBranch.parse(params)).toMatchObject({ selected: true }) - expect(PrForBranch.omit({ selected: true }).parse(params)).toEqual({ - repo: 'repo', - branch: 'main', - reason: 'swr' - }) - expect(PrForBranch.parse({ repo: 'repo', branch: 'main' })).toEqual({ - repo: 'repo', - branch: 'main' - }) -}) - -it('keeps a selected join during an awaited quota probe and its later paused admission', async () => { - await read('quiet-selected', 'active') - await vi.advanceTimersByTimeAsync(60_000) - const confirmation = read('quiet-selected') - await vi.advanceTimersByTimeAsync(0) - await confirmation - const branches = ['ordinary-a', 'ordinary-b', 'ordinary-c'] - await Promise.all(branches.map((branch) => read(branch, 'active'))) - await vi.advanceTimersByTimeAsync(300_000) - const quotaProbe = Promise.withResolvers() - // ast-grep-ignore: test-no-wall-clock -- The imported runtime fixture installs the fake clock. - const resetAt = Date.now() + 60_000 - mocks.gate.mockResolvedValue(resetAt).mockReturnValueOnce(quotaProbe.promise) - const starts: string[] = [] - mocks.resolve.mockImplementation(async ({ branchName }) => { - starts.push(branchName) - return found() - }) - const demand = (branch: string, selected = false) => - rpcRead({ - repo: 'repo', - branch, - currentHeadOid: 'head-a', - reason: 'swr', - acceptRevalidationOnly: true, - selected - }) - const first = demand('quiet-selected') - await vi.advanceTimersByTimeAsync(0) - expect(mocks.gate).toHaveBeenCalled() - expect(starts).toEqual([]) - const joined = demand('quiet-selected', true) - const ordinary = branches.map((branch) => demand(branch)) - await vi.advanceTimersByTimeAsync(0) - quotaProbe.resolve(resetAt) - await vi.advanceTimersByTimeAsync(25_000) - await Promise.all([first, joined, ...ordinary]) - mocks.gate.mockResolvedValue(null) - await vi.advanceTimersByTimeAsync(65_000) - expect(starts).toEqual(['quiet-selected', 'ordinary-a', 'ordinary-b', 'ordinary-c']) -}) - -it('uses selected demand only for admission priority, preserving the shared retry interval', async () => { - await read('retry-policy', 'active') - await vi.advanceTimersByTimeAsync(60_000) - mocks.resolve.mockRejectedValueOnce(new Error('offline')) - // ast-grep-ignore: test-no-wall-clock -- The imported runtime fixture installs the fake clock. - const requestedAt = Date.now() - const response = rpcRead({ - repo: 'repo', - branch: 'retry-policy', - currentHeadOid: 'head-a', - reason: 'swr', - acceptRevalidationOnly: true, - selected: true - }) - await vi.advanceTimersByTimeAsync(0) - expect(await response).toMatchObject({ - kind: 'upstream-error', - nextAutoRetryAt: requestedAt + 120_000 - }) -}) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts deleted file mode 100644 index a12fd68ed62..00000000000 --- a/src/main/runtime/integrations/reviews/runtime-hosted-pr-deadlines.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { expect, it, vi } from 'vitest' -import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' -import { makeCandidate } from '../../../github/pull-requests/refresh/pr-refresh-coordinator-test-harness' -import { fixture, found, mocks, read, rpcRead } from './runtime-hosted-pr-snapshot-test-harness' - -it('delivers post-push data from its fresh producer while an older timed producer is pending', async () => { - const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') - const old = Promise.withResolvers() - mocks.resolve.mockReturnValueOnce(old.promise) - const producer = read('pushed', 'swr') - await vi.advanceTimersByTimeAsync(0) - const delivered: PRRefreshOutcome[] = [] - const remove = coordinator.addPRRefreshOutcomeObserver((_candidate, outcome) => - delivered.push(outcome) - ) - try { - fixture.title = 'after push' - coordinator.enqueuePRRefresh( - makeCandidate({ branch: 'pushed', cacheKey: '/repo::pushed', currentHeadOid: 'head-a' }), - 'post-push' - ) - await vi.advanceTimersByTimeAsync(2_500) - expect(delivered).toContainEqual({ - kind: 'found', - fetchedAt: 3_500, - pr: expect.objectContaining({ title: 'after push' }) - }) - old.resolve(found()) - await producer - } finally { - remove() - } -}) - -it('delivers an unrelated row without a spacing delay after joining an existing producer', async () => { - const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') - const result = Promise.withResolvers() - mocks.resolve.mockReturnValueOnce(result.promise) - const producer = read('joining', 'active') - await vi.advanceTimersByTimeAsync(0) - const delivered: { branch: string; outcome: PRRefreshOutcome }[] = [] - const remove = coordinator.addPRRefreshOutcomeObserver((candidate, outcome) => { - delivered.push({ branch: candidate.branch, outcome }) - }) - try { - for (const branch of ['joining', 'unrelated']) { - coordinator.enqueuePRRefresh( - makeCandidate({ branch, cacheKey: `/repo::${branch}`, currentHeadOid: 'head-a' }), - 'swr' - ) - } - await vi.advanceTimersByTimeAsync(0) - fixture.title = 'shared answer' - result.resolve(found()) - await producer - await vi.advanceTimersByTimeAsync(0) - expect(delivered).toContainEqual({ - branch: 'unrelated', - outcome: { - kind: 'found', - fetchedAt: 1_000, - pr: expect.objectContaining({ title: 'shared answer' }) - } - }) - } finally { - remove() - } -}) - -it.each([false, true])( - 'delivers post-push data while another row waits for a later rate-limit reset (clock jump: %s)', - async (clockJump) => { - const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') - const delivered: PRRefreshOutcome[] = [] - const remove = coordinator.addPRRefreshOutcomeObserver((_candidate, outcome) => - delivered.push(outcome) - ) - const candidate = (branch: string) => - makeCandidate({ - branch, - cacheKey: `/repo::${branch}`, - currentHeadOid: 'head-a' - }) - try { - fixture.title = 'after push' - mocks.gate.mockImplementation(async (row) => (row.branch === 'later' ? 61_000 : null)) - if (clockJump) { - await coordinator.refreshPRNow(candidate('later')) - vi.setSystemTime(301_000) - } - coordinator.enqueuePRRefresh(candidate('pushed'), 'post-push') - await vi.advanceTimersByTimeAsync(0) - if (!clockJump) { - await coordinator.refreshPRNow(candidate('later')) - } - await vi.advanceTimersByTimeAsync(2_500) - expect(delivered).toContainEqual({ - kind: 'found', - fetchedAt: clockJump ? 303_500 : 3_500, - pr: expect.objectContaining({ title: 'after push' }) - }) - } finally { - remove() - } - } -) - -it.each(['deadline', 'abort'] as const)( - 'detaches an automatic cold-read waiter on %s while its producer completes for another client', - async (end) => { - const result = Promise.withResolvers() - mocks.resolve.mockReturnValueOnce(result.promise) - const producer = read('pending', 'active') - await vi.advanceTimersByTimeAsync(0) - const controller = new AbortController() - const joined = rpcRead( - { - repo: 'repo', - branch: 'pending', - currentHeadOid: 'head-a', - reason: 'swr', - acceptRevalidationOnly: true - }, - controller.signal - ) - const abandoned = - end === 'abort' - ? expect(joined).rejects.toThrow('cancelled') - : expect(joined).resolves.toMatchObject({ revalidation: { retryAfterMs: 10_000 } }) - await vi.advanceTimersByTimeAsync(0) - if (end === 'abort') { - controller.abort() - } else { - await vi.advanceTimersByTimeAsync(25_000) - } - await abandoned - fixture.title = 'producer completed' - result.resolve(found()) - await expect(producer).resolves.toMatchObject({ pr: { title: 'producer completed' } }) - await expect(read('pending')).resolves.toMatchObject({ pr: { title: 'producer completed' } }) - } -) diff --git a/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts deleted file mode 100644 index afb937d99cf..00000000000 --- a/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import type { RelayAuthContext } from './relay-auth-identity' -import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract' - -function deferred() { - let resolve!: (value: T) => void - const promise = new Promise((resolvePromise) => { - resolve = resolvePromise - }) - return { promise, resolve } -} - -const context: RelayAuthContext = { - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - accessToken: 'access-1', - relayEntitled: true -} - -describe('RelayAuthCoordinator', () => { - afterEach(() => vi.useRealTimers()) - - it('rejects a token refresh whose session read crosses an auth mutation', async () => { - const refreshRead = deferred() - let readCount = 0 - let current = context - let refreshAccessToken: (() => Promise) | null = null - const coordinator = new RelayAuthCoordinator({ - readContext: () => { - readCount += 1 - return readCount === 2 ? refreshRead.promise : Promise.resolve(current) - }, - openBroker: async (input) => { - refreshAccessToken = input.refreshAccessToken - return { closeNow: vi.fn() } - }, - onStatus: vi.fn() - }) - coordinator.reconcile() - await vi.waitFor(() => expect(refreshAccessToken).not.toBeNull()) - const refreshing = refreshAccessToken!() - current = { ...context, identity: { ...context.identity, organizationId: 'org-2' } } - coordinator.reconcile() - refreshRead.resolve(context) - - await expect(refreshing).resolves.toEqual({ accessToken: null }) - await vi.waitFor(() => expect(readCount).toBeGreaterThanOrEqual(3)) - }) - - it('rebuilds a self-closed broker on the next ensureLive and leaves a replaced one alone', async () => { - vi.useFakeTimers() - let live = true - const openBroker = vi.fn(async () => { - live = true - return { closeNow: vi.fn(), isLive: () => live } - }) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: vi.fn() - }) - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - // A stale broker's self-close reaches ensureLive while the current one is live: no rebuild. - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(1) - - // Token refresh gave up: the broker is closed, neither live nor recovering. - live = false - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - coordinator.stop() - }) - - it('keeps a dead broker whose pool is already re-asking the director', async () => { - vi.useFakeTimers() - let recovering = true - const closeNow = vi.fn() - const openBroker = vi.fn(async () => ({ - closeNow, - isLive: () => false, - isRecovering: () => recovering - })) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: vi.fn() - }) - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(1) - expect(closeNow).not.toHaveBeenCalled() - - // Once the pool stops retrying (or its relay JWT runs out), the tick rebuilds as before. - recovering = false - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(closeNow).toHaveBeenCalledTimes(1) - expect(openBroker).toHaveBeenCalledTimes(2) - coordinator.stop() - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.test.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.test.ts deleted file mode 100644 index 5b14fac6f7a..00000000000 --- a/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayControlLiveness } from './relay-control-liveness' - -const KEEPALIVE_INTERVAL_MS = 30_000 - -function keepaliveControl() { - const ping = vi.fn() - const send = vi.fn() - const terminate = vi.fn() - const liveness = new RelayControlLiveness({ - cellUrl: 'https://relay-c1.example', - ping, - send, - isLive: () => terminate.mock.calls.length === 0, - terminate, - random: () => 0.5 - }) - liveness.start() - liveness.startKeepalive(KEEPALIVE_INTERVAL_MS) - return { liveness, ping, send, terminate } -} - -describe('RelayControlLiveness keepalive acks', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('never probes a control whose keepalives are answered', async () => { - const { liveness, send, ping, terminate } = keepaliveControl() - // The edge answers each keepalive within a round trip. - send.mockImplementation(() => setTimeout(() => liveness.noteInbound(), 300)) - await vi.advanceTimersByTimeAsync(10 * 60_000) - expect(send.mock.calls.length).toBeGreaterThanOrEqual(19) - expect(ping).not.toHaveBeenCalled() - expect(terminate).not.toHaveBeenCalled() - liveness.stop() - }) - - it('probes once a reply is 10s overdue and tears down after three unanswered pings', async () => { - const { liveness, ping, terminate } = keepaliveControl() - // Blackhole from the start: the first keepalive goes out at 30s. - await vi.advanceTimersByTimeAsync(KEEPALIVE_INTERVAL_MS + 9_999) - expect(ping).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - expect(ping).toHaveBeenCalledTimes(1) - expect(console.warn).toHaveBeenCalledWith( - expect.stringMatching( - /^\[relay\] control keepalive overdue cell=\S+ sinceInboundMs=40000 probe=armed$/ - ) - ) - // Three 8s probe intervals: torn down at 64s, well before the 75s silence bound. - await vi.advanceTimersByTimeAsync(24_000) - expect(terminate).toHaveBeenCalledTimes(1) - expect(console.warn).toHaveBeenCalledWith( - '[relay] control torn down cell=https://relay-c1.example reason=probe-unanswered' - ) - liveness.stop() - }) - - it('keeps a control whose one lost ack is followed by a pong', async () => { - const { liveness, send, ping, terminate } = keepaliveControl() - await vi.advanceTimersByTimeAsync(KEEPALIVE_INTERVAL_MS + 10_000) - expect(ping).toHaveBeenCalledTimes(1) - liveness.notePong() - // Later keepalives are answered again. - send.mockImplementation(() => setTimeout(() => liveness.noteInbound(), 300)) - await vi.advanceTimersByTimeAsync(5 * 60_000) - expect(ping).toHaveBeenCalledTimes(1) - expect(terminate).not.toHaveBeenCalled() - liveness.stop() - }) - - it('does not watch acks on relays that never offered keepalive', async () => { - const ping = vi.fn() - const terminate = vi.fn() - const liveness = new RelayControlLiveness({ - cellUrl: 'https://relay-c1.example', - ping, - isLive: () => true, - terminate - }) - liveness.start() - // Relay pings arrive every 15s as before. - const relayPing = setInterval(() => liveness.noteInbound(), 15_000) - await vi.advanceTimersByTimeAsync(5 * 60_000) - clearInterval(relayPing) - expect(ping).not.toHaveBeenCalled() - expect(terminate).not.toHaveBeenCalled() - liveness.stop() - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-recovery.test.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-recovery.test.ts deleted file mode 100644 index cab9dbd0350..00000000000 --- a/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-recovery.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayHttpError, type RelayAssignment } from '../director/relay-http-client' -import type * as RelayHttpClient from '../director/relay-http-client' -import type { RelayControlOriginOptions } from './relay-control-origin-options' -import type { RelayOriginPoolOptions } from './relay-origin-pool-options' -import type { RelayControlOrigin } from './relay-control-origin' -import { RelayOriginPool } from './relay-origin-pool' - -type FakeOrigin = { - options: RelayControlOriginOptions - cellUrl: string - live: boolean - closeNow: ReturnType -} - -const harness = vi.hoisted(() => { - const origins: FakeOrigin[] = [] - return { requestRelayAssignment: vi.fn(), origins, failConnects: false } -}) - -vi.mock('../director/relay-http-client', async (importOriginal) => ({ - ...(await importOriginal()), - requestRelayAssignment: harness.requestRelayAssignment -})) -vi.mock('./relay-control-origin', () => ({ - RelayControlOrigin: class { - readonly options: RelayControlOriginOptions - assignment: RelayAssignment - live = true - availableControl = null - pendingRequestCount = 0 - controlLeaseExpiresAt = Date.now() + 6 * 60 * 60_000 - constructor(options: RelayControlOriginOptions) { - this.options = options - this.assignment = options.assignment - harness.origins.push(this) - } - get cellUrl(): string { - return this.assignment.cellUrl - } - hasLiveControl = (): boolean => this.live - open = async (): Promise => { - if (harness.failConnects) { - throw new Error('relay_control_connect_timeout') - } - } - rebind = async (): Promise => { - if (harness.failConnects) { - throw new Error('relay_control_connect_timeout') - } - } - closeNow = vi.fn() - refreshAuthorization = vi.fn() - updateAssignment = vi.fn() - } -})) - -const edge: RelayAssignment = { - v: 1, - cellUrl: 'https://relay-edge.example', - assignmentEpoch: 1, - lease: 'l' -} -const hk: RelayAssignment = { - v: 1, - cellUrl: 'https://relay-hk.example', - assignmentEpoch: 2, - lease: 'l' -} - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pool created these fakes through the mocked RelayControlOrigin. -const asOrigin = (fake: FakeOrigin) => fake as unknown as RelayControlOrigin - -async function openPool(): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked origin reads no identity, keypair or wiring members. - const options = { - directorUrl: 'https://relay.example', - relayHostId: 'host', - isCurrent: () => true, - onStatus: vi.fn(), - random: () => 1 - } as unknown as RelayOriginPoolOptions - const pool = new RelayOriginPool(options) - await pool.openInitial(edge, 'relay-jwt') - return pool -} - -describe('RelayOriginPool recovery', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - harness.origins.length = 0 - harness.failConnects = false - harness.requestRelayAssignment.mockReset() - }) - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('re-asks the director for a failing data path at most once a minute per host', async () => { - harness.requestRelayAssignment.mockResolvedValue(edge) - const pool = await openPool() - const first = harness.origins[0] - for (let i = 0; i < 6; i++) { - first.options.onDataPathUnhealthy(asOrigin(first)) - await vi.advanceTimersByTimeAsync(10_000) - } - expect(harness.requestRelayAssignment).toHaveBeenCalledTimes(1) - first.options.onDataPathUnhealthy(asOrigin(first)) - await vi.advanceTimersByTimeAsync(0) - expect(harness.requestRelayAssignment).toHaveBeenCalledTimes(2) - pool.closeNow() - }) - - it('keeps the old cell for a minute when the director moves the host, so live phones finish', async () => { - harness.requestRelayAssignment.mockResolvedValue(hk) - const pool = await openPool() - const first = harness.origins[0] - // A live phone session is still spliced through the old origin. - first.options.onConnectionOwned('conn-live', asOrigin(first)) - first.options.onDataPathUnhealthy(asOrigin(first)) - await vi.advanceTimersByTimeAsync(0) - expect(pool.activeAssignment).toEqual(hk) - await vi.advanceTimersByTimeAsync(59_000) - expect(first.closeNow).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1_000) - expect(first.closeNow).toHaveBeenCalled() - pool.closeNow() - }) - - it('stops claiming recovery five minutes into a failing retry', async () => { - harness.requestRelayAssignment.mockResolvedValue(edge) - const pool = await openPool() - harness.failConnects = true - const first = harness.origins[0] - first.live = false - first.options.onClose(asOrigin(first), 1006) - await vi.advanceTimersByTimeAsync(0) - expect(pool.isRecovering()).toBe(true) - await vi.advanceTimersByTimeAsync(4 * 60_000) - expect(pool.isRecovering()).toBe(true) - await vi.advanceTimersByTimeAsync(61_000) - expect(pool.isRecovering()).toBe(false) - pool.closeNow() - }) - - it('stops claiming recovery at once when the director refuses the relay token', async () => { - harness.requestRelayAssignment.mockRejectedValue(new RelayHttpError('assignment', 401)) - const pool = await openPool() - const first = harness.origins[0] - first.live = false - first.options.onClose(asOrigin(first), 1006) - await vi.advanceTimersByTimeAsync(0) - expect(pool.isRecovering()).toBe(false) - pool.closeNow() - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-retry.test.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-retry.test.ts deleted file mode 100644 index 6eab94666fc..00000000000 --- a/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-retry.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayHttpError, type RelayAssignment } from '../director/relay-http-client' -import type * as RelayHttpClient from '../director/relay-http-client' -import type { RelayControlOriginOptions } from './relay-control-origin-options' -import type { RelayOriginPoolOptions } from './relay-origin-pool-options' -import { RelayOriginPool } from './relay-origin-pool' -import type { RelayControlOrigin } from './relay-control-origin' - -type FakeOrigin = { options: RelayControlOriginOptions } - -const harness = vi.hoisted(() => { - const origins: FakeOrigin[] = [] - return { requestRelayAssignment: vi.fn(), origins, failOpens: false } -}) - -vi.mock('../director/relay-http-client', async (importOriginal) => ({ - ...(await importOriginal()), - requestRelayAssignment: harness.requestRelayAssignment -})) -vi.mock('./relay-control-origin', () => ({ - RelayControlOrigin: class { - readonly options: RelayControlOriginOptions - readonly failOpen = harness.failOpens - assignment: RelayAssignment - availableControl = null - pendingRequestCount = 0 - controlLeaseExpiresAt = Date.now() + 6 * 60 * 60_000 - constructor(options: RelayControlOriginOptions) { - this.options = options - this.assignment = options.assignment - harness.origins.push(this) - } - get cellUrl(): string { - return this.assignment.cellUrl - } - hasLiveControl = (): boolean => !this.failOpen - open = async (): Promise => { - if (this.failOpen) { - throw new Error('relay_control_connect_timeout') - } - } - rebind = async (): Promise => { - throw new Error('relay_control_connect_timeout') - } - closeNow = vi.fn() - refreshAuthorization = vi.fn() - updateAssignment = vi.fn() - } -})) - -const assignment: RelayAssignment = { - v: 1, - cellUrl: 'https://relay-edge.example', - assignmentEpoch: 1, - lease: 'lease' -} - -async function poolWithDeadControl(ask: () => Promise) { - const askedAt: number[] = [] - harness.requestRelayAssignment.mockImplementation(async () => { - askedAt.push(Date.now()) - return ask() - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the mocked origin reads no identity, keypair or wiring members. - const options = { - directorUrl: 'https://relay.example', - relayHostId: 'host', - isCurrent: () => true, - onStatus: vi.fn(), - random: () => 1 - } as unknown as RelayOriginPoolOptions - const pool = new RelayOriginPool(options) - await pool.openInitial(assignment, 'relay-jwt') - // Every later connect to the cell fails, as from a network that cannot hold it. - harness.failOpens = true - const first = harness.origins[0] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pool created this fake through the mocked RelayControlOrigin. - first.options.onClose(first as unknown as RelayControlOrigin, 1006) - // With random() = 1 every backoff waits its full cap, so the gaps between asks show the cap. - const gapsBetweenAsks = async (count: number): Promise => { - while (askedAt.length < count) { - await vi.advanceTimersByTimeAsync(1_000) - } - return askedAt.slice(1).map((at, index) => at - askedAt[index]) - } - return { pool, gapsBetweenAsks } -} - -describe('RelayOriginPool drain retry cap', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - harness.origins.length = 0 - harness.failOpens = false - harness.requestRelayAssignment.mockReset() - }) - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) - - const THIRTY_MINUTES = 30 * 60_000 - - async function asksDuring(ms: number, ask: () => Promise): Promise { - const { pool, gapsBetweenAsks } = await poolWithDeadControl(ask) - await vi.advanceTimersByTimeAsync(ms) - const gaps = await gapsBetweenAsks(0) - pool.closeNow() - return gaps - } - - it('asks the director no more often than the full backoff while it keeps naming a dead cell', async () => { - const deadCell = await asksDuring(THIRTY_MINUTES, async () => assignment) - harness.origins.length = 0 - harness.failOpens = false - const directorDown = await asksDuring(THIRTY_MINUTES, async () => { - throw new RelayHttpError('assignment', 503) - }) - expect(deadCell.length).toBeLessThanOrEqual(directorDown.length) - // Backoff reaches the 300s cap, not 60s. - expect(Math.max(...deadCell)).toBeGreaterThan(250_000) - }) - - it('falls back to the full backoff when the director alternates between failing cells', async () => { - const deadCell = await asksDuring(THIRTY_MINUTES, async () => assignment) - harness.origins.length = 0 - harness.failOpens = false - let epoch = 1 - const alternating = await asksDuring(THIRTY_MINUTES, async () => { - epoch += 1 - const cell = epoch % 2 === 0 ? 'a' : 'b' - return { ...assignment, cellUrl: `https://relay-${cell}.example`, assignmentEpoch: epoch } - }) - // Each of the two cells gets the short cap once; after that the rate matches a dead cell. - expect(alternating.length).toBeLessThanOrEqual(deadCell.length + 2) - expect(Math.max(...alternating)).toBeGreaterThan(250_000) - }) - - it('retries within 60s each time the director names a different cell that then fails', async () => { - let epoch = 1 - const gaps = await asksDuring(THIRTY_MINUTES, async () => { - epoch += 1 - return { ...assignment, cellUrl: `https://relay-c${epoch}.example`, assignmentEpoch: epoch } - }) - expect(gaps.length).toBeGreaterThan(25) - expect(Math.max(...gaps)).toBeLessThanOrEqual(61_000) - }) - - it('keeps the full backoff while the director itself is failing', async () => { - const gaps = await asksDuring(THIRTY_MINUTES, async () => { - throw new RelayHttpError('assignment', 503) - }) - expect(Math.max(...gaps)).toBeGreaterThan(250_000) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts deleted file mode 100644 index 676d73f5c89..00000000000 --- a/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { RelayRegionPreferenceResolver } from './relay-region-preference' - -const DIRECTOR = 'https://relay.example.test' -const US = 'https://us-c1.relay.example.test' -const US_SECONDARY = 'https://us-c2.relay.example.test' -const ASIA = 'https://asia-c1.relay.example.test' -const CELL = 'https://cell-7.relay.example.test' -const BOTH_REGIONS = [ - { region: 'us-central1', probeOrigins: [US] }, - { region: 'asia-east2', probeOrigins: [ASIA] } -] -const tempPaths: string[] = [] - -afterEach(() => { - vi.unstubAllEnvs() - for (const path of tempPaths.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } -}) - -function userDataPath(): string { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-region-')) - tempPaths.push(path) - return path -} - -function catalogFetch(regions: unknown) { - return vi.fn(async () => Response.json({ v: 1, regions })) -} - -// Each list starts with the discarded warm-up probe, then the three kept samples. -function sampledProbe(samples: Record) { - const calls: string[] = [] - const probe = async (origin: string): Promise => { - calls.push(origin) - return samples[origin]?.shift() ?? null - } - return { calls, probe } -} - -function writeNoHintCache(path: string, expiresAt: number): void { - writeFileSync( - cachePath(path), - JSON.stringify({ v: 2, directorUrl: DIRECTOR, region: null, expiresAt }) - ) -} - -function cachePath(path: string): string { - return join(path, 'orca-relay-region-preference.json') -} - -function writeCache(path: string, region: string, expiresAt = 999): void { - writeFileSync( - cachePath(path), - JSON.stringify({ v: 2, directorUrl: DIRECTOR, region, latencyMs: 100, expiresAt }) - ) -} - -describe('Relay region preference', () => { - it('measures a warm-up plus three rounds across one- and two-origin catalogs', async () => { - const path = userDataPath() - const fetch = catalogFetch([ - { region: 'us-central1', probeOrigins: [US, US_SECONDARY] }, - { region: 'asia-east2', probeOrigins: [ASIA] } - ]) - const { calls, probe } = sampledProbe({ - [US]: [400, 160, 170, 150], - [US_SECONDARY]: [390, 155, 165, 145], - [ASIA]: [90, 35, 40, 30] - }) - const resolver = new RelayRegionPreferenceResolver({ - directorUrl: DIRECTOR, - userDataPath: path, - fetch, - probe, - now: () => 1_000 - }) - - await expect(resolver.resolve()).resolves.toBe('asia-east2') - expect(calls.filter((origin) => origin === US)).toHaveLength(4) - expect(calls.filter((origin) => origin === US_SECONDARY)).toHaveLength(4) - expect(calls.filter((origin) => origin === ASIA)).toHaveLength(4) - expect(JSON.parse(readFileSync(cachePath(path), 'utf8'))).toMatchObject({ - v: 2, - directorUrl: DIRECTOR, - region: 'asia-east2', - latencyMs: 30 - }) - - const offlineFetch = vi.fn(async () => { - throw new Error('offline') - }) - await expect( - new RelayRegionPreferenceResolver({ - directorUrl: DIRECTOR, - userDataPath: path, - fetch: offlineFetch, - now: () => 2_000 - }).resolve() - ).resolves.toBe('asia-east2') - expect(offlineFetch).not.toHaveBeenCalled() - }) - - it.each([ - { name: 'a flapping near region', near: [50, 10, 20, 400] }, - { name: 'an unreachable near region', near: [] } - ])('sends no hint when $name leaves a sole survivor', async ({ near }) => { - const path = userDataPath() - const { probe } = sampledProbe({ [US]: near, [ASIA]: [230, 220, 218, 218] }) - - await expect( - new RelayRegionPreferenceResolver({ - directorUrl: DIRECTOR, - userDataPath: path, - fetch: catalogFetch(BOTH_REGIONS), - probe, - now: () => 1_000 - }).resolve() - ).resolves.toBeUndefined() - const cached = JSON.parse(readFileSync(cachePath(path), 'utf8')) - expect(cached).toEqual({ v: 2, directorUrl: DIRECTOR, region: null, expiresAt: 3_601_000 }) - }) -}) - -describe('Relay region cache self-heal', () => { - const LIVE_EXPIRY = 50_000_000 - - function resolverFor(path: string, cellMs: number[]) { - const { calls, probe } = sampledProbe({ - [US]: [300, 36, 38, 40], - [ASIA]: [400, 218, 220, 222], - [CELL]: cellMs - }) - const fetch = catalogFetch(BOTH_REGIONS) - return { - calls, - fetch, - resolver: new RelayRegionPreferenceResolver({ - directorUrl: DIRECTOR, - userDataPath: path, - fetch, - probe, - now: () => 1_000 - }) - } - } - - it.each([ - { name: 'no cache', write: () => {} }, - { name: 'an expired cache', write: (path: string) => writeCache(path, 'asia-east2', 999) }, - { name: 'a no-hint cache', write: (path: string) => writeNoHintCache(path, LIVE_EXPIRY) } - ])('skips the probes and stays unarmed for $name', async ({ write }) => { - const path = userDataPath() - write(path) - const first = resolverFor(path, [800, 700, 710, 720]) - - await first.resolver.invalidateIfAssignedCellIsFar(CELL) - expect(first.fetch).not.toHaveBeenCalled() - expect(first.calls).toHaveLength(0) - - writeCache(path, 'asia-east2', LIVE_EXPIRY) - await first.resolver.invalidateIfAssignedCellIsFar(CELL) - expect(existsSync(cachePath(path))).toBe(false) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-recovery.test.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-recovery.test.ts deleted file mode 100644 index 4398aebecc7..00000000000 --- a/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-recovery.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RelaySessionBrokerOptions } from './relay-session-broker-contract' -import { RelaySessionBroker } from './relay-session-broker' -import type * as RelayHttpClient from '../director/relay-http-client' - -const http = vi.hoisted(() => ({ - exchangeRelayAuthorization: vi.fn(), - requestRelayAssignment: vi.fn() -})) -const pool = vi.hoisted(() => ({ recovering: false, live: true })) - -vi.mock('../../../power/system-power-lifecycle', () => ({ - subscribeSystemPowerLifecycle: () => () => {} -})) -vi.mock('../director/relay-http-client', async (importOriginal) => ({ - ...(await importOriginal()), - exchangeRelayAuthorization: http.exchangeRelayAuthorization, - requestRelayAssignment: http.requestRelayAssignment -})) -vi.mock('../origin-lifecycle/relay-origin-pool', () => ({ - RelayOriginPool: class { - activeAssignment = { v: 1, cellUrl: 'https://relay-c1.example', assignmentEpoch: 1, lease: 'l' } - openInitial = vi.fn(async () => {}) - refreshAuthorization = vi.fn() - closeNow = vi.fn() - hasLiveControl = () => pool.live - isRecovering = () => pool.recovering - } -})) - -const HOUR = 60 * 60_000 - -function brokerOptions(overrides: Partial): RelaySessionBrokerOptions { - return { - authConfig: { - apiBaseUrl: 'https://api.example', - authorizeEndpoint: 'https://api.example/authorize', - sessionEndpoint: 'https://api.example/session', - refreshEndpoint: 'https://api.example/refresh', - capabilitiesEndpoint: 'https://api.example/capabilities', - profileEndpoint: 'https://api.example/profile', - orgEndpoint: 'https://api.example/org', - logoutEndpoint: 'https://api.example/logout', - relayTokenEndpoint: 'https://api.example/relay-token', - connectorTokenEndpoint: 'https://api.example/connector-token', - relayDirectorUrl: 'https://relay.example', - clientId: 'client', - scope: 'openid' - }, - accessToken: 'access', - identity: { userId: 'u', profileId: 'p', organizationId: 'o' }, - keypair: { publicKey: new Uint8Array(32), secretKey: new Uint8Array(32), publicKeyB64: '' }, - appVersion: '1.0.0', - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the origin pool that reads the wiring is mocked. - mobileSocketWiring: {} as unknown as RelaySessionBrokerOptions['mobileSocketWiring'], - isCurrent: () => true, - refreshAccessToken: async () => ({ accessToken: 'access-2' }), - onStatus: vi.fn(), - random: () => 0.5, - ...overrides - } -} - -describe('RelaySessionBroker recovery signals', () => { - beforeEach(() => { - vi.useFakeTimers() - pool.recovering = false - pool.live = true - http.exchangeRelayAuthorization.mockResolvedValue({ - relayToken: 'relay-jwt', - expiresAt: Date.now() + HOUR - }) - http.requestRelayAssignment.mockResolvedValue({ - v: 1, - cellUrl: 'https://relay-c1.example', - assignmentEpoch: 1, - lease: 'l' - }) - }) - afterEach(() => { - vi.useRealTimers() - vi.clearAllMocks() - }) - - it('tells its owner when it closes itself after token refresh gives up', async () => { - const onSelfClose = vi.fn() - const refreshAccessToken = vi.fn(async () => { - throw new Error('api unreachable') - }) - const broker = await RelaySessionBroker.connect( - brokerOptions({ onSelfClose, refreshAccessToken }) - ) - // Renewal fires before expiry, then retries every 5-15s until expiry + 60s. - await vi.advanceTimersByTimeAsync(HOUR) - expect(refreshAccessToken).toHaveBeenCalled() - expect(onSelfClose).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(80_000) - expect(onSelfClose).toHaveBeenCalledTimes(1) - expect(broker.isLive()).toBe(false) - }) - - it('does not report an owner-initiated close', async () => { - const onSelfClose = vi.fn() - const broker = await RelaySessionBroker.connect(brokerOptions({ onSelfClose })) - broker.closeNow() - expect(onSelfClose).not.toHaveBeenCalled() - }) - - it('counts as recovering only while open and its pool retries', async () => { - const broker = await RelaySessionBroker.connect(brokerOptions({})) - pool.live = false - expect(broker.isRecovering()).toBe(false) - pool.recovering = true - expect(broker.isRecovering()).toBe(true) - broker.closeNow() - expect(broker.isRecovering()).toBe(false) - }) -}) diff --git a/src/main/runtime/rpc/server/pairing/network/pairing-network-interfaces.test.ts b/src/main/runtime/rpc/server/pairing/network/pairing-network-interfaces.test.ts deleted file mode 100644 index 0753e26c2c7..00000000000 --- a/src/main/runtime/rpc/server/pairing/network/pairing-network-interfaces.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import type * as NodeOs from 'node:os' -import type { NetworkInterfaceInfo } from 'node:os' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { networkInterfacesMock } = vi.hoisted(() => ({ - networkInterfacesMock: vi.fn<() => NodeJS.Dict>() -})) - -vi.mock('node:os', async (importOriginal) => ({ - ...(await importOriginal()), - networkInterfaces: networkInterfacesMock -})) - -import { getDefaultPairingAddress, getPairingNetworkInterfaces } from './pairing-network-interfaces' - -function ipv4(address: string, internal = false): NetworkInterfaceInfo { - return { - address, - family: 'IPv4', - internal, - netmask: '255.255.0.0', - mac: '00:00:00:00:00:00', - cidr: null - } -} - -function ipv6(address: string): NetworkInterfaceInfo { - return { - address, - family: 'IPv6', - internal: false, - netmask: 'ffff:ffff:ffff:ffff::', - mac: '00:00:00:00:00:00', - cidr: null, - scopeid: 0 - } -} - -const noDefaultRoute = async (): Promise> => new Set() - -describe('getPairingNetworkInterfaces', () => { - beforeEach(() => { - networkInterfacesMock.mockReset() - }) - - it('never offers link-local or loopback addresses', async () => { - networkInterfacesMock.mockReturnValue({ - 'Ethernet 2': [ipv4('169.254.83.107'), ipv6('fe80::1234')], - Loopback: [ipv4('127.0.0.1', true)], - 'Wi-Fi': [ipv4('192.168.1.20')] - }) - - const interfaces = await getPairingNetworkInterfaces('::', noDefaultRoute) - - expect(interfaces.map((iface) => iface.address)).toEqual(['192.168.1.20']) - }) - - it('offers no direct address when only link-local adapters exist', async () => { - networkInterfacesMock.mockReturnValue({ - 'Ethernet 2': [ipv4('169.254.83.107'), ipv6('fe80::1234')] - }) - - await expect(getDefaultPairingAddress('0.0.0.0', noDefaultRoute)).resolves.toBeNull() - }) - - it('still ranks Tailscale first, then prefers the default-route adapter', async () => { - networkInterfacesMock.mockReturnValue({ - 'Ethernet 3': [ipv4('10.8.0.2')], - 'vEthernet (WSL (Hyper-V firewall))': [ipv4('172.20.96.1')], - 'Wi-Fi': [ipv4('192.168.1.20')], - Tailscale: [ipv4('100.101.102.103')] - }) - const defaultRoute = async (): Promise> => new Set(['Wi-Fi']) - - const interfaces = await getPairingNetworkInterfaces('0.0.0.0', defaultRoute) - - expect(interfaces.map((iface) => iface.address)).toEqual([ - '100.101.102.103', - '192.168.1.20', - '10.8.0.2', - '172.20.96.1' - ]) - await expect(getDefaultPairingAddress('0.0.0.0', defaultRoute)).resolves.toBe('100.101.102.103') - }) - - it('advertises the default-route LAN over an idle adapter listed first', async () => { - networkInterfacesMock.mockReturnValue({ - 'Ethernet 3': [ipv4('10.8.0.2')], - 'vEthernet (Default Switch)': [ipv4('172.28.80.1')], - 'Wi-Fi': [ipv4('192.168.1.20')] - }) - - await expect(getDefaultPairingAddress('0.0.0.0', async () => new Set(['wi-fi']))).resolves.toBe( - '192.168.1.20' - ) - }) -}) diff --git a/src/main/runtime/terminal/surface/closed-pane-exit-cleanup-main.test.ts b/src/main/runtime/terminal/surface/closed-pane-exit-cleanup-main.test.ts deleted file mode 100644 index 368f0276f0a..00000000000 --- a/src/main/runtime/terminal/surface/closed-pane-exit-cleanup-main.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -// Close drops panes before terminal exit; main must recover their closed-pane identity even headless (L80 Q2). -import { expect, it, vi } from 'vitest' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID, TEST_WORKTREE_ID } = - await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../../orca-runtime') -const { SURFACE_TAB_ID, SURFACE_PTYS, surfaceRuntime } = - await import('./terminal-surface-replies.test-fixture') - -const PANE_A = `${SURFACE_TAB_ID}:${HEADLESS_LEAF_ID}` -const PANE_B = `${SURFACE_TAB_ID}:${HEADLESS_SECOND_LEAF_ID}` -const INCARNATIONS: Record = { 'pty-a': 'inc-a', 'pty-b': 'inc-b' } - -type Host = 'no window' | 'a window' -type Harness = ReturnType -type Runtime = Harness['runtime'] - -/** The scenario's split tab, each pane bound to its terminal's incarnation, as a spawn commit leaves it. */ -function closingHost(host: Host): Harness & { reconciled: string[] } { - const harness = surfaceRuntime() - const { runtime, store, setSession } = harness - setSession({ - ...store.getSession(), - terminalPtyIncarnationsByPaneKey: { [PANE_A]: 'inc-a', [PANE_B]: 'inc-b' } - }) - for (const [leafId, ptyId] of Object.entries(SURFACE_PTYS)) { - runtime.registerPty(ptyId, TEST_WORKTREE_ID, null, { - tabId: SURFACE_TAB_ID, - leafId, - incarnationId: INCARNATIONS[ptyId] - }) - } - if (host === 'a window') { - runtime.attachWindow(1) - } - runtime.syncWindowGraph(host === 'a window' ? 1 : HEADLESS_RUNTIME_WINDOW_ID, { - tabs: [], - leaves: [] - }) - const reconciled: string[] = [] - watchReconciled(runtime, reconciled) - return { ...harness, reconciled } -} - -function watchReconciled(runtime: Runtime, into: string[]): void { - Reflect.set(runtime, 'reconcileAgentStatusForEndedProcessFn', (keys: Set) => { - into.push(...keys) - }) -} - -/** The CLI's close of pty-b's pane by its handle; the tab stays open with pty-a's pane. */ -async function closePaneByHandle(runtime: Runtime): Promise { - const listed = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) - await runtime.closeTerminal( - listed.terminals.find((terminal) => terminal.ptyId === 'pty-b')!.handle - ) -} - -/** The window's own tab close, as `layout.apply` forwards it; the window kills the terminals. */ -async function closeTabAsWindow(runtime: Runtime): Promise { - await runtime['store']!.applyLayoutCommand!( - { - type: 'closeTabs', - workspace: TEST_WORKTREE_ID, - tabIds: [SURFACE_TAB_ID], - force: true, - recordClose: 'user' - }, - ['local'] - ) -} - -async function phoneShowsPane(runtime: Runtime, leafId: string): Promise { - const phone = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - return phone.tabs.some( - (tab) => tab.type === 'terminal' && tab.parentTabId === SURFACE_TAB_ID && tab.leafId === leafId - ) -} - -const CLOSES = [ - { route: 'a pane closed by handle in a tab that stays', close: closePaneByHandle }, - { route: 'the window’s tab close', close: closeTabAsWindow } -] as const - -for (const host of ['no window', 'a window'] as const) { - for (const { route, close } of CLOSES) { - it(`close then exit retires the pane's agent status and phone row: ${route}, with ${host}`, async () => { - const harness = closingHost(host) - - await close(harness.runtime) - expect(harness.store.getSession().closedTerminalPanesByPaneKey?.[PANE_B]).toMatchObject({ - ptyId: 'pty-b', - incarnationId: 'inc-b', - worktreeId: TEST_WORKTREE_ID - }) - harness.runtime.onPtyExit('pty-b', 0, 'inc-b') - - expect(harness.reconciled).toContain(PANE_B) - expect(harness.store.getSession().closedTerminalPanesByPaneKey?.[PANE_B]).toBeUndefined() - expect(await phoneShowsPane(harness.runtime, HEADLESS_SECOND_LEAF_ID)).toBe(false) - }) - - it(`exit then close retires them too: ${route}, with ${host}`, async () => { - const harness = closingHost(host) - - harness.runtime.onPtyExit('pty-b', 0, 'inc-b') - await close(harness.runtime).catch(() => {}) - - expect(harness.reconciled).toContain(PANE_B) - expect(await phoneShowsPane(harness.runtime, HEADLESS_SECOND_LEAF_ID)).toBe(false) - }) - - it(`close, restart, then exit still finds the pane from disk: ${route}, with ${host}`, async () => { - const harness = closingHost(host) - await close(harness.runtime) - - // The relaunch reattaches the closed pane's live terminal; no pane holds it any more. - const relaunched = new OrcaRuntimeService(harness.runtime['store']) - relaunched.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - if (host === 'a window') { - relaunched.attachWindow(1) - } - relaunched.syncWindowGraph(host === 'a window' ? 1 : HEADLESS_RUNTIME_WINDOW_ID, { - tabs: [], - leaves: [] - }) - relaunched.registerPty('pty-b', TEST_WORKTREE_ID) - relaunched['terminalIdentity'].setPtyIncarnationId( - relaunched['ptysById'].get('pty-b')!, - 'inc-b' - ) - const reconciled: string[] = [] - watchReconciled(relaunched, reconciled) - - relaunched.onPtyExit('pty-b', 0, 'inc-b') - - expect(reconciled).toContain(PANE_B) - expect(harness.store.getSession().closedTerminalPanesByPaneKey?.[PANE_B]).toBeUndefined() - }) - - it(`does not take the closed pane for a later incarnation of the id: ${route}, with ${host}`, async () => { - const harness = closingHost(host) - await close(harness.runtime) - harness.runtime['terminalIdentity'].setPtyIncarnationId( - harness.runtime['ptysById'].get('pty-b')!, - 'inc-later' - ) - - harness.runtime.onPtyExit('pty-b', 0, 'inc-later') - - expect(harness.reconciled).not.toContain(PANE_B) - expect(harness.store.getSession().closedTerminalPanesByPaneKey?.[PANE_B]).toBeDefined() - }) - } -} diff --git a/src/main/skills/install/skill-install-discovery-verification.test.ts b/src/main/skills/install/skill-install-discovery-verification.test.ts deleted file mode 100644 index 584e91d4eae..00000000000 --- a/src/main/skills/install/skill-install-discovery-verification.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { SkillInstallResult } from '../../../shared/skill-install-contract' -import type { SkillDiscoveryResult } from '../../../shared/skills' - -const { discoverSkillsInWslMock } = vi.hoisted(() => ({ - discoverSkillsInWslMock: vi.fn() -})) - -vi.mock('../discovery/skill-discovery-wsl', () => ({ - discoverSkillsInWsl: discoverSkillsInWslMock -})) - -import { verifySkillInstallDiscovery } from './skill-install-discovery-verification' - -function installResult(paths: string[]): SkillInstallResult { - return { - operationId: 'operation-wsl', - status: 'installed', - name: 'review', - packageDigest: 'a'.repeat(64), - canonicalPath: paths[0], - placements: paths.map((path, index) => ({ - provider: index === 0 ? 'agent-skills' : 'claude', - path, - topology: index === 0 ? 'canonical-copy' : 'provider-alias', - status: 'installed' - })) - } -} - -function discovery(rootPaths: string[], unavailableRoots: string[] = []): SkillDiscoveryResult { - return { - skills: [ - { - id: 'review', - name: 'review', - description: 'Review', - providers: ['agent-skills', 'claude'], - sourceKind: 'home', - sourceLabel: 'Agent skills home', - rootPath: rootPaths[0], - rootPaths, - directoryPath: `${rootPaths[0]}/review`, - skillFilePath: `${rootPaths[0]}/review/SKILL.md`, - installed: true, - updatedAt: null - } - ], - // Unavailable roots remain possibly present; absence is unproven. - sources: unavailableRoots.map((path) => ({ - id: path, - label: 'Agent skills home', - path, - sourceKind: 'home' as const, - providers: ['agent-skills' as const], - owner: null, - exists: true, - skippedReason: 'unavailable' as const - })), - scannedAt: 1 - } -} - -beforeEach(() => { - discoverSkillsInWslMock.mockReset() -}) - -describe('WSL install discovery verification', () => { - it('matches UNC placements against distro-native discovery paths', async () => { - discoverSkillsInWslMock.mockResolvedValue( - discovery(['/home/alice/.agents/skills', '/home/alice/.claude/skills']) - ) - const result = await verifySkillInstallDiscovery({ - result: installResult([ - '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.agents\\skills\\review', - '\\\\wsl$\\ubuntu\\home\\alice\\.claude\\skills\\review' - ]), - scope: 'global', - homeDirectory: '\\\\wsl.localhost\\Ubuntu\\home\\alice', - wslDistro: 'Ubuntu' - }) - - expect(result.status).toBe('installed') - expect(result.placements).not.toContainEqual(expect.objectContaining({ status: 'failed' })) - expect(discoverSkillsInWslMock).toHaveBeenCalledWith({ - distro: 'Ubuntu', - homeDir: '/home/alice', - cwd: '/home/alice', - names: ['review'], - sourceKinds: ['home', 'repo'] - }) - }) - - // Retained pre-install discovery cannot prove new bytes landed; verification needs an answered root. - it('does not verify a placement backed only by a root that did not answer', async () => { - discoverSkillsInWslMock.mockResolvedValue( - discovery(['/home/alice/.agents/skills'], ['/home/alice/.agents/skills']) - ) - const result = await verifySkillInstallDiscovery({ - result: installResult(['\\\\wsl.localhost\\Ubuntu\\home\\alice\\.agents\\skills\\review']), - scope: 'global', - homeDirectory: '\\\\wsl.localhost\\Ubuntu\\home\\alice', - wslDistro: 'Ubuntu' - }) - - expect(result).toMatchObject({ - status: 'failed', - errorCategory: 'skill-discovery-canonical-missing' - }) - expect(result.placements[0].failure?.retryable).toBe(true) - }) - - it('still verifies through a co-owning root that did answer', async () => { - discoverSkillsInWslMock.mockResolvedValue( - discovery( - ['/home/alice/.agents/skills', '/home/alice/.claude/skills'], - ['/home/alice/.agents/skills'] - ) - ) - const result = await verifySkillInstallDiscovery({ - result: installResult(['\\\\wsl.localhost\\Ubuntu\\home\\alice\\.claude\\skills\\review']), - scope: 'global', - homeDirectory: '\\\\wsl.localhost\\Ubuntu\\home\\alice', - wslDistro: 'Ubuntu' - }) - - expect(result.status).toBe('installed') - }) - - it('fails verification without scanning a mismatched UNC distro', async () => { - const result = await verifySkillInstallDiscovery({ - result: installResult(['\\\\wsl.localhost\\Debian\\home\\alice\\.agents\\skills\\review']), - scope: 'global', - homeDirectory: '\\\\wsl.localhost\\Debian\\home\\alice', - wslDistro: 'Ubuntu' - }) - - expect(result).toMatchObject({ - status: 'failed', - errorCategory: 'skill-discovery-verification-failed' - }) - expect(discoverSkillsInWslMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/speech/dictation-cleanup-service.test.ts b/src/main/speech/dictation-cleanup-service.test.ts deleted file mode 100644 index af9b728e7eb..00000000000 --- a/src/main/speech/dictation-cleanup-service.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { DICTATION_CLEANUP_TIMEOUT_MS } from '../../shared/dictation-cleanup' -import { - createMockDiscoveryChild, - type MockDiscoveryChild -} from '../text-generation/execution/commit-message-text-generation-test-harness' -import type * as DictationCleanup from '../../shared/dictation-cleanup' -import type * as GenerationLanes from '../text-generation/execution/source-control-generation-lanes' -import { cancelDictationCleanup, cleanUpDictatedText } from './dictation-cleanup-service' - -const children: MockDiscoveryChild[] = [] -const cancelRegistrations: string[] = [] -let agentId = 'claude' - -vi.mock('../../shared/dictation-cleanup', async (importOriginal) => ({ - ...(await importOriginal()), - isDictationCleanupOn: () => true -})) -vi.mock('../text-generation/commit-message-text-generation', () => ({ - resolveCommitMessageSettings: () => ({ ok: true, params: { agentId, model: 'default' } }) -})) -vi.mock('../text-generation/execution/commit-message-agent-environment', () => ({ - prepareLocalCommitMessageAgentEnv: async () => ({ ok: true }) -})) -vi.mock('../text-generation/execution/source-control-generation-lanes', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - setLocalGenerationCancelToken: (lane: string, cancel: () => void) => { - cancelRegistrations.push(lane) - actual.setLocalGenerationCancelToken(lane, cancel) - } - } -}) -vi.mock('../text-generation/execution/source-control-agent-launch', () => ({ - spawnSourceControlAgent: ({ args }: { args: string[] }) => { - const child = createMockDiscoveryChild() - if (args.includes('mcp')) { - // Codex's read-only policy probe: no MCP servers configured. - queueMicrotask(() => { - child.stdout.emit('data', Buffer.from('[]')) - child.emit('close', 0) - }) - } else { - // A killed agent exits, as SIGKILL makes a real one do. - child.kill = vi.fn(() => { - queueMicrotask(() => child.emit('close', null, 'SIGKILL')) - return true - }) - children.push(child) - } - return child - } -})) - -const deps = { getSettings: () => ({}), getAgentEnvResolvers: () => undefined } - -afterEach(() => { - children.length = 0 - cancelRegistrations.length = 0 - agentId = 'claude' - vi.useRealTimers() -}) - -function startCleanup(requestId: string): ReturnType { - return cleanUpDictatedText({ text: requestId, terms: [], requestId }, deps) -} - -/** Starts a cleanup and returns once it can be canceled: its agent running, or queued for one. */ -async function startCancelableCleanup( - requestId: string -): Promise<{ cleanup: ReturnType }> { - const registeredBefore = cancelRegistrations.length - const cleanup = startCleanup(requestId) - await vi.waitFor(() => expect(cancelRegistrations.length).toBeGreaterThan(registeredBefore)) - return { cleanup } -} - -async function expectSecondAgentToFinish( - second: ReturnType -): Promise { - await vi.waitFor(() => expect(children).toHaveLength(2)) - const [firstAgent, secondAgent] = children - expect(firstAgent.kill).toHaveBeenCalled() - expect(secondAgent.kill).not.toHaveBeenCalled() - secondAgent.stdout.emit('data', Buffer.from('Second.')) - secondAgent.emit('close', 0) - await expect(second).resolves.toMatchObject({ status: 'cleaned', text: 'Second.' }) -} - -describe('overlapping dictation cleanups share a folder but stop independently', () => { - it('skipping the first stops only its agent while the second keeps running', async () => { - const first = startCleanup('a') - await vi.waitFor(() => expect(children).toHaveLength(1)) - const { cleanup: second } = await startCancelableCleanup('b') - expect(children).toHaveLength(2) - - cancelDictationCleanup('a') - - await expect(first).resolves.toEqual({ status: 'canceled' }) - await expectSecondAgentToFinish(second) - }) - - it('the first timing out stops only its agent while the second keeps running', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const first = startCleanup('a') - await vi.waitFor(() => expect(children).toHaveLength(1)) - await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) - const { cleanup: second } = await startCancelableCleanup('b') - expect(children).toHaveLength(2) - - await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) - - await expect(first).resolves.toEqual({ status: 'timed-out' }) - await expectSecondAgentToFinish(second) - }) - - // Codex runs one at a time under its home lock, so the second cleanup waits queued. - it('skipping a running Codex cleanup lets the queued one start and finish', async () => { - agentId = 'codex' - const first = startCleanup('a') - await vi.waitFor(() => expect(children).toHaveLength(1)) - const { cleanup: second } = await startCancelableCleanup('b') - expect(children).toHaveLength(1) - - cancelDictationCleanup('a') - - await expect(first).resolves.toEqual({ status: 'canceled' }) - await expectSecondAgentToFinish(second) - }) - - it('a running Codex cleanup timing out lets the queued one start and finish', async () => { - agentId = 'codex' - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const first = startCleanup('a') - await vi.waitFor(() => expect(children).toHaveLength(1)) - await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) - const { cleanup: second } = await startCancelableCleanup('b') - expect(children).toHaveLength(1) - - await vi.advanceTimersByTimeAsync(DICTATION_CLEANUP_TIMEOUT_MS / 2) - - await expect(first).resolves.toEqual({ status: 'timed-out' }) - await expectSecondAgentToFinish(second) - }) -}) diff --git a/src/main/startup/linux-runtime/linux-rttime-limit.test.ts b/src/main/startup/linux-runtime/linux-rttime-limit.test.ts deleted file mode 100644 index dad9c50398e..00000000000 --- a/src/main/startup/linux-runtime/linux-rttime-limit.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { allowsRealtimePriority, readZeroRtTimeLimit } from './linux-rttime-limit' - -let dir: string -beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-rttime-')) -}) -afterEach(() => rmSync(dir, { recursive: true, force: true })) - -function limitsFile(rtPrio: [string, string], rtTime: [string, string]): string { - const path = join(dir, 'limits') - writeFileSync( - path, - [ - 'Limit Soft Limit Hard Limit Units ', - `Max realtime priority ${rtPrio[0].padEnd(21)}${rtPrio[1].padEnd(21)}`, - `Max realtime timeout ${rtTime[0].padEnd(21)}${rtTime[1].padEnd(21)}us `, - '' - ].join('\n') - ) - return path -} - -describe('readZeroRtTimeLimit', () => { - it.each([ - [['0', '0'], { soft: '0', hard: '0' }], - [['0', 'unlimited'], { soft: '0', hard: 'unlimited' }], - [['200000', '0'], { soft: '200000', hard: '0' }], - [['unlimited', 'unlimited'], null], - [['200000', '200000'], null] - ] as const)('reads %j as %j', (rtTime, expected) => { - expect(readZeroRtTimeLimit('linux', limitsFile(['0', '0'], [...rtTime]))).toEqual(expected) - }) - - it('returns null off Linux, for an unreadable file, or without the limit line', () => { - const path = limitsFile(['0', '0'], ['0', '0']) - expect(readZeroRtTimeLimit('darwin', path)).toBeNull() - expect(readZeroRtTimeLimit('linux', join(dir, 'missing'))).toBeNull() - writeFileSync(path, 'Limit Soft Limit Hard Limit Units\n') - expect(readZeroRtTimeLimit('linux', path)).toBeNull() - }) -}) - -describe('allowsRealtimePriority', () => { - it.each([ - [['0', '0'], false], - [['0', '95'], true], - [['95', '95'], true] - ] as const)('treats RTPRIO %j as %s', (rtPrio, expected) => { - expect(allowsRealtimePriority('linux', limitsFile([...rtPrio], ['0', '0']))).toBe(expected) - }) - - it('is false off Linux or when the limits cannot be read', () => { - expect(allowsRealtimePriority('darwin', limitsFile(['95', '95'], ['0', '0']))).toBe(false) - expect(allowsRealtimePriority('linux', join(dir, 'missing'))).toBe(false) - }) -}) diff --git a/src/main/startup/process-failure/main-process-error-guards.test.ts b/src/main/startup/process-failure/main-process-error-guards.test.ts deleted file mode 100644 index 186ffed4fe7..00000000000 --- a/src/main/startup/process-failure/main-process-error-guards.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('main-process fatal error guards (issue #9441)', () => { - it('never throws when the breadcrumb sink fails', async () => { - vi.resetModules() - vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: vi.fn(() => { - throw new Error('sink offline') - }) - })) - const { recordFatalMainProcessError } = await import('./main-process-error-guards') - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - try { - expect(() => - recordFatalMainProcessError('main_uncaught_exception', 'not-an-error') - ).not.toThrow() - } finally { - consoleError.mockRestore() - } - }) - - it('bounds and isolates console formatting for hostile rejection values', async () => { - vi.resetModules() - const record = vi.fn() - vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: record - })) - const { recordFatalMainProcessError } = await import('./main-process-error-guards') - const hostileReason = { - toString(): never { - throw new Error('toString failed') - }, - [Symbol.for('nodejs.util.inspect.custom')](): never { - throw new Error('inspect failed') - } - } - const consoleError = vi.spyOn(console, 'error').mockImplementation((...values: unknown[]) => { - if (values.some((value) => typeof value !== 'string')) { - throw new Error('unsafe console formatting') - } - }) - - expect(() => - recordFatalMainProcessError('main_unhandled_rejection', hostileReason) - ).not.toThrow() - expect(record).toHaveBeenCalledWith( - 'main_unhandled_rejection', - expect.objectContaining({ errorName: 'object', errorMessage: '[unprintable value]' }), - 'main_unhandled_rejection' - ) - expect(consoleError).toHaveBeenCalledWith( - expect.stringMatching(/^\[main_unhandled_rejection\]/) - ) - expect(String(consoleError.mock.calls[0]?.[0]).length).toBeLessThan(5_000) - }) - - it('caps oversized rejection diagnostics before recording or logging', async () => { - vi.resetModules() - const record = vi.fn() - vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: record - })) - const { recordFatalMainProcessError } = await import('./main-process-error-guards') - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const error = Object.assign(new Error('m'.repeat(100_000)), { code: 'c'.repeat(100_000) }) - error.name = 'n'.repeat(100_000) - error.stack = Array.from({ length: 100 }, () => 's'.repeat(1_000)).join('\n') - - recordFatalMainProcessError('main_unhandled_rejection', error) - - const details = record.mock.calls[0]?.[1] as Record - expect(details.errorName).toHaveLength(100) - expect(details.errorMessage).toHaveLength(500) - expect(details.errorStack.length).toBeLessThanOrEqual(4_000) - expect(details.errorCode).toHaveLength(100) - expect(String(consoleError.mock.calls[0]?.[0]).length).toBeLessThan(5_000) - }) - - it('rethrows non-pipe errors outside the uncaughtException handler', async () => { - vi.resetModules() - vi.doMock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: vi.fn() - })) - const { installUncaughtPipeErrorGuard } = await import('./main-process-error-guards') - const originalOn = process.on.bind(process) - const originalOff = process.off.bind(process) - let handler: ((error: unknown) => void) | null = null - let scheduled: (() => void) | null = null - vi.spyOn(console, 'error').mockImplementation(() => {}) - vi.spyOn(process, 'on').mockImplementation(((event, listener) => { - if (event === 'uncaughtException') { - handler = listener as (error: unknown) => void - return process - } - return originalOn(event, listener) - }) as typeof process.on) - const offSpy = vi.spyOn(process, 'off').mockImplementation(((event, listener) => { - if (event === 'uncaughtException') { - return process - } - return originalOff(event, listener) - }) as typeof process.off) - vi.spyOn(globalThis, 'setImmediate').mockImplementation(((callback) => { - scheduled = callback as () => void - return {} as NodeJS.Immediate - }) as typeof setImmediate) - - installUncaughtPipeErrorGuard() - - const error = new Error('boom') - expect(() => handler?.(error)).not.toThrow() - expect(offSpy).toHaveBeenCalledWith('uncaughtException', handler) - expect(scheduled).not.toBeNull() - expect(() => scheduled?.()).toThrow(error) - }) -}) diff --git a/src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts b/src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts deleted file mode 100644 index 6e6d17932ed..00000000000 --- a/src/main/startup/shell-environment/hydrate-shell-path.windows.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import 'node:events' - -import { - _resetHydrateShellPathCache, - configureWindowsShellPathHydration, - hydrateShellPath, - mergePathSegments, - type HydrationResult -} from './hydrate-shell-path' - -const { spawnMock } = vi.hoisted(() => ({ - spawnMock: vi.fn() -})) - -vi.mock('child_process', () => ({ - spawn: spawnMock -})) - -type HydrationSpawner = (shell: string) => Promise - -type Deferred = { - promise: Promise - resolve: (value: T) => void -} - -function deferred(): Deferred { - let resolve!: (value: T) => void - const promise = new Promise((next) => { - resolve = next - }) - return { promise, resolve } -} - -describe('Windows shell PATH hydration', () => { - const originalPath = process.env.PATH - - beforeEach(() => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - _resetHydrateShellPathCache() - spawnMock.mockReset() - }) - - afterEach(() => { - vi.restoreAllMocks() - if (originalPath === undefined) { - delete process.env.PATH - } else { - process.env.PATH = originalPath - } - }) - - it('serializes shell changes, discards stale results, and caches the newest request', async () => { - const powerShellResult = deferred() - const gitBashResult = deferred() - let activeProbes = 0 - let maxActiveProbes = 0 - const powerShellSpawner = vi.fn(async () => { - activeProbes += 1 - maxActiveProbes = Math.max(maxActiveProbes, activeProbes) - const result = await powerShellResult.promise - activeProbes -= 1 - return result - }) - const gitBashSpawner = vi.fn(async () => { - activeProbes += 1 - maxActiveProbes = Math.max(maxActiveProbes, activeProbes) - const result = await gitBashResult.promise - activeProbes -= 1 - return result - }) - process.env.PATH = 'C:\\Windows' - const powerShellReady = hydrateShellPath({ spawner: powerShellSpawner, force: true }) - const powerShellMerged = powerShellReady.then((result) => mergePathSegments(result.segments)) - await vi.waitFor(() => expect(powerShellSpawner).toHaveBeenCalledWith('powershell.exe')) - - configureWindowsShellPathHydration('git-bash', 'C:\\Git\\bin\\bash.exe') - const gitBashReady = hydrateShellPath({ spawner: gitBashSpawner, force: true }) - const gitBashMerged = gitBashReady.then((result) => mergePathSegments(result.segments)) - const cachedGitBashReady = hydrateShellPath({ spawner: gitBashSpawner }) - expect(cachedGitBashReady).toBe(gitBashReady) - expect(gitBashSpawner).not.toHaveBeenCalled() - - powerShellResult.resolve({ - segments: ['C:\\stale-powershell'], - ok: true, - failureReason: 'none' - }) - await vi.waitFor(() => expect(gitBashSpawner).toHaveBeenCalledWith('C:\\Git\\bin\\bash.exe')) - gitBashResult.resolve({ - segments: ['C:\\current-git-bash'], - ok: true, - failureReason: 'none' - }) - await Promise.all([powerShellMerged, gitBashMerged, cachedGitBashReady]) - - expect(maxActiveProbes).toBe(1) - expect(powerShellSpawner).toHaveBeenCalledOnce() - expect(gitBashSpawner).toHaveBeenCalledOnce() - expect(process.env.PATH).toBe('C:\\current-git-bash;C:\\Windows') - }) - - it('discards an active probe when the configured shell has no profile', async () => { - const powerShellResult = deferred() - const spawner = vi.fn(() => powerShellResult.promise) - const staleReady = hydrateShellPath({ spawner, force: true }) - await vi.waitFor(() => expect(spawner).toHaveBeenCalledOnce()) - - configureWindowsShellPathHydration('cmd.exe') - const currentReady = hydrateShellPath({ spawner }) - powerShellResult.resolve({ - segments: ['C:\\stale-powershell'], - ok: true, - failureReason: 'none' - }) - - await expect(Promise.all([staleReady, currentReady])).resolves.toEqual([ - { segments: [], ok: false, failureReason: 'no_shell' }, - { segments: [], ok: false, failureReason: 'no_shell' } - ]) - expect(spawner).toHaveBeenCalledOnce() - }) - - it('removes profile entries when switching to a shell without a profile', () => { - process.env.PATH = 'C:\\Inherited;C:\\Windows' - mergePathSegments(['C:\\PowerShell-profile', 'C:\\Inherited']) - - configureWindowsShellPathHydration('cmd.exe') - - expect(process.env.PATH).toBe('C:\\Inherited;C:\\Windows') - }) - - it('replaces profile entries introduced by the previously configured shell', () => { - process.env.PATH = 'C:\\Inherited;C:\\Windows' - mergePathSegments(['C:\\PowerShell-profile', 'C:\\Inherited']) - - configureWindowsShellPathHydration('git-bash', 'C:\\Git\\bin\\bash.exe') - mergePathSegments(['C:\\GitBash-profile', 'C:\\Inherited']) - - expect(process.env.PATH).toBe('C:\\GitBash-profile;C:\\Inherited;C:\\Windows') - }) -}) diff --git a/src/main/startup/windows-startup/windows-renderer-runtime-files.test.ts b/src/main/startup/windows-startup/windows-renderer-runtime-files.test.ts deleted file mode 100644 index c4add320906..00000000000 --- a/src/main/startup/windows-startup/windows-renderer-runtime-files.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { electronApp, handleFailure } = vi.hoisted(() => ({ - electronApp: { isPackaged: true }, - handleFailure: vi.fn() -})) - -vi.mock('electron', () => ({ app: electronApp })) -vi.mock('../main-process-preflight-failure', () => ({ - handleMainProcessPreflightFailure: handleFailure -})) - -import { - ensureWindowsRendererRuntimeFiles, - findUnusableRendererRuntimeFile -} from './windows-renderer-runtime-files' - -let installDir: string -let execPath: string - -beforeEach(() => { - installDir = mkdtempSync(join(os.tmpdir(), 'orca-renderer-runtime-files-')) - execPath = join(installDir, 'Orca.exe') -}) - -afterEach(() => { - rmSync(installDir, { recursive: true, force: true }) -}) - -describe('findUnusableRendererRuntimeFile', () => { - it('accepts a complete install', () => { - writeFileSync(join(installDir, 'ffmpeg.dll'), 'MZ') - expect(findUnusableRendererRuntimeFile(execPath)).toBeNull() - }) - - it('reports a DLL an unfinished update has not written yet', () => { - expect(findUnusableRendererRuntimeFile(execPath)).toBe('ffmpeg.dll') - }) - - it('reports a DLL that is still empty', () => { - writeFileSync(join(installDir, 'ffmpeg.dll'), '') - expect(findUnusableRendererRuntimeFile(execPath)).toBe('ffmpeg.dll') - }) -}) - -describe('ensureWindowsRendererRuntimeFiles', () => { - const originalPlatform = process.platform - const originalExecPath = process.execPath - - const setPlatform = (value: NodeJS.Platform): void => { - Object.defineProperty(process, 'platform', { value, configurable: true }) - } - - beforeEach(() => { - handleFailure.mockReset() - electronApp.isPackaged = true - setPlatform('win32') - Object.defineProperty(process, 'execPath', { value: execPath, configurable: true }) - vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - afterEach(() => { - setPlatform(originalPlatform) - Object.defineProperty(process, 'execPath', { value: originalExecPath, configurable: true }) - vi.restoreAllMocks() - }) - - it('fails the preflight with an explanation when ffmpeg.dll is missing', () => { - expect(ensureWindowsRendererRuntimeFiles(false)).toBe(false) - expect(handleFailure).toHaveBeenCalledTimes(1) - expect(String(handleFailure.mock.calls[0][0])).toContain( - 'ffmpeg.dll is missing, empty, or in use' - ) - }) -}) diff --git a/src/main/window/renderer-recovery/renderer-liveness-at-death.test.ts b/src/main/window/renderer-recovery/renderer-liveness-at-death.test.ts deleted file mode 100644 index 90d4d0b74b0..00000000000 --- a/src/main/window/renderer-recovery/renderer-liveness-at-death.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { EventEmitter } from 'node:events' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const recordCoalescedDurableCrashBreadcrumb = vi.fn() -vi.mock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ - recordCoalescedDurableCrashBreadcrumb: (...args: unknown[]) => - recordCoalescedDurableCrashBreadcrumb(...args) -})) - -import { trackRendererLivenessAtDeath } from './renderer-liveness-at-death' - -function createWindow(state: { minimized?: boolean; visible?: boolean; destroyed?: boolean } = {}) { - const contents = new EventEmitter() - const window = Object.assign(new EventEmitter(), { - webContents: contents, - isDestroyed: () => state.destroyed === true, - isMinimized: () => state.minimized === true, - isVisible: () => state.visible !== false, - isFocused: () => false - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the tracker only reads the emitter API and the four getters stubbed above. - return { window: window as unknown as Electron.BrowserWindow, contents } -} - -const MAIN_FRAME_NAVIGATION = { isMainFrame: true, isSameDocument: false } - -describe('trackRendererLivenessAtDeath', () => { - let now = 0 - beforeEach(() => { - now = 1_000 - recordCoalescedDurableCrashBreadcrumb.mockClear() - }) - - it('reports how long the renderer has been hung, and clears it on responsive', () => { - const { window, contents } = createWindow({ minimized: true }) - const tracker = trackRendererLivenessAtDeath(window, () => now) - contents.emit('did-finish-load') - window.emit('unresponsive') - now += 5_000 - window.emit('unresponsive') - now += 40_000 - - expect(recordCoalescedDurableCrashBreadcrumb).toHaveBeenCalledWith( - expect.objectContaining({ name: 'renderer_unresponsive' }) - ) - window.emit('responsive') - expect(recordCoalescedDurableCrashBreadcrumb).toHaveBeenLastCalledWith( - expect.objectContaining({ name: 'renderer_responsive', data: { hungForMs: 45_000 } }) - ) - expect(tracker.takeAtRendererGone().rendererUnresponsiveForMs).toBeUndefined() - - window.emit('unresponsive') - now += 30_000 - expect(tracker.takeAtRendererGone()).toMatchObject({ - rendererUnresponsiveForMs: 30_000, - rendererDocumentLoaded: true, - mainWindowState: 'minimized' - }) - }) - - it('does not carry a hang into the next document after a recovery reload', () => { - const { window, contents } = createWindow() - const tracker = trackRendererLivenessAtDeath(window, () => now) - window.emit('unresponsive') - contents.emit('did-start-navigation', MAIN_FRAME_NAVIGATION) - - expect(tracker.takeAtRendererGone().rendererUnresponsiveForMs).toBeUndefined() - }) - - it('reports a failed main-frame load as not loaded, though did-finish-load follows it', () => { - const { window, contents } = createWindow() - const tracker = trackRendererLivenessAtDeath(window, () => now) - contents.emit('did-start-navigation', MAIN_FRAME_NAVIGATION) - contents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///missing', true) - contents.emit('did-finish-load') - now += 12_000 - - expect(tracker.takeAtRendererGone()).toMatchObject({ - rendererDocumentLoaded: false, - rendererDocumentLoadFailed: true, - rendererDocumentAgeMs: 12_000 - }) - }) - - it('ignores aborted loads, subframe failures and same-document navigations', () => { - const { window, contents } = createWindow() - const tracker = trackRendererLivenessAtDeath(window, () => now) - contents.emit('did-start-navigation', MAIN_FRAME_NAVIGATION) - contents.emit('did-fail-load', {}, -3, 'ERR_ABORTED', 'file:///app', true) - contents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///frame', false) - contents.emit('did-finish-load') - now += 5_000 - contents.emit('did-start-navigation', { isMainFrame: true, isSameDocument: true }) - contents.emit('did-start-navigation', { isMainFrame: false, isSameDocument: false }) - - const state = tracker.takeAtRendererGone() - expect(state).toMatchObject({ rendererDocumentLoaded: true, rendererDocumentAgeMs: 5_000 }) - expect(state.rendererDocumentLoadFailed).toBeUndefined() - }) -}) diff --git a/src/main/window/renderer-relays/session-tab-close-request-relay.test.ts b/src/main/window/renderer-relays/session-tab-close-request-relay.test.ts deleted file mode 100644 index 62c6a9e939a..00000000000 --- a/src/main/window/renderer-relays/session-tab-close-request-relay.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { EventEmitter } from 'node:events' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const ipcEmitter = new EventEmitter() -const ipcMainMock = { - on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.on(channel, listener) - }), - removeListener: vi.fn((channel: string, listener: (...args: unknown[]) => void) => { - ipcEmitter.removeListener(channel, listener) - }) -} - -vi.mock('electron', () => ({ ipcMain: ipcMainMock })) - -function createMainWindow() { - const webContents = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - send: vi.fn() - }) - const mainWindow = Object.assign(new EventEmitter(), { - isDestroyed: () => false, - webContents - }) - return { mainWindow, webContents } -} - -describe('requestSessionTabCloseFromRenderer', () => { - beforeEach(() => { - vi.useRealTimers() - ipcEmitter.removeAllListeners() - ipcMainMock.on.mockClear() - ipcMainMock.removeListener.mockClear() - }) - - it('waits for the targeted renderer acknowledgement', async () => { - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') - const request = webContents.send.mock.calls[0]?.[1] as { - requestId: string - tabId: string - worktreeId: string - expiresAt: number - } - - expect(request).toMatchObject({ tabId: 'tab-1', worktreeId: 'wt-1' }) - expect(request.expiresAt).toBeGreaterThan(Date.now()) - ipcEmitter.emit('ui:sessionTabCloseResponse', { sender: {} }, { requestId: request.requestId }) - let settled = false - void pending.finally(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - - ipcEmitter.emit( - 'ui:sessionTabCloseResponse', - { sender: webContents }, - { requestId: request.requestId } - ) - await expect(pending).resolves.toBeUndefined() - }) - - it('propagates renderer cancellation', async () => { - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-pinned', 'wt-1') - const request = webContents.send.mock.calls[0]?.[1] as { requestId: string } - - ipcEmitter.emit( - 'ui:sessionTabCloseResponse', - { sender: webContents }, - { requestId: request.requestId, error: 'session_tab_close_canceled' } - ) - - await expect(pending).rejects.toThrow('session_tab_close_canceled') - }) - - it.each(['destroyed', 'render-process-gone', 'did-start-loading'])( - 'rejects when web contents emits %s', - async (eventName) => { - const { requestSessionTabCloseFromRenderer } = - await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') - - webContents.emit(eventName) - - await expect(pending).rejects.toThrow('renderer_unavailable') - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) - } - ) - - it('times out after the renderer confirmation lease and response grace', async () => { - vi.useFakeTimers() - vi.setSystemTime(1_000) - const { requestSessionTabCloseFromRenderer } = await import('./session-tab-close-request-relay') - const { mainWindow, webContents } = createMainWindow() - const pending = requestSessionTabCloseFromRenderer(mainWindow as never, 'tab-1', 'wt-1') - const request = webContents.send.mock.calls[0]?.[1] as { expiresAt: number } - const rejection = expect(pending).rejects.toThrow('session_tab_close_timeout') - - await vi.advanceTimersByTimeAsync(request.expiresAt - Date.now() + 5_000) - - await rejection - expect(ipcEmitter.listenerCount('ui:sessionTabCloseResponse')).toBe(0) - }) -}) diff --git a/src/main/wsl/filesystem/wsl-automount-root.test.ts b/src/main/wsl/filesystem/wsl-automount-root.test.ts deleted file mode 100644 index aaf96e137f8..00000000000 --- a/src/main/wsl/filesystem/wsl-automount-root.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// The gate's running reads go through wsl.exe; these tests feed the cache their own lists. -vi.mock('../discovery/distro-catalog', () => ({ - listRunningWslDistrosAsync: vi.fn(), - listWslDistrosAsync: vi.fn() -})) - -import { - _resetWslBackgroundDistroGateForTests, - noteWslDistroMayHaveStopped, - noteWslDistroWoken, - WSL_STOP_SETTLE_MS -} from '../discovery/wsl-background-distro-gate' -import { - _resetRunningWslDistroCacheForTests, - resolveRunningWslDistros -} from '../discovery/wsl-running-distro-cache' -import { - followWslAutomountRoots, - knownWslAutomountRoots, - onWslAutomountRootsChanged, - parseWslAutomountRoot, - resetWslAutomountRootsForTests, - WSL_AUTOMOUNT_WAKE_REREAD_INTERVAL_MS -} from './wsl-automount-root' - -let now = 1_000 -const unfollows: (() => void)[] = [] - -function follow(read: (distro: string) => Promise): void { - unfollows.push(followWslAutomountRoots(() => ['Ubuntu'], read)) -} - -/** One confirmed running-distro list, probed at the current test clock. */ -async function listRunning(distros: string[]): Promise { - await resolveRunningWslDistros(async () => distros) -} - -beforeEach(() => { - now = 1_000 - vi.spyOn(performance, 'now').mockImplementation(() => now) -}) - -afterEach(() => { - // The real cache keeps its listeners across tests. - unfollows.splice(0).forEach((unfollow) => unfollow()) - resetWslAutomountRootsForTests() - _resetWslBackgroundDistroGateForTests() - _resetRunningWslDistroCacheForTests() - vi.restoreAllMocks() -}) - -describe('parseWslAutomountRoot', () => { - it.each([ - ['/mnt/c/', '/mnt/'], - ['/c/', '/'], - ['/windows/c', '/windows/'], - ['not a path', null], - [null, null] - ])('%s → %s', (value, expected) => { - expect(parseWslAutomountRoot(value)).toBe(expected) - }) -}) - -describe('followWslAutomountRoots', () => { - it("reads a project distro's root once it runs, and again after it restarts", async () => { - const read = vi.fn(async () => '/') - const changed = vi.fn() - onWslAutomountRootsChanged(changed) - follow(read) - await listRunning(['Ubuntu', 'Debian']) - await vi.waitFor(() => expect(knownWslAutomountRoots()).toEqual(['/mnt/', '/'])) - // Only the project distros, and only once while it runs. - await listRunning(['Ubuntu']) - expect(read).toHaveBeenCalledExactlyOnceWith('Ubuntu') - expect(changed).toHaveBeenCalledOnce() - await listRunning([]) - expect(knownWslAutomountRoots()).toEqual(['/mnt/']) - now += WSL_STOP_SETTLE_MS - await listRunning(['Ubuntu']) - await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2)) - }) - - it('never reads from a list probed while the distro was still stopping, only from a settled one', async () => { - const read = vi.fn(async () => '/') - follow(read) - noteWslDistroMayHaveStopped('Ubuntu') - // wsl.exe still lists a terminating distro; reading its root now would boot it again. - now += WSL_STOP_SETTLE_MS - 1 - await listRunning(['Ubuntu']) - expect(read).not.toHaveBeenCalled() - - now += 1 - await listRunning(['Ubuntu']) - expect(read).toHaveBeenCalledExactlyOnceWith('Ubuntu') - }) -}) - -describe('followWslAutomountRoots: one guest read per distro start', () => { - /** Settles the reads one confirmed list started before the next probe. */ - async function observeRunning(times: number): Promise { - for (let i = 0; i < times; i++) { - await listRunning(['Ubuntu']) - await new Promise((resolve) => setImmediate(resolve)) - } - } - - it('picks up a root edited across a restart no probe saw, once Orca wakes the distro', async () => { - let root = '/old/' - const changed = vi.fn() - onWslAutomountRootsChanged(changed) - follow(async () => root) - await observeRunning(1) - expect(knownWslAutomountRoots()).toEqual(['/mnt/', '/old/']) - - // An unchanged re-read leaves listeners (the git router's cache) alone. - now += WSL_AUTOMOUNT_WAKE_REREAD_INTERVAL_MS - noteWslDistroWoken('Ubuntu') - now += 1 - await observeRunning(1) - expect(changed).toHaveBeenCalledOnce() - - // Stopped and started again between probes, wsl.conf edited meanwhile. - root = '/new/' - now += WSL_AUTOMOUNT_WAKE_REREAD_INTERVAL_MS - noteWslDistroWoken('Ubuntu') - now += 1 - await observeRunning(1) - expect(knownWslAutomountRoots()).toEqual(['/mnt/', '/new/']) - - root = '/mnt/' - now += WSL_AUTOMOUNT_WAKE_REREAD_INTERVAL_MS - noteWslDistroWoken('Ubuntu') - now += 1 - await observeRunning(1) - expect(knownWslAutomountRoots()).toEqual(['/mnt/']) - }) -}) diff --git a/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts b/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts deleted file mode 100644 index a690af455ae..00000000000 --- a/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const hostRows = vi.hoisted(() => new Map()) -const updates = vi.hoisted((): string[] => []) -const failNextUpdate = vi.hoisted(() => ({ value: false })) -const throwOnUpdate = vi.hoisted(() => ({ value: false })) -const updateAttempts = vi.hoisted(() => ({ count: 0 })) -const failOnUpdateOf = vi.hoisted((): { id: string | null; thenAlso: string | null } => ({ - id: null, - thenAlso: null -})) - -vi.mock('./wsl-host-service-instance', () => ({ - getWslHostService: () => ({ - recordForEnvironment: () => ({ distro: 'Ubuntu' }), - ensureForRuntimeCall: async () => {} - }) -})) -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: () => ({ id: 'wsl:Ubuntu', runtimeId: 'rt-1' }) -})) -vi.mock('../../../shared/remote-runtime/host-catalog/runtime-environments', () => ({ - getPreferredPairingOffer: () => ({}) -})) -vi.mock('../../../shared/remote-runtime/pairing/pairing', () => ({ - encodePairingOffer: () => 'code', - parsePairingCode: () => ({ code: 'code' }) -})) -vi.mock('../../managed-server/migration/catalog/orcad-migration-request', () => ({ - sendSupportedMigrationRequest: async ( - _pairing: unknown, - method: string, - params: { id: string; updates?: { enabled: boolean } } - ) => { - const row = hostRows.get(params.id) - if (method === 'automation.show') { - return row - ? { ok: true, result: { automation: row } } - : { ok: false, error: { message: 'Automation not found.' } } - } - updateAttempts.count++ - if (throwOnUpdate.value) { - throw new Error('connect ECONNREFUSED') - } - if (failNextUpdate.value || failOnUpdateOf.id === params.id) { - failNextUpdate.value = false - // Then the host drops: the next update (turning one back on) fails too. - failOnUpdateOf.id = failOnUpdateOf.thenAlso - failOnUpdateOf.thenAlso = null - return { ok: false, error: { message: 'busy' } } - } - updates.push(params.id) - if (row) { - row.enabled = params.updates?.enabled ?? true - } - return { ok: true, result: {} } - } -})) - -import { enableWslHostAutomations } from './wsl-host-automation-enable' -import { disableWslHostAutomations, restoreWslHostAutomations } from './wsl-host-automation-disable' - -beforeEach(() => { - hostRows.clear() - updates.length = 0 - throwOnUpdate.value = false - updateAttempts.count = 0 -}) - -describe('enableWslHostAutomations', () => { - it('turns on only automations still exactly as the move left them', async () => { - hostRows.set('untouched', { enabled: false, updatedAt: 10 }) - hostRows.set('edited-on-host', { enabled: false, updatedAt: 99 }) - hostRows.set('already-on', { enabled: true, updatedAt: 10 }) - await enableWslHostAutomations('/user-data', 'wsl:Ubuntu', [ - { id: 'untouched', updatedAt: 10 }, - { id: 'edited-on-host', updatedAt: 10 }, - { id: 'already-on', updatedAt: 10 }, - { id: 'deleted-on-host', updatedAt: 10 } - ]) - expect(updates).toEqual(['untouched']) - }) -}) - -describe('undo on the host', () => { - it('turns back on what it turned off before throwing, so a refused undo changes nothing', async () => { - hostRows.set('a', { enabled: true, updatedAt: 1 }) - hostRows.set('b', { enabled: true, updatedAt: 1 }) - failOnUpdateOf.id = 'b' - await expect(disableWslHostAutomations('/user-data', 'wsl:Ubuntu', ['a', 'b'])).rejects.toThrow( - 'wsl_move_automation_disable_failed:busy' - ) - expect(hostRows.get('a')?.enabled).toBe(true) - expect(hostRows.get('b')?.enabled).toBe(true) - }) - - it('carries what it could not turn back on on the error', async () => { - hostRows.set('a', { enabled: true, updatedAt: 1 }) - hostRows.set('b', { enabled: true, updatedAt: 1 }) - failOnUpdateOf.id = 'b' - failOnUpdateOf.thenAlso = 'a' - const error = await disableWslHostAutomations('/user-data', 'wsl:Ubuntu', ['a', 'b']).catch( - (thrown: unknown) => thrown - ) - expect(error).toMatchObject({ leftOff: ['a'] }) - expect(hostRows.get('a')?.enabled).toBe(false) - }) - - it('stops at a host that stops answering, leaving the rest off rather than wait on each', async () => { - for (const id of ['a', 'b', 'c']) { - hostRows.set(id, { enabled: false, updatedAt: 1 }) - } - throwOnUpdate.value = true - const error = await restoreWslHostAutomations('/user-data', 'wsl:Ubuntu', [ - 'a', - 'b', - 'c' - ]).catch((thrown: unknown) => thrown) - expect(error).toMatchObject({ leftOff: ['a', 'b', 'c'] }) - expect(updateAttempts.count).toBe(1) - }) -}) diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx deleted file mode 100644 index e9077348be8..00000000000 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx +++ /dev/null @@ -1,96 +0,0 @@ -// @vitest-environment happy-dom -import { useState } from 'react' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' -import { useAgentPickerDraftScope } from './agent-launch-picker-drafts' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger -} from '@/components/ui/dropdown-menu' -import { TooltipProvider } from '@/components/ui/tooltip' -import type { - AgentPickerDraft, - AgentPickerEntry -} from '../../../../shared/agent-launch/picker/agent-launch-picker' -vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) -afterEach(cleanup) - -const efforts = [ - { value: 'low', label: 'Low' }, - { value: 'high', label: 'High' } -] -const entry: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - defaultSurface: 'terminal', - surfaces: ['chat', 'terminal'], - terminal: {}, - structured: {}, - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [ - { id: 'astra', label: 'Astra', isDefault: true, efforts }, - { id: 'luna', label: 'Luna', isDefault: false, efforts } - ] - }, - rows: [{ kind: 'cli', agent: 'codex', chat: true }] -} - -// A form that re-derives each entry's draft from what it saved and resets its draft scope, as Automations do. -function Form({ query, onPick }: { query: string; onPick: (draft?: AgentPickerDraft) => void }) { - const [saved, setSaved] = useState({}) - const draftScope = useAgentPickerDraftScope(saved.model) - return ( - - - Agent - - ({ agent: 'codex', surface: 'terminal', choices: { ...saved } })} - runLaunch={(_row, draft) => { - onPick(draft) - if (draft) { - setSaved(draft.choices) - } - }} - /> - - - - ) -} - -it.each([['a search-result row', 'astra low']])( - 'applies each model and effort picked in %s setup to the form and keeps the panel on them', - (_row, query) => { - const onPick = vi.fn() - render(
) - fireEvent.click(screen.getAllByRole('button', { name: 'Configure Codex' })[0]) - fireEvent.click(screen.getByRole('option', { name: 'Luna' })) - expect(onPick).toHaveBeenLastCalledWith( - expect.objectContaining({ choices: expect.objectContaining({ model: 'luna' }) }) - ) - expect(screen.getByRole('option', { name: 'Luna' }).getAttribute('data-current')).toBe('true') - fireEvent.click(screen.getByRole('radio', { name: 'High' })) - expect(onPick).toHaveBeenLastCalledWith( - expect.objectContaining({ - choices: expect.objectContaining({ model: 'luna', options: { effort: 'high' } }) - }) - ) - // Typed Arguments stay staged in the panel across a close, after the form took its picks. - fireEvent.change(screen.getByRole('textbox', { name: 'Arguments' }), { - target: { value: '--search' } - }) - fireEvent.keyDown(screen.getByRole('menu', { name: 'Configure Codex' }), { key: 'Escape' }) - expect(screen.queryByRole('menu', { name: 'Configure Codex' })).toBeNull() - fireEvent.click(screen.getAllByRole('button', { name: 'Configure Codex' })[0]) - expect(screen.getByRole('textbox', { name: 'Arguments' })).toHaveProperty('value', '--search') - } -) diff --git a/src/renderer/src/components/automations/authoring/AutomationEditorDialog.test.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.test.tsx deleted file mode 100644 index bad7ad2bf97..00000000000 --- a/src/renderer/src/components/automations/authoring/AutomationEditorDialog.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -// @vitest-environment happy-dom - -import React from 'react' -import { cleanup, render, screen } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import type { AutomationSchedulePreset } from '../../../../../shared/automations/automation-definition' -import { AutomationEditorDialog, type AutomationDraft } from './AutomationEditorDialog' -import { getSchedulePresetDraft } from './AutomationSchedulePicker' - -vi.mock('./AutomationEditorPromptEditor', () => ({ - AutomationEditorPromptEditor: () => null, - getAutomationPromptEditorRoot: () => null -})) -vi.mock('./AutomationEditorSettingsSidebar', () => ({ - AutomationEditorSettingsSidebar: ({ - onDraftChange - }: { - onDraftChange: (updater: (current: AutomationDraft) => AutomationDraft) => void - }) => { - const selectPreset = (preset: AutomationSchedulePreset): void => - onDraftChange((current) => ({ ...current, ...getSchedulePresetDraft(current, preset) })) - const selectModel = (model: string): void => - onDraftChange((current) => ({ ...current, launchPreferences: { model } })) - return ( - <> - - - - - - ) - } -})) - -const DRAFT: AutomationDraft = { - name: '', - prompt: '', - agentId: 'claude', - extraAgentArgs: '', - projectId: 'repo-1', - workspaceMode: 'existing', - workspaceId: '', - baseBranch: '', - reuseSession: false, - precheckCommand: '', - precheckTimeoutSeconds: '60', - preset: 'weekdays', - time: '09:00', - dayOfWeek: '1', - customSchedule: '', - missedRunGraceMinutes: '720', - savedSchedule: null, - scheduleWarning: null -} - -function Harness({ - isEditing = false, - initialDraft = DRAFT -}: { - isEditing?: boolean - initialDraft?: AutomationDraft -}): React.JSX.Element { - const [open, setOpen] = React.useState(true) - const [draft, setDraft] = React.useState(initialDraft) - return ( - - - repoId} - repoMap={new Map()} - worktrees={[]} - settings={null} - draft={draft} - onProjectChange={vi.fn()} - onOpenChange={setOpen} - onDraftChange={(updater) => setDraft(updater)} - onSetupDecisionTouched={vi.fn()} - onApplyTemplate={vi.fn()} - onSave={vi.fn()} - /> - - ) -} - -function backdrop(): Element { - const overlay = document.querySelector('[data-slot="dialog-overlay"]') - if (!overlay) { - throw new Error('Missing dialog backdrop') - } - return overlay -} - -afterEach(cleanup) - -describe('AutomationEditorDialog outside dismissal', () => { - it('keeps an edited draft open on a backdrop click while Escape still discards it', async () => { - const user = userEvent.setup() - render() - await user.type(screen.getByLabelText('Automation name'), 'Nightly') - - await user.click(backdrop()) - - expect(screen.getByLabelText('Automation name').value).toBe('Nightly') - await user.keyboard('{Escape}') - expect(screen.queryByRole('dialog')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts b/src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts deleted file mode 100644 index 76d9b1b8b28..00000000000 --- a/src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ProjectHostSetup } from '../../../../../shared/project-types' -import type { Repo } from '../../../../../shared/repo-types' -import { - getVisibleAutomationSetupDecision, - resolveAutomationSetupDecisionForSave -} from './automation-setup-decision' - -const repo: Repo = { - id: 'repo-1', - path: '/repo', - displayName: 'orca', - badgeColor: 'blue', - addedAt: 1, - kind: 'git', - hookSettings: { - mode: 'override', - setupRunPolicy: 'run-by-default', - scripts: { setup: 'pnpm install', archive: '' } - } -} - -function setup(overrides: Partial = {}): ProjectHostSetup { - return { - id: 'setup-1', - projectId: 'project-1', - hostId: 'local', - repoId: 'repo-1', - path: '/repo', - displayName: 'orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1, - ...overrides - } -} - -describe('automation setup decision defaults', () => { - it('uses only the selected repo host setup and refuses an ambiguous repo table', () => { - const remote = { ...repo, connectionId: 'builder' } - const localSetup = setup({ - hookSettings: { - mode: 'override', - setupRunPolicy: 'run-by-default', - scripts: { setup: 'local setup', archive: '' } - } - }) - const remoteSetup = setup({ - hostId: 'ssh:builder', - hookSettings: { - mode: 'override', - setupRunPolicy: 'skip-by-default', - scripts: { setup: 'remote setup', archive: '' } - } - }) - const args = { - workspaceMode: 'new_per_run' as const, - repoId: repo.id, - projectHostSetups: [localSetup, remoteSetup] - } - expect(getVisibleAutomationSetupDecision({ ...args, repos: [remote] })).toBe('skip') - expect(getVisibleAutomationSetupDecision({ ...args, repos: [repo, remote] })).toBeUndefined() - }) - - it('shows setup choice for shared orca.yaml setup and default tabs', () => { - expect( - getVisibleAutomationSetupDecision({ - workspaceMode: 'new_per_run', - repoId: 'repo-1', - repos: [ - { - ...repo, - hookSettings: { - mode: 'override', - setupRunPolicy: 'run-by-default', - scripts: { setup: '', archive: '' } - } - } - ], - projectHostSetups: [], - yamlHooks: { - scripts: { setup: 'pnpm install' }, - defaultTabs: [] - } - }) - ).toBe('run') - - expect( - getVisibleAutomationSetupDecision({ - workspaceMode: 'new_per_run', - repoId: 'repo-1', - repos: [ - { - ...repo, - hookSettings: { - mode: 'override', - setupRunPolicy: 'skip-by-default', - scripts: { setup: '', archive: '' } - } - } - ], - projectHostSetups: [], - yamlHooks: { - scripts: {}, - defaultTabs: [{ title: 'Dev', command: 'pnpm dev' }] - } - }) - ).toBe('skip') - }) - - it('fails closed when saving before shared hook inspection is available', () => { - expect( - resolveAutomationSetupDecisionForSave({ - workspaceMode: 'new_per_run', - repoId: 'repo-1', - repos: [ - { - ...repo, - hookSettings: { - mode: 'override', - setupRunPolicy: 'run-by-default', - scripts: { setup: '', archive: '' } - } - } - ], - projectHostSetups: [], - draftSetupDecision: undefined - }) - ).toBe('skip') - }) -}) diff --git a/src/renderer/src/components/browser-pane/host-guest/viewport/browser-page-viewport.test.ts b/src/renderer/src/components/browser-pane/host-guest/viewport/browser-page-viewport.test.ts deleted file mode 100644 index ca4f84a5795..00000000000 --- a/src/renderer/src/components/browser-pane/host-guest/viewport/browser-page-viewport.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it } from 'vitest' -import type { BrowserGuestMetadata } from '../../../../../../shared/browser/guest-lifecycle/browser-guest-metadata' -import { - clearBrowserGuestMetadata, - subscribeBrowserGuestMetadata -} from '../metadata/browser-guest-metadata-cache' -import { registerPersistentWebview, unregisterPersistentWebview } from '../webview-registry' -import { - getBrowserOverlaySlotViewport, - ensureBrowserPageViewport, - registerBrowserOverlaySlotViewport, - removeBrowserPageViewport, - setBrowserPageAgentViewportSize, - setBrowserPageViewportPresetSize -} from './browser-page-viewport' - -function mountSlotViewport(workspaceTabId: string): HTMLDivElement { - const root = document.createElement('div') - root.className = 'relative flex min-h-0 flex-1 flex-col' - document.body.appendChild(root) - registerBrowserOverlaySlotViewport(workspaceTabId, root) - return root -} - -afterEach(() => { - clearBrowserGuestMetadata() - for (const id of ['page-1', 'page-2']) { - unregisterPersistentWebview(id) - removeBrowserPageViewport(id) - setBrowserPageAgentViewportSize(id, null) - setBrowserPageViewportPresetSize(id, null) - } - for (const id of ['workspace-1']) { - getBrowserOverlaySlotViewport(id)?.remove() - registerBrowserOverlaySlotViewport(id, null) - } -}) - -describe('local guest metadata disposal', () => { - function prepareGuest() { - let finish!: (value: BrowserGuestMetadata | undefined) => void - Object.defineProperty(window, 'api', { - configurable: true, - value: { - browser: { - unregisterGuest: async () => {}, - getGuestMetadata: () => new Promise((resolve) => (finish = resolve)) - } - } - }) - const root = mountSlotViewport('workspace-1') - const viewport = ensureBrowserPageViewport('page-1', 'workspace-1')! - let readable = true - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: DOM tag with the native identity method used by these owners. - const webview = Object.assign(document.createElement('webview'), { - getWebContentsId: () => { - if (!readable) { - throw new Error('guest detached') - } - return 41 - } - }) as Electron.WebviewTag - const remove = webview.remove.bind(webview) - webview.remove = () => { - readable = false - remove() - } - viewport.content.appendChild(webview) - registerPersistentWebview('page-1', webview) - const observed: (BrowserGuestMetadata | null)[] = [] - const detach = subscribeBrowserGuestMetadata('page-1', webview, (state) => observed.push(state)) - return { - root, - webview, - observed, - detach, - makeUnreadable: () => { - readable = false - }, - finish: () => - finish({ - browserPageId: 'page-1', - webContentsId: 41, - revision: 1, - navigationRevision: 1, - kind: 'snapshot', - url: 'https://old.test/', - title: 'Old', - loading: false, - canGoBack: false, - canGoForward: false, - errorPage: false, - loadError: null, - hasCertificateFailure: false - }) - } - } - - it('ends guests under a removed slot even when their native identity is already unreadable', async () => { - const rig = prepareGuest() - await Promise.resolve() - rig.root.remove() - rig.makeUnreadable() - registerBrowserOverlaySlotViewport('workspace-1', null) - rig.finish() - await Promise.resolve() - await Promise.resolve() - expect(rig.observed).toEqual([null]) - rig.detach() - }) -}) diff --git a/src/renderer/src/components/editor/combined-diff/resolve-changes/combined-diff-entries.test.ts b/src/renderer/src/components/editor/combined-diff/resolve-changes/combined-diff-entries.test.ts deleted file mode 100644 index 6c059e1c442..00000000000 --- a/src/renderer/src/components/editor/combined-diff/resolve-changes/combined-diff-entries.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveCombinedUncommittedSnapshotEntries } from './combined-diff-entries' - -import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types' - -describe('resolveCombinedUncommittedSnapshotEntries', () => { - it('uses live metadata when a stale snapshot area moves to a rename entry', () => { - const snapshotEntries: GitStatusEntry[] = [ - { path: 'src/new.ts', status: 'modified', area: 'unstaged', oldPath: 'src/old-copy.ts' } - ] - const liveEntries: GitStatusEntry[] = [ - { - path: 'src/new.ts', - status: 'renamed', - area: 'staged', - oldPath: 'src/old.ts', - added: 3, - removed: 1 - } - ] - - expect(resolveCombinedUncommittedSnapshotEntries(snapshotEntries, liveEntries)).toEqual([ - { - path: 'src/new.ts', - status: 'renamed', - area: 'staged', - oldPath: 'src/old.ts', - added: 3, - removed: 1 - } - ]) - }) - - it('does not remap duplicate-path snapshots to a retained fallback area', () => { - const snapshotEntries: GitStatusEntry[] = [ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 }, - { path: 'src/file.ts', status: 'modified', area: 'unstaged', added: 2 } - ] - const retained: GitStatusEntry[] = [{ path: 'src/file.ts', status: 'modified', area: 'staged' }] - - expect(resolveCombinedUncommittedSnapshotEntries(snapshotEntries, [], retained)).toEqual([ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 } - ]) - }) - - it('does not let a retained stale area duplicate an original target area', () => { - const snapshotEntries: GitStatusEntry[] = [ - { path: 'src/file.ts', status: 'modified', area: 'unstaged', added: 2 }, - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 } - ] - const retained: GitStatusEntry[] = [{ path: 'src/file.ts', status: 'modified', area: 'staged' }] - - expect(resolveCombinedUncommittedSnapshotEntries(snapshotEntries, [], retained)).toEqual([ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 } - ]) - }) - - it('drops a stale snapshot area when resolving it would duplicate an existing area', () => { - const snapshotEntries: GitStatusEntry[] = [ - { path: 'src/file.ts', status: 'modified', area: 'unstaged', added: 2 }, - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 } - ] - const liveEntries: GitStatusEntry[] = [ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 6 } - ] - - expect(resolveCombinedUncommittedSnapshotEntries(snapshotEntries, liveEntries)).toEqual([ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 } - ]) - }) - - it('keeps the original target area when it appears before a stale area', () => { - const snapshotEntries: GitStatusEntry[] = [ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 }, - { path: 'src/file.ts', status: 'modified', area: 'unstaged', added: 2 } - ] - const liveEntries: GitStatusEntry[] = [ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 6 } - ] - - expect(resolveCombinedUncommittedSnapshotEntries(snapshotEntries, liveEntries)).toEqual([ - { path: 'src/file.ts', status: 'modified', area: 'staged', added: 4 } - ]) - }) -}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-model.test.ts b/src/renderer/src/components/editor/git-graph/git-graph-model.test.ts deleted file mode 100644 index 16e94e19af3..00000000000 --- a/src/renderer/src/components/editor/git-graph/git-graph-model.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { expect, it } from 'vitest' -import { GitGraphModel } from './git-graph-model' -import type { - GitHistoryItem, - GitHistoryResult -} from '../../../../../shared/git/history/git-history-types' - -const item = (id: string, parentIds: string[] = []): GitHistoryItem => ({ - id, - parentIds, - subject: id, - message: id -}) -const page = (items: GitHistoryItem[]): GitHistoryResult => ({ - items, - hasMore: false, - hasIncomingChanges: false, - hasOutgoingChanges: false, - limit: 50 -}) -const currentRef = { id: 'refs/heads/main', name: 'main', revision: 'M' } - -it('recolors a late side parent and all later rotating colors without changing published rows', () => { - const model = new GitGraphModel() - const merge = item('M', ['A', 'B']) - const later = item('X', ['Y']) - const first = { ...page([merge, later]), currentRef } - model.update(first) - const published = model.rows - const expected = [ - { id: 'A', color: 'git-graph-lane-1' }, - { id: 'B', color: 'git-graph-lane-2' } - ] - expect(published[0]?.outputSwimlanes).toEqual(expected) - expect(published[1]?.outputSwimlanes).toEqual([ - ...expected, - { id: 'Y', color: 'git-graph-lane-3' } - ]) - const parent = { ...item('B'), references: [currentRef] } - model.update({ ...first, items: [merge, later, parent] }) - expect(model.rows[0]?.outputSwimlanes).toEqual([ - { id: 'A', color: 'git-graph-lane-1' }, - { id: 'B', color: 'git-graph-ref' } - ]) - expect(model.rows[1]?.outputSwimlanes).toEqual([ - { id: 'A', color: 'git-graph-lane-1' }, - { id: 'B', color: 'git-graph-ref' }, - { id: 'Y', color: 'git-graph-lane-2' } - ]) - expect(published[0]?.outputSwimlanes).toEqual(expected) - expect(published[1]?.outputSwimlanes).toEqual([ - ...expected, - { id: 'Y', color: 'git-graph-lane-3' } - ]) - model.update(first) - model.update({ ...first, items: [merge, later, item('C')] }) - expect(model.rows[0]?.outputSwimlanes).toEqual(expected) - expect(model.rows[1]?.outputSwimlanes).toEqual([ - ...expected, - { id: 'Y', color: 'git-graph-lane-3' } - ]) -}) - -it('resolves same-batch parents first-wins, keeps roots separate and updates raw details and HEAD', () => { - const model = new GitGraphModel() - const merge = item('M', ['A', 'B']) - const parent = { ...item('B'), references: [currentRef] } - const lead = item('lead') - model.update({ ...page([lead]), currentRef }) - model.update({ - ...page([lead, merge, parent, item('B'), item('A', ['C']), item('C')]), - currentRef: { ...currentRef } - }) - expect(model.rows[1]?.outputSwimlanes).toEqual([ - { id: 'A', color: 'git-graph-lane-1' }, - { id: 'B', color: 'git-graph-ref' } - ]) - expect(model.rows[2]?.outputSwimlanes).toEqual([{ id: 'A', color: 'git-graph-lane-1' }]) - expect(model.rows.at(-1)?.outputSwimlanes).toEqual([]) - expect(model.find('B')?.item).toEqual({ - id: 'B', - subject: 'B', - message: 'B', - parentIds: [], - references: [currentRef] - }) - expect(model.find('B')?.index).toBe(2) - const refreshed = { ...parent, subject: 'Updated', message: 'New body' } - model.update({ ...page([merge, refreshed]), currentRef: { ...currentRef, revision: 'B' } }) - expect(model.rows.map((row) => row.kind)).toEqual(['node', 'HEAD']) - expect(model.find('B')?.item.subject).toBe('Updated') - expect(model.find('B')?.item.references?.[0]?.color).toBeUndefined() - model.update(undefined) - expect(model.rows).toEqual([]) - expect(model.find('B')).toBeUndefined() - model.update(page([item('fresh')])) - model.update(page([])) - expect(model.rows).toEqual([]) - expect(model.find('fresh')).toBeUndefined() -}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-viewport.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-viewport.test.tsx deleted file mode 100644 index e74de361508..00000000000 --- a/src/renderer/src/components/editor/git-graph/git-graph-viewport.test.tsx +++ /dev/null @@ -1,93 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { useGitGraphViewport } from './use-git-graph-viewport' - -it('keeps visible geometry through hidden panes, fractional scroll, resize, append, shrink, reveal and remount', async () => { - let height = 0 - let resize = () => {} - let reveal = (_index: number) => {} - const owner = { scrollOffset: 0 } - const getOffset = () => owner.scrollOffset - const setOffset = (value: number) => { - owner.scrollOffset = value - } - const host = document.createElement('div') - document.body.append(host) - let root = createRoot(host) - vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(() => height) - vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(function ( - this: HTMLElement - ) { - const child = this.firstElementChild - return Number.parseFloat(child instanceof HTMLElement ? child.style.height : '0') + 48 - }) - vi.stubGlobal( - 'ResizeObserver', - class { - constructor(callback: () => void) { - resize = callback - } - observe() {} - disconnect() {} - } - ) - function Pane({ count }: { count: number }) { - const viewport = useGitGraphViewport(count, getOffset, setOffset) - reveal = viewport.reveal - return ( -
-
- {viewport.items.map((row) => ( - - ))} -
-
- ) - } - const render = (count: number) => act(async () => root.render()) - const rows = () => Array.from(host.querySelectorAll('[data-row]')) - const scroll = () => host.querySelector(':scope > div')! - try { - await render(100) - expect(rows()).toHaveLength(0) - height = 48 - await act(async () => resize()) - expect(scroll().dataset.end).toBe('1') - expect(rows().at(-1)?.dataset.row).toBe('13') - await act(async () => { - scroll().scrollTop = 24.5 - scroll().dispatchEvent(new Event('scroll')) - }) - expect(scroll().dataset.end).toBe('3') - expect(rows().at(-1)?.style.top).toBe('360px') - await act(async () => { - scroll().scrollTop = 2352 - scroll().dispatchEvent(new Event('scroll')) - }) - await render(150) - expect(scroll().dataset.end).toBe('99') - expect(rows().at(-1)?.dataset.row).toBe('111') - await act(async () => reveal(149)) - expect(scroll().scrollTop).toBe(3600) - await act(async () => reveal(20)) - expect(scroll().scrollTop).toBe(480) - await act(async () => reveal(21)) - expect(scroll().scrollTop).toBe(480) - await render(10) - expect(rows().at(-1)?.dataset.row).toBe('9') - await act(async () => root.unmount()) - root = createRoot(host) - await render(100) - expect(scroll().scrollTop).toBe(480) - height = 240 - await act(async () => resize()) - expect(scroll().dataset.end).toBe('29') - } finally { - await act(async () => root.unmount()) - host.remove() - vi.restoreAllMocks() - vi.unstubAllGlobals() - } -}) diff --git a/src/renderer/src/components/editor/loading/log-tail/useLocalLogTail.test.tsx b/src/renderer/src/components/editor/loading/log-tail/useLocalLogTail.test.tsx deleted file mode 100644 index 0c545929750..00000000000 --- a/src/renderer/src/components/editor/loading/log-tail/useLocalLogTail.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -// @vitest-environment happy-dom -import { renderHook, waitFor } from '@testing-library/react' -import { useState } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import type { FileContent } from '../editor-panel-content-types' -import { useLocalLogTail } from './useLocalLogTail' - -const FILE_PATH = '/home/user/.codex/sessions/log.jsonl' -const FILE_IDENTITY = '1:2:3' - -const openFile = { - id: FILE_PATH, - filePath: FILE_PATH, - relativePath: FILE_PATH, - worktreeId: 'wt-1', - language: 'jsonl', - isDirty: false, - runtimeEnvironmentId: null, - mode: 'edit', - readOnly: true, - liveTail: true -} satisfies OpenFile - -function encodedResult(content: string, fromByteOffset: number) { - const bytes = Buffer.from(content) - return { - contentBase64: bytes.toString('base64'), - nextByteOffset: fromByteOffset + bytes.byteLength, - fileSize: fromByteOffset + bytes.byteLength, - fileIdentity: FILE_IDENTITY, - hasMore: false, - reset: false - } -} - -let startMock: ReturnType -let stopMock: ReturnType -let readMock: ReturnType -let reloadMock: Mock<(file: OpenFile) => void> -let warnMock: ReturnType - -beforeEach(() => { - startMock = vi.fn().mockResolvedValue(undefined) - stopMock = vi.fn().mockResolvedValue(undefined) - readMock = vi.fn() - reloadMock = vi.fn<(file: OpenFile) => void>() - warnMock = vi.spyOn(console, 'warn').mockImplementation(() => {}) - Object.defineProperty(window, 'api', { - configurable: true, - value: { - fs: { - startLocalLogTail: startMock, - stopLocalLogTail: stopMock, - readLocalLogTail: readMock, - onLocalLogTailChanged: vi.fn(() => vi.fn()) - } - } - }) -}) - -afterEach(() => { - Reflect.deleteProperty(window, 'api') - warnMock.mockRestore() - vi.clearAllMocks() -}) - -function useHarness(files: OpenFile[], initialContent: FileContent) { - const [contents, setContents] = useState>({ - [FILE_PATH]: initialContent - }) - useLocalLogTail({ - openFiles: files, - fileContents: contents, - setFileContents: setContents, - reloadContent: reloadMock - }) - return contents -} - -describe('useLocalLogTail', () => { - it('re-reads a partial snapshot line and appends it only after completion', async () => { - const snapshot = 'complete\n{"partial":' - const offset = Buffer.byteLength('complete\n') - readMock.mockResolvedValue(encodedResult('{"partial":true}\n', offset)) - - const { result } = renderHook(() => - useHarness([openFile], { - content: snapshot, - isBinary: false, - fileIdentity: FILE_IDENTITY - }) - ) - - await waitFor(() => { - expect(result.current[FILE_PATH]?.content).toBe('complete\n{"partial":true}\n') - }) - }) - - it('commits complete lines read before a later transient chunk failure', async () => { - const first = encodedResult('new\n', 4) - readMock - .mockResolvedValueOnce({ ...first, fileSize: first.fileSize + 1, hasMore: true }) - .mockRejectedValueOnce(new Error('temporary read failure')) - const { result } = renderHook(() => - useHarness([openFile], { - content: 'old\n', - isBinary: false, - fileIdentity: FILE_IDENTITY - }) - ) - - await waitFor(() => expect(result.current[FILE_PATH]?.content).toBe('old\nnew\n')) - }) -}) diff --git a/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx b/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx deleted file mode 100644 index 1af1857e7a4..00000000000 --- a/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx +++ /dev/null @@ -1,108 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' - -const { listPythonEnvironments } = vi.hoisted(() => { - const listPythonEnvironments = vi.fn() - // The kernel session subscribes to kernel frames when it loads. - Object.defineProperty(window, 'api', { - configurable: true, - value: { notebook: { onKernelFrame: () => () => {}, listPythonEnvironments } } - }) - return { listPythonEnvironments } -}) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) -vi.mock('@/store/index', () => ({ useAppStore: { subscribe: () => () => {} } })) - -import { IpynbKernelToolbar } from './IpynbKernelToolbar' -import { trustNotebook } from './ipynb-kernel-session' -import { getSession, setEnvironment, updateSession } from './ipynb-kernel-store' - -const FILE = '/repo/nb.ipynb' -const CREATE_VENV = /^Create virtual environment…/ -const TRUST_FIRST = 'Run a cell to trust this notebook first' - -afterEach(cleanup) - -function renderToolbar(filePath: string) { - return render( - - - - ) -} - -function togglePicker(label: string): void { - fireEvent.pointerDown(screen.getByRole('button', { name: label }), { - button: 0, - ctrlKey: false, - pointerType: 'mouse' - }) -} - -describe('kernel picker trust', () => { - it('lists workspace envs without running them until the notebook is trusted', async () => { - const file = '/repo/untrusted.ipynb' - const venv = { path: '/repo/.venv/bin/python', name: '.venv' } - listPythonEnvironments.mockResolvedValue({ - workspace: [venv], - path: [{ path: '/usr/bin/python3', name: 'python3', version: '3.12.1' }] - }) - renderToolbar(file) - - togglePicker('Select Kernel') - await screen.findByText('/repo/.venv/bin/python') - expect(listPythonEnvironments).toHaveBeenLastCalledWith({ - filePath: file, - rootPath: '/repo', - runWorkspaceInterpreters: false - }) - // Unknown versions show only the environment name. - expect(screen.getByText('.venv')).toBeTruthy() - // Reusing a repository-supplied .venv executes its Python, so creation requires trust. - expect(screen.getByRole('menuitem', { name: CREATE_VENV }).dataset.disabled).toBe('') - expect(screen.getByText(TRUST_FIRST)).toBeTruthy() - - act(() => trustNotebook(file)) - await waitFor(() => - expect(listPythonEnvironments).toHaveBeenLastCalledWith({ - filePath: file, - rootPath: '/repo', - runWorkspaceInterpreters: true - }) - ) - expect(screen.getByRole('menuitem', { name: CREATE_VENV }).dataset.disabled).toBeUndefined() - expect(screen.queryByText(TRUST_FIRST)).toBeNull() - }) -}) - -describe('ipykernel setup dialog', () => { - it('Cancel drops the waiting cells, as Esc does', () => { - const venv = { path: '/repo/.venv/bin/python', name: '.venv', version: '3.12.1' } - setEnvironment(FILE, venv) - updateSession(FILE, () => ({ - setup: { base: venv, offer: 'install', phase: 'idle', error: null }, - queue: [{ key: 'a', code: 'x' }] - })) - render( - - - - ) - - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) - expect(getSession(FILE)).toMatchObject({ status: 'off', setup: null, queue: [] }) - expect(screen.queryByText('Install ipykernel?')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.test.ts b/src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.test.ts deleted file mode 100644 index c1395f9966a..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -// @vitest-environment happy-dom -import { Schema } from '@tiptap/pm/model' -import { EditorState } from '@tiptap/pm/state' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { focusRichMarkdownEditorFromSearch } from './rich-markdown-search-focus' - -const schema = new Schema({ - nodes: { - doc: { content: 'paragraph+' }, - paragraph: { content: 'text*' }, - text: {} - } -}) - -function createSurface() { - const root = document.createElement('div') - root.className = 'rich-markdown-editor-shell' - const editorDom = document.createElement('div') - editorDom.contentEditable = 'true' - editorDom.tabIndex = -1 - const paragraph = document.createElement('p') - paragraph.textContent = 'First editable paragraph' - editorDom.append(paragraph) - const search = document.createElement('div') - search.className = 'rich-markdown-search' - const findInput = document.createElement('input') - const replaceInput = document.createElement('input') - search.append(findInput, replaceInput) - root.append(editorDom, search) - document.body.append(root) - const focus = vi.spyOn(editorDom, 'focus') - const viewFocus = vi.fn(() => editorDom.focus({ preventScroll: true })) - const view = { dom: editorDom, focus: viewFocus, state: EditorState.create({ schema }) } - root.addEventListener('mousedown', (event) => { - if (event instanceof MouseEvent) { - focusRichMarkdownEditorFromSearch(event, view) - } - }) - return { root, editorDom, paragraph, findInput, replaceInput, focus, viewFocus } -} - -afterEach(() => { - vi.restoreAllMocks() - document.body.replaceChildren() -}) - -describe('rich markdown search focus handoff', () => { - it.each(['find', 'replace'] as const)( - 'returns keyboard focus from %s without preventing native selection or requesting scroll', - (field) => { - const { paragraph, editorDom, findInput, replaceInput, focus, viewFocus } = createSurface() - const input = field === 'find' ? findInput : replaceInput - input.focus() - const event = new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 }) - - paragraph.dispatchEvent(event) - - expect(document.activeElement).toBe(editorDom) - expect(focus).toHaveBeenCalledExactlyOnceWith({ preventScroll: true }) - expect(viewFocus).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - } - ) - - it('restores the editor selection before native Shift click handling', () => { - const { paragraph, editorDom, findInput, viewFocus } = createSurface() - findInput.focus() - const event = new MouseEvent('mousedown', { - bubbles: true, - cancelable: true, - button: 0, - shiftKey: true - }) - - paragraph.dispatchEvent(event) - - expect(document.activeElement).toBe(editorDom) - expect(viewFocus).toHaveBeenCalledExactlyOnceWith() - expect(event.defaultPrevented).toBe(false) - }) - - it('does not steal focus from a different editor find widget or unrelated field', () => { - const first = createSurface() - const second = createSurface() - const unrelated = document.createElement('input') - document.body.append(unrelated) - - for (const input of [second.findInput, unrelated]) { - input.focus() - first.paragraph.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 })) - expect(document.activeElement).toBe(input) - } - - expect(first.focus).not.toHaveBeenCalled() - }) - - it('allows editable content nested inside an unrelated noneditable ancestor', () => { - const { root, paragraph, findInput, focus } = createSurface() - root.setAttribute('contenteditable', 'false') - findInput.focus() - - paragraph.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 })) - - expect(focus).toHaveBeenCalledExactlyOnceWith({ preventScroll: true }) - }) -}) diff --git a/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts b/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts deleted file mode 100644 index 6c6b954d0f1..00000000000 --- a/src/renderer/src/components/feature-wall/setup/FullDiskAccessSetupPrompt.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -// @vitest-environment happy-dom - -import * as React from 'react' -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - DeveloperPermissionRequestResult, - DeveloperPermissionState -} from '../../../../../shared/developer-permissions-types' -import { FullDiskAccessSetupPrompt } from './FullDiskAccessSetupPrompt' - -vi.mock('sonner', () => ({ - toast: { - error: vi.fn(), - message: vi.fn(), - success: vi.fn() - } -})) - -function setUserAgent(userAgent: string): void { - Object.defineProperty(window.navigator, 'userAgent', { - value: userAgent, - configurable: true - }) -} - -function installDeveloperPermissionsApi(args: { - getStatus: () => Promise - request?: () => Promise -}): void { - Object.assign(window, { - api: { - developerPermissions: { - getStatus: vi.fn(args.getStatus), - request: vi.fn( - args.request ?? - (async () => ({ - id: 'full-disk-access', - status: 'unknown', - openedSystemSettings: true - })) - ) - } - } - }) -} - -async function renderPrompt(): Promise<{ container: HTMLDivElement; root: Root }> { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - await act(async () => { - root.render(React.createElement(FullDiskAccessSetupPrompt)) - }) - await act(async () => { - await Promise.resolve() - }) - return { container, root } -} - -describe('FullDiskAccessSetupPrompt state helpers', () => { - afterEach(() => { - vi.restoreAllMocks() - document.body.innerHTML = '' - Reflect.deleteProperty(window, 'api') - Object.defineProperty(window.navigator, 'userAgent', { - value: '', - configurable: true - }) - }) - - it('keeps the latest macOS status when overlapping refreshes finish out of order', async () => { - setUserAgent('Macintosh') - let resolveFirst!: (states: DeveloperPermissionState[]) => void - const firstRefresh = new Promise((resolve) => { - resolveFirst = resolve - }) - const getStatus = vi - .fn() - .mockReturnValueOnce(firstRefresh) - .mockResolvedValueOnce([{ id: 'full-disk-access', status: 'granted' }]) - installDeveloperPermissionsApi({ getStatus }) - - const { container, root } = await renderPrompt() - await act(async () => { - window.dispatchEvent(new Event('focus')) - await Promise.resolve() - }) - expect(container.textContent).not.toContain('Full Disk Access') - - await act(async () => { - resolveFirst([{ id: 'full-disk-access', status: 'unknown' }]) - await Promise.resolve() - }) - - expect(container.textContent).not.toContain('Full Disk Access') - root.unmount() - }) - - it('does not query or render the macOS Full Disk Access prompt on non-macOS', async () => { - setUserAgent('Windows NT 10.0') - const getStatus = vi.fn().mockResolvedValue([{ id: 'full-disk-access', status: 'unknown' }]) - installDeveloperPermissionsApi({ getStatus }) - - const { container, root } = await renderPrompt() - - expect(container.textContent).not.toContain('Full Disk Access') - expect(getStatus).not.toHaveBeenCalled() - root.unmount() - }) -}) diff --git a/src/renderer/src/components/github-project/slug-dialog/SlugDialogBody.images.test.tsx b/src/renderer/src/components/github-project/slug-dialog/SlugDialogBody.images.test.tsx deleted file mode 100644 index a413e00c7fb..00000000000 --- a/src/renderer/src/components/github-project/slug-dialog/SlugDialogBody.images.test.tsx +++ /dev/null @@ -1,106 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ details: vi.fn(), patch: vi.fn() })) -vi.mock('@/store', () => ({ - useAppStore: (select: (state: unknown) => unknown) => - select({ - patchProjectIssueOrPr: mocks.patch, - projectViewCache: { - key: { - data: { - rows: [ - { - id: 'row', - content: { - number: 2, - repository: 'acme/widgets', - title: 'Image', - labels: [], - assignees: [] - } - } - ] - } - } - } - }) -})) -vi.mock('@/hooks/useGitHubTaskItems', () => ({ - useGitHubTaskProjectTable: (table: unknown) => table -})) -vi.mock('@/runtime/repository-github/github-slug-owner-api', () => ({ - gitHubSlugApiForTarget: () => ({ projectWorkItemDetailsBySlug: mocks.details }) -})) -vi.mock('./LabelsEditor', () => ({ LabelsEditor: () => null })) -vi.mock('./AssigneesEditor', () => ({ AssigneesEditor: () => null })) -vi.mock('./Comments', () => ({ CommentsList: () => null, NewCommentForm: () => null })) -import { SlugDialogBody } from './SlugDialogBody' -afterEach(cleanup) - -it.each([true, false])( - 'uses the authoritative save map, including absent old-host maps (%s)', - async (hasMap) => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - const edited = - '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc489)' - mocks.details.mockResolvedValue({ - ok: true, - details: { - item: { title: 'Image' }, - body, - bodyImageUrls: { - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/old.png?jwt=OLD' - }, - comments: [] - } - }) - mocks.patch.mockReset().mockResolvedValue( - hasMap - ? { - ok: true, - bodyImageUrls: { - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc489': - 'https://private-user-images.githubusercontent.com/1/new.png?jwt=NEW' - } - } - : { ok: true } - ) - render( - {}} - /> - ) - const image = await screen.findByRole('img') - expect(image.getAttribute('src')).toBe( - 'https://private-user-images.githubusercontent.com/1/old.png?jwt=OLD' - ) - fireEvent.click(image.closest('button')!) - const editor = screen.getByRole('textbox') - expect(editor).toHaveProperty('value', body) - fireEvent.change(editor, { target: { value: edited } }) - fireEvent.click(screen.getByRole('button', { name: 'Save' })) - await waitFor(() => - expect(screen.getByRole('img').getAttribute('src')).toBe( - hasMap - ? 'https://private-user-images.githubusercontent.com/1/new.png?jwt=NEW' - : 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc489' - ) - ) - expect(mocks.patch).toHaveBeenCalledWith('key', 'row', { - body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc489)' - }) - } -) diff --git a/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts deleted file mode 100644 index d8f8aa50ee0..00000000000 --- a/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { - AgentSessionStatusEvent, - AgentSessionStatusSummary -} from '../../../../../shared/agent-session/agent-session-wire' -import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import { - _resetNativeChatRestartOffer, - dismissNativeChatRestartOffer, - getNativeChatRestartOffer, - refreshNativeChatRestartOffer -} from './native-chat-resume-on-restart-store' - -const mocks = vi.hoisted(() => ({ - rpc: vi.fn(), - subscribeStatus: vi.fn(), - unsubscribe: vi.fn() -})) -vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: mocks.rpc -})) - -vi.mock('../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: mocks.subscribeStatus -})) - -const failure = { - sessionId: 'a', - workspaceId: 'workspace', - agent: 'codex', - trigger: 'update', - latestPrompt: 'Fix it', - recordedAt: 1, - failedAt: 2, - outcome: 'refused', - reason: 'agent_session_restart_work_superseded' -} - -function summary( - status: AgentSessionStatusSummary['status'], - latestPrompt: string, - updatedAt: number -): AgentSessionStatusSummary { - return { - sessionId: 'a', - workspaceId: 'workspace', - agent: 'codex', - status, - latestPrompt, - updatedAt - } -} - -function hostEmit(): (event: AgentSessionStatusEvent) => void { - const call = mocks.subscribeStatus.mock.calls[0] - if (!call) { - throw new Error('status feed not subscribed') - } - return call[1] -} - -function offerReads(): number { - return mocks.rpc.mock.calls.filter(([, method]) => method === 'agentSession.restartResumable') - .length -} - -async function listFailure(later: { failed: unknown[] } = { failed: [] }): Promise { - mocks.rpc - .mockResolvedValueOnce({ sessions: [], failed: [failure] }) - .mockResolvedValue({ sessions: [], ...later }) - await refreshNativeChatRestartOffer() - await vi.advanceTimersByTimeAsync(0) -} - -beforeEach(() => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - vi.clearAllMocks() - mocks.subscribeStatus.mockResolvedValue({ unsubscribe: mocks.unsubscribe }) - _resetNativeChatRestartOffer() - resetStructuredAgentSessionStatusFeedsForTests() -}) - -afterEach(() => { - _resetNativeChatRestartOffer() - resetStructuredAgentSessionStatusFeedsForTests() - vi.useRealTimers() -}) - -it('never lets a re-read that was already in flight bring back a dismissed failure', async () => { - await listFailure({ failed: [failure] }) - const stale = Promise.withResolvers() - mocks.rpc.mockImplementation((_target: unknown, method: string) => - method === 'agentSession.restartResumable' - ? stale.promise - : Promise.resolve({ sessions: [], failed: [] }) - ) - hostEmit()({ type: 'status', session: summary('working', 'Carry on please', Date.now() + 1) }) - await vi.advanceTimersByTimeAsync(500) - expect(offerReads()).toBe(2) - - await dismissNativeChatRestartOffer(['a']) - expect(getNativeChatRestartOffer().failed).toEqual([]) - stale.resolve({ sessions: [], failed: [failure] }) - await vi.advanceTimersByTimeAsync(0) - - expect(getNativeChatRestartOffer().failed).toEqual([]) -}) diff --git a/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx b/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx deleted file mode 100644 index 6be4e226b0c..00000000000 --- a/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx +++ /dev/null @@ -1,86 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { NativeChatImageAttachmentPreview } from './NativeChatImageAttachmentPreview' -import type { NativeChatComposerImageAttachment } from './native-chat-image-attachment' - -const mocks = vi.hoisted(() => ({ - useLocalImageSrc: vi.fn(), - getConnectionIdForFile: vi.fn(() => { - throw new Error('Image preview fixtures must not resolve editor file connections') - }) -})) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, options?: Record) => - fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? '') -})) - -vi.mock('@/lib/workspace/ownership/connection-context', () => ({ - getConnectionIdForFile: mocks.getConnectionIdForFile -})) - -vi.mock('@/components/editor/document-images/useLocalImageSrc', () => ({ - useLocalImageSrc: mocks.useLocalImageSrc -})) - -afterEach(() => { - cleanup() - vi.unstubAllGlobals() - mocks.useLocalImageSrc.mockReset() - expect(mocks.getConnectionIdForFile).not.toHaveBeenCalled() - mocks.getConnectionIdForFile.mockClear() -}) - -function renderPreview( - attachment: NativeChatComposerImageAttachment, - hostEnvironmentId?: string -): void { - vi.stubGlobal('IntersectionObserver', undefined) - render( - - ) -} - -async function clickOn(target: Element): Promise { - await act(async () => { - target.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })) - target.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, button: 0 })) - target.dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 })) - await new Promise((resolve) => setTimeout(resolve, 0)) - }) -} - -describe('NativeChatImageAttachmentPreview', () => { - it('stays open through a click on the chat context menu, but not elsewhere outside', async () => { - mocks.useLocalImageSrc.mockReturnValue('blob:on-disk-1') - renderPreview({ id: 'a1', path: '/tmp/example.png', previewUrl: 'data:thumbnail' }) - fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: example.png' })) - expect( - within(screen.getByRole('dialog')) - .getByTestId('pan-zoom-image-canvas') - .closest('[data-native-chat-copy-image-src]') - ?.getAttribute('data-native-chat-copy-image-src') - ).toBe('blob:on-disk-1') - const menu = document.body.appendChild(document.createElement('div')) - menu.setAttribute('data-native-chat-context-menu', '') - const copyItem = menu.appendChild(document.createElement('div')) - const elsewhere = document.body.appendChild(document.createElement('div')) - // Radix arms its outside-pointer listener a tick after the dialog opens. - await act(async () => new Promise((resolve) => setTimeout(resolve, 0))) - - await clickOn(copyItem) - expect(screen.queryByRole('dialog')).toBeTruthy() - - await clickOn(elsewhere) - expect(screen.queryByRole('dialog')).toBeNull() - menu.remove() - elsewhere.remove() - }) -}) diff --git a/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.fork-source.test.tsx b/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.fork-source.test.tsx deleted file mode 100644 index 86d0a422cfb..00000000000 --- a/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.fork-source.test.tsx +++ /dev/null @@ -1,96 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { act, cleanup, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import { NativeChatRowActionsProvider } from './NativeChatRowActionsProvider' -import { NativeChatNoticeRow } from '../notices/NativeChatNoticeRow' -import { ssh } from '../../../sidebar/worktree-list/listing/host-status-test-fixtures' -import type { NativeChatTextBlock } from '../../../../../../shared/native-chat/native-chat-types' - -const initial = useAppStore.getInitialState() -const LOCAL_WORKTREE = 'repo-local::/repos/local' -const SSH_WORKTREE = 'repo-ssh::/remote/repo' - -const divider: NativeChatTextBlock = { - type: 'text', - text: 'Forked from Annotate capabilities', - presentation: 'forked-from', - forkedFrom: { sessionId: 'source-chat' } -} - -function chatTab(id: string): AppState['unifiedTabsByWorktree'][string][number] { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership reads only the chat tab's id and content type. - return { - id, - contentType: 'agent-session', - entityId: `${id}-session` - } as AppState['unifiedTabsByWorktree'][string][number] -} - -beforeEach(() => { - useAppStore.setState(initial, true) - useAppStore.setState({ - terminalStartupRestorationReady: true, - repos: [ - { - id: 'repo-local', - path: '/repos/local', - displayName: 'Local', - badgeColor: '#000', - addedAt: 0 - }, - { - id: 'repo-ssh', - path: '/remote/repo', - displayName: 'Remote', - badgeColor: '#000', - addedAt: 0, - connectionId: 'target-ssh' - } - ], - unifiedTabsByWorktree: { - [LOCAL_WORKTREE]: [chatTab('local-chat')], - [SSH_WORKTREE]: [chatTab('ssh-chat')] - }, - sshConnectionStates: new Map([['target-ssh', ssh('disconnected', 'target-ssh')]]) - }) -}) -afterEach(() => { - cleanup() - useAppStore.setState(initial, true) -}) - -function renderDivider(tabId: string): void { - render( - - - - ) -} - -it('lets a fork in a local workspace open its source', () => { - renderDivider('local-chat') - expect( - screen.getByRole('button', { name: 'Forked from Annotate capabilities' }) - ).toBeInTheDocument() -}) - -it('shows plain words while the SSH workspace is disconnected, and the pill once it connects', () => { - renderDivider('ssh-chat') - expect(screen.queryByRole('button')).toBeNull() - expect(document.body).toHaveTextContent('Forked from Annotate capabilities') - act(() => - useAppStore.setState({ - sshConnectionStates: new Map([['target-ssh', ssh('connected', 'target-ssh')]]) - }) - ) - expect( - screen.getByRole('button', { name: 'Forked from Annotate capabilities' }) - ).toBeInTheDocument() -}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts deleted file mode 100644 index c4ffc2bb913..00000000000 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Tab } from '../../../../../../shared/tab-types' -import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types' -import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { getStructuredAgentSessionTabs } from './structured-agent-session-tabs' - -function chat(id: string, worktreeId: string): Tab { - return { - id, - entityId: 'session-shared', - groupId: `group-${worktreeId}`, - worktreeId, - contentType: 'agent-session', - agentSessionAgent: 'codex', - label: id, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 - } -} - -function session(worktreeIds: readonly string[]): WorkspaceSessionState { - const entries = (value: (worktreeId: string) => V): Record => - Object.fromEntries(worktreeIds.map((worktreeId) => [worktreeId, value(worktreeId)])) - return { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: entries((worktreeId) => [chat(`chat-${worktreeId}`, worktreeId)]), - tabGroups: entries((worktreeId) => [ - { - id: `group-${worktreeId}`, - worktreeId, - activeTabId: `chat-${worktreeId}`, - tabOrder: [`chat-${worktreeId}`], - recentTabIds: [`chat-${worktreeId}`] - } - ]), - activeGroupIdByWorktree: entries((worktreeId) => `group-${worktreeId}`) - } -} - -const ids = (tabs: readonly Tab[]) => tabs.map((tab) => tab.id) -// Folder workspace keys are real tab-map keys and valid hydration workspace keys. -const EARLY = folderWorkspaceKey('early') -const LATER = folderWorkspaceKey('later') - -// Scoped hydration rebuilds the workspaces it names; the warm chat list must match a cold read. -describe('chat-tab list after scoped session hydration', () => { - it('follows the hydrated source order for the shared session first match', () => { - const store = createTestStore() - const keys = [EARLY, LATER] - store.getState().hydrateTabsSession(session(keys), { additionalValidWorkspaceKeys: keys }) - expect(ids(getStructuredAgentSessionTabs(store.getState().unifiedTabsByWorktree))).toEqual([ - `chat-${EARLY}`, - `chat-${LATER}` - ]) - - store.getState().hydrateTabsSession(session([EARLY]), { - additionalValidWorkspaceKeys: keys, - replaceWorkspaceKeys: [EARLY] - }) - const source = store.getState().unifiedTabsByWorktree - expect(Object.keys(source)).toEqual([LATER, EARLY]) - const warm = getStructuredAgentSessionTabs(source) - expect(ids(warm)).toEqual([`chat-${LATER}`, `chat-${EARLY}`]) - expect(ids(getStructuredAgentSessionTabs({ ...source }))).toEqual(ids(warm)) - expect(warm.find((tab) => tab.entityId === 'session-shared')?.worktreeId).toBe(LATER) - }) - - it('takes hydrated record order over the selection order', () => { - const store = createTestStore() - const keys = [EARLY, LATER] - store.getState().hydrateTabsSession(session([LATER, EARLY]), { - additionalValidWorkspaceKeys: keys - }) - expect(ids(getStructuredAgentSessionTabs(store.getState().unifiedTabsByWorktree))).toEqual([ - `chat-${LATER}`, - `chat-${EARLY}` - ]) - - store.getState().hydrateTabsSession(session([EARLY, LATER]), { - additionalValidWorkspaceKeys: keys, - replaceWorkspaceKeys: [LATER, EARLY] - }) - const source = store.getState().unifiedTabsByWorktree - expect(Object.keys(source)).toEqual([EARLY, LATER]) - const warm = getStructuredAgentSessionTabs(source) - expect(ids(warm)).toEqual([`chat-${EARLY}`, `chat-${LATER}`]) - expect(ids(getStructuredAgentSessionTabs({ ...source }))).toEqual(ids(warm)) - }) -}) diff --git a/src/renderer/src/components/plugins/view/plugin-view-request-handler.test.ts b/src/renderer/src/components/plugins/view/plugin-view-request-handler.test.ts deleted file mode 100644 index ea7628cd2a4..00000000000 --- a/src/renderer/src/components/plugins/view/plugin-view-request-handler.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' -import { useAppStore } from '@/store' -import { usePluginViewCaptureStore } from '@/store/plugins/capture/plugin-view-capture' -import { reportPluginPanelDraw } from '../../right-sidebar/plugin-panels/health/plugin-panel-draw-status' -import { handlePluginViewRequest } from './plugin-view-request-handler' - -const KEY = 'acme.todos' -const TAB = `plugin:${KEY}/todos` as const -const initialState = useAppStore.getState() - -function plugin(): PluginHostListEntry { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handler and the stores read only these fields. - return { - pluginKey: KEY, - name: 'Todos', - status: 'idle', - panels: [{ id: 'todos', title: 'Todos', tabKey: TAB }], - customEditors: [ - { id: 'notes', title: 'Notes', extensions: ['.notes'], filenames: [], priority: 'option' } - ], - commands: [] - } as unknown as PluginHostListEntry -} - -beforeEach(() => { - Object.defineProperty(window, 'api', { - configurable: true, - value: { plugins: { list: vi.fn().mockResolvedValue([plugin()]) } } - }) - useAppStore.setState({ - activeView: 'terminal', - activeWorktreeId: 'wt-1', - rightSidebarOpen: false - }) -}) - -afterEach(() => { - useAppStore.setState(initialState, true) - usePluginViewCaptureStore.getState().end() - reportPluginPanelDraw(TAB, null) - document.body.innerHTML = '' - document.documentElement.classList.remove('dark') -}) - -describe('open-panel', () => { - it('leaves Settings to show it, but a capture never changes the view', async () => { - useAppStore.setState({ activeView: 'settings', previousViewBeforeSettings: 'terminal' }) - const captured = await handlePluginViewRequest({ - requestId: 'r1', - kind: 'open-panel', - pluginKey: KEY, - panelId: 'todos', - capture: { guestRevision: null, timeoutMs: 10 } - }) - expect(captured).toMatchObject({ ok: false, code: 'no_workspace' }) - expect(useAppStore.getState().activeView).toBe('settings') - await handlePluginViewRequest({ - requestId: 'r2', - kind: 'open-panel', - pluginKey: KEY, - panelId: 'todos' - }) - expect(useAppStore.getState().activeView).toBe('terminal') - }) -}) - -describe('open-panel with ifShown', () => { - it('never opens or switches: another tab or a closed sidebar answers not_shown', async () => { - useAppStore.setState({ rightSidebarOpen: true, rightSidebarTab: 'explorer' }) - const request = { - requestId: 'r', - kind: 'open-panel' as const, - pluginKey: KEY, - panelId: 'todos', - capture: { guestRevision: null, ifShown: true, timeoutMs: 5_000 } - } - await expect(handlePluginViewRequest(request)).resolves.toEqual({ - requestId: 'r', - ok: false, - code: 'not_shown', - message: 'the right sidebar shows another tab' - }) - expect(useAppStore.getState()).toMatchObject({ - rightSidebarOpen: true, - rightSidebarTab: 'explorer' - }) - useAppStore.setState({ rightSidebarOpen: false, rightSidebarTab: TAB }) - await expect(handlePluginViewRequest(request)).resolves.toMatchObject({ - message: 'the right sidebar is closed' - }) - expect(useAppStore.getState().rightSidebarOpen).toBe(false) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-session-account-render.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-session-account-render.test.tsx deleted file mode 100644 index dacf5f4093c..00000000000 --- a/src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-session-account-render.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -// @vitest-environment happy-dom -import type * as I18n from '@/i18n/i18n' -import { act } from '@testing-library/react' -import { expect, it, vi } from 'vitest' -import { useAppStore } from '../../../../store/index' -import { emptyCodexAccountsState } from '@/runtime/provider-accounts/observations/runtime-provider-accounts-client' -import { - accountSettings, - recordedSession, - details, - flushAccountWork, - installAccountFixture -} from './ai-vault-account-test-fixture' - -vi.mock('@/i18n/i18n', async (importOriginal) => ({ - ...(await importOriginal()), - translate: (_key: string, fallback: string) => fallback -})) -installAccountFixture() - -it('requires successful Claude evidence, with Account after Worktree and usable Unknown actions', async () => { - const settings = accountSettings() - const saved = settings.claudeManagedAccounts[0]! - let deferred = Promise.withResolvers<{ - accounts: (typeof saved & { home?: string })[] - activeAccountId: string | null - }>() - const list = vi.fn(() => deferred.promise) - window.api.claudeAccounts = { ...window.api.claudeAccounts, list } - window.api.codexAccounts = { - ...window.api.codexAccounts, - list: vi.fn(async () => emptyCodexAccountsState()) - } - useAppStore.setState({ settings }) - const stale = recordedSession('claude') - const current = { - ...stale, - id: 'current', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/profiles/current' } - } - const panel = details([ - stale, - current, - { ...stale, id: 'old-response', accountHome: undefined }, - { ...stale, id: 'default', accountHome: null } - ]) - panel.unknown(stale.id) - panel.unknown('current') - panel.unknown('old-response') - expect(panel.account('default').getByText('System default')).toBeTruthy() - await act(async () => - deferred.resolve({ - accounts: [{ ...saved, home: '/profiles/current', email: 'current@example.com' }], - activeAccountId: 'another' - }) - ) - panel.unknown(stale.id) - expect(panel.account('current').getByText('current@example.com')).toBeTruthy() - for (const outcome of ['partial', 'empty', 'older', 'rejected'] as const) { - deferred = Promise.withResolvers() - if (outcome === 'rejected') { - window.api.codexAccounts.list = vi.fn().mockRejectedValue(new Error('Codex unavailable')) - } - await act(async () => { - const currentSettings = useAppStore.getState().settings! - useAppStore.setState({ - settings: { - ...currentSettings, - claudeManagedAccounts: currentSettings.claudeManagedAccounts.map((account) => ({ - ...account, - lastAuthenticatedAt: account.lastAuthenticatedAt + 1 - })) - } - }) - }) - panel.unknown(stale.id) - await act(async () => { - if (outcome === 'partial' || outcome === 'rejected') { - deferred.reject(new Error('Claude unavailable')) - } else { - deferred.resolve({ - accounts: outcome === 'older' ? [{ ...saved, email: 'older@example.com' }] : [], - activeAccountId: 'another' - }) - } - }) - if (outcome === 'older') { - expect(panel.account(stale.id).getByText('older@example.com')).toBeTruthy() - } else { - panel.unknown(stale.id) - } - } - await flushAccountWork() - expect(list).toHaveBeenCalledTimes(5) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.test.ts b/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.test.ts deleted file mode 100644 index 67a32cc05ed..00000000000 --- a/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { searchHit } from '../../../../../../shared/ai-vault/search/ai-vault-search-test-fixture' - -import { resolveAiVaultSessionResumeInChatEligibility } from '../session-actions/ai-vault-session-resume-in-chat' -import { - aiVaultSearchHitToSession, - canResumeAiVaultSearchHit, - hasAiVaultSearchHitPath, - withAiVaultHistoryPreviews -} from './ai-vault-search-session' - -afterEach(() => vi.restoreAllMocks()) - -describe('withAiVaultHistoryPreviews', () => { - it('restores resume correspondence when history arrives after a search hit, even with an existing preview', () => { - const hit = aiVaultSearchHitToSession( - { ...searchHit(), agent: 'claude', cwd: '/private/var/example' }, - 'local' - ) - const previewed = { - ...hit, - previewMessages: [{ role: 'user' as const, text: 'Keep this preview', timestamp: null }] - } - const history = { ...hit, cwdAliases: ['/var/example'] } - const resume = (session: typeof hit) => - resolveAiVaultSessionResumeInChatEligibility({ - session, - targetWorkspaceId: 'folder:example', - targetWorkspacePath: '/var/example', - structuredRouteAvailable: true - }) - expect(resume(withAiVaultHistoryPreviews([previewed], [])[0]).available).toBe(false) - const [hydrated] = withAiVaultHistoryPreviews([previewed], [history]) - expect(hydrated.previewMessages).toBe(previewed.previewMessages) - expect(resume(hydrated)).toEqual({ available: true, workspaceId: 'folder:example' }) - const redacted = { ...hit, filePath: '' } - expect(resume(withAiVaultHistoryPreviews([redacted], [history])[0]).available).toBe(true) - for (const rows of [ - [history, { ...history, id: 'duplicate' }], - [{ ...history, cwd: '/private/var/different' }], - [{ ...history, filePath: '/other-transcript' }], - [{ ...history, executionHostId: 'runtime:other' as const }] - ]) { - expect(withAiVaultHistoryPreviews([hit], rows)[0].cwdAliases).toBeUndefined() - } - }) -}) - -describe('aiVaultSearchHitToSession', () => { - it('uses the selected execution host and only host-provided source fields', () => { - const hit = { - ...searchHit(), - executionHostId: 'local', - accountHome: { variable: 'CODEX_HOME', path: '/accounts/recorded' }, - accountWslDistro: 'Ubuntu' - } - const session = aiVaultSearchHitToSession(hit, 'ssh:paired-host') - - expect(session.executionHostId).toBe('ssh:paired-host') - expect(session.id).toBe('ssh:paired-host:codex:host-session:/host/transcript.jsonl') - expect(session.filePath).toBe('/host/transcript.jsonl') - expect(session.resumeCommand).toBe('host-resume-command') - expect(session.previewMessages).toEqual([]) - expect(session.accountHome).toEqual(hit.accountHome) - expect(session.accountWslDistro).toBe('Ubuntu') - }) - - it('opens a native chat hit through its owner when transport withholds the command', () => { - const hit = { - ...searchHit(), - source: { presence: 'present' as const }, - resumeCommand: undefined, - structuredSession: { sessionId: 'native-session', workspaceId: 'host-workspace' } - } - - expect(canResumeAiVaultSearchHit(hit)).toBe(true) - expect(hasAiVaultSearchHitPath(hit)).toBe(false) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-review-creation.test.ts b/src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-review-creation.test.ts deleted file mode 100644 index 97b5e7649c9..00000000000 --- a/src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-review-creation.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - computeChecksPanelConfirmedReadiness, - type ChecksPanelConfirmedReadinessInput -} from './checks-panel-review-creation' - -describe('computeChecksPanelConfirmedReadiness', () => { - const NOW = 1_000_000 - function readiness( - overrides: Partial = {} - ): ChecksPanelConfirmedReadinessInput { - return { - contextKeyMatches: true, - eligibility: { canCreate: true, blockedReason: null, reviewLookupOutcome: 'not_found' }, - eligibilityCompletedAt: NOW - 1_000, - eligibilityRequestStartedAt: NOW - 2_000, - reviewLookup: 'not_found', - hardErrorObservedAt: undefined, - gitSnapshotMatches: true, - now: NOW, - ...overrides - } - } - - it('confirms fresh, matching eligibility', () => { - expect(computeChecksPanelConfirmedReadiness(readiness())).toEqual({ - confirmed: true, - needsPush: false - }) - }) - - it('confirms needs_push as the Push & Create path', () => { - expect( - computeChecksPanelConfirmedReadiness( - readiness({ - eligibility: { - canCreate: false, - blockedReason: 'needs_push', - reviewLookupOutcome: 'not_found' - } - }) - ) - ).toEqual({ confirmed: true, needsPush: true }) - }) - - it('drops confirmed when the context key does not match', () => { - expect( - computeChecksPanelConfirmedReadiness(readiness({ contextKeyMatches: false })).confirmed - ).toBe(false) - }) - - it('drops confirmed on positive unresolved and existing_review', () => { - expect( - computeChecksPanelConfirmedReadiness(readiness({ reviewLookup: 'positive_unresolved' })) - .confirmed - ).toBe(false) - expect( - computeChecksPanelConfirmedReadiness( - readiness({ - eligibility: { - canCreate: false, - blockedReason: 'existing_review', - reviewLookupOutcome: 'found' - } - }) - ).confirmed - ).toBe(false) - }) - - it('drops confirmed when eligibility is older than 5 minutes', () => { - expect( - computeChecksPanelConfirmedReadiness( - readiness({ eligibilityCompletedAt: NOW - 5 * 60_000 - 1 }) - ).confirmed - ).toBe(false) - }) - - it('drops confirmed when the git snapshot no longer matches', () => { - expect( - computeChecksPanelConfirmedReadiness(readiness({ gitSnapshotMatches: false })).confirmed - ).toBe(false) - }) - - describe('hard error clearing', () => { - it('clears when the request started strictly after the error with an accepted outcome', () => { - expect( - computeChecksPanelConfirmedReadiness( - readiness({ - hardErrorObservedAt: NOW - 3_000, - eligibilityRequestStartedAt: NOW - 2_000, - eligibility: { canCreate: true, blockedReason: null, reviewLookupOutcome: 'not_found' } - }) - ).confirmed - ).toBe(true) - }) - - it('does not clear for an in-flight request that started before the error', () => { - expect( - computeChecksPanelConfirmedReadiness( - readiness({ hardErrorObservedAt: NOW - 1_500, eligibilityRequestStartedAt: NOW - 2_000 }) - ).confirmed - ).toBe(false) - }) - - it('does not clear on a late unavailable fallback', () => { - expect( - computeChecksPanelConfirmedReadiness( - readiness({ - hardErrorObservedAt: NOW - 3_000, - eligibilityRequestStartedAt: NOW - 2_000, - eligibility: { - canCreate: false, - blockedReason: 'no_upstream', - reviewLookupOutcome: 'unavailable' - } - }) - ).confirmed - ).toBe(false) - }) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/hosted-review/creation/use-generate-before-create-pull-request-context.test.tsx b/src/renderer/src/components/right-sidebar/hosted-review/creation/use-generate-before-create-pull-request-context.test.tsx deleted file mode 100644 index f3587ab3417..00000000000 --- a/src/renderer/src/components/right-sidebar/hosted-review/creation/use-generate-before-create-pull-request-context.test.tsx +++ /dev/null @@ -1,106 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { createRunningPullRequestGenerationRecord } from '@/store/slices/hosted-review/generation/pull-request-generation' -import type { HostedReviewCreationEligibility } from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts' -import { useCreatePullRequestDialogFields } from './useCreatePullRequestDialogFields' -import { useGenerateBeforeCreatePullRequest } from './use-generate-before-create-pull-request' - -const revisions = { base: 0, title: 0, body: 0, draft: 0 } -const eligibility: HostedReviewCreationEligibility = { - provider: 'github', - review: null, - canCreate: true, - blockedReason: null, - nextAction: null, - reviewLookupOutcome: 'not_found', - defaultBaseRef: 'main' -} - -function seedRecord(key: string) { - return createRunningPullRequestGenerationRecord( - { - worktreeId: key, - worktreePath: `/repo/${key}`, - requestId: key === 'a' ? 1 : 2, - runtimeTarget: { kind: 'local' }, - repoId: 'repo-1', - branch: key - }, - { base: 'main', title: `Seed ${key}`, body: `Body ${key}`, draft: false }, - revisions, - true - ) -} - -function useComposer(key: string) { - const record = useAppStore((state) => state.pullRequestGenerationRecords[key]) - const fields = useCreatePullRequestDialogFields({ - open: true, - repoId: 'repo-1', - worktreeId: key, - worktreePath: `/repo/${key}`, - branch: key, - eligibility, - settings: null, - target: { kind: 'local' }, - submitting: false, - generation: { - generating: record?.status === 'running', - generateError: null, - seedRestoreKey: `${key}:${record?.context.requestId}`, - seed: record?.editedFields?.fields ?? record?.seed, - seedFieldRevisions: record?.editedFields?.revisions ?? record?.seedFieldRevisions, - onGenerate: vi.fn(async () => undefined), - onCancelGenerate: vi.fn() - } - }) - useGenerateBeforeCreatePullRequest({ - aiGenerationEnabled: false, - canCreate: true, - createPullRequest: vi.fn(async () => {}), - fields: { base: fields.base, title: fields.title, body: fields.body, draft: fields.draft }, - fieldRevisions: fields.fieldRevisions, - fieldsInitialized: fields.initializedFromEligibility, - fieldsAreSeedPlaceholders: fields.fieldsAreSeedPlaceholders, - generatePullRequestFields: fields.handleGenerate, - generationKey: key, - repo: null - }) - return fields -} - -afterEach(() => { - cleanup() - useAppStore.setState({ pullRequestGenerationRecords: {} }) -}) - -describe('auto-submit field ownership during real composer seeding', () => { - it('does not publish the old composer fields into another pending branch', () => { - useAppStore.setState({ - pullRequestGenerationRecords: { a: seedRecord('a'), b: seedRecord('b') } - }) - const { result, rerender } = renderHook(({ key }) => useComposer(key), { - initialProps: { key: 'a' } - }) - act(() => { - result.current.setTitle('Manual A title') - result.current.setBody('Manual A details') - }) - expect(useAppStore.getState().pullRequestGenerationRecords.a?.editedFields?.fields.title).toBe( - 'Manual A title' - ) - rerender({ key: 'b' }) - expect(useAppStore.getState().pullRequestGenerationRecords.b?.editedFields).toBeUndefined() - expect(result.current.title).toBe('Seed b') - act(() => result.current.setTitle('Manual B title')) - rerender({ key: 'a' }) - expect(result.current.title).toBe('Manual A title') - expect(result.current.body).toBe('Manual A details') - expect(useAppStore.getState().pullRequestGenerationRecords.b?.editedFields?.fields.title).toBe( - 'Manual B title' - ) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts b/src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts deleted file mode 100644 index a6babfc68ab..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildSourceControlManualReviewUrl } from './manual-review-url' - -describe('buildSourceControlManualReviewUrl', () => { - it('qualifies GitHub fork heads when the push target remote differs from the base repo', () => { - expect( - buildSourceControlManualReviewUrl({ - baseRef: 'refs/remotes/upstream/main', - branchName: 'feature/fork-head', - repoRemoteName: 'upstream', - repoRemoteUrl: 'https://github.com/stablyai/orca.git', - pushTarget: { - remoteName: 'fork', - branchName: 'feature/fork-head', - remoteUrl: 'git@github.com:contributor/orca.git' - } - }) - ).toBe('https://github.com/stablyai/orca/compare/main...contributor:feature/fork-head?expand=1') - }) - - it('keeps slashes literal in a GitHub compare URL for a slash-containing branch name', () => { - expect( - buildSourceControlManualReviewUrl({ - baseRef: 'refs/remotes/origin/main', - branchName: 'slashdevcorpse/identifying-pwsh.exe-error', - repoRemoteName: 'origin', - repoRemoteUrl: 'git@github.com:stablyai/orca.git', - upstreamName: 'origin/slashdevcorpse/identifying-pwsh.exe-error' - }) - ).toBe( - 'https://github.com/stablyai/orca/compare/main...slashdevcorpse/identifying-pwsh.exe-error?expand=1' - ) - }) - - it('opens the GitLab New-MR page on the fork project when the branch was pushed to a fork', () => { - expect( - buildSourceControlManualReviewUrl({ - baseRef: 'refs/remotes/upstream/main', - branchName: 'feature/fork-head', - repoRemoteName: 'upstream', - repoRemoteUrl: 'git@gitlab.company.test:group/sub/orca.git', - provider: 'gitlab', - pushTarget: { - remoteName: 'fork', - branchName: 'feature/fork-head', - remoteUrl: 'git@gitlab.company.test:contributor/orca.git' - } - }) - // On the fork project — not group/sub/orca, where source_branch would 404. - ).toBe( - 'https://gitlab.company.test/contributor/orca/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Ffork-head&merge_request%5Btarget_branch%5D=main' - ) - }) - - it('suppresses the link when the branch tracks a fork remote with no resolvable push URL', () => { - // A fork-only tracked branch without pushTarget would 404 through the base-repo compare URL. - expect( - buildSourceControlManualReviewUrl({ - baseRef: 'refs/remotes/origin/main', - branchName: 'quick-commands', - repoRemoteName: 'origin', - repoRemoteUrl: 'https://github.com/stablyai/orca.git', - upstreamName: 'pr-devajmeireles-orca/quick-commands' - }) - ).toBeNull() - }) - - it('uses the pushed upstream branch name when the local branch tracks a differently named branch on the base remote', () => { - expect( - buildSourceControlManualReviewUrl({ - baseRef: 'refs/remotes/origin/main', - branchName: 'local-wip-name', - repoRemoteName: 'origin', - repoRemoteUrl: 'git@github.com:stablyai/orca.git', - upstreamName: 'origin/feature/pushed-name' - }) - ).toBe('https://github.com/stablyai/orca/compare/main...feature/pushed-name?expand=1') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/review/use-pull-request-generation.test.tsx b/src/renderer/src/components/right-sidebar/source-control/review/use-pull-request-generation.test.tsx deleted file mode 100644 index c74dd5caf45..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/review/use-pull-request-generation.test.tsx +++ /dev/null @@ -1,85 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as RuntimeGitGenerationClient from '@/runtime/source-control/git/runtime-git-generation-client' -import type { RuntimeGeneratePullRequestFieldsResult } from '@/runtime/source-control/git/runtime-git-client-context' -import { useAppStore } from '@/store/index' -import { makeRepo, makeWorktree } from '../../../worktree-jump/worktree-jump-palette-test-fixtures' - -const runtime = vi.hoisted(() => ({ - cancel: vi.fn().mockResolvedValue(undefined), - generate: vi.fn() -})) - -vi.mock('@/runtime/source-control/git/runtime-git-generation-client', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - cancelRuntimeGeneratePullRequestFields: runtime.cancel, - generateRuntimePullRequestFields: runtime.generate - } -}) - -import { useSourceControlPullRequestGeneration } from './use-pull-request-generation' - -afterEach(() => { - cleanup() - vi.restoreAllMocks() - runtime.cancel.mockReset().mockResolvedValue(undefined) - runtime.generate.mockReset() - useAppStore.setState({ pullRequestGenerationRecords: {} }) -}) - -describe('useSourceControlPullRequestGeneration outcome', () => { - it('captures the owning host’s Jira key before a background generation outlives a workspace switch', async () => { - const workspace = makeWorktree('wt-1', 'Jira task', { - linkedWorkItem: { - provider: 'jira', - type: 'issue', - number: 0, - title: 'Fix login', - jiraIdentifier: 'ALT-42', - url: 'https://jira.example.com/browse/alt-42' - } - }) - const lookup = vi - .spyOn(useAppStore.getState(), 'getKnownWorktreeById') - .mockReturnValue(workspace) - let answer: (value: RuntimeGeneratePullRequestFieldsResult) => void = () => {} - runtime.generate.mockImplementation( - () => - new Promise((resolve) => { - answer = resolve - }) - ) - const state = useAppStore.getState() - const { result } = renderHook(() => - useSourceControlPullRequestGeneration({ - activeRepo: { ...makeRepo(), connectionId: 'owner-host' }, - activeRepoTarget: { kind: 'environment', environmentId: 'owner-environment' }, - activeWorktreeId: 'wt-1', - allocatePullRequestGenerationRequestId: () => 11, - branchName: 'user/alt-42-fix-login', - hostedReviewCreateProvider: 'gitlab', - refreshGitStatusAfterPullRequestGeneration: vi.fn(), - setPullRequestGenerationRecord: state.setPullRequestGenerationRecord, - updatePullRequestGenerationRecord: state.updatePullRequestGenerationRecord, - worktreePath: '/repo/wt' - }) - ) - const outcome = result.current.handleGeneratePullRequestFieldsForActive( - { base: 'main', title: 'ALT-42 Fix login', body: '', draft: false }, - { base: 0, title: 0, body: 0, draft: 0 }, - undefined, - { autoSubmit: true } - ) - expect(lookup).toHaveBeenCalledWith('wt-1', 'ssh:owner-host') - lookup.mockReturnValue(makeWorktree('other', 'Unrelated task')) - answer({ - success: true, - fields: { base: 'main', title: 'Better login', body: 'Generated', draft: false } - }) - await expect(outcome).resolves.toMatchObject({ result: { title: 'ALT-42 Better login' } }) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts deleted file mode 100644 index 2b3a2722aef..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createGitStatusRefreshScheduler } from './git-status-refresh-scheduler' - -const options = { - safetyIntervalMs: 60_000, - activityDebounceMs: 125, - activityMinGapMs: 3000, - slowTaskBackoff: { idleMultiplier: 1, changeSignalMultiplier: 1, maxIntervalMs: 300_000 } -} -beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(0) -}) -afterEach(() => vi.useRealTimers()) - -it('rejects late hidden signals and catches up after an aborted read settles', async () => { - const reads: AbortSignal[] = [] - let finish: (() => void) | undefined - const scheduler = createGitStatusRefreshScheduler(({ signal }) => { - reads.push(signal) - return reads.length === 1 - ? new Promise((resolve) => { - finish = resolve - }) - : Promise.resolve() - }, options) - scheduler.resumeSafety() - scheduler.pause() - expect(reads[0].aborted).toBe(true) - scheduler.signal() - scheduler.refreshNow() - scheduler.retime() - await vi.advanceTimersByTimeAsync(60_000) - expect(reads).toHaveLength(1) - scheduler.resumeSafety() - finish?.() - await vi.advanceTimersByTimeAsync(3000) - expect(reads).toHaveLength(2) - scheduler.pause() - scheduler.signal() - scheduler.refreshNow() - await vi.advanceTimersByTimeAsync(300_000) - expect(reads).toHaveLength(2) - scheduler.resumeSafety() - await vi.advanceTimersByTimeAsync(0) - expect(reads).toHaveLength(3) - scheduler.dispose() -}) - -it('paces visible unfocused edits at 60s while retaining 240s safety and focused catch-up', async () => { - let focused = false - const reads: number[] = [] - const scheduler = createGitStatusRefreshScheduler( - async () => { - reads.push(Date.now()) - }, - { - ...options, - cadenceScale: () => (focused ? 1 : 4), - activityCadenceScale: () => (focused ? 1 : 20) - } - ) - scheduler.resumeSafety() - await vi.advanceTimersByTimeAsync(0) - for (let i = 0; i < 5; i++) { - scheduler.signal() - await vi.advanceTimersByTimeAsync(12_000) - } - expect(reads).toEqual([0, 60_000]) - await vi.advanceTimersByTimeAsync(240_000) - expect(reads).toEqual([0, 60_000, 300_000]) - scheduler.signal() - await vi.advanceTimersByTimeAsync(10_000) - focused = true - scheduler.retime() - await vi.advanceTimersByTimeAsync(125) - expect(reads).toEqual([0, 60_000, 300_000, 310_125]) - scheduler.dispose() -}) - -it('retains quiet-failure safety retry and one trailing read for an in-flight wake', async () => { - const reads: number[] = [] - let finish: (() => void) | undefined - const scheduler = createGitStatusRefreshScheduler(() => { - reads.push(Date.now()) - if (reads.length === 1) { - return Promise.reject(new Error('offline')) - } - if (reads.length === 2) { - return new Promise((resolve) => { - finish = resolve - }) - } - return Promise.resolve() - }, options) - scheduler.resumeSafety() - await vi.advanceTimersByTimeAsync(60_000) - expect(reads).toEqual([0, 60_000]) - scheduler.refreshNow() - scheduler.signal() - finish?.() - await vi.advanceTimersByTimeAsync(3000) - expect(reads).toEqual([0, 60_000, 63_000]) - scheduler.dispose() -}) diff --git a/src/renderer/src/components/settings/chat/chat-naming-persistence.test.tsx b/src/renderer/src/components/settings/chat/chat-naming-persistence.test.tsx deleted file mode 100644 index 8651c9c6023..00000000000 --- a/src/renderer/src/components/settings/chat/chat-naming-persistence.test.tsx +++ /dev/null @@ -1,85 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { expect, it } from 'vitest' -import { setSourceControlActionDefault } from '../../../../../shared/source-control/ai/recipes/source-control-ai-actions' -import { - getDefaultSourceControlAiSettings, - normalizeSourceControlAiSettings -} from '../../../../../shared/source-control/ai/settings/source-control-ai-settings' -import type { - SourceControlAiSettings, - SourceControlAiSettingsPatch -} from '../../../../../shared/source-control/ai/settings/source-control-ai-settings-types' -import { useSourceControlActionRecipeDraftState } from '../source-control/source-control-action-recipe-draft-state' -import { useAppStore } from '../../../store/index' -import { useSettingsInteractionController } from '../page/use-settings-interaction-controller' -import { persist, settingsModel } from '../__fixtures__/settings-persistence-test-fixture' - -it('retains the legacy Git failure contract and composes later queued naming writes', async () => { - const previousBranch = normalizeSourceControlAiSettings( - useAppStore.getState().settings?.sourceControlAi - ).actions?.branchName - persist.mockRejectedValueOnce(new Error('Settings disk is unavailable')) - const { result } = renderHook(() => useSettingsInteractionController(settingsModel())) - await act(async () => { - const failed = result.current.writeSourceControlAiSettings((current) => ({ - actions: setSourceControlActionDefault(current.actions, 'branchName', { - commandInputTemplate: 'Must not persist' - }) - })) - const settled = expect(failed).resolves.toBeUndefined() - const agent = result.current.writeSourceControlAiSettingsOrThrow((current) => ({ - actions: setSourceControlActionDefault(current.actions, 'conversationName', { - agentId: 'codex' - }) - })) - const recipe = result.current.writeSourceControlAiSettingsOrThrow((current) => ({ - actions: setSourceControlActionDefault(current.actions, 'conversationName', { - agentArgs: '--model fast', - commandInputTemplate: 'Name {firstPrompt}' - }) - })) - await Promise.all([settled, agent, recipe]) - }) - expect(useAppStore.getState().settings?.sourceControlAi).toMatchObject({ - enabled: false, - actions: { - commitMessage: { commandInputTemplate: 'Keep the Git recipe' }, - conversationName: { - agentId: 'codex', - agentArgs: '--model fast', - commandInputTemplate: 'Name {firstPrompt}' - } - } - }) - expect(useAppStore.getState().settings?.sourceControlAi?.actions?.branchName).toEqual( - previousBranch - ) - expect(persist).toHaveBeenCalledTimes(3) -}) - -it('saving only Arguments keeps a newer model choice saved by another editor', async () => { - let current: SourceControlAiSettings = { - ...getDefaultSourceControlAiSettings(), - agentId: 'codex', - modelOverridesByOperation: { commitMessage: { selectedModelByAgent: { codex: 'gpt-5.4' } } } - } - const writeConfig = async (patch: SourceControlAiSettingsPatch) => { - current = { ...current, ...(typeof patch === 'function' ? patch(current) : patch) } - } - const view = renderHook( - ({ config }) => useSourceControlActionRecipeDraftState({ config, writeConfig }), - { initialProps: { config: current } } - ) - act(() => view.result.current.onActionAgentArgsChange('commitMessage', '--verbose')) - current = { - ...current, - modelOverridesByOperation: { commitMessage: { selectedModelByAgent: { codex: 'gpt-5.5' } } } - } - view.rerender({ config: current }) - await act(() => view.result.current.saveActionTemplateDraft('commitMessage')) - expect(current.actions?.commitMessage?.agentArgs).toBe('--verbose') - expect(current.modelOverridesByOperation?.commitMessage?.selectedModelByAgent?.codex).toBe( - 'gpt-5.5' - ) -}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts deleted file mode 100644 index f54ef4ed939..00000000000 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-remote-attribution.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' -import { toWebTerminalSurfaceTabId } from '../../../../../../shared/workspace-layout/terminal-surface-id' -import { applyWebSessionTabsSnapshot } from '../../../../runtime/web-session-tabs-sync/snapshot-api' -import { - ENV, - LEAF_ID, - NOW, - makeSnapshot, - makeState, - resetWebSessionTabsSyncTestState -} from '../../../../runtime/web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture' - -vi.mock('../../../../store/index', () => ({ useAppStore: { setState: vi.fn() } })) - -function status(tabId: string, worktreeId: string): AgentStatusEntry { - return { - paneKey: makePaneKey(tabId, LEAF_ID), - tabId, - worktreeId, - agentType: 'omp', - state: 'done', - prompt: 'Finished the change', - updatedAt: NOW, - stateStartedAt: NOW, - stateHistory: [] - } -} - -function hostSnapshot(tabId: string, worktreeId: string) { - return makeSnapshot( - [ - { - type: 'terminal', - id: `${tabId}::${LEAF_ID}`, - parentTabId: tabId, - leafId: LEAF_ID, - title: 'OMP', - isActive: false, - status: 'ready', - terminal: `terminal-${tabId}`, - agentStatus: status(tabId, worktreeId) - } - ], - { worktree: worktreeId } - ) -} - -describe('remote completed sidebar rows before tab hydration', () => { - beforeEach(resetWebSessionTabsSyncTestState) - - it('retracts only the publishing host and workspace when client tabs are missing', () => { - const worktreeId = 'folder:remote-workspace' - const initial = makeState() - const owner = applyWebSessionTabsSnapshot(initial, hostSnapshot('owner', worktreeId), ENV, NOW) - const sibling = applyWebSessionTabsSnapshot( - initial, - hostSnapshot('sibling', worktreeId), - 'other-host', - NOW - ) - const otherWorkspace = applyWebSessionTabsSnapshot( - initial, - hostSnapshot('other-workspace', 'folder:other'), - ENV, - NOW - ) - const unknown = status(toWebTerminalSurfaceTabId('unknown-owner'), worktreeId) - const beforeTabs = makeState({ - agentStatusByPaneKey: { - ...owner.agentStatusByPaneKey, - ...sibling.agentStatusByPaneKey, - ...otherWorkspace.agentStatusByPaneKey, - [unknown.paneKey]: unknown - } - }) - const removed = { - ...beforeTabs, - ...applyWebSessionTabsSnapshot( - beforeTabs, - makeSnapshot([], { worktree: worktreeId, snapshotVersion: 2 }), - ENV, - NOW + 1 - ) - } - expect(Object.keys(removed.agentStatusByPaneKey).sort()).toEqual( - [ - makePaneKey(toWebTerminalSurfaceTabId('sibling'), LEAF_ID), - makePaneKey(toWebTerminalSurfaceTabId('other-workspace'), LEAF_ID), - unknown.paneKey - ].sort() - ) - }) - - it('does not treat workspace visibility removal as host tab retraction', () => { - const worktreeId = 'folder:remote-workspace' - const initial = makeState() - const mirror = applyWebSessionTabsSnapshot( - initial, - hostSnapshot('host-tab', worktreeId), - ENV, - NOW - ) - const beforeTabs = makeState({ agentStatusByPaneKey: mirror.agentStatusByPaneKey }) - const tombstone = { - ...makeSnapshot([], { - worktree: worktreeId, - publicationEpoch: 'visibility-inventory-removal' - }), - removed: true as const - } - const removed = { - ...beforeTabs, - ...applyWebSessionTabsSnapshot(beforeTabs, tombstone, ENV, NOW + 1) - } - expect(removed.agentStatusByPaneKey).toEqual(beforeTabs.agentStatusByPaneKey) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/cross-project-lineage.test.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/cross-project-lineage.test.ts deleted file mode 100644 index 29df8dbf223..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/cross-project-lineage.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' - -import type { Worktree } from '../../../../../../shared/worktree/types' -import { repo, worktree } from './worktree-list-groups-test-fixtures' - -import { buildRows } from './build-rows.test-fixture' - -const childRepo = { ...repo, id: 'child-repo', displayName: 'Child project', path: '/tmp/child' } -const repos = new Map([ - [repo.id, repo], - [childRepo.id, childRepo] -]) -const parent: Worktree = { - ...worktree, - id: 'parent', - instanceId: 'parent-instance', - isMainWorktree: true -} -const child: Worktree = { - ...worktree, - id: 'child', - instanceId: 'child-instance', - repoId: childRepo.id, - path: '/tmp/child-worktree' -} -const lineage: WorktreeLineage = { - worktreeId: child.id, - worktreeInstanceId: 'child-instance', - parentWorktreeId: parent.id, - parentWorktreeInstanceId: 'parent-instance', - origin: 'cli', - capture: { source: 'terminal-context', confidence: 'inferred' }, - createdAt: 1 -} -const lineageById = { [child.id]: lineage } -const worktreeMap = new Map([ - [parent.id, parent], - [child.id, child] -]) - -describe('cross-project sidebar lineage', () => { - it('ranks by actual owner and keeps notices/actions there while counting displayed children', () => { - const gammaRepo = { ...repo, id: 'gamma', displayName: 'Gamma' } - const rows = buildRows( - 'repo', - [ - { ...parent, lastActivityAt: 1 }, - { ...child, lastActivityAt: 100 }, - { ...worktree, id: 'gamma', repoId: gammaRepo.id, lastActivityAt: 50 } - ], - new Map([...repos, [gammaRepo.id, gammaRepo]]), - null, - new Set(), - undefined, - undefined, - 'recent', - lineageById, - worktreeMap, - true, - undefined, - [], - new Set(), - new Map([[childRepo.id, { repo: childRepo, hiddenWorktrees: [] }]]), - new Map(), - [{ creationId: 'creating-child', repoId: childRepo.id }] - ) - expect( - rows.filter((row) => row.type === 'header').map((row) => [row.repo?.id, row.count]) - ).toEqual([ - [childRepo.id, 0], - [gammaRepo.id, 1], - [repo.id, 2] - ]) - expect(rows.find((row) => row.type === 'item' && row.worktree.id === child.id)).toMatchObject({ - repo: childRepo, - sectionKey: `repo:${repo.id}`, - depth: 1 - }) - const nextSection = rows.findIndex( - (row) => row.type === 'header' && row.repo?.id === gammaRepo.id - ) - expect(rows.slice(1, nextSection).map((row) => row.type)).toEqual([ - 'imported-worktrees-card', - 'pending-creation' - ]) - expect(rows.find((row) => row.type === 'pending-creation')).toMatchObject({ repo: childRepo }) - }) - - it('keeps a hidden parent child in its own section without redundant context', () => { - const rows = buildRows( - 'repo', - [child], - repos, - null, - new Set(), - undefined, - undefined, - undefined, - lineageById, - worktreeMap, - true - ) - expect(rows.filter((row) => row.type === 'item')).toMatchObject([ - { worktree: child, sectionKey: `repo:${childRepo.id}`, depth: 0, showProjectName: false } - ]) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/recent-project-rank-scan-budget.test.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/recent-project-rank-scan-budget.test.ts deleted file mode 100644 index 8a92e8d5700..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/recent-project-rank-scan-budget.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { sortProjectEntries } from '../../../../../../shared/project-section-order' -import type { OrderedGroupEntry } from '../../../../../../shared/sidebar-list/sections/worktree-group-entry' -import { repo, worktree } from './worktree-list-groups-test-fixtures' - -function entry( - key: string, - label: string, - activities: number[], - addedAt = 0, - repoIds = [key] -): OrderedGroupEntry { - return [ - key, - { - label, - repo: { ...repo, id: key, addedAt }, - repoIds: new Set(repoIds), - items: activities.map((lastActivityAt, index) => ({ - ...worktree, - id: `${key}:${index}`, - lastActivityAt - })) - } - ] -} - -describe('recent project rank scan budget', () => { - it('preserves identity collisions, manual ties, key-ordered label ties and missing activity fallbacks', () => { - const hottest = entry('collision', 'hottest', [10, 300, 20]) - const hot = entry('collision', 'hot', [200]) - const tieA = entry('a', 'same', [100], 0, ['tie']) - const tieB = entry('b', 'same', [100], 0, ['tie']) - const tieRank = entry('rank', 'later label', [100], 0, ['rank']) - const emptyNew = entry('new', 'new', [], 999) - const emptyOld = entry('old', 'old', [], 1) - const noRepo: OrderedGroupEntry = [ - 'no-repo', - { label: 'absent', items: [], repoIds: new Set() } - ] - const missing = entry('missing', 'missing', [0], 5) - Reflect.deleteProperty(missing[1].items[0], 'lastActivityAt') - const invalid = entry('invalid', 'invalid', [Number.NaN, Number.NEGATIVE_INFINITY], 6) - const infinite = entry('infinite', 'infinite', [Number.POSITIVE_INFINITY]) - const entries = [ - tieA, - hot, - emptyOld, - hottest, - noRepo, - invalid, - tieB, - missing, - emptyNew, - tieRank, - infinite, - tieA - ] - const order = new Map([ - ['rank', 0], - ['tie', 1] - ]) - const expected = [ - infinite, - hottest, - hot, - tieRank, - // Equal labels fall to the section key, so input order cannot decide them. - tieA, - tieA, - tieB, - emptyNew, - invalid, - missing, - emptyOld, - noRepo - ] - const actual = sortProjectEntries(entries, 'recent', order) - expect(actual).toEqual(expected) - actual.forEach((row, index) => expect(row).toBe(expected[index])) - expect(entries[0]).toBe(tieA) - }) - - it('reads current activity and fallback evidence on each new call and leaves manual mode intact', () => { - const first = entry('first', 'first', [100]) - const second = entry('second', 'second', [200]) - const old = entry('old', 'old', [], 1) - const newer = entry('newer', 'newer', [], 2) - const entries = [first, second, old, newer] - expect(sortProjectEntries(entries, 'recent', undefined)).toEqual([second, first, newer, old]) - first[1].items[0].lastActivityAt = 300 - if (!old[1].repo) { - throw new Error('Missing fixture repository') - } - old[1].repo.addedAt = 3 - expect(sortProjectEntries(entries, 'recent', undefined)).toEqual([first, second, old, newer]) - expect(sortProjectEntries(entries, 'manual', undefined)).toBe(entries) - expect( - sortProjectEntries(entries, 'manual', new Map(entries.map(([key], index) => [key, -index]))) - ).toEqual([newer, old, second, first]) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.ts deleted file mode 100644 index d9c8ef4b003..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useWorktreeListScrollToTop } from './use-scroll-to-top' -import { HARD_SCROLL_UP } from './hard-scroll-up' - -let clockMs = 0 - -function advance(ms: number): void { - clockMs += ms - act(() => { - vi.advanceTimersByTime(ms) - }) -} - -function createViewportElement({ - scrollTop = 1200, - scrollHeight = 5000, - clientHeight = 1000 -}: { scrollTop?: number; scrollHeight?: number; clientHeight?: number } = {}): HTMLElement { - const element = document.createElement('div') - // happy-dom reports zero layout; stub the metrics the detector reads. - Object.defineProperty(element, 'scrollHeight', { value: scrollHeight, configurable: true }) - Object.defineProperty(element, 'clientHeight', { value: clientHeight, configurable: true }) - Object.defineProperty(element, 'scrollTop', { - value: scrollTop, - configurable: true, - writable: true - }) - element.scrollTo = vi.fn(() => { - element.scrollTop = 0 - }) as unknown as HTMLElement['scrollTo'] - element.focus = vi.fn() - document.body.append(element) - return element -} - -/** Enough upward wheel travel to clear `hardTotalDeltaPx` inside the intent window. */ -function dispatchHardWheelUp(element: HTMLElement, samples = 4): void { - for (let i = 0; i < samples; i += 1) { - clockMs += 16 - act(() => { - element.dispatchEvent(new WheelEvent('wheel', { deltaY: -240 })) - }) - } -} - -describe('useWorktreeListScrollToTop', () => { - beforeEach(() => { - clockMs = 0 - vi.useFakeTimers() - vi.spyOn(window.performance, 'now').mockImplementation(() => clockMs) - }) - - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - document.body.replaceChildren() - }) - - it('suppresses detection for the post-jump window after scrollToTop', () => { - const element = createViewportElement() - const onUserScrollIntent = vi.fn() - const { result } = renderHook(() => - useWorktreeListScrollToTop({ scrollElement: element, onUserScrollIntent }) - ) - - dispatchHardWheelUp(element) - act(() => { - result.current.scrollToTop() - }) - const jumpAt = clockMs - expect(onUserScrollIntent).toHaveBeenCalledTimes(1) - expect(element.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'auto' }) - expect(result.current.showScrollToTop).toBe(false) - - // Momentum events land back at depth while suppression is active. - element.scrollTop = 1200 - dispatchHardWheelUp(element) - expect(clockMs).toBeLessThan(jumpAt + HARD_SCROLL_UP.suppressAfterJumpMs) - expect(result.current.showScrollToTop).toBe(false) - - advance(HARD_SCROLL_UP.suppressAfterJumpMs) - dispatchHardWheelUp(element) - expect(result.current.showScrollToTop).toBe(true) - }) - - it('clears the timer and detaches listeners when the scroll element goes away', () => { - const element = createViewportElement() - const { result, rerender } = renderHook( - ({ scrollElement }: { scrollElement: HTMLElement | null }) => - useWorktreeListScrollToTop({ scrollElement }), - { initialProps: { scrollElement: element as HTMLElement | null } } - ) - - dispatchHardWheelUp(element) - expect(result.current.showScrollToTop).toBe(true) - - rerender({ scrollElement: null }) - expect(result.current.showScrollToTop).toBe(false) - - dispatchHardWheelUp(element) - advance(HARD_SCROLL_UP.hideAfterIdleMs * 2) - expect(result.current.showScrollToTop).toBe(false) - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stopped-host-reopen.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stopped-host-reopen.test.ts deleted file mode 100644 index 5612a5de94a..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stopped-host-reopen.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('@/store/index', () => ({ - useAppStore: { - getState: () => { - throw new Error('These transport fixtures must not read app-store ownership') - } - } -})) - -import { wslHostStoppedMessage } from '../../../../../../shared/wsl-host-stopped-message' -import { flushAsyncTicks } from '../../pty-connection/test-fixtures/pty-connection-test-async' -import { createRemoteRuntimeTransportMocks } from '../remote/remote-runtime-pty-transport-test-harness' -import type { MultiplexSubscriptionCallbacks } from '../remote/remote-runtime-pty-transport-stream-fixtures' - -const ORIGINAL_ID = 'remote:env-1@@terminal-1' - -let callbacks: MultiplexSubscriptionCallbacks = null -let resolvedHandle = 'terminal-1' -const { runtimeCall, latestSubscribePayload, emitSnapshot, resetRemoteRuntimeTransport } = - createRemoteRuntimeTransportMocks({ - getCallbacks: () => callbacks, - setCallbacks: (value) => { - callbacks = value - }, - getResolvedPaneHandle: () => resolvedHandle, - setResolvedPaneHandle: (value) => { - resolvedHandle = value - } - }) - -beforeEach(resetRemoteRuntimeTransport) - -async function completeAttach(): Promise { - await vi.waitFor(() => expect(latestSubscribePayload()).toBeDefined()) - const { streamId } = latestSubscribePayload() - callbacks?.onResponse({ ok: true, result: { type: 'subscribed', streamId } }) - emitSnapshot(streamId, 'prompt$ ') -} - -/** Every runtime call is refused the way main refuses one for a stopped distro, until `start()`. */ -function stoppedHost(): { start: () => void } { - let stopped = true - const call = runtimeCall.getMockImplementation() - runtimeCall.mockImplementation(async (request: { method: string }) => { - if (stopped) { - throw new Error( - `Error invoking remote method 'runtimeEnvironments:call': Error: ${wslHostStoppedMessage('Ubuntu')}` - ) - } - return call?.(request) - }) - return { - start: () => { - stopped = false - } - } -} - -describe('a restored remote pane whose host was stopped', () => { - it.each(['connect', 'attach'] as const)( - 'reopens by %s once the host is running again, though its own retry has nothing armed', - async (entry) => { - const host = stoppedHost() - const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') - const transport = createRemoteRuntimePtyTransport('env-1', { - worktreeId: 'wt-1', - tabId: 'tab-1', - leafId: 'pane:1' - }) - const onError = vi.fn() - if (entry === 'connect') { - void transport.connect({ url: '', sessionId: ORIGINAL_ID, callbacks: { onError } }) - } else { - transport.attach({ existingPtyId: ORIGINAL_ID, cols: 80, rows: 24, callbacks: { onError } }) - } - await vi.waitFor(() => expect(onError).toHaveBeenCalled()) - await flushAsyncTicks() - expect(transport.getPtyId()).toBeNull() - - host.start() - // The refusal armed nothing, so the pane's own retry cannot bring it back. - expect(transport.retryRecovery?.()).toBe(false) - expect(transport.reopenAfterHostReturned?.()).toBe(true) - await completeAttach() - - await vi.waitFor(() => expect(transport.getPtyId()).toBe(ORIGINAL_ID)) - // Connected now: a second host return does not open it again. - expect(transport.reopenAfterHostReturned?.()).toBe(false) - transport.destroy?.() - } - ) -}) diff --git a/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts b/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts deleted file mode 100644 index ca536bcdbff..00000000000 --- a/src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import type { EditorFilesSlice } from '@/store/slices/editor/types/editor-files-slice' -import type { MarkdownDocument } from '../../../../shared/file-listing/file-document' - -import { registerOsMarkdownFileOpenBridge } from './os-markdown-file-open-bridge' - -const mocks = vi.hoisted(() => ({ - openFile: vi.fn(() => 'file-1'), - updateSettings: vi.fn(async (_updates: { floatingTerminalEnabled?: boolean }) => {}), - toastError: vi.fn(), - subscribe: vi.fn<(listener: (state: { workspaceSessionReady: boolean }) => void) => () => void>() -})) - -let storeState: { - openFile: typeof mocks.openFile - updateSettings: typeof mocks.updateSettings - settings: { floatingTerminalEnabled?: boolean } | undefined - floatingWorkspacePanelOpen: boolean - workspaceSessionReady: boolean -} - -vi.mock('../../store', () => ({ - useAppStore: { getState: () => storeState, subscribe: mocks.subscribe } -})) -vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) - -let frames: FrameRequestCallback[] = [] -let dispatchEvent = vi.fn() -let unhandledRejections: unknown[] = [] -const recordUnhandledRejection = (reason: unknown): void => void unhandledRejections.push(reason) - -function stubPreload(ui: Record): void { - dispatchEvent = vi.fn() - vi.stubGlobal('window', { api: { ui }, dispatchEvent }) -} - -/** Runs the callbacks the bridge deferred to the next frame. */ -function runFrames(): void { - const pending = frames - frames = [] - for (const frame of pending) { - frame(0) - } -} - -/** Drains microtasks and lets Node emit any unhandled rejection the bridge leaked. */ -async function settle(): Promise { - await new Promise((resolve) => setImmediate(resolve)) - await new Promise((resolve) => setImmediate(resolve)) -} - -describe('registerOsMarkdownFileOpenBridge', () => { - beforeEach(() => { - vi.clearAllMocks() - frames = [] - unhandledRejections = [] - storeState = { - openFile: mocks.openFile, - updateSettings: mocks.updateSettings, - settings: { floatingTerminalEnabled: true }, - floatingWorkspacePanelOpen: false, - workspaceSessionReady: true - } - mocks.openFile.mockReturnValue('file-1') - mocks.updateSettings.mockImplementation( - async (updates: { floatingTerminalEnabled?: boolean }) => { - storeState.settings = { ...storeState.settings, ...updates } - } - ) - mocks.subscribe.mockReset().mockReturnValue(() => {}) - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => - frames.push(callback) - ) - vi.spyOn(console, 'error').mockImplementation(() => {}) - process.on('unhandledRejection', recordUnhandledRejection) - }) - - afterEach(() => { - process.off('unhandledRejection', recordUnhandledRejection) - vi.unstubAllGlobals() - vi.restoreAllMocks() - }) - - it('ignores a non-array payload from a mismatched preload', async () => { - stubPreload({ - onOpenMarkdownFiles: () => () => {}, - // Older preloads can return non-arrays; validate before reading length across the boundary. - consumePendingMarkdownFileOpens: () => Promise.resolve(null as unknown as MarkdownDocument[]) - }) - - registerOsMarkdownFileOpenBridge([]) - await settle() - runFrames() - - expect(mocks.openFile).not.toHaveBeenCalled() - expect(mocks.updateSettings).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - expect(unhandledRejections).toEqual([]) - }) -}) diff --git a/src/renderer/src/hooks/useComposerState.integration.test.ts b/src/renderer/src/hooks/useComposerState.integration.test.ts deleted file mode 100644 index 89483295b28..00000000000 --- a/src/renderer/src/hooks/useComposerState.integration.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -// @vitest-environment happy-dom - -import { renderHook } from '@testing-library/react' - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { EMPTY_RETIRED_NAME_REGISTRY } from '../../../shared/worktree/naming/retired-name-registry' - -import type { Repo } from '../../../shared/repo-types' -import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' -import { normalizeTaskSourceContext } from '../../../shared/work-items/task-source-context' -import { useComposerState } from './useComposerState' - -let originalApiDescriptor: PropertyDescriptor | undefined - -beforeEach(() => { - originalApiDescriptor = Object.getOwnPropertyDescriptor(window, 'api') - const preflight = { - detectAgents: vi.fn().mockResolvedValue([]) - } satisfies Pick - const worktrees = { - listRetiredNames: vi - .fn() - .mockResolvedValue(EMPTY_RETIRED_NAME_REGISTRY) - } satisfies Pick - Object.defineProperty(window, 'api', { - configurable: true, - value: { preflight, worktrees } - }) -}) - -afterEach(() => { - vi.restoreAllMocks() - if (originalApiDescriptor) { - Object.defineProperty(window, 'api', originalApiDescriptor) - } else { - Reflect.deleteProperty(window, 'api') - } -}) - -describe('useComposerState integrated lifecycle', () => { - it('passes the selected runtime repository to the name field when IDs repeat across hosts', () => { - const localRepo: Repo = { - id: 'same-id', - path: '/local', - displayName: 'Local', - badgeColor: '', - addedAt: 0, - defaultJiraProject: { id: '10', key: 'LOC', name: 'Local', siteId: 'site-a' } - } - const runtimeRepo: Repo = { - ...localRepo, - path: '/remote', - executionHostId: 'runtime:remote', - defaultJiraProject: { id: '20', key: 'REM', name: 'Remote', siteId: 'site-b' } - } - const projection = projectHostSetupProjectionFromRepos([localRepo, runtimeRepo]) - useAppStore.setState({ - repos: [localRepo, runtimeRepo], - projects: [...projection.projects], - projectHostSetups: projection.setups.map((setup) => ({ - ...setup, - id: `${setup.hostId}:setup` - })), - projectGroups: [], - newWorkspaceDraft: null, - worktreesByRepo: {}, - sparsePresetsByRepo: {}, - runtimeEnvironments: [ - { - id: 'remote', - name: 'Remote', - createdAt: 0, - updatedAt: 0, - lastUsedAt: null, - runtimeId: null, - endpoints: [], - preferredEndpointId: 'endpoint' - } - ] - }) - const composer = renderHook(() => - useComposerState({ - persistDraft: false, - initialTaskSourceContext: normalizeTaskSourceContext({ - provider: 'jira', - projectId: 'repo:same-id', - hostId: 'runtime:remote' - }) - }) - ) - expect(composer.result.current.cardProps.selectedRepo).toBe(runtimeRepo) - expect(composer.result.current.cardProps.smartNameJiraSourceContext?.hostId).toBe( - 'runtime:remote' - ) - composer.unmount() - }) -}) diff --git a/src/renderer/src/lib/agent-session/launch/pane/agent-launch-pane-verdict-application.test.ts b/src/renderer/src/lib/agent-session/launch/pane/agent-launch-pane-verdict-application.test.ts deleted file mode 100644 index e7cfc7dad8a..00000000000 --- a/src/renderer/src/lib/agent-session/launch/pane/agent-launch-pane-verdict-application.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import type { AgentLaunchPaneVerdict } from '../../../../../../shared/agent-launch/contracts/agent-launch-pane-verdict' -import { createTabsSliceMockApi } from '../../../../store/slices/tabs/tabs-slice-test-harness' -import { createTestStore } from '../../../../store/testing/app-store-test-fixture' - -// Main's answer to the window's layout commands, as a switch-on build sends them. -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('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => ({ - ...(await importOriginal()), - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) -})) -const testStore = vi.hoisted(() => { - const ref: { current: ReturnType | null } = { current: null } - return ref -}) -vi.mock('@/store/index', () => ({ - useAppStore: { - getState: () => { - if (!testStore.current) { - throw new Error('no test store') - } - return testStore.current.getState() - } - } -})) -const applyClosedTerminalLeafNotice = vi.hoisted(() => vi.fn()) -vi.mock('@/components/terminal-pane/layout/close/closed-terminal-leaf-notice', () => ({ - applyClosedTerminalLeafNotice -})) - -createTabsSliceMockApi() - -const { applyAgentLaunchPaneVerdict } = await import('./agent-launch-pane-verdict-application') -const { agentLaunchPanePrompt, rememberAgentLaunchPanePrompt } = - await import('./agent-launch-pane-prompt') - -const WT = 'repo1::/tmp/feature' -const LEAF = '3f2504e0-4f89-41d3-9a0c-0305e82c3301' -let store: ReturnType -let tabId: string - -function launchTab() { - return store.getState().tabsByWorktree[WT]?.find((tab) => tab.id === tabId) -} - -function apply(verdict: AgentLaunchPaneVerdict, leafId = LEAF): void { - applyAgentLaunchPaneVerdict({ worktreeId: WT, tabId, leafId, verdict }) -} - -beforeEach(() => { - store = createTestStore() - testStore.current = store - applyClosedTerminalLeafNotice.mockClear() - store.getState().setActiveWorktree(WT) - tabId = store.getState().createTab(WT, undefined, undefined, { - initialLeafId: LEAF, - agentLaunchPane: { leafId: LEAF, operationId: 'op-1' } - }).id - rememberAgentLaunchPanePrompt(tabId, 'fix the build') -}) - -describe("a launch pane's verdict in the window", () => { - it('final, for a launch pane the user already closed out of a split: nothing is kept', () => { - store.getState().setTabLayout(tabId, { - root: { type: 'leaf', leafId: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' }, - activeLeafId: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d', - expandedLeafId: null - }) - apply({ kind: 'not-started', code: 'agent_launch_tab_closed' }) - expect(launchTab()?.agentLaunchPane).toBeUndefined() - expect(agentLaunchPanePrompt(tabId)).toBeNull() - }) -}) diff --git a/src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-execution-host-scope.test.ts b/src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-execution-host-scope.test.ts deleted file mode 100644 index d107f474265..00000000000 --- a/src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-execution-host-scope.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -/** Provider session IDs locate machine-local transcripts; resuming elsewhere fails or opens an unrelated same-ID transcript. Worktree IDs/merged sleeping records/current-catalog routing lack sufficient host scope. Refuse positively foreign records while preserving unstamped legacy resumes; absence of evidence alone cannot strand them. */ -import { afterEach, describe, expect, it } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' - -import { useAppStore } from '@/store/index' -import { makeWorktree } from '../../../store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '../../../store/repos/repo.test-fixture' -import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-session' -import './sleeping-record-execution-host-scope' - -const initialAppStoreState = useAppStore.getState() - -const TARGET_ID = 'openclaw' -const REMOTE_PATH = '/home/neil/projects/orca-test123' -const WORKTREE_ID = `repo-1::${REMOTE_PATH}` -const SESSION_ID = '87987465-66f6-4967-bf3f-0659565cbcc5' - -afterEach(() => { - useAppStore.setState(initialAppStoreState, true) -}) - -function makeRecord( - overrides: Partial = {} -): SleepingAgentSessionRecord { - return { - paneKey: 'tab-1:leaf-1', - tabId: 'tab-1', - worktreeId: WORKTREE_ID, - agent: 'claude', - providerSession: { key: 'session_id', id: SESSION_ID }, - prompt: 'finish the task', - state: 'working', - origin: 'quit', - capturedAt: 1, - updatedAt: 1, - ...overrides - } -} - -/** Use connected SSH so host authority allows the sweep; otherwise unrelated connection refusal makes these assertions vacuous. */ -function seedAnsweredSshWorkspace(...records: SleepingAgentSessionRecord[]): void { - useAppStore.setState({ - repos: [{ ...TEST_REPO, id: 'repo-1', path: '/home/neil/projects', connectionId: TARGET_ID }], - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ - id: WORKTREE_ID, - repoId: 'repo-1', - path: REMOTE_PATH, - hostId: `ssh:${TARGET_ID}` - }) - ] - }, - tabsByWorktree: {}, - sleepingAgentSessionsByPaneKey: Object.fromEntries( - records.map((record) => [record.paneKey, record]) - ) - }) - useAppStore.getState().setSshConnectionState(TARGET_ID, { - targetId: TARGET_ID, - status: 'connected', - error: null, - reconnectAttempt: 0 - }) -} - -describe('the resume sweep under execution-host scope', () => { - it('declines only the foreign record and resumes its native sibling', () => { - const foreign = makeRecord({ - paneKey: 'tab-1:leaf-1', - tabId: 'tab-1', - connectionId: null, - providerSession: { key: 'session_id', id: 'session-from-the-laptop' } - }) - const native = makeRecord({ paneKey: 'tab-2:leaf-1', tabId: 'tab-2', connectionId: TARGET_ID }) - seedAnsweredSshWorkspace(foreign, native) - - expect(resumeSleepingAgentSessionsForWorktree(WORKTREE_ID)).toBe(1) - const state = useAppStore.getState() - expect(state.sleepingAgentSessionsByPaneKey[foreign.paneKey]).toBe(foreign) - expect(state.sleepingAgentSessionsByPaneKey[native.paneKey]).toBeUndefined() - }) -}) diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts b/src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts deleted file mode 100644 index 1bc1fb85a48..00000000000 --- a/src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { activateAndRevealWorktree } from './worktree-activation' -import * as activationGate from './worktree-agent-activation-gate' -import { ensureWorktreeHasInitialTerminal } from './initial-surface/worktree-initial-terminal-seeding' -import { - makeCreatedAgentWorktree as makeWorktree, - seedEmptyActivatableWorktree -} from '@/lib/workspace/activation/worktree-activation-created-agent.test-fixture' - -// Main's answer to the window's layout commands, as a switch-on build sends them. -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()) -) - -const initialAppStoreState = useAppStore.getState() - -afterEach(() => { - vi.unstubAllGlobals() - vi.restoreAllMocks() - useAppStore.setState(initialAppStoreState, true) -}) - -/** The state a workspace lands in once its last terminal is closed: the row survives as an - * explicit empty list rather than disappearing, beside the close's record. */ -function seedClosedLastTerminal(worktreeId: string): void { - useAppStore.setState({ - tabsByWorktree: { [worktreeId]: [] }, - closedTerminalTabTombstonesByTabId: { closed: { closedAt: Date.now(), worktreeId } } - }) - const { renderableTabCount } = useAppStore.getState().reconcileWorktreeTabModel(worktreeId) - expect(renderableTabCount).toBe(0) -} - -describe('activating a workspace whose last terminal was closed', () => { - it('lets the latest caller surface supersede an older callback on the shared gate', async () => { - const worktree = makeWorktree() - seedEmptyActivatableWorktree(worktree) - seedClosedLastTerminal(worktree.id) - useAppStore.setState({ - sleepingAgentSessionsByPaneKey: { - 'pane-1': { worktreeId: worktree.id } - } as never - }) - let resolveGate!: (outcome: activationGate.WorktreeAgentActivationOutcome) => void - const pendingGate = new Promise((resolve) => { - resolveGate = resolve - }) - vi.spyOn(activationGate, 'gateWorktreeAgentActivation').mockReturnValue(pendingGate) - - activateAndRevealWorktree(worktree.id, { agent: 'codex', notifyHostRuntime: false }) - activateAndRevealWorktree(worktree.id, { - providesInitialSurface: true, - notifyHostRuntime: false - }) - resolveGate('empty') - await pendingGate - - expect(useAppStore.getState().tabsByWorktree[worktree.id]).toEqual([]) - }) - - it('does not double-seed when another recovery creates a tab before the gate settles', async () => { - const worktree = makeWorktree() - seedEmptyActivatableWorktree(worktree) - seedClosedLastTerminal(worktree.id) - useAppStore.setState({ - sleepingAgentSessionsByPaneKey: { - 'pane-1': { worktreeId: worktree.id } - } as never - }) - let resolveGate!: (outcome: activationGate.WorktreeAgentActivationOutcome) => void - const pendingGate = new Promise((resolve) => { - resolveGate = resolve - }) - vi.spyOn(activationGate, 'gateWorktreeAgentActivation').mockReturnValue(pendingGate) - - activateAndRevealWorktree(worktree.id, { agent: 'codex', notifyHostRuntime: false }) - const recoveredTabId = ensureWorktreeHasInitialTerminal( - useAppStore.getState(), - worktree.id, - undefined, - undefined, - undefined, - undefined, - { reseedEmptiedWorkspace: true } - ) - resolveGate('empty') - await pendingGate - - expect(useAppStore.getState().tabsByWorktree[worktree.id]).toHaveLength(1) - expect(useAppStore.getState().tabsByWorktree[worktree.id]?.[0]?.id).toBe(recoveredTabId) - }) -}) diff --git a/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.test.ts b/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.test.ts deleted file mode 100644 index 918077634f8..00000000000 --- a/src/renderer/src/runtime/ephemeral-vm/ephemeral-vm-environment-check.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { callRuntimeRpc, supportsCapability, store } = vi.hoisted(() => { - const entries: Record = {} - return { - callRuntimeRpc: vi.fn(), - supportsCapability: vi.fn(async () => true), - store: { - entries, - getState: () => ({ - pendingWorktreeCreations: entries, - updatePendingWorktreeCreation: (id: string, patch: Record) => { - if (entries[id]) { - Object.assign(entries[id], patch) - } - } - }) - } - } -}) - -vi.mock('@/store/index', () => ({ useAppStore: { getState: store.getState } })) -vi.mock('sonner', () => ({ toast: { error: vi.fn(), warning: vi.fn() } })) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc })) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ - runtimeEnvironmentSupportsCapability: supportsCapability -})) - -import { gateVmCreateOnEnvironmentCheck } from './ephemeral-vm-environment-check' -import { - cancelVmEnvironmentCheck, - resolveVmEnvironmentCheckDecision -} from './ephemeral-vm-environment-check-decision' - -const failing = { - worktreePath: '/w', - ok: false, - checks: [{ id: 'tool.pnpm', category: 'tools', status: 'fail', message: 'pnpm missing' }] -} -const passing = { worktreePath: '/w', ok: true, checks: [] } - -async function settle(): Promise { - for (let i = 0; i < 10; i++) { - await Promise.resolve() - } -} - -describe('gateVmCreateOnEnvironmentCheck', () => { - beforeEach(() => { - for (const key of Object.keys(store.entries)) { - delete store.entries[key] - } - store.entries.c1 = {} - callRuntimeRpc.mockReset() - supportsCapability.mockResolvedValue(true) - }) - - it('pauses on failed checks, re-runs them on retry, and continues once they pass', async () => { - callRuntimeRpc.mockResolvedValueOnce(failing).mockResolvedValueOnce(passing) - const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') - await settle() - expect(store.entries.c1.environmentCheck?.status).toBe('failed') - - resolveVmEnvironmentCheckDecision('c1', 'retry') - await expect(gate).resolves.toBe(true) - expect(callRuntimeRpc).toHaveBeenCalledTimes(2) - expect(store.entries.c1.environmentCheck?.status).toBe('passed') - }) - - it('continues on Open anyway and stops when the build is dismissed', async () => { - callRuntimeRpc.mockResolvedValue(failing) - const opened = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') - await settle() - resolveVmEnvironmentCheckDecision('c1', 'open-anyway') - await expect(opened).resolves.toBe(true) - - const dismissed = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') - await settle() - delete store.entries.c1 - cancelVmEnvironmentCheck('c1') - await expect(dismissed).resolves.toBe(false) - }) - - it('aborts a running check when the build is dismissed', async () => { - let signal: AbortSignal | undefined - callRuntimeRpc.mockImplementation( - (_target, _method, _params, options: { signal: AbortSignal }) => - new Promise((_resolve, reject) => { - signal = options.signal - options.signal.addEventListener('abort', () => reject(new Error('aborted'))) - }) - ) - const gate = gateVmCreateOnEnvironmentCheck('c1', 'env-1', '/w') - await settle() - delete store.entries.c1 - cancelVmEnvironmentCheck('c1') - await expect(gate).resolves.toBe(false) - expect(signal?.aborted).toBe(true) - }) -}) diff --git a/src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts b/src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts deleted file mode 100644 index d28372c6311..00000000000 --- a/src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { deferred } from './testing/web-session-terminal-orphan-recovery-regression-fixtures' -import { toRemoteRuntimePtyId } from '../../../../../shared/remote-runtime/remote-runtime-pty-id' -import { - clearWebSessionTerminalOrphanRecoveryForTests, - recoverWebSessionTerminalOrphansBeforeApply -} from './web-session-terminal-orphan-recovery' - -describe('web session terminal orphan recovery', () => { - beforeEach(() => clearWebSessionTerminalOrphanRecoveryForTests()) - - it('serializes a newer convergence snapshot after an in-flight adoption conflict', async () => { - const worktree = 'repo::/worktree' - const adoptionEntered = deferred() - let rejectFirstAdoption: (() => void) | null = null - const call = vi.fn(async ({ method }) => { - if (method === 'terminal.list') { - return { - ok: true as const, - result: { - terminals: [ - { - handle: 'term_live', - ptyId: 'pty-live', - incarnationId: 'inc-live', - orphaned: true - } - ], - topologyRevisions: { [worktree]: 1 }, - totalCount: 1, - truncated: false - } - } - } - return await new Promise((resolve) => { - rejectFirstAdoption = () => - resolve({ ok: false as const, error: { code: 'conflict', message: 'closed' } }) - adoptionEntered.resolve() - }) - }) - const state = { - tabsByWorktree: { - [worktree]: [{ id: 'web-terminal-host-tab', worktreeId: worktree } as never] - }, - terminalLayoutsByTabId: { - 'web-terminal-host-tab': { - root: { type: 'leaf' as const, leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null, - ptyIdsByLeafId: { - 'leaf-1': toRemoteRuntimePtyId('term_live', 'windows-2') - } - } - }, - activeTabIdByWorktree: {}, - activeGroupIdByWorktree: {} - } - const missing = { - worktree, - publicationEpoch: 'missing', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - const converged = { - ...missing, - publicationEpoch: 'closed', - snapshotVersion: 2, - tabs: [ - { - type: 'terminal' as const, - id: 'host-tab::leaf-1', - parentTabId: 'host-tab', - leafId: 'leaf-1', - title: 'closed', - isActive: false, - status: 'ready' as const, - terminal: 'term_live' - } - ] - } - - const first = recoverWebSessionTerminalOrphansBeforeApply(state, missing, 'windows-2', { - call: call as never - }) - await adoptionEntered.promise - const second = recoverWebSessionTerminalOrphansBeforeApply(state, converged, 'windows-2', { - call: call as never - }) - rejectFirstAdoption!() - - await expect(first).resolves.toBeNull() - await expect(second).resolves.toMatchObject({ - publicationEpoch: 'closed', - snapshotVersion: 2, - tabs: [{ id: 'host-tab::leaf-1', status: 'ready', terminal: 'term_live' }] - }) - }) -}) diff --git a/src/renderer/src/runtime/hosts/connections/runtime-host-contact-regained.test.ts b/src/renderer/src/runtime/hosts/connections/runtime-host-contact-regained.test.ts deleted file mode 100644 index 0eceac2a015..00000000000 --- a/src/renderer/src/runtime/hosts/connections/runtime-host-contact-regained.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' - -vi.mock('sonner', () => ({ - toast: { warning: vi.fn(), dismiss: vi.fn() } -})) - -vi.mock('@/store/index', async () => { - const { create } = await import('zustand') - const { createRuntimeStatusSlice } = - await import('@/store/slices/runtime-status/create-runtime-status-slice') - type Slice = ReturnType - return { - useAppStore: create()((...a) => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the slice reads only its own fields. - createRuntimeStatusSlice(...(a as unknown as Parameters)) - ) - } -}) - -import { useAppStore } from '@/store/index' -import { clearRuntimeEnvironmentConnectionGenerations as clearRuntimeEnvironmentConnectionGenerationsForTests } from '@/store/slices/runtime-status/runtime-status-connection-generation' -import { subscribeRuntimeHostContactRegained } from './runtime-host-contact-regained' -import { - forgetStructuredSessionSelection, - registerStructuredSelectionCatalogStore -} from '@/lib/agent-session/options/structured-agent-session-selection-controller' - -function makeStatus(runtimeId: string): RuntimeStatus { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture carries only the fields the slice reads. - return { - runtimeId, - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 3 - } as RuntimeStatus -} - -let lastVerified: RuntimeStatus | null = null - -// Same-runtime return retains verified status and advances contact epoch, not connection generation. -function publish(status: RuntimeStatus | null, checkedAt: number): void { - lastVerified = status ?? lastVerified - useAppStore.getState().setRuntimeEnvironmentStatus('env-a', { - status, - checkedAt, - snapshot: { - environmentId: 'env-a', - pairingRevision: 1, - sequence: checkedAt, - checkedAt, - status: lastVerified, - verification: status ? 'verified' : 'unavailable', - transport: status ? 'ready' : 'disconnected' - } - }) -} - -let restoreCatalog: () => void -beforeEach(() => { - restoreCatalog = registerStructuredSelectionCatalogStore({ - read: useAppStore.getState, - subscribe: useAppStore.subscribe - }) - clearRuntimeEnvironmentConnectionGenerationsForTests() - vi.stubGlobal('window', { api: {}, dispatchEvent: vi.fn() }) - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map() }) - lastVerified = null -}) - -afterEach(() => { - forgetStructuredSessionSelection('continuity') - forgetStructuredSessionSelection('keyless') - restoreCatalog() - vi.unstubAllGlobals() -}) - -describe('subscribeRuntimeHostContactRegained', () => { - it('fires when the runtime answers again after an outage, and not while it stays down', () => { - publish(makeStatus('runtime-a'), 1) - let phase = 'down' - const observed: string[] = [] - const stop = subscribeRuntimeHostContactRegained('env-a', () => observed.push(phase)) - - publish(null, 2) - publish(null, 3) - expect(observed).toEqual([]) - - phase = 'same-runtime-return' - publish(makeStatus('runtime-a'), 4) - expect(observed).toEqual(['same-runtime-return']) - phase = 'unchanged' - publish(makeStatus('runtime-a'), 5) - expect(observed).toEqual(['same-runtime-return']) - - phase = 'restart' - publish(makeStatus('runtime-b'), 6) - expect(observed).toEqual(['same-runtime-return', 'restart']) - - stop() - phase = 'disposed' - publish(null, 7) - publish(makeStatus('runtime-b'), 8) - expect(observed).toEqual(['same-runtime-return', 'restart']) - }) -}) diff --git a/src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed-lifecycle.test.ts b/src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed-lifecycle.test.ts deleted file mode 100644 index 901dc759582..00000000000 --- a/src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed-lifecycle.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentSessionStatusEvent, - AgentSessionStatusSummary -} from '../../../../../shared/agent-session/agent-session-wire' - -const mocks = vi.hoisted(() => ({ subscribe: vi.fn() })) -vi.mock('../requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: mocks.subscribe -})) -vi.mock('../../rpc/compatibility/runtime-capability-proof', () => ({ - runtimeEnvironmentSupportsCapability: vi.fn() -})) - -import { - getStructuredAgentSessionStatusFeed, - resetStructuredAgentSessionStatusFeedsForTests -} from './structured-agent-session-status-feed' - -type Subscription = { - emit: (event: AgentSessionStatusEvent) => void - unsubscribe: ReturnType -} -const subscriptions: Subscription[] = [] -const owned: AgentSessionStatusSummary = { - sessionId: 'running', - workspaceId: 'workspace', - agent: 'codex', - status: 'working', - latestPrompt: 'work', - updatedAt: 1, - hostExecutionOwned: true, - hostExecutionPhase: 'starting' -} -const done: AgentSessionStatusSummary = { - ...owned, - sessionId: 'completed', - status: 'idle', - hostExecutionOwned: undefined, - hostExecutionPhase: undefined, - runtimePermission: null -} - -function subscription(index = 0): Subscription { - const value = subscriptions[index] - if (!value) { - throw new Error('missing subscription') - } - return value -} - -describe('structured status feed execution authority lifecycle', () => { - beforeEach(() => { - vi.useFakeTimers() - resetStructuredAgentSessionStatusFeedsForTests() - subscriptions.length = 0 - mocks.subscribe.mockReset() - mocks.subscribe.mockImplementation((_target, emit: Subscription['emit']) => { - const unsubscribe = vi.fn(() => emit({ type: 'end' })) - subscriptions.push({ emit, unsubscribe }) - return Promise.resolve({ unsubscribe }) - }) - }) - - afterEach(() => { - resetStructuredAgentSessionStatusFeedsForTests() - vi.useRealTimers() - }) - - it('revokes on end before reentrant unsubscribe and ignores late frames', async () => { - const feed = getStructuredAgentSessionStatusFeed({ kind: 'local' }) - feed.activate() - await vi.advanceTimersByTimeAsync(0) - expect(feed.getNamingActive('running')).toBeNull() - subscription().emit({ - type: 'snapshot', - sessions: [owned, done], - namingActiveSessionIds: ['running'] - }) - subscription().emit({ type: 'snapshot', sessions: [] }) - expect(feed.getNamingActive('running')).toBe(true) - subscription().emit({ type: 'end' }) - expect(feed.getNamingActive('running')).toBeNull() - expect(subscription().unsubscribe).toHaveBeenCalledOnce() - expect(feed.getSnapshot().get('running')).toEqual({ - ...owned, - hostExecutionOwned: undefined, - hostExecutionPhase: undefined, - runtimePermission: null - }) - expect(feed.getSnapshot().get('completed')).toBe(done) - subscription().emit({ type: 'status', session: owned }) - expect(feed.getSnapshot().get('running')?.hostExecutionOwned).toBeUndefined() - expect(vi.getTimerCount()).toBe(1) - await vi.advanceTimersByTimeAsync(250) - subscription(1).emit({ type: 'snapshot', sessions: [] }) - expect(feed.getNamingActive('running')).toBeNull() - subscription(1).emit({ type: 'snapshot', sessions: [done], namingActiveSessionIds: [] }) - subscription().emit({ type: 'snapshot', sessions: [], namingActiveSessionIds: ['running'] }) - expect(feed.getNamingActive('running')).toBe(false) - expect(feed.getSnapshot().get('running')?.hostExecutionOwned).toBeUndefined() - subscription(1).emit({ type: 'status', session: owned }) - expect(feed.getSnapshot().get('running')?.hostExecutionOwned).toBe(true) - }) -}) diff --git a/src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed.test.ts b/src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed.test.ts deleted file mode 100644 index 8780cdf5fc4..00000000000 --- a/src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentSessionStatusEvent, - AgentSessionStatusSummary -} from '../../../../../shared/agent-session/agent-session-wire' -import '../../../../../shared/agent-session/agent-session-attention-capabilities' - -const mocks = vi.hoisted(() => ({ - subscribeStatus: vi.fn(), - supportsCapability: vi.fn(), - unsubscribe: vi.fn() -})) - -vi.mock('../requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: mocks.subscribeStatus -})) - -vi.mock('../../rpc/compatibility/runtime-capability-proof', () => ({ - runtimeEnvironmentSupportsCapability: mocks.supportsCapability -})) - -import { - getStructuredAgentSessionStatusFeed, - resetStructuredAgentSessionStatusFeedsForTests -} from './structured-agent-session-status-feed' - -const LOCAL = { kind: 'local' } as const - -function summary( - sessionId: string, - status: AgentSessionStatusSummary['status'] = 'idle' -): AgentSessionStatusSummary { - return { - sessionId, - workspaceId: 'wt-1', - agent: 'codex', - status, - latestPrompt: 'hello', - updatedAt: 1 - } -} - -/** The event callback the feed handed to the most recent subscription. */ -function hostEmit(index = 0): (event: AgentSessionStatusEvent) => void { - const call = mocks.subscribeStatus.mock.calls[index] - if (!call) { - throw new Error('status feed not subscribed') - } - return call[1] as (event: AgentSessionStatusEvent) => void -} - -describe('structured agent session status feed', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.clearAllMocks() - resetStructuredAgentSessionStatusFeedsForTests() - mocks.subscribeStatus.mockResolvedValue({ unsubscribe: mocks.unsubscribe }) - mocks.supportsCapability.mockResolvedValue(true) - }) - - afterEach(() => { - resetStructuredAgentSessionStatusFeedsForTests() - vi.useRealTimers() - }) - - it('confirms sessions per connection and rejects late events from a disconnected stream', async () => { - const feed = getStructuredAgentSessionStatusFeed(LOCAL) - const deactivate = feed.activate() - await vi.advanceTimersByTimeAsync(0) - hostEmit()({ type: 'snapshot', sessions: [summary('one'), summary('two')] }) - expect(feed.getSessionObservation('one')).toBe('live') - await vi.advanceTimersByTimeAsync(31 * 60_000) - expect(feed.getSessionObservation('one')).toBe('live') - expect(mocks.subscribeStatus).toHaveBeenCalledOnce() - hostEmit()({ type: 'end' }) - expect(feed.getSessionObservation('one')).toBe('unverifiable') - hostEmit()({ type: 'status', session: summary('one') }) - expect(feed.getSessionObservation('one')).toBe('unverifiable') - await vi.advanceTimersByTimeAsync(300) - hostEmit(1)({ type: 'snapshot', sessions: [summary('two')] }) - expect(feed.getSessionObservation('two')).toBe('live') - expect(feed.getSessionObservation('one')).toBe('unverifiable') - expect(feed.getSnapshot().has('one')).toBe(true) - hostEmit(1)({ type: 'status', session: summary('one') }) - expect(feed.getSessionObservation('one')).toBe('live') - deactivate() - expect(feed.getSessionObservation('one')).toBe('unverifiable') - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/renderer/src/store/folder-workspaces/folder-path-status-ownership.test.ts b/src/renderer/src/store/folder-workspaces/folder-path-status-ownership.test.ts deleted file mode 100644 index 9ec1245a304..00000000000 --- a/src/renderer/src/store/folder-workspaces/folder-path-status-ownership.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { FolderWorkspacePathStatus } from '../../../../shared/folder-workspaces/folder-workspace-path-status' - -import './folder-path-status' -import '../../../../shared/project-groups' -import { makeFolderWorkspace } from '@/components/worktree-jump/worktree-jump-palette-test-fixtures' -import { createTestStore } from '../testing/app-store-test-fixture' - -const mocks = vi.hoisted(() => ({ getPathStatus: vi.fn(), callRuntimeRpc: vi.fn() })) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - callRuntimeRpc: mocks.callRuntimeRpc - } -}) - -const owners = [ - { executionHostId: 'local', runtimeEnvironmentId: null, path: '/local/folder' }, - { executionHostId: 'runtime:builder', runtimeEnvironmentId: 'builder', path: '/remote/folder' } -] as const - -const folders = owners.map((owner) => - makeFolderWorkspace({ executionHostId: owner.executionHostId, folderPath: owner.path }) -) -const request = { scope: 'folder-workspace', folderWorkspaceId: folders[0].id } as const - -beforeEach(() => { - vi.clearAllMocks() - vi.stubGlobal('window', { - api: { folderWorkspaces: { getPathStatus: mocks.getPathStatus } } - }) -}) - -describe('folder path status ownership', () => { - it.each(owners)( - 'rejects a delayed $executionHostId error after its folder path changes', - async (owner) => { - const store = createTestStore() - // The selected folder is second, so a bare-id lookup would fingerprint the other host. - store.setState({ - folderWorkspaces: [ - ...folders.filter((folder) => folder.executionHostId !== owner.executionHostId), - ...folders.filter((folder) => folder.executionHostId === owner.executionHostId) - ] - }) - const pending = Promise.withResolvers() - mocks.getPathStatus.mockReturnValue(pending.promise) - mocks.callRuntimeRpc.mockImplementation(async () => ({ status: await pending.promise })) - const oldProbe = store.getState().fetchFolderWorkspacePathStatus(request, owner) - const repairedPath = `${owner.path}-repaired` - store.setState((state) => ({ - folderWorkspaces: state.folderWorkspaces.map((folder) => - folder.executionHostId === owner.executionHostId - ? { ...folder, folderPath: repairedPath } - : folder - ), - folderWorkspacePathStatuses: {} - })) - const repairedStatus = { path: repairedPath, exists: true } - mocks.getPathStatus.mockResolvedValue(repairedStatus) - mocks.callRuntimeRpc.mockResolvedValue({ status: repairedStatus }) - await store.getState().fetchFolderWorkspacePathStatus(request, { ...owner, force: true }) - - pending.resolve({ path: owner.path, exists: false, reason: 'missing' }) - await oldProbe - - expect(store.getState().getFreshFolderWorkspacePathStatus(request, owner)).toEqual( - repairedStatus - ) - } - ) -}) diff --git a/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts b/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts deleted file mode 100644 index 724e4cad736..00000000000 --- a/src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _clearGitHubPRRefreshStartedEntriesForTest } from '../requests/request-coordination' -import { - createTestStore, - makePR, - mockApi, - resetRemoteRuntimeMocks -} from '../github-slice-test-harness' -import type { AppState } from '../../types' -import { getHostedReviewCacheKey } from '../../slices/hosted-review/hosted-review-cache-identity' - -describe('createGitHubSlice.fetchPRForBranch', () => { - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - mockApi.gh.prForBranch.mockResolvedValue(null) - mockApi.gh.refreshPRNow.mockReset() - mockApi.gh.refreshPRNow.mockResolvedValue({ kind: 'no-pr', fetchedAt: Date.now() }) - mockApi.hostedReview.forBranch.mockResolvedValue(null) - _clearGitHubPRRefreshStartedEntriesForTest() - }) - - afterEach(() => { - _clearGitHubPRRefreshStartedEntriesForTest() - vi.useRealTimers() - }) - - it('ignores a direct exact linked PR refresh after the worktree was unlinked', async () => { - const store = createTestStore() - const repoPath = '/repo' - const repoId = 'repo-1' - const branch = 'feature/unlinked-direct-pr' - const worktreeId = 'wt-unlinked-direct-pr' - const hostedReviewCacheKey = getHostedReviewCacheKey(repoPath, branch, null, repoId) - let resolveRefresh: ( - value: Awaited> - ) => void = () => {} - const refresh = new Promise>>((resolve) => { - resolveRefresh = resolve - }) - mockApi.gh.refreshPRNow.mockReturnValueOnce(refresh) - - store.setState({ - repos: [{ id: repoId, path: repoPath, name: 'repo', kind: 'git' }], - worktreesByRepo: { - [repoId]: [ - { - id: worktreeId, - repoId, - path: '/repo/worktrees/unlinked-direct-pr', - branch, - displayName: 'unlinked-direct-pr', - isMainWorktree: false, - isBare: false, - isArchived: false, - linkedPR: 12 - } - ] - } - } as unknown as Partial) - - const request = store.getState().fetchPRForBranch(repoPath, branch, { - force: true, - repoId, - worktreeId, - linkedPRNumber: 12 - }) - store.setState({ - worktreesByRepo: { - [repoId]: [ - { - id: worktreeId, - repoId, - path: '/repo/worktrees/unlinked-direct-pr', - branch, - displayName: 'unlinked-direct-pr', - isMainWorktree: false, - isBare: false, - isArchived: false, - linkedPR: null - } - ] - }, - hostedReviewCache: {}, - prCache: {} - } as unknown as Partial) - resolveRefresh({ - kind: 'found', - pr: makePR({ number: 12, title: 'Stale exact linked PR' }), - fetchedAt: Date.now() - }) - - await expect(request).resolves.toBeNull() - - expect(store.getState().prCache[`${repoId}::${branch}`]).toBeUndefined() - expect(store.getState().hostedReviewCache[hostedReviewCacheKey]).toBeUndefined() - }) -}) diff --git a/src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts b/src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts deleted file mode 100644 index 7d99cc2bfcc..00000000000 --- a/src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' -import type { PluginChangeEvent } from '../../../../../shared/plugins/events/plugin-change-event' -import type { usePluginPanelsStore } from './plugin-contribution-catalog' - -type List = () => Promise -type PanelStore = typeof usePluginPanelsStore - -function plugin(): PluginHostListEntry { - return { - pluginKey: 'samples.current', - consentFingerprint: 'test', - name: 'Current', - version: '1', - publisher: 'test', - status: 'idle', - needsReconsent: false, - isDev: false, - official: false, - bundled: false, - capabilities: [], - panels: [], - commands: [], - hasWorker: false, - restarts: 0 - } -} - -function view(store: PanelStore) { - const { plugins, panelErrors, fetchStatus } = store.getState() - return { plugins, panelErrors, fetchStatus } -} - -async function harness(list: List) { - let changed: ((event: PluginChangeEvent) => void) | undefined - const onChanged = vi.fn((callback: (event: PluginChangeEvent) => void) => { - changed = callback - return vi.fn() - }) - vi.stubGlobal('window', { api: { plugins: { list, onChanged } } }) - const { usePluginPanelsStore: store, ensurePluginPanelsLoaded: ensure } = - await import('./plugin-contribution-catalog') - return { store, ensure, onChanged, change: () => changed?.({ contentPacksChanged: false }) } -} - -beforeEach(() => { - vi.resetModules() - vi.useFakeTimers() - vi.setSystemTime(0) -}) - -afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -it('keeps an authoritative replacement made reentrantly during loading above the older failure', async () => { - const gate = Promise.withResolvers() - const rows = [plugin()] - const list = vi - .fn() - .mockRejectedValueOnce(new Error('starting')) - .mockReturnValueOnce(gate.promise) - const { store } = await harness(list) - await store.getState().fetchPlugins() - const unsubscribe = store.subscribe((state) => { - if (state.fetchStatus === 'loading') { - store.getState().setPlugins(rows) - } - }) - const pending = store.getState().fetchPlugins() - const failure = new Error('old request failed') - gate.reject(failure) - await expect(pending).resolves.toBeUndefined() - await expect(list.mock.results[1]?.value).rejects.toBe(failure) - await vi.advanceTimersByTimeAsync(500) - expect(list).toHaveBeenCalledTimes(2) - expect(store.getState().plugins).toBe(rows) - expect(view(store)).toEqual({ plugins: rows, panelErrors: {}, fetchStatus: 'ready' }) - expect(vi.getTimerCount()).toBe(0) - unsubscribe() -}) - -it('retains the latest reentrant fetch and ignores the superseded request result', async () => { - const gate = Promise.withResolvers() - const rows = [plugin()] - const list = vi - .fn() - .mockRejectedValueOnce(new Error('starting')) - .mockResolvedValueOnce(rows) - .mockReturnValueOnce(gate.promise) - const { store } = await harness(list) - await store.getState().fetchPlugins() - let entered = false - let latest: Promise | undefined - const unsubscribe = store.subscribe((state) => { - if (!entered && state.fetchStatus === 'loading') { - entered = true - latest = store.getState().fetchPlugins() - } - }) - const old = store.getState().fetchPlugins() - await latest - const timers = vi.getTimerCount() - gate.reject(new Error('superseded')) - await expect(old).resolves.toBeUndefined() - await vi.advanceTimersByTimeAsync(500) - expect(list).toHaveBeenCalledTimes(3) - expect(store.getState().plugins).toBe(rows) - expect(view(store)).toEqual({ plugins: rows, panelErrors: {}, fetchStatus: 'ready' }) - unsubscribe() - expect(timers).toBe(0) -}) diff --git a/src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts b/src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts deleted file mode 100644 index 1b631407459..00000000000 --- a/src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PluginChangeEvent } from '../../../../../shared/plugins/events/plugin-change-event' -import { - pluginLanguageResourceId, - type PluginLanguagePackRegistration -} from '../../../../../shared/plugins/artifacts/plugin-language-pack-artifact' -import type * as LanguagePackModule from './plugin-language-packs' - -let languagePacks: typeof LanguagePackModule - -function pack(name: string): PluginLanguagePackRegistration { - const id = `plugin:${name}` as const - return { - id, - resourceLanguage: pluginLanguageResourceId(id), - pluginKey: name, - locale: 'en', - catalog: {}, - coverage: 100 - } -} - -function installBridge() { - const requests: ReturnType>[] = [] - const listLanguagePacks = vi.fn(() => { - const request = Promise.withResolvers() - requests.push(request) - return request.promise - }) - const listeners: ((event: PluginChangeEvent) => void)[] = [] - const onChanged = vi.fn((listener: (event: PluginChangeEvent) => void) => { - listeners.push(listener) - return () => {} - }) - vi.stubGlobal('api', { plugins: { listLanguagePacks, onChanged } }) - return { requests, listLanguagePacks, onChanged, listeners } -} - -beforeEach(async () => { - vi.resetModules() - languagePacks = await import('./plugin-language-packs') -}) - -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) - -describe('plugin language-pack startup ownership', () => { - it('keeps the shared startup request alive after the first consumer unmounts', async () => { - const bridge = installBridge() - const first = renderHook(() => languagePacks.usePluginLanguagePacks()) - first.unmount() - const second = renderHook(() => languagePacks.usePluginLanguagePacks()) - const dispatches = bridge.listLanguagePacks.mock.calls.length - await act(async () => { - for (const request of bridge.requests) { - request.resolve([pack('retained')]) - } - await Promise.all(bridge.requests.map((request) => request.promise)) - }) - expect(dispatches).toBe(1) - expect(second.result.current).toEqual([pack('retained')]) - }) - - it('retries a wedged startup request instead of joining it for the session', async () => { - vi.useFakeTimers() - try { - const bridge = installBridge() - languagePacks.ensurePluginLanguagePacksLoaded() - // A request that is merely slow is shared, not duplicated. - vi.advanceTimersByTime(9_000) - languagePacks.ensurePluginLanguagePacksLoaded() - expect(bridge.listLanguagePacks).toHaveBeenCalledTimes(1) - // Past the join window it is wedged, so a later consumer must be able to make progress. - vi.advanceTimersByTime(2_000) - languagePacks.ensurePluginLanguagePacksLoaded() - expect(bridge.listLanguagePacks).toHaveBeenCalledTimes(2) - bridge.requests[1].resolve([pack('recovered')]) - await vi.waitFor(() => - expect(languagePacks.usePluginLanguagePackStore.getState().loaded).toBe(true) - ) - expect(languagePacks.usePluginLanguagePackStore.getState().entries).toEqual([ - pack('recovered') - ]) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/renderer/src/store/project-groups/repos-project-group-cross-host-move.test.ts b/src/renderer/src/store/project-groups/repos-project-group-cross-host-move.test.ts deleted file mode 100644 index cb5f69c3fc8..00000000000 --- a/src/renderer/src/store/project-groups/repos-project-group-cross-host-move.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * #13699: a project can only join a group in its own host's catalog. The host stores any other - * group id as "no group" and still returns the row, so the move used to look successful. - */ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import type { ProjectGroup } from '../../../../shared/project-group-types' -import type { Repo } from '../../../../shared/repo-types' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import { - createCompatibleRuntimeStatusResponseIfNeeded, - type RuntimeEnvironmentCallRequest -} from '../../runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache' -import { createTestStore } from '../testing/app-store-test-fixture' - -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) - -const REMOTE_HOST: ExecutionHostId = 'runtime:env-b' - -const remoteRepo: Repo = { - id: 'remote-only', - path: '/srv/remote-only', - displayName: 'remote-only', - badgeColor: '#111', - addedAt: 1, - executionHostId: REMOTE_HOST, - projectGroupId: 'remote-group' -} - -function group(id: string, executionHostId: ExecutionHostId): ProjectGroup { - return { - id, - name: id, - parentPath: null, - executionHostId, - parentGroupId: null, - createdFrom: 'manual', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } -} - -const moveProject = vi.fn() -const runtimeCall = vi.fn<(request: RuntimeEnvironmentCallRequest) => Promise>() - -function runtimeMoveReturns(repo: Repo): void { - runtimeCall.mockResolvedValue({ - id: 'rpc-move', - ok: true, - result: { repo }, - _meta: { runtimeId: 'runtime-b' } - }) -} - -function moveCalls(): RuntimeEnvironmentCallRequest[] { - return runtimeCall.mock.calls - .map(([request]) => request) - .filter((request) => request.method === 'projectGroup.moveProject') -} - -beforeEach(() => { - clearRuntimeCompatibilityCacheForTests() - vi.mocked(toast.error).mockReset() - moveProject.mockReset() - runtimeCall.mockReset() - vi.stubGlobal('window', { - api: { - projectGroups: { moveProject }, - runtimeEnvironments: { - call: (request: RuntimeEnvironmentCallRequest) => - createCompatibleRuntimeStatusResponseIfNeeded(request) ?? runtimeCall(request) - } - } - }) -}) - -describe('moving one twin of a repo id on a paired server (server-local and server-SSH rows)', () => { - it('names the twin by its server-side SSH target and updates only that row', async () => { - const serverLocalTwin: Repo = { ...remoteRepo, connectionId: null, projectGroupId: null } - const serverSshTwin: Repo = { ...remoteRepo, connectionId: 'srv-ssh', projectGroupId: null } - runtimeMoveReturns({ ...serverSshTwin, projectGroupId: 'remote-group' }) - const store = createTestStore() - store.setState({ - repos: [serverLocalTwin, serverSshTwin], - projectGroups: [group('remote-group', REMOTE_HOST)] - }) - - await expect(store.getState().moveProjectToGroup(serverSshTwin, 'remote-group')).resolves.toBe( - true - ) - - expect(moveCalls().map((request) => request.params)).toEqual([ - { repo: remoteRepo.id, groupId: 'remote-group', connectionId: 'srv-ssh' } - ]) - expect(store.getState().repos.map((repo) => repo.projectGroupId ?? null)).toEqual([ - null, - 'remote-group' - ]) - }) -}) diff --git a/src/renderer/src/store/repos/repos-catalog-connection-fence.test.ts b/src/renderer/src/store/repos/repos-catalog-connection-fence.test.ts deleted file mode 100644 index d6b178b7042..00000000000 --- a/src/renderer/src/store/repos/repos-catalog-connection-fence.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -/** - * #20811: a repo catalog fetched over a runtime connection that was replaced mid-fetch must not - * overwrite the current one, and a dropped catalog is not an answer for repo-scoped UI cleanup. - */ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import { - createCompatibleRuntimeStatusResponseIfNeeded, - type RuntimeEnvironmentCallRequest -} from '../../runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache' -import { createTestStore } from '../testing/app-store-test-fixture' - -const sshState = vi.hoisted(() => ({ generation: 0 })) - -vi.mock('../slices/ssh/runtime-environment-ssh', async (importOriginal) => ({ - ...(await importOriginal()), - getEnvironmentSshStateGeneration: () => sshState.generation -})) - -function repo(id: string, path: string): Repo { - return { id, path, displayName: id, badgeColor: '#000', addedAt: 1 } -} - -const runtimeEnvironmentCall = vi.fn() - -function stubRemoteRepoList(remote: Promise, onStart: () => void): void { - runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { - if (args.method === 'repo.list') { - onStart() - return remote - } - return { - id: 'rpc-other', - ok: true, - result: { projects: [], setups: [] }, - _meta: { runtimeId: 'runtime-remote' } - } - }) -} - -beforeEach(() => { - sshState.generation = 0 - clearRuntimeCompatibilityCacheForTests() - runtimeEnvironmentCall.mockReset() - vi.stubGlobal('window', { - api: { - repos: { list: vi.fn().mockResolvedValue([repo('local-repo', '/local')]) }, - projects: { - list: vi.fn().mockResolvedValue([]), - listHostSetups: vi.fn().mockResolvedValue([]) - }, - runtimeEnvironments: { - list: vi.fn().mockResolvedValue([{ id: 'env-1', name: 'Remote' }]), - call: (args: RuntimeEnvironmentCallRequest) => - createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) - } - }, - dispatchEvent: vi.fn() - }) -}) - -describe('repo catalogs use the host-catalog fence (#20811)', () => { - it('keeps the newer all-host load when a superseded one finishes listing hosts late', async () => { - const olderHosts = Promise.withResolvers<{ id: string; name: string }[]>() - const listHosts = vi - .fn() - .mockReturnValueOnce(olderHosts.promise) - .mockResolvedValue([{ id: 'env-1', name: 'Remote' }]) - vi.mocked(window.api.runtimeEnvironments).list = listHosts - const newerRemote = Promise.withResolvers() - const newerStarted = Promise.withResolvers() - stubRemoteRepoList(newerRemote.promise, newerStarted.resolve) - const store = createTestStore() - - const older = store.getState().fetchReposForAllHosts() - await vi.waitFor(() => expect(listHosts).toHaveBeenCalledOnce()) - const newer = store.getState().fetchReposForAllHosts() - await newerStarted.promise - olderHosts.resolve([{ id: 'env-1', name: 'Remote' }]) - await older - newerRemote.resolve({ - id: 'rpc-repo-list', - ok: true, - result: { repos: [repo('remote-repo', '/remote')] }, - _meta: { runtimeId: 'runtime-remote' } - }) - await newer - - expect(store.getState().repos.map((entry) => entry.id)).toContain('remote-repo') - }) -}) diff --git a/src/renderer/src/store/repos/repos-remove-missing-remote-project.test.ts b/src/renderer/src/store/repos/repos-remove-missing-remote-project.test.ts deleted file mode 100644 index 779bc96d670..00000000000 --- a/src/renderer/src/store/repos/repos-remove-missing-remote-project.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -/** Treat only repo_not_found as already removed and purge client ghost rows (#11994). Other failures retain rows; toasts remain opt-in for single-project callers while bulk/background aggregate errors. */ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import { createTestStore } from '../testing/app-store-test-fixture' -import type { Repo } from '../../../../shared/repo-types' -import { - createCompatibleRuntimeStatusResponseIfNeeded, - type RuntimeEnvironmentCallRequest -} from '../../runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -const staleRemoteRepo: Repo = { - id: 'project-b', - path: '/Users/mini/project-b', - displayName: 'Project B', - badgeColor: '#000', - addedAt: 1, - executionHostId: 'runtime:env-1' -} - -const liveRemoteRepo: Repo = { - id: 'project-a', - path: '/Users/mini/project-a', - displayName: 'Project A', - badgeColor: '#111', - addedAt: 2, - executionHostId: 'runtime:env-1' -} - -const reposRemove = vi.fn() -const reposRemoveForHost = vi.fn() -const ptyKill = vi.fn() -const runtimeEnvironmentCall = vi.fn() -const runtimeEnvironmentTransportCall = vi.fn() - -function answerRepoRmWith(code: string): void { - runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { - if (args.method === 'repo.rm') { - return { - id: 'rpc-repo-rm', - ok: false, - error: { code, message: code }, - _meta: { runtimeId: 'runtime-remote' } - } - } - return { id: 'rpc-other', ok: true, result: {}, _meta: { runtimeId: 'runtime-remote' } } - }) -} - -function seedRemoteProjects(repos: readonly Repo[]): ReturnType { - const store = createTestStore() - store.setState({ - settings: { activeRuntimeEnvironmentId: 'env-1' } as never, - repos: [...repos] - }) - return store -} - -beforeEach(() => { - clearRuntimeCompatibilityCacheForTests() - vi.mocked(toast.error).mockReset() - for (const mock of [ - reposRemove, - reposRemoveForHost, - ptyKill, - runtimeEnvironmentCall, - runtimeEnvironmentTransportCall - ]) { - mock.mockReset() - } - runtimeEnvironmentTransportCall.mockImplementation( - (args: RuntimeEnvironmentCallRequest) => - createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) - ) - vi.stubGlobal('window', { - api: { - repos: { remove: reposRemove, removeForHost: reposRemoveForHost }, - pty: { kill: ptyKill }, - runtimeEnvironments: { call: runtimeEnvironmentTransportCall }, - ui: { set: vi.fn().mockResolvedValue(undefined) } - } - }) -}) - -describe('removeProject when the owning host already dropped the project', () => { - it('still finishes the removal when the residue cleanup throws', async () => { - answerRepoRmWith('repo_not_found') - reposRemoveForHost.mockImplementation(() => { - throw new Error('Forgetting a host is unavailable in paired web clients.') - }) - const store = seedRemoteProjects([liveRemoteRepo, staleRemoteRepo]) - - await store.getState().removeProject('project-b', { hostId: 'runtime:env-1' }) - - expect(store.getState().repos.map((repo) => repo.id)).toEqual(['project-a']) - }) -}) diff --git a/src/renderer/src/store/repos/runtime-catalog-merge-removed-env-guard.test.ts b/src/renderer/src/store/repos/runtime-catalog-merge-removed-env-guard.test.ts deleted file mode 100644 index 19dcd74a1eb..00000000000 --- a/src/renderer/src/store/repos/runtime-catalog-merge-removed-env-guard.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call' -/** Only tombstoned catalog.hostId values block late merges (#8881); an unhydrated saved list or serving-local runtime stamps cannot prove removal. */ -import { describe, it, expect, vi } from 'vitest' - -import type { Repo } from '../../../../shared/repo-types' -import type { PublicKnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: vi.fn(), - unregisterPtyDataHandlers: vi.fn() -})) - -// All RPCs share this fixture shape; compatibility probes read projects/setups while repo.list reads repos. -const rpcResult = vi.hoisted(() => ({ current: { repos: [] as Repo[], projects: [], setups: [] } })) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - callRuntimeRpc: vi.fn(async () => rpcResult.current) - } -}) - -const localReposList = vi.fn<() => Promise>() - -// @ts-expect-error -- minimal window.api stub for the store under test -globalThis.window = { api: { repos: { list: localReposList } } } - -import { createTestStore, seedStore } from '../testing/app-store-test-fixture' -import { TEST_REPO } from './repo.test-fixture' - -function env(id: string): PublicKnownRuntimeEnvironment { - return { id } as unknown as PublicKnownRuntimeEnvironment -} - -function repo(id: string, extra: Partial = {}): Repo { - return { - id, - path: `/${id}`, - displayName: id, - badgeColor: '#000', - addedAt: 0, - ...extra - } as Repo -} - -describe('environment-catalog merge guard drops catalogs for a removed env', () => { - it('fetchRuntimeEnvironmentRepos skips the merge when the catalog env was removed (tombstoned)', async () => { - const store = createTestStore() - seedStore(store, { - repos: [TEST_REPO], - runtimeEnvironments: [env('env-gone'), env('env-b')] - }) - // Tombstone env-gone before its in-flight fetch returns. - store.getState().setRuntimeEnvironments([env('env-b')]) - rpcResult.current = { repos: [repo('ghost')], projects: [], setups: [] } - - await store.getState().fetchRuntimeEnvironmentRepos('env-gone') - - expect(store.getState().repos.map((r) => r.id)).toEqual(['repo1']) - }) - - it('fetchRuntimeEnvironmentRepos merges a catalog whose env is absent but not tombstoned (not yet hydrated)', async () => { - // On boot, disk catalogs may arrive before the saved list; absence alone cannot block merging. - const store = createTestStore() - seedStore(store, { repos: [TEST_REPO], runtimeEnvironments: [] }) - rpcResult.current = { repos: [repo('fresh')], projects: [], setups: [] } - - await store.getState().fetchRuntimeEnvironmentRepos('env-hydrating') - - expect( - store - .getState() - .repos.map((r) => r.id) - .sort() - ).toEqual(['fresh', 'repo1']) - }) -}) diff --git a/src/renderer/src/store/repos/store-session-cascades.test.ts b/src/renderer/src/store/repos/store-session-cascades.test.ts deleted file mode 100644 index ecc22cf5c33..00000000000 --- a/src/renderer/src/store/repos/store-session-cascades.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import { createTestStore } from '../testing/app-store-test-fixture' -import { makeWorktree } from '../slices/worktrees/worktree.test-fixture' -import { makeTab, makeLayout } from '../terminals/testing/terminal-tab.test-fixture' -import { createStoreSessionMockApi } from '../testing/app-store-session-api.test-fixture' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -const mockApi = createStoreSessionMockApi() - -describe('removeProject cascade', () => { - beforeEach(() => { - vi.clearAllMocks() - mockApi.repos.removeForHost.mockResolvedValue(undefined) - mockApi.pty.kill.mockResolvedValue(undefined) - }) - - it('cleans up all associated worktrees, tabs, ptys, and filter state', async () => { - const store = createTestStore() - const wt1 = 'repo1::/path/wt1' - const wt2 = 'repo1::/path/wt2' - - store.setState({ - repos: [ - { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } - ], - activeRepoId: 'repo1', - filterRepoIds: ['repo1'], - worktreesByRepo: { - repo1: [ - makeWorktree({ id: wt1, repoId: 'repo1', path: '/path/wt1' }), - makeWorktree({ id: wt2, repoId: 'repo1', path: '/path/wt2' }) - ] - }, - tabsByWorktree: { - [wt1]: [makeTab({ id: 'tab1', worktreeId: wt1 })], - [wt2]: [makeTab({ id: 'tab2', worktreeId: wt2 })] - }, - ptyIdsByTabId: { - tab1: ['pty1'], - tab2: ['pty2'] - }, - suppressedPtyExitIds: { pty1: true, pty2: true }, - pendingPaneAccountRestarts: { pty1: 'codex', pty2: 'codex' }, - terminalLayoutsByTabId: { - tab1: makeLayout(), - tab2: makeLayout() - }, - activeTabId: 'tab1' - }) - - await store.getState().removeProject('repo1', { hostId: 'local' }) - const s = store.getState() - - expect(s.repos).toEqual([]) - expect(s.activeRepoId).toBeNull() - expect(s.filterRepoIds).not.toContain('repo1') - expect(s.worktreesByRepo['repo1']).toBeUndefined() - expect(s.tabsByWorktree[wt1]).toBeUndefined() - expect(s.tabsByWorktree[wt2]).toBeUndefined() - expect(s.ptyIdsByTabId['tab1']).toBeUndefined() - expect(s.ptyIdsByTabId['tab2']).toBeUndefined() - expect(s.terminalLayoutsByTabId['tab1']).toBeUndefined() - expect(s.terminalLayoutsByTabId['tab2']).toBeUndefined() - expect(s.activeTabId).toBeNull() - - // Tabs are gone before async exit events fire, so retaining one-shot guards would leak ephemeral PTY ids. - - store.getState().clearTabPtyId('tab1', 'pty1') - store.getState().clearTabPtyId('tab2', 'pty2') - - // Why: exit IPC can arrive after repo purge but before the pane unmounts; a late exit must not recreate an index for an ownerless tab. - expect(store.getState().ptyIdsByTabId['tab1']).toBeUndefined() - expect(store.getState().ptyIdsByTabId['tab2']).toBeUndefined() - }) -}) diff --git a/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents-pairing.test.ts b/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents-pairing.test.ts deleted file mode 100644 index 89227023ecc..00000000000 --- a/src/renderer/src/store/slices/agent-inventory/runtime-detected-agents-pairing.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call' -import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof' -import type * as RuntimeCompatibilityProbeModule from '@/runtime/rpc/compatibility/runtime-compatibility-probe' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { PublicKnownRuntimeEnvironment } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments' - -const rpc = vi.hoisted(() => ({ call: vi.fn(), supports: vi.fn(), status: vi.fn() })) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (original) => ({ - ...(await original()), - callRuntimeRpc: rpc.call -})) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (original) => ({ - ...(await original()), - runtimeEnvironmentSupportsCapability: rpc.supports -})) -vi.mock('@/runtime/rpc/compatibility/runtime-compatibility-probe', async (original) => ({ - ...(await original()), - getRuntimeEnvironmentStatus: rpc.status -})) -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: vi.fn(), - unregisterPtyDataHandlers: vi.fn() -})) - -// @ts-expect-error -- minimal API stub for the store under test -globalThis.window = { api: {} } -import { createRuntimeDetectedAgentsPairingTestStore as createTestStore } from './runtime-detected-agents-pairing.test-fixture' -import { getRuntimeAgentInventoryKey } from './runtime-agent-inventory-key' - -function environment(pairingRevision: number): PublicKnownRuntimeEnvironment { - return { - id: 'detection-peer', - name: 'Paired host', - createdAt: 1, - updatedAt: pairingRevision, - pairingRevision, - lastUsedAt: null, - runtimeId: null, - endpoints: [], - preferredEndpointId: 'host' - } -} - -const WORKTREE = 'repo::/workspace' -const WORKSPACE_KEY = getRuntimeAgentInventoryKey('detection-peer', WORKTREE) - -beforeEach(() => { - rpc.call.mockReset() - rpc.supports.mockReset() - rpc.status.mockReset() - createTestStore().getState().clearRuntimeDetectedAgents('detection-peer') -}) - -describe('runtime detection across a re-pair', () => { - it('sends a workspace probe whose capability check straddles a re-pair fenced to the retired pairing', async () => { - const store = createTestStore() - let answerCapability!: (supported: boolean) => void - rpc.supports.mockReturnValueOnce( - new Promise((resolve) => { - answerCapability = resolve - }) - ) - rpc.call.mockResolvedValue(['claude']) - store.getState().setRuntimeEnvironments([environment(1)]) - const old = store.getState().ensureRuntimeDetectedAgents('detection-peer', WORKTREE) - store.getState().setRuntimeEnvironments([environment(2)]) - answerCapability(true) - await old - expect(rpc.call).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'detection-peer' }, - 'preflight.detectAgents', - { worktreeId: 'repo::/workspace' }, - { expectedEnvironmentPairingRevision: 1 } - ) - expect(store.getState().runtimeDetectedAgentIds[WORKSPACE_KEY]).toBeUndefined() - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts b/src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts deleted file mode 100644 index ffe576f6a22..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' -import { - resetAgentPaneAuthorityAliasesForTests, - resolveAgentPaneAuthorityKey -} from './agent-pane-authority' -import { createTestStore } from '../../testing/app-store-test-fixture' - -const SOURCE = makePaneKey('tab-source', '11111111-1111-4111-8111-111111111111') -const TARGET = makePaneKey('tab-target', '22222222-2222-4222-8222-222222222222') - -const retirePaneAuthority = vi.fn() -const restorePaneAuthority = vi.fn() -const transferPaneAuthority = vi.fn() -const dropByTabPrefix = vi.fn() - -beforeEach(() => { - resetAgentPaneAuthorityAliasesForTests() - vi.clearAllMocks() - vi.stubGlobal('window', { - api: { - agentStatus: { - retirePaneAuthority, - restorePaneAuthority, - transferPaneAuthority, - dropByTabPrefix, - drop: vi.fn() - } - } - }) -}) - -afterEach(() => { - resetAgentPaneAuthorityAliasesForTests() - vi.unstubAllGlobals() -}) - -describe('agent pane authority', () => { - // Detach/reattach must lift renderer tombstones or still-running panes lose status permanently (STA-4114). - it('lifts the retirement fence on re-attach so an in-flight turn can still report done', () => { - const store = createTestStore() - store.getState().setAgentStatus(TARGET, { state: 'working', prompt: 'turn in flight' }) - store.getState().retireAgentPaneAuthority(TARGET) - - // Reattach mid-turn emits no new turn; revival cannot wait for one. - store.getState().setAgentStatus(TARGET, { state: 'done', prompt: 'turn in flight' }) - expect(store.getState().agentStatusByPaneKey[TARGET]).toBeUndefined() - - store.getState().restoreAgentPaneAuthority(TARGET) - expect(store.getState().recentlyRetiredAgentStatusPaneKeys[TARGET]).toBeUndefined() - expect(restorePaneAuthority).toHaveBeenCalledWith(TARGET) - - store.getState().setAgentStatus(TARGET, { state: 'done', prompt: 'turn in flight' }) - expect(store.getState().agentStatusByPaneKey[TARGET]?.state).toBe('done') - }) - - it('does not lift a closed-tab tombstone on re-attach', () => { - const store = createTestStore() - store.getState().setAgentStatus(TARGET, { state: 'working', prompt: 'before close' }) - store.getState().dropAgentStatusByTabPrefix('tab-target') - - store.getState().restoreAgentPaneAuthority(TARGET) - expect(restorePaneAuthority).not.toHaveBeenCalled() - - store.getState().setAgentStatus(TARGET, { state: 'working', prompt: 'after close' }) - expect(store.getState().agentStatusByPaneKey[TARGET]).toBeUndefined() - }) - - it('clears the alias when a pane moves back to a key it previously left', () => { - const store = createTestStore() - store.getState().setAgentStatus(SOURCE, { state: 'working', prompt: 'source' }) - - store - .getState() - .transferAgentPaneAuthority({ fromPaneKey: SOURCE, toPaneKey: TARGET, ptyId: 'pty-1' }) - store - .getState() - .transferAgentPaneAuthority({ fromPaneKey: TARGET, toPaneKey: SOURCE, ptyId: 'pty-1' }) - - expect(resolveAgentPaneAuthorityKey(SOURCE)).toBe(SOURCE) - expect(resolveAgentPaneAuthorityKey(TARGET)).toBe(SOURCE) - store.getState().setAgentStatus(SOURCE, { state: 'done', prompt: 'back home' }) - expect(store.getState().agentStatusByPaneKey[SOURCE]?.prompt).toBe('back home') - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-runtime-orchestration.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-runtime-orchestration.test.ts deleted file mode 100644 index a7136bb9fe2..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-status-runtime-orchestration.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { createTestStore } from '../../testing/app-store-test-fixture' - -import type { AgentStatusObservation } from '../../../../../shared/agent-status/contracts/agent-status-observation' - -import '@/components/sidebar/workspace-card/activity/worktree-card-agent-summary' - -{ - describe('agent status runtime orchestration metadata', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('keeps current payload orchestration ahead of a stale runtime map entry', () => { - vi.useFakeTimers() - const store = createTestStore() - const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' - - store.getState().setRuntimeAgentOrchestrationByPaneKey({ - [childPaneKey]: { - taskId: 'task-1', - dispatchId: 'ctx-1', - parentTerminalHandle: 'term-stale' - } - }) - store.getState().setAgentStatus(childPaneKey, { - state: 'working', - prompt: 'child agent', - agentType: 'codex', - orchestration: { - taskId: 'task-2', - dispatchId: 'ctx-2', - parentTerminalHandle: 'term-current' - } - }) - - expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toEqual({ - taskId: 'task-2', - dispatchId: 'ctx-2', - parentTerminalHandle: 'term-current' - }) - }) - - it('clears stale live orchestration when a reused pane starts non-orchestrated work', () => { - vi.useFakeTimers() - const store = createTestStore() - const childPaneKey = 'tab-child:11111111-1111-4111-8111-111111111111' - - store.getState().setAgentStatus(childPaneKey, { - state: 'done', - prompt: 'finished child', - agentType: 'codex', - orchestration: { - taskId: 'task-1', - dispatchId: 'ctx-1', - parentTerminalHandle: 'term-parent' - } - }) - store.getState().setRuntimeAgentOrchestrationByPaneKey({}) - store.getState().setAgentStatus(childPaneKey, { - state: 'working', - prompt: 'manual follow-up', - agentType: 'codex' - }) - - expect(store.getState().agentStatusByPaneKey[childPaneKey].orchestration).toBeUndefined() - }) - }) -} - -{ - // Observation-stamped and unstamped rows must remain indistinguishable to existing consumers (STA-4293 step 1). - - const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' - const OBSERVATION: AgentStatusObservation = { - origin: 'hook', - authorityId: 'main-agent-hooks:test', - incarnation: 3, - revision: 17, - observedAt: 1_700_000_000_000, - boundary: true, - kind: 'transition' - } - - describe('agent status observation is behavior-neutral', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('does not carry a previous observation onto an unstamped write', () => { - vi.useFakeTimers() - const store = createTestStore() - store.getState().setAgentStatus(PANE_KEY, { - state: 'working', - prompt: 'p', - agentType: 'claude', - observation: OBSERVATION - }) - store.getState().setAgentStatus(PANE_KEY, { state: 'done', prompt: 'p', agentType: 'claude' }) - - // Why: inheriting it would let a stale authority claim ordering over a row it never observed. - expect(store.getState().agentStatusByPaneKey[PANE_KEY]?.observation).toBeUndefined() - }) - }) -} diff --git a/src/renderer/src/store/slices/editor/git/editor-branch-line-total.test.ts b/src/renderer/src/store/slices/editor/git/editor-branch-line-total.test.ts deleted file mode 100644 index 4d635805f6b..00000000000 --- a/src/renderer/src/store/slices/editor/git/editor-branch-line-total.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createEditorStore } from '../editor-slice-test-harness' -import type { GitStatusResult } from '../../../../../../shared/git/status/git-status-types' - -const MERGE_BASE = '1f3c0d9a5b6e7f8091a2b3c4d5e6f708192a3b4c' - -function status(overrides: Partial = {}): GitStatusResult { - return { - conflictOperation: 'unknown', - entries: [{ path: 'src/index.ts', status: 'modified', area: 'unstaged' }], - head: 'head-1', - ignoredPaths: [], - ...overrides - } -} - -describe('createEditorSlice branch line total', () => { - it('keeps the published total when a later status omits the field', () => { - const store = createEditorStore() - store - .getState() - .setGitStatus( - 'wt-1', - status({ branchLineTotal: { added: 24, removed: 3, mergeBase: MERGE_BASE } }) - ) - const published = store.getState().gitBranchLineTotalByWorktree['wt-1'] - - // Omitted totals mean deferred computation; retain host backfill cache or polling flashes the chip blank. - store.getState().setGitStatus('wt-1', status()) - - expect(store.getState().gitBranchLineTotalByWorktree['wt-1']).toBe(published) - }) - - it('clears an unavailable total and restores it only after a new exact result', () => { - const store = createEditorStore() - const total = { added: 0, removed: 3, mergeBase: MERGE_BASE } - store.getState().setGitStatus('wt-1', status({ branchLineTotal: total })) - - store.getState().setGitStatus('wt-1', status({ branchLineTotalUnavailable: MERGE_BASE })) - - expect(store.getState().gitBranchLineTotalByWorktree['wt-1']).toBeUndefined() - store.getState().setGitStatus('wt-1', status()) - expect(store.getState().gitBranchLineTotalByWorktree['wt-1']).toBeUndefined() - - const recovered = { added: 1, removed: 3, mergeBase: MERGE_BASE } - store.getState().setGitStatus('wt-1', status({ branchLineTotal: recovered })) - expect(store.getState().gitBranchLineTotalByWorktree['wt-1']).toEqual(recovered) - }) - - it('does not clear a newer total when an older fork point becomes unavailable', () => { - const store = createEditorStore() - const total = { added: 2, removed: 1, mergeBase: 'rebased' } - store.getState().setGitStatus('wt-1', status({ branchLineTotal: total })) - - store.getState().setGitStatus('wt-1', status({ branchLineTotalUnavailable: MERGE_BASE })) - - expect(store.getState().gitBranchLineTotalByWorktree['wt-1']).toEqual(total) - }) - - it('keeps totals independent per worktree', () => { - const store = createEditorStore() - store - .getState() - .setGitStatus( - 'wt-1', - status({ branchLineTotal: { added: 24, removed: 3, mergeBase: MERGE_BASE } }) - ) - store - .getState() - .setGitStatus( - 'wt-2', - status({ branchLineTotal: { added: 1, removed: 1, mergeBase: 'other' } }) - ) - - store.getState().setGitStatus('wt-1', status({ didHitLimit: true, statusLength: 2 })) - - expect(store.getState().gitBranchLineTotalByWorktree['wt-1']).toBeUndefined() - expect(store.getState().gitBranchLineTotalByWorktree['wt-2']).toEqual({ - added: 1, - removed: 1, - mergeBase: 'other' - }) - }) -}) diff --git a/src/renderer/src/store/slices/editor/git/editor-remote-branch-actions.test.ts b/src/renderer/src/store/slices/editor/git/editor-remote-branch-actions.test.ts deleted file mode 100644 index 0d0f32796d3..00000000000 --- a/src/renderer/src/store/slices/editor/git/editor-remote-branch-actions.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { createEditorStore } from '../editor-slice-test-harness' - -const { toastErrorMock } = vi.hoisted(() => ({ - toastErrorMock: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { error: toastErrorMock } -})) - -const { notifyHostOfMirroredEditorCloseMock } = vi.hoisted(() => ({ - notifyHostOfMirroredEditorCloseMock: vi.fn() -})) -vi.mock('@/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab', () => ({ - notifyHostOfMirroredEditorClose: (...args: unknown[]) => - notifyHostOfMirroredEditorCloseMock(...args) -})) - -describe('createEditorSlice remote branch actions', () => { - const gitStatusMock = vi.fn() - const gitUpstreamStatusMock = vi.fn() - const gitPushMock = vi.fn() - const gitPullMock = vi.fn() - const gitFastForwardMock = vi.fn() - const gitRebaseFromBaseMock = vi.fn() - const gitFetchMock = vi.fn() - - beforeEach(() => { - toastErrorMock.mockReset() - gitStatusMock.mockReset() - gitUpstreamStatusMock.mockReset() - gitPushMock.mockReset() - gitPullMock.mockReset() - gitFastForwardMock.mockReset() - gitRebaseFromBaseMock.mockReset() - gitFetchMock.mockReset() - - gitStatusMock.mockResolvedValue({ entries: [], conflictOperation: 'unknown' }) - gitUpstreamStatusMock.mockResolvedValue({ - hasUpstream: true, - upstreamName: 'origin/main', - ahead: 1, - behind: 0 - }) - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ;(globalThis as any).window = (globalThis as any).window ?? {} - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ;(globalThis as any).window.api = { - git: { - status: gitStatusMock, - upstreamStatus: gitUpstreamStatusMock, - push: gitPushMock, - pull: gitPullMock, - fastForward: gitFastForwardMock, - rebaseFromBase: gitRebaseFromBaseMock, - fetch: gitFetchMock - } - } - }) - - it('keeps isRemoteOperationActive true while any remote op is in flight', async () => { - // Refcount remote operations across worktrees; push A settling must not reenable still-running pull B. - const store = createEditorStore() - - let resolveA: () => void = () => {} - let resolveB: () => void = () => {} - gitPushMock - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveA = resolve - }) - ) - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveB = resolve - }) - ) - - const pushA = store.getState().pushBranch('wt-1', '/a', true) - // Kick microtasks so pushA has begun and flipped the flag on. - await Promise.resolve() - expect(store.getState().isRemoteOperationActive).toBe(true) - - const pushB = store.getState().pushBranch('wt-2', '/b', false, undefined, undefined, { - runtimeTarget: { kind: 'local' } - }) - await Promise.resolve() - expect(store.getState().isRemoteOperationActive).toBe(true) - - expect(store.getState().remoteOperations).toEqual([ - { worktreeId: 'wt-1', kind: 'publish' }, - { worktreeId: 'wt-2', kind: 'push' } - ]) - resolveA() - await pushA.catch(() => {}) - expect(store.getState().remoteOperations).toEqual([{ worktreeId: 'wt-2', kind: 'push' }]) - // B is still running, so the busy flag must remain true. - expect(store.getState().isRemoteOperationActive).toBe(true) - - resolveB() - await pushB.catch(() => {}) - expect(store.getState().remoteOperations).toEqual([]) - expect(store.getState().isRemoteOperationActive).toBe(false) - }) -}) diff --git a/src/renderer/src/store/slices/hosted-review/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review/hosted-review.test.ts deleted file mode 100644 index 5030cf1ff9a..00000000000 --- a/src/renderer/src/store/slices/hosted-review/hosted-review.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { create } from 'zustand' -import type { AppState } from '../../types' -import { createHostedReviewSlice } from './hosted-review' - -import type { HostedReviewInfo } from '../../../../../shared/source-control/hosted-review/hosted-review-contracts' - -const runtimeRpc = vi.hoisted(() => ({ - callRuntimeRpc: vi.fn() -})) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: runtimeRpc.callRuntimeRpc -})) - -const mockApi = { - hostedReview: { - forBranch: vi.fn(), - getCreationEligibility: vi.fn(), - create: vi.fn(), - createStacked: vi.fn() - } -} - -globalThis.window = { api: mockApi } as never - -function makeStore(settings: AppState['settings'] = null) { - return create< - Pick< - AppState, - | 'hostedReviewCache' - | 'fetchHostedReviewForBranch' - | 'getHostedReviewCreationEligibility' - | 'createHostedReview' - | 'createStackedHostedReview' - | 'settings' - | 'repos' - | 'prCache' - > - >()((...args) => ({ - settings, - repos: [{ id: 'repo-1', path: '/repo', connectionId: null } as AppState['repos'][number]], - prCache: {}, - ...createHostedReviewSlice(...(args as Parameters)) - })) -} - -const githubReview: HostedReviewInfo = { - provider: 'github', - number: 12, - title: 'Branch PR', - state: 'open', - url: 'https://github.com/acme/orca/pull/12', - status: 'success', - updatedAt: '2026-05-10T00:00:00.000Z', - mergeable: 'MERGEABLE' -} - -describe('hosted review slice', () => { - beforeEach(() => { - mockApi.hostedReview.forBranch.mockReset() - mockApi.hostedReview.getCreationEligibility.mockReset() - mockApi.hostedReview.create.mockReset() - mockApi.hostedReview.createStacked.mockReset() - runtimeRpc.callRuntimeRpc.mockReset() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('does not reuse an old-head request after the branch advances', async () => { - const mergedAtHead: HostedReviewInfo = { - ...githubReview, - state: 'merged', - headSha: 'aaaaaaa' - } - let resolveOldHead!: (value: HostedReviewInfo | null) => void - mockApi.hostedReview.forBranch - .mockResolvedValueOnce(mergedAtHead) - .mockImplementationOnce( - () => - new Promise((resolve) => { - resolveOldHead = resolve - }) - ) - .mockResolvedValueOnce(null) - const store = makeStore() - const fetch = store.getState().fetchHostedReviewForBranch - await fetch('/repo', 'feature/inflight-head', { currentHeadOid: 'aaaaaaa' }) - const oldFetch = fetch('/repo', 'feature/inflight-head', { - force: true, - currentHeadOid: 'aaaaaaa' - }) - const newFetch = fetch('/repo', 'feature/inflight-head', { - staleWhileRevalidate: true, - currentHeadOid: 'bbbbbbb' - }) - resolveOldHead(mergedAtHead) - - await expect(newFetch).resolves.toBeNull() - await expect(oldFetch).resolves.toEqual(mergedAtHead) - - await expect( - fetch('/repo', 'feature/inflight-head', { - currentHeadOid: 'bbbbbbb' - }) - ).resolves.toBeNull() - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-create-stale-layout.test.ts b/src/renderer/src/store/slices/tabs/tabs-create-stale-layout.test.ts deleted file mode 100644 index 81f418cc5d6..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-create-stale-layout.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -// A workspace whose last tab closed under another owner can keep a layout that points at groups that -// no longer exist. A new tab then creates a fresh group, and that group must become the layout, or the -// tab is invisible: an empty tab strip and a 0-size pane until a workspace switch rebuilds the layout. -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -const mockApi = { - worktrees: { remove: vi.fn().mockResolvedValue(undefined), updateMeta: vi.fn() }, - pty: { kill: vi.fn().mockResolvedValue(undefined) }, - runtimeEnvironments: { call: vi.fn().mockResolvedValue({ ok: true, result: {} }) } -} -// @ts-expect-error -- minimal window.api stub for the store under test -globalThis.window = { api: mockApi } - -import { createTestStore, seedStore } from '../../testing/app-store-test-fixture' -import { makeWorktree } from '../worktrees/worktree.test-fixture' - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -const WT = 'repo1::/path/wt1' - -function storeWithStaleLayout(): ReturnType { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt1' })] - }, - activeWorktreeId: WT, - // The workspace's last tab is gone, and so are its groups, but the layout still names one. - unifiedTabsByWorktree: { [WT]: [] }, - groupsByWorktree: {}, - layoutByWorktree: { [WT]: { type: 'leaf', groupId: 'gone-root-group' } }, - activeGroupIdByWorktree: { [WT]: 'gone-root-group' } - }) - return store -} - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('a new tab in a workspace whose layout outlived its groups', () => { - it('puts the created group in the layout, so the tab is visible', () => { - const store = storeWithStaleLayout() - const tab = store.getState().createUnifiedTab(WT, 'browser') - const state = store.getState() - const groups = state.groupsByWorktree[WT] ?? [] - expect(groups).toHaveLength(1) - expect(groups[0]?.tabOrder).toContain(tab.id) - expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: groups[0]?.id }) - expect(state.activeGroupIdByWorktree[WT]).toBe(groups[0]?.id) - }) - - it('leaves a live layout alone when the workspace already has a group', () => { - const store = storeWithStaleLayout() - const first = store.getState().createUnifiedTab(WT, 'browser') - const layout = store.getState().layoutByWorktree[WT] - const second = store.getState().createUnifiedTab(WT, 'browser') - const state = store.getState() - expect(state.layoutByWorktree[WT]).toBe(layout) - expect(state.groupsByWorktree[WT]?.[0]?.tabOrder).toEqual([first.id, second.id]) - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-label-and-pin-state.test.ts b/src/renderer/src/store/slices/tabs/tabs-label-and-pin-state.test.ts deleted file mode 100644 index 2f4c8a37b20..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-label-and-pin-state.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, it, expect, beforeEach, vi } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import { createTabsSliceMockApi } from './tabs-slice-test-harness' -import { createTestStore } from '../../testing/app-store-test-fixture' -import { makeOpenFile } from '../editor/types/open-file.test-fixture' -import { drawTabsFromMain } from './tabs-drawn-from-main.test-fixture' -import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture' -import { withLayoutOwnerTabProps } from '@/components/tab-bar/tab-bar-layout-owner-props' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -{ - createTabsSliceMockApi() - const mockWindow = globalThis.window - - const WT = 'repo1::/tmp/feature' - - describe('TabsSlice', () => { - beforeEach(() => { - globalThis.window = mockWindow - }) - - let store: ReturnType - - beforeEach(() => { - store = createTestStore() - }) - - describe('pinTab / unpinTab', () => { - it('pins a tab and promotes preview to permanent', async () => { - store.setState({ - openFiles: [makeOpenFile({ id: 'f.ts', worktreeId: WT, isPreview: true })] - }) - const tab = store.getState().createUnifiedTab(WT, 'editor', { - id: 'f.ts', - label: 'f.ts', - isPreview: true - }) - const main = await drawTabsFromMain(store) - try { - const pin = (): void => store.getState().pinTab(tab.id) - // A layout-owner build pins through main first, as the tab bar does; then main promotes. - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - withLayoutOwnerTabProps( - { - togglePinned: pin, - makePreviewFilePermanent: (fileId, tabId) => - store.getState().makePreviewFilePermanent(fileId, tabId) - }, - () => WT - ).togglePinned({ - unifiedTabId: tab.id, - isPinned: false, - type: 'editor', - data: { id: 'f.ts' } - }) - } else { - pin() - } - await main.settle() - - const updated = store.getState().unifiedTabsByWorktree[WT][0] - expect(updated.isPinned).toBe(true) - expect(updated.isPreview).toBe(ORCA_LAYOUT_OWNER_IS_MAIN ? undefined : false) - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - expect(layoutApplyTestTransport.sentOfType('promotePreviewTab')).toEqual([ - { type: 'promotePreviewTab', workspace: WT, tabId: tab.id } - ]) - } - } finally { - main.close() - } - }) - }) - }) -} diff --git a/src/renderer/src/store/slices/tabs/tabs-open-close-lifecycle.test.ts b/src/renderer/src/store/slices/tabs/tabs-open-close-lifecycle.test.ts deleted file mode 100644 index b6ff5d40a03..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-open-close-lifecycle.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import '../../../../../shared/constants' -import { buildMobileSessionTabSnapshots } from '../../../runtime/sync-runtime-graph/mobile-session-snapshots' -import { closeMobileSessionTabInStore } from '../../../runtime/web-session-tabs-sync/closing/mobile-session-tab-close' -import { createTabsSliceMockApi } from './tabs-slice-test-harness' -import { createTestStore } from '../../testing/app-store-test-fixture' -import { makeOpenFile } from '../editor/types/open-file.test-fixture' -import { makeTabGroup, makeUnifiedTab } from './tab-group.test-fixture' - -import { drawTabsFromMain } from './tabs-drawn-from-main.test-fixture' - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -createTabsSliceMockApi() - -const WT = 'repo1::/tmp/feature' - -describe('TabsSlice', () => { - let store: ReturnType - - beforeEach(() => { - store = createTestStore() - }) - - describe('closeUnifiedTab', () => { - it('removes a mobile-closed markdown tab from open files so it is not republished', async () => { - const groupId = 'editor-group' - const file = makeOpenFile({ - id: '/tmp/feature/README.md', - filePath: '/tmp/feature/README.md', - relativePath: 'README.md', - language: 'markdown', - worktreeId: WT - }) - const tab = makeUnifiedTab({ - id: 'readme-unified', - entityId: file.id, - contentType: 'editor', - label: 'README.md', - worktreeId: WT, - groupId - }) - store.setState({ - openFiles: [file], - unifiedTabsByWorktree: { [WT]: [tab] }, - groupsByWorktree: { - [WT]: [ - makeTabGroup({ - id: groupId, - worktreeId: WT, - activeTabId: tab.id, - tabOrder: [tab.id], - recentTabIds: [tab.id] - }) - ] - }, - activeGroupIdByWorktree: { [WT]: groupId }, - activeFileId: file.id, - activeFileIdByWorktree: { [WT]: file.id }, - activeWorktreeId: WT, - activeTabType: 'editor', - activeTabTypeByWorktree: { [WT]: 'editor' } - }) - - expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs).toMatchObject([ - { id: tab.id, type: 'markdown', filePath: file.filePath } - ]) - - const main = await drawTabsFromMain(store) - expect(closeMobileSessionTabInStore(store.getState(), WT, tab.id)).toBe(true) - // A layout-owner build closes the tab in main; the file goes after its frame drops the tab. - await main.settle() - main.close() - - expect(store.getState().openFiles).toEqual([]) - expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs ?? []).toEqual([]) - }) - }) -}) diff --git a/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-cache-hydration.test.ts b/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-cache-hydration.test.ts deleted file mode 100644 index c9bb0ee37c9..00000000000 --- a/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-cache-hydration.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import type { - WorkspaceCleanupScanProgress, - WorkspaceCleanupScanResult -} from '../../../../../shared/workspace-cleanup/workspace-cleanup' -import { - NOW, - createCleanupTestStore, - deferred, - installWorkspaceCleanupApi, - makeCandidate -} from './workspace-cleanup-slice-test-harness' - -const CACHED_AT = NOW - 60 * 60 * 1000 - -function makeCachedScan(): WorkspaceCleanupScanResult { - return { - scannedAt: CACHED_AT, - candidates: [ - makeCandidate({ worktreeId: 'repo1::/tmp/alpha', displayName: 'alpha' }), - makeCandidate({ worktreeId: 'repo1::/tmp/beta', displayName: 'beta' }) - ], - errors: [] - } -} - -describe('workspace cleanup cache hydration', () => { - it('bails when a broad scan starts while the cache read is in flight', async () => { - const cacheRead = deferred() - const broadScan = deferred() - const scan = vi.fn().mockReturnValue(broadScan.promise) - installWorkspaceCleanupApi(scan, vi.fn().mockReturnValue(cacheRead.promise)) - const store = createCleanupTestStore() - - const hydration = store.getState().hydrateWorkspaceCleanupFromCache() - const scanPromise = store.getState().scanWorkspaceCleanup() - cacheRead.resolve(makeCachedScan()) - - await expect(hydration).resolves.toBe(false) - expect(store.getState().workspaceCleanupScan).toBeNull() - - broadScan.resolve({ scannedAt: NOW, candidates: [], errors: [] }) - await scanPromise - expect(store.getState().workspaceCleanupScan?.scannedAt).toBe(NOW) - }) - - it('reconciles a refresh into the hydrated snapshot instead of clearing it', async () => { - const pending = deferred() - let onProgress: ((progress: WorkspaceCleanupScanProgress) => void) | undefined - const scan = vi.fn((_args, progressCallback) => { - onProgress = progressCallback - return pending.promise - }) - installWorkspaceCleanupApi(scan, vi.fn().mockResolvedValue(makeCachedScan())) - const store = createCleanupTestStore() - await store.getState().hydrateWorkspaceCleanupFromCache() - - const scanPromise = store.getState().scanWorkspaceCleanup() - const refreshedAlpha = makeCandidate({ - worktreeId: 'repo1::/tmp/alpha', - displayName: 'alpha', - lastActivityAt: NOW - 1000, - fingerprint: 'fingerprint-alpha-2' - }) - const gamma = makeCandidate({ worktreeId: 'repo1::/tmp/gamma', displayName: 'gamma' }) - onProgress?.({ - scanId: 'scan-1', - scannedAt: NOW, - scannedWorktreeCount: 2, - totalWorktreeCount: 3, - candidates: [refreshedAlpha, gamma], - errors: [], - candidateMode: 'append' - }) - - await vi.waitFor(() => { - expect(store.getState().workspaceCleanupProgress?.scannedWorktreeCount).toBe(2) - }) - const streaming = store.getState().workspaceCleanupScan - // Update in place, keep unseen snapshot rows, append new — never clear. - expect(streaming?.candidates.map((candidate) => candidate.worktreeId)).toEqual([ - 'repo1::/tmp/alpha', - 'repo1::/tmp/beta', - 'repo1::/tmp/gamma' - ]) - expect(streaming?.candidates[0]?.fingerprint).toBe('fingerprint-alpha-2') - // The presented "as of" time stays the snapshot's until the scan settles. - expect(streaming?.scannedAt).toBe(CACHED_AT) - - pending.resolve({ scannedAt: NOW, candidates: [refreshedAlpha, gamma], errors: [] }) - await scanPromise - - const settled = store.getState().workspaceCleanupScan - expect(settled?.scannedAt).toBe(NOW) - // beta vanished from the final result, so only the settle removes it. - expect(settled?.candidates.map((candidate) => candidate.worktreeId)).toEqual([ - 'repo1::/tmp/alpha', - 'repo1::/tmp/gamma' - ]) - }) -}) diff --git a/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-finished-agents.test.ts b/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-finished-agents.test.ts deleted file mode 100644 index e87a78a96b5..00000000000 --- a/src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-finished-agents.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { - makeFacets, - makeFacetCandidate -} from '@/components/workspace-cleanup/query/workspace-cleanup-facet.test.fixture' -import { expect, it } from 'vitest' -import { createTestStore } from '../../testing/app-store-test-fixture' -import { makeTab } from '../../terminals/testing/terminal-tab.test-fixture' -import { makeUnifiedTab } from '../tabs/tab-group.test-fixture' -import { makeWorktree } from '../worktrees/worktree.test-fixture' -import { makeCandidate, WORKTREE_ID } from './workspace-cleanup-slice-test-harness' -import { getWorkspaceCleanupAgentEvidence } from './workspace-cleanup-agent-evidence' -import { getWorkspaceCleanupCandidateIdentity } from '../../../../../shared/workspace-cleanup/workspace-cleanup-host-identity' -import { matchesWorkspaceCleanupAgent } from '@/components/workspace-cleanup/query/workspace-cleanup-facet-matchers' - -it('counts current Done agents only for their workspace host', () => { - const store = createTestStore() - const tab = makeTab({ id: 'done-tab', worktreeId: WORKTREE_ID, ptyId: null }) - store.setState({ - tabsByWorktree: { [WORKTREE_ID]: [tab] }, - unifiedTabsByWorktree: { - [WORKTREE_ID]: [ - makeUnifiedTab({ - id: tab.id, - worktreeId: WORKTREE_ID, - groupId: 'g', - executionHostId: 'ssh:a' - }) - ] - }, - worktreesByRepo: { - repo1: [ - makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', hostId: 'ssh:a' }), - makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', hostId: 'ssh:b' }) - ] - }, - agentStatusByPaneKey: { - 'done-tab:0': { - paneKey: 'done-tab:0', - tabId: tab.id, - worktreeId: WORKTREE_ID, - state: 'done', - prompt: 'finished task', - agentType: 'claude', - updatedAt: 1000, - stateStartedAt: 1000, - stateHistory: [], - connectionId: 'a' - } - } - }) - const a = makeCandidate({ executionHostId: 'ssh:a', connectionId: 'a' }) - const b = makeCandidate({ executionHostId: 'ssh:b', connectionId: 'b' }) - const evidence = getWorkspaceCleanupAgentEvidence(store.getState(), [a, b]) - expect(evidence.get(getWorkspaceCleanupCandidateIdentity(a))).toEqual({ finishedAgentCount: 1 }) - expect(evidence.get(getWorkspaceCleanupCandidateIdentity(b))).toEqual({ finishedAgentCount: 0 }) - store.setState({ - agentStatusByPaneKey: {}, - sleepingAgentSessionsByPaneKey: { - 'done-tab:0': { - paneKey: 'done-tab:0', - tabId: tab.id, - worktreeId: WORKTREE_ID, - agent: 'claude', - providerSession: { key: 'session_id', id: 'sleep-session' }, - prompt: 'finished task', - state: 'done', - capturedAt: 2000, - updatedAt: 1000, - connectionId: 'a', - origin: 'worktree-sleep' - } - } - }) - expect( - getWorkspaceCleanupAgentEvidence(store.getState(), [a]).get( - getWorkspaceCleanupCandidateIdentity(a) - ) - ).toEqual({ finishedAgentCount: 0 }) -}) - -it('does not treat an old retained-row count as proof that a workspace has finished agents', () => { - const candidate = makeFacetCandidate() - const facets = makeFacets({ - candidate: { - localContext: { - ...candidate.localContext, - finishedAgentCount: undefined, - retainedDoneAgentCount: 2 - } - } - }) - expect(matchesWorkspaceCleanupAgent(facets, { states: [], retainedDoneAgents: 'only' })).toBe( - false - ) - expect(matchesWorkspaceCleanupAgent(facets, { states: [], retainedDoneAgents: 'exclude' })).toBe( - false - ) - expect(matchesWorkspaceCleanupAgent(facets, { states: [], retainedDoneAgents: 'any' })).toBe(true) -}) diff --git a/src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-twin-host.test.ts b/src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-twin-host.test.ts deleted file mode 100644 index 5b80c677985..00000000000 --- a/src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-twin-host.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../../../shared/worktree/types' -import { resetHostedReviewLinkMutationGenerationForTests } from './hosted-review-link-mutation' -import { makeWorktree } from '../worktree.test-fixture' -import { - createTestStore, - mockApi, - resetRemoteRuntimeMocks, - resetWorktreeSliceModuleMemory -} from '../worktrees-slice-test-harness' - -vi.mock('sonner', () => ({ - toast: { warning: vi.fn(), info: vi.fn(), success: vi.fn(), error: vi.fn(), dismiss: vi.fn() } -})) - -beforeEach(() => { - vi.clearAllMocks() - resetWorktreeSliceModuleMemory() - resetRemoteRuntimeMocks() - resetHostedReviewLinkMutationGenerationForTests() -}) - -// #32918: one project at the same path on two hosts shares the id `repoId::path`. -const id = 'repo1::/srv/ai-tools' - -function storeWith(...rows: Partial[]) { - const store = createTestStore() - const worktrees = rows.map((row) => - makeWorktree({ id, repoId: 'repo1', path: '/srv/ai-tools', ...row }) - ) - store.setState({ worktreesByRepo: { repo1: worktrees } }) - return store -} - -function twinStore() { - return storeWith( - { hostId: 'runtime:env-a', head: 'aaa', branch: 'refs/heads/master', displayName: 'master' }, - { hostId: 'runtime:env-b', head: 'bbb', branch: 'refs/heads/feature', displayName: 'feature' } - ) -} - -describe('updateWorktreeGitIdentity with a same-path twin on another host', () => { - it('leaves both copies alone when the answering host is unknown', () => { - const store = twinStore() - - store - .getState() - .updateWorktreeGitIdentity(id, { head: 'ccc', branch: 'refs/heads/other' }, null) - - const [onA, onB] = store.getState().worktreesByRepo.repo1 - expect(onA.branch).toBe('refs/heads/master') - expect(onB.branch).toBe('refs/heads/feature') - }) - - it("clears only the switching twin's push target and review link, on its own host", async () => { - const pushTarget = { remoteName: 'fork', branchName: 'old/review-head' } - const store = storeWith( - { hostId: 'local', branch: 'refs/heads/stack/two', linkedPR: 7, pushTarget }, - { hostId: 'ssh:box-b', branch: 'refs/heads/stack/one', linkedPR: 101, pushTarget } - ) - - store.getState().updateWorktreeGitIdentity(id, { branch: 'refs/heads/stack/two' }, 'ssh:box-b') - - await vi.waitFor(() => expect(mockApi.worktrees.updateMeta).toHaveBeenCalledTimes(1)) - expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith( - expect.objectContaining({ - worktreeId: id, - executionHostId: 'ssh:box-b', - updates: expect.objectContaining({ linkedPR: null, pushTarget: undefined }) - }) - ) - const [localAfter, remoteAfter] = store.getState().worktreesByRepo.repo1 - expect(localAfter).toMatchObject({ linkedPR: 7, pushTarget }) - expect(remoteAfter).toMatchObject({ branch: 'refs/heads/stack/two', pushTarget: undefined }) - }) -}) - -describe('updateWorktreeGitIdentity host matching', () => { - it("reaches a paired server's SSH checkout through its runtime alias, not its twin", () => { - const store = storeWith( - { hostId: 'local', branch: 'refs/heads/master' }, - { - hostId: 'ssh:private-target', - runtimeOwnerEnvironmentId: 'hub-a', - branch: 'refs/heads/master' - } - ) - - store - .getState() - .updateWorktreeGitIdentity(id, { branch: 'refs/heads/feature' }, 'runtime:hub-a') - - const [local, paired] = store.getState().worktreesByRepo.repo1 - expect(local.branch).toBe('refs/heads/master') - expect(paired.branch).toBe('refs/heads/feature') - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/session/worktrees-terminal-pr-url-linking.test.ts b/src/renderer/src/store/slices/worktrees/session/worktrees-terminal-pr-url-linking.test.ts deleted file mode 100644 index 050883c6bf5..00000000000 --- a/src/renderer/src/store/slices/worktrees/session/worktrees-terminal-pr-url-linking.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } })) -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - HostedReviewInfo, - HostedReviewForBranchArgs -} from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts' -import { makeWorktree } from '../worktree.test-fixture' -import { getWorkspaceAttachments } from '../../../../../../shared/workspace-attachments/workspace-attachments' -import { - createTestStore, - mockApi, - resetRemoteRuntimeMocks, - resetWorktreeSliceModuleMemory -} from '../worktrees-slice-test-harness' - -function installReviewRead() { - const read = vi.fn<(args: HostedReviewForBranchArgs) => Promise>() - Object.defineProperty(window.api, 'hostedReview', { - configurable: true, - value: { forBranch: read } - }) - return read -} - -const confirmedReview = (number: number): HostedReviewInfo => ({ - provider: 'github', - number, - title: 'Confirmed', - state: 'open', - status: 'success', - mergeable: 'MERGEABLE', - url: `https://github.com/acme/orca/pull/${number}`, - updatedAt: '2026-01-01' -}) - -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) - -describe('worktree remote runtime mutations', () => { - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - Object.defineProperty(window.api, 'gh', { - configurable: true, - value: { workItemByOwnerRepo: vi.fn().mockResolvedValue(null) } - }) - }) - - it('preserves a manual primary while appending a PR confirmed after the selection changes', async () => { - const store = createTestStore() - let resolveLookup: (value: HostedReviewInfo | null) => void = () => {} - installReviewRead().mockImplementation( - () => - new Promise((resolve) => { - resolveLookup = resolve - }) - ) - const wt = makeWorktree({ - id: 'repo1::/path/wt1', - repoId: 'repo1', - path: '/worktrees/orca', - branch: 'refs/heads/feature/pr-link', - pushTarget: { - remoteName: 'origin', - branchName: 'feature/pr-link' - } - }) - store.setState({ - repos: [ - { id: 'repo1', path: '/repos/orca', displayName: 'orca', badgeColor: '#000', addedAt: 0 } - ], - worktreesByRepo: { repo1: [wt] } - }) - - store.getState().observeTerminalGitHubPullRequestLink(wt.id, { - url: 'https://github.com/acme/orca/pull/42', - slug: { owner: 'acme', repo: 'orca' }, - number: 42 - }) - expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled() - await vi.dynamicImportSettled() - - store.setState({ - worktreesByRepo: { repo1: [{ ...wt, linkedPR: 7 }] } - }) - - resolveLookup(confirmedReview(42)) - await vi.dynamicImportSettled() - - expect(store.getState().worktreesByRepo.repo1[0]?.linkedPR).toBe(7) - expect( - getWorkspaceAttachments(store.getState().worktreesByRepo.repo1[0]).map((item) => item.number) - ).toEqual([7, 42]) - expect(mockApi.worktrees.updateMeta).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-diff-memory.test.ts b/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-diff-memory.test.ts deleted file mode 100644 index df0a23fbfd1..00000000000 --- a/src/renderer/src/store/slices/worktrees/teardown/removed-worktree-diff-memory.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { hostWorktreeTarget } from '../../../../../../shared/worktree/host-qualified-identity' -import '../../../../../../shared/workspace-scope' -import { - claimCombinedDiffView, - clearCombinedDiffViewMemory, - readCombinedDiffViewMemory, - releaseCombinedDiffView, - rememberCombinedDiffView, - type CombinedDiffViewLease -} from '@/components/editor/combined-diff/remember-view/combined-diff-view-cache' -import { createTestStore } from '../../../testing/app-store-test-fixture' -import { makeWorktree } from '../worktree.test-fixture' -import { buildWorktreePurgeState } from './worktree-purge-state' -import { applyRemoveWorktreeSuccessState } from './remove-worktree-store-cleanup' - -const removed = 'repo::/workspace/deleted' - -function mountDiff(worktreeId: string): { key: string; lease: CombinedDiffViewLease } { - const key = `${worktreeId}::all-diffs::uncommitted::pane` - const lease = claimCombinedDiffView(key, worktreeId) - rememberCombinedDiffView(lease, { - view: { - entrySignature: 'entries', - gitStatusSignature: '', - sections: [ - { - key: 'source', - path: 'source.ts', - status: 'modified', - originalContent: 'before'.repeat(1000), - modifiedContent: 'after'.repeat(1000), - collapsed: false, - loading: false, - dirty: false, - diffResult: null, - largeDiffRenderLimit: null - } - ], - sectionHeights: {}, - loadedIndices: [0] - }, - scrollTop: 42, - scrollAnchor: { key: 'source', offset: 0 } - }) - return { key, lease } -} - -function seedDiff(worktreeId: string): string { - const { key, lease } = mountDiff(worktreeId) - releaseCombinedDiffView(lease) - return key -} - -afterEach(() => { - clearCombinedDiffViewMemory() -}) - -describe('removed workspace diff memory', () => { - it('ignores the unmount write of a viewer whose workspace was already removed', () => { - const { key, lease } = mountDiff(removed) - const store = createTestStore() - applyRemoveWorktreeSuccessState(store.setState, removed, new Set()) - releaseCombinedDiffView(lease) - rememberCombinedDiffView(lease, { scrollTop: 7, scrollAnchor: { key: 'source', offset: 3 } }) - expect(readCombinedDiffViewMemory(key)).toBeUndefined() - // A workspace recreated under the same id starts fresh once its viewer mounts. - rememberCombinedDiffView(claimCombinedDiffView(key, removed), { scrollTop: 7 }) - expect(readCombinedDiffViewMemory(key)).toEqual({ worktreeId: removed, scrollTop: 7 }) - }) - - it('keeps cached views when a different host still owns the same workspace id', () => { - const key = seedDiff(removed) - const store = createTestStore() - store.setState({ - worktreesByRepo: { - repo: [ - makeWorktree({ id: removed, repoId: 'repo', hostId: 'local' }), - makeWorktree({ id: removed, repoId: 'repo', hostId: 'runtime:remote' }) - ] - } - }) - buildWorktreePurgeState(store.getState(), [ - hostWorktreeTarget({ id: removed, hostId: 'runtime:remote' }) - ]) - expect(readCombinedDiffViewMemory(key)?.scrollTop).toBe(42) - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/teardown/store-worktree-removal-cascade.test.ts b/src/renderer/src/store/slices/worktrees/teardown/store-worktree-removal-cascade.test.ts deleted file mode 100644 index 80d18530ab7..00000000000 --- a/src/renderer/src/store/slices/worktrees/teardown/store-worktree-removal-cascade.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import { createCompatibleRuntimeStatusResponseIfNeeded } from '../../../../runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../../../runtime/rpc/compatibility/runtime-compatibility-cache' -import 'sonner' -import { createTestStore, seedStore } from '../../../testing/app-store-test-fixture' -import { makeLayout, makeTab } from '../../../terminals/testing/terminal-tab.test-fixture' -import { makeWorktree } from '../worktree.test-fixture' -import { saveSessionCommitDrafts } from '@/lib/source-control/drafts/source-control-commit-draft-session' -import { createStoreCascadesMockApi } from '../../../testing/app-store-cascade-api.test-fixture' -import '../../../../../../shared/worktree/host-qualified-identity' - -const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => [])) -const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown, - unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers -})) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -const mockApi = createStoreCascadesMockApi() - -describe('removeWorktree cascade', () => { - beforeEach(() => { - vi.clearAllMocks() - clearRuntimeCompatibilityCacheForTests() - saveSessionCommitDrafts({}) - mockApi.worktrees.remove.mockResolvedValue(undefined) - mockApi.worktrees.forceDeletePreservedBranch.mockResolvedValue({ deleted: true }) - mockApi.runtimeEnvironments.call.mockReset() - mockApi.runtimeEnvironments.call.mockImplementation((args: { method: string }) => - Promise.resolve( - createCompatibleRuntimeStatusResponseIfNeeded(args) ?? { - id: 'rpc-default', - ok: true, - result: {}, - _meta: { runtimeId: 'remote-runtime' } - } - ) - ) - }) - - it('sets delete state with dirty/untracked error and canForceDelete=true on failure', async () => { - const store = createTestStore() - const worktreeId = 'repo1::/path/wt1' - const error = 'Worktree has uncommitted or untracked changes.' - - mockApi.worktrees.remove.mockRejectedValueOnce(new Error(error)) - - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1' })] - }, - tabsByWorktree: { [worktreeId]: [makeTab({ id: 'tab1', worktreeId })] }, - ptyIdsByTabId: { tab1: ['pty1'] }, - terminalLayoutsByTabId: { tab1: makeLayout() }, - activeWorktreeId: worktreeId, - activeTabId: 'tab1' - }) - - const result = await store.getState().removeWorktree({ id: worktreeId, executionHostId: null }) - const s = store.getState() - - expect(result).toEqual({ ok: false, error }) - expect(s.deleteStateByWorktreeId[worktreeId]).toEqual({ - isDeleting: false, - error, - canForceDelete: true, - forceDeleteReason: 'dirty' - }) - expect(s.worktreesByRepo['repo1']).toHaveLength(1) - expect(s.tabsByWorktree[worktreeId]).toHaveLength(1) - expect(s.ptyIdsByTabId['tab1']).toEqual(['pty1']) - - expect(s.activeWorktreeId).toBe(worktreeId) - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts b/src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts deleted file mode 100644 index 7df43ed7040..00000000000 --- a/src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '../../../types' -import { - beginHugeRepoWarningProbe, - clearHugeRepoWarningDismissalsForTests, - hasDismissedHugeRepoWarning, - markHugeRepoWarningDismissed -} from '@/lib/source-control/warnings/source-control-huge-repo-warning-dismissals' -import '../create-worktree-slice' -import { makeWorktree } from '../worktree.test-fixture' -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) - -describe('removeWorktree state cleanup', () => { - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - clearHugeRepoWarningDismissalsForTests() - }) - - it('invalidates huge-repo warning probes after successful explicit removal', async () => { - const store = createTestStore() - const removed = makeWorktree({ - id: 'repo1::/path/reused', - instanceId: 'persisted-instance', - repoId: 'repo1', - path: '/path/reused' - }) - store.setState({ worktreesByRepo: { repo1: [removed] } } as Partial) - const staleProbe = beginHugeRepoWarningProbe(removed) - expect(markHugeRepoWarningDismissed(staleProbe)).toBe(true) - - await store.getState().removeWorktree({ id: removed.id, executionHostId: null }) - - // The same-path replacement can reuse persisted instance metadata. - const replacementProbe = beginHugeRepoWarningProbe({ ...removed }) - expect(hasDismissedHugeRepoWarning(staleProbe)).toBe(false) - expect(markHugeRepoWarningDismissed(staleProbe)).toBe(false) - expect(hasDismissedHugeRepoWarning(replacementProbe)).toBe(false) - }) - - it('records the sidebar scroll anchor in the same tick it removes the worktree', async () => { - const store = createTestStore() - const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) - store.setState({ worktreesByRepo: { repo1: [wt] } } as Partial) - - const sidebar = new EventTarget() - let worktreePresentWhenRecorded: boolean | null = null - sidebar.addEventListener('orca-record-virtualized-scroll-anchor', () => { - worktreePresentWhenRecorded = - store.getState().worktreesByRepo.repo1?.some((w) => w.id === wt.id) ?? false - }) - const globalWithDocument = globalThis as { document?: unknown } - const originalDocument = globalWithDocument.document - globalWithDocument.document = { - querySelector: (selector: string) => (selector === '[data-worktree-sidebar]' ? sidebar : null) - } - - try { - await store.getState().removeWorktree({ id: wt.id, executionHostId: null }) - } finally { - globalWithDocument.document = originalDocument - } - - // The anchor must be captured while the row still exists so restore pins the pre-removal position. - expect(worktreePresentWhenRecorded).toBe(true) - expect(store.getState().worktreesByRepo.repo1).toEqual([]) - }) -}) diff --git a/src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts b/src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts deleted file mode 100644 index 376281faf45..00000000000 --- a/src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' -import '../../../../../shared/constants' -import { - resetAgentPaneAuthorityAliasesForTests, - resolveAgentPaneAuthorityKey -} from '../../slices/agent-status/agent-pane-authority' -import { createTestStore } from '../../testing/app-store-test-fixture' - -const LEAF_1 = '11111111-1111-4111-8111-111111111111' -const LEAF_2 = '22222222-2222-4222-8222-222222222222' - -describe('setTabLayout PTY ownership', () => { - beforeEach(() => { - resetAgentPaneAuthorityAliasesForTests() - }) - - it('moves live and future pane authority onto the retained PTY leaf', () => { - const store = createTestStore() - const removedPaneKey = makePaneKey('tab-1', LEAF_1) - const retainedPaneKey = makePaneKey('tab-1', LEAF_2) - store.getState().setAgentStatus(removedPaneKey, { - state: 'working', - prompt: 'before repair', - agentType: 'codex' - }) - - store.getState().setTabLayout('tab-1', { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_2 } - }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-agent', - [LEAF_2]: 'pty-agent' - } - }) - - expect(store.getState().agentStatusByPaneKey[removedPaneKey]).toBeUndefined() - expect(store.getState().agentStatusByPaneKey[retainedPaneKey]?.prompt).toBe('before repair') - expect(resolveAgentPaneAuthorityKey(removedPaneKey)).toBe(retainedPaneKey) - - store.getState().setAgentStatus(removedPaneKey, { - state: 'working', - prompt: 'after repair', - agentType: 'codex' - }) - expect(store.getState().agentStatusByPaneKey[retainedPaneKey]?.prompt).toBe('after repair') - }) - - it('does not steal authority from a pane that was already detached to another tab', () => { - const store = createTestStore() - const removedPaneKey = makePaneKey('source-tab', LEAF_1) - const retainedPaneKey = makePaneKey('source-tab', LEAF_2) - const detachedPaneKey = makePaneKey('target-tab', LEAF_1) - store.getState().setTabLayout('target-tab', { - root: { type: 'leaf', leafId: LEAF_1 }, - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_1]: 'pty-detached' } - }) - store.getState().transferAgentPaneAuthority({ - fromPaneKey: removedPaneKey, - toPaneKey: detachedPaneKey, - ptyId: 'pty-detached' - }) - - store.getState().setTabLayout('source-tab', { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_2 } - }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-detached', - [LEAF_2]: 'pty-detached' - } - }) - - expect(resolveAgentPaneAuthorityKey(removedPaneKey)).toBe(detachedPaneKey) - expect(resolveAgentPaneAuthorityKey(detachedPaneKey)).toBe(detachedPaneKey) - expect(resolveAgentPaneAuthorityKey(retainedPaneKey)).toBe(retainedPaneKey) - }) -}) diff --git a/src/renderer/src/store/terminals/pty/terminal-pty-release-orphan-retention.test.ts b/src/renderer/src/store/terminals/pty/terminal-pty-release-orphan-retention.test.ts deleted file mode 100644 index 7891a7c5610..00000000000 --- a/src/renderer/src/store/terminals/pty/terminal-pty-release-orphan-retention.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' - -import { createTestStore, seedStore } from '../../testing/app-store-test-fixture' -import { makeTab } from '../testing/terminal-tab.test-fixture' -import { makeWorktree } from '../../slices/worktrees/worktree.test-fixture' - -import { createStoreCascadesMockApi } from '../../testing/app-store-cascade-api.test-fixture' - -const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => [])) -const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown, - unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers -})) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -const mockApi = createStoreCascadesMockApi() - -describe('setActiveWorktree', () => { - beforeEach(() => { - vi.clearAllMocks() - mockApi.worktrees.updateMeta.mockResolvedValue({}) - }) - - // Promote a surviving split pane into the relay slot on exit; otherwise relay-drop clearing can make orphan sweep delete the live tab (#9911). - it('promotes a surviving pane into the relay slot so a split tab is not orphaned after a relay drop', () => { - const store = createTestStore() - const wt = 'repo1::/path/wt1' - const tabId = 'tab-split' - - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] - }, - tabsByWorktree: { [wt]: [makeTab({ id: tabId, worktreeId: wt, ptyId: 'pty-B' })] }, - ptyIdsByTabId: { [tabId]: ['pty-A', 'pty-B'] }, - // Newest-bound pane B owns the single relay slot. - lastKnownRelayPtyIdByTabId: { [tabId]: 'pty-B' }, - terminalLayoutsByTabId: { - [tabId]: { - root: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: 'leaf-a' }, - second: { type: 'leaf', leafId: 'leaf-b' } - }, - activeLeafId: 'leaf-a', - expandedLeafId: null, - ptyIdsByLeafId: { 'leaf-a': 'pty-A', 'leaf-b': 'pty-B' } - } - }, - // The transiently-absent unified entry is the condition #9911 recovers from. - unifiedTabsByWorktree: { [wt]: [] } - }) - - // Pane B (the relay-slot owner) exits: the slot must fall back to survivor A. - store.getState().clearTabPtyId(tabId, 'pty-B') - expect(store.getState().ptyIdsByTabId[tabId]).toEqual(['pty-A']) - expect(store.getState().lastKnownRelayPtyIdByTabId[tabId]).toBe('pty-A') - - // Relay drop bulk-clears the row + live index but preserves the relay slot. - store.getState().clearTabPtyId(tabId) - const state = store.getState() - expect(state.ptyIdsByTabId[tabId]).toEqual([]) - expect(state.tabsByWorktree[wt][0].ptyId).toBeNull() - expect(state.lastKnownRelayPtyIdByTabId[tabId]).toBe('pty-A') - }) -}) diff --git a/src/renderer/src/store/terminals/sleep/store-sleep-runtime-convergence.test.ts b/src/renderer/src/store/terminals/sleep/store-sleep-runtime-convergence.test.ts deleted file mode 100644 index ea37ae3e37f..00000000000 --- a/src/renderer/src/store/terminals/sleep/store-sleep-runtime-convergence.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import '../../../../../shared/constants' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../../runtime/rpc/compatibility/runtime-compatibility-cache' -import { createTestStore, seedStore } from '../../testing/app-store-test-fixture' -import { makeTab } from '../testing/terminal-tab.test-fixture' -import { makeWorktree } from '../../slices/worktrees/worktree.test-fixture' -import { shutdownBufferCaptures } from '@/components/terminal-pane/snapshots/shutdown-buffer-captures' -import { applySleepRuntimeRpcDefault } from './terminal-sleep-rpc.test-fixture' -import { createStoreCascadesMockApi } from '../../testing/app-store-cascade-api.test-fixture' - -const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => [])) -const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown, - unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers -})) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -const mockApi = createStoreCascadesMockApi() - -// Sleep must clear live status or mid-turn agents remain working until the 30-minute TTL. -describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => { - beforeEach(() => { - vi.clearAllMocks() - clearRuntimeCompatibilityCacheForTests() - mockApi.pty.kill.mockResolvedValue(undefined) - mockUnregisterPtyDataHandlers.mockReturnValue([]) - applySleepRuntimeRpcDefault(mockApi) - shutdownBufferCaptures.clear() - }) - - it('waits for sibling local PTY kills before rolling back a failed shutdown', async () => { - const store = createTestStore() - const wt = 'repo1::/path/wt1' - let resolveSlowKill = (): void => {} - const slowKill = new Promise((resolve) => { - resolveSlowKill = resolve - }) - const handlerSnapshots = [ - { ptyId: 'pty-fails', dataHandler: vi.fn() }, - { ptyId: 'pty-slow', dataHandler: vi.fn() } - ] - mockUnregisterPtyDataHandlers.mockReturnValueOnce(handlerSnapshots) - mockApi.pty.kill.mockImplementation((ptyId: string) => - ptyId === 'pty-fails' ? Promise.reject(new Error('physical stop failed')) : slowKill - ) - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] - }, - tabsByWorktree: { [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })] }, - ptyIdsByTabId: { 'tab-1': ['pty-fails', 'pty-slow'] } - }) - - const shutdown = store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true }) - const rejection = expect(shutdown).rejects.toThrow('physical stop failed') - - resolveSlowKill() - await rejection - - expect(store.getState().ptyIdsByTabId['tab-1']).toEqual(['pty-fails']) - }) -}) diff --git a/src/shared/workspace-attachments/workspace-attachment-mutation.test.ts b/src/shared/workspace-attachments/workspace-attachment-mutation.test.ts index 023f8f147e1..2c50fa21422 100644 --- a/src/shared/workspace-attachments/workspace-attachment-mutation.test.ts +++ b/src/shared/workspace-attachments/workspace-attachment-mutation.test.ts @@ -122,14 +122,4 @@ describe('source-aware reference deltas', () => { expect(normalizeWorkspaceAttachments(structuredClone(result))).toEqual(result) } }) - it('collapses repoId conflicts the same way regardless of input order', () => { - const items: WorkspaceAttachment[] = [ - foreign, - { ...foreign, repoId: 'r1' }, - { ...foreign, repoId: 'r2' }, - { ...legacy, repoId: 'r1' } - ] - expect(normalizeWorkspaceAttachments(items)).toHaveLength(1) - expect(normalizeWorkspaceAttachments(items.toReversed())).toHaveLength(1) - }) }) diff --git a/tests/tools/omp-remote-sidebar-rendered/README.md b/tests/tools/omp-remote-sidebar-rendered/README.md index 7a22d0987b5..01633336764 100644 --- a/tests/tools/omp-remote-sidebar-rendered/README.md +++ b/tests/tools/omp-remote-sidebar-rendered/README.md @@ -6,6 +6,6 @@ ORCA_BACKGROUND_LAUNCH=1 node tests/tools/omp-remote-sidebar-rendered/run.mjs The fixture uses the production worktree selector, row builder, compact sidebar rows and styles. It supplies completed paired and SSH OMP status entries before any client tabs hydrate, alongside a local completed orphan. Both remote rows must render and the local orphan must remain absent. It then removes the injected statuses and verifies the rows disappear. -This checks rendered presentation, not a live paired/SSH transport or the full Orca shell. Real snapshot retraction, host/workspace isolation and visibility tombstones are covered by `worktree-agent-remote-attribution.test.ts`. The indexed retraction regression covers 100 workspaces with a single status-key enumeration per batch. +This checks rendered presentation, not a live paired/SSH transport or the full Orca shell. The indexed retraction regression covers 100 workspaces with a single status-key enumeration per batch. The existing hidden Electron fixture host provides an isolated profile. CDP screenshots and a report are written under `.bench-fixtures/omp-remote-sidebar-*`; every native window must remain hidden and unfocused.