diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 85c8cc9f0c6..7f8164b1eb4 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -214,7 +214,6 @@ 1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts 2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts 2 test-no-real-time-wait:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts -1 test-no-real-time-wait:src/shared/darwin-process-table-capture.test.ts 1 test-no-real-time-wait:src/shared/darwin-terminal-names-real-ps.test.ts 1 test-no-real-time-wait:src/shared/darwin-terminal-names.test.ts 1 test-no-real-time-wait:src/shared/git/status/git-branch-line-total-soft-deadline.test.ts @@ -628,7 +627,6 @@ 1 test-timeout-needs-reason:src/renderer/src/hooks/agent-hook-completion-notifications.test.ts 1 test-timeout-needs-reason:src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts 1 test-timeout-needs-reason:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts -1 test-timeout-needs-reason:src/shared/dsh-real-cli.test.ts 1 test-timeout-needs-reason:src/shared/wsl-login-shell-command.test.ts 1 test-timeout-needs-reason:tests/e2e/active-view-restart-restore.spec.ts 1 test-timeout-needs-reason:tests/e2e/agent-send-picker-reveal.spec.ts diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 491e47fa748..bef6f0b90de 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -20,7 +20,6 @@ 1 src/renderer/src/components/activity/use-agent-pane-threads.ts 4 src/renderer/src/components/agent/AgentSettingsDialog.tsx 1 src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts -1 src/renderer/src/components/automations/automations-page-fixtures.ts 1 src/renderer/src/components/automations/hosts/automation-host-client.ts 1 src/renderer/src/components/automations/use-automations-page-controller.ts 1 src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index c361edcc424..e976b64d092 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -3614,11 +3614,11 @@ "https://github.com/stablyai/orca/issues/9563" ], "invariant": "A safely promotable headless serve process is the single app owner. Desktop activation preserves its daemon-backed sessions. On macOS, a CLI-supervised serve update keeps the node-mode parent alive across ShipIt's atomic bundle swap, restarts with the original serve arguments only after the target bundle is present, and clears handoff state only after that target version reports runtime readiness. Once a supervised child exits or fails to start, no late handoff completion may signal it or arm force-kill escalation. Unsupported or failed handoffs leave the current serving owner intact or recover it once without an install retry loop.", - "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. Audit2252: The removed synthetic lock/gate/hydration fixture supplies no current promotion continuity oracle. Existing other selectors retain only their own independent scope; changed selector execution is pending. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. 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: Unit tests coalesce early activation, preserve daemon and SSH identity, and reproduce the update race with a staged target, old serving child, persistent CLI parent, atomic .app replacement, and replacement readiness message. They assert the parent does not exit for launchd to respawn the old app, the native updater does not launch an interactive GUI, the replacement version is verified before handoff completion, mismatches become durable failures without retries, and unsupported/preflight-failed installs do not invoke native quit or PTY cleanup. Force handoff completion to fail after the replacement child exits and require zero later child signals and zero escalation timers. A joined lock-owner/activation/hydration contract asserts that a forced relaunch opens exactly one window and that the renderer promoted inside the serve process launches zero agent resumes, creates no replacement tab or startup command, and leaves every surviving session record untouched. The Electron journey independently verifies headless promotion retains owner/runtime/daemon/PTY identity and terminal I/O.", + "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. Audit2252: The removed synthetic lock/gate/hydration fixture supplies no current promotion continuity oracle. Existing other selectors retain only their own independent scope; changed selector execution is pending. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. 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: Unit tests coalesce early activation, preserve daemon and SSH identity, and reproduce the update race with a staged target, old serving child, persistent CLI parent, atomic .app replacement, and replacement readiness message. They assert the parent does not exit for launchd to respawn the old app, the native updater does not launch an interactive GUI, the replacement version is verified before handoff completion, mismatches become durable failures without retries, and unsupported/preflight-failed installs do not invoke native quit or PTY cleanup. Force handoff completion to fail after the replacement child exits and require zero later child signals and zero escalation timers. A joined lock-owner/activation/hydration contract asserts that a forced relaunch opens exactly one window and that the renderer promoted inside the serve process launches zero agent resumes, creates no replacement tab or startup command, and leaves every surviving session record untouched. The Electron journey independently verifies headless promotion retains owner/runtime/daemon/PTY identity and terminal I/O. Audit4587 retires the one-case CLI WebSocket protocol/preflight suite and its hand-built server; its cross-layer non-delivery witness is intentionally lost, with no replacement coverage claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/serve-signal-exit-diagnostic.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-launch/serve-desktop-activation.test.ts src/cli/runtime/client.test.ts src/cli/runtime/websocket-transport.test.ts src/main/runtime/construction/orca-runtime.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-launch/serve-desktop-activation.test.ts src/cli/runtime/client.test.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm exec electron-vite build --mode e2e", "pnpm run test:e2e -- tests/e2e/headless-serve-desktop-activation.spec.ts --workers=1" ], @@ -3629,7 +3629,6 @@ "src/cli/runtime/serve-signal-exit-diagnostic.test.ts", "src/main/startup/serve-launch/serve-desktop-activation.test.ts", "src/cli/runtime/client.test.ts", - "src/cli/runtime/websocket-transport.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "tests/e2e/headless-serve-desktop-activation.spec.ts" ], @@ -6394,9 +6393,9 @@ "https://github.com/stablyai/orca/issues/9229" ], "invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.", - "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. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): 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. Audit3774 (independent peer expansion of3773): deliberately retire7authored/13potential expanded registrations across4whole suites: standalone truncated8-byte E2EE guard; open/empty readiness null fast-path; capability parser acceptance/atomic malformed-array bounds; phone/delegated-parent/desktop/in-process creator provenance projections. These are real guard/policy alarms accepted as low marginal value, not tautologies. No equivalent replacement, authenticated-refusal, observer delivery, persisted visibility, synchronous scheduling or fresh execution is claimed. Prior dated receipts retain their exact original scopes and do not validate the changed/reduced current selector. Independent daemon E2E receipts remain scoped to their own unchanged commands. Historical prior account (preserved verbatim): 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): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): 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 isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.", + "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. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): 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. Audit3774 (independent peer expansion of3773): deliberately retire7authored/13potential expanded registrations across4whole suites: standalone truncated8-byte E2EE guard; open/empty readiness null fast-path; capability parser acceptance/atomic malformed-array bounds; phone/delegated-parent/desktop/in-process creator provenance projections. These are real guard/policy alarms accepted as low marginal value, not tautologies. No equivalent replacement, authenticated-refusal, observer delivery, persisted visibility, synchronous scheduling or fresh execution is claimed. Prior dated receipts retain their exact original scopes and do not validate the changed/reduced current selector. Independent daemon E2E receipts remain scoped to their own unchanged commands. Historical prior account (preserved verbatim): 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): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): 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 isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back. Audit4587 retires the one-case CLI WebSocket protocol/preflight suite and its hand-built server; its cross-layer non-delivery witness is intentionally lost, with no replacement coverage claimed.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], @@ -6405,7 +6404,6 @@ "src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts", "src/shared/remote-runtime/remote-runtime-client.test.ts", "src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", - "src/cli/runtime/websocket-transport.test.ts", "src/renderer/src/web/web-runtime-client.test.ts", "src/renderer/src/components/terminal/terminal-close-incarnation.test.ts", "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", diff --git a/src/cli/runtime/transport-framing.test.ts b/src/cli/runtime/transport-framing.test.ts index 2c7bfb5ecf0..66fbcbfa177 100644 --- a/src/cli/runtime/transport-framing.test.ts +++ b/src/cli/runtime/transport-framing.test.ts @@ -18,10 +18,10 @@ const reply = (result: unknown) => `${JSON.stringify({ id: 'request-1', ok: true, result, _meta: { runtimeId: 'runtime-1' } })}\n` class TestSocket extends EventEmitter { - setEncoding = vi.fn() - write = vi.fn() - end = vi.fn() - destroy = vi.fn() + setEncoding = (): void => {} + write = (): void => {} + end = (): void => {} + destroy = (): void => {} } let socket: TestSocket @@ -30,50 +30,16 @@ beforeEach(() => { createConnection.mockReturnValue(socket) }) afterEach(() => { - vi.restoreAllMocks() vi.useRealTimers() }) describe('CLI runtime response framing', () => { - it.each([1, 7, 256, 4096])( - 'reads a fragmented response with %i-character chunks', - async (size) => { - const result = { data: '界😀'.repeat(10000) } - const encoded = reply(result) - const pending = sendRequest(metadata, 'terminal.read', {}, 30000) - for (let offset = 0; offset < encoded.length; offset += size) { - socket.emit('data', encoded.slice(offset, offset + size)) - } - await expect(pending).resolves.toMatchObject({ result }) - expect(socket.setEncoding).toHaveBeenCalledExactlyOnceWith('utf8') - expect(socket.end).toHaveBeenCalledOnce() - } - ) - - it('searches each fragment once without rescanning the accumulated reply', async () => { - const encoded = reply({ data: 'x'.repeat(1024 * 1024) }) + it('reads a response split across chunks without losing its payload', async () => { + const encoded = reply({ data: '界😀done' }) const pending = sendRequest(metadata, 'terminal.read', {}, 30000) - const originalIndexOf = String.prototype.indexOf - let searchedCharacters = 0 - const search = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function ( - this: string, - value, - position - ) { - if (value === '\n') { - searchedCharacters += this.length - (position ?? 0) - } - return originalIndexOf.call(this, value, position) - }) - try { - for (let offset = 0; offset < encoded.length; offset += 256) { - socket.emit('data', encoded.slice(offset, offset + 256)) - } - } finally { - search.mockRestore() - } - await expect(pending).resolves.toMatchObject({ ok: true }) - expect(searchedCharacters).toBe(encoded.length) + socket.emit('data', encoded.slice(0, 7)) + socket.emit('data', encoded.slice(7)) + await expect(pending).resolves.toMatchObject({ result: { data: '界😀done' } }) }) it('refreshes keepalives across chunks and ignores blanks and data after the final frame', async () => { @@ -86,13 +52,10 @@ describe('CLI runtime response framing', () => { socket.emit('data', `${reply({ data: 'done' })}invalid JSON\n`) socket.emit('data', 'more ignored data') await expect(pending).resolves.toMatchObject({ result: { data: 'done' } }) - expect(socket.end).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) }) it.each([ ['broken JSON\n', 'invalid_runtime_response'], - ['{}\n', 'invalid_runtime_response'], ['{"id":"other","ok":true,"result":{}}\n', 'invalid_runtime_response'], [ '{"id":"request-1","ok":true,"result":{},"_meta":{"runtimeId":"other"}}\n', @@ -105,29 +68,18 @@ describe('CLI runtime response framing', () => { socket.emit('data', line.slice(0, 2)) socket.emit('data', line.slice(2) + reply({ data: 'ignored' })) await expect(pending).rejects.toMatchObject({ code }) - expect(socket.end).toHaveBeenCalledOnce() } ) - it('preserves terminal failure envelopes', async () => { - const pending = sendRequest(metadata, 'terminal.read', {}, 30000) - socket.emit('data', '{"id":"request-1","ok":false,"error":{"code":"bad","message":"no"}}\n') - await expect(pending).resolves.toMatchObject({ - ok: false, - error: { code: 'bad', message: 'no' } - }) - }) - it('rejects close with an incomplete frame and does not parse later data', async () => { const pending = sendRequest(metadata, 'terminal.read', {}, 30000) socket.emit('data', '{"id":') socket.emit('close') socket.emit('data', reply({ data: 'ignored' })) await expect(pending).rejects.toMatchObject({ code: 'runtime_unavailable' }) - expect(socket.end).toHaveBeenCalledOnce() }) - it('destroys a timed out socket holding an incomplete frame', async () => { + it('rejects a timed out incomplete frame and ignores a late reply', async () => { vi.useFakeTimers() const pending = sendRequest(metadata, 'terminal.read', {}, 100) const rejected = expect(pending).rejects.toMatchObject({ code: 'runtime_timeout' }) @@ -135,7 +87,5 @@ describe('CLI runtime response framing', () => { await vi.advanceTimersByTimeAsync(100) socket.emit('data', reply({ data: 'ignored' })) await rejected - expect(socket.destroy).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) }) }) diff --git a/src/cli/runtime/websocket-transport.test.ts b/src/cli/runtime/websocket-transport.test.ts deleted file mode 100644 index a0cfb912efa..00000000000 --- a/src/cli/runtime/websocket-transport.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { createServer, type Server } from 'node:http' -import 'node:fs' -import 'node:os' -import 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { WebSocketServer } from 'ws' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' - -import type { RuntimeStatus } from '../../shared/runtime-types' -import { - decrypt, - deriveSharedKey, - encrypt, - generateKeyPair, - publicKeyToBase64 -} from '../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import './websocket-transport' -import '../../shared/remote-runtime/requests/remote-runtime-prepared-request-admission' -import { RuntimeClient } from './client' -import '../workspaces/worktree-removal-request' -import { launchOrcaApp } from './launch' -import './environments' -import { - MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - RUNTIME_PROTOCOL_VERSION -} from '../../shared/protocol-version' - -vi.mock('./launch', () => ({ - launchOrcaApp: vi.fn() -})) - -type TestRuntime = { - endpoint: string - publicKeyB64: string - deviceToken: string - authFrames: Record[] - requestMethods: string[] - requestParams: unknown[] - connectionCount: () => number - close: () => Promise -} - -describe('CLI remote WebSocket transport', () => { - const servers: TestRuntime[] = [] - - afterEach(async () => { - vi.mocked(launchOrcaApp).mockClear() - await Promise.all(servers.splice(0).map((server) => server.close())) - }) - - it('blocks remote RPCs when the server protocol is too old', async () => { - const runtime = await startTestRuntime('runtime-old', { runtimeProtocolVersion: 1 }) - servers.push(runtime) - - const client = new RuntimeClient( - '/tmp/unused', - 5_000, - encodePairingOffer({ - v: 2, - endpoint: runtime.endpoint, - deviceToken: runtime.deviceToken, - publicKeyB64: runtime.publicKeyB64 - }) - ) - - await expect(client.call('repo.list')).rejects.toMatchObject({ - code: 'incompatible_runtime', - message: expect.stringContaining('server is too old') - }) - expect(runtime.connectionCount()).toBe(1) - expect(runtime.authFrames).toHaveLength(1) - expect(runtime.requestMethods).toEqual(['status.get']) - }) -}) - -async function startTestRuntime( - runtimeId: string, - statusOverrides: { - runtimeProtocolVersion?: number - minCompatibleRuntimeClientVersion?: number - desktopWindowStatus?: 'available' | 'openable' | 'initializing' | 'blocked' - appVersion?: string - remoteUpdateSupport?: { - installMode: 'unsupported-headless-serve' - automatic: false - reason: 'manual-service-update-required' - } - capabilities?: string[] - malformed?: boolean - failure?: boolean - hold?: string - onRequest?: (method: string) => void - disconnect?: boolean - mutationDisconnect?: boolean - rejectAuth?: boolean - degradations?: RuntimeStatus['degradations'] - } = {} -): Promise { - const serverKeyPair = generateKeyPair() - const deviceToken = `token-${runtimeId}` - const httpServer = createServer() - const wss = new WebSocketServer({ server: httpServer }) - const authFrames: Record[] = [] - const requestMethods: string[] = [] - const requestParams: unknown[] = [] - let connectionCount = 0 - - wss.on('connection', (ws) => { - let sharedKey: Uint8Array | null = null - let authenticated = false - - ws.on('message', (data) => { - const frame = data.toString() - if (!sharedKey) { - const hello = JSON.parse(frame) as Record & { - type?: string - publicKeyB64?: string - } - if (!hello.publicKeyB64) { - // Legacy-only host: refuses a v2 hello the way hosts before v2 do. - ws.close(4001, 'Invalid e2ee_hello') - return - } - connectionCount += 1 - const clientPublicKey = Buffer.from(hello.publicKeyB64 ?? '', 'base64') - sharedKey = deriveSharedKey(serverKeyPair.secretKey, clientPublicKey) - ws.send(JSON.stringify({ type: 'e2ee_ready' })) - return - } - - const plaintext = decrypt(frame, sharedKey) - if (!plaintext) { - ws.close(4003, 'decrypt failed') - return - } - if (!authenticated) { - const auth = JSON.parse(plaintext) as Record & { - type?: string - deviceToken?: string - } - authFrames.push(auth) - if ( - auth.type !== 'e2ee_auth' || - auth.deviceToken !== deviceToken || - statusOverrides.rejectAuth - ) { - ws.send(encrypt(JSON.stringify({ type: 'e2ee_error' }), sharedKey)) - ws.close(4001, 'auth failed') - return - } - authenticated = true - ws.send(encrypt(JSON.stringify({ type: 'e2ee_authenticated' }), sharedKey)) - return - } - - const request: { id: string; method: string; params?: unknown } = JSON.parse(plaintext) - requestMethods.push(request.method) - requestParams.push(request.params) - statusOverrides.onRequest?.(request.method) - if (request.method === statusOverrides.hold) { - return - } - if (request.method === 'status.get' && statusOverrides.disconnect) { - ws.close() - return - } - if (request.method === 'worktree.rm' && statusOverrides.mutationDisconnect) { - ws.close() - return - } - const response = - request.method === 'status.get' && statusOverrides.failure - ? { - id: request.id, - ok: false, - error: { code: 'runtime_unavailable', message: 'status failed' }, - _meta: { runtimeId } - } - : request.method === 'worktree.rm' - ? { id: request.id, ok: true, result: { removed: true }, _meta: { runtimeId } } - : request.method === 'status.get' - ? { - id: request.id, - ok: true, - result: statusOverrides.malformed - ? { capabilities: 42 } - : { - runtimeId, - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: null, - desktopWindowStatus: statusOverrides.desktopWindowStatus, - liveTabCount: 0, - liveLeafCount: 0, - runtimeProtocolVersion: - statusOverrides.runtimeProtocolVersion ?? RUNTIME_PROTOCOL_VERSION, - minCompatibleRuntimeClientVersion: - statusOverrides.minCompatibleRuntimeClientVersion ?? - MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, - appVersion: statusOverrides.appVersion, - remoteUpdateSupport: statusOverrides.remoteUpdateSupport, - capabilities: statusOverrides.capabilities, - degradations: statusOverrides.degradations - }, - _meta: { runtimeId } - } - : { - id: request.id, - ok: false, - error: { code: 'method_not_found', message: 'Unknown method' }, - _meta: { runtimeId } - } - ws.send(encrypt(JSON.stringify(response), sharedKey)) - }) - }) - - await listen(httpServer) - const address = httpServer.address() - if (!address || typeof address === 'string') { - throw new Error('Expected TCP test server') - } - - return { - endpoint: `ws://127.0.0.1:${address.port}`, - publicKeyB64: publicKeyToBase64(serverKeyPair.publicKey), - deviceToken, - authFrames, - requestMethods, - requestParams, - connectionCount: () => connectionCount, - close: async () => { - await new Promise((resolve) => { - wss.close(() => resolve()) - for (const client of wss.clients) { - client.close() - } - }) - await closeHttpServer(httpServer) - } - } -} - -async function listen(server: Server): Promise { - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) -} - -async function closeHttpServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.close((error) => { - if (error) { - reject(error) - return - } - resolve() - }) - }) -} diff --git a/src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx b/src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx deleted file mode 100644 index c5510a4f3e1..00000000000 --- a/src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx +++ /dev/null @@ -1,4 +0,0 @@ -// @vitest-environment happy-dom -import './AutomationsPage.escape-precedence.spec' -import './AutomationsPage.external-scope.spec' -import './AutomationsPage.refresh-selection.spec' diff --git a/src/renderer/src/components/automations/AutomationsPage.escape-precedence.spec.tsx b/src/renderer/src/components/automations/AutomationsPage.escape-precedence.spec.tsx deleted file mode 100644 index 99171389359..00000000000 --- a/src/renderer/src/components/automations/AutomationsPage.escape-precedence.spec.tsx +++ /dev/null @@ -1,72 +0,0 @@ -// @vitest-environment happy-dom - -/** Window capture runs before Radix document capture; preventing Escape here would veto dismissal of an overlaid dialog (STA-5207). */ - -import { describe, expect, it, vi } from 'vitest' -import { - installAutomationsPageHarness, - mocks, - renderPage, - settleHostQueries -} from './automations-page-test-harness' - -function pressEscape(target: EventTarget): KeyboardEvent { - const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) - target.dispatchEvent(event) - return event -} - -async function renderWithCloseSpy(): Promise> { - const closeAutomationsPage = vi.fn() - mocks.state.closeAutomationsPage = closeAutomationsPage - await renderPage() - await settleHostQueries() - return closeAutomationsPage -} - -describe('automations page Escape precedence', () => { - installAutomationsPageHarness() - - it('closes the page when nothing is layered above it', async () => { - const closeAutomationsPage = await renderWithCloseSpy() - - const event = pressEscape(document.body) - - expect(event.defaultPrevented).toBe(true) - expect(closeAutomationsPage).toHaveBeenCalledTimes(1) - }) - - it('leaves Escape to a store modal opened over the page', async () => { - mocks.state.activeModal = 'new-workspace-composer' - const closeAutomationsPage = await renderWithCloseSpy() - const input = document.createElement('input') - document.body.appendChild(input) - - const event = pressEscape(input) - - expect(event.defaultPrevented).toBe(false) - expect(closeAutomationsPage).not.toHaveBeenCalled() - }) - - it('leaves Escape to a store modal even when focus is on page chrome', async () => { - mocks.state.activeModal = 'worktree-palette' - const closeAutomationsPage = await renderWithCloseSpy() - - const event = pressEscape(document.body) - - expect(event.defaultPrevented).toBe(false) - expect(closeAutomationsPage).not.toHaveBeenCalled() - }) - - it('leaves Escape to a visible overlay that the store does not track', async () => { - const closeAutomationsPage = await renderWithCloseSpy() - const overlay = document.createElement('div') - overlay.setAttribute('role', 'dialog') - document.body.appendChild(overlay) - - const event = pressEscape(document.body) - - expect(event.defaultPrevented).toBe(false) - expect(closeAutomationsPage).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/automations/AutomationsPage.external-scope.spec.tsx b/src/renderer/src/components/automations/AutomationsPage.external-scope.spec.tsx deleted file mode 100644 index 6b417860ff1..00000000000 --- a/src/renderer/src/components/automations/AutomationsPage.external-scope.spec.tsx +++ /dev/null @@ -1,69 +0,0 @@ -// @vitest-environment happy-dom - -/** Drive the page’s scope producer and inspect IPC; client tests with pre-narrowed scopes cannot verify which hosts the page asks. */ - -import { describe, expect, it } from 'vitest' - -import { - api, - installAutomationsPageHarness, - mocks, - renderPage, - settleHostQueries -} from './automations-page-test-harness' -import { listedExternalEntries } from './automations-page-listed-items' -import { makeExternalManager } from './automations-page-fixtures' - -const DESKTOP_SELF_FILTER = { - kind: 'host' as const, - host: { authority: { kind: 'desktop' as const }, selector: { kind: 'self' as const } } -} - -function sshFilter(targetId: string): unknown { - return { - kind: 'host', - host: { authority: { kind: 'desktop' }, selector: { kind: 'ssh', targetId } } - } -} - -/** Registered SSH targets, each with the generation that makes it fenceable. */ -function withSshHosts(...targetIds: string[]): void { - mocks.state.sshTargetLabels = new Map(targetIds.map((targetId) => [targetId, targetId])) - mocks.state.sshTargetGenerations = new Map(targetIds.map((targetId) => [targetId, 1])) - mocks.state.sshConnectionStates = new Map( - targetIds.map((targetId) => [targetId, { status: 'connected' }]) - ) -} - -function openclawOnly(): void { - api.automations.listExternalManagerForOwner.mockImplementation( - async ({ provider }: { provider: string }) => - provider === 'openclaw' - ? { manager: makeExternalManager(), error: null, updatedAt: 1 } - : { manager: null, error: null, updatedAt: 1 } - ) -} - -describe('AutomationsPage external manager probes', () => { - installAutomationsPageHarness() - - it('drops the previous host rows when the selection moves, not when the new probe lands', async () => { - withSshHosts('staging') - mocks.state.automationHostFilter = DESKTOP_SELF_FILTER - openclawOnly() - - const { rerender } = await renderPage() - await settleHostQueries() - expect(listedExternalEntries().length).toBeGreaterThan(0) - - // The new host never answers, so anything still listed belongs to the old one. - api.automations.listExternalManagerForOwner.mockImplementation( - async () => await new Promise(() => undefined) - ) - mocks.state.automationHostFilter = sshFilter('staging') - await rerender() - await settleHostQueries() - - expect(listedExternalEntries()).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx b/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx deleted file mode 100644 index 2a96389539d..00000000000 --- a/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx +++ /dev/null @@ -1,133 +0,0 @@ -// @vitest-environment happy-dom - -/** Refresh reaches one authority at a time; deriving selection/history from that answer would drop or mislabel other hosts’ rows under All hosts. */ - -import { act } from 'react' -import { describe, expect, it, vi } from 'vitest' -import { - api, - installAutomationsPageHarness, - mocks, - refreshOnFocus, - renderPage, - RUNTIME_SELF_FILTER, - runtimeHost, - scopedList, - SELF_PRECONDITION, - settleHostQueries -} from './automations-page-test-harness' -import { listedRows } from './automations-page-listed-items' -import { makeAutomation, makeRun } from './automations-page-fixtures' - -async function openAutomationRow(container: HTMLElement, name: string): Promise { - const row = [ - ...container.querySelectorAll('[data-testid="automation-row"]') - ].find((candidate) => candidate.textContent === name) - expect(row).toBeTruthy() - await act(async () => row?.click()) - await settleHostQueries() -} - -describe('AutomationsPage selection', () => { - installAutomationsPageHarness() - - it('fetches the newly selected automation runs when the selection changes', async () => { - scopedList([ - makeAutomation({ id: 'a-1', name: 'Nightly' }), - makeAutomation({ id: 'a-2', name: 'Weekly' }) - ]) - - const { container, rerender } = await renderPage() - api.automations.listRuns.mockClear() - - mocks.state.selectedAutomationId = 'a-2' - await rerender() - await openAutomationRow(container, 'Weekly') - - // Fence history reads too so moved rows refuse rather than answer from a former host. - expect(api.automations.listRuns).toHaveBeenCalledWith({ - automationId: 'a-2', - expectedOwner: SELF_PRECONDITION, - preview: true - }) - expect(mocks.detailPane?.selected?.id).toBe('a-2') - }) -}) - -describe('AutomationsPage multi-host selection', () => { - installAutomationsPageHarness() - - it('keeps a selection that lives on another host when the window regains focus', async () => { - runtimeHost([makeAutomation({ id: 'a-remote', name: 'Remote nightly' })], []) - const desktop = makeAutomation({ id: 'a-desktop', name: 'Desktop nightly' }) - scopedList([desktop]) - api.automations.list.mockResolvedValue([desktop]) - const setSelectedAutomationId = vi.fn((id: string | null) => { - mocks.state.selectedAutomationId = id - }) - mocks.state.selectedAutomationId = 'a-remote' - mocks.state.setSelectedAutomationId = setSelectedAutomationId - - const { container, rerender } = await renderPage() - await settleHostQueries() - await refreshOnFocus() - await rerender() - - // One authority’s refresh cannot decide whether another authority’s selected row still exists. - expect(setSelectedAutomationId).not.toHaveBeenCalled() - await openAutomationRow(container, 'Remote nightly') - expect(container.querySelector('[data-testid="detail-name"]')?.textContent).toBe( - 'Remote nightly' - ) - }) - - it('shows the selected host’s runs when another authority holds the same id', async () => { - runtimeHost( - [makeAutomation({ id: 'a-1', name: 'Remote nightly' })], - [makeRun({ id: 'run-remote', automationId: 'a-1' })] - ) - // IDs can collide across authorities; desktop remains independently reachable. - api.automations.list.mockResolvedValue([makeAutomation({ id: 'a-1', name: 'Desktop nightly' })]) - api.automations.listRuns.mockResolvedValue([ - makeRun({ id: 'run-desktop', automationId: 'a-1' }) - ]) - scopedList([]) - mocks.state.automationHostFilter = RUNTIME_SELF_FILTER - mocks.state.selectedAutomationId = 'a-1' - - const { container } = await renderPage() - await settleHostQueries() - await refreshOnFocus() - await openAutomationRow(container, 'Remote nightly') - - expect(mocks.detailPane?.selected?.name).toBe('Remote nightly') - expect(mocks.detailPane?.selectedRuns.map((run) => run.id)).toEqual(['run-remote']) - }) - - it('keeps both authorities’ rows on screen and selectable under All hosts', async () => { - runtimeHost( - [makeAutomation({ id: 'a-1', name: 'Remote nightly' })], - [makeRun({ id: 'run-remote', automationId: 'a-1' })] - ) - scopedList([makeAutomation({ id: 'a-1', name: 'Desktop nightly' })]) - // The stored id names the record; only the row key can say whose copy. - mocks.state.selectedAutomationId = 'a-1' - - const { container } = await renderPage() - await settleHostQueries() - - // Two stored records, not one row and a silent drop into #44's empty state. - expect( - [...container.querySelectorAll('[data-testid="automation-row"]')].map( - (row) => row.textContent - ) - ).toEqual(['Desktop nightly', 'Remote nightly']) - - const remote = listedRows().find((row) => row.automation.name === 'Remote nightly') - await act(async () => { - mocks.listPanel?.selectAutomationRow(remote?.key ?? '') - }) - - expect(mocks.detailPane?.selected?.name).toBe('Remote nightly') - }) -}) diff --git a/src/renderer/src/components/automations/automations-page-actions-test-harness.ts b/src/renderer/src/components/automations/automations-page-actions-test-harness.ts deleted file mode 100644 index cb581cd733e..00000000000 --- a/src/renderer/src/components/automations/automations-page-actions-test-harness.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { EVERY_AGENT_CHAT } from '../../../../shared/native-chat/every-agent-chat.test-fixture' -import { - addRuntimeProject, - api, - mocks, - renderPage, - runtimeHost, - RUNTIME_ID, - RUNTIME_SELF_FILTER, - scopedList, - settleHostQueries -} from './automations-page-test-harness' -import { RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID } from './automations-page-runtime-fixtures' -import { act } from 'react' -import { expect, vi } from 'vitest' -import { checkRuntimeHooks, type HookCheckResult } from '@/runtime/repo-hooks/runtime-hooks-client' -import { loadHostStructuredAgents } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' -import { getDefaultSettings } from '../../../../shared/constants' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationDraft } from './authoring/AutomationEditorDialog' -import { - AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY as LIST_HOST_SCOPE, - AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY as OWNER_FENCING, - AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY as CREATE_IDEMPOTENCY, - AUTOMATION_SURFACE_RUNTIME_CAPABILITY, - AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY -} from '../../../../shared/automations/automation-runtime-capabilities' -import { - STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, - STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY -} from '../../../../shared/agent-session/agent-session-runtime-capabilities' -import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities' -import { makeAutomation } from './automations-page-fixtures' - -export const CHAT_CAPABILITIES = [ - LIST_HOST_SCOPE, - OWNER_FENCING, - CREATE_IDEMPOTENCY, - AUTOMATION_SURFACE_RUNTIME_CAPABILITY, - AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY, - STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, - STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, - STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY -] - -export function draftRecord(current: unknown): object { - if (current === null || typeof current !== 'object') { - throw new Error('Missing editor draft') - } - return current -} - -/** The runtime answers a create; without this the RPC double returns an empty result. */ -export function runtimeCreateReturns(automation: Automation): void { - const previous = mocks.callRuntimeRpc.getMockImplementation() - mocks.callRuntimeRpc.mockImplementation( - async (target: unknown, method: string, params: unknown, options: unknown) => { - if (method === 'automation.create') { - return { automation } - } - return await previous?.(target, method, params, options) - } - ) -} - -export async function save(): Promise { - await act(async () => { - mocks.editorDialog?.onSave() - }) -} - -export function createRpcCalls(): unknown[][] { - return mocks.callRuntimeRpc.mock.calls.filter((call) => call[1] === 'automation.create') -} - -export const REGISTERED_CHAT_CAPABILITIES = [ - ...CHAT_CAPABILITIES, - STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY -] - -export function observeRuntimeIncarnation( - runtimeId: string, - capabilities = REGISTERED_CHAT_CAPABILITIES -): void { - const status = { runtimeId, capabilities } - mocks.state.runtimeStatusByEnvironmentId = new Map([[RUNTIME_ID, { status }]]) - mocks.getRuntimeEnvironmentStatus.mockResolvedValue(status) -} - -export async function learnRuntimeAgents(runtimeId: string, agents: string[]): Promise { - const previous = mocks.callRuntimeRpc.getMockImplementation() - mocks.callRuntimeRpc.mockImplementation(async (target, method, params, options) => - method === 'agentSession.agents' - ? { agents: agents.map((agent) => ({ agent, capabilities: {} })) } - : await previous?.(target, method, params, options) - ) - try { - await loadHostStructuredAgents(`runtime:${RUNTIME_ID}`, REGISTERED_CHAT_CAPABILITIES, runtimeId) - } finally { - mocks.callRuntimeRpc.mockImplementation(previous ?? (() => ({}))) - } -} - -export async function openCreateDialogFor(projectId: string, workspaceId: string): Promise { - await act(async () => { - mocks.listPanel?.openCreateDialog() - }) - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...draftRecord(current), - name: 'Sweep', - prompt: 'Do the sweep', - projectId, - workspaceMode: 'existing', - workspaceId - })) - }) -} - -export async function holdRuntimeSave( - draft: Partial = {}, - initialAgents = ['pi'] -) { - api.automations.list.mockResolvedValue([]) - scopedList([]) - runtimeHost([], []) - addRuntimeProject() - mocks.state.settings = { ...getDefaultSettings('/tmp'), nativeChatProviders: EVERY_AGENT_CHAT } - mocks.state.automationHostFilter = RUNTIME_SELF_FILTER - observeRuntimeIncarnation('A') - await learnRuntimeAgents('A', initialAgents) - runtimeCreateReturns(makeAutomation({ id: 'a-new' })) - const held = Promise.withResolvers() - vi.mocked(checkRuntimeHooks).mockReturnValue(held.promise) - const page = await renderPage() - await settleHostQueries() - await openCreateDialogFor(RUNTIME_REPO_ID, RUNTIME_WORKSPACE_ID) - await act(async () => { - mocks.editorDialog?.onDraftChange((current) => ({ - ...draftRecord(current), - agentId: 'pi', - workspaceMode: 'new_per_run', - workspaceId: '', - ...draft - })) - }) - await save() - expect(checkRuntimeHooks).toHaveBeenCalledWith(`runtime:${RUNTIME_ID}`, RUNTIME_REPO_ID, {}) - expect(createRpcCalls()).toHaveLength(0) - return { - page, - async release() { - await act(async () => { - held.resolve({ status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false }) - }) - await settleHostQueries() - } - } -} diff --git a/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts b/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts deleted file mode 100644 index 7852a857b10..00000000000 --- a/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { Worktree } from '../../../../shared/worktree/types' -import type { AutomationHostCatalogView } from './hosts/use-automation-host-catalog' -import type { AutomationCreateDestinationControl } from './authoring/use-automation-create-destination' -import type { ExternalAutomationListEntry } from './external/external-automation-list-entries' -import type { AutomationListRow } from './listing/automation-list-row-identity' -import type { AutomationListViewItem } from './listing/automation-list-view' -import type { AutomationTemplate } from './authoring/automation-templates' - -export type ListPanelProps = { - sortedListItems: readonly AutomationListViewItem[] - selectedExternal: ExternalAutomationListEntry | null - externalActionKey: string | null - requestExternalAction: ( - manager: ExternalAutomationListEntry['manager'], - job: ExternalAutomationListEntry['job'], - action: 'run' | 'pause' | 'resume' | 'delete', - scope: ExternalAutomationListEntry['scope'] - ) => void - hasListItems: boolean - hasFilteredListItems: boolean - selectedRowKey: string | null - selectedExternalKey: string | null - hostCatalog: AutomationHostCatalogView - searchCounts: { hostRowCount: number; visibleRowCount: number; searchActive: boolean } - externalManagersUncheckedNotice: string | null - isActionEnabled: (row: AutomationListRow, action: string) => boolean - onSelectHost: (filter: unknown) => void - selectAutomationRow: (rowKey: string | null) => void - selectExternalKey: (entryKey: string | null) => void - onOpenDetail: () => void - onRefresh: () => void - onOpenRuns: () => void - runNow: (row: AutomationListRow) => void - openEditDialog: (row: AutomationListRow) => void - toggleAutomation: (row: AutomationListRow) => void - requestDeleteAutomation: (row: AutomationListRow) => void - openCreateDialog: () => void - canCreateAutomation: boolean -} - -export type EditorDialogProps = { - launchAuthority?: AutomationAuthorityRef - open: boolean - isEditing: boolean - isSaving: boolean - createDestination?: AutomationCreateDestinationControl - editDestination?: AutomationCreateDestinationControl - notice?: { message: string; recovery: string | null } | null - onNoticeRecover?: (action: string) => void - repos?: { id: string }[] - worktrees: Worktree[] - draft?: { projectId: string; workspaceId: string } - canSave?: boolean - onSave: () => void - onProjectChange: (projectId: string) => void - onDraftChange: (updater: (current: unknown) => unknown) => void - onApplyTemplate: (template: AutomationTemplate) => void -} - -export type DeleteDialogProps = { - deleteTarget: Automation | null - onConfirm: () => void -} diff --git a/src/renderer/src/components/automations/automations-page-destination-fixtures.ts b/src/renderer/src/components/automations/automations-page-destination-fixtures.ts deleted file mode 100644 index 53a9be5a2dc..00000000000 --- a/src/renderer/src/components/automations/automations-page-destination-fixtures.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { mocks, RUNTIME_ID } from './automations-page-test-harness' -import { CHAT_CAPABILITIES } from './automations-page-actions-test-harness' -import type { Repo } from '../../../../shared/repo-types' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' - -export function observeRuntimeChat(capabilities: string[] | null): void { - mocks.state.runtimeStatusByEnvironmentId = new Map( - capabilities === null ? [] : [[RUNTIME_ID, { status: { capabilities } }]] - ) -} - -export function capableChatDestination(): void { - observeRuntimeChat(CHAT_CAPABILITIES) - mocks.getRuntimeEnvironmentStatus.mockResolvedValue({ capabilities: CHAT_CAPABILITIES }) -} - -export const SSH_TARGET_ID = 'ssh-target-1' -export const SSH_REPO_ID = 'repo-ssh' -export const SSH_HOST_KEY = hostStableKey({ - authority: { kind: 'desktop' }, - selector: { kind: 'ssh', targetId: SSH_TARGET_ID } -}) - -export const DESKTOP_SELF_KEY = hostStableKey({ - authority: { kind: 'desktop' }, - selector: { kind: 'self' } -}) -export const RUNTIME_SELF_KEY = hostStableKey({ - authority: { kind: 'runtime', environmentId: RUNTIME_ID }, - selector: { kind: 'self' } -}) - -/** A desktop-registered SSH host, with the generation that makes it fenceable. */ -export function addSshHost(): void { - mocks.state.sshTargetLabels = new Map([[SSH_TARGET_ID, 'openclaw']]) - mocks.state.sshTargetGenerations = new Map([[SSH_TARGET_ID, 1]]) - mocks.state.sshConnectionStates = new Map([[SSH_TARGET_ID, { status: 'connected' }]]) -} - -/** A project checked out on that SSH host rather than locally. */ -export function addSshProject(): void { - const repo: Repo = { - id: SSH_REPO_ID, - displayName: 'orca', - path: '/repos/orca', - badgeColor: '#222222', - addedAt: 1, - worktreeBaseRef: 'main', - connectionId: SSH_TARGET_ID - } - mocks.state.repos = [...(mocks.state.repos as Repo[]), repo] - mocks.repoMap.set(SSH_REPO_ID, repo) - // The host needs a ready setup or save refuses the project before choosing a destination. - mocks.state.projectHostSetups = [ - ...mocks.state.projectHostSetups, - { - id: 'setup-ssh', - projectId: 'project-ssh', - hostId: `ssh:${SSH_TARGET_ID}`, - repoId: SSH_REPO_ID, - path: '/repos/orca', - displayName: 'orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } - ] -} diff --git a/src/renderer/src/components/automations/automations-page-fixtures.ts b/src/renderer/src/components/automations/automations-page-fixtures.ts index 9b60daacd74..02c5c2e0fd5 100644 --- a/src/renderer/src/components/automations/automations-page-fixtures.ts +++ b/src/renderer/src/components/automations/automations-page-fixtures.ts @@ -1,29 +1,14 @@ -/** Default to runnable local records so Run Now reaches its handler; cases needing refusal override the relevant fields. */ - import type { Automation } from '../../../../shared/automations/automation-definition' import type { AutomationRun, AutomationRunUsage } from '../../../../shared/automations/history/automation-run' -import type { ExternalAutomationManager } from '../../../../shared/automations/external/external-automation' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { AutomationHostCatalogEntry } from './hosts/automation-host-catalog-types' -import type { AppState } from '@/store/types' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import type { - ExternalAutomationScope, - ScopedExternalAutomationManager -} from './external/external-automation-scope-client' import { automationListRowKey, type AutomationListRow } from './listing/automation-list-row-identity' -import { ALL_AUTOMATION_HOSTS_FILTER } from '../../../../shared/automations/ownership/automation-host-filter' -import { getDefaultSettings } from '../../../../shared/constants' export const REPO_ID = 'repo-1' -export const WORKSPACE_ID = 'workspace-1' export function makeAutomation(overrides: Partial = {}): Automation { return { @@ -114,186 +99,3 @@ export function makeRunUsage(overrides: Partial = {}): Autom ...overrides } } - -export function makeExternalManager( - overrides: Partial = {} -): ExternalAutomationManager { - return { - id: 'openclaw:local', - provider: 'openclaw', - label: 'OpenClaw', - targetLabel: 'This computer', - target: { type: 'local' }, - status: 'available', - error: null, - canManage: true, - jobs: [ - { - id: 'job-1', - managerId: 'openclaw:local', - provider: 'openclaw', - name: 'OpenClaw job', - schedule: 'Daily at 09:00', - rawSchedule: '0 9 * * *', - enabled: true, - state: 'active', - prompt: null, - promptPreview: 'Sweep', - nextRunAt: null, - lastRunAt: null, - lastStatus: null, - lastError: null, - workdir: null, - runCount: 0, - runs: [] - } - ], - ...overrides - } -} - -/** The desktop-self scope every manager fixture is discovered under by default. */ -export function makeExternalAutomationScope( - overrides: Partial = {} -): ExternalAutomationScope { - return { - owner: { - authority: { kind: 'desktop' }, - selector: { kind: 'self' } - }, - provider: 'openclaw', - ...overrides - } -} - -export function makeScopedExternalManager( - overrides: Partial = {}, - scope: ExternalAutomationScope = makeExternalAutomationScope() -): ScopedExternalAutomationManager { - return { scope, manager: makeExternalManager(overrides) } -} - -function makeRepo(): Repo { - return { - id: REPO_ID, - displayName: 'orca', - path: '/repos/orca', - badgeColor: '#000000', - addedAt: 1, - worktreeBaseRef: 'main' - } -} - -/** Ready and local, so the editor can build a run context and state a Self destination. */ -function makeProjectHostSetup(): ProjectHostSetup { - return { - id: 'setup-1', - projectId: 'project-1', - hostId: 'local', - repoId: REPO_ID, - path: '/repos/orca', - displayName: 'orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } -} - -export function makeWorktree(overrides: Partial = {}): Worktree { - return { - id: WORKSPACE_ID, - repoId: REPO_ID, - displayName: 'main', - path: '/repos/orca', - branch: 'main', - head: 'abc123', - isBare: false, - isMainWorktree: true, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - ...overrides - } -} - -export type AutomationsPageFixtureState = Record & - Pick - -export type AutomationsPageStoreFixtures = { - state: AutomationsPageFixtureState - repoMap: Map - worktreeMap: Map -} - -/** A store shaped like the page's reads; actions are spies so nothing escapes the test. */ -export function makeStoreState(): AutomationsPageStoreFixtures { - const repo = makeRepo() - const worktree = makeWorktree() - const noop = (): void => undefined - return { - state: { - repos: [repo], - projectHostSetups: [makeProjectHostSetup()], - worktreesByRepo: { [REPO_ID]: [worktree] }, - unifiedTabsByWorktree: {}, - terminalLayoutsByTabId: {}, - ptyIdsByTabId: {}, - activeWorktreeId: null, - fetchWorktrees: noop, - fetchAllWorktrees: noop, - fetchRuntimeEnvironmentRepos: async () => [], - startupWorktreeRefreshCompleted: true, - updateSettings: noop, - openSettingsPage: noop, - openSettingsTarget: noop, - closeAutomationsPage: noop, - activeModal: 'none', - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - removedSshTargetLabels: new Map(), - // Hydrated absence proves no desktop SSH targets; the catalog should project only Self. - sshTargetsHydrated: true, - sshStateByEnvironment: new Map(), - runtimeEnvironments: [], - runtimeEnvironmentCatalogSettled: true, - runtimeStatusByEnvironmentId: new Map(), - automationHostFilter: ALL_AUTOMATION_HOSTS_FILTER, - setAutomationHostFilter: noop, - settings: getDefaultSettings('/tmp'), - preflightStatus: null, - preflightStatusChecked: true, - preflightStatusContextKey: null, - refreshPreflightStatus: noop, - selectedAutomationId: null, - setSelectedAutomationId: noop, - pendingAutomationRunNavigation: null, - setPendingAutomationRunNavigation: noop, - hydratePersistedUI: noop, - recordFeatureInteraction: noop, - allWorktrees: () => [worktree], - getKnownWorktreeById: () => worktree - }, - repoMap: new Map([[REPO_ID, repo]]), - worktreeMap: new Map([[WORKSPACE_ID, worktree]]) - } -} - -export type DetailPaneProps = { - selected: Automation | null - selectedHostEntry: AutomationHostCatalogEntry | null - selectedRuns: AutomationRun[] - selectedRunsNotice: { message: string } | null - runNow: (automation: Automation) => void - toggleAutomation: (automation: Automation) => void - requestDeleteAutomation: (automation: Automation) => void - openEditDialog: (automation: Automation) => void - openAutomationRunPage: (run: AutomationRun) => void - recoverSelectedRuns: (action: 'retry') => void -} diff --git a/src/renderer/src/components/automations/automations-page-listed-items.ts b/src/renderer/src/components/automations/automations-page-listed-items.ts deleted file mode 100644 index 2f64eff3037..00000000000 --- a/src/renderer/src/components/automations/automations-page-listed-items.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** Read authority-qualified row keys and render order from the mocked list panel, matching real clicks rather than synthesizing identity. */ - -import type { AutomationListRow } from './listing/automation-list-row-identity' -import type { ExternalAutomationListEntry } from './external/external-automation-list-entries' -import { mocks } from './automations-page-test-harness' - -function listedItems() { - return mocks.listPanel?.sortedListItems ?? [] -} - -/** Local rows the page listed, in render order. */ -export function listedRows(): readonly AutomationListRow[] { - return listedItems().flatMap((item) => (item.kind === 'local' ? [item.row] : [])) -} - -/** External entries the page listed, in render order. */ -export function listedExternalEntries(): readonly ExternalAutomationListEntry[] { - return listedItems().flatMap((item) => (item.kind === 'external' ? [item.entry] : [])) -} - -export function listedRow(automationId: string): AutomationListRow { - const row = listedRows().find((entry) => entry.automation.id === automationId) - if (!row) { - throw new Error(`no listed row for ${automationId}`) - } - return row -} diff --git a/src/renderer/src/components/automations/automations-page-runtime-fixtures.ts b/src/renderer/src/components/automations/automations-page-runtime-fixtures.ts deleted file mode 100644 index f35be180c75..00000000000 --- a/src/renderer/src/components/automations/automations-page-runtime-fixtures.ts +++ /dev/null @@ -1,66 +0,0 @@ -import type { AutomationsPageFixtureState } from './automations-page-fixtures' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' - -export const RUNTIME_REPO_ID = 'repo-2' -export const RUNTIME_WORKSPACE_ID = 'workspace-2' - -/** Builds the host-scoped response used by the page harness. */ -export function selfScopedList(automations: Automation[]): Record { - return { - automations, - items: automations.map((automation) => ({ - automationId: automation.id, - selector: { kind: 'self' } - })), - orphanCount: 0 - } -} - -type RuntimeFixtureMocks = { - state: AutomationsPageFixtureState - repoMap: Map - worktreeMap: Map -} - -/** Adds a runtime-owned project whose id is ambiguous in a flat repo lookup. */ -export function addRuntimeProject(mocks: RuntimeFixtureMocks, runtimeId: string): void { - const repo = { - id: RUNTIME_REPO_ID, - displayName: 'gpu-orca', - path: '/repos/gpu-orca', - badgeColor: '#111111', - addedAt: 1, - worktreeBaseRef: 'main', - executionHostId: `runtime:${runtimeId}` - } as Repo - const worktree = { - id: RUNTIME_WORKSPACE_ID, - repoId: RUNTIME_REPO_ID, - displayName: 'main', - path: '/repos/gpu-orca', - branch: 'main' - } as Worktree - const setup: ProjectHostSetup = { - id: 'setup-2', - projectId: 'project-2', - hostId: `runtime:${runtimeId}`, - repoId: RUNTIME_REPO_ID, - path: '/repos/gpu-orca', - displayName: 'gpu-orca', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } - const repos = mocks.state.repos as Repo[] - const setups = mocks.state.projectHostSetups - const worktreesByRepo = mocks.state.worktreesByRepo as Record - mocks.state.repos = [...repos, repo] - mocks.state.projectHostSetups = [...setups, setup] - mocks.state.worktreesByRepo = { ...worktreesByRepo, [RUNTIME_REPO_ID]: [worktree] } - mocks.repoMap.set(RUNTIME_REPO_ID, repo) - mocks.worktreeMap.set(RUNTIME_WORKSPACE_ID, worktree) -} diff --git a/src/renderer/src/components/automations/automations-page-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx deleted file mode 100644 index 1dbb50644f4..00000000000 --- a/src/renderer/src/components/automations/automations-page-test-harness.tsx +++ /dev/null @@ -1,399 +0,0 @@ -import type { - ListPanelProps, - EditorDialogProps, - DeleteDialogProps -} from './automations-page-child-props.test-fixture' -import { resetHostStructuredAgentsForTests } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' -import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities' -/** Record child props to test page orchestration rather than presentation. Import this harness first so shared vi.mock registrations precede AutomationsPage loading. */ - -import { act, createElement, StrictMode, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, type Mock, vi } from 'vitest' - -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' - -import { - AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY as LIST_HOST_SCOPE, - AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY as OWNER_FENCING, - AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY as CREATE_IDEMPOTENCY -} from '../../../../shared/automations/automation-runtime-capabilities' -import type { AppState } from '@/store/types' - -import { AutomationDestinationField } from './authoring/AutomationDestinationField' -import { TooltipProvider } from '@/components/ui/tooltip' - -import { resetAutomationCapabilityProbes } from './hosts/automation-capability-probe' -import { - addRuntimeProject as addRuntimeProjectFixture, - selfScopedList -} from './automations-page-runtime-fixtures' - -type AutomationsPageMocks = { - state: AutomationsPageFixtureState - repoMap: Map - worktreeMap: Map - listPanel: ListPanelProps | null - detailPane: DetailPaneProps | null - editorDialog: EditorDialogProps | null - deleteDialog: DeleteDialogProps | null - callRuntimeRpc: Mock - getRuntimeEnvironmentStatus: Mock - setAutomationHostFilter: Mock - toastError: Mock - toastSuccess: Mock - toastMessage: Mock - setPendingRunNavigation: Mock -} - -// Mock factories only close over this exported binding; vi.hoisted bindings cannot be exported. -export const mocks: AutomationsPageMocks = { - state: { repos: [], projectHostSetups: [], worktreesByRepo: {} }, - repoMap: new Map(), - worktreeMap: new Map(), - listPanel: null, - detailPane: null, - editorDialog: null, - deleteDialog: null, - callRuntimeRpc: vi.fn(), - getRuntimeEnvironmentStatus: vi.fn(), - setAutomationHostFilter: vi.fn(), - toastError: vi.fn(), - toastSuccess: vi.fn(), - toastMessage: vi.fn(), - setPendingRunNavigation: vi.fn() -} - -vi.mock('@/store/index', () => { - const useAppStore = (selector: (state: Partial) => unknown): unknown => - selector(mocks.state as Partial) - useAppStore.getState = (): Partial => mocks.state as Partial - return { useAppStore } -}) - -vi.mock('@/store/repos/use-repository-catalog', () => ({ - useRepoMap: () => mocks.repoMap -})) -vi.mock('@/store/slices/worktrees/listing/use-worktree-catalog', () => ({ - useWorktreeMap: () => mocks.worktreeMap -})) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: (...args: unknown[]) => mocks.callRuntimeRpc(...args) -})) -vi.mock('@/runtime/rpc/compatibility/runtime-compatibility-probe', () => ({ - getRuntimeEnvironmentStatus: (...args: unknown[]) => mocks.getRuntimeEnvironmentStatus(...args) -})) - -vi.mock('sonner', () => ({ - toast: { - error: (...args: unknown[]) => mocks.toastError(...args), - success: (...args: unknown[]) => mocks.toastSuccess(...args), - message: (...args: unknown[]) => mocks.toastMessage(...args) - } -})) - -vi.mock('@/lib/window-activity/window-visibility-interval', () => ({ - installWindowVisibilityInterval: () => () => undefined -})) - -vi.mock('@/components/contextual-tours/use-contextual-tour', () => ({ - useContextualTour: () => undefined -})) - -vi.mock('@/components/ui/tooltip', () => ({ - TooltipProvider: ({ children }: { children: ReactNode }) => <>{children}, - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: () => null -})) - -vi.mock('@/runtime/repo-hooks/runtime-hooks-client', () => ({ - checkRuntimeHooks: vi.fn(async () => ({ hooks: null, ok: true })) -})) - -vi.mock('@/runtime/repo-hooks/ensure-hooks-confirmed', () => ({ - ensureHooksConfirmed: vi.fn(async () => 'inherit'), - ensureHooksApproved: vi.fn(async () => ({ decision: 'run' })) -})) - -vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ - activateAndRevealWorktree: vi.fn() -})) - -vi.mock('./listing/AutomationsListPanel', () => ({ - AutomationsListPanel: (props: ListPanelProps) => { - const selectAutomationRow = (rowKey: string | null): void => { - props.selectAutomationRow(rowKey) - props.onOpenDetail() - } - mocks.listPanel = { ...props, selectAutomationRow } - return ( -
- - {props.sortedListItems.map((item) => - item.kind === 'local' ? ( - - ) : ( - - ) - )} - {props.hasListItems ? null :
} -
- ) - } -})) - -vi.mock('./details/AutomationsDetailPane', () => ({ - AutomationsDetailPane: (props: DetailPaneProps) => { - mocks.detailPane = props - return ( -
- {props.selected?.name ?? 'none'} - {props.selectedRuns.length} -
- ) - } -})) - -vi.mock('./authoring/AutomationEditorDialog', () => ({ - AutomationEditorDialog: (props: EditorDialogProps) => { - mocks.editorDialog = props - return ( -
- {props.open ? 'open' : 'closed'} - {props.open && props.editDestination ? ( - - - - - ) : null} -
- ) - } -})) - -vi.mock('./authoring/AutomationDeleteDialogs', () => ({ - AutomationDeleteDialog: (props: DeleteDialogProps) => { - mocks.deleteDialog = props - return null - }, - ExternalAutomationDeleteDialog: () => null -})) - -import AutomationsPage from './AutomationsPage' -import { - makeAutomation, - makeRun, - makeStoreState, - type AutomationsPageFixtureState, - type DetailPaneProps -} from './automations-page-fixtures' - -function mockGroup(...names: K[]): Record { - return Object.fromEntries(names.map((name) => [name, vi.fn()])) as Record -} - -export const api = { - automations: mockGroup( - 'list', - 'listRuns', - 'create', - 'update', - 'delete', - 'runNow', - 'listScoped', - 'listExternalManagerForOwner', - 'runExternalActionForOwner', - 'retainExternalScopes' - ), - ssh: mockGroup('listTargets', 'connect'), - runtimeEnvironments: mockGroup('connect'), - ui: mockGroup('get') -} - -/** The precondition a Desktop + Self row captures; every fenced request repeats it. */ -export const SELF_PRECONDITION = { selector: { kind: 'self' } } -/** The owner the catalog projects for Desktop + Self, which every scoped call names. */ -export const DESKTOP_SELF_OWNER = { authority: { kind: 'desktop' }, selector: { kind: 'self' } } - -export const RUNTIME_ID = 'gpu' -/** A runtime that advertises both automation capabilities, so its rows carry owners. */ -const RUNTIME_CAPABILITIES = [LIST_HOST_SCOPE, OWNER_FENCING, CREATE_IDEMPOTENCY] -export const RUNTIME_SELF_FILTER = { - kind: 'host' as const, - host: { - authority: { kind: 'runtime' as const, environmentId: RUNTIME_ID }, - selector: { kind: 'self' as const } - } -} - -/** Serve desktop-local RPCs from the programmable API mocks and runtime-target RPCs from runtimeHost state. */ -async function answerAutomationRpc( - target: unknown, - method: string, - params?: unknown -): Promise { - if ((target as { kind?: string } | null)?.kind === 'environment') { - const answers = mocks.state.runtimeAnswers as - | { automations: Automation[]; runs: AutomationRun[] } - | undefined - if (method === 'automation.list') { - return selfScopedList(answers?.automations ?? []) - } - return method === 'automation.runs' ? { runs: answers?.runs ?? [] } : {} - } - const args = params as Record | undefined - switch (method) { - case 'automation.list': - return args?.selector - ? await api.automations.listScoped({ selector: args.selector }) - : { automations: await api.automations.list() } - case 'automation.runs': - return { runs: await api.automations.listRuns(args) } - case 'automation.create': - return { automation: await api.automations.create(args) } - case 'automation.update': - return { automation: await api.automations.update(args) } - case 'automation.delete': - return await api.automations.delete(args).then(() => ({})) - case 'automation.runNow': - return { run: await api.automations.runNow(args) } - default: - return {} - } -} - -/** Puts a reachable, capable second authority in the catalog and answers for it. */ -export function runtimeHost(automations: Automation[], runs: AutomationRun[]): void { - mocks.state.runtimeEnvironments = [ - { id: RUNTIME_ID, name: 'GPU box', createdAt: 1, pairingRevision: 4 } - ] - mocks.state.runtimeStatusByEnvironmentId = new Map([ - [RUNTIME_ID, { status: { capabilities: RUNTIME_CAPABILITIES } }] - ]) - mocks.getRuntimeEnvironmentStatus.mockResolvedValue({ capabilities: RUNTIME_CAPABILITIES }) - mocks.state.runtimeAnswers = { automations, runs } -} - -export const addRuntimeProject = (): void => addRuntimeProjectFixture(mocks, RUNTIME_ID) - -/** Answers the host-scoped read, which is where the list's rows and owners come from. */ -export function scopedList(automations: Automation[]): void { - api.automations.listScoped.mockResolvedValue(selfScopedList(automations)) -} - -const roots: Root[] = [] - -export async function renderPage(options?: { strict?: boolean }): Promise<{ - container: HTMLDivElement - rerender: () => Promise -}> { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - roots.push(root) - const rerender = async (): Promise => { - await act(async () => { - // StrictMode doubles effects to expose dispose-without-revive controller bugs. - const page = options?.strict - ? createElement(StrictMode, null, createElement(AutomationsPage)) - : createElement(AutomationsPage) - root.render(page) - }) - } - await rerender() - return { container, rerender } -} - -/** Lets the per-host queries, their capability probes, and the history read settle. */ -export async function settleHostQueries(): Promise { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 0)) - }) -} - -/** The alt-tab-back trigger: one of the two events bound to the page refresh. */ -export async function refreshOnFocus(): Promise { - await act(async () => { - window.dispatchEvent(new Event('focus')) - await new Promise((resolve) => setTimeout(resolve, 0)) - }) -} - -export function rows(container: HTMLElement, testId: string): string[] { - return [...container.querySelectorAll(`[data-testid="${testId}"]`)].map( - (node) => node.textContent ?? '' - ) -} - -/** Registers the per-case store reset and renderer cleanup for the current suite. */ -export function installAutomationsPageHarness(): void { - beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - vi.clearAllMocks() - setLocalRuntimeCapabilitiesForTests([]) - // Confirmed capabilities are module-level and must not leak between tests. - resetAutomationCapabilityProbes() - resetHostStructuredAgentsForTests() - // A prior test's wholesale mockImplementation must not leak forward. - mocks.callRuntimeRpc.mockReset() - mocks.callRuntimeRpc.mockImplementation(answerAutomationRpc) - mocks.listPanel = null - mocks.detailPane = null - mocks.editorDialog = null - mocks.deleteDialog = null - const fixtures = makeStoreState() - mocks.state = fixtures.state - mocks.state.folderWorkspaces = [] - mocks.state.setAutomationHostFilter = mocks.setAutomationHostFilter - mocks.repoMap = fixtures.repoMap - mocks.worktreeMap = fixtures.worktreeMap - api.automations.list.mockResolvedValue([makeAutomation()]) - api.automations.listRuns.mockResolvedValue([]) - api.automations.listExternalManagerForOwner.mockResolvedValue({ - manager: null, - error: null, - updatedAt: 0 - }) - api.automations.retainExternalScopes.mockResolvedValue(undefined) - api.automations.listScoped.mockResolvedValue(selfScopedList([makeAutomation()])) - api.automations.create.mockResolvedValue(makeAutomation()) - api.automations.update.mockResolvedValue(makeAutomation()) - api.automations.delete.mockResolvedValue(undefined) - api.automations.runNow.mockResolvedValue(makeRun()) - api.ui.get.mockResolvedValue({}) - // @ts-expect-error test window mock - globalThis.window.api = api - }) - - afterEach(async () => { - await act(async () => { - roots.splice(0).forEach((root) => root.unmount()) - }) - document.body.innerHTML = '' - setLocalRuntimeCapabilitiesForTests(null) - }) -} diff --git a/src/shared/__fixtures__/grok-inline-startup-pty-trace.ts b/src/shared/__fixtures__/grok-inline-startup-pty-trace.ts deleted file mode 100644 index 97846def799..00000000000 --- a/src/shared/__fixtures__/grok-inline-startup-pty-trace.ts +++ /dev/null @@ -1,124 +0,0 @@ -import type { GrokStartupTraceChunk } from './grok-startup-pty-trace' - -/** - * Recorded PTY output of `grok --no-alt-screen`, grok's inline (non - * alternate-screen) rendering mode — also reachable via `--minimal` and - * `[ui] screen_mode = "minimal"` in ~/.grok/config.toml. - * - * Recorded from: grok 1.0.0 (3cd0d0cbcebe) [stable] on macOS (darwin 25.3.0), - * xterm-256color 120x30 via node-pty, cwd = an Orca git worktree, 10s of output - * from spawn. - * - * This mode emits NO alternate-screen switch, so the composer-glyph marker never - * anchors and the 2004-anchored quiet window is the only delivery path. Elision - * follows the alt-screen fixture: entries without `data` are marker-free render - * frames kept only as timestamp + byte count. - */ -export const GROK_INLINE_STARTUP_PTY_TRACE: GrokStartupTraceChunk[] = [ - { - t: 279, - data: '\u001b]0;grok\u0007\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1015h\u001b[?1006h\u001b[?1004h\u001b[?2004h\u001b[?25l\u001b]12;rgb:c8/c8' - }, - { t: 279, bytes: 8 }, - { t: 2280, bytes: 11 }, - { t: 2587, bytes: 5 }, - { t: 2612, bytes: 825 }, - { t: 2612, bytes: 925 }, - { t: 2612, bytes: 928 }, - { t: 2612, bytes: 958 }, - { t: 2612, bytes: 810 }, - { t: 2613, bytes: 1000 }, - { - t: 2613, - data: ';80;80;88;48;2;20;20;20m╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\u001b[39;48;2;20;20;20m \u001b[26;1H \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;200;200;200;48;2;20;20;20m❯ \u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[39;48;2;20;20;20m \u001b[27;1H \u001b[38;2;80;80;88;48;2;20;20;20m╰─────────────────────────────────────────────────────────────────────────────── \u001b[38;2;128;128;128;48;2;20;20;20mGrok 4.' - }, - { - t: 2613, - data: '5 (high)\u001b[38;2;88;88;88;48;2;20;20;20m · \u001b[38;2;108;108;108;48;2;20;20;20malways-approve\u001b[38;2;80;80;88;48;2;20;20;20m ─╯\u001b[39;48;2;20;20;20m \u001b[28;1H \u001b[29;1H \u001b[38;2;108;108;108;48;2;20;20;20m[stable]\u001b[39;48;2;20;20;20m \u001b[30;1H \u001b[39m\u001b[49m\u001b[59m\u001b[0m\u001b[26;7H\u001b[?25h\u001b[?2026l' - }, - { t: 2614, bytes: 169 }, - { t: 2676, bytes: 158 }, - { t: 2697, bytes: 158 }, - { t: 2772, bytes: 586 }, - { t: 2781, bytes: 410 }, - { t: 2866, bytes: 971 }, - { t: 2866, bytes: 69 }, - { t: 2878, bytes: 970 }, - { t: 2878, bytes: 308 }, - { t: 2951, bytes: 970 }, - { t: 2951, bytes: 784 }, - { t: 3036, bytes: 970 }, - { t: 3036, bytes: 968 }, - { t: 3036, bytes: 417 }, - { t: 3121, bytes: 948 }, - { t: 3121, bytes: 954 }, - { t: 3121, bytes: 792 }, - { t: 3207, bytes: 966 }, - { t: 3207, bytes: 964 }, - { t: 3207, bytes: 837 }, - { t: 3291, bytes: 970 }, - { t: 3291, bytes: 966 }, - { t: 3291, bytes: 956 }, - { t: 3291, bytes: 195 }, - { t: 3376, bytes: 968 }, - { t: 3376, bytes: 962 }, - { t: 3376, bytes: 785 }, - { t: 3461, bytes: 944 }, - { t: 3461, bytes: 912 }, - { t: 3461, bytes: 79 }, - { t: 3546, bytes: 962 }, - { t: 3546, bytes: 568 }, - { t: 3630, bytes: 839 }, - { t: 3630, bytes: 40 }, - { t: 3715, bytes: 424 }, - { t: 3800, bytes: 168 }, - { t: 3885, bytes: 218 }, - { t: 4139, bytes: 219 }, - { t: 4394, bytes: 219 }, - { t: 4732, bytes: 219 }, - { t: 5582, bytes: 219 }, - { t: 5922, bytes: 219 }, - { t: 6177, bytes: 219 }, - { t: 6432, bytes: 219 }, - { t: 6602, bytes: 219 }, - { t: 6686, bytes: 158 }, - { t: 6771, bytes: 410 }, - { t: 6857, bytes: 878 }, - { t: 6857, bytes: 463 }, - { t: 6941, bytes: 970 }, - { t: 6941, bytes: 718 }, - { t: 7026, bytes: 970 }, - { t: 7026, bytes: 968 }, - { t: 7026, bytes: 292 }, - { t: 7110, bytes: 964 }, - { t: 7110, bytes: 962 }, - { t: 7110, bytes: 549 }, - { t: 7195, bytes: 964 }, - { t: 7195, bytes: 969 }, - { t: 7195, bytes: 967 }, - { t: 7195, bytes: 306 }, - { t: 7279, bytes: 970 }, - { t: 7279, bytes: 968 }, - { t: 7279, bytes: 961 }, - { t: 7279, bytes: 103 }, - { t: 7364, bytes: 968 }, - { t: 7364, bytes: 956 }, - { t: 7364, bytes: 795 }, - { t: 7449, bytes: 964 }, - { t: 7450, bytes: 962 }, - { t: 7450, bytes: 316 }, - { t: 7535, bytes: 954 }, - { t: 7535, bytes: 550 }, - { t: 7621, bytes: 960 }, - { t: 7621, bytes: 94 }, - { t: 7704, bytes: 438 }, - { t: 7789, bytes: 168 }, - { t: 7874, bytes: 83 }, - { t: 8043, bytes: 219 }, - { t: 8381, bytes: 219 }, - { t: 8635, bytes: 219 }, - { t: 8890, bytes: 219 }, - { t: 9144, bytes: 219 }, - { t: 9398, bytes: 219 }, - { t: 9738, bytes: 219 } -] diff --git a/src/shared/__fixtures__/grok-startup-pty-trace.ts b/src/shared/__fixtures__/grok-startup-pty-trace.ts deleted file mode 100644 index c8b23c0d5ad..00000000000 --- a/src/shared/__fixtures__/grok-startup-pty-trace.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Recorded PTY output of a `grok` launch, used to pin when the draft-paste - * readiness scanner would deliver a launch draft. - * - * Recorded from: grok 1.0.0 (3cd0d0cbcebe) [stable] on macOS (darwin 25.3.0), - * xterm-256color 120x30 via node-pty, cwd = an Orca git worktree, 10s of output - * from spawn. - * - * Entries without `data` are grok logo-shimmer render frames, verified to hold - * none of DECSET 1049h / 2004h, DECTCEM show-cursor, or the composer glyphs - * U+276F / U+203A. Only their timestamp and byte count are kept so the fixture - * stays small; the replay substitutes filler of the recorded length. Timings are - * what the scanner reacts to, so they are preserved verbatim. - */ -export type GrokStartupTraceChunk = { - /** ms after spawn */ - t: number - data?: string - /** Length of an elided, marker-free animation frame. */ - bytes?: number -} - -export const GROK_STARTUP_PTY_TRACE: GrokStartupTraceChunk[] = [ - { - t: 274, - data: '\u001b]0;grok\u0007\u001b[?1049h\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1015h\u001b[?1006h\u001b[?1004h\u001b[?2004h\u001b[?25l' - }, - { t: 274, bytes: 18 }, - { t: 582, bytes: 5 }, - { t: 607, bytes: 825 }, - { t: 607, bytes: 925 }, - { t: 607, bytes: 928 }, - { t: 607, bytes: 958 }, - { t: 607, bytes: 810 }, - { t: 607, bytes: 1000 }, - { - t: 607, - data: ';80;80;88;48;2;20;20;20m╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\u001b[39;48;2;20;20;20m \u001b[26;1H \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;200;200;200;48;2;20;20;20m❯ \u001b[38;2;225;225;225;48;2;20;20;20m \u001b[38;2;80;80;88;48;2;20;20;20m│\u001b[39;48;2;20;20;20m \u001b[27;1H \u001b[38;2;80;80;88;48;2;20;20;20m╰─────────────────────────────────────────────────────────────────────────────── \u001b[38;2;128;128;128;48;2;20;20;20mGrok 4.' - }, - { - t: 607, - data: '5 (high)\u001b[38;2;88;88;88;48;2;20;20;20m · \u001b[38;2;108;108;108;48;2;20;20;20malways-approve\u001b[38;2;80;80;88;48;2;20;20;20m ─╯\u001b[39;48;2;20;20;20m \u001b[28;1H \u001b[29;1H \u001b[38;2;108;108;108;48;2;20;20;20m[stable]\u001b[39;48;2;20;20;20m \u001b[30;1H \u001b[39m\u001b[49m\u001b[59m\u001b[0m\u001b[26;7H\u001b[?25h\u001b[?2026l' - }, - { t: 613, bytes: 169 }, - { t: 664, bytes: 158 }, - { t: 691, bytes: 158 }, - { t: 762, bytes: 410 }, - { t: 776, bytes: 586 }, - { t: 861, bytes: 971 }, - { t: 861, bytes: 69 }, - { t: 945, bytes: 970 }, - { t: 945, bytes: 784 }, - { t: 1031, bytes: 970 }, - { t: 1031, bytes: 968 }, - { t: 1031, bytes: 417 }, - { t: 1109, bytes: 948 }, - { t: 1110, bytes: 954 }, - { t: 1110, bytes: 792 }, - { t: 1115, bytes: 972 }, - { t: 1115, bytes: 968 }, - { t: 1115, bytes: 336 }, - { t: 1200, bytes: 964 }, - { t: 1200, bytes: 964 }, - { t: 1200, bytes: 962 }, - { t: 1200, bytes: 62 }, - { t: 1286, bytes: 970 }, - { t: 1286, bytes: 966 }, - { t: 1286, bytes: 956 }, - { t: 1286, bytes: 195 }, - { t: 1370, bytes: 968 }, - { t: 1370, bytes: 962 }, - { t: 1370, bytes: 785 }, - { t: 1455, bytes: 944 }, - { t: 1455, bytes: 912 }, - { t: 1455, bytes: 79 }, - { t: 1540, bytes: 962 }, - { t: 1540, bytes: 568 }, - { t: 1625, bytes: 839 }, - { t: 1625, bytes: 40 }, - { t: 1710, bytes: 424 }, - { t: 1795, bytes: 168 }, - { t: 1879, bytes: 218 }, - { t: 2134, bytes: 219 }, - { t: 2389, bytes: 219 }, - { t: 2728, bytes: 219 }, - { t: 3579, bytes: 219 }, - { t: 3918, bytes: 219 }, - { t: 4172, bytes: 219 }, - { t: 4425, bytes: 219 }, - { t: 4594, bytes: 219 }, - { t: 4680, bytes: 158 }, - { t: 4764, bytes: 410 }, - { t: 4850, bytes: 878 }, - { t: 4850, bytes: 463 }, - { t: 4934, bytes: 970 }, - { t: 4934, bytes: 718 }, - { t: 5019, bytes: 970 }, - { t: 5019, bytes: 968 }, - { t: 5019, bytes: 292 }, - { t: 5103, bytes: 964 }, - { t: 5103, bytes: 962 }, - { t: 5103, bytes: 549 }, - { t: 5188, bytes: 964 }, - { t: 5188, bytes: 969 }, - { t: 5188, bytes: 967 }, - { t: 5188, bytes: 306 }, - { t: 5272, bytes: 970 }, - { t: 5272, bytes: 968 }, - { t: 5272, bytes: 961 }, - { t: 5272, bytes: 103 }, - { t: 5358, bytes: 968 }, - { t: 5358, bytes: 956 }, - { t: 5358, bytes: 795 }, - { t: 5442, bytes: 964 }, - { t: 5442, bytes: 962 }, - { t: 5442, bytes: 316 }, - { t: 5527, bytes: 954 }, - { t: 5527, bytes: 550 }, - { t: 5612, bytes: 960 }, - { t: 5612, bytes: 94 }, - { t: 5696, bytes: 438 }, - { t: 5781, bytes: 168 }, - { t: 5866, bytes: 83 }, - { t: 6120, bytes: 219 }, - { t: 6375, bytes: 219 }, - { t: 6631, bytes: 219 }, - { t: 6884, bytes: 219 }, - { t: 7139, bytes: 219 }, - { t: 7393, bytes: 219 }, - { t: 7732, bytes: 219 }, - { t: 8580, bytes: 219 }, - { t: 8664, bytes: 158 }, - { t: 8750, bytes: 410 }, - { t: 8835, bytes: 796 }, - { t: 8919, bytes: 908 }, - { t: 8919, bytes: 861 }, - { t: 9004, bytes: 966 }, - { t: 9004, bytes: 894 }, - { t: 9090, bytes: 970 }, - { t: 9090, bytes: 968 }, - { t: 9090, bytes: 768 }, - { t: 9175, bytes: 964 }, - { t: 9175, bytes: 969 }, - { t: 9175, bytes: 967 }, - { t: 9175, bytes: 306 }, - { t: 9260, bytes: 970 }, - { t: 9260, bytes: 968 }, - { t: 9260, bytes: 958 }, - { t: 9260, bytes: 291 }, - { t: 9344, bytes: 960 }, - { t: 9344, bytes: 956 }, - { t: 9344, bytes: 605 }, - { t: 9430, bytes: 952 }, - { t: 9430, bytes: 936 }, - { t: 9430, bytes: 377 }, - { t: 9515, bytes: 960 }, - { t: 9515, bytes: 775 }, - { t: 9600, bytes: 914 }, - { t: 9600, bytes: 427 }, - { t: 9684, bytes: 618 }, - { t: 9770, bytes: 180 }, - { t: 9855, bytes: 219 } -] diff --git a/src/shared/bundled-skill-summary.test.ts b/src/shared/bundled-skill-summary.test.ts deleted file mode 100644 index 8b40536315d..00000000000 --- a/src/shared/bundled-skill-summary.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { BundledSkillOp, BundledSkillPlan } from './bundled-skill-plan' -import { bundledSkillNudgeKey, summarizeBundledSkillPlan } from './bundled-skill-summary' - -const folder = { kind: 'folder', entries: ['SKILL.md:file'], skillDigest: 'a'.repeat(64) } as const - -function op(fields: Partial): BundledSkillOp { - return { - kind: 'keep', - path: '/home/me/.agents/skills/x', - role: 'shared', - agents: [], - observed: folder, - cleanup: [], - ...fields - } -} - -/** A plan as a paired server returns it: planned on the server's disk against the server's own bundle. */ -const serverPlan = (ops: BundledSkillOp[]): BundledSkillPlan => ({ - scope: 'global', - homeDirectory: '/home/me', - skills: [{ name: 'orca-cli', digest: 'b'.repeat(64), ops }], - planDigest: 'c'.repeat(64) -}) - -describe('another Orca build’s copy in a planned host’s plan', () => { - it('reads as current and is never offered as an update', () => { - const plan = serverPlan([ - op({ kind: 'leave', reason: 'other-build', replaceable: true }), - op({ - path: '/home/me/.claude/skills/x', - role: 'agent', - observed: { kind: 'link', target: 'x' } - }) - ]) - - expect(summarizeBundledSkillPlan(plan)).toMatchObject({ - badge: null, - hasWork: false, - skills: [{ name: 'orca-cli', state: 'current' }] - }) - expect(bundledSkillNudgeKey('runtime:server-1', plan)).toBeNull() - }) -}) diff --git a/src/shared/claimed-agent-pty-owner.test.ts b/src/shared/claimed-agent-pty-owner.test.ts index b68e5bb8554..fef6c28b025 100644 --- a/src/shared/claimed-agent-pty-owner.test.ts +++ b/src/shared/claimed-agent-pty-owner.test.ts @@ -1,12 +1,9 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import type { AgentSessionExecutionClaim, AgentSessionSurfaceBinding } from './agent-session/agent-session-host-authority' -import { - ClaimedAgentPtyOwnerRegistry, - MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES -} from './claimed-agent-pty-owner' +import { ClaimedAgentPtyOwnerRegistry } from './claimed-agent-pty-owner' function claim( identityDigest = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', @@ -49,25 +46,7 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { ).rejects.toThrow('agent_session_conflict') }) - it('does not find an owner through another worktree scope', async () => { - const registry = new ClaimedAgentPtyOwnerRegistry() - await registry.ensure({ - claim: claim(), - surface, - spawn: async () => ({ ptyId: 'pty-1' }) - }) - - expect( - registry.find( - claim( - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - 'ccccccccccccccccccccccccccccccccccccccccccc' - ) - ) - ).toBeNull() - }) - - it('generation-guards release across a replacement owner', async () => { + it('ignores a stale release generation and releases the matching owner', async () => { const registry = new ClaimedAgentPtyOwnerRegistry() const first = await registry.ensure({ claim: claim(), @@ -76,7 +55,7 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { }) registry.release('pty-1', 'stale-generation') - expect(registry.find(claim())?.generation).toBe(first.owner.generation) + expect(registry.find(claim())).toMatchObject({ ptyId: 'pty-1' }) registry.release('pty-1', first.owner.generation) expect(registry.find(claim())).toBeNull() @@ -134,70 +113,6 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { }) }) - it('rejects a recovered owner that reuses only one half of its generation identity', () => { - const registry = new ClaimedAgentPtyOwnerRegistry() - const owner = { - claim: claim(), - generation: 'generation-1', - phase: 'live' as const, - ptyId: 'pty-1', - surface - } - registry.register(owner) - - expect(() => registry.register({ ...owner, ptyId: 'pty-2' })).toThrow('agent_session_conflict') - expect(() => registry.register({ ...owner, generation: 'generation-2' })).toThrow( - 'agent_session_conflict' - ) - }) - - it('retains only allowlisted owner fields', () => { - const registry = new ClaimedAgentPtyOwnerRegistry() - const owner = { - claim: { ...claim(), unknownPayload: 'claim payload' }, - generation: 'generation-1', - phase: 'live' as const, - ptyId: 'pty-1', - surface: { ...surface, unknownPayload: 'surface payload' }, - unknownPayload: 'owner payload' - } - - registry.register(owner) - - expect(registry.list()).toEqual([ - { - claim: claim(), - generation: 'generation-1', - phase: 'live', - ptyId: 'pty-1', - surface - } - ]) - }) - - it('fails closed when recovered owner evidence reaches the process-wide cap', () => { - const registry = new ClaimedAgentPtyOwnerRegistry() - const owners = Array.from({ length: MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES }, (_, index) => ({ - claim: claim(`identity-${index}`), - generation: `generation-${index}`, - phase: 'live' as const, - ptyId: `pty-${index}`, - surface - })) - registry.reconcileAuthoritative(owners) - - expect(() => - registry.register({ - claim: claim('one-more-identity'), - generation: 'one-more-generation', - phase: 'live', - ptyId: 'one-more-pty', - surface - }) - ).toThrow('execution_owner_unavailable') - expect(registry.list()).toHaveLength(MAX_CLAIMED_AGENT_PTY_OWNER_ENTRIES) - }) - it('atomically converges from conflicting provider evidence to one owner', async () => { const registry = new ClaimedAgentPtyOwnerRegistry() const ownerA = { @@ -226,7 +141,10 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { spawn: async () => ({ ptyId: 'unexpected' }), isLive: (owner) => owner.generation === ownerB.generation }) - ).resolves.toMatchObject({ disposition: 'adopted', owner: ownerB }) + ).resolves.toMatchObject({ + disposition: 'adopted', + owner: { ptyId: 'pty-b', generation: 'generation-b' } + }) }) it('prunes an advertised generation when an authoritative snapshot omits it', async () => { @@ -241,12 +159,11 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { registry.reconcileAuthoritative([recovered]) registry.reconcileAuthoritative([]) - const spawn = vi.fn(async () => ({ ptyId: 'pty-new' })) + const spawn = async () => ({ ptyId: 'pty-new' }) await expect(registry.ensure({ claim: claim(), surface, spawn })).resolves.toMatchObject({ disposition: 'created', owner: { ptyId: 'pty-new' } }) - expect(spawn).toHaveBeenCalledOnce() }) it('replaces a reused PTY id with the exact newly advertised generation', async () => { @@ -261,7 +178,7 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { const newOwner = { ...oldOwner, generation: 'generation-new' } registry.reconcileAuthoritative([oldOwner]) registry.reconcileAuthoritative([newOwner]) - const isLive = vi.fn((owner: typeof newOwner) => owner.generation === 'generation-new') + const isLive = (owner: typeof newOwner) => owner.generation === 'generation-new' await expect( registry.ensure({ @@ -270,27 +187,32 @@ describe('ClaimedAgentPtyOwnerRegistry', () => { spawn: async () => ({ ptyId: 'unexpected' }), isLive }) - ).resolves.toMatchObject({ disposition: 'adopted', owner: newOwner }) - expect(isLive).toHaveBeenCalledWith(expect.objectContaining({ generation: 'generation-new' })) + ).resolves.toMatchObject({ + disposition: 'adopted', + owner: { ptyId: 'pty-reused', generation: 'generation-new' } + }) }) it('does not let reconciliation erase an in-flight reservation', async () => { const registry = new ClaimedAgentPtyOwnerRegistry() let finish!: (result: { ptyId: string }) => void - const spawn = vi.fn( - () => - new Promise<{ ptyId: string }>((resolve) => { - finish = resolve - }) - ) + const spawn = () => + new Promise<{ ptyId: string }>((resolve) => { + finish = resolve + }) const first = registry.ensure({ claim: claim(), surface, spawn }) registry.reconcileAuthoritative([]) const second = registry.ensure({ claim: claim(), surface, spawn }) finish({ ptyId: 'pty-reserved' }) - await expect(first).resolves.toMatchObject({ disposition: 'created' }) - await expect(second).resolves.toMatchObject({ disposition: 'adopted' }) - expect(spawn).toHaveBeenCalledOnce() + await expect(first).resolves.toMatchObject({ + disposition: 'created', + owner: { ptyId: 'pty-reserved' } + }) + await expect(second).resolves.toMatchObject({ + disposition: 'adopted', + owner: { ptyId: 'pty-reserved' } + }) }) }) diff --git a/src/shared/claude-model-list-probe.test.ts b/src/shared/claude-model-list-probe.test.ts index eaea828e014..db107053d41 100644 --- a/src/shared/claude-model-list-probe.test.ts +++ b/src/shared/claude-model-list-probe.test.ts @@ -13,35 +13,9 @@ function controlResponseLine(models: unknown[]): string { } describe('parseClaudeModelList', () => { - it('skips init noise, CRLF endings, and duplicate values', () => { - const stdout = - '{"type":"system","subtype":"init","model":"claude-sonnet-5"}\r\n' + - 'not json at all\r\n' + - `${controlResponseLine([ - { value: 'sonnet', displayName: 'Sonnet' }, - { value: 'sonnet', displayName: 'Sonnet (duplicate)' }, - { value: ' ', displayName: 'Blank' } - ])}\r\n` - expect(parseClaudeModelList(stdout)).toEqual([ - { id: 'sonnet', label: 'Sonnet', effortLevels: [], supportsFastMode: false } - ]) - }) - it('drops the disabled placeholder row the CLI advertises for a model it cannot run', () => { - // Captured from `claude` 2.1.237: Fable 5.1 is announced but gated on 2.1.255+. const parsed = parseClaudeModelList( - controlResponseLine([ - { value: 'sonnet', displayName: 'Sonnet' }, - { - value: 'cc-update-required-1', - resolvedModel: 'cc-update-required-1', - displayName: 'Fable 5.1 (disabled)', - description: 'Update to 2.1.255+ to use Fable 5.1', - supportsEffort: true, - supportedEffortLevels: ['low', 'medium', 'high', 'xhigh', 'max'], - disabled: true - } - ]) + controlResponseLine([{ value: 'sonnet' }, { value: 'disabled-model', disabled: true }]) ) expect(parsed.map(({ id }) => id)).toEqual(['sonnet']) }) diff --git a/src/shared/codex-subagent-transcript.test.ts b/src/shared/codex-subagent-transcript.test.ts index e9a32e51af2..4604e638382 100644 --- a/src/shared/codex-subagent-transcript.test.ts +++ b/src/shared/codex-subagent-transcript.test.ts @@ -1,20 +1,13 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createCodexSubagentTranscriptState, - hasTrackedCodexTranscriptSubagents, reconcileCodexSubagentTranscript } from './codex-subagent-transcript' -import { - codexRosterToSnapshots, - queueCodexSubagentIdentity, - retryPendingCodexSubagentIdentities, - upsertCodexSubagent, - type CodexSubagentRoster -} from './codex-subagent-roster' +import { codexRosterToSnapshots, type CodexSubagentRoster } from './codex-subagent-roster' const CHILD_ID = '019fa65f-3144-7151-9c02-cff7a28f316f' @@ -52,47 +45,10 @@ describe('Codex subagent transcript reconciliation', () => { dirs.length = 0 }) - it('adds a child from the parent rollout and removes it after task completion', () => { - const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-')) - dirs.push(dir) - const parentPath = join(dir, 'rollout-parent.jsonl') - const childPath = join(dir, `rollout-child-${CHILD_ID}.jsonl`) - writeFileSync(parentPath, jsonl([activity('started')])) - writeFileSync(childPath, jsonl([{ type: 'event_msg', payload: { type: 'task_started' } }])) - const state = createCodexSubagentTranscriptState() - const roster: CodexSubagentRoster = new Map() - - reconcileCodexSubagentTranscript(state, roster, parentPath) - - expect(hasTrackedCodexTranscriptSubagents(state)).toBe(true) - expect(codexRosterToSnapshots(roster)).toEqual([ - { - id: CHILD_ID, - description: 'sidebar_repro', - state: 'working', - startedAt: 1234, - agentType: undefined, - model: undefined - } - ]) - - writeFileSync( - childPath, - jsonl([ - { type: 'event_msg', payload: { type: 'task_started' } }, - { type: 'event_msg', payload: { type: 'task_complete' } } - ]) - ) - reconcileCodexSubagentTranscript(state, roster, parentPath) - - expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false) - expect(codexRosterToSnapshots(roster)).toBeUndefined() - }) - it('resolves a child rollout filed under a later session day than the parent', () => { const root = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-')) dirs.push(root) - const childStartedAt = Date.now() + const childStartedAt = 1_767_225_600_000 const parentDir = dayDirectory(root, childStartedAt - 24 * 60 * 60 * 1000) const childDir = dayDirectory(root, childStartedAt) mkdirSync(parentDir, { recursive: true }) @@ -115,87 +71,7 @@ describe('Codex subagent transcript reconciliation', () => { reconcileCodexSubagentTranscript(state, roster, parentPath) // Why: only a cross-day lookup can observe the completion; the parent-directory scan never finds this file. - expect(roster.size).toBe(0) - expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false) - }) - - it('retires a child whose rollout never becomes readable', () => { - vi.useFakeTimers() - try { - const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-')) - dirs.push(dir) - const parentPath = join(dir, 'rollout-parent.jsonl') - writeFileSync(parentPath, jsonl([activity('started')])) - const state = createCodexSubagentTranscriptState() - const roster: CodexSubagentRoster = new Map() - - reconcileCodexSubagentTranscript(state, roster, parentPath) - expect(roster.size).toBe(1) - - // Why: within the grace window a slow-to-appear rollout must not drop a live child. - vi.advanceTimersByTime(30_000) - reconcileCodexSubagentTranscript(state, roster, parentPath) - expect(roster.size).toBe(1) - - vi.advanceTimersByTime(31_000) - reconcileCodexSubagentTranscript(state, roster, parentPath) - expect(roster.size).toBe(0) - expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false) - } finally { - vi.useRealTimers() - } - }) - - it('names a hook-only worker child from its own rollout once the hook read missed it', () => { - const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-')) - dirs.push(dir) - const parentPath = join(dir, 'rollout-parent.jsonl') - const childPath = join(dir, `rollout-child-${CHILD_ID}.jsonl`) - writeFileSync(parentPath, '') - const state = createCodexSubagentTranscriptState() - const roster: CodexSubagentRoster = new Map() - // SubagentStart carries only the role; a session_meta past 64 KiB (large tool lists) used to stay unread. - upsertCodexSubagent(roster, CHILD_ID, { agentType: 'worker', state: 'working' }, 1234) - writeFileSync( - childPath, - jsonl([ - { - type: 'session_meta', - payload: { - id: CHILD_ID, - base_instructions: { text: 'x'.repeat(100 * 1024) }, - source: { - subagent: { - thread_spawn: { agent_path: null, agent_nickname: 'Planck', agent_role: 'worker' } - } - } - } - } - ]) - ) - - reconcileCodexSubagentTranscript(state, roster, parentPath) - expect(retryPendingCodexSubagentIdentities(roster)).toBe(true) - expect(codexRosterToSnapshots(roster)).toEqual([ - expect.objectContaining({ id: CHILD_ID, agentType: 'worker', description: 'Planck' }) - ]) - }) - - it('keeps a task path the parent supplied over a queued header read', () => { - const dir = mkdtempSync(join(tmpdir(), 'codex-subagent-transcript-')) - dirs.push(dir) - const childPath = join(dir, `rollout-child-${CHILD_ID}.jsonl`) - writeFileSync( - childPath, - jsonl([{ type: 'session_meta', payload: { id: CHILD_ID, agent_nickname: 'Planck' } }]) - ) - const roster: CodexSubagentRoster = new Map() - upsertCodexSubagent(roster, CHILD_ID, { agentType: 'worker', state: 'working' }, 1234) - queueCodexSubagentIdentity(roster, CHILD_ID, childPath) - upsertCodexSubagent(roster, CHILD_ID, { description: 'pr_review', state: 'working' }, 1234) - - expect(retryPendingCodexSubagentIdentities(roster)).toBe(false) - expect(codexRosterToSnapshots(roster)?.[0]).toMatchObject({ description: 'pr_review' }) + expect(codexRosterToSnapshots(roster)).toBeUndefined() }) it('removes a child when Codex reports it interrupted', () => { @@ -210,8 +86,7 @@ describe('Codex subagent transcript reconciliation', () => { writeFileSync(parentPath, jsonl([activity('started'), activity('interrupted')])) reconcileCodexSubagentTranscript(state, roster, parentPath) - expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false) - expect(roster.size).toBe(0) + expect(codexRosterToSnapshots(roster)).toBeUndefined() }) describe('child model identity', () => { @@ -237,17 +112,6 @@ describe('Codex subagent transcript reconciliation', () => { return { parentPath, childPath } } - it('reports the model from the child rollout, not the parent model', () => { - const { parentPath } = seedPair([started(), turnContext('gpt-5.6-terra')]) - const state = createCodexSubagentTranscriptState() - const roster: CodexSubagentRoster = new Map() - - reconcileCodexSubagentTranscript(state, roster, parentPath) - - // The parent runs sol; only the child's own turn_context may set its model. - expect(codexRosterToSnapshots(roster)?.[0]?.model).toBe('gpt-5.6-terra') - }) - it('keeps the discovered model when a later poll carries no turn_context', () => { const { parentPath, childPath } = seedPair([started(), turnContext('gpt-5.6-terra')]) const state = createCodexSubagentTranscriptState() @@ -293,8 +157,7 @@ describe('Codex subagent transcript reconciliation', () => { reconcileCodexSubagentTranscript(state, roster, parentPath) - expect(roster.size).toBe(0) - expect(hasTrackedCodexTranscriptSubagents(state)).toBe(false) + expect(codexRosterToSnapshots(roster)).toBeUndefined() }) }) }) diff --git a/src/shared/command-code-output-retention.test.ts b/src/shared/command-code-output-retention.test.ts deleted file mode 100644 index 681d12270e5..00000000000 --- a/src/shared/command-code-output-retention.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createCommandCodeOutputStatusDetector } from './command-code-output-status' - -function heapAfterGc(): number { - if (!('gc' in globalThis) || typeof globalThis.gc !== 'function') { - throw new Error('The test runner must enable --expose-gc') - } - globalThis.gc() - globalThis.gc() - return process.memoryUsage().heapUsed -} - -describe('Command Code output retention', () => { - it('keeps small boundary carries without pinning oversized output on ordinary panes', () => { - const before = heapAfterGc() - const detectors = Array.from({ length: 8 }, (_value, index) => { - const detector = createCommandCodeOutputStatusDetector({ onWorking: () => {} }) - detector.observe(`${index}:${'x'.repeat(4 * 1024 * 1024)}`) - return detector - }) - expect(heapAfterGc() - before).toBeLessThan(2 * 1024 * 1024) - for (const detector of detectors) { - expect(detector.observe('\nordinary shell output\n')).toBe(false) - } - }) -}) diff --git a/src/shared/command-code-output-status.test.ts b/src/shared/command-code-output-status.test.ts index d2f80ebd304..06d68a0358b 100644 --- a/src/shared/command-code-output-status.test.ts +++ b/src/shared/command-code-output-status.test.ts @@ -1,37 +1,7 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { createCommandCodeOutputStatusDetector } from './command-code-output-status' -afterEach(() => { - vi.restoreAllMocks() -}) - describe('createCommandCodeOutputStatusDetector', () => { - it('marks Command Code working with the submitted prompt when the TUI starts thinking', () => { - const onWorking = vi.fn() - const detector = createCommandCodeOutputStatusDetector({ - startupCommand: 'command-code --trust', - onWorking - }) - - expect(detector.observe('❯ Fix the yellow spinner\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(true) - - expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner') - }) - - it('waits for the Command Code banner before trusting generic status text', () => { - const onWorking = vi.fn() - const detector = createCommandCodeOutputStatusDetector({ - startupCommand: null, - onWorking - }) - - expect(detector.observe('Thinking about unrelated shell output')).toBe(false) - expect(detector.observe('# Command Code v0.27.2\r\n')).toBe(false) - expect(detector.observe('⌘ Parsing...')).toBe(true) - - expect(onWorking).toHaveBeenCalledWith('') - }) - it('detects the Command Code banner across PTY chunk boundaries', () => { const onWorking = vi.fn() const detector = createCommandCodeOutputStatusDetector({ @@ -46,22 +16,6 @@ describe('createCommandCodeOutputStatusDetector', () => { expect(onWorking).toHaveBeenCalledWith('') }) - it('detects the banner after chunks that carry no banner characters at all', () => { - const onWorking = vi.fn() - const detector = createCommandCodeOutputStatusDetector({ - startupCommand: null, - onWorking - }) - - // Ordinary agent output with no '#': the raw prefilter skips these without building a window. - expect(detector.observe('Codex is editing the file and rendering a diff\r\n')).toBe(false) - expect(detector.observe('Codex wrote 12 lines\r\n')).toBe(false) - expect(detector.observe('# Command Code v0.27.2\r\n')).toBe(false) - expect(detector.observe('⌘ Parsing...')).toBe(true) - - expect(onWorking).toHaveBeenCalledWith('') - }) - it('detects the Command Code banner when ANSI styling splits the words', () => { const onWorking = vi.fn() const detector = createCommandCodeOutputStatusDetector({ @@ -172,30 +126,3 @@ describe('createCommandCodeOutputStatusDetector', () => { expect(onWorking).not.toHaveBeenCalled() }) }) - -describe('terminal control stripping', () => { - function promptFrom(raw: string): string | null { - let captured: string | null = null - const detector = createCommandCodeOutputStatusDetector({ - startupCommand: 'command-code', - onWorking: (prompt) => { - captured = prompt - } - }) - detector.observe(raw) - return captured - } - - it('strips control bytes wherever they sit around the prompt text', () => { - expect(promptFrom('❯ plain prompt\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe('plain prompt') - expect(promptFrom('\x07❯ leading control\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe( - 'leading control' - ) - expect(promptFrom('❯ trailing control\x07\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe( - 'trailing control' - ) - expect(promptFrom('❯ adjacent\x07\x01\x02controls\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe( - 'adjacentcontrols' - ) - }) -}) diff --git a/src/shared/crash-reporting.test.ts b/src/shared/crash-reporting.test.ts index 4c6abeeab4a..078da5f3317 100644 --- a/src/shared/crash-reporting.test.ts +++ b/src/shared/crash-reporting.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { formatCrashReportText, - sanitizeCrashReportDetails, sanitizeCrashReportString, type CrashReportRecord } from './crash-reporting' @@ -27,14 +26,6 @@ function notesReport(overrides: Partial = {}): CrashReportRec } } -/** Notes are emitted indented inside the fence; mirror that when asserting. */ -function indentNote(note: string): string { - return note - .split('\n') - .map((line) => ` ${line}`) - .join('\n') -} - describe('crash-reporting shared helpers', () => { it('redacts paths and common secret-shaped strings', () => { const text = @@ -53,60 +44,6 @@ describe('crash-reporting shared helpers', () => { ) }) - it('keeps details on a strict primitive allowlist', () => { - const longStack = [ - 'Error: boom', - ...Array.from( - { length: 200 }, - (_, index) => `at Component${index} (/Users/alice/project/src/file-${index}.tsx:1:1)` - ) - ].join('\n') - - expect( - sanitizeCrashReportDetails({ - name: 'GPU /home/alice/repo', - code: 9, - crashed: true, - missing: null, - error_stack: longStack, - minidumpPath: '/Users/alice/Library/Application Support/Orca/reports/abc.dmp', - nested: { nope: true }, - infinite: Number.POSITIVE_INFINITY - }) - ).toEqual({ - name: 'GPU [redacted-path]', - code: 9, - crashed: true, - missing: null, - error_stack: expect.stringContaining('[redacted-path]'), - minidumpPath: '[redacted-path]' - }) - expect( - String(sanitizeCrashReportDetails({ error_stack: longStack }).error_stack).length - ).toBeGreaterThan(240) - expect(String(sanitizeCrashReportDetails({ errorStack: longStack }).errorStack).length).toBe( - 4_003 - ) - expect( - String(sanitizeCrashReportDetails({ componentStack: longStack }).componentStack).length - ).toBe(4_003) - expect(String(sanitizeCrashReportDetails({ description: longStack }).description).length).toBe( - 243 - ) - }) - - it('keeps a user note longer than the 240-char detail cap intact', () => { - // A real 1.4.184 note was cut mid-word by the telemetry detail budget. - const note = - `My phone is connected. ${'The Claude terminal never came back. '.repeat(20)}`.trim() - - const text = formatCrashReportText(notesReport(), note) - - expect(note.length).toBeGreaterThan(240) - expect(text).toContain(`--- begin user notes ---\n${indentNote(note)}\n--- end user notes ---`) - expect(text).not.toContain('...') - }) - it('still redacts paths and secrets far past the old 240-char cap', () => { const note = [ 'a'.repeat(1_000), @@ -123,22 +60,6 @@ describe('crash-reporting shared helpers', () => { expect(text).not.toContain('ghp_abcdefghijklmnopqrstuvwxyz') }) - it('keeps user notes when the report is truncated to the endpoint cap', () => { - // Tail truncation must remove reproducible machine data before user notes. - const text = formatCrashReportText( - notesReport({ - details: Object.fromEntries( - Array.from({ length: 400 }, (_, index) => [`detail_${index}`, 'x'.repeat(240)]) - ) - }), - 'the sidebar went blank' - ) - - expect(text.length).toBeLessThanOrEqual(64_000) - expect(text).toContain('[Crash report truncated to fit feedback endpoint limits.]') - expect(text).toContain('--- begin user notes ---\n the sidebar went blank') - }) - it.each([ ['POSIX', '/home/alice/orca/app.log then recovered.'], ['Windows', 'C:\\Users\\alice\\Orca\\app.log then recovered.'], diff --git a/src/shared/darwin-process-table-capture.test.ts b/src/shared/darwin-process-table-capture.test.ts index 6b59c552b85..708da7f353b 100644 --- a/src/shared/darwin-process-table-capture.test.ts +++ b/src/shared/darwin-process-table-capture.test.ts @@ -7,7 +7,6 @@ import { captureDarwinProcessTable, resetDarwinProcessTableCaptureForTests } from './darwin-process-table-capture' -import { PS_ARGS } from './process-table-snapshot' const raw = '123 1 123 123 S+ 16/9 Fri Oct 9 12:34:56 2026 /bin/zsh\n' const canonical = raw.replace('16/9', 'ttys009') @@ -43,13 +42,7 @@ describe('Darwin translation deadline', () => { await vi.advanceTimersByTimeAsync(100) await rejected expect(signal?.aborted).toBe(true) - expect(capture.mock.calls.map(([args]) => args)).toEqual([ - ['-axo', PS_ARGS[1].replace('tty=', 'tdev=')] - ]) - for (let index = 0; index < 5; index++) { - expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) - } - expect(naming).toHaveBeenCalledTimes(1) + expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) finish(raw.replace('16/9', 'stale-name')) await pending @@ -58,24 +51,6 @@ describe('Darwin translation deadline', () => { expect(await captureDarwinProcessTable(capture, validate, 100)).toBe( raw.replace('16/9', 'fresh-name') ) - expect(naming).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) - }) - - it('does not start naming after the capture has consumed its budget', async () => { - const lateCapture = vi.fn(async (args: readonly string[]) => { - if (args[1].includes('tdev=')) { - await new Promise((resolve) => setTimeout(resolve, 100)) - return raw - } - return canonical - }) - - const first = captureDarwinProcessTable(lateCapture, validate, 100) - const rejected = expect(first).rejects.toThrow('capture_over_budget') - await vi.advanceTimersByTimeAsync(100) - await rejected - expect(naming).not.toHaveBeenCalled() }) it('rejects late successful names even when Promise completion beats the overdue timer', async () => { @@ -90,23 +65,5 @@ describe('Darwin translation deadline', () => { await expect(captureDarwinProcessTable(capture, validate, 100)).rejects.toThrow( 'capture_over_budget' ) - expect(capture).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - }) - - it('rejects expiry during output validation without another capture', async () => { - let clock = 0 - vi.spyOn(performance, 'now').mockImplementation(() => clock) - naming.mockResolvedValue(canonical) - const slowValidation = (stdout: string): string => { - clock = 101 - return stdout - } - - await expect(captureDarwinProcessTable(capture, slowValidation, 100)).rejects.toThrow( - 'capture_over_budget' - ) - expect(capture).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) }) }) diff --git a/src/shared/darwin-process-table-inventory-drain.test.ts b/src/shared/darwin-process-table-inventory-drain.test.ts index 19dc21817e0..87f481b274d 100644 --- a/src/shared/darwin-process-table-inventory-drain.test.ts +++ b/src/shared/darwin-process-table-inventory-drain.test.ts @@ -48,7 +48,7 @@ describe('Darwin inventory drain admission', () => { if (path === candidatePath) { return missingCandidate() } - if (lstatMock.mock.calls.length === 2) { + if (path === '/dev/entry-0') { throw new Error('stat invocation failed') } return pending.promise @@ -60,19 +60,15 @@ describe('Darwin inventory drain admission', () => { }) await vi.advanceTimersByTimeAsync(0) expect(settled).toBe(false) - expect(lstatMock).toHaveBeenCalledTimes(3) expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) - expect(opendirMock).toHaveBeenCalledTimes(1) const stat = { rdev: 0x10000009n, isCharacterDevice: () => true } lstatMock.mockResolvedValue(stat) pending.resolve(stat) expect(await first).toBe(raw.replace('16/9', 'entry-1')) - expect(lstatMock).toHaveBeenCalledTimes(3) - expect(vi.getTimerCount()).toBe(0) }) - it('holds admission until its one uncancelable stat drains and admits no later reads', async () => { + it('uses canonical fallback until expired inventory drains, then admits fresh names', async () => { opendirMock.mockResolvedValue( Array.from({ length: 12 }, (_, index) => ({ name: `entry-${index}` })) ) @@ -88,51 +84,18 @@ describe('Darwin inventory drain admission', () => { const rejected = expect(first).rejects.toThrow('capture_over_budget') await vi.advanceTimersByTimeAsync(100) await rejected - expect(lstatMock).toHaveBeenCalledTimes(2) const stat = { rdev: 0x10000009n, isCharacterDevice: () => true } - for (let index = 0; index < 5; index++) { - expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) - } - expect(opendirMock).toHaveBeenCalledTimes(1) - expect(lstatMock).toHaveBeenCalledTimes(2) + expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) pending.resolve(stat) await vi.advanceTimersByTimeAsync(0) - expect(lstatMock).toHaveBeenCalledTimes(2) lstatMock.mockImplementation(async (path: string) => path === candidatePath ? missingCandidate() : stat ) expect(await captureDarwinProcessTable(capture, validate, 100)).toBe( raw.replace('16/9', 'entry-0') ) - expect(opendirMock).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) - }) - - it('holds admission while an expired pty candidate stat drains', async () => { - const pending = deferred<{ - rdev: bigint - isCharacterDevice: () => boolean - }>() - lstatMock.mockReturnValue(pending.promise) - - const first = captureDarwinProcessTable(capture, validate, 100) - const rejected = expect(first).rejects.toThrow('capture_over_budget') - await vi.advanceTimersByTimeAsync(100) - await rejected - expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) - expect(lstatMock).toHaveBeenCalledTimes(1) - expect(opendirMock).not.toHaveBeenCalled() - - const stat = { rdev: 0x10000009n, isCharacterDevice: () => true } - pending.resolve(stat) - await vi.advanceTimersByTimeAsync(0) - lstatMock.mockResolvedValue(stat) - expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) - expect(lstatMock).toHaveBeenCalledTimes(2) - expect(opendirMock).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) }) it('closes a directory that opens after expiry and holds admission until its close drains', async () => { @@ -157,9 +120,7 @@ describe('Darwin inventory drain admission', () => { opened.resolve(entries()) await vi.advanceTimersByTimeAsync(0) expect(closeStarted).toBe(true) - expect(lstatMock.mock.calls).toEqual([[candidatePath, { bigint: true }]]) expect(await captureDarwinProcessTable(capture, validate, 100)).toBe(canonical) - expect(opendirMock).toHaveBeenCalledTimes(1) close.resolve() await vi.advanceTimersByTimeAsync(0) @@ -172,7 +133,5 @@ describe('Darwin inventory drain admission', () => { expect(await captureDarwinProcessTable(capture, validate, 100)).toBe( raw.replace('16/9', 'fresh-name') ) - expect(opendirMock).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) }) }) diff --git a/src/shared/darwin-terminal-names-real-ps.test.ts b/src/shared/darwin-terminal-names-real-ps.test.ts index 36368ef8af9..3c0394488a4 100644 --- a/src/shared/darwin-terminal-names-real-ps.test.ts +++ b/src/shared/darwin-terminal-names-real-ps.test.ts @@ -51,21 +51,4 @@ describe.runIf(process.platform === 'darwin')('nameDarwinTerminals against real ) expect(ttyByPid(named).get(terminalPid)).toMatch(/^ttys\d{3,}$/) }) - - it('matches ps terminal names for every process present in both captures', async () => { - // Retry once: a terminal can close between the two ps runs. - let mismatches: string[] = [] - for (let attempt = 0; attempt < 2; attempt += 1) { - const raw = execFileSync('ps', RAW_ARGS, { encoding: 'utf8' }) - const canonical = ttyByPid(execFileSync('ps', [...PS_ARGS], { encoding: 'utf8' })) - const named = ttyByPid(await nameDarwinTerminals(raw)) - mismatches = [...named] - .filter(([pid, tty]) => canonical.has(pid) && canonical.get(pid) !== tty) - .map(([pid, tty]) => `${pid}: ${tty} != ${canonical.get(pid)}`) - if (mismatches.length === 0) { - break - } - } - expect(mismatches).toEqual([]) - }) }) diff --git a/src/shared/darwin-terminal-names.test.ts b/src/shared/darwin-terminal-names.test.ts index 9f330fa0c90..14ccf0d72a2 100644 --- a/src/shared/darwin-terminal-names.test.ts +++ b/src/shared/darwin-terminal-names.test.ts @@ -7,24 +7,14 @@ type DeviceEntry = { rdev: bigint kind?: 'character' | 'symlink' | 'file' delayMs?: number - error?: Error } class TestDeviceDirectory { entries: DeviceEntry[] = [] - openedPaths: string[] = [] - readPaths: string[] = [] closedDirectories = 0 - peakReads = 0 - openError?: Error enumerationError?: Error - private activeReads = 0 - openDirectory = async (path: string): Promise> => { - this.openedPaths.push(path) - if (this.openError) { - throw this.openError - } + openDirectory = async (): Promise> => { return this.enumerate() } @@ -44,24 +34,14 @@ class TestDeviceDirectory { readDevice = async ( path: string ): Promise<{ rdev: bigint; isCharacterDevice: () => boolean }> => { - this.readPaths.push(path) const entry = this.entries.find((candidate) => join('/dev', candidate.name) === path) if (!entry) { throw new Error('device disappeared') } - this.activeReads += 1 - this.peakReads = Math.max(this.peakReads, this.activeReads) - try { - await new Promise((resolve) => setTimeout(resolve, entry.delayMs ?? 1)) - if (entry.error) { - throw entry.error - } - return { - rdev: entry.rdev, - isCharacterDevice: () => (entry.kind ?? 'character') === 'character' - } - } finally { - this.activeReads -= 1 + await new Promise((resolve) => setTimeout(resolve, entry.delayMs ?? 1)) + return { + rdev: entry.rdev, + isCharacterDevice: () => (entry.kind ?? 'character') === 'character' } } } @@ -85,7 +65,6 @@ describe('nameDarwinTerminals', () => { expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('??')) directory.entries = [{ name: 'ttys009', rdev: 0x10000009n }] expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('ttys009')) - expect(directory.openedPaths).toEqual(['/dev', '/dev']) }) it('updates a known device name after a rename between captures', async () => { @@ -95,9 +74,6 @@ describe('nameDarwinTerminals', () => { directory.entries = [{ name: 'cu.after', rdev: 0x1600002an }] expect(await nameDarwinTerminals(darwinRow('22/42'), directory)).toBe(darwinRow('cu.after')) - expect(directory.readPaths).toEqual( - ['ttys042', 'cu.before', 'ttys042', 'cu.after'].map((name) => join('/dev', name)) - ) }) it('scans until a serial name resolves while excluding links and files', async () => { @@ -113,14 +89,9 @@ describe('nameDarwinTerminals', () => { expect(await nameDarwinTerminals(darwinRow('22/42'), directory)).toBe( darwinRow('cu.serial-adapter') ) - expect(directory.readPaths).toEqual( - ['ttys042', 'tty-link', 'tty-file', 'null', 'cu.serial-adapter'].map((name) => - join('/dev', name) - ) - ) }) - it('stops scheduling stats after cancellation while draining all active reads', async () => { + it('drains an active inventory read and closes its directory on cancellation', async () => { const directory = new TestDeviceDirectory() directory.entries = Array.from({ length: 20 }, (_, index) => ({ name: `entry-${index}`, @@ -140,16 +111,13 @@ describe('nameDarwinTerminals', () => { void rejection.catch(() => {}) try { await vi.advanceTimersByTimeAsync(2) - expect(directory.readPaths).toHaveLength(2) controller.abort() await vi.advanceTimersByTimeAsync(0) expect(settled).toBe(false) await vi.advanceTimersByTimeAsync(8) - expect(directory.readPaths).toHaveLength(2) await rejection expect(directory.closedDirectories).toBe(1) - expect(directory.peakReads).toBe(1) } finally { controller.abort() try { @@ -161,20 +129,6 @@ describe('nameDarwinTerminals', () => { } }) - it('bounds large inventories and closes the directory without admitting device reads', async () => { - const directory = new TestDeviceDirectory() - directory.entries = Array.from({ length: 20_000 }, (_, index) => ({ - name: `entry-${index}-${'x'.repeat(240)}`, - rdev: 0n - })) - - await expect(nameDarwinTerminals(darwinRow('16/9'), directory)).rejects.toThrow( - 'Directory listing is too large' - ) - expect(directory.readPaths).toEqual([join('/dev', 'ttys009')]) - expect(directory.closedDirectories).toBe(1) - }) - it('closes an interrupted directory iterator and rejects partial inventories', async () => { const directory = new TestDeviceDirectory() directory.entries = [{ name: 'cu.device', rdev: 0x10000009n }] @@ -184,26 +138,19 @@ describe('nameDarwinTerminals', () => { 'directory enumeration failed' ) expect(directory.closedDirectories).toBe(1) - expect(directory.readPaths).toEqual([join('/dev', 'ttys009')]) }) - it.each([ - '123 1 S+ node 16/9\n', - 'not-pid 1 123 123 S+ 16/9 tail\n', - '123 nope 123 123 S+ 16/9 tail\n', - '123 1 nope 123 S+ 16/9 tail\n', - '123 1 123 nope S+ 16/9 tail\n', - 'PID PPID PGID TPGID STAT TDEV STARTED COMMAND\n', - '123 1 123 123 S+ 16/9 \t\r\n' - ])('rejects unsupported row framing without a device scan (%s)', async (row) => { - const directory = new TestDeviceDirectory() - await expect(nameDarwinTerminals(darwinRow('16/9') + row, directory)).rejects.toThrow( - 'malformed_darwin_device_row' - ) - expect(directory.openedPaths).toEqual([]) - }) + it.each(['123 1 S+ node 16/9\n', 'not-pid 1 123 123 S+ 16/9 tail\n'])( + 'rejects unsupported row framing (%s)', + async (row) => { + const directory = new TestDeviceDirectory() + await expect(nameDarwinTerminals(darwinRow('16/9') + row, directory)).rejects.toThrow( + 'malformed_darwin_device_row' + ) + } + ) - it('rejects undecodable filenames and closes the directory before any stat reads', async () => { + it('rejects undecodable filenames and closes the directory', async () => { const directory = new TestDeviceDirectory() directory.entries = [ { name: 'cu.device', rdev: 0x10000009n }, @@ -213,7 +160,6 @@ describe('nameDarwinTerminals', () => { 'undecodable_device_name' ) expect(directory.closedDirectories).toBe(1) - expect(directory.readPaths).toEqual([join('/dev', 'ttys009')]) }) it('accepts signed and sign-extended device numbers while ignoring arbitrary wide rdev', async () => { @@ -243,24 +189,19 @@ describe('nameDarwinTerminals', () => { ] expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('cu.alias')) - expect(directory.openedPaths).toEqual(['/dev']) }) - it.each(['symlink', 'file'] as const)( - 'rejects a %s pty candidate and falls back to a character device', - async (kind) => { - const directory = new TestDeviceDirectory() - directory.entries = [ - { name: 'ttys009', rdev: 0x10000009n, kind }, - { name: 'cu.real', rdev: 0x10000009n } - ] + it('rejects a symlink pty candidate and falls back to a character device', async () => { + const directory = new TestDeviceDirectory() + directory.entries = [ + { name: 'ttys009', rdev: 0x10000009n, kind: 'symlink' }, + { name: 'cu.real', rdev: 0x10000009n } + ] - expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('cu.real')) - expect(directory.openedPaths).toEqual(['/dev']) - } - ) + expect(await nameDarwinTerminals(darwinRow('16/9'), directory)).toBe(darwinRow('cu.real')) + }) - it('stops candidate stats after cancellation and rejects once the active read drains', async () => { + it('rejects cancellation after its active candidate read drains', async () => { const directory = new TestDeviceDirectory() directory.entries = [1, 2, 3].map((minor) => ({ name: `ttys00${minor}`, @@ -281,16 +222,11 @@ describe('nameDarwinTerminals', () => { void rejection.catch(() => {}) try { await vi.advanceTimersByTimeAsync(2) - expect(directory.readPaths).toEqual([join('/dev', 'ttys001')]) controller.abort() await vi.advanceTimersByTimeAsync(0) expect(settled).toBe(false) await vi.advanceTimersByTimeAsync(8) - expect(directory.readPaths).toEqual([join('/dev', 'ttys001')]) await rejection - - expect(directory.openedPaths).toEqual([]) - expect(directory.peakReads).toBe(1) } finally { controller.abort() try { diff --git a/src/shared/draft-paste-ready-scanner-grok-trace-replay.test.ts b/src/shared/draft-paste-ready-scanner-grok-trace-replay.test.ts deleted file mode 100644 index b7a10f858b4..00000000000 --- a/src/shared/draft-paste-ready-scanner-grok-trace-replay.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Replay alt-screen and inline grok startup captures: ~12Hz logo shimmer defeats the 1.5s quiet window, causing 8s timeout delays/dropped drafts. Preserve both marker and quiet-floor paths. -import { describe, expect, it } from 'vitest' -import { createDraftPasteReadyScanner } from './draft-paste-ready-scanner' -import type { DraftPasteReadySignal } from './agent-launch/catalog/tui-agent-config-types' -import { - GROK_STARTUP_PTY_TRACE, - type GrokStartupTraceChunk -} from './__fixtures__/grok-startup-pty-trace' -import { GROK_INLINE_STARTUP_PTY_TRACE } from './__fixtures__/grok-inline-startup-pty-trace' - -const QUIET_WINDOW_MS = 1500 -const HARD_TIMEOUT_MS = 8000 - -function chunkData(chunk: GrokStartupTraceChunk): string { - return chunk.data ?? 'x'.repeat(chunk.bytes ?? 0) -} - -/** Replay caller timer semantics: re-arm quiet requests, cancel on earlier chunks, and let hard timeout outrank late markers. Null means timeout; main drops that draft. Mirrors agent-draft-readiness.ts/orca-runtime.ts. */ -function replayReadyAtMs( - signal: DraftPasteReadySignal, - trace: GrokStartupTraceChunk[] -): number | null { - const scanner = createDraftPasteReadyScanner(signal) - let quietDeadline: number | null = null - for (const [index, chunk] of trace.entries()) { - const settledAt = - quietDeadline !== null ? Math.min(quietDeadline, HARD_TIMEOUT_MS) : HARD_TIMEOUT_MS - if (chunk.t >= settledAt) { - return quietDeadline !== null && quietDeadline <= HARD_TIMEOUT_MS ? quietDeadline : null - } - const scanned = scanner.observe(chunkData(chunk)) - if (scanned.ready) { - return chunk.t - } - quietDeadline = scanned.armQuietTimer ? chunk.t + QUIET_WINDOW_MS : quietDeadline - if (index === trace.length - 1 && quietDeadline !== null && quietDeadline < HARD_TIMEOUT_MS) { - return quietDeadline - } - } - return null -} - -describe('grok startup trace replay (alternate-screen mode)', () => { - it('reports readiness on the frame that paints the composer box', () => { - const composerFrame = GROK_STARTUP_PTY_TRACE.find((chunk) => chunk.data?.includes('❯')) - expect(composerFrame).toBeDefined() - expect(replayReadyAtMs('grok-composer-prompt', GROK_STARTUP_PTY_TRACE)).toBe(composerFrame?.t) - }) -}) - -describe('grok startup trace replay (inline mode, no alternate screen)', () => { - it('arms a quiet window before the inline trace reaches the modeled timeout', () => { - // Inline grok emits no 1049h; retain a separate quiet anchor or main would drop the issue-URL draft. - const readyAt = replayReadyAtMs('grok-composer-prompt', GROK_INLINE_STARTUP_PTY_TRACE) - expect(readyAt).not.toBeNull() - expect(readyAt).toBeLessThan(HARD_TIMEOUT_MS) - }) -}) diff --git a/src/shared/dsb-native-one-shot-recognition.test.ts b/src/shared/dsb-native-one-shot-recognition.test.ts index 3f8ab311629..55835dc4e77 100644 --- a/src/shared/dsb-native-one-shot-recognition.test.ts +++ b/src/shared/dsb-native-one-shot-recognition.test.ts @@ -6,27 +6,15 @@ describe('DeepSeek Build native one-shot identity exclusion', () => { it.each([ 'dsb agent -p task', 'dsb agent -- --print task', - 'deepseek-build agent -- --prompt-file task.txt', 'deepseek-build agent --single task', - 'dsb agent --print task', 'dsb agent --prompt-json "[]"', 'dsb agent --prompt-file /tmp/task.txt', - 'deepseek-build-agent -p task', 'deepseek-build-agent.exe --print task', 'deepseek-build-agent --single=task', 'deepseek-build-agent -ptask', - 'deepseek-build-agent -cp task', 'deepseek-build-agent -cptask', - 'deepseek-build-agent -p-', - 'deepseek-build-agent -cp--print', - 'dsb agent -p-', - 'dsb agent -cp--print', - 'dsb agent -cp task', 'dsb run task', - 'deepseek-build-agent --resume saved-session --print task', 'deepseek-build-agent --resume --prompt-file task.txt', - 'dsb --cwd folder agent --model deepseek-v4-flash --prompt-file task.txt', - 'node --import ./preload.mjs /x/node_modules/@innocarpe/deepseek-build/npm/bin/dsb.js agent --print task', '"C:\\Program Files\\nodejs\\node.exe" --require preload.js "C:\\x\\node_modules\\@innocarpe\\deepseek-build\\npm\\bin\\deepseek-build.js" agent --prompt-json=[]' ])('does not claim interactive ownership for %s', (line) => { expect(recognizeAgentProcessFromCommandLine(line)).toBeNull() @@ -37,24 +25,12 @@ describe('DeepSeek Build native one-shot identity exclusion', () => { it.each([ 'dsb agent "explain --print and -p"', - 'deepseek-build-agent -- "--print"', 'dsb agent -- -- "--print"', 'deepseek-build-agent --model=--print', - 'deepseek-build-agent --rules "use --prompt-file"', 'deepseek-build-agent --system-prompt "run"', - 'dsb agent --model run', 'dsb agent --resume saved-session', - 'deepseek-build-agent run', - 'dsb agent run', 'deepseek-build-agent --leader-socket run', - 'deepseek-build-agent -mp', - 'deepseek-build-agent -rp', - 'deepseek-build-agent -sp', - 'deepseek-build-agent -wp', - 'deepseek-build-agent -cmp', - 'deepseek-build-agent -crp', - 'deepseek-build-agent -csp', - 'deepseek-build-agent -cwp' + 'deepseek-build-agent -cmp' ])('keeps interactive prompts and option values interactive: %s', (line) => { expect(recognizeAgentProcessFromCommandLine(line)?.agent).toBe('dsb') }) diff --git a/src/shared/dsh-real-cli.test.ts b/src/shared/dsh-real-cli.test.ts deleted file mode 100644 index dc0c21a4974..00000000000 --- a/src/shared/dsh-real-cli.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' -import { recognizeAgentProcessFromCommandLine } from './agent-status/process/agent-process-recognition' - -const binary = process.env.ORCA_REAL_DSH_CLI - -// No model call: published profile configuration and help establish the launcher contract. -describe.skipIf(!binary)('published DSH 0.2 CLI', () => { - it('keeps positional and explicit headless profiles outside interactive recognition', async () => { - if (!binary) { - throw new Error('Set ORCA_REAL_DSH_CLI to the official dsh executable') - } - const root = await mkdtemp(join(tmpdir(), 'orca-dsh-cli-')) - const env = { ...process.env, DSH_HOME: root, DEEPSEEK_API_KEY: '' } - try { - const version = await runProcess({ program: binary, args: ['--version'], cwd: root, env }) - expect(version.code).toBe(0) - expect(version.stdout.trim()).toMatch(/^0\.2\./) - for (const profile of ['headless', 'sdk', 'sdk-minimal', 'acp']) { - for (const args of [[profile], ['--profile', profile]]) { - const result = await runProcess({ - program: binary, - args: [...args, '--dump-default-config'], - cwd: root, - env, - timeoutMs: 30_000 - }) - expect(result.code).toBe(0) - expect(result.stdout).toContain('@deepseek-ai/dsh-') - const command = `"${binary}" ${args.join(' ')}` - expect(recognizeAgentProcessFromCommandLine(command)).toBeNull() - expect( - recognizeAgentProcessFromCommandLine(command, { includeHeadlessOneShot: true })?.agent - ).toBe('dsh') - } - } - const help = await runProcess({ - program: binary, - args: ['headless', '--help'], - cwd: root, - env, - timeoutMs: 30_000 - }) - expect(help.code).toBe(0) - expect(help.stdout).toContain('Answer one task and exit') - } finally { - await rm(root, { recursive: true, force: true }) - } - }, 120_000) -})