diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 6e8726754dd..1f14decb770 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -10,7 +10,6 @@ 1 test-no-in-test-import-actual:src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts 1 test-no-in-test-import-actual:src/main/linear/accounts/linear-account-client.test.ts 1 test-no-in-test-import-actual:src/main/linear/issues/linear-description-images.test.ts -1 test-no-in-test-import-actual:src/main/managed-server/host-state/orcad-snapshot-room.test.ts 1 test-no-in-test-import-actual:src/main/omp/omp-session-cwd-lookup.test.ts 1 test-no-in-test-import-actual:src/main/pty/scrollback/overlay-mirror.test.ts 1 test-no-in-test-import-actual:src/main/runtime/rpc/server/pairing/mobile-pairing-userdata-path.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index b48d5d15016..ce456df31ec 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -3741,7 +3741,7 @@ "providers": ["local", "daemon", "ssh", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "paired-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. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here.", + "coverageNotes": "Audit5594 removes the entire src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts suite and its active selectors. Intentionally lose disposed-frame containment, reload/cancel resume and closed-sender refusal alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/14066", "https://linear.app/stably/issue/STA-4016", @@ -3750,7 +3750,7 @@ "invariant": "Every genuine renderer graph reload revision settles exactly once, while a blocked external navigation that preserves the current document never starts a revision. A cancelled renderer-document navigation restores authority only when that same renderer survived; cancellation after an earlier document committed remains fenced until publication or timeout. Replacing a reload cancels only the prior revision; its timer and callbacks cannot settle a newer revision. A desktop reload succeeds only from a publication carrying a new renderer-document generation, while a failed headless promotion may recover only from its originating window. Timeout, renderer loss, and close reach a terminal graph state, and successful desktop publication permanently retires headless sentinel fallback until a new headless runtime is established.", "oracle": "Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -3758,7 +3758,6 @@ ], "testFiles": [ "src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts", - "src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts", "src/main/ipc/runtime.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", @@ -3775,13 +3774,6 @@ "settlement and timeout release their timers" ] }, - { - "file": "src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts", - "assertions": [ - "disposed-frame failures are contained and send admission remains closed until a valid renderer document returns", - "late events cannot revive a closed sender" - ] - }, { "file": "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts", "assertions": [ @@ -3889,7 +3881,8 @@ "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/runtime-renderer-notification-sender.test.ts src/main/window/renderer-document-navigation.test.ts src/main/ipc/runtime.test.ts src/main/window/attach-main-window-services.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts\"", "Exact retired testFiles selector: \"src/main/window/attach-main-window-services.test.ts\"", - "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." + "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.", + "Audit5594 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts" ], "demotionRule": "Demote if a reload revision settles more than once, a stale document or competing window can publish, a timer survives settlement, desktop failure stays indefinitely reloading, headless fallback returns after successful promotion, or either isolated Electron journey loses runtime or PTY identity." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 13bac691993..3f9ea7a32a4 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -920,7 +920,6 @@ "src/main/claude/structured/turns/claude-command-lifecycle-frames.test.ts": 268, "src/main/claude/structured/turns/claude-command-lifecycle.test.ts": 1107, "src/main/claude/structured/turns/claude-command-turn.test.ts": 292, - "src/main/claude/structured/launch/claude-config-dir-pin.test.ts": 47, "src/main/claude/claude-context-model-switch.test.ts": 422, "src/main/claude/claude-context-usage-restart.test.ts": 925, "src/main/claude/claude-context-usage-unloaded-turn.test.ts": 4910, @@ -1022,7 +1021,6 @@ "src/main/codex-accounts/managed-homes/codex-config-mirror.test.ts": 331, "src/main/codex-accounts/credentials/codex-credential-absence-grace.test.ts": 62, "src/main/codex-accounts/managed-homes/codex-managed-home-path-wsl-check.test.ts": 71, - "src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts": 283, "src/main/filesystem/atomic-file-publication.test.ts": 127, "src/main/codex-accounts/managed-homes/guest-codex-account-homes.test.ts": 86, "src/main/codex-accounts/managed-homes/host-codex-managed-home-ownership.test.ts": 51, @@ -1487,7 +1485,6 @@ "src/main/git/command-runner/wsl-host-failure.test.ts": 241, "src/main/git/command-runner/wsl-service-failure-direct-git.test.ts": 259, "src/main/git/remotes/current-branch-identity-real-git.test.ts": 431, - "src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback-gate.test.ts": 465, "src/main/git/refs/fork-remotes/fork-remote-refspec.test.ts": 51, "src/main/git/refs/fork-remotes/fork-remote-stale-branch-refspec.test.ts": 46, "src/main/git/command-runner/git-capability-state.test.ts": 60, @@ -1639,8 +1636,6 @@ "src/main/github/github-project-account.test.ts": 547, "src/main/github/github-repository-identity.fork-owner-repo.test.ts": 478, "src/main/github/github-repository-identity.signed-cache.test.ts": 479, - "src/main/github/github-repository-identity.ssh-host-alias.test.ts": 523, - "src/main/github/github-rest-revalidation.test.ts": 637, "src/main/github/issue-work-item-details-fresh.test.ts": 490, "src/main/github/issues.test.ts": 569, "src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts": 643, @@ -1769,7 +1764,6 @@ "src/main/ipc/filesystem/local-disk-write-precondition.test.ts": 8407, "src/main/ipc/filesystem/local-regular-file-read.test.ts": 78, "src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts": 93, - "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts": 54, "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts": 145, "src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts": 162, "src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts": 51, @@ -2194,7 +2188,6 @@ "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/electron/electron-sidecar-tab-registry.test.ts": 105, "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, @@ -2432,7 +2425,6 @@ "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-enablement.test.ts": 340, "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, @@ -2453,7 +2445,6 @@ "src/main/plugins/view/plugin-view-editor-shot.test.ts": 194, "src/main/plugins/view/plugin-view-replay-shot.test.ts": 256, "src/main/plugins/view/plugin-view-target.test.ts": 143, - "src/main/plugins/workers/plugin-host-methods.test.ts": 277, "src/main/plugins/workers/plugin-host-panel-methods.test.ts": 304, "src/main/plugins/workers/plugin-host-runtime.test.ts": 274, "src/main/plugins/workers/plugin-host-status-bar-methods.test.ts": 270, @@ -2901,7 +2892,6 @@ "src/main/runtime/terminal/recovery/restored-pane-start-layout-owner.test.ts": 6438, "src/main/runtime/files/paths/ripgrep-filename-identity.test.ts": 59, "src/main/runtime/rpc/device-key-auth.test.ts": 518, - "src/main/runtime/rpc/dispatcher-feature-readiness.test.ts": 719, "src/main/runtime/rpc/dispatcher-request-parsing.test.ts": 452, "src/main/runtime/rpc/dispatcher-transport-parity.test.ts": 5288, "src/main/runtime/rpc/e2ee-channel-text-backpressure.test.ts": 204, @@ -3012,7 +3002,6 @@ "src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts": 5136, "src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts": 45, "src/main/runtime/rpc/methods/orchestration/worker/start/readiness/worker-start-prompt-contract.test.ts": 6279, - "src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts": 4508, "src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-liveness-verdict.test.ts": 5279, "src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-terminal-custody-at-creation.test.ts": 5687, "src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-new-worktree-start.test.ts": 6117, @@ -3462,7 +3451,6 @@ "src/main/managed-server/activation/orcad-retained-fence-takeover.test.ts": 210, "src/main/persistence/migrating-orcad-catalog/retained-source/orcad-retained-source-changes.test.ts": 2185, "src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts": 916, - "src/main/managed-server/host-state/orcad-snapshot-room.test.ts": 402, "src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts": 627, "src/main/managed-server/lifecycle/orcad-terminal-census-client.test.ts": 217, "src/main/managed-server/lifecycle/orcad-tunneled-pairing.test.ts": 94, @@ -3496,7 +3484,6 @@ "src/main/ssh/remote-host/ssh-host-proxy-environment.test.ts": 170, "src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts": 510, "src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts": 455, - "src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts": 55, "src/main/ssh/host-server/ssh-host-server-on-connect-telemetry.test.ts": 440, "src/main/ssh/host-server/ssh-host-server-on-connect.test.ts": 536, "src/main/ssh/host-server/ssh-host-server-telemetry.test.ts": 194, @@ -3530,7 +3517,6 @@ "src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts": 288, "src/main/ssh/targets/ssh-target-id-migration.test.ts": 50, "src/main/ssh/targets/ssh-target-identity.test.ts": 43, - "src/main/ssh/targets/ssh-target-orcad-claims.test.ts": 265, "src/main/ssh/targets/ssh-target-orcad-dependents.test.ts": 305, "src/main/ssh/targets/ssh-target-orcad-preflight.test.ts": 1698, "src/main/ssh/targets/ssh-target-readoption.test.ts": 52, @@ -3548,7 +3534,6 @@ "src/main/startup/e2e-external-open-guard.test.ts": 44, "src/main/startup/e2e-spawn-log-env.test.ts": 89, "src/main/startup/first-window-startup-services.test.ts": 54, - "src/main/startup/gpu-fallback-marker.test.ts": 61, "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, @@ -3572,7 +3557,6 @@ "src/main/startup/serve-signal-handlers.test.ts": 48, "src/main/startup/single-instance-lock-exit.electron.test.ts": 551, "src/main/startup/skill-share-deep-link-state.test.ts": 217, - "src/main/startup/windows-app-data-path.test.ts": 55, "src/main/startup/windows-install-dir-acl-recovery.test.ts": 614, "src/main/startup/windows-install-dir-acl-repair.win32.test.ts": 132, "src/main/startup/windows-install-dir-package-acl-grant.test.ts": 88, @@ -3613,7 +3597,6 @@ "src/main/text-generation/models/commit-message-text-generation-model-discovery.test.ts": 504, "src/main/text-generation/requests/commit-message-text-generation-regression.test.ts": 408, "src/main/text-generation/requests/conversation-name-generation-request.test.ts": 507, - "src/main/text-generation/requests/jira-issue-summary-requests.test.ts": 276, "src/main/text-generation/failures/kimi-generation-failure.test.ts": 151, "src/main/text-generation/execution/source-control-agent-cli-path.test.ts": 615, "src/main/text-generation/execution/source-control-local-process.test.ts": 1834, @@ -3658,13 +3641,11 @@ "src/main/warp-themes/theme-file-scanner.test.ts": 56, "src/main/windows/windows-command-paths.test.ts": 77, "src/main/window/clipboard-agent-session-attachment-paste.test.ts": 585, - "src/main/window/clipboard-copied-file-paths.test.ts": 58, "src/main/window/clipboard-dashboard-popout-access.test.ts": 1361, "src/main/window/clipboard-macos-image-paste.test.ts": 1087, "src/main/window/clipboard-publisher-executable.test.ts": 62, "src/main/window/clipboard-remote-file-staging-fs.test.ts": 66, "src/main/window/clipboard-remote-file-staging.test.ts": 105, - "src/main/window/clipboard-text-publisher.test.ts": 383, "src/main/window/clipboard-windows-image-file.test.ts": 84, "src/main/window/createMainWindow-close-confirmation.test.ts": 1319, "src/main/window/createMainWindow-low-commit-oom-recovery.test.ts": 1642, @@ -3692,7 +3673,6 @@ "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-renderer-notification-sender.test.ts": 54, "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, @@ -3899,7 +3879,6 @@ "src/renderer/src/components/automations/external-automation-scope-keys.test.ts": 53, "src/renderer/src/components/automations/hosts/use-automation-host-catalog-readoption.test.tsx": 802, "src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx": 920, - "src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx": 679, "src/renderer/src/components/automations/use-selected-automation-run-history.test.tsx": 2104, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.drag-focus.test.tsx": 5826, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx": 3085, @@ -4034,7 +4013,6 @@ "src/renderer/src/components/editor/external-changes/editor-external-watch-path-index.test.ts": 1754, "src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts": 1915, "src/renderer/src/components/editor/editor-git-discard-other-workspace.test.ts": 1967, - "src/renderer/src/components/editor/editor-header-file-rename.test.ts": 2025, "src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts": 5906, "src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-labels.test.ts": 1223, "src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts": 1809, @@ -4356,7 +4334,6 @@ "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, "src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342, "src/shared/new-workspace/smart-workspace-source-results.test.ts": 136, - "src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx": 278, "src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx": 419, "src/renderer/src/components/new-workspace/use-linear-source-connection.test.tsx": 1335, "src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx": 2290, @@ -4660,10 +4637,8 @@ "src/renderer/src/components/task-page/jira/task-page-jira-board-detail-integration.test.tsx": 2192, "src/renderer/src/components/task-page/jira/task-page-jira-board-view.test.tsx": 2287, "src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts": 204, - "src/renderer/src/components/task-page/jira/filters/use-task-page-jira-project-scope.test.tsx": 2642, "src/renderer/src/components/task-page/jira/creation/use-task-page-jira-summary-generation.test.tsx": 571, "src/renderer/src/components/task-page/linear/task-page-linear-creation-lifetime.test.tsx": 3315, - "src/renderer/src/components/task-page/linear/issues/task-page-linear-in-orca-issues.test.ts": 430, "src/renderer/src/components/task-page/linear/issue-refresh/task-page-linear-refresh-lifecycle.test.tsx": 1814, "src/renderer/src/components/task-page/task-page-cache-selectors.test.ts": 108, "src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1953, @@ -4862,7 +4837,6 @@ "src/renderer/src/components/terminal-pane/terminal-resume-escape-gap.test.ts": 102, "src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts": 80, "src/renderer/src/components/terminal-pane/snapshots/terminal-snapshot-replay-paint.test.ts": 499, - "src/renderer/src/components/terminal-pane/titles/terminal-title-evidence.test.ts": 184, "src/renderer/src/components/terminal-pane/links/http/terminal-url-link-click.test.ts": 2057, "src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.test.ts": 1878, "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts": 1806, @@ -5042,7 +5016,6 @@ "src/shared/agent-status/title/agent-title-tracker.test.ts": 172, "src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts": 678, "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts": 541, - "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-platform.test.ts": 617, "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-target.test.ts": 92, "src/renderer/src/lib/agent-session/resume/history/ai-vault-session-drag.test.ts": 68, "src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.test.ts": 408, @@ -5231,7 +5204,6 @@ "src/renderer/src/runtime/hosted-terminals/recovery/inventory/web-session-terminal-orphan-absence-across-republication.test.ts": 678, "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/web-session-terminal-orphan-recovery-sleep.test.ts": 1066, "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, @@ -5325,7 +5297,6 @@ "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-manual-refresh-broadcast.test.ts": 693, "src/renderer/src/store/github/refresh/github-pr-refresh-states-leak.test.ts": 1327, "src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts": 1458, "src/renderer/src/store/github/repositories/github-repo-lookup-index.test.ts": 51, @@ -5355,7 +5326,6 @@ "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/repos/repos-nested-ssh-projection.test.ts": 1780, "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, @@ -5367,7 +5337,6 @@ "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/agent-inventory/runtime-detected-agents.test.ts": 478, "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, @@ -5390,7 +5359,6 @@ "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-pane-layout-operations.test.ts": 1652, "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, @@ -5398,7 +5366,6 @@ "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, - "src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts": 50, "src/renderer/src/store/terminals/terminals-hydration-canonical-pty-overlap.test.ts": 1946, "src/renderer/src/store/terminals/terminals-hydration-canonical-rows.test.ts": 1680, "src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts": 597, @@ -5445,7 +5412,6 @@ "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, "src/renderer/src/store/slices/worktrees/host-scoped-row-merges.test.ts": 1805, - "src/renderer/src/store/slices/worktrees/listing/detected-worktree-meta.test.ts": 318, "src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts": 1828, "src/renderer/src/store/slices/worktrees/metadata/worktree-meta-persist.test.ts": 361, "src/renderer/src/store/slices/worktrees/teardown/host-qualified-removal-refusal.test.ts": 518, @@ -5817,12 +5783,10 @@ "src/shared/native-chat/tools/native-chat-tool-run-outcome.test.ts": 68, "src/shared/native-chat/tools/native-chat-turn-membership-derived-tool-row.test.ts": 268, "src/shared/native-chat/transcript/native-chat-image-transcript-markers.test.ts": 94, - "src/shared/native-chat/transcript/native-chat-subagent-items.test.ts": 188, "src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts": 715, "src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts": 182, "src/shared/native-chat/transcript/native-chat-turn-fold.test.ts": 192, "src/shared/native-chat/transcript/native-chat-turn-status.test.ts": 69, - "src/shared/native-chat/transcript/native-chat-unverifiable-turn-status.test.ts": 150, "src/shared/native-file-drop.test.ts": 59, "src/shared/ndjson-retained-chunk-memory.test.ts": 327, "src/shared/nested-repo-telemetry.test.ts": 55, @@ -6167,9 +6131,7 @@ "src/shared/workspace-layout/persistence/workspace-layout-load-check-details.test.ts": 286, "src/shared/workspace-layout/persistence/workspace-layout-load-duplicate-pty.test.ts": 340, "src/shared/workspace-layout/persistence/workspace-layout-load-normalization.test.ts": 470, - "src/shared/workspace-layout/persistence/workspace-layout-load-synthetic-pane-title.test.ts": 324, "src/shared/workspace-layout/persistence/workspace-layout-load-view-less-tabs.test.ts": 294, - "src/shared/workspace-layout/commands/workspace-layout-move-tab-anchor.test.ts": 160, "src/shared/workspace-layout/commands/workspace-layout-move-tab-pin.test.ts": 180, "src/shared/workspace-layout/commands/workspace-layout-open-in-new-group.test.ts": 195, "src/shared/workspace-layout/editor-tabs/workspace-layout-owned-editor-id.test.ts": 334, diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 6afb0f65e4a..026151e55a8 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -191,7 +191,6 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/cursor/hook-service.test.ts', 'src/main/orca-profiles/profile-index-store.test.ts', 'src/main/startup/windows-install-permissions/windows-install-dir-acl-repair.win32.test.ts', - 'src/main/startup/windows-startup/windows-app-data-path.test.ts', 'src/main/startup/windows-startup/windows-std-handle-inheritance.win32.test.ts', 'src/main/startup/windows-startup/windows-isolated-spawner.win32.test.ts', 'src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts', diff --git a/mobile/src/host-screen/workspace-list/use-slow-pending-keys.test.tsx b/mobile/src/host-screen/workspace-list/use-slow-pending-keys.test.tsx deleted file mode 100644 index c0de9248955..00000000000 --- a/mobile/src/host-screen/workspace-list/use-slow-pending-keys.test.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import { createElement } from 'react' -import { act, create as createRenderer, type ReactTestRenderer } from 'react-test-renderer' - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useSlowPendingKeys } from './use-slow-pending-keys' - -const renderers = new Set>() -function create(...args: Parameters): ReturnType { - const renderer = createRenderer(...args) - renderers.add(renderer) - return renderer -} -function unmountRenderers(): void { - act(() => { - for (const renderer of renderers) { - renderer.unmount() - } - }) - renderers.clear() -} - -let latest: ReadonlySet = new Set() -function Probe({ pending }: { pending: ReadonlySet }) { - latest = useSlowPendingKeys(pending) - return null -} - -function mount(pending: ReadonlySet): ReactTestRenderer { - let renderer: ReactTestRenderer | null = null - act(() => { - renderer = create(createElement(Probe, { pending })) - }) - if (!renderer) { - throw new Error('not mounted') - } - return renderer -} - -function update(renderer: ReactTestRenderer, pending: ReadonlySet): void { - act(() => renderer.update(createElement(Probe, { pending }))) -} - -function advance(ms: number): void { - act(() => { - vi.advanceTimersByTime(ms) - }) -} - -describe('useSlowPendingKeys', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - afterEach(() => { - unmountRenderers() - vi.useRealTimers() - }) - - it('times each key from when it first went pending, across re-renders', () => { - const renderer = mount(new Set(['a'])) - advance(300) - update(renderer, new Set(['a', 'b'])) - advance(200) - expect([...latest]).toEqual(['a']) - advance(300) - expect([...latest].sort()).toEqual(['a', 'b']) - }) - - it('waits out the delay afresh for a key that settles and goes pending again', () => { - const renderer = mount(new Set(['a'])) - advance(600) - update(renderer, new Set()) - update(renderer, new Set(['a'])) - expect([...latest]).toEqual([]) - advance(499) - expect([...latest]).toEqual([]) - advance(1) - expect([...latest]).toEqual(['a']) - }) -}) diff --git a/mobile/src/platform/clipboard/clipboard.test.tsx b/mobile/src/platform/clipboard/clipboard.test.tsx deleted file mode 100644 index 33d8d62d109..00000000000 --- a/mobile/src/platform/clipboard/clipboard.test.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import { act, create } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ClipboardImage, ClipboardReader } from './clipboard' - -const clipboard = vi.hoisted(() => ({ - setStringAsync: vi.fn(() => Promise.resolve(true)), - getStringAsync: vi.fn(() => Promise.resolve('')), - getImageAsync: vi.fn<() => Promise>(() => Promise.resolve(null)), - hasStringAsync: vi.fn(() => Promise.resolve(false)), - hasImageAsync: vi.fn(() => Promise.resolve(false)) -})) - -vi.mock('expo-clipboard', () => clipboard) - -import { useClipboardReader } from './clipboard' - -function mountReader(): ClipboardReader { - const held: { reader: ClipboardReader | null } = { reader: null } - function Screen(): null { - held.reader = useClipboardReader() - return null - } - act(() => { - create() - }) - const reader = held.reader - if (reader === null) { - throw new Error('nothing mounted') - } - return reader -} - -beforeEach(() => { - clipboard.setStringAsync.mockReset() - clipboard.setStringAsync.mockImplementation(() => Promise.resolve(true)) - clipboard.getStringAsync.mockReset() - clipboard.getStringAsync.mockImplementation(() => Promise.resolve('')) - clipboard.getImageAsync.mockReset() - clipboard.getImageAsync.mockImplementation(() => Promise.resolve(null)) - clipboard.hasStringAsync.mockReset() - clipboard.hasStringAsync.mockImplementation(() => Promise.resolve(false)) - clipboard.hasImageAsync.mockReset() - clipboard.hasImageAsync.mockImplementation(() => Promise.resolve(false)) -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('reading the clipboard on a phone', () => { - it('starts both probes before either has answered', async () => { - // Hold both probes open to prove they start in parallel; sequential awaits add IPC latency on mount/foreground/toggle. - const started: string[] = [] - let releaseString = (): void => {} - clipboard.hasStringAsync.mockImplementation( - () => - new Promise((resolve) => { - started.push('string') - releaseString = () => resolve(true) - }) - ) - clipboard.hasImageAsync.mockImplementation(() => { - started.push('image') - releaseString() - return Promise.resolve(false) - }) - await expect(mountReader().contents()).resolves.toEqual({ text: true, image: false }) - expect(started).toEqual(['string', 'image']) - }) -}) diff --git a/src/main/claude/structured/launch/claude-config-dir-pin.test.ts b/src/main/claude/structured/launch/claude-config-dir-pin.test.ts deleted file mode 100644 index d81ef82d32f..00000000000 --- a/src/main/claude/structured/launch/claude-config-dir-pin.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { homedir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { - claudeConfigDirEnvPatch, - defaultClaudeConfigDir, - withoutInheritedClaudeConfigDir -} from './claude-config-dir-pin' - -describe('claude config dir pin', () => { - it('does not pin the CLI default home, so the macOS Keychain stays reachable', () => { - expect(claudeConfigDirEnvPatch(join(homedir(), '.claude'), { env: {} })).toEqual({}) - expect(claudeConfigDirEnvPatch(`${join(homedir(), '.claude')}/`, { env: {} })).toEqual({}) - expect(claudeConfigDirEnvPatch(' ', { env: {} })).toEqual({}) - }) - - it('treats an inherited CLAUDE_CONFIG_DIR as the default the CLI already resolves', () => { - const env = { CLAUDE_CONFIG_DIR: '/inherited/home' } - expect(defaultClaudeConfigDir(env)).toBe('/inherited/home') - expect(claudeConfigDirEnvPatch('/inherited/home', { env })).toEqual({}) - expect(claudeConfigDirEnvPatch('/other/home', { env })).toEqual({ - CLAUDE_CONFIG_DIR: '/other/home' - }) - }) - - it('compares Windows homes case-insensitively', () => { - const env = { CLAUDE_CONFIG_DIR: 'C:\\Users\\Work\\.claude' } - expect(claudeConfigDirEnvPatch('c:\\users\\work\\.claude', { env, platform: 'win32' })).toEqual( - {} - ) - }) - - it('drops an inherited CLAUDE_CONFIG_DIR, case-insensitively on Windows, and nothing else', () => { - expect( - withoutInheritedClaudeConfigDir( - { CLAUDE_CONFIG_DIR: '/shell/claude', PATH: '/bin', UNSET: undefined }, - 'darwin' - ) - ).toEqual({ PATH: '/bin' }) - expect( - withoutInheritedClaudeConfigDir({ claude_config_dir: 'C:\\shell', Path: 'C:\\bin' }, 'win32') - ).toEqual({ Path: 'C:\\bin' }) - expect( - withoutInheritedClaudeConfigDir({ claude_config_dir: '/shell/claude' }, 'darwin') - ).toEqual({ claude_config_dir: '/shell/claude' }) - }) -}) diff --git a/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts b/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts deleted file mode 100644 index a0adcb0de6d..00000000000 --- a/src/main/codex-accounts/reset-credits/codex-reset-credit-ledger.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { CodexResetCreditAttemptLedger } from '../../../shared/codex-reset-credit-attempt-ledger' -import type { CodexResetCreditExpectedScope } from '../../../shared/codex-reset-credit-scope' -import { ProfileStateWriterError } from '../../persistence/profile-state/writer/profile-state-writer-errors' -import { CodexResetCreditLedger } from './codex-reset-credit-ledger' - -function scope(accountId: string): CodexResetCreditExpectedScope { - return { - target: { runtime: 'host', wslDistro: null }, - accountId, - accountRevision: 1, - offerRevision: 'offer-1' - } -} - -function setup() { - let durable: CodexResetCreditAttemptLedger = { version: 1, attempts: [] } - const barrier = vi.fn(async () => {}) - const store = { - getCodexResetCreditAttemptLedger: () => structuredClone(durable), - replaceCodexResetCreditAttemptLedgerAndFlush: vi.fn( - async (next: CodexResetCreditAttemptLedger) => { - await barrier() - durable = structuredClone(next) - } - ) - } - return { ledger: new CodexResetCreditLedger(store), store, barrier } -} - -describe('async reset-credit ledger', () => { - it('serializes replacement construction so concurrent account writes survive', async () => { - const { ledger, store, barrier } = setup() - const gate = Promise.withResolvers() - barrier.mockImplementationOnce(() => gate.promise) - const first = ledger.createFresh('first', scope('account-1')) - const second = ledger.createFresh('second', scope('account-2')) - const pendingFirst = ledger.markProviderPending('first', first) - const pendingSecond = ledger.markProviderPending('second', second) - await vi.waitFor(() => expect(barrier).toHaveBeenCalledOnce()) - expect(first.state).toBe('fresh') - expect(second.state).toBe('fresh') - expect(store.getCodexResetCreditAttemptLedger().attempts).toEqual([]) - - gate.resolve() - await Promise.all([pendingFirst, pendingSecond]) - expect(store.getCodexResetCreditAttemptLedger().attempts).toMatchObject([ - { idempotencyKey: 'first', state: 'providerPending' }, - { idempotencyKey: 'second', state: 'providerPending' } - ]) - expect(ledger.getUnresolvedKey(first.accountScopeKey)).toBe('first') - expect(ledger.getUnresolvedKey(second.accountScopeKey)).toBe('second') - }) - - it('keeps pending guards until settlement commits and can retry a known failure', async () => { - const { ledger, store, barrier } = setup() - const attempt = ledger.createFresh('first', scope('account-1')) - await ledger.markProviderPending('first', attempt) - const gate = Promise.withResolvers() - barrier.mockImplementationOnce(() => gate.promise) - const settled = ledger.markSettled('first', attempt, 'reset') - const rejected = expect(settled).rejects.toThrow('disk full') - await vi.waitFor(() => expect(barrier).toHaveBeenCalledTimes(2)) - expect(attempt.state).toBe('providerPending') - expect(ledger.getUnresolvedKey(attempt.accountScopeKey)).toBe('first') - - gate.reject(new Error('disk full')) - await rejected - expect(attempt.state).toBe('providerPending') - expect(store.getCodexResetCreditAttemptLedger().attempts[0]?.state).toBe('providerPending') - expect(ledger.error).toBeNull() - await ledger.markSettled('first', attempt, 'alreadyRedeemed') - expect(attempt.settledOutcome).toBe('alreadyRedeemed') - expect(ledger.getUnresolvedKey(attempt.accountScopeKey)).toBeUndefined() - }) - - it('waits for queued writes before removing an account and retains other accounts', async () => { - const { ledger, store, barrier } = setup() - const first = ledger.createFresh('first', scope('account-1')) - const second = ledger.createFresh('second', scope('account-2')) - await ledger.markProviderPending('first', first) - const gate = Promise.withResolvers() - barrier.mockImplementationOnce(() => gate.promise) - const pendingSecond = ledger.markProviderPending('second', second) - const removed = ledger.discardForRemovedAccount('account-1') - await vi.waitFor(() => expect(barrier).toHaveBeenCalledTimes(2)) - expect(ledger.get('first')).toBe(first) - - gate.resolve() - await Promise.all([pendingSecond, removed]) - expect(store.getCodexResetCreditAttemptLedger().attempts).toMatchObject([ - { idempotencyKey: 'second', state: 'providerPending' } - ]) - expect(ledger.get('first')).toBeUndefined() - expect(ledger.getUnresolvedKey(first.accountScopeKey)).toBeUndefined() - expect(ledger.get('second')).toBe(second) - }) - - it('fails queued and future mutations closed when a commit outcome is unknown', async () => { - const { ledger, store, barrier } = setup() - const attempt = ledger.createFresh('first', scope('account-1')) - const second = ledger.createFresh('second', scope('account-2')) - const gate = Promise.withResolvers() - barrier.mockImplementationOnce(() => gate.promise) - const pending = ledger.markProviderPending('first', attempt) - const queued = ledger.markProviderPending('second', second) - const rejected = expect(pending).rejects.toThrow('worker stopped') - const blocked = expect(queued).rejects.toThrow('durability is unknown') - await vi.waitFor(() => expect(barrier).toHaveBeenCalledOnce()) - gate.reject(new ProfileStateWriterError('worker-exit', 'worker stopped', 'indeterminate')) - await Promise.all([rejected, blocked]) - - ledger.releaseFresh('first', attempt) - expect(ledger.get('first')).toBe(attempt) - expect(ledger.findAttemptFor('other', attempt.scopeKey, 'none')?.idempotencyKey).toBe('first') - expect(store.replaceCodexResetCreditAttemptLedgerAndFlush).toHaveBeenCalledOnce() - await expect(ledger.discardForRemovedAccount('account-1')).rejects.toThrow( - 'durability is unknown' - ) - }) -}) diff --git a/src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback-gate.test.ts b/src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback-gate.test.ts deleted file mode 100644 index af4edd1a875..00000000000 --- a/src/main/git/command-runner/hosted-cli/default-wsl-cli-fallback-gate.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -// E9: a cwd-less gh/glab call whose host CLI is missing must not boot a stopped default distro from -// background work (rate limits, auth status, Settings, task-source probes). -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { fakeSpawnReturning } from '../../../../shared/__fixtures__/fake-spawned-child' -import type * as WslModule from '../../../wsl/discovery/distro-catalog' -import type * as BackgroundDistroGate from '../../../wsl/discovery/wsl-background-distro-gate' - -const { spawnMock, getDefaultWslDistroMock, readWslDistroRunningStateMock } = vi.hoisted(() => ({ - spawnMock: vi.fn(), - getDefaultWslDistroMock: vi.fn(), - readWslDistroRunningStateMock: vi.fn() -})) - -vi.mock('child_process', () => ({ - execFile: vi.fn(), - execFileSync: vi.fn(), - spawn: spawnMock -})) - -vi.mock('../../../wsl/discovery/distro-catalog', async (importOriginal) => ({ - ...(await importOriginal()), - getDefaultWslDistro: getDefaultWslDistroMock -})) - -vi.mock('../../../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => ({ - ...(await importOriginal()), - readWslDistroRunningState: readWslDistroRunningStateMock -})) - -import { ghExecFileAsync } from './gh-exec-file' -import { glabExecFileAsync } from './glab-exec-file' -import { setDefaultWslDistroOverride } from '../host-routing/wsl-command-resolution' -import { _resetGhRateLimitBreaker } from './gh-rate-limit-breaker' -import { runAsWslExecUserAct } from '../../../wsl/discovery/wsl-background-exec-gate' -import { - WslDistroStoppedError, - WslDistroUnverifiableError -} from '../../../wsl/filesystem/wsl-unc-access-gate' -import { starOrca } from '../../../github/client/fetch/orca-star' - -const originalPlatform = process.platform - -const CLIS = [ - { cli: 'gh', run: () => ghExecFileAsync(['api', 'rate_limit']) }, - { cli: 'glab', run: () => glabExecFileAsync(['api', 'user']) } -] as const - -function hostMissingThenWslAnswers(cli: string): void { - spawnMock - .mockImplementationOnce( - fakeSpawnReturning({ - spawnError: Object.assign(new Error(`spawn ${cli} ENOENT`), { code: 'ENOENT' }) - }) - ) - .mockImplementationOnce(fakeSpawnReturning({ stdout: '{}' })) -} - -function spawnedWsl(): boolean { - return spawnMock.mock.calls.some(([program]) => program === 'wsl.exe') -} - -beforeEach(() => { - spawnMock.mockReset() - getDefaultWslDistroMock.mockReset().mockReturnValue('Ubuntu') - readWslDistroRunningStateMock.mockReset().mockResolvedValue('running') - setDefaultWslDistroOverride(null) - _resetGhRateLimitBreaker() - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) -}) - -afterEach(() => { - _resetGhRateLimitBreaker() - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) -}) - -describe.each(CLIS)('$cli default-distro fallback', ({ cli, run }) => { - it('never starts a stopped default distro, and says it is stopped rather than missing', async () => { - readWslDistroRunningStateMock.mockResolvedValue('stopped') - hostMissingThenWslAnswers(cli) - - const error = await run().catch((caught: unknown) => caught) - - expect(error).toBeInstanceOf(WslDistroStoppedError) - expect(String(error)).toContain("WSL distro 'Ubuntu' is not running") - expect(String(error)).not.toMatch(/ENOENT|not found/) - expect(spawnedWsl()).toBe(false) - }) - - it('never starts one whose state WSL could not report', async () => { - readWslDistroRunningStateMock.mockResolvedValue('unverifiable') - hostMissingThenWslAnswers(cli) - - await expect(run()).rejects.toBeInstanceOf(WslDistroUnverifiableError) - expect(spawnedWsl()).toBe(false) - }) - - it('still falls back to a stopped one inside a user act for it', async () => { - readWslDistroRunningStateMock.mockResolvedValue('stopped') - hostMissingThenWslAnswers(cli) - - await expect(runAsWslExecUserAct('Ubuntu', run)).resolves.toEqual({ stdout: '{}', stderr: '' }) - expect(spawnedWsl()).toBe(true) - }) -}) - -describe('starring Orca, which is always a click', () => { - it('may start the stopped default distro its gh lives in', async () => { - readWslDistroRunningStateMock.mockResolvedValue('stopped') - hostMissingThenWslAnswers('gh') - - await expect(starOrca()).resolves.toBe(true) - expect(spawnedWsl()).toBe(true) - }) -}) diff --git a/src/main/github/api/github-rest-revalidation.test.ts b/src/main/github/api/github-rest-revalidation.test.ts deleted file mode 100644 index 299974fc318..00000000000 --- a/src/main/github/api/github-rest-revalidation.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { revalidateGitHubRestJson } from './github-rest-revalidation' - -const { gh, spend } = vi.hoisted(() => ({ gh: vi.fn(), spend: vi.fn() })) -vi.mock('../../git/command-runner/hosted-cli/gh-exec-file', () => ({ - ghExecFileAsync: gh -})) -vi.mock('./rate-limit', () => ({ - noteRepositoryRateLimitSpend: spend -})) - -const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } -const endpoint = 'repos/acme/widgets/pulls/7' -const options = { cwd: '/repo' } -let read: typeof revalidateGitHubRestJson -function http(status: number, body = '', etag?: string): { stdout: string; stderr: string } { - return { - stdout: `HTTP/2.0 ${status} ${status === 304 ? 'Not Modified' : 'OK'}\n${etag ? `Etag: ${etag}\r\n` : ''}\r\n${body}`, - stderr: '' - } -} -function notModified() { - return Object.assign(new Error('gh: HTTP 304'), http(304)) -} - -describe('GitHub REST revalidation', () => { - beforeEach(async () => { - vi.resetModules() - gh.mockReset() - spend.mockReset() - read = (await import('./github-rest-revalidation')).revalidateGitHubRestJson - }) - afterEach(() => vi.unstubAllEnvs()) - - it('revalidates immediately and returns the validated body on gh HTTP 304 exits without spending quota', async () => { - gh.mockResolvedValueOnce(http(200, '{"number":7}', 'W/"v1"')).mockRejectedValueOnce( - notModified() - ) - expect(await read(repository, endpoint, options)).toBe('{"number":7}') - expect(await read(repository, endpoint, options)).toBe('{"number":7}') - expect(gh.mock.calls[1][0]).toEqual([ - 'api', - endpoint, - '--include', - '-H', - 'If-None-Match: W/"v1"' - ]) - expect(spend).toHaveBeenCalledTimes(1) - expect(spend).toHaveBeenCalledWith(repository, 'core', 1, expect.objectContaining(options)) - }) - - it('does not return cached data after authorization failures and discards its validator', async () => { - gh.mockResolvedValueOnce(http(200, '{"number":7}', '"v1"')) - await read(repository, endpoint, options) - const failure = Object.assign( - new Error('HTTP 403 forbidden'), - http(403, '{"message":"forbidden"}') - ) - gh.mockRejectedValueOnce(failure).mockResolvedValueOnce(http(200, '{"number":8}')) - await expect(read(repository, endpoint, options)).rejects.toBe(failure) - expect(await read(repository, endpoint, options)).toBe('{"number":8}') - expect(gh.mock.calls[2][0]).not.toContain('-H') - }) - - it('does not retain malformed or validator-free bodies and rejects ungrounded 304 responses', async () => { - gh.mockResolvedValueOnce(http(200, '{"number":7}')) - .mockResolvedValueOnce(http(200, 'truncated', '"bad"')) - .mockRejectedValueOnce(notModified()) - await read(repository, endpoint, options) - await expect(read(repository, endpoint, options)).rejects.toThrow() - await expect(read(repository, endpoint, options)).rejects.toThrow( - 'without a cached representation' - ) - expect(gh.mock.calls.every(([args]) => !args.includes('-H'))).toBe(true) - }) - - it('does not let an older read replace a newer validator', async () => { - let finish: (result: ReturnType) => void = () => {} - gh.mockImplementationOnce( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - .mockResolvedValueOnce(http(200, '{"number":8}', '"new"')) - .mockRejectedValueOnce(notModified()) - const older = read(repository, endpoint, options) - await read(repository, endpoint, options) - finish(http(200, '{"number":7}', '"old"')) - await older - expect(await read(repository, endpoint, options)).toBe('{"number":8}') - expect(gh.mock.calls[2][0]).toContain('If-None-Match: "new"') - }) -}) diff --git a/src/main/github/pull-requests/refresh/merged-pr-commit-membership.test.ts b/src/main/github/pull-requests/refresh/merged-pr-commit-membership.test.ts deleted file mode 100644 index 273bdeab5a8..00000000000 --- a/src/main/github/pull-requests/refresh/merged-pr-commit-membership.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) - -vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ - ghExecFileAsync: ghExecFileAsyncMock -})) -vi.mock('../../api/rate-limit', () => ({ - repositoryRateLimitGuard: () => ({ blocked: false }), - noteRepositoryRateLimitSpend: () => {} -})) - -import { - getMergedPRHeadRelationship, - resetMergedPRCommitMembershipCacheForTest -} from './merged-pr-commit-membership' - -const REBASED_AWAY = '6ada46e391c5e4025d13d0304c4c0729af13a923' - -function membership() { - return getMergedPRHeadRelationship({ - ownerRepo: { owner: 'stablyai', repo: 'orca' }, - prNumber: 41082, - commitOid: REBASED_AWAY, - ghOptions: { cwd: '/repo' } - }) -} - -function scriptForcePushes(beforeOids: (string | null)[], hasPreviousPage = false): void { - ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[1] === 'graphql') { - return { - stdout: JSON.stringify({ - data: { - repository: { - pullRequest: { - timelineItems: { - totalCount: 23, - pageInfo: { hasPreviousPage }, - nodes: beforeOids.map((oid) => ({ beforeCommit: oid ? { oid } : null })) - } - } - } - } - }) - } - } - // GitHub drops a force-pushed-away commit's PR association. - return { stdout: '[]' } - }) -} - -describe('getMergedPRHeadRelationship', () => { - it('proves absence from a complete filtered page despite an unfiltered total count', async () => { - scriptForcePushes([ - '1111111111111111111111111111111111111111', - '2222222222222222222222222222222222222222' - ]) - await expect(membership()).resolves.toBe('not-contained') - }) - - it('keeps absence unknown when a previous filtered page exists', async () => { - scriptForcePushes(['1111111111111111111111111111111111111111'], true) - await expect(membership()).resolves.toBe('unknown') - }) - - it('preserves uncertainty when a force-push event has no prior commit', async () => { - scriptForcePushes([null]) - await expect(membership()).resolves.toBe('unknown') - }) - - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - resetMergedPRCommitMembershipCacheForTest() - }) - - it('treats a force-pushed-away head as association without claiming its changes landed', async () => { - scriptForcePushes([null, REBASED_AWAY]) - await expect(membership()).resolves.toBe('associated') - }) -}) diff --git a/src/main/github/repositories/github-repository-identity.ssh-host-alias.test.ts b/src/main/github/repositories/github-repository-identity.ssh-host-alias.test.ts deleted file mode 100644 index ae219555fe9..00000000000 --- a/src/main/github/repositories/github-repository-identity.ssh-host-alias.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import type * as CommandExecFileModule from '../../git/command-runner/process-capture/command-exec-file' -import type * as GitExecFileModule from '../../git/command-runner/git-exec-file' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - commandExecFileAsyncMock, - gitExecFileAsyncMock, - resolveWithSshGMock, - readLocalGitConfigSignatureMock -} = vi.hoisted(() => ({ - commandExecFileAsyncMock: vi.fn(), - gitExecFileAsyncMock: vi.fn(), - resolveWithSshGMock: vi.fn(), - readLocalGitConfigSignatureMock: vi.fn(async () => 'sig-10284') -})) - -vi.mock('../../git/command-runner/process-capture/command-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - commandExecFileAsync: commandExecFileAsyncMock -})) - -vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ - ...(await importOriginal()), - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('./local-git-config-signature', () => ({ - readLocalGitConfigSignature: readLocalGitConfigSignatureMock -})) - -vi.mock('../../ssh/config/ssh-g-config-resolution', () => ({ - resolveWithSshG: resolveWithSshGMock -})) - -import { - getOwnerRepoForRemote, - _resetOwnerRepoCache, - _getOwnerRepoCacheSize -} from './github-repository-identity' -import { - classifyGitHubOwnerRepoFromRemoteUrl, - resolveGitHubOwnerRepoFromRemoteUrl, - _resetSshHostnameResolutionCache -} from './github-ssh-host-alias-resolution' - -const REPO = '/tmp/ssh-alias-checkout' - -function sshConfig(hostname: string, port = 22) { - return { - hostname, - port, - identityFile: [], - identitiesOnly: false, - forwardAgent: false, - proxyUseFdpass: false, - controlMaster: 'no', - controlPersist: 'no' - } -} - -function mockRemoteUrl(url: string): void { - gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[0] === 'remote' && args[1] === 'get-url') { - return { stdout: `${url}\n` } - } - throw new Error(`unexpected git args: ${args.join(' ')}`) - }) -} - -beforeEach(() => { - _resetOwnerRepoCache() - _resetSshHostnameResolutionCache() - commandExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockReset() - resolveWithSshGMock.mockReset() - readLocalGitConfigSignatureMock.mockClear() -}) - -afterEach(() => { - vi.useRealTimers() -}) - -describe('#10284 SSH Host alias → github.com owner/repo', () => { - it('does not read an SSH repoPath locally when its provider is missing', async () => { - await expect( - getOwnerRepoForRemote( - '/remote/repo', - 'origin', - 'ssh-1', - {}, - { - requireVerifiedSshProbe: true - } - ) - ).rejects.toThrow('Remote connection dropped.') - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('isolates the same alias across native and WSL runtimes', async () => { - resolveWithSshGMock.mockResolvedValueOnce(sshConfig('github.com')) - commandExecFileAsyncMock.mockResolvedValueOnce({ - stdout: 'hostname gitlab.com\nport 22\n', - stderr: '' - }) - - await expect( - resolveGitHubOwnerRepoFromRemoteUrl('git@forge-work:team/orca.git') - ).resolves.toEqual({ owner: 'team', repo: 'orca' }) - await expect( - resolveGitHubOwnerRepoFromRemoteUrl('git@forge-work:team/orca.git', { - repoPath: REPO, - wslDistro: 'Ubuntu' - }) - ).resolves.toBeNull() - expect(resolveWithSshGMock).toHaveBeenCalledTimes(1) - expect(commandExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) - - it('does not pin an SSH-config-dependent miss to the Git config signature', async () => { - vi.useFakeTimers() - mockRemoteUrl('git@forge-work:team/orca.git') - resolveWithSshGMock - .mockResolvedValueOnce(sshConfig('gitlab.com')) - .mockResolvedValueOnce(sshConfig('github.com')) - - await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toBeNull() - await vi.advanceTimersByTimeAsync(60_001) - await expect(getOwnerRepoForRemote(REPO, 'origin')).resolves.toEqual({ - owner: 'team', - repo: 'orca' - }) - }) - - it('isolates case-sensitive OpenSSH Host aliases in the cache', async () => { - resolveWithSshGMock.mockImplementation(async (host: string) => - sshConfig(host === 'GitHub-Work' ? 'github.com' : 'gitlab.com') - ) - - await expect( - classifyGitHubOwnerRepoFromRemoteUrl('git@GitHub-Work:team/orca.git') - ).resolves.toEqual({ - kind: 'github', - ownerRepo: { owner: 'team', repo: 'orca' } - }) - await expect( - classifyGitHubOwnerRepoFromRemoteUrl('git@github-work:team/orca.git') - ).resolves.toEqual({ - kind: 'not-github', - cacheWithGitConfigSignature: false - }) - expect(resolveWithSshGMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts deleted file mode 100644 index df203247d25..00000000000 --- a/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - CRASH_FUSE_COOLDOWN_INITIAL_MS, - CRASH_FUSE_TRIAL_STABLE_MS, - WatcherProcessCrashFuse -} from './parcel-watcher-crash-fuse' - -function tripAt(fuse: WatcherProcessCrashFuse, start: number): void { - fuse.recordCrash(start) - fuse.recordCrash(start + 40_000) - fuse.recordCrash(start + 80_000) -} - -describe('WatcherProcessCrashFuse', () => { - beforeEach(() => { - vi.spyOn(console, 'error').mockImplementation(() => undefined) - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('resets escalation only after the trial child confirms delivery for the stable period', () => { - const fuse = new WatcherProcessCrashFuse() - tripAt(fuse, 0) - const trialAt = 80_000 + CRASH_FUSE_COOLDOWN_INITIAL_MS - expect(fuse.isOpen(trialAt)).toBe(false) - fuse.noteChildStarted() - const healthyAt = trialAt + 60_000 - fuse.recordDeliveryHealth('healthy', healthyAt) - - expect(fuse.isOpen(healthyAt + CRASH_FUSE_TRIAL_STABLE_MS)).toBe(false) - - tripAt(fuse, healthyAt + CRASH_FUSE_TRIAL_STABLE_MS + 1) - const reopenedAt = healthyAt + CRASH_FUSE_TRIAL_STABLE_MS + 1 + 80_000 - expect(fuse.isOpen(reopenedAt + CRASH_FUSE_COOLDOWN_INITIAL_MS - 1)).toBe(true) - expect(fuse.isOpen(reopenedAt + CRASH_FUSE_COOLDOWN_INITIAL_MS)).toBe(false) - }) - - it('keeps escalating when the trial child survives without ever confirming delivery', () => { - const fuse = new WatcherProcessCrashFuse() - tripAt(fuse, 0) - const trialAt = 80_000 + CRASH_FUSE_COOLDOWN_INITIAL_MS - expect(fuse.isOpen(trialAt)).toBe(false) - fuse.noteChildStarted() - - const crashAt = trialAt + 3 * CRASH_FUSE_TRIAL_STABLE_MS - expect(fuse.isOpen(crashAt)).toBe(false) - fuse.recordCrash(crashAt) - - expect(fuse.isOpen(crashAt + 2 * CRASH_FUSE_COOLDOWN_INITIAL_MS - 1)).toBe(true) - }) - - it('does not count a stalled stretch toward the stable period', () => { - const fuse = new WatcherProcessCrashFuse() - tripAt(fuse, 0) - const trialAt = 80_000 + CRASH_FUSE_COOLDOWN_INITIAL_MS - expect(fuse.isOpen(trialAt)).toBe(false) - fuse.recordDeliveryHealth('healthy', trialAt) - fuse.recordDeliveryHealth('stalled', trialAt + CRASH_FUSE_TRIAL_STABLE_MS - 1) - - const crashAt = trialAt + 2 * CRASH_FUSE_TRIAL_STABLE_MS - expect(fuse.isOpen(crashAt)).toBe(false) - fuse.recordCrash(crashAt) - - expect(fuse.isOpen(crashAt + 2 * CRASH_FUSE_COOLDOWN_INITIAL_MS - 1)).toBe(true) - }) - - it('neither starts nor clears the stable period on an unknown report', () => { - const fuse = new WatcherProcessCrashFuse() - tripAt(fuse, 0) - const trialAt = 80_000 + CRASH_FUSE_COOLDOWN_INITIAL_MS - expect(fuse.isOpen(trialAt)).toBe(false) - fuse.recordDeliveryHealth('unknown', trialAt) - const crashAt = trialAt + 2 * CRASH_FUSE_TRIAL_STABLE_MS - expect(fuse.isOpen(crashAt)).toBe(false) - fuse.recordCrash(crashAt) - expect(fuse.isOpen(crashAt + 2 * CRASH_FUSE_COOLDOWN_INITIAL_MS - 1)).toBe(true) - - const nextTrialAt = crashAt + 2 * CRASH_FUSE_COOLDOWN_INITIAL_MS - expect(fuse.isOpen(nextTrialAt)).toBe(false) - fuse.recordDeliveryHealth('healthy', nextTrialAt) - fuse.recordDeliveryHealth('unknown', nextTrialAt + CRASH_FUSE_TRIAL_STABLE_MS - 1) - const stableAt = nextTrialAt + CRASH_FUSE_TRIAL_STABLE_MS - expect(fuse.isOpen(stableAt)).toBe(false) - fuse.recordCrash(stableAt + 1) - expect(fuse.isOpen(stableAt + 1)).toBe(false) - }) -}) diff --git a/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.test.ts b/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.test.ts deleted file mode 100644 index 6888a083801..00000000000 --- a/src/main/ipc/runtime-environments/status/runtime-environment-contact-loss.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -// #34089: whether a paired server's host may be gone comes only from dials Orca already makes: -// its health probes and its control socket's reconnects. -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' -import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' - -const mocks = vi.hoisted(() => ({ - asleep: false, - send: vi.fn() -})) - -vi.mock('../../../runtime/construction/runtime-desktop-surface', () => ({ - getRuntimeDesktopSurface: () => ({}) -})) -vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ - sendRemoteRuntimeRequestOnSocket: mocks.send -})) -vi.mock( - '../../../../shared/remote-runtime/host-catalog/runtime-environments', - async (importOriginal) => ({ - ...(await importOriginal>()), - getPreferredPairedRuntimeConnection: () => ({ endpoint: 'ws://vm', credential: {} }) - }) -) -vi.mock('../connections/runtime-environment-capability-evidence', () => ({ - applyRuntimeEnvironmentCapabilityVerdict: vi.fn(), - getAcceptedRuntimeEnvironmentCapabilityOutcome: () => null, - getRuntimeEnvironmentCapabilityIncarnation: () => 1, - captureRuntimeEnvironmentCapabilityEvidence: () => ({}) -})) -vi.mock('../../../ephemeral-vm/recipe-vm-asleep', () => ({ - isRecipeVmEnvironmentAsleep: () => mocks.asleep -})) - -import { createRuntimeEnvironmentStatusOwner } from './runtime-environment-status-owner' -import { - clearRuntimeEnvironmentContactLoss, - isRuntimeEnvironmentContactLost, - noteRuntimeEnvironmentSharedControlContact, - RUNTIME_CONTACT_LOST_AFTER_MS -} from './runtime-environment-contact-loss' - -const ENV = 'env-vm' -const START = Date.parse('2026-11-08T12:00:00Z') - -function owner() { - const transport = { isReady: () => false, request: vi.fn(), establish: vi.fn(), pause: vi.fn() } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the fields the status owner reads. - const environment = { id: ENV, pairingRevision: 1, createdAt: 0 } as KnownRuntimeEnvironment - return createRuntimeEnvironmentStatusOwner('/data', environment, transport) -} - -/** Three probes spread over `spanMs`, starting at START. */ -async function probeOver(spanMs: number): Promise { - const status = owner() - for (const at of [0, spanMs / 2, spanMs]) { - vi.setSystemTime(START + at) - await status.refresh({ timeoutMs: 1_000, observeOnly: true }) - } -} - -const unreachable = (): never => { - throw new RemoteRuntimeClientError('remote_runtime_unavailable', 'connect ECONNREFUSED') -} - -describe('paired server contact loss', () => { - afterEach(() => { - vi.useRealTimers() - mocks.asleep = false - mocks.send.mockReset() - clearRuntimeEnvironmentContactLoss(ENV) - }) - - it('is lost only after minutes of failed health probes, and found again by an answer', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - mocks.send.mockImplementation(unreachable) - await probeOver(RUNTIME_CONTACT_LOST_AFTER_MS / 2) - expect(isRuntimeEnvironmentContactLost(ENV)).toBe(false) - - await probeOver(RUNTIME_CONTACT_LOST_AFTER_MS) - expect(isRuntimeEnvironmentContactLost(ENV)).toBe(true) - - mocks.send.mockResolvedValue({ id: 'status.get', ok: true, result: {}, _meta: {} }) - await owner().refresh({ timeoutMs: 1_000, observeOnly: true }) - expect(isRuntimeEnvironmentContactLost(ENV)).toBe(false) - }) - - it('counts nothing for a VM the user put to sleep, which is never dialed', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - mocks.asleep = true - await probeOver(RUNTIME_CONTACT_LOST_AFTER_MS * 2) - expect(isRuntimeEnvironmentContactLost(ENV)).toBe(false) - }) - - it('counts each control-socket reconnect once, but not a socket the user closed', () => { - const spread = [0, RUNTIME_CONTACT_LOST_AFTER_MS / 2, RUNTIME_CONTACT_LOST_AFTER_MS] - for (const at of spread) { - noteRuntimeEnvironmentSharedControlContact( - ENV, - { state: 'closed', reconnectAttempt: 0 }, - START + at - ) - } - expect(isRuntimeEnvironmentContactLost(ENV, START + RUNTIME_CONTACT_LOST_AFTER_MS)).toBe(false) - - // One reconnect attempt republished as its pending requests change is still one failure. - for (const at of spread) { - noteRuntimeEnvironmentSharedControlContact( - ENV, - { state: 'reconnecting', reconnectAttempt: 1 }, - START + at - ) - } - expect(isRuntimeEnvironmentContactLost(ENV, START + RUNTIME_CONTACT_LOST_AFTER_MS)).toBe(false) - - spread.forEach((at, index) => - noteRuntimeEnvironmentSharedControlContact( - ENV, - { state: 'reconnecting', reconnectAttempt: index + 2 }, - START + at - ) - ) - expect(isRuntimeEnvironmentContactLost(ENV, START + RUNTIME_CONTACT_LOST_AFTER_MS)).toBe(true) - - noteRuntimeEnvironmentSharedControlContact(ENV, { state: 'ready', reconnectAttempt: 0 }) - expect(isRuntimeEnvironmentContactLost(ENV, START + RUNTIME_CONTACT_LOST_AFTER_MS)).toBe(false) - }) - - it('starts over after a quiet spell longer than any retry, such as the computer sleeping', () => { - // A drop as the computer went to sleep, then quick failures while its network comes back. - noteRuntimeEnvironmentSharedControlContact( - ENV, - { state: 'reconnecting', reconnectAttempt: 1 }, - START - ) - const woke = START + 8 * 60 * 60_000 - for (const [index, at] of [0, 2_000, 4_000].entries()) { - noteRuntimeEnvironmentSharedControlContact( - ENV, - { state: 'reconnecting', reconnectAttempt: index + 2 }, - woke + at - ) - } - expect(isRuntimeEnvironmentContactLost(ENV, woke + 5_000)).toBe(false) - }) -}) diff --git a/src/main/managed-server/host-state/orcad-snapshot-room.test.ts b/src/main/managed-server/host-state/orcad-snapshot-room.test.ts deleted file mode 100644 index 15fa5bb8bd4..00000000000 --- a/src/main/managed-server/host-state/orcad-snapshot-room.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -import type * as RecordFile from '../install/orcad-remote-record-file' -import type * as InstallLock from '../install/remote-install-lock' -import type * as VersionedInstall from '../install/remote-versioned-install' - -vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand: vi.fn() -})) -vi.mock('../../../shared/shell/launch/shell-argument-quoting', () => ({ - quotePosixShell: (s: string) => `'${s}'` -})) -vi.mock('../install/remote-install-lock', async (importOriginal) => ({ - ...(await importOriginal()), - acquireInstallLock: vi.fn() -})) -vi.mock('../install/orcad-remote-record-file', async (importOriginal) => ({ - ...(await importOriginal()), - writeAtomicOrcadRemoteRecord: vi.fn() -})) -vi.mock('../install/remote-versioned-install', async (importOriginal) => ({ - ...(await importOriginal()), - readLocalFullVersion: () => '0.2.0+bb01' -})) -vi.mock('../install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() })) -vi.mock('../install/orcad-remote-preflight', () => ({ - preflightInstalledOrcad: vi.fn(async () => ({})) -})) -vi.mock('../install/orcad-local-build-hash', () => ({ - computeLocalOrcadBuildHash: () => 'abc123def4567890' -})) - -import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { acquireInstallLock } from '../install/remote-install-lock' -import { writeAtomicOrcadRemoteRecord } from '../install/orcad-remote-record-file' -import { deployOrcad } from '../install/orcad-remote-deploy' -import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' -import { ORCAD_SNAPSHOT_SPACE_INSUFFICIENT_CODE } from './orcad-snapshot-room' - -import { OrcadFenceLostError } from '../activation/orcad-activation-fence-scope' - -import { FakeOrcadHost, NEW, OLD } from '../activation/orcad-activation-host-test-harness' - -let host = FakeOrcadHost.deployedOld() - -function answerRoom(neededKb: number, reclaimKb: number, availableKb: number): void { - vi.mocked(execCommand).mockImplementation(async (_conn, command) => - command.includes('SNAPSHOT_SPACE') - ? `SNAPSHOT_SPACE ${neededKb} ${reclaimKb} /dev/sda1 100 1 ${availableKb} 1% /home\n` - : host.exec(command) - ) -} - -const IDLE = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 } -const deploy = (extra: Partial[0]> = {}) => - deployOrcad({ - conn: Object.create(null), - host: getRemoteHostPlatform('linux-x64'), - remoteHome: '/home/work', - nodePath: '/usr/bin/node', - userDataDir: '/home/work/.orca', - bindHost: '127.0.0.1', - port: 7777, - readinessTimeoutMs: 50, - sleep: async () => {}, - now: () => new Date('2026-02-02T00:00:00.000Z'), - localOrcadDir: '/local/out/orcad', - target: 'linux-x64-glibc217', - census: IDLE, - recountCensus: async () => extra.census ?? IDLE, - releaseIncumbentAdmission: async () => {}, - ...extra - }) - -beforeEach(() => { - vi.clearAllMocks() - host = FakeOrcadHost.deployedOld() - vi.mocked(acquireInstallLock).mockImplementation(async (_conn, dir, _host, options) => { - if (!host.acquireFence(options)) { - const { RemoteInstallLockBusyError } = await vi.importActual( - '../install/remote-install-lock' - ) - throw new RemoteInstallLockBusyError(dir, 0) - } - }) - vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => - host.write(path, contents) - ) -}) - -describe('an update on a host without room for its snapshot (#30491)', () => { - it('keeps the running server and says how much to free, stopping nothing', async () => { - answerRoom(400_000, 0, 1_000) - - const result = await deploy() - - expect(result).toMatchObject({ - outcome: 'installed-not-activated', - code: ORCAD_SNAPSHOT_SPACE_INSUFFICIENT_CODE - }) - expect(JSON.stringify(result)).toMatch( - /has 1000 KB free, and the snapshot needs about 390\.6 MB.*left the current server \(0\.1\.0\+aa01\) in place/u - ) - expect([...host.alive]).toEqual([OLD]) - expect(host.activeVersion()).toBe(OLD) - expect(host.commands.some((command) => command.includes('kill -TERM'))).toBe(false) - expect(host.journal).toBeNull() - expect(host.fence).toBe(false) - }) - - it('goes ahead when the room probe loses its channel, leaving the capture to decide', async () => { - vi.mocked(execCommand).mockImplementation(async (_conn, command) => { - if (command.includes('SNAPSHOT_SPACE')) { - throw Object.assign(new Error('lost'), { sshChannelCloseConfirmed: false }) - } - return host.exec(command) - }) - - expect(await deploy()).toMatchObject({ outcome: 'installed-and-activated' }) - expect(host.activeVersion()).toBe(NEW) - }) - - it('still stops on a lost fence from the room probe', async () => { - vi.mocked(execCommand).mockImplementation(async (_conn, command) => { - if (command.includes('SNAPSHOT_SPACE')) { - throw Object.assign(new Error('fence lost'), { - exitCode: 75, - stdout: '__ORCAD_FENCE_LOST__\n' - }) - } - return host.exec(command) - }) - - await expect(deploy()).rejects.toBeInstanceOf(OrcadFenceLostError) - expect([...host.alive]).toEqual([OLD]) - expect(host.commands.some((command) => command.includes('kill -TERM'))).toBe(false) - }) - - it('updates when pruning earlier snapshots makes the room', async () => { - answerRoom(400_000, 500_000, 1_000) - - expect(await deploy()).toMatchObject({ outcome: 'installed-and-activated' }) - expect(host.activeVersion()).toBe(NEW) - }) -}) diff --git a/src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts b/src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts deleted file mode 100644 index 00130da15f5..00000000000 --- a/src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - withDeactivatedVersion, - withDeactivatedVersionCommitted, - type OrcadActivationRecord -} from '../activation/orcad-activation-record' -import { planManagedOrcadAutoUpdate } from './orcad-managed-update-decision' - -describe('redeploying a host another desktop stopped, across Orca versions', () => { - const servedBy = (appVersion: string, active: string): OrcadActivationRecord => ({ - schemaVersion: 1, - active, - previous: null, - activatedAt: '2026-10-01T00:00:00.000Z', - activeAppVersion: appVersion, - snapshot: null - }) - const plan = (record: OrcadActivationRecord, appVersion: string, failedBefore = false) => - planManagedOrcadAutoUpdate({ - record, - candidateVersion: `${appVersion}+cand`, - appVersion, - failedBefore - }) - - it('never lets an older desktop downgrade a host a newer desktop stopped', () => { - const stopped = withDeactivatedVersionCommitted(servedBy('1.5.0', '1.5.0+new')) - expect(plan(stopped, '1.4.0')).toEqual({ action: 'skip', reason: 'host-newer' }) - expect(plan(stopped, '1.5.0')).toEqual({ action: 'update' }) - expect(plan(stopped, '1.6.0')).toEqual({ action: 'update' }) - }) - - it('redeploys a stop recorded without the app version', () => { - // What a stop committed by a build that predates keeping the app version leaves. - const legacy = withDeactivatedVersion(servedBy('1.5.0', '1.5.0+new')) - expect(plan(legacy, '1.6.0')).toEqual({ action: 'update' }) - expect(plan(legacy, '1.4.0')).toEqual({ action: 'update' }) - expect(plan(legacy, '1.4.0', true)).toEqual({ action: 'update' }) - }) - - it('retries the redeploy after an earlier failure, since nothing serves', () => { - const stopped = withDeactivatedVersionCommitted(servedBy('1.4.0', '1.4.0+old')) - expect(plan(stopped, '1.4.0', true)).toEqual({ action: 'update' }) - // A host that still serves keeps the once-per-version suppression. - expect(plan(servedBy('1.4.0', '1.4.0+old'), '1.5.0', true)).toEqual({ - action: 'skip', - reason: 'failed-before' - }) - }) - - it('never reactivates a build an explicit rollback left, after a stop', () => { - const rolledBack = { ...servedBy('1.5.0', '1.5.0+old'), rolledBackFrom: '1.5.0+cand' } - expect(plan(withDeactivatedVersionCommitted(rolledBack), '1.5.0')).toEqual({ - action: 'skip', - reason: 'rolled-back' - }) - }) -}) diff --git a/src/main/native-chat/agent-session-wire/publication/history/agent-session-fork-marker.test.ts b/src/main/native-chat/agent-session-wire/publication/history/agent-session-fork-marker.test.ts deleted file mode 100644 index da0a88e3d14..00000000000 --- a/src/main/native-chat/agent-session-wire/publication/history/agent-session-fork-marker.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { projectForkMarker, readForkMarker, FORK_MARKER_ITEM_ID } from './agent-session-fork-marker' -import { ForkMarkerSubscriptions } from '../subscribers/agent-session-fork-marker-delivery' -import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { Subscriber } from '../subscribers/agent-session-subscribe-input' -import type { AgentSessionJournal } from '../../../agent-session-journal/journal-store' - -type NamedRecord = Pick< - AgentSessionRecord, - 'sessionId' | 'provider' | 'conversationName' | 'conversationNameSource' | 'forkedFrom' -> - -function store(...records: NamedRecord[]) { - const byId = new Map(records.map((record) => [record.sessionId, record])) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the marker reads only these naming fields. - return { getRecord: (id: string) => (byId.get(id) as AgentSessionRecord | undefined) ?? null } -} - -const link = (sessionId: string, plainName?: true): NamedRecord['forkedFrom'] => ({ - sessionId, - itemId: 'response', - childBoundary: { kind: 'start' }, - ...(plainName ? { plainName } : {}) -}) - -describe('readForkMarker', () => { - it('names an older fork source by its shown name and says it is a fork', () => { - const marker = readForkMarker( - store( - { sessionId: 'root', provider: 'codex', conversationName: 'Annotate' }, - { - sessionId: 'parent', - provider: 'codex', - conversationName: 'Annotate fork', - forkedFrom: link('root') - }, - { sessionId: 'child', provider: 'codex', forkedFrom: link('parent', true) } - ), - 'child' - ) - expect(marker).toMatchObject({ - sourceName: 'Annotate', - sourceForked: true, - sourceMissing: false, - sourceParentId: 'root' - }) - }) - - it('reports a source this host has no record of', () => { - expect( - readForkMarker( - store({ sessionId: 'child', provider: 'codex', forkedFrom: link('gone', true) }), - 'child' - ) - ).toMatchObject({ sourceName: 'another chat', sourceForked: false, sourceMissing: true }) - }) -}) - -describe('projectForkMarker', () => { - it('re-projects when only the source fork state changes', () => { - const snapshot: AgentJournalSnapshot = { - sessionId: 'child', - cursor: { epoch: 'e', sequence: 0 }, - submissions: [], - items: [] - } - const forkedFrom = link('parent', true)! - const base = { forkedFrom, sourceName: 'Annotate', sourceMissing: false } - projectForkMarker(snapshot, { ...base, sourceForked: false }) - const row = projectForkMarker(snapshot, { ...base, sourceForked: true }).items.find( - (item) => item.itemId === FORK_MARKER_ITEM_ID - ) - expect(row?.body).toMatchObject({ forkedFrom: { sessionId: 'parent', sourceForked: true } }) - }) -}) - -describe('ForkMarkerSubscriptions', () => { - it("re-delivers a fork's divider when its source's own source is renamed", async () => { - const root: NamedRecord = { sessionId: 'root', provider: 'codex', conversationName: 'Annotate' } - const records = store( - root, - { - sessionId: 'parent', - provider: 'codex', - conversationName: 'Annotate fork', - forkedFrom: link('root') - }, - { sessionId: 'child', provider: 'codex', forkedFrom: link('parent', true) } - ) - const emitted: unknown[] = [] - const fields = { - sessionId: 'child', - boundedFrames: false, - cursor: { epoch: 'e', sequence: 0 }, - fence: 1, - readForkMarker: () => readForkMarker(records, 'child') - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: marker delivery reads only these subscriber fields. - const subscriber = fields as unknown as Subscriber - subscriber.forkMarkerView = JSON.stringify(subscriber.readForkMarker?.()) - const snapshot: AgentJournalSnapshot = { - sessionId: 'child', - cursor: { epoch: 'e', sequence: 0 }, - submissions: [], - items: [] - } - const journalFields = { - identity: { sessionId: 'child' }, - cursor: () => snapshot.cursor, - reads: { forkMarkerGroup: async () => snapshot } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: marker delivery reads only these journal members. - const journal = journalFields as unknown as AgentSessionJournal - const deliveries: Promise[] = [] - const port = { - isActive: () => true, - emit: async (_target: Subscriber, event: unknown) => { - emitted.push(event) - } - } - const markers: ForkMarkerSubscriptions = new ForkMarkerSubscriptions( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: delivery calls only isActive and emit. - () => port as never, - () => [subscriber], - () => 0, - () => journal, - (target, read) => deliveries.push(markers.refresh(target, read)) - ) - markers.add(subscriber) - - // The parent's older " fork" title no longer matches, so its shown name becomes its saved one. - root.conversationName = 'Annotate v2' - markers.refreshSources(() => journal, ['root']) - markers.refreshSources(() => journal, ['unrelated']) - await Promise.all(deliveries) - markers.delete(subscriber) - - expect(emitted).toHaveLength(1) - expect(emitted[0]).toMatchObject({ - type: 'batch', - batch: { - items: [ - { - itemId: FORK_MARKER_ITEM_ID, - body: { - text: 'Forked from Annotate fork', - forkedFrom: { sessionId: 'parent', sourceForked: true } - } - } - ] - } - }) - }) -}) diff --git a/src/main/notifications/macos-focus-state.test.ts b/src/main/notifications/macos-focus-state.test.ts deleted file mode 100644 index 15601293ab0..00000000000 --- a/src/main/notifications/macos-focus-state.test.ts +++ /dev/null @@ -1,47 +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 { isMacosFocusActive } from './macos-focus-state' - -describe('isMacosFocusActive', () => { - let dir: string - let assertionsPath: string - - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-focus-')) - assertionsPath = join(dir, 'Assertions.json') - }) - - afterEach(() => rmSync(dir, { recursive: true, force: true })) - - function writeAssertions(records: unknown[]): void { - writeFileSync( - assertionsPath, - JSON.stringify({ - data: [{ storeInvalidationRecords: [{}], storeAssertionRecords: records }] - }) - ) - } - - it('reports Focus active while an assertion is live', async () => { - writeAssertions([{ assertionUUID: 'a' }]) - await expect(isMacosFocusActive(assertionsPath, 'darwin')).resolves.toBe(true) - }) - - it('reports inactive once every assertion is invalidated', async () => { - writeAssertions([]) - await expect(isMacosFocusActive(assertionsPath, 'darwin')).resolves.toBe(false) - }) - - it('fails open when the store is missing or malformed', async () => { - await expect(isMacosFocusActive(assertionsPath, 'darwin')).resolves.toBe(false) - writeFileSync(assertionsPath, '{not json') - await expect(isMacosFocusActive(assertionsPath, 'darwin')).resolves.toBe(false) - }) - - it('never suppresses off macOS', async () => { - writeAssertions([{ assertionUUID: 'a' }]) - await expect(isMacosFocusActive(assertionsPath, 'linux')).resolves.toBe(false) - }) -}) diff --git a/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts deleted file mode 100644 index 3712e029db3..00000000000 --- a/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { ElectronSidecarTabRegistry } from './electron-sidecar-tab-registry' - -describe('ElectronSidecarTabRegistry', () => { - it('preserves requested ids and fences explicit worktree scope', () => { - const registry = new ElectronSidecarTabRegistry() - registry.register('sidecar-a', 'public-a', 'worktree-a') - registry.register('sidecar-b', 'public-b', 'worktree-b') - - expect(registry.require('public-a', 'worktree-a').sidecarPageId).toBe('sidecar-a') - expect(() => registry.require('public-a', 'worktree-b')).toThrow( - expect.objectContaining({ code: 'browser_tab_not_found' }) - ) - expect(registry.active('worktree-b').publicPageId).toBe('public-b') - }) - - it('rewrites sidecar ids, worktree-relative indices, and stale pages', () => { - const registry = new ElectronSidecarTabRegistry() - registry.register('sidecar-a', 'public-a', 'worktree-a') - registry.register('sidecar-b', 'public-b', 'worktree-b') - registry.register('sidecar-c', 'public-c', 'worktree-a') - - const tabs = registry.reconcileTabs( - [ - { browserPageId: 'sidecar-a', active: false }, - { browserPageId: 'sidecar-b', active: true }, - { browserPageId: 'sidecar-c', active: true } - ], - 'worktree-a' - ) - expect(tabs).toEqual([ - expect.objectContaining({ browserPageId: 'public-a', index: 0 }), - expect.objectContaining({ browserPageId: 'public-c', index: 1 }) - ]) - expect(registry.active('worktree-a').publicPageId).toBe('public-c') - - registry.reconcileTabs([{ browserPageId: 'sidecar-c' }]) - expect(() => registry.require('public-a')).toThrow( - expect.objectContaining({ code: 'browser_tab_not_found' }) - ) - }) - - it('keeps a listed popup with its opener: scoped, listed last, and handing back to it on close', () => { - const registry = new ElectronSidecarTabRegistry() - registry.register('sidecar-a', 'public-a', 'worktree-a') - registry.register('sidecar-b', 'public-b', 'worktree-a') - - const tabs = registry.reconcileTabs( - [ - { browserPageId: 'sidecar-a' }, - { browserPageId: 'sidecar-b', active: true }, - { browserPageId: 'popup-7', openerBrowserPageId: 'sidecar-b' } - ], - 'worktree-a' - ) - expect(tabs[2]).toEqual( - expect.objectContaining({ browserPageId: 'popup-7', openerBrowserPageId: 'public-b' }) - ) - expect(registry.require('popup-7', 'worktree-a').sidecarPageId).toBe('popup-7') - expect(registry.active('worktree-a').publicPageId).toBe('public-b') - - registry.register('sidecar-c', 'public-c', 'worktree-a') - expect(registry.pageAt('worktree-a', 2).publicPageId).toBe('public-c') - expect(registry.pageAt('worktree-a', 3).publicPageId).toBe('popup-7') - - const popup = registry.require('popup-7') - registry.setActive(popup) - registry.delete(popup) - expect(registry.active('worktree-a').publicPageId).toBe('public-b') - }) - - it('rewrites page ids in tab and command results', () => { - const registry = new ElectronSidecarTabRegistry() - registry.register('sidecar-a', 'public-a', 'worktree-a') - - expect( - registry.rewriteResult({ - browserPageId: 'sidecar-a', - tab: { - browserPageId: 'sidecar-a', - certificateFailure: { browserPageId: 'sidecar-a', challengeId: 'challenge-a' } - } - }) - ).toEqual({ - browserPageId: 'public-a', - tab: { - browserPageId: 'public-a', - certificateFailure: { browserPageId: 'public-a', challengeId: 'challenge-a' } - } - }) - }) -}) diff --git a/src/main/plugins/activation/plugin-enablement.test.ts b/src/main/plugins/activation/plugin-enablement.test.ts deleted file mode 100644 index 674a3b72c38..00000000000 --- a/src/main/plugins/activation/plugin-enablement.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { tmpdir } from 'node:os' -import { describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../shared/constants' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import { pluginManifestSchema } from '../../../shared/plugins/manifest/plugin-manifest' -import type { Store } from '../../persistence/loading-store/store' -import { applyPluginConsent, revokePluginConsent } from './plugin-enablement' -import type { ValidDiscoveredPlugin } from '../discovery/plugin-discovery' -import type { PluginService } from '../plugin-service' - -const pluginKey = 'samples.demo' -const manifest = pluginManifestSchema.parse({ - manifestVersion: 1, - id: 'demo', - publisher: 'samples', - name: 'Demo', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - contributes: {}, - capabilities: [] -}) - -function createStore(): { - store: Store - getSettings: () => GlobalSettings - updateSettings: ReturnType -} { - let settings = getDefaultSettings(tmpdir()) - const updateSettings = vi.fn((updates: Partial) => { - settings = { ...settings, ...updates } - }) - return { - store: { getSettings: () => settings, updateSettings } as unknown as Store, - getSettings: () => settings, - updateSettings - } -} - -function createPluginService( - getFingerprint: () => string, - overrides: Partial = {} -): PluginService { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the enablement paths read only these members. - return { - options: {}, - findValidPlugin: (requestedKey: string) => - requestedKey === pluginKey - ? { - pluginKey, - rootDir: tmpdir(), - manifest, - consentFingerprint: getFingerprint(), - consentContentHash: null, - contentHash: null, - isDev: true, - ...overrides - } - : null, - reconcileActivationState: vi.fn().mockResolvedValue(undefined) - } as unknown as PluginService -} - -describe('applyPluginConsent', () => { - it('stores approval only for the fingerprint the user reviewed', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-reviewed') - - await applyPluginConsent({ - store: harness.store, - pluginService, - pluginKey, - reviewedFingerprint: 'sha256-reviewed', - decision: 'approve' - }) - - expect(harness.getSettings().pluginConsents[pluginKey]).toBe('sha256-reviewed') - expect(harness.getSettings().disabledPlugins).not.toContain(pluginKey) - }) - - it('rejects a stale review after a same-key plugin update without writing settings', async () => { - const harness = createStore() - let currentFingerprint = 'sha256-reviewed-v1' - const pluginService = createPluginService(() => currentFingerprint) - currentFingerprint = 'sha256-current-v2' - - await expect( - applyPluginConsent({ - store: harness.store, - pluginService, - pluginKey, - reviewedFingerprint: 'sha256-reviewed-v1', - decision: 'approve' - }) - ).rejects.toThrow('changed since its permissions were reviewed') - - expect(harness.getSettings().pluginConsents[pluginKey]).toBeUndefined() - }) - - it('allows a stale dialog to keep the newer plugin disabled', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-current-v2') - - await applyPluginConsent({ - store: harness.store, - pluginService, - pluginKey, - reviewedFingerprint: 'sha256-reviewed-v1', - decision: 'keep-disabled' - }) - - expect(harness.getSettings().disabledPlugins).toContain(pluginKey) - }) -}) - -describe('revokePluginConsent', () => { - it('drops only this plugin’s approval, leaves it enabled, and stops it running', async () => { - const harness = createStore() - harness.store.updateSettings({ - pluginConsents: { [pluginKey]: 'sha256-old', 'samples.other': 'sha256-other' } - }) - const pluginService = createPluginService(() => 'sha256-old') - await revokePluginConsent({ store: harness.store, pluginService, pluginKey }) - expect(harness.getSettings().pluginConsents).toEqual({ 'samples.other': 'sha256-other' }) - expect(harness.getSettings().disabledPlugins).not.toContain(pluginKey) - }) -}) diff --git a/src/main/plugins/workers/host-api/plugin-host-methods.test.ts b/src/main/plugins/workers/host-api/plugin-host-methods.test.ts deleted file mode 100644 index dafaf64c6f6..00000000000 --- a/src/main/plugins/workers/host-api/plugin-host-methods.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { executePluginHostCall } from './plugin-host-methods' -import type { PluginHostServices } from './plugin-host-method-bindings' - -function createServices(storageSet: PluginHostServices['storage']['set']): PluginHostServices { - return { - resolveActiveWorktreeContext: vi.fn().mockResolvedValue(null), - listWorktreeTerminals: vi.fn().mockResolvedValue([]), - sendTerminalText: vi.fn().mockResolvedValue({ accepted: true }), - listAgentStatuses: () => [], - dispatchPluginNotification: vi.fn().mockResolvedValue({ delivered: true }), - storage: { - get: vi.fn(), - set: storageSet, - delete: vi.fn(), - keys: vi.fn().mockReturnValue([]) - }, - secrets: { - get: vi.fn().mockReturnValue({ ok: true, value: null }), - set: vi.fn().mockReturnValue({ ok: true }), - delete: vi.fn(), - protection: vi.fn().mockReturnValue('unavailable') - }, - settings: { - getAll: vi.fn().mockReturnValue({}), - set: vi.fn().mockReturnValue({ ok: true }) - } - } -} - -describe('executePluginHostCall mutation auditing', () => { - it('fails closed before a mutation when the audit intent cannot be recorded', async () => { - const storageSet = vi.fn().mockReturnValue({ ok: true }) - const outcome = await executePluginHostCall({ - pluginId: 'samples.demo', - method: 'storage.set', - params: { key: 'answer', value: 42 }, - surface: 'worker', - grantedCapabilities: ['storage:own'], - services: createServices(storageSet), - audit: { record: vi.fn().mockRejectedValue(new Error('disk full')) } - }) - - expect(outcome).toMatchObject({ ok: false, code: 'action_failed' }) - expect(storageSet).not.toHaveBeenCalled() - }) -}) - -describe('workspace.readContext host reachability', () => { - it('keeps the active remote context when its host cannot list terminals', async () => { - const services = createServices(vi.fn()) - vi.mocked(services.resolveActiveWorktreeContext).mockResolvedValue({ - worktreeId: 'remote-repo::/home/user/repo', - branch: '', - displayName: 'Remote main' - }) - vi.mocked(services.listWorktreeTerminals).mockRejectedValue(new Error('host_unreachable')) - - const outcome = await executePluginHostCall({ - pluginId: 'samples.demo', - method: 'workspace.readContext', - params: {}, - surface: 'panel', - grantedCapabilities: ['workspace:read'], - services - }) - - expect(outcome).toMatchObject({ - ok: true, - value: { branch: '', displayName: 'Remote main', terminals: [] } - }) - }) -}) - -describe('workspace.readContext workspace id', () => { - it('is the id workspace.list gives: identity form, folder key, else the raw id', async () => { - const contexts = [ - { worktreeId: 'repo::/w', identityKey: 'wt2:local:i1' }, - { worktreeId: 'folder:f1' }, - // A remote workspace known only from stored rows has no identity. - { worktreeId: 'remote-repo::/home/user/repo' } - ] - const outcomes = await Promise.all( - contexts.map((context) => { - const services = createServices(vi.fn()) - vi.mocked(services.resolveActiveWorktreeContext).mockResolvedValue({ - ...context, - branch: '', - displayName: 'w' - }) - return executePluginHostCall({ - pluginId: 'samples.demo', - method: 'workspace.readContext', - params: {}, - surface: 'worker', - grantedCapabilities: ['workspace:read'], - services - }) - }) - ) - expect(outcomes).toMatchObject([ - { ok: true, value: { workspaceId: 'identity:wt2:local:i1' } }, - { ok: true, value: { workspaceId: 'folder:f1' } }, - { ok: true, value: { workspaceId: 'remote-repo::/home/user/repo' } } - ]) - }) -}) - -describe('workspace.readContext in frames', () => { - it('gives panels only path-free ids', async () => { - const read = (worktreeId: string) => { - const services = createServices(vi.fn()) - vi.mocked(services.resolveActiveWorktreeContext).mockResolvedValue({ - worktreeId, - branch: '', - displayName: 'w' - }) - return executePluginHostCall({ - pluginId: 'samples.demo', - method: 'workspace.readContext', - params: {}, - surface: 'panel', - grantedCapabilities: ['workspace:read'], - services - }) - } - const [raw, folder] = await Promise.all([read('repo::/home/me/w'), read('folder:f1')]) - expect(raw.ok && raw.value).not.toHaveProperty('workspaceId') - expect(folder).toMatchObject({ ok: true, value: { workspaceId: 'folder:f1' } }) - }) -}) diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-pr-cadence.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-pr-cadence.test.ts deleted file mode 100644 index 5403ce92e10..00000000000 --- a/src/main/runtime/integrations/reviews/runtime-hosted-pr-cadence.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { PRAutoRefreshCadence } from '../../../../shared/review-refresh-policy' -import { fixture, found, mocks, read } from './runtime-hosted-pr-snapshot-test-harness' - -// The harness resets modules per test; change the cadence on that same instance, as the host's -// settings sync does. -async function setHostCadence(cadence: PRAutoRefreshCadence): Promise { - const policy = await import('../../../../shared/review-refresh-policy') - const coordinator = await import('../../../github/pull-requests/refresh/pr-refresh-coordinator') - policy.setPRAutoRefreshCadence(cadence) - coordinator.retimePRRefreshesForCadence() -} - -describe('hosted PR snapshots under the host’s auto-refresh cadence', () => { - it('stretches a confirmed quiet result by the cadence, and keeps it while off', async () => { - await setHostCadence('reduced') - await read('quiet', 'active') - await vi.advanceTimersByTimeAsync(5 * 60_000) - const confirmation = read('quiet') - await vi.advanceTimersByTimeAsync(0) - expect(await confirmation).toMatchObject({ fetchedAt: 301_000 }) - fixture.title = 'moved' - // Quiet is five minutes on Default; Reduced keeps it for twenty-five. - await vi.advanceTimersByTimeAsync(24 * 60_000) - expect(await read('quiet')).toMatchObject({ pr: { title: 'before' }, fetchedAt: 301_000 }) - await vi.advanceTimersByTimeAsync(60_000) - const due = read('quiet') - await vi.advanceTimersByTimeAsync(0) - expect(await due).toMatchObject({ pr: { title: 'moved' } }) - - await setHostCadence('off') - const calls = mocks.resolve.mock.calls.length - await vi.advanceTimersByTimeAsync(24 * 60 * 60_000) - expect(await read('quiet')).toMatchObject({ pr: { title: 'moved' } }) - expect(mocks.resolve).toHaveBeenCalledTimes(calls) - fixture.title = 'looked again' - expect(await read('quiet', 'active')).toMatchObject({ pr: { title: 'looked again' } }) - }) - - it('takes a failure’s retry off the timer while off and restores it from the failure time', async () => { - await read('failing', 'active') - await vi.advanceTimersByTimeAsync(60_000) - mocks.resolve.mockImplementation(async () => ({ - kind: 'upstream-error', - errorType: 'network', - message: 'offline', - // ast-grep-ignore: test-no-wall-clock -- the shared snapshot harness installs fake timers - fetchedAt: Date.now() - })) - const failing = read('failing') - await vi.advanceTimersByTimeAsync(0) - // Failed at 61 s: the retry waits for the two-minute background interval. - expect(await failing).toMatchObject({ kind: 'upstream-error', nextAutoRetryAt: 181_000 }) - - await setHostCadence('off') - const off = await read('failing') - expect(off).toMatchObject({ kind: 'upstream-error' }) - expect(off).not.toHaveProperty('nextAutoRetryAt') - await vi.advanceTimersByTimeAsync(10_000) - await setHostCadence('default') - expect(await read('failing')).toMatchObject({ nextAutoRetryAt: 181_000 }) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - - mocks.resolve.mockImplementation(async () => found()) - fixture.title = 'recovered' - // ast-grep-ignore: test-no-wall-clock -- the shared snapshot harness installs fake timers - await vi.advanceTimersByTimeAsync(181_000 - Date.now()) - const recovered = read('failing') - await vi.advanceTimersByTimeAsync(0) - expect(await recovered).toMatchObject({ kind: 'found', pr: { title: 'recovered' } }) - }) - - it('retires a queued revalidation when the host turns auto-refresh off', async () => { - await read('queued', 'active') - await vi.advanceTimersByTimeAsync(60_000) - // ast-grep-ignore: test-no-wall-clock -- the shared snapshot harness installs fake timers - mocks.gate.mockResolvedValue(Date.now() + 120_000) - const waiting = read('queued') - await vi.advanceTimersByTimeAsync(25_000) - expect(await waiting).toMatchObject({ fetchedAt: 1_000, revalidation: expect.any(Object) }) - - await setHostCadence('off') - mocks.gate.mockResolvedValue(null) - await vi.advanceTimersByTimeAsync(60 * 60_000) - expect(mocks.resolve).toHaveBeenCalledTimes(1) - - await setHostCadence('default') - fixture.title = 'read again' - const due = read('queued') - await vi.advanceTimersByTimeAsync(0) - expect(await due).toMatchObject({ pr: { title: 'read again' } }) - }) - - // A revalidation is held at its quota check when auto-refresh turns off; Default returns and a new - // timer read of the same PR replaces it before that check answers. - async function retireWhileAwaitingQuota(pauseMs: number | null) { - await read('held', 'active') - await vi.advanceTimersByTimeAsync(60_000) - const quota = Promise.withResolvers() - mocks.gate.mockReturnValue(quota.promise) - const waiting = read('held') - await vi.advanceTimersByTimeAsync(0) - await setHostCadence('off') - const retired = await waiting - await setHostCadence('default') - mocks.gate.mockResolvedValue(null) - fixture.title = 'read again' - const replacement = read('held') - await vi.advanceTimersByTimeAsync(0) - // ast-grep-ignore: test-no-wall-clock -- the shared snapshot harness installs fake timers - quota.resolve(pauseMs === null ? null : Date.now() + pauseMs) - return { retired, replacement } - } - - it('lets the retired revalidation neither start nor take the replacement’s place once quota admits it', async () => { - const { retired, replacement } = await retireWhileAwaitingQuota(null) - expect(retired).toMatchObject({ kind: 'found', fetchedAt: 1_000 }) - // The retired read had already taken the key's ordinary 10 s start cooldown before quota. - await vi.advanceTimersByTimeAsync(10_000) - expect(await replacement).toMatchObject({ pr: { title: 'read again' } }) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - }) - - it('keeps the quota pause the retired revalidation learned for the replacement, which then reads once', async () => { - const { retired, replacement } = await retireWhileAwaitingQuota(120_000) - expect(retired).toMatchObject({ kind: 'found', fetchedAt: 1_000 }) - await vi.advanceTimersByTimeAsync(25_000) - expect(await replacement).toMatchObject({ fetchedAt: 1_000, revalidation: expect.any(Object) }) - expect(mocks.resolve).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(120_000) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - expect(await read('held')).toMatchObject({ pr: { title: 'read again' } }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts deleted file mode 100644 index c29dd067b06..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/stop/worker-stop-exit-race.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - OPERATOR_CLOSE_EXIT_CAUSE, - type TerminalExitCause -} from '../../../../../../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' - -const h = createOrchestrationWorkerReleaseHarness() -beforeEach(() => h.setup()) -afterEach(() => h.cleanup()) - -type StopReceipt = { state: string; alreadySettled: boolean; processAction: string } - -function fireExit(handle: string, cause: TerminalExitCause = OPERATOR_CLOSE_EXIT_CAUSE): void { - ;( - h.runtime as unknown as { - failActiveDispatchOnExit: ( - handle: string, - paneKey: string | null, - cause: TerminalExitCause - ) => void - } - ).failActiveDispatchOnExit(handle, h.workerPaneKey, cause) -} - -describe('a worker whose process exits while its own stop is in flight', () => { - it('reports the stop that succeeded, not a failed dispatch', async () => { - const { dispatchId } = await h.startWorker() - // The PTY exit lands between beginWorkerStop and settleWorkerStop. - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - fireExit(handle) - return { handle, tabId: 'tab-worker', ptyKilled: true } as never - }) - - const receipt = (await h.call('orchestration.workerStop', { - dispatch: dispatchId - })) as StopReceipt - expect(receipt).toMatchObject({ state: 'stopped', processAction: 'closed_agent_terminal' }) - expect(h.db.getWorkerDispatch(dispatchId)?.state).toBe('stopped') - - const second = (await h.call('orchestration.workerStop', { - dispatch: dispatchId - })) as StopReceipt - expect(second).toMatchObject({ state: 'stopped', alreadySettled: true }) - }) - - it('still reports the stop when the exit races a close that then throws', async () => { - const { dispatchId } = await h.startWorker() - vi.mocked(h.runtime.closeTerminal).mockImplementation(async (handle) => { - fireExit(handle) - throw new Error('Terminal handle is stale') - }) - - const receipt = (await h.call('orchestration.workerStop', { - dispatch: dispatchId - })) as StopReceipt - expect(receipt.state).toBe('stopped') - }) - - it('accepts an exit observed while inspecting the process before close', async () => { - const { dispatchId } = await h.startWorker() - vi.mocked(h.runtime.showTerminal).mockImplementation(async (handle) => { - fireExit(handle) - return { handle, connected: false } as never - }) - vi.spyOn(h.runtime, 'getTerminalLivenessVerdict').mockReturnValue({ status: 'exited' }) - - await expect( - h.call('orchestration.workerStop', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'stopped', processAction: 'none' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - }) - - it('certifies a later death instead of crediting a stopping row from a dead runtime', async () => { - const { dispatchId } = await h.startWorker() - // The stop RPC committed `stopping` in an earlier runtime and the app died before settling. - h.db.beginWorkerStop(dispatchId, 'runtime_from_a_previous_process') - expect(h.db.getWorkerDispatch(dispatchId)?.state).toBe('stopping') - - fireExit('term_worker', { kind: 'signaled', signal: 9 }) - - expect(h.db.getDispatchContextById(dispatchId)?.termination_reason).toBe('signaled') - expect(h.db.getWorkerDispatch(dispatchId)?.state).toBe('failed') - }) - - it('gives a second concurrent stop the first caller receipt, not dispatch_inactive', async () => { - const { dispatchId } = await h.startWorker() - - const [first, second] = await Promise.all([ - h.call('orchestration.workerStop', { dispatch: dispatchId }) as Promise, - h.call('orchestration.workerStop', { dispatch: dispatchId }) as Promise - ]) - - expect(first).toMatchObject({ state: 'stopped' }) - expect(second).toEqual(first) - expect(h.db.getWorkerDispatch(dispatchId)?.state).toBe('stopped') - }) -}) diff --git a/src/main/runtime/rpc/startup/dispatcher-feature-readiness.test.ts b/src/main/runtime/rpc/startup/dispatcher-feature-readiness.test.ts deleted file mode 100644 index ecfdc06ba24..00000000000 --- a/src/main/runtime/rpc/startup/dispatcher-feature-readiness.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { z } from 'zod' -import { RpcDispatcher } from '../dispatcher' -import { defineMethod, defineStreamingMethod, type RpcRequest } from '../core' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { ensureAgentSessionFeatureRequirement } from './agent-launch-feature-requirement' -import { - _resetOrcadFeatureReadinessForTests, - installOrcadFeatureReadiness, - ORCAD_FEATURE_WAIT_MS -} from './orcad-readiness' - -const request = (method: string, params: unknown = {}): RpcRequest => ({ - id: 'r1', - authToken: 't', - method, - params -}) - -function dispatcher(): { dispatcher: RpcDispatcher; ran: string[] } { - const ran: string[] = [] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dispatcher reads only these runtime members for plain methods. - const runtime = { - getRuntimeId: () => 'rt', - recordFeatureInteraction: vi.fn() - } as unknown as OrcaRuntimeService - const methods = [ - defineMethod({ - name: 'aiVault.searchStatus', - requires: ['sessionSearch'], - permission: 'workspace', - params: z.object({}), - handler: () => { - ran.push('searchStatus') - return { ready: true } - } - }), - defineMethod({ - name: 'status.get', - permission: 'workspace', - params: z.object({}), - handler: () => { - ran.push('status') - return {} - } - }), - defineMethod({ - name: 'terminal.create', - requires: (params) => (params.command === 'claude' ? ['accounts'] : []), - permission: 'workspace', - params: z.object({ command: z.string().optional() }), - handler: (params) => { - ran.push(`create ${params.command ?? 'shell'}`) - return {} - } - }), - defineMethod({ - name: 'terminal.ensureAgentSession', - requires: ensureAgentSessionFeatureRequirement, - permission: 'workspace', - params: z.object({ kind: z.enum(['automatic', 'explicit']) }), - handler: (params) => { - ran.push(`ensure ${params.kind}`) - return {} - } - }), - defineStreamingMethod({ - name: 'accounts.subscribe', - requires: ['accounts'], - permission: 'workspace', - params: z.object({}), - handler: async (_params, _ctx, emit) => { - ran.push('subscribe') - emit({ type: 'ready' }) - } - }) - ] - return { dispatcher: new RpcDispatcher({ runtime, methods }), ran } -} - -afterEach(() => { - _resetOrcadFeatureReadinessForTests() - vi.useRealTimers() -}) - -describe('RPC methods that require an orcad startup phase', () => { - it('wait for their phase, while methods that need none run at once', async () => { - const readiness = installOrcadFeatureReadiness() - const { dispatcher: rpc, ran } = dispatcher() - const search = rpc.dispatch(request('aiVault.searchStatus')) - await expect(rpc.dispatch(request('status.get'))).resolves.toMatchObject({ ok: true }) - expect(ran).toEqual(['status']) - - readiness.open('sessionSearch') - await expect(search).resolves.toMatchObject({ ok: true, result: { ready: true } }) - expect(ran).toEqual(['status', 'searchStatus']) - }) - - it('refuse retryably with runtime_unavailable once the bounded wait runs out', async () => { - vi.useFakeTimers() - installOrcadFeatureReadiness() - const { dispatcher: rpc, ran } = dispatcher() - const search = rpc.dispatch(request('aiVault.searchStatus')) - await vi.advanceTimersByTimeAsync(ORCAD_FEATURE_WAIT_MS) - await expect(search).resolves.toMatchObject({ - ok: false, - error: { code: 'runtime_unavailable' } - }) - expect(ran).toEqual([]) - }) - - it('gate streaming methods the same way', async () => { - const readiness = installOrcadFeatureReadiness() - const { dispatcher: rpc, ran } = dispatcher() - const replies: string[] = [] - const stream = rpc.dispatchStreaming(request('accounts.subscribe'), (reply) => - replies.push(reply) - ) - await Promise.resolve() - expect(ran).toEqual([]) - readiness.open('accounts') - await stream - expect(ran).toEqual(['subscribe']) - expect(replies).toHaveLength(1) - }) - - // A handler run for a caller that left leaks its close cleanup, or runs a retried mutation twice. - it('refuse a unary call whose request is aborted while it waits, never running it', async () => { - vi.useFakeTimers() - const readiness = installOrcadFeatureReadiness() - const { dispatcher: rpc, ran } = dispatcher() - const aborted = new AbortController() - let reply: unknown = 'pending' - void rpc.dispatch(request('aiVault.searchStatus'), { signal: aborted.signal }).then((r) => { - reply = r - }) - await vi.advanceTimersByTimeAsync(1) - aborted.abort() - await vi.advanceTimersByTimeAsync(1) - expect(reply).toMatchObject({ ok: false, error: { code: 'runtime_unavailable' } }) - readiness.open('sessionSearch') - await vi.advanceTimersByTimeAsync(1) - expect(ran).toEqual([]) - }) - - it('refuse a stream whose connection closes while it waits, never running its handler', async () => { - vi.useFakeTimers() - const readiness = installOrcadFeatureReadiness() - const { dispatcher: rpc, ran } = dispatcher() - const closed = new AbortController() - const replies: string[] = [] - void rpc.dispatchStreaming(request('accounts.subscribe'), (reply) => replies.push(reply), { - connectionSignal: closed.signal - }) - await vi.advanceTimersByTimeAsync(1) - closed.abort() - await vi.advanceTimersByTimeAsync(1) - expect(replies.map((reply) => JSON.parse(reply))).toMatchObject([ - { ok: false, error: { code: 'runtime_unavailable' } } - ]) - readiness.open('accounts') - await vi.advanceTimersByTimeAsync(1) - expect(ran).toEqual([]) - }) -}) diff --git a/src/main/ssh/targets/ssh-target-orcad-claims.test.ts b/src/main/ssh/targets/ssh-target-orcad-claims.test.ts deleted file mode 100644 index 6eab4968a03..00000000000 --- a/src/main/ssh/targets/ssh-target-orcad-claims.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import type { SshRemotePtyLease, SshTarget } from '../../../shared/ssh-types' -import { SshTargetOrcadClaims } from './ssh-target-orcad-claims' -import { emptyDependentStateStore } from './testing/ssh-target-orcad-dependents-fixture' - -type SetupOptions = { - target?: Partial - repos?: { id: string; path: string; displayName: string }[] - folders?: { id: string; name: string; folderPath: string }[] - leases?: Partial[] -} - -function setup(options: SetupOptions = {}) { - let target: SshTarget = { - id: 'ssh-1', - label: 'Builder', - host: 'builder', - port: 22, - username: 'dev', - ...options.target - } - const flush = vi.fn(async () => {}) - const rows = { connectionId: 'ssh-1' } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preflight reads only id, name, folderPath and connectionId. - const folders = (options.folders ?? []).map((f) => ({ ...f, ...rows })) as never - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preflight reads only id, path, displayName, kind and connectionId. - const repos = (options.repos ?? []).map((r) => ({ ...r, ...rows })) as never - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preflight reads only ptyId and state. - const leases = (options.leases ?? []) as never - const claims = new SshTargetOrcadClaims({ - ...emptyDependentStateStore(), - allocateSshTargetGeneration: () => 4, - flushPendingOrThrowAsync: flush, - getFolderWorkspaces: () => folders, - getRepos: () => repos, - getSshRemotePtyLeases: () => leases, - getSshTarget: (id) => (id === target.id ? target : undefined), - getSshTargets: () => [target], - updateSshTarget: (_id, updates) => (target = { ...target, ...updates }) - }) - return { claims, flush, current: () => target } -} - -describe('managed orcad SSH target claims', () => { - it('is idempotent for its own environment and keeps an earlier provisioning request', () => { - const { claims } = setup({ - target: { - generation: 2, - orcadFence: { environmentId: 'environment-1' }, - orcadProvisioning: { requestId: 'request-1', name: 'From dialog' } - } - }) - const claimed = claims.claim('ssh-1', 'environment-1', { - deployName: 'Other name', - ownerRecorded: true - }) - expect(claimed.generation).toBe(2) - expect(claimed.orcadProvisioning).toEqual({ requestId: 'request-1', name: 'From dialog' }) - }) - - it('will not reuse its own owner without the durable record that explains it', () => { - const { claims, current } = setup({ - target: { generation: 2, orcadFence: { environmentId: 'environment-1' } } - }) - expect(() => - claims.claim('ssh-1', 'environment-1', { deployName: 'Managed', ownerRecorded: false }) - ).toThrow('no record explains why') - expect(current().orcadProvisioning).toBeUndefined() - }) - - it.each<[string, SetupOptions, string]>([ - ['another owner', { target: { orcadFence: { environmentId: 'other' } } }, 'already owned'], - [ - 'direct SSH repositories', - { repos: [{ id: 'repo-1', path: '/srv/app', displayName: 'app' }] }, - 'repositories or folder workspaces' - ], - [ - 'folder workspaces', - { folders: [{ id: 'folder-1', name: 'scratch', folderPath: '/srv/scratch' }] }, - 'repositories or folder workspaces' - ], - [ - 'a saved terminal lease', - { leases: [{ ptyId: 'pty-1', state: 'detached' }] }, - 'terminal-lease ×1 (pty-1 (detached))' - ], - [ - 'saved port forwards', - { - target: { - portForwards: [{ localPort: 1, remoteHost: 'localhost', remotePort: 2 }] - } - }, - 'port forwards' - ] - ])('refuses a target with %s and leaves it unclaimed', (_label, options, message) => { - const { claims, current } = setup(options) - expect(claims.preflight('ssh-1').claimable).toBe(false) - expect(() => - claims.claim('ssh-1', 'environment-1', { deployName: 'Managed', ownerRecorded: false }) - ).toThrow(message) - expect(current().orcadProvisioning).toBeUndefined() - }) - - it('lifts a Stop and remove hold once the user sets a server up again', () => { - const { claims, current } = setup() - claims.claim('ssh-1', 'environment-1', { deployName: 'Managed', ownerRecorded: false }) - claims.releaseForUserRemoval('ssh-1', 'environment-1') - expect(current().managedServerRemoved).toBeDefined() - - claims.claim('ssh-1', 'environment-2', { deployName: 'Managed', ownerRecorded: false }) - expect(current().managedServerRemoved).toBeUndefined() - // A later release that is not a user removal must not bring the overridden hold back. - claims.release('ssh-1', 'environment-2') - expect(current().managedServerRemoved).toBeUndefined() - }) - - it('releases only its own claim and clears the provisioning intent', () => { - const { claims, current } = setup() - claims.claim('ssh-1', 'environment-1', { deployName: 'Managed', ownerRecorded: false }) - expect(claims.release('ssh-1', 'environment-2')).toBeNull() - expect(claims.release('ssh-1', 'environment-1')).toMatchObject({ - orcadFence: undefined, - orcadProvisioning: undefined - }) - expect(current().orcadFence).toBeUndefined() - }) -}) diff --git a/src/main/startup/gpu-recovery/gpu-fallback-marker.test.ts b/src/main/startup/gpu-recovery/gpu-fallback-marker.test.ts deleted file mode 100644 index b5ac4b394df..00000000000 --- a/src/main/startup/gpu-recovery/gpu-fallback-marker.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - GPU_FALLBACK_MARKER_FILE, - readActiveGpuFallbackMarker, - readGpuFallbackMarker, - writeGpuFallbackMarker -} from './gpu-fallback-marker' - -describe('gpu-fallback-marker', () => { - let userDataPath: string - const environment = { - appVersion: '1.2.3', - electronVersion: '42.3.3', - platform: 'win32' as const - } - - beforeEach(() => { - userDataPath = mkdtempSync(join(os.tmpdir(), 'orca-gpu-fallback-test-')) - }) - - afterEach(() => { - rmSync(userDataPath, { recursive: true, force: true }) - }) - - it('persists explicit safe-graphics consent across launches', () => { - writeGpuFallbackMarker( - userDataPath, - { engagedAt: 123, crashesInWindow: 3, userConfirmed: true }, - environment - ) - expect(readActiveGpuFallbackMarker(userDataPath, environment)?.userConfirmed).toBe(true) - }) - - it('keeps an active marker for repeated launches on the same build', () => { - writeGpuFallbackMarker( - userDataPath, - { engagedAt: 1, crashesInWindow: 4, userConfirmed: false }, - environment - ) - expect(existsSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE))).toBe(true) - - const firstRead = readActiveGpuFallbackMarker(userDataPath, environment) - expect(firstRead?.crashesInWindow).toBe(4) - expect(existsSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE))).toBe(true) - - const secondRead = readActiveGpuFallbackMarker(userDataPath, environment) - expect(secondRead?.crashesInWindow).toBe(4) - }) - - it('clears an active marker when the app build changes', () => { - writeGpuFallbackMarker( - userDataPath, - { engagedAt: 1, crashesInWindow: 4, userConfirmed: false }, - environment - ) - - expect( - readActiveGpuFallbackMarker(userDataPath, { - ...environment, - appVersion: '1.2.4' - }) - ).toBeNull() - expect(existsSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE))).toBe(false) - }) - - // A macOS fallback marker would skip the Graphite fix inside GPU-feature setup; ensure fallback stays win32-only. - it('clears an active marker on macOS so the Graphite fix is never skipped', () => { - writeGpuFallbackMarker( - userDataPath, - { engagedAt: 1, crashesInWindow: 4, userConfirmed: false }, - environment - ) - - expect( - readActiveGpuFallbackMarker(userDataPath, { - ...environment, - platform: 'darwin' - }) - ).toBeNull() - expect(existsSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE))).toBe(false) - }) - - it('clears a corrupt or wrong-version marker', () => { - writeFileSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE), '{ not json') - expect(readGpuFallbackMarker(userDataPath)).toBeNull() - expect(readActiveGpuFallbackMarker(userDataPath, environment)).toBeNull() - expect(existsSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE))).toBe(false) - - writeFileSync( - join(userDataPath, GPU_FALLBACK_MARKER_FILE), - JSON.stringify({ schemeVersion: 999, engagedAt: 1, crashesInWindow: 1 }) - ) - expect(readGpuFallbackMarker(userDataPath)).toBeNull() - expect(readActiveGpuFallbackMarker(userDataPath, environment)).toBeNull() - expect(existsSync(join(userDataPath, GPU_FALLBACK_MARKER_FILE))).toBe(false) - }) -}) diff --git a/src/main/startup/windows-startup/windows-app-data-path.test.ts b/src/main/startup/windows-startup/windows-app-data-path.test.ts deleted file mode 100644 index 97b86b2ec73..00000000000 --- a/src/main/startup/windows-startup/windows-app-data-path.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { existsSync, mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, win32 } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' -import { - deriveWindowsAppDataPath, - ensureWindowsAppDataPath, - type WindowsAppDataPathHost -} from './windows-app-data-path' - -const ERROR_MESSAGE = /could not find the Windows roaming AppData folder/ - -function createHost( - nativeAppData: string | Error, - switches: string[] = [] -): WindowsAppDataPathHost & { - calls: string[] - paths: Map -} { - const calls: string[] = [] - const paths = new Map() - return { - calls, - paths, - getName: () => 'orca', - commandLine: { hasSwitch: (name) => switches.includes(name) }, - getPath: (name) => { - calls.push(`get:${name}`) - const overridden = paths.get(name) - if (overridden) { - return overridden - } - if (nativeAppData instanceof Error) { - throw nativeAppData - } - return nativeAppData - }, - setPath: (name, value) => { - calls.push(`set:${name}`) - paths.set(name, value) - } - } -} - -const tempDirs: string[] = [] -afterEach(() => { - for (const dir of tempDirs.splice(0)) { - removeTreeSync(dir) - } -}) - -describe('deriveWindowsAppDataPath', () => { - it('prefers APPDATA', () => { - expect( - deriveWindowsAppDataPath({ - APPDATA: 'D:\\Profiles\\me\\Roaming', - USERPROFILE: 'C:\\Users\\me' - }) - ).toBe('D:\\Profiles\\me\\Roaming') - }) - - it('falls back to USERPROFILE\\AppData\\Roaming when APPDATA is unset or relative', () => { - expect(deriveWindowsAppDataPath({ USERPROFILE: 'C:\\Users\\me' })).toBe( - 'C:\\Users\\me\\AppData\\Roaming' - ) - expect(deriveWindowsAppDataPath({ APPDATA: 'Roaming', USERPROFILE: 'C:\\Users\\me' })).toBe( - 'C:\\Users\\me\\AppData\\Roaming' - ) - }) -}) - -describe('ensureWindowsAppDataPath', () => { - it('keeps the native appData and pins userData to the path Electron would derive', () => { - const host = createHost('C:\\Users\\me\\AppData\\Roaming') - ensureWindowsAppDataPath(host, { APPDATA: 'D:\\ignored' }, 'win32') - expect(host.calls).toEqual(['get:appData', 'set:userData']) - expect(host.paths.get('userData')).toBe('C:\\Users\\me\\AppData\\Roaming\\orca') - }) - - it('creates and sets appData from the environment before userData when the lookup throws', () => { - // Use real missing directories to prove profileless sessions get their fallback created. - const root = mkdtempSync(join(tmpdir(), 'orca-appdata-')) - tempDirs.push(root) - const missingAppData = join(root, 'missing', 'Roaming') - const host = createHost(new Error('Failed to get appData path')) - - ensureWindowsAppDataPath(host, { APPDATA: missingAppData }, 'win32') - - expect(host.calls).toEqual(['get:appData', 'set:appData', 'set:userData']) - expect(host.paths.get('appData')).toBe(missingAppData) - expect(host.paths.get('userData')).toBe(win32.join(missingAppData, 'orca')) - expect(existsSync(missingAppData)).toBe(true) - }) - - it('fails with a readable error, setting nothing, when both variables are missing', () => { - const host = createHost(new Error('Failed to get appData path')) - expect(() => ensureWindowsAppDataPath(host, {}, 'win32')).toThrow(ERROR_MESSAGE) - expect(host.paths.size).toBe(0) - }) -}) diff --git a/src/main/text-generation/requests/jira-issue-summary-requests.test.ts b/src/main/text-generation/requests/jira-issue-summary-requests.test.ts deleted file mode 100644 index cff5c158da7..00000000000 --- a/src/main/text-generation/requests/jira-issue-summary-requests.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ - prepare: vi.fn(), - generate: vi.fn(), - cancel: vi.fn(), - resolve: vi.fn(), - status: vi.fn() -})) -vi.mock('../../jira/client', () => ({ getStatus: mocks.status })) -vi.mock('../execution/commit-message-agent-environment', () => ({ - prepareLocalCommitMessageAgentEnv: mocks.prepare -})) -vi.mock('../commit-message-text-generation', () => ({ - resolveCommitMessageSettings: mocks.resolve -})) -vi.mock('./jira-issue-summary-text-generation', () => ({ - generateJiraIssueSummaryFromContext: mocks.generate, - cancelGenerateJiraIssueSummaryLocal: mocks.cancel -})) -import { - generateJiraIssueSummaryRequest, - cancelJiraIssueSummaryRequest -} from './jira-issue-summary-requests' -import { getDefaultSettings } from '../../../shared/constants' -function deferred() { - let resolve!: (value: T) => void - const promise = new Promise((done) => { - resolve = done - }) - return { promise, resolve } -} -const args = { description: 'Draft', siteId: 'site-1', requestId: 'req-1', draftId: 'draft-1' } -const settings = getDefaultSettings('/fixture') -const host = { - getSettings: () => settings, - getAgentEnvironment: () => ({ prepareForCodexLaunch: () => 'host-codex-home' }) -} -beforeEach(() => { - vi.clearAllMocks() - mocks.resolve.mockReturnValue({ - ok: true, - params: { agentId: 'custom', model: '', customAgentCommand: 'agent' } - }) - mocks.prepare.mockResolvedValue({ ok: true, env: { CODEX_HOME: 'host-codex-home' } }) - mocks.generate.mockResolvedValue({ success: true, summary: 'Generated title' }) - mocks.status.mockReturnValue({ sites: [{ id: 'site-1' }, { id: 'site-2' }] }) -}) -describe('Jira title host ownership', () => { - it('does not launch a replaced request after its environment finishes', async () => { - const slow = deferred<{ ok: true }>() - mocks.prepare.mockReturnValueOnce(slow.promise) - const old = generateJiraIssueSummaryRequest(host, 'owner-1', args) - await generateJiraIssueSummaryRequest(host, 'owner-1', { - ...args, - requestId: 'req-2', - description: 'New' - }) - slow.resolve({ ok: true }) - expect(await old).toMatchObject({ canceled: true }) - expect(mocks.generate).toHaveBeenCalledTimes(1) - expect(mocks.generate.mock.calls[0][0].description).toBe('New') - }) - it.each([ - ['owner-2', args], - ['owner-1', { ...args, draftId: 'draft-2' }], - ['owner-1', { ...args, siteId: 'site-2' }] - ])('rejects competing generation from another owner, draft or account', async (owner, other) => { - const pending = deferred<{ success: true; summary: string }>() - mocks.generate.mockReturnValue(pending.promise) - const first = generateJiraIssueSummaryRequest(host, 'owner-1', args) - await Promise.resolve() - mocks.cancel.mockClear() - cancelJiraIssueSummaryRequest(owner, other) - expect(await generateJiraIssueSummaryRequest(host, owner, other)).toMatchObject({ - success: false - }) - expect(mocks.cancel).not.toHaveBeenCalled() - pending.resolve({ success: true, summary: 'First' }) - await first - }) - it('ignores an old cancel after a newer request starts', async () => { - const pending = deferred<{ ok: true }>() - mocks.prepare.mockReturnValueOnce(pending.promise) - const newer = { ...args, requestId: 'req-2' } - const result = generateJiraIssueSummaryRequest(host, 'owner-1', newer) - cancelJiraIssueSummaryRequest('owner-1', args) - pending.resolve({ ok: true }) - expect(await result).toMatchObject({ success: true }) - }) - it.each(['cancel', 'disconnect'])( - 'prevents spawning after %s during environment preparation', - async (action) => { - const pending = deferred<{ ok: true }>() - mocks.prepare.mockReturnValue(pending.promise) - const abort = new AbortController() - const result = generateJiraIssueSummaryRequest(host, 'owner-1', args, abort.signal) - if (action === 'cancel') { - cancelJiraIssueSummaryRequest('owner-1', args) - } else { - abort.abort() - } - pending.resolve({ ok: true }) - expect(await result).toMatchObject({ canceled: true }) - expect(mocks.generate).not.toHaveBeenCalled() - } - ) - it('rechecks a disconnected Jira account before spawning', async () => { - mocks.status.mockReturnValueOnce({ sites: [{ id: 'site-1' }] }).mockReturnValue({ sites: [] }) - expect(await generateJiraIssueSummaryRequest(host, 'owner-1', args)).toMatchObject({ - success: false - }) - expect(mocks.generate).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/window/clipboard/clipboard-copied-file-paths.test.ts b/src/main/window/clipboard/clipboard-copied-file-paths.test.ts deleted file mode 100644 index 2282ecfca9c..00000000000 --- a/src/main/window/clipboard/clipboard-copied-file-paths.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readClipboardCopiedFilePaths } from './clipboard-copied-file-paths' - -function clipboardWith(formats: Record) { - return { - readBuffer: (format: string): Buffer => { - const value = formats[format] - return typeof value === 'string' ? Buffer.from(value, 'utf8') : (value ?? Buffer.alloc(0)) - } - } -} - -function filenamesPlist(paths: string[]): string { - const entries = paths.map((path) => `${path}`).join('') - return `${entries}` -} - -describe('readClipboardCopiedFilePaths', () => { - it('lists every file Finder copied, decoding XML entities', () => { - const clipboard = clipboardWith({ - NSFilenamesPboardType: filenamesPlist(['/Users/me/Q&A shot.png', '/Users/me/b.pdf']), - 'public.file-url': 'file:///Users/me/Q&A%20shot.png' - }) - expect(readClipboardCopiedFilePaths(clipboard, 'darwin')).toEqual([ - '/Users/me/Q&A shot.png', - '/Users/me/b.pdf' - ]) - }) - - it('falls back to the first file URL on macOS, but not a file-reference URL', () => { - expect( - readClipboardCopiedFilePaths( - clipboardWith({ 'public.file-url': 'file:///Users/me/my%20shot.png' }), - 'darwin' - ) - ).toEqual(['/Users/me/my shot.png']) - expect( - readClipboardCopiedFilePaths( - clipboardWith({ 'public.file-url': 'file:///.file/id=6571367.2773272' }), - 'darwin' - ) - ).toEqual([]) - }) - - it('reads a Linux file manager uri-list and rejects non-file entries', () => { - expect( - readClipboardCopiedFilePaths( - clipboardWith({ - 'text/uri-list': '# copied\r\nfile:///home/me/a.png\r\nfile:///home/me/b%20c.txt\r\n' - }), - 'linux' - ) - ).toEqual(['/home/me/a.png', '/home/me/b c.txt']) - expect( - readClipboardCopiedFilePaths( - clipboardWith({ 'text/uri-list': 'file:///home/me/a.png\nhttps://example.com/x' }), - 'linux' - ) - ).toEqual([]) - }) - - it('reads the single file Explorer copied and nothing when it copied several', () => { - const shellItems = (count: number): Buffer => { - const cida = Buffer.alloc(4 + 4 * (count + 1)) - cida.writeUInt32LE(count) - return cida - } - const explorer = (count: number) => - clipboardWith({ - FileNameW: Buffer.from('C:\\Users\\me\\shot.png\0', 'utf16le'), - 'Shell IDList Array': shellItems(count) - }) - expect(readClipboardCopiedFilePaths(explorer(1), 'win32')).toEqual(['C:\\Users\\me\\shot.png']) - expect(readClipboardCopiedFilePaths(explorer(2), 'win32')).toEqual([]) - }) - - it('returns nothing for plain text, oversized lists, or a failing clipboard', () => { - expect(readClipboardCopiedFilePaths(clipboardWith({}), 'darwin')).toEqual([]) - const huge = filenamesPlist(['/a'.padEnd(300 * 1024, 'a')]) - expect( - readClipboardCopiedFilePaths(clipboardWith({ NSFilenamesPboardType: huge }), 'darwin') - ).toEqual([]) - const failing = { - readBuffer: (): Buffer => { - throw new Error('format unavailable') - } - } - expect(readClipboardCopiedFilePaths(failing, 'linux')).toEqual([]) - }) -}) diff --git a/src/main/window/clipboard/clipboard-text-publisher.test.ts b/src/main/window/clipboard/clipboard-text-publisher.test.ts deleted file mode 100644 index 64c7c3fabfe..00000000000 --- a/src/main/window/clipboard/clipboard-text-publisher.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' -import { - assertClipboardTextWriteWithinLimitWithYield, - CLIPBOARD_TEXT_WRITE_MAX_BYTES -} from '../../../shared/clipboard-text' -import { CLIPBOARD_IMAGE_MAX_BASE64_CHARS } from '../../../shared/clipboard-image' -import { createClipboardPublisher } from './clipboard-text-publisher' - -vi.mock('electron', () => ({ app: {}, clipboard: {} })) - -const ok: ProcessResult = { code: 0, signal: null, stdout: '', stderr: '', timedOut: false } -const run = vi.fn(async (_spec: ProcessSpec): Promise => ok) -const write = vi.fn() -const clearCache = vi.fn() -function publisher(wayland = true, validate = assertClipboardTextWriteWithinLimitWithYield) { - return createClipboardPublisher({ - isWayland: () => wayland, - helperPath: () => '/bundle/bin/orca-wayland-clipboard', - run, - write, - clearCache, - validate - }) -} -function writer(wayland = true, validate = assertClipboardTextWriteWithinLimitWithYield) { - return publisher(wayland, validate).publishText -} - -describe('terminal clipboard writes', () => { - beforeEach(() => { - vi.resetAllMocks() - run.mockResolvedValue(ok) - }) - - it.each([ - ['timeout', { ...ok, code: null, timedOut: true }], - ['helper failure', { ...ok, code: 70 }] - ])('rejects %s without falling back to an unsafe Electron write', async (_label, result) => { - run.mockResolvedValueOnce(result) - await expect(writer()('copy')).rejects.toThrow('Wayland clipboard write failed') - expect(write).not.toHaveBeenCalled() - expect(clearCache).not.toHaveBeenCalled() - }) - - it('rejects oversized text before either clipboard backend is invoked', async () => { - await expect(writer()('x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES + 1))).rejects.toThrow( - 'Clipboard text is too large' - ) - expect(run).not.toHaveBeenCalled() - expect(write).not.toHaveBeenCalled() - }) - - it.each([ - { label: 'count', count: 32, bytes: 1 }, - { label: 'retained bytes', count: 1, bytes: CLIPBOARD_IMAGE_MAX_BASE64_CHARS * 2 } - ])( - 'bounds other clipboard operations by $label and releases capacity after failure', - async ({ count, bytes }) => { - const copy = publisher(false) - let release: () => void = () => undefined - const gate = new Promise((resolve) => { - release = resolve - }) - const publications: number[] = [] - const first = copy.publish(bytes, async () => { - await gate - throw new Error('file helper failed') - }) - const rejected = expect(first).rejects.toThrow('file helper failed') - const queued = Array.from({ length: count - 1 }, (_, index) => - copy.publish(bytes, () => { - publications.push(index) - return index - }) - ) - await expect(copy.publish(bytes, () => publications.push(-1))).rejects.toThrow( - 'Too many pending clipboard writes' - ) - expect(publications).toEqual([]) - const text = copy.publishText('after failed file', 'ordinary') - release() - await rejected - await Promise.all(queued) - await text - expect(publications).toHaveLength(count - 1) - expect(publications).not.toContain(-1) - expect(write).toHaveBeenLastCalledWith('after failed file', 'ordinary') - await expect(copy.publish(bytes, () => 'after flood')).resolves.toBe('after flood') - } - ) - - it('bounds requests queued behind a stalled helper', async () => { - let release: (value: typeof ok) => void = () => undefined - run.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - const copy = writer() - const queued = Array.from({ length: 32 }, (_, index) => copy(String(index))) - await expect(copy('overflow')).rejects.toThrow('Too many pending clipboard writes') - await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) - release(ok) - await Promise.all(queued) - await copy('after flood') - expect(run).toHaveBeenCalledTimes(33) - }) - - it('bounds the total text retained behind a stalled helper', async () => { - let release: (value: typeof ok) => void = () => undefined - run.mockImplementationOnce( - () => - new Promise((resolve) => { - release = resolve - }) - ) - const copy = writer(true, async (text) => text) - const text = 'x'.repeat(CLIPBOARD_TEXT_WRITE_MAX_BYTES / 2 + 1) - const first = copy(text) - await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)) - let failure: unknown - void copy(text).catch((error: unknown) => { - failure = error - }) - await vi.waitFor( - () => expect(failure).toEqual(new Error('Too many pending clipboard writes')), - { timeout: 200 } - ) - release(ok) - await first - await copy(text) - expect(run).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts b/src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts deleted file mode 100644 index 5ae840abb4d..00000000000 --- a/src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' - -type RendererSend = (channel: string, ...args: unknown[]) => void - -function createSender( - options: { - send?: RendererSend - windowDestroyed?: boolean - webContentsDestroyed?: boolean - } = {} -) { - const send = options.send ?? vi.fn() - const onFailure = vi.fn() - const warn = vi.fn() - const sender = createRuntimeRendererNotificationSender({ - isWindowDestroyed: () => options.windowDestroyed ?? false, - webContents: { - isDestroyed: () => options.webContentsDestroyed ?? false, - send - }, - onFailure, - warn - }) - return { sender, send, onFailure, warn } -} - -describe('runtime renderer notification sender', () => { - it('contains a disposed frame and suppresses repeated sends and warnings', () => { - const failure = new Error('Render frame was disposed before WebFrameMain could be accessed') - const fixture = createSender({ - send: vi.fn(() => { - throw failure - }) - }) - - expect(fixture.sender.send('repos:changed')).toBe(false) - expect(fixture.sender.send('worktrees:changed')).toBe(false) - expect(fixture.sender.send('repos:changed')).toBe(false) - - expect(fixture.send).toHaveBeenCalledOnce() - expect(fixture.warn).toHaveBeenCalledOnce() - expect(fixture.onFailure).toHaveBeenCalledExactlyOnceWith('renderer-frame-unavailable') - }) - - it('pauses during a main-frame reload and resumes only after load finishes', () => { - const fixture = createSender() - - fixture.sender.onMainFrameReloadStarted() - expect(fixture.sender.send('repos:changed')).toBe(false) - fixture.sender.onMainFrameLoadFinished() - - expect(fixture.sender.send('repos:changed')).toBe(true) - expect(fixture.send).toHaveBeenCalledOnce() - expect(fixture.onFailure).not.toHaveBeenCalled() - }) - - it('resumes when a provisional main-frame reload is cancelled', () => { - const fixture = createSender() - - fixture.sender.onMainFrameReloadStarted() - expect(fixture.sender.send('repos:changed')).toBe(false) - fixture.sender.onMainFrameReloadCancelled() - - expect(fixture.sender.send('repos:changed')).toBe(true) - expect(fixture.send).toHaveBeenCalledOnce() - }) - - it('treats an absent or destroyed renderer as unavailable without throwing', () => { - const missingWindow = createSender({ windowDestroyed: true }) - const missingWebContents = createSender({ webContentsDestroyed: true }) - - expect(missingWindow.sender.send('repos:changed')).toBe(false) - expect(missingWebContents.sender.send('repos:changed')).toBe(false) - expect(missingWindow.onFailure).not.toHaveBeenCalled() - expect(missingWebContents.onFailure).not.toHaveBeenCalled() - }) - - it('keeps close terminal when renderer lifecycle events arrive late', () => { - const fixture = createSender() - - fixture.sender.close() - fixture.sender.onMainFrameLoadFinished() - fixture.sender.onMainFrameReloadStarted() - fixture.sender.onRendererProcessGone() - - expect(fixture.sender.send('repos:changed')).toBe(false) - expect(fixture.send).not.toHaveBeenCalled() - expect(fixture.warn).not.toHaveBeenCalled() - expect(fixture.onFailure).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx b/src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx deleted file mode 100644 index bdee9b8dac2..00000000000 --- a/src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../../shared/repo-types' -import { makeAutomation, makeAutomationListRow, REPO_ID } from '../automations-page-fixtures' -import type { AutomationListRow } from './automation-list-row-identity' - -import * as searchRows from './automation-list-search-rows' -import { useAutomationListSearch } from './use-automation-list-search' - -// Count index builds instead of timing the 50ms claim to avoid CI timing flakes. -vi.mock('./automation-list-search-rows', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - buildAutomationListSearchRows: vi.fn(actual.buildAutomationListSearchRows), - matchAutomationListSearchRowKeys: vi.fn(actual.matchAutomationListSearchRowKeys) - } -}) - -const buildRowsSpy = vi.mocked(searchRows.buildAutomationListSearchRows) -const matchRowsSpy = vi.mocked(searchRows.matchAutomationListSearchRowKeys) - -const repoMap = new Map([ - [REPO_ID, { id: REPO_ID, displayName: 'orca', path: '/src/orca' } as Repo] -]) - -type SearchResult = ReturnType - -let container: HTMLDivElement -let root: Root -let latest: SearchResult | null = null - -function Harness({ query, rows }: { query: string; rows: readonly AutomationListRow[] }): null { - latest = useAutomationListSearch({ - listSearchQuery: query, - rows, - externalAutomationEntries: [], - repoMap, - selectedRowKey: null, - selectedExternalKey: null, - selectAutomationRow: () => undefined, - selectExternalKey: () => undefined - }) - return null -} - -function render(query: string, rows: readonly AutomationListRow[]): void { - act(() => { - root.render() - }) -} - -beforeEach(() => { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - buildRowsSpy.mockClear() - matchRowsSpy.mockClear() -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() - latest = null -}) - -describe('useAutomationListSearch cross-host identity', () => { - it('keeps both hosts’ copies of one automation ID through a matching query', () => { - // Bare-ID reconstruction would duplicate one authority’s row and drop its colliding counterpart. - const collided = [ - makeAutomationListRow({ - automation: makeAutomation({ id: 'a-1', name: 'Nightly desktop' }) - }), - makeAutomationListRow({ - automation: makeAutomation({ id: 'a-1', name: 'Nightly web-01' }), - hostStableKey: 'host:runtime:gpu:ssh:web-01', - hostLabel: 'web-01' - }) - ] - render('nightly', collided) - - expect(latest?.filteredRows.map((row) => row.automation.name)).toEqual([ - 'Nightly desktop', - 'Nightly web-01' - ]) - }) -}) diff --git a/src/renderer/src/components/browser-pane/use-browser-extensions-tour.test.ts b/src/renderer/src/components/browser-pane/use-browser-extensions-tour.test.ts deleted file mode 100644 index d6c3e5e8c92..00000000000 --- a/src/renderer/src/components/browser-pane/use-browser-extensions-tour.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - shouldRequestBrowserExtensionsTour, - type BrowserExtensionsTourEligibilityInput -} from './use-browser-extensions-tour' - -const SESSION_STARTED_AT = 1_000_000 - -function input( - overrides: Partial = {} -): BrowserExtensionsTourEligibilityInput { - return { - persistedUIReady: true, - extensionsEnabled: true, - seenIds: [], - tourShownThisSession: false, - onboardingVisible: false, - autoEligible: false, - featureInteractions: { - browser: { firstInteractedAt: SESSION_STARTED_AT - 1, interactionCount: 3 } - }, - sessionStartedAt: SESSION_STARTED_AT, - ...overrides - } -} - -describe('shouldRequestBrowserExtensionsTour', () => { - it('shows on a browser visit in a later session than the first one', () => { - expect(shouldRequestBrowserExtensionsTour(input())).toBe(true) - }) - - it('leaves the first browser session to Import', () => { - expect( - shouldRequestBrowserExtensionsTour( - input({ - featureInteractions: { - browser: { firstInteractedAt: SESSION_STARTED_AT + 5, interactionCount: 1 } - } - }) - ) - ).toBe(false) - expect(shouldRequestBrowserExtensionsTour(input({ featureInteractions: {} }))).toBe(false) - }) - - it('never shows twice', () => { - expect(shouldRequestBrowserExtensionsTour(input({ seenIds: ['browser-extensions'] }))).toBe( - false - ) - }) - - it('waits when another tour already ran this session', () => { - expect(shouldRequestBrowserExtensionsTour(input({ tourShownThisSession: true }))).toBe(false) - }) - - it('lets auto-tour users finish the browser tour (with its Import step) first', () => { - expect(shouldRequestBrowserExtensionsTour(input({ autoEligible: true }))).toBe(false) - expect( - shouldRequestBrowserExtensionsTour(input({ autoEligible: true, seenIds: ['browser'] })) - ).toBe(true) - }) - - it('reaches users who never got automatic tours', () => { - expect(shouldRequestBrowserExtensionsTour(input({ autoEligible: null }))).toBe(true) - }) - - it('skips people who already opened the extensions menu', () => { - expect( - shouldRequestBrowserExtensionsTour( - input({ - featureInteractions: { - browser: { firstInteractedAt: 1, interactionCount: 3 }, - 'browser-extensions': { firstInteractedAt: 2, interactionCount: 1 } - } - }) - ) - ).toBe(false) - }) - - it('stays quiet while extensions are off, onboarding is up, or UI state is loading', () => { - expect(shouldRequestBrowserExtensionsTour(input({ extensionsEnabled: false }))).toBe(false) - expect(shouldRequestBrowserExtensionsTour(input({ onboardingVisible: true }))).toBe(false) - expect(shouldRequestBrowserExtensionsTour(input({ persistedUIReady: false }))).toBe(false) - }) -}) diff --git a/src/renderer/src/components/editor/panel/header/editor-header-file-rename.test.ts b/src/renderer/src/components/editor/panel/header/editor-header-file-rename.test.ts deleted file mode 100644 index 82b34855d7f..00000000000 --- a/src/renderer/src/components/editor/panel/header/editor-header-file-rename.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -// @vitest-environment happy-dom - -import type * as EditorAutosave from '../../autosave/editor-autosave' -import type * as RuntimeFileMetadataClient from '@/runtime/files/metadata/runtime-file-metadata-client' -import { act, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { useEditorHeaderFileRename } from './editor-header-file-rename' -import '../untitled-rename/useUntitledFileRename' -import '@/store/index' -import '@/store/slices/worktrees/worktree.test-fixture' -import '@/store/repos/repo.test-fixture' - -const renameFileOnDiskMock = vi.hoisted(() => vi.fn()) -afterEach(() => vi.unstubAllGlobals()) -const renameIO = vi.hoisted(() => ({ - exists: vi.fn(), - quiesce: vi.fn(), - save: vi.fn(), - move: vi.fn() -})) -vi.mock('@/runtime/files/metadata/runtime-file-metadata-client', async (original) => ({ - ...(await original()), - runtimePathExists: renameIO.exists -})) -vi.mock('../../autosave/editor-autosave', async (original) => ({ - ...(await original()), - requestEditorSaveQuiesce: renameIO.quiesce, - requestEditorFileSave: renameIO.save -})) -vi.mock('@/lib/editor/file-operations/execute-open-editor-path-move', () => ({ - executeOpenEditorPathMove: renameIO.move -})) - -vi.mock('@/store/workspaces/selection/use-selected-worktree', () => ({ - useWorktreeById: () => ({ path: '/repo', repoId: 'repo-1' }) -})) - -vi.mock('@/lib/editor/file-operations/rename-file', () => ({ - renameFileOnDisk: renameFileOnDiskMock -})) - -function baseFile(overrides: Partial = {}): OpenFile { - return { - id: '/repo/notes.md', - filePath: '/repo/notes.md', - relativePath: 'notes.md', - worktreeId: 'wt-1', - language: 'markdown', - isDirty: false, - mode: 'edit', - ...overrides - } -} - -function renameInputStub(value: string): HTMLInputElement { - const input = document.createElement('input') - input.value = value - return input -} - -describe('useEditorHeaderFileRename', () => { - beforeEach(() => { - renameFileOnDiskMock.mockReset() - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - callback(0) - return 1 - }) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - }) - - // Focused input removal emits focusout after file switches; stale blur commits must not rename the replacement file. - it('closes the rename input when the active file changes', () => { - const { result, rerender } = renderHook((file: OpenFile) => useEditorHeaderFileRename(file), { - initialProps: baseFile() - }) - - act(() => { - result.current.openRenameInput() - }) - act(() => { - result.current.renameInputRef(renameInputStub('renamed.md')) - }) - - rerender( - baseFile({ id: '/repo/other.md', filePath: '/repo/other.md', relativePath: 'other.md' }) - ) - - expect(result.current.isRenaming).toBe(false) - }) -}) diff --git a/src/renderer/src/components/feature-wall/commit-pr-settings/AiCommitPrSettingsCard.discovery.test.tsx b/src/renderer/src/components/feature-wall/commit-pr-settings/AiCommitPrSettingsCard.discovery.test.tsx deleted file mode 100644 index ba93c6cae03..00000000000 --- a/src/renderer/src/components/feature-wall/commit-pr-settings/AiCommitPrSettingsCard.discovery.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -// @vitest-environment happy-dom -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { expect, it } from 'vitest' -import { useAppStore } from '@/store/index' -import { TooltipProvider } from '../../ui/tooltip' -import { persist } from '../../settings/__fixtures__/settings-persistence-test-fixture' -import { AiCommitPrSettingsCard } from './AiCommitPrSettingsCard' - -import * as models from '../../../../../shared/source-control/ai/settings/source-control-ai-model-selection' - -it.each(['omitted', 'efforts replaced'])( - 'keeps accepted choices when discovery is %s', - async (change) => { - const settings = useAppStore.getState().settings! - useAppStore.setState({ - settings: { - ...settings, - commitMessageAi: { - enabled: true, - agentId: 'codex', - selectedModelByAgent: { codex: 'gpt-5.5' }, - selectedThinkingByModel: {}, - customPrompt: '', - customAgentCommand: '', - discoveredModelsByAgent: { - codex: [ - { - id: 'gpt-6.1-sol', - label: 'GPT-6.1 Sol', - defaultThinkingLevel: 'low', - thinkingLevels: [ - { id: 'low', label: 'Low' }, - { id: 'high', label: 'High' } - ] - } - ] - } - } - } - }) - render( - - - - ) - fireEvent.pointerDown(screen.getByRole('button', { name: 'Select agent' }), { - button: 0, - ctrlKey: false - }) - fireEvent.click(screen.getByRole('button', { name: 'Configure Codex' })) - fireEvent.click(screen.getByRole('option', { name: 'GPT-6.1 Sol' })) - fireEvent.click(screen.getByRole('radio', { name: 'High' })) - act(() => - useAppStore.setState(({ settings }) => ({ - settings: { - ...settings!, - commitMessageAi: { ...settings!.commitMessageAi!, customPrompt: 'A newer instruction' }, - sourceControlAi: { - ...settings!.sourceControlAi!, - ...models.withDiscoveredModels( - settings!.sourceControlAi!, - 'codex', - change === 'omitted' - ? [{ id: 'gpt-6.2-sol', label: 'GPT-6.2 Sol' }] - : [ - { - id: 'gpt-6.1-sol', - label: 'GPT-6.1 Sol', - defaultThinkingLevel: 'low', - thinkingLevels: [{ id: 'low', label: 'Low' }] - } - ], - 'local' - ) - } - } - })) - ) - expect(persist).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: /^Use$/ })) - await waitFor(() => expect(persist).toHaveBeenCalledOnce()) - expect(useAppStore.getState().settings?.commitMessageAi).toMatchObject({ - selectedModelByAgent: { codex: 'gpt-6.1-sol' }, - selectedThinkingByModel: { 'gpt-6.1-sol': 'high' }, - customPrompt: 'A newer instruction' - }) - } -) diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.typography.test.ts b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.typography.test.ts deleted file mode 100644 index 94aa239026e..00000000000 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.typography.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it } from 'vitest' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' -import { nativeChatAppearanceStyle } from './native-chat-appearance-style' - -const SYSTEM_FONT = '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif' - -function styleFor(settings: Partial) { - return nativeChatAppearanceStyle({ theme: 'dark', ...settings }, null, true) -} - -describe('native chat typography', () => { - it('rounds the line height to whole pixels at every Text size', () => { - const lines = [12, 13, 14, 16, 18, 20].map( - (fontSize) => styleFor({ nativeChatAppearance: { fontSize } })['--chat-line-height'] - ) - expect(lines).toEqual(['18px', '20px', '22px', '25px', '28px', '31px']) - }) - - it('keeps labels, icons and spacing at their earlier size: 14px at the default, Text size elsewhere', () => { - const chrome = [12, 13, 14, 16, 20].map( - (fontSize) => styleFor({ nativeChatAppearance: { fontSize } })['--chat-ui-font-size'] - ) - expect(chrome).toEqual(['12px', '14px', '14px', '16px', '20px']) - }) - - it('uses the system UI font only while neither the chat nor the IDE font was chosen', () => { - expect(styleFor({ appFontFamily: 'Geist' })['--chat-font-family']).toBe(SYSTEM_FONT) - expect(styleFor({})['--chat-font-family']).toBe(SYSTEM_FONT) - expect( - styleFor({ appFontFamily: 'Geist', nativeChatAppearance: { fontFamily: 'Georgia' } })[ - '--chat-font-family' - ] - ).toMatch(/^"Georgia", /) - // Absent: the root falls back to the IDE font. - expect(styleFor({ appFontFamily: 'Inter' })['--chat-font-family']).toBeUndefined() - expect( - styleFor({ - appFontFamily: 'Geist', - terminalFontFamily: 'JetBrains Mono', - nativeChatAppearance: { matchTerminalInterface: true } - })['--chat-font-family'] - ).toMatch(/JetBrains Mono/) - }) - - it('keeps the brighter text color 10 points above body text, up to full strength', () => { - const mixes = (theme: 'dark' | 'light', contrast: number) => { - const style = styleFor({ theme, nativeChatAppearance: { contrast } }) - return [style['--chat-foreground-mix'], style['--chat-strong-mix']] - } - expect(mixes('dark', 75)).toEqual(['72%', '82%']) - expect(mixes('light', 75)).toEqual(['76%', '86%']) - expect(mixes('dark', 150)).toEqual(['100%', '100%']) - }) - - it('scales body text with Contrast, keeping the earlier ends', () => { - const mixes = (theme: 'dark' | 'light') => - [50, 75, 100, 125, 150].map( - (contrast) => - styleFor({ theme, nativeChatAppearance: { contrast } })['--chat-foreground-mix'] - ) - expect(mixes('dark')).toEqual(['56%', '72%', '88%', '94%', '100%']) - expect(mixes('light')).toEqual(['64%', '76%', '88%', '94%', '100%']) - }) -}) diff --git a/src/renderer/src/components/native-chat/composer/focus/use-native-chat-composer-reveal-focus.test.tsx b/src/renderer/src/components/native-chat/composer/focus/use-native-chat-composer-reveal-focus.test.tsx deleted file mode 100644 index 22ea2149cae..00000000000 --- a/src/renderer/src/components/native-chat/composer/focus/use-native-chat-composer-reveal-focus.test.tsx +++ /dev/null @@ -1,91 +0,0 @@ -// @vitest-environment happy-dom -import { act, useRef } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { NativeChatComposerHandle } from '../native-chat-composer-types' -import { useNativeChatComposerRevealFocus } from './use-native-chat-composer-reveal-focus' -import { requestNativeChatComposerFocus } from './native-chat-composer-focus-intent' - -Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) -let root: Root -let container: HTMLDivElement -let sidebar: HTMLDivElement -let prompt: boolean -const frames: (() => void)[] = [] -const scheduleFrame = (callback: () => void) => frames.push(callback) -function Probe() { - const rootRef = useRef(null) - const composerRef = useRef({ - insertAgentReferences: () => false, - insertTypedText: () => false, - acceptsText: () => true, - contains: (element) => rootRef.current?.contains(element) === true, - appendText: () => {}, - handlePasteEvent: () => {}, - pasteFromClipboard: () => {}, - focus: () => { - rootRef.current?.querySelector('textarea')?.focus() - return true - } - }) - useNativeChatComposerRevealFocus({ - tabId: 'tab', - rootRef, - composerRef, - isVisible: true, - isFocusedGroup: true, - composerReady: !prompt, - surfaceReady: prompt, - scheduleFrame - }) - return ( -
- {prompt ? ( -
- -
- ) : ( -