diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 654470b90a4..bb09acc589f 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -257,7 +257,6 @@ 1 test-no-real-time-wait:src/main/windows/windows-process-tree-command-line-patch.test.ts 2 test-no-real-time-wait:src/main/windows/windows-pty-job.win32.test.ts 1 test-no-real-time-wait:src/main/worker-thread-child-process/worker-thread-child-process.test.ts -1 test-no-real-time-wait:src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts 1 test-no-real-time-wait:src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts 2 test-no-real-time-wait:src/main/wsl/execution/wsl-command-loop.test.ts 2 test-no-real-time-wait:src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts @@ -273,7 +272,6 @@ 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/viewport/terminal-fit-restore.test.ts 1 test-no-real-time-wait:src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts -1 test-no-real-time-wait:src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.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 diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index bbb5f649286..f907d5d4bef 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -231,10 +231,10 @@ 1 src/renderer/src/lib/runtime-session-mirror-targets.ts 1 src/renderer/src/lib/workspace/ownership/single-runtime-legacy-owner.ts 1 src/renderer/src/lib/skills/runtime/skill-runtime-command.ts -1 src/renderer/src/lib/terminal-close-route.ts -4 src/renderer/src/lib/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers +1 src/renderer/src/lib/workspace/ownership/terminal-close-route.ts +4 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers 3 src/renderer/src/lib/unread-badge-count-selector.ts -1 src/renderer/src/lib/web-runtime-worktree-terminal-after-wake.ts +1 src/renderer/src/runtime/hosted-terminals/restoration/web-runtime-worktree-terminal-after-wake.ts 1 src/renderer/src/lib/work-items/linear/linear-issue-url-lookup.ts 1 src/renderer/src/lib/work-items/linear/linear-issue-write.ts 1 src/renderer/src/lib/workspace/activation/worktree-activation.ts diff --git a/config/mobile-localization-coverage-allowlist.json b/config/mobile-localization-coverage-allowlist.json index 265dd13cf28..113c65c34da 100644 --- a/config/mobile-localization-coverage-allowlist.json +++ b/config/mobile-localization-coverage-allowlist.json @@ -560,21 +560,21 @@ "count": 1 }, { - "filePath": "mobile/src/transport/hosts/mobile-relay-host-overlay.ts", + "filePath": "mobile/src/host-catalog/mobile-relay-host-overlay.ts", "kind": "object-property:message", "text": "Expected exactly one endpoint for configured relay metadata", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/transport/hosts/mobile-relay-host-overlay.ts", + "filePath": "mobile/src/host-catalog/mobile-relay-host-overlay.ts", "kind": "object-property:message", "text": "Relay host identity mismatch", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/transport/hosts/mobile-relay-host-overlay.ts", + "filePath": "mobile/src/host-catalog/mobile-relay-host-overlay.ts", "kind": "object-property:message", "text": "Relay identity and endpoint must coexist", "dynamic": false, diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 68511863f1e..3dae37fc31e 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -651,7 +651,7 @@ 2 src/renderer/src/components/terminal-pane/mobile-driver/MobileDriverOverlay.tsx 1 src/renderer/src/components/terminal-pane/mobile-driver/TerminalPaneMobileDriverPortals.tsx 1 src/renderer/src/components/terminal-pane/mounting/use-terminal-pane-mount-lifecycle.ts -2 src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.ts +1 src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.ts 1 src/renderer/src/components/terminal-pane/parking/retention/terminal-pending-startup-park-presence.ts 1 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/TerminalPaneRecoveryPortals.tsx 2 src/renderer/src/components/terminal-pane/session-fork/TerminalAgentSessionForkDialog.tsx @@ -705,7 +705,7 @@ 4 src/renderer/src/hooks/skills/freshness/useSkillFreshness.ts 1 src/renderer/src/hooks/useTaskPageGitHubWorkItemMutation.ts 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts -1 src/renderer/src/lib/host-chat-program-acquisition.ts +1 src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts 1 src/renderer/src/lib/quick-open-file-history.ts 2 src/renderer/src/lib/worker-auto-close.ts 1 src/renderer/src/runtime/native-chat/naming/structured-chat-name-observation.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 4cb8372bf84..c4b70e948dd 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1643,13 +1643,13 @@ "invariant": "Automatic hibernation must retain two stable confirmations and fresh execution-host evidence before shutdown. Skipping a workspace with no completed agent must not authorize a newly completed pane using stale client PTYs.", "oracle": "Audit2058 intentionally retires the standalone visibility subscription/callback-count alarm without replacement. Audit2310 additionally retires two pane-age getter-map expiry/pruning samples without equivalent replacement. The reduced five-source hibernation selector was freshly run on Linux:52 tests pass. The earlier 54-test receipt is archived verbatim in knownGaps and does not validate the reduced source. Its prior macOS execution receipt/current-command association is archived verbatim in knownGaps and is not current execution evidence for the reduced selector. Current covered platform is Linux; remote replies remain scripted, with no live SSH/WSL/native provider or p95 claim. Historical prior account (preserved verbatim): Working and waiting agents across remote workspaces must not be shut down. A skipped workspace completing while another inventory awaits remains ineligible until two later host-confirmed passes, and so does a workspace that only becomes runtime-owned while an inventory is outstanding — a pass carrying no host evidence for a workspace never counts as one of its two confirmations. Folder and git workspaces hibernate the exact host PTY; rejected/truncated inventories and intervening input/output or state changes block shutdown.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts --maxWorkers=2" + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/components/terminal-pane/parking/retention/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts --maxWorkers=2" ], "testFiles": [ "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts", "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts", "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts", - "src/renderer/src/lib/foreground-terminal-tabs.test.ts", + "src/renderer/src/components/terminal-pane/parking/retention/foreground-terminal-tabs.test.ts", "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts" ], "assertionRefs": [ @@ -1676,6 +1676,7 @@ "runner": "local", "platform": "linux", "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts --maxWorkers=2", + "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/components/terminal-pane/parking/retention/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts --maxWorkers=2", "result": "passed", "durationSeconds": 5.426, "summary": "52 tests across the five coordinator/planner/age/foreground/liveness-race files passed on public parent60aee85d9182f602af45cf5f6facae7257670061 plus the audit2310 test-removal candidate (source tree da2595af5391e9fa07a924ac69afede47ad31906). Includes the reduced two-case pane-age suite. Scripted runtime contracts; no live SSH/native WSL, soak or measured p95 claim." @@ -4224,10 +4225,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coverageNotes": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "oracle": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -4324,7 +4325,11 @@ "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", - "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed." + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed.", + "Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed.", + "Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed.", + "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired." ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -8563,13 +8568,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated 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): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated 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): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated 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): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "oracle": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated 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): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -9051,7 +9056,11 @@ "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", - "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed." + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed.", + "Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed.", + "Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed.", + "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired." ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -9229,7 +9238,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. 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. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. 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): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. 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. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. 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): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6836", "https://github.com/stablyai/orca/pull/6858", @@ -9237,7 +9246,7 @@ "https://github.com/stablyai/orca/pull/7054" ], "invariant": "High-volume terminal output must stay bounded across daemon socket writes, SSH relay writer/decoder/source retention/reconnect, main model and projection admission, runtime metadata, detectors, and tail checks, main-to-renderer in-flight bytes, renderer scheduler queues, and hidden-output restore without starving focused input. Every new SSH session offers V1 and every same-build relay supports it; legacy delivery is reachable only when capability negotiation proves the peer cannot use V1. Negotiated SSH spans remain exact and contiguous through activation, exit, cancellation, recovery, desktop projection, and required remote replacement; provisional activation data cannot project, reconnect may release it only into the exact attempt's private recovery quarantine after contract validation, and exit seals that quarantine against later same-token frames until ordered admission or exact cancellation proof. Reconnect checkpoint capture freezes exact provider-generation/PTy admission, cancels queued old work, and waits for the running raw completion before exposing its accepted checkpoint; timeout or failure detaches only that PTy's old model, makes the checkpoint unavailable, and releases the bounded fence without closing the shared provider, while the same failure outside an active exact migration remains generation-fatal and overlapping reconnects preserve any earlier outstanding fence. Pending renderer projection IDs are capped and compacted across split remainders, exit preparation owns its renderer fence through finalization, exit-time cancellation transfers published projections before proof commit, generation close fences late proof while draining exact projection waiters, closed-generation identity compacts without weakening stale rejection, canceled source-delivery retirement retains at most one ordered token per PTY, and pause/resume targets only the exact provider generation. Additional subscribers cannot stall the owner, while the required legacy primary retains backpressure.", - "oracle": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. 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. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. 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): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", + "oracle": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. 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. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. 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): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", @@ -9391,7 +9400,11 @@ "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", - "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed." + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed.", + "Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed.", + "Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed.", + "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -12094,7 +12107,7 @@ "providers": ["remote-runtime", "ssh", "local", "daemon"], "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit1400 intentionally deletes or reduces the listed sources. No fresh execution result validates their reduced selectors. Historical coverage account: Local macOS evidence covers runtime-RPC stream budgets, paired-renderer parse/discard credit, and negotiated host-side suppression for hidden paired desktop panes. Deferred credit is shared by local and remote transports, batches ACKs at 192 KiB or 4 ms, grows per-stream windows from 512 KiB to 2 MiB and aggregate windows from 2 MiB to 8 MiB, bounds queued output to 256 KiB per stream, and caps each multiplex connection at 32 active or pending streams for an 8 MiB aggregate pending-output ceiling. Deterministic tests cover replay ordering, stale generations, malformed frames, hidden panes, queue eviction, disposal, send/recovery failure, repeated pending-slot replacement, reconnect, mixed-version pause negotiation, and round-robin fairness. The opt-in benchmark models 1/20/100 ms RTT and 1/4/8 viewers, throughput, window use, completion spread and protocol-frame counts. It measures model scheduler elapsed time separately from actual @xterm/headless parser CPU/retained heap; modeled credit and ACK results do not qualify production credit enforcement. Live Android restore evidence, browser/WebGL parser measurements, and legacy JSON subscribe parity remain required. The audit removed the PTY ACK wrapper suite, which replayed credit arithmetic with mocked IPC. Its isolated wrapper alarms are no longer registered here; generic credit and runtime stream tests do not establish equivalent PTY integration coverage. The audit removes the standalone auto-settle-before-deferred-claim example. Nested-owner and claimed-child completion tests remain; they do not establish that removed timing alarm. The test-value audit removes the bulk-ACK threshold, output-pause capability/paused-input, transformed-metadata disposal, late-parser and renderer-throw examples. The retained captured-parser, malformed-frame and failed-ACK timer checks do not exercise real xterm parsing or server credit enforcement and do not replace the removed alarms. Historical run commands and results remain historical. The test-value audit removes the pure mobile stream-decision suite: pause/resume/rearm/viewport branch inventories no longer have that isolated alarm. The surviving stream-hook tests do not establish equivalent WebView restore, PTY resize, input-lease or subscription delivery coverage. Historical run commands and counts are preserved as historical records; a narrowed selector is not a new passed run. Audit1302: src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts: Keep production RPC dispatcher/terminal framing with emitted binary bytes, UTF-8 reconstruction and client ACK releasing genuinely withheld output; also keep the direct binary-subscribe chunk boundary. Remove shared-budget fairness matrix that sleeps real time and relies on exact synthetic per-stream window scheduling. Lose that eight-stream fairness/call wiring alarm; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts removed. Lose ORCA_TERMINAL_PERF_BENCH diagnostic report and local xterm parser measurements; this was not an ordinary CI assertion gate. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit1400 intentionally deletes or reduces the listed sources. No fresh execution result validates their reduced selectors. Historical coverage account: Local macOS evidence covers runtime-RPC stream budgets, paired-renderer parse/discard credit, and negotiated host-side suppression for hidden paired desktop panes. Deferred credit is shared by local and remote transports, batches ACKs at 192 KiB or 4 ms, grows per-stream windows from 512 KiB to 2 MiB and aggregate windows from 2 MiB to 8 MiB, bounds queued output to 256 KiB per stream, and caps each multiplex connection at 32 active or pending streams for an 8 MiB aggregate pending-output ceiling. Deterministic tests cover replay ordering, stale generations, malformed frames, hidden panes, queue eviction, disposal, send/recovery failure, repeated pending-slot replacement, reconnect, mixed-version pause negotiation, and round-robin fairness. The opt-in benchmark models 1/20/100 ms RTT and 1/4/8 viewers, throughput, window use, completion spread and protocol-frame counts. It measures model scheduler elapsed time separately from actual @xterm/headless parser CPU/retained heap; modeled credit and ACK results do not qualify production credit enforcement. Live Android restore evidence, browser/WebGL parser measurements, and legacy JSON subscribe parity remain required. The audit removed the PTY ACK wrapper suite, which replayed credit arithmetic with mocked IPC. Its isolated wrapper alarms are no longer registered here; generic credit and runtime stream tests do not establish equivalent PTY integration coverage. The audit removes the standalone auto-settle-before-deferred-claim example. Nested-owner and claimed-child completion tests remain; they do not establish that removed timing alarm. The test-value audit removes the bulk-ACK threshold, output-pause capability/paused-input, transformed-metadata disposal, late-parser and renderer-throw examples. The retained captured-parser, malformed-frame and failed-ACK timer checks do not exercise real xterm parsing or server credit enforcement and do not replace the removed alarms. Historical run commands and results remain historical. The test-value audit removes the pure mobile stream-decision suite: pause/resume/rearm/viewport branch inventories no longer have that isolated alarm. The surviving stream-hook tests do not establish equivalent WebView restore, PTY resize, input-lease or subscription delivery coverage. Historical run commands and counts are preserved as historical records; a narrowed selector is not a new passed run. Audit1302: src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts: Keep production RPC dispatcher/terminal framing with emitted binary bytes, UTF-8 reconstruction and client ACK releasing genuinely withheld output; also keep the direct binary-subscribe chunk boundary. Remove shared-budget fairness matrix that sleeps real time and relies on exact synthetic per-stream window scheduling. Lose that eight-stream fairness/call wiring alarm; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts removed. Lose ORCA_TERMINAL_PERF_BENCH diagnostic report and local xterm parser measurements; this was not an ordinary CI assertion gate. No equivalent replacement coverage is claimed. Broader617 Mobile owner follow-up retires six whole work-count/timing registrations from mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts, retaining five functional handoff/readiness/absence/recovery registrations. Prior Audit1400 retained-but-unvalidated and archived inventories describe earlier source and remain historical after this follow-up. No equivalent replacement, fresh execution, timing measurement, physical phone, or deployed mixed-host validation is claimed by this source change. Current premerge review correction for the Broader617 Mobile owner follow-up: four additional whole mock-only/mock-produced-state stream registrations are retired, for ten total cuts and one unchanged retained registration, keeps asking until a tab snapshot replaces the exhausted handle. The preceding five-retained description records the superseded candidate, not current coverage. The retained case checks the real hook-owned recovery-needed result; handoff, readiness and absence-marker mock-delivery alarms are intentionally lost without equivalent replacement. Dead test render counting and unused handoff setup are removed. No new native, physical-phone, timing or deployed-host proof is implied.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6951", "https://github.com/stablyai/orca/pull/6955", @@ -12151,7 +12164,9 @@ "Audit1400 retained but unvalidated assertion inventory pending a new run of the reduced command:\n[\n {\n \"file\": \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"assertions\": [\n \"legacy binary output queued during initial snapshot serialization stays bounded\",\n \"stale mobile resize re-stream completions are dropped for legacy binary streams\",\n \"aborted stream signals do not register stale listeners\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-output-batching.test.ts\",\n \"assertions\": [\n \"desktop output bursts coalesce before stream emission\",\n \"large binary output is encoded lazily before the first output frame\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\n \"assertions\": [\n \"requested snapshots fall back smaller when serialized data exceeds the send budget\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts\",\n \"assertions\": [\n \"oversized live output frames are bounded for subscribed binary streams\",\n \"multibyte live output flushes when encoded bytes reach the batch budget\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts\",\n \"assertions\": [\n \"send and recovery serialization failures detach once instead of leaking credit or retrying forever\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"32 active or pending slots cap aggregate queued output and repeated pending-slot subscribe cancels its older waiter\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts\",\n \"assertions\": [\n \"three negotiated hidden desktop streams emit zero output frames under sustained load while an unpaused stream remains live\",\n \"an older client that omits pause negotiation continues receiving output\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"a runtime-owned hidden pane pauses output, consumes status/title/theme facts, and keeps input writable\",\n \"reveal resumes before one authoritative snapshot and exact live output with no hidden raw write, loss, or duplication\",\n \"dispose releases pause and unregisters the fact consumer\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"desired pause reapplies after either capability/snapshot ordering and across reconnect\",\n \"reconnect delivers each authoritative snapshot and post-resume live marker exactly once\"\n ]\n },\n {\n \"file\": \"src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts\",\n \"assertions\": [\n \"nested synchronous deliveries restore the outer credit owner\",\n \"every claimed scheduler child must settle before the parent credits\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts\",\n \"assertions\": [\n \"paired renderer ACK waits for the output scheduler captured parse callback before releasing encoded-byte credit\",\n \"unknown stream output is unsubscribed and malformed framing closes the connection; malformed transformed data is discarded and credited before resync\",\n \"an ACK write failure tears down the stream with zero rearmed flush timers under fake time\"\n ]\n },\n {\n \"file\": \"mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts\",\n \"assertions\": [\n \"trades a lease-only stream for output when a chat tab hands off to a terminal tab\",\n \"repairs a lease-only stream once its WebView reports ready\",\n \"stops rearming a handle whose stream never comes back (covered: %s, #10681)\",\n \"does not charge the rearm budget for a subscribe its own gates turned away\",\n \"charges the rearm budget for a subscribe the bridge refused before returning\",\n \"refills the rearm budget when terminal.list reports the handle again (covered: %s, #10681)\",\n \"does not let a dead PTY buy a new budget with its own `subscribed` ack\",\n \"refills the budget for a rearmed stream that outlives the teardown window\",\n \"keeps an absence marker observed before the budget ran out\",\n \"keeps asking until a tab snapshot replaces the exhausted handle\",\n \"resumes a cold-start lease-only stream when WebView readiness arrives late\"\n ]\n }\n]", "Audit1400 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts\",\n \"assertions\": [\n \"the opt-in benchmark reports modeled RTT throughput, window use, protocol-frame counts and completion spread, with model scheduler elapsed time and separately measured @xterm/headless parser CPU and retained heap\"\n ]\n }\n]", "Audit1400 archived original active assertionRefs verbatim after retirement of all passed receipts:\n[\n {\n \"file\": \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"assertions\": [\n \"legacy binary output queued during initial snapshot serialization stays bounded\",\n \"stale mobile resize re-stream completions are dropped for legacy binary streams\",\n \"aborted stream signals do not register stale listeners\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-output-batching.test.ts\",\n \"assertions\": [\n \"desktop output bursts coalesce before stream emission\",\n \"large binary output is encoded lazily before the first output frame\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\n \"assertions\": [\n \"requested snapshots fall back smaller when serialized data exceeds the send budget\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts\",\n \"assertions\": [\n \"oversized live output frames are bounded for subscribed binary streams\",\n \"multibyte live output flushes when encoded bytes reach the batch budget\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts\",\n \"assertions\": [\n \"send and recovery serialization failures detach once instead of leaking credit or retrying forever\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"32 active or pending slots cap aggregate queued output and repeated pending-slot subscribe cancels its older waiter\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts\",\n \"assertions\": [\n \"three negotiated hidden desktop streams emit zero output frames under sustained load while an unpaused stream remains live\",\n \"an older client that omits pause negotiation continues receiving output\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"a runtime-owned hidden pane pauses output, consumes status/title/theme facts, and keeps input writable\",\n \"reveal resumes before one authoritative snapshot and exact live output with no hidden raw write, loss, or duplication\",\n \"dispose releases pause and unregisters the fact consumer\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"desired pause reapplies after either capability/snapshot ordering and across reconnect\",\n \"reconnect delivers each authoritative snapshot and post-resume live marker exactly once\"\n ]\n },\n {\n \"file\": \"src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts\",\n \"assertions\": [\n \"nested synchronous deliveries restore the outer credit owner\",\n \"every claimed scheduler child must settle before the parent credits\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts\",\n \"assertions\": [\n \"paired renderer ACK waits for the output scheduler captured parse callback before releasing encoded-byte credit\",\n \"unknown stream output is unsubscribed and malformed framing closes the connection; malformed transformed data is discarded and credited before resync\",\n \"an ACK write failure tears down the stream with zero rearmed flush timers under fake time\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts\",\n \"assertions\": [\n \"the opt-in benchmark reports modeled RTT throughput, window use, protocol-frame counts and completion spread, with model scheduler elapsed time and separately measured @xterm/headless parser CPU and retained heap\"\n ]\n },\n {\n \"file\": \"mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts\",\n \"assertions\": [\n \"trades a lease-only stream for output when a chat tab hands off to a terminal tab\",\n \"repairs a lease-only stream once its WebView reports ready\",\n \"stops rearming a handle whose stream never comes back (covered: %s, #10681)\",\n \"does not charge the rearm budget for a subscribe its own gates turned away\",\n \"charges the rearm budget for a subscribe the bridge refused before returning\",\n \"refills the rearm budget when terminal.list reports the handle again (covered: %s, #10681)\",\n \"does not let a dead PTY buy a new budget with its own `subscribed` ack\",\n \"refills the budget for a rearmed stream that outlives the teardown window\",\n \"keeps an absence marker observed before the budget ran out\",\n \"keeps asking until a tab snapshot replaces the exhausted handle\",\n \"resumes a cold-start lease-only stream when WebView readiness arrives late\"\n ]\n }\n ]", - "Audit1400 archived active selectors after retirement of all passed receipts: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts --maxWorkers=1\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts src/renderer/src/runtime/runtime-terminal-stream.test.ts --maxWorkers=1\",\"ORCA_TERMINAL_PERF_BENCH=1 pnpm exec vitest run --config config/vitest.config.ts --disableConsoleIntercept src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts\",\"pnpm --dir mobile exec vitest run --root .. mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts\"],\"testFiles\":[\"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\"src/main/runtime/rpc/terminal-output-batching.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts\",\"src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts\",\"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts\",\"src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts\",\"src/renderer/src/runtime/runtime-terminal-stream.test.ts\",\"mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts\"]}" + "Audit1400 archived active selectors after retirement of all passed receipts: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts --maxWorkers=1\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts src/renderer/src/runtime/runtime-terminal-stream.test.ts --maxWorkers=1\",\"ORCA_TERMINAL_PERF_BENCH=1 pnpm exec vitest run --config config/vitest.config.ts --disableConsoleIntercept src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts\",\"pnpm --dir mobile exec vitest run --root .. mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts\"],\"testFiles\":[\"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\"src/main/runtime/rpc/terminal-output-batching.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts\",\"src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts\",\"src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts\",\"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts\",\"src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts\",\"src/renderer/src/runtime/runtime-terminal-stream.test.ts\",\"mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts\"]}", + "Broader617 Mobile owner follow-up retires six whole work-count/timing registrations from mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts, retaining five functional handoff/readiness/absence/recovery registrations. Prior Audit1400 retained-but-unvalidated and archived inventories describe earlier source and remain historical after this follow-up. No equivalent replacement, fresh execution, timing measurement, physical phone, or deployed mixed-host validation is claimed by this source change.", + "Current premerge review correction for the Broader617 Mobile owner follow-up: four additional whole mock-only/mock-produced-state stream registrations are retired, for ten total cuts and one unchanged retained registration, keeps asking until a tab snapshot replaces the exhausted handle. The preceding five-retained description records the superseded candidate, not current coverage. The retained case checks the real hook-owned recovery-needed result; handoff, readiness and absence-marker mock-delivery alarms are intentionally lost without equivalent replacement. Dead test render counting and unused handoff setup are removed. No new native, physical-phone, timing or deployed-host proof is implied." ], "demotionRule": "Cannot promote while a supported stream path has uncapped snapshot or live-output buffering." }, @@ -12767,14 +12782,14 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/5308", "https://github.com/stablyai/orca/issues/7547", "https://github.com/stablyai/orca/issues/8212" ], "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", - "oracle": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", + "oracle": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", @@ -13204,7 +13219,11 @@ "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", - "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed." + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed.", + "Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed.", + "Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed.", + "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired." ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, @@ -14448,10 +14467,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coverageNotes": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "oracle": "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. 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): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", "commands": [ "gh workflow run packaged-browser-e2e.yml", "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", @@ -14529,7 +14548,11 @@ "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", - "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed." + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed.", + "Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed.", + "Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed.", + "Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, diff --git a/config/renderer-layout-writer-baseline.txt b/config/renderer-layout-writer-baseline.txt index 1c132f4e79c..750730bd624 100644 --- a/config/renderer-layout-writer-baseline.txt +++ b/config/renderer-layout-writer-baseline.txt @@ -17,7 +17,7 @@ 4 src/renderer/src/components/terminal-pane/render-health/recovery/terminal-recovery-ledger-test-store.ts 3 src/renderer/src/components/worktree-jump/worktree-jump-palette-status-inputs.ts 1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts -4 src/renderer/src/lib/floating-workspace-terminal-actions.ts +4 src/renderer/src/components/floating-terminal/floating-workspace-terminal-actions.ts 1 src/renderer/src/lib/pane-manager/client-hosted-browser-row-state.ts 4 src/renderer/src/lib/workspace/persistence/session-write-subscriber.ts 1 src/renderer/src/lib/workspace/persistence/workspace-session-browser-tabs.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 41126b14233..0c11d32079d 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -5318,8 +5318,6 @@ "src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx": 5296, "src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx": 2493, "src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx": 1043, - "src/renderer/src/components/new-workspace/ProjectCombobox.test.tsx": 848, - "src/renderer/src/components/new-workspace/ProjectComboboxRow.test.tsx": 415, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx": 1387, @@ -5482,7 +5480,6 @@ "src/renderer/src/components/settings/browser/BrowserUserAgentSetting.test.tsx": 2325, "src/renderer/src/components/settings/chat/ChatNamingSetting.test.tsx": 2454, "src/renderer/src/components/settings/chat/ChatPermissionSetting.test.tsx": 834, - "src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx": 2540, "src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx": 2718, "src/renderer/src/lib/skills/runtime/skill-runtime-command.test.ts": 1670, "src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.test.tsx": 1025, @@ -5511,7 +5508,6 @@ "src/renderer/src/components/settings/terminal/appearance/TerminalContrastSetting.test.tsx": 798, "src/renderer/src/components/settings/terminal/session-management/TerminalLimitSetting.test.tsx": 1015, "src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx": 1237, - "src/renderer/src/components/settings/terminal/appearance/TerminalSettingsPreview.lifecycle.test.tsx": 595, "src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx": 401, "src/renderer/src/components/settings/voice/VoiceMicrophoneSetting.test.tsx": 957, "src/renderer/src/components/settings/voice/VoicePane.test.tsx": 1042, @@ -5524,7 +5520,6 @@ "src/renderer/src/components/settings/developer-permissions/developer-permissions-search.test.ts": 308, "src/renderer/src/components/settings/shortcuts/keybinding-diagnostic-text.test.ts": 522, "src/renderer/src/components/settings/shortcuts/keybinding-title-copy.test.ts": 227, - "src/renderer/src/lib/agent-session/launch/native-chat-provider-choice.test.tsx": 3738, "src/renderer/src/components/settings/notifications/notification-host-pending-save.test.tsx": 2029, "src/renderer/src/components/settings/repository/RepositoryJiraProjectSection.test.tsx": 463, "src/renderer/src/components/settings/repository/RepositoryPaneDraftInput.test.tsx": 314, @@ -5669,8 +5664,6 @@ "src/renderer/src/components/skills/sharing/SkillSharedLinkRow.test.tsx": 817, "src/renderer/src/components/skills/SkillsPage.test.tsx": 3822, "src/renderer/src/components/skills/catalog/skill-agent-filter.test.ts": 274, - "src/shared/skill-share-link.test.ts": 55, - "src/renderer/src/components/skills/sharing/skill-share-package-selection.test.ts": 49, "src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 207, "src/renderer/src/components/stats/usage-daily-chart.test.tsx": 333, @@ -5959,7 +5952,6 @@ "src/renderer/src/components/terminal-pane/emulation/terminal-capability-replies.test.ts": 131, "src/renderer/src/components/terminal-pane/clipboard/terminal-clipboard-paste.test.ts": 76, "src/renderer/src/components/terminal-pane/parking/retention/terminal-cold-park-timer-rearm.test.tsx": 701, - "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts": 638, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-image-path.test.ts": 61, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts": 800, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-path-writer.test.ts": 245, @@ -6344,7 +6336,7 @@ "src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts": 2094, "src/renderer/src/lib/editor/file-operations/editor-file-operation-owner.test.ts": 2848, "src/renderer/src/lib/emulator-error-copy.test.ts": 415, - "src/renderer/src/lib/ensure-hooks-confirmed.test.ts": 799, + "src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.test.ts": 799, "src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts": 3601, "src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796, "src/renderer/src/lib/feature-education-telemetry.test.ts": 52, @@ -6352,13 +6344,8 @@ "src/renderer/src/lib/file-search-selection.test.ts": 51, "src/renderer/src/lib/find-query-bounds.test.ts": 45, "src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872, - "src/renderer/src/lib/focus-terminal-tab-surface.split-focus.test.ts": 331, - "src/renderer/src/lib/foreground-terminal-tabs.test.ts": 55, - "src/shared/new-workspace/github-links.test.ts": 76, + "src/renderer/src/components/terminal-pane/parking/retention/foreground-terminal-tabs.test.ts": 55, "src/renderer/src/lib/work-items/github/github-source-runtime-context.test.ts": 62, - "src/shared/new-workspace/gitlab-links.test.ts": 56, - "src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1904, - "src/renderer/src/lib/host-chat-program.test.ts": 2419, "src/renderer/src/lib/host-mirror-handle-gap-drain.test.ts": 1706, "src/renderer/src/lib/host-mirror-handle-gap-resume.test.ts": 1811, "src/renderer/src/lib/host-mirrored-pane-resume-replay.test.ts": 1814, @@ -6403,12 +6390,8 @@ "src/renderer/src/lib/monaco-languages/textmate-token-provider.test.ts": 245, "src/renderer/src/lib/monaco-languages/zig-highlighting.test.ts": 7984, "src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts": 2773, - "src/renderer/src/lib/new-workspace.test.ts": 4534, - "src/renderer/src/lib/non-secure-context-crypto.repro.test.ts": 1691, - "src/renderer/src/lib/onboarding-folder-cancellation.test.ts": 2486, "src/renderer/src/lib/open-agent-message-sender.test.ts": 1497, "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts": 545, - "src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts": 884, "src/renderer/src/lib/order-empty-query-worktrees.test.ts": 62, "src/renderer/src/lib/os-file-drop-cancellation-guard.test.ts": 204, "src/renderer/src/lib/os-file-drop-preload-integration.test.tsx": 353, @@ -6424,7 +6407,6 @@ "src/renderer/src/lib/pane-manager/pane-layout-geometry-apply.test.ts": 897, "src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts": 69, "src/renderer/src/lib/pane-manager/pane-manager-spawn-placement.test.ts": 766, - "src/renderer/src/lib/pane-manager/pane-overlay-focus.test.ts": 622, "src/renderer/src/lib/pane-manager/pane-scroll.test.ts": 153, "src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts": 43, "src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts": 88, @@ -6469,20 +6451,20 @@ "src/renderer/src/lib/pane-manager/xterm-parse-barrier.test.ts": 154, "src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts": 1266, "src/renderer/src/lib/pane-manager/xterm-write-callback-guard.test.ts": 53, - "src/renderer/src/lib/pane-spawn-deferral-drain.test.ts": 61, - "src/renderer/src/lib/parked-terminal-host-hydration.test.ts": 274, + "src/renderer/src/components/terminal-pane/session-restore/spawn-deferral/pane-spawn-deferral-drain.test.ts": 61, + "src/renderer/src/components/terminal-pane/mounting/parked-terminal-host-hydration.test.ts": 274, "src/renderer/src/lib/text-input/paste/paste-payload-metadata.test.ts": 53, "src/renderer/src/lib/path-head-elision.test.ts": 53, "src/renderer/src/lib/path.test.ts": 55, "src/renderer/src/lib/plugin-command-keybindings.test.ts": 1909, "src/renderer/src/lib/plugin-command-replacements.test.ts": 95, "src/renderer/src/lib/plugin-icons/plugin-icon-svg.test.ts": 231, - "src/renderer/src/lib/plugin-monaco-token-rules.test.ts": 51, + "src/renderer/src/lib/editor/appearance/plugin-monaco-token-rules.test.ts": 51, "src/renderer/src/lib/source-control/review/pr-bot-author-overrides.test.ts": 349, "src/renderer/src/lib/source-control/review/comments/pr-comment-thread-resolution.test.ts": 48, - "src/renderer/src/lib/project-clone-url-prefill.test.ts": 61, - "src/renderer/src/lib/project-host-workspace-target.jira-mapping.test.ts": 76, - "src/renderer/src/lib/project-host-workspace-target.test.ts": 92, + "src/renderer/src/lib/workspace/creation/project-clone-url-prefill.test.ts": 61, + "src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts": 76, + "src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts": 92, "src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx": 285, "src/renderer/src/lib/react-commit-cascade-observer.test.ts": 189, "src/renderer/src/lib/react-commit-cascade-telemetry.test.ts": 159, @@ -6523,7 +6505,6 @@ "src/renderer/src/lib/simulator/tabs/simulator-pane-shutdown-scheduler.test.ts": 1679, "src/renderer/src/lib/simulator/tabs/simulator-tab-layout-owner.test.ts": 2398, "src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts": 1903, - "src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts": 547, "src/renderer/src/lib/source-control/remote/source-control-remote-error.test.ts": 340, "src/renderer/src/lib/ssh-config-passive-sync.test.ts": 1513, "src/renderer/src/lib/state-collection-byte-estimate.test.ts": 86, @@ -6538,7 +6519,7 @@ "src/renderer/src/lib/syntax-highlighting/textmate-core.test.ts": 60, "src/renderer/src/lib/tab-agent-status-index.test.ts": 210, "src/renderer/src/lib/task-provider-error-copy.test.ts": 363, - "src/renderer/src/lib/terminal-app-theme.test.ts": 301, + "src/renderer/src/app-shell/appearance/terminal-app-theme.test.ts": 301, "src/renderer/src/lib/terminal-input-activity-coalescing.test.ts": 43, "src/renderer/src/lib/text-input/paste/text-control-paste-ownership.test.ts": 217, "src/renderer/src/lib/text-input/paste/text-control-paste.test.ts": 222, @@ -6554,9 +6535,7 @@ "src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts": 2432, "src/renderer/src/lib/window-visibility-interval.test.ts": 48, "src/renderer/src/lib/window-visibility-timeout-poller.test.ts": 207, - "src/renderer/src/lib/windows-terminal-capabilities-race.test.ts": 450, - "src/renderer/src/lib/windows-terminal-capabilities.test.ts": 585, - "src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts": 198, + "src/renderer/src/runtime/hosts/capabilities/windows-terminal-capabilities-race.test.ts": 450, "src/renderer/src/lib/workspace/activation/workspace-activation-path-gate.test.ts": 2107, "src/renderer/src/lib/browser/workspace/workspace-browser-tab-open-placement.test.ts": 1996, "src/renderer/src/lib/workspace-doc-address-input.test.ts": 470, @@ -8048,8 +8027,6 @@ "tests/e2e/structured-session-tab-close-regressions.unit.test.ts": 32432, "tests/e2e/sustained-agent-typing-load-scripts.unit.test.ts": 2169, "tests/e2e/task-page-linear-refresh-authority.unit.test.ts": 5548, - "tests/e2e/task-page-linear-refresh-transport.unit.test.ts": 2019, - "tests/e2e/terminal-agent-fork-draft-ownership.unit.test.ts": 30195, "tests/e2e/terminal-binding-crash-hydration.unit.test.ts": 1769, "tests/e2e/terminal-foreground-confirmation.unit.test.ts": 644, "tests/e2e/terminal-perf-presentation.unit.test.ts": 60, diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 0a28a818ae2..a8dddc16970 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -48,6 +48,7 @@ const RATCHET_INPUTS = { 'check-repo-host-read-ratchet.mjs': ['src/cli/', 'src/main/', 'src/shared/'], 'check-runtime-electron-ratchet.mjs': ['src/main/', 'src/cli/', 'src/shared/'], 'check-tab-map-seam-ratchet.mjs': ['src/renderer/src/'], + 'check-terminal-parking-ownership-ratchet.mjs': ['src/renderer/src/'], 'check-unproven-pty-retirement-ratchet.mjs': ['src/main/'], 'check-workspace-record-read-ratchet.mjs': ['src/renderer/src/'], 'check-worktree-id-composer-ratchet.mjs': ['src/', 'mobile/src/'] diff --git a/config/scripts/preflight/changed-checks/run-lint.mjs b/config/scripts/preflight/changed-checks/run-lint.mjs index 85e16fbc944..2e4afe7b826 100644 --- a/config/scripts/preflight/changed-checks/run-lint.mjs +++ b/config/scripts/preflight/changed-checks/run-lint.mjs @@ -41,6 +41,7 @@ export const LINT_STEPS = [ 'check:ts-nocheck-ratchet', 'check:workspace-record-read-ratchet', 'check:tab-map-seam-ratchet', + 'check:terminal-parking-ownership-ratchet', 'check:unproven-pty-retirement-ratchet', 'check:daemon-blocking-call-ratchet', 'check:main-sync-fs-ratchet', diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs deleted file mode 100644 index 7f4a6dfb6b1..00000000000 --- a/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs +++ /dev/null @@ -1,87 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { CONSUMERS, consumerViolations, writerViolations } from './check-tab-map-seam-ratchet.mjs' - -const BRIDGE = - 'src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx' -const rules = CONSUMERS.get(BRIDGE) - -describe('tab-map seam guard', () => { - it('rejects an ordinary handler reaching the cold path or walking a map', () => { - const text = [ - 'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)', - 'const reconcile = () => reconcileFromSnapshot()', - 'const ordinary = () => { reconcileFromSnapshot(); Object.keys(source) }' - ].join('\n') - expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ - 'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path', - 'bridge.tsx:3 Object.keys outside a named cold path' - ]) - }) - - it('rejects an unreviewed value import, not type imports', () => { - const text = [ - "import { wholeMap } from './new-walk'", - "import type { Walk } from './new-walk'" - ].join('\n') - expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ - 'bridge.tsx:1 imports wholeMap; repaired consumers import only reviewed helpers' - ]) - }) - - it('follows a raw record through a local binding unless it is marked full resync', () => { - const text = [ - 'function raw(state) {', - ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', - ' set({ unifiedTabsByWorktree: next })', - '}', - 'function annotated(state) {', - ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', - ' markFullResync(next, "hydration")', - ' set({ unifiedTabsByWorktree: next })', - '}' - ].join('\n') - expect(writerViolations('writer.ts', text)).toEqual([ - 'writer.ts:3 raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync' - ]) - }) - - it('follows aliases of cold helpers and enumerators', () => { - const text = [ - 'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)', - 'const reconcile = () => reconcileFromSnapshot()', - 'const resync = reconcileFromSnapshot', - 'const keys = Object.keys' - ].join('\n') - expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ - 'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path', - 'bridge.tsx:4 Object.keys outside a named cold path' - ]) - }) - - it('follows aliased raw records and requires annotation before publication', () => { - const raw = - 'raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync' - const text = [ - 'function aliased(state) {', - ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', - ' const unifiedTabsByWorktree = next', - ' set({ unifiedTabsByWorktree })', - '}', - 'function late(state) {', - ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', - ' set({ unifiedTabsByWorktree: next })', - ' markFullResync(next, "hydration")', - '}', - 'function early(state) {', - ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', - ' const alias = next', - ' markFullResync(alias, "hydration")', - ' set({ unifiedTabsByWorktree: alias })', - '}' - ].join('\n') - expect(writerViolations('writer.ts', text)).toEqual([ - `writer.ts:4 ${raw}`, - `writer.ts:8 ${raw}` - ]) - }) -}) diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs new file mode 100644 index 00000000000..276f658f30c --- /dev/null +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs @@ -0,0 +1,478 @@ +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import ts from 'typescript-api' + +const RENDERER = 'src/renderer/src/' +const WATCHERS = `${RENDERER}components/terminal-pane/parking/output-watchers/` +const ROOTS = new Map([ + [ + `${RENDERER}components/terminal/terminal-provider-snapshot-bound-pty-ids.ts`, + ['createTerminalProviderSnapshotBoundPtyIdsSelector'] + ], + [`${RENDERER}components/use-terminal-watcher-effects.ts`, ['useTerminalWatcherEffects']], + [`${RENDERER}components/use-terminal-parking-pass.ts`, ['useTerminalParkingPass']], + [ + `${RENDERER}components/terminal-parking-pass-candidates.ts`, + ['collectTerminalParkingPassCandidates'] + ], + [`${RENDERER}components/terminal/split-group-mount.ts`, ['anyMountedWorktreeHasLayout']], + [ + `${RENDERER}components/terminal-pane/parking/lifecycle/use-parked-terminal-watcher-synchronization.ts`, + ['useParkedTerminalWatcherSynchronization'] + ], + [ + `${RENDERER}components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.ts`, + ['useTerminalTabColdParking'] + ], + [ + `${WATCHERS}terminal-parked-tab-watchers.ts`, + ['syncParkedTerminalTabWatchers', 'canWatcherCoverParkedTerminalTab'] + ], + [`${WATCHERS}parked-terminal-tab-coverage.ts`, ['canWatcherCoverParkedTerminalTab']], + [ + `${RENDERER}lib/agent-session/resume/resume-sleeping-agent-session.ts`, + ['resumeSleepingAgentSessionsForWorktree'] + ] +]) +const HOT_MAPS = new Set([ + 'tabsByWorktree', + 'unifiedTabsByWorktree', + 'terminalLayoutsByTabId', + 'sleepingAgentSessionsByPaneKey' +]) +const OWNER_ROOTS = [ + { + rel: 'store/terminals/terminal-parking-input-owner.ts', + name: 'acceptTerminalParkingInputs', + inputs: [] + }, + { + rel: 'store/terminals/terminal-parking-input-owner.ts', + name: 'publishAcceptedTerminalParkingInputs', + inputs: [] + }, + { + rel: 'store/terminals/terminal-parking-input-owner.ts', + name: 'invalidateTerminalParkingPtyInputs', + inputs: [] + }, + { + rel: 'store/terminals/terminal-tab-owner-index.ts', + name: 'update', + inputs: ['tabsByWorktree'] + }, + { rel: 'store/terminals/sleeping-agent-record-index.ts', name: 'update', inputs: ['records'] }, + { + rel: 'store/terminals/sleeping-agent-record-index.ts', + name: 'acceptTransition', + inputs: ['previous', 'next'] + }, + { + rel: 'lib/workspace/tabs/worktree-tab-bucket-projection.ts', + name: 'project', + inputs: ['source'] + } +] +const KEY_DIFFS = new Set([ + `${RENDERER}store/terminals/terminal-parking-input-owner.ts#diffUnknownParkingRecordKeys`, + `${RENDERER}store/terminals/terminal-tab-owner-index.ts#diffUnknownTabOwnerKeys`, + `${RENDERER}store/terminals/sleeping-agent-record-index.ts#diffUnknownSleepingRecordKeys`, + `${RENDERER}lib/workspace/tabs/worktree-tab-bucket-projection.ts#diffUnknownProjectionKeys` +]) +const COLD_RESYNCS = new Set([ + `${RENDERER}store/terminals/terminal-parking-input-owner.ts#resyncTerminalParkingWorkspaceIds`, + `${RENDERER}store/terminals/sleeping-agent-record-index.ts#resyncSleepingAgentRecordKeys` +]) + +function isColdResyncCall(node, source) { + for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { + if ( + ts.isConditionalExpression(ancestor) && + ancestor.condition.getText(source) === 'previous' && + node.pos >= ancestor.whenFalse.pos + ) { + return true + } + if ( + ts.isBinaryExpression(ancestor) && + ancestor.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && + ancestor.left.getText(source) === 'keys' + ) { + return true + } + if ( + ts.isIfStatement(ancestor) && + node.pos >= ancestor.thenStatement.pos && + node.end <= ancestor.thenStatement.end + ) { + const condition = ancestor.expression.getText(source).replace(/\s+/g, ' ') + if ( + condition === 'ptyIds === undefined' || + condition.includes( + 'previous.settings?.terminalSshViewParking !== state.settings?.terminalSshViewParking' + ) + ) { + return true + } + } + } + return false +} +const STORE_BOUNDARIES = new Set([`${RENDERER}store/index.ts`, `${RENDERER}store.ts`]) +// Resource delivery and startup recovery are separate entry points, not parking input discovery. +const EFFECT_BOUNDARIES = new Set([ + `${RENDERER}components/terminal/terminal-provider-snapshot-bound-pty-ids.ts#resyncUnknownSnapshot`, + `${RENDERER}components/terminal/use-terminal-startup-activation.ts#useTerminalStartupActivation`, + `${WATCHERS}terminal-parked-pty-watcher.ts#startParkedPtyWatcher`, + `${RENDERER}components/terminal-pane/parking/capture/parked-terminal-buffer-capture.ts#captureParkedTerminalBuffers`, + `${RENDERER}lib/agent-session/resume/sleeping-agent-session-launch.ts#launchSleepingAgentSession`, + `${RENDERER}lib/host-mirror-handle-gap-wait.ts#parkUntilHostMirrorHandleLands`, + `${RENDERER}runtime/web-session-tabs-sync/hydration/host-session-mirror-hydration.ts#parkUntilHostSessionMirrorHydrates` +]) +const ENUMERATORS = new Set(['entries', 'values', 'keys', 'assign']) + +const ADDRESSED_FIELDS = new Set([ + 'terminalLayoutsByTabId', + 'ptyIdsByTabId', + 'lastKnownRelayPtyIdByTabId', + 'runtimePaneTitlesByTabId', + 'pendingStartupByTabId', + 'sleepingAgentSessionsByPaneKey' +]) +const ORDINARY_WRITERS = [ + 'store/terminals/terminal-layout-state.ts', + 'store/terminals/terminal-pane-hibernation.ts', + 'store/terminals/terminal-pty-bindings.ts', + 'store/terminals/terminal-pty-release.ts', + 'store/terminals/terminal-orphan-cleanup.ts', + 'store/terminals/terminal-startup-queues.ts', + 'store/terminals/terminal-tab-presentation.ts', + 'store/terminals/terminal-shutdown-state.ts', + 'store/terminals/window-tab-start-in-main.ts', + 'store/slices/agent-status/agent-status-live-reducer.ts', + 'store/slices/agent-status/agent-status-launch-actions.ts', + 'store/slices/agent-status/agent-status-provider-session-actions.ts', + 'store/slices/agent-status/agent-status-recovery-actions.ts', + 'store/slices/agent-status/agent-status-authority-actions.ts' +].map((rel) => RENDERER + rel) +const RECORD_TRANSITIONS = new Set([ + 'replaceRecordEntries', + 'removePaneKeys', + 'removePaneKeysByTabPrefix' +]) + +function collectUnaddressedWrites(root) { + const violations = [] + for (const rel of ORDINARY_WRITERS) { + const { source, aliases, assignments } = readModule(root, rel) + function addressed(value, field, seen = new Set()) { + if (ts.isCallExpression(value) && ts.isIdentifier(value.expression)) { + return RECORD_TRANSITIONS.has(value.expression.text) + } + if (ts.isPropertyAccessExpression(value)) { + return value.name.text === field + } + if (ts.isConditionalExpression(value)) { + return addressed(value.whenTrue, field, seen) && addressed(value.whenFalse, field, seen) + } + if (ts.isIdentifier(value)) { + if (seen.has(value.text)) { + return false + } + seen.add(value.text) + const alias = aliases.get(value.text) + return ( + alias !== undefined && + [alias, ...(assignments.get(value.text) ?? [])].every((replacement) => + addressed(replacement, field, new Set(seen)) + ) + ) + } + return false + } + function visit(node) { + if (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) { + const field = + ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : null + const value = ts.isPropertyAssignment(node) ? node.initializer : node.name + if (ADDRESSED_FIELDS.has(field) && !addressed(value, field)) { + const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1 + violations.push(`${rel}:${line}: ${field} write needs complete record-key provenance.`) + } + } + ts.forEachChild(node, visit) + } + visit(source) + } + return violations +} + +function resolveImport(root, from, specifier) { + const base = specifier.startsWith('@/') + ? RENDERER + specifier.slice(2) + : specifier.startsWith('.') + ? path.posix.join(path.posix.dirname(from), specifier) + : null + if (!base) { + return null + } + return ( + [base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`].find( + (candidate) => + fs.existsSync(path.join(root, candidate)) && + fs.statSync(path.join(root, candidate)).isFile() + ) ?? null + ) +} + +function readModule(root, rel) { + const source = ts.createSourceFile( + rel, + fs.readFileSync(path.join(root, rel), 'utf8'), + ts.ScriptTarget.Latest, + true + ) + const imports = new Map() + const functions = new Map() + const aliases = new Map() + const assignments = new Map() + function visit(node) { + if ( + ts.isBinaryExpression(node) && + ts.isIdentifier(node.left) && + node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && + node.operatorToken.kind <= ts.SyntaxKind.LastAssignment + ) { + const values = assignments.get(node.left.text) ?? [] + values.push(node.right) + assignments.set(node.left.text, values) + } + if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { + const target = resolveImport(root, rel, node.moduleSpecifier.text) + const bindings = node.importClause?.namedBindings + if (target && bindings && ts.isNamedImports(bindings)) { + for (const binding of bindings.elements) { + imports.set(binding.name.text, { + rel: target, + name: binding.propertyName?.text ?? binding.name.text + }) + } + } + } + if ( + (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) && + node.name && + node.body + ) { + functions.set(node.name.text, node) + } + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) { + aliases.set(node.name.text, node.initializer) + if (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer)) { + functions.set(node.name.text, node.initializer) + } + } + ts.forEachChild(node, visit) + } + visit(source) + return { source, imports, functions, aliases, assignments } +} + +export function collectParkingOwnershipViolations(root = process.cwd()) { + const modules = new Map() + const pending = [...ROOTS].flatMap(([rel, names]) => + names.map((name) => ({ rel, name, tainted: new Set() })) + ) + for (const { rel, name, inputs } of OWNER_ROOTS) { + pending.push({ rel: RENDERER + rel, name, tainted: new Set(inputs) }) + } + const visited = new Set() + const violations = new Set() + while (pending.length) { + const { rel, name, tainted } = pending.pop() + if (STORE_BOUNDARIES.has(rel) || EFFECT_BOUNDARIES.has(`${rel}#${name}`)) { + continue + } + const identity = `${rel}#${name}#${[...tainted].sort().join(',')}` + if (visited.has(identity)) { + continue + } + visited.add(identity) + let mod = modules.get(rel) + if (!mod) { + modules.set(rel, (mod = readModule(root, rel))) + } + const fn = mod.functions.get(name) + if (!fn) { + continue + } + function hotMap(node, seen = new Set()) { + if (ts.isPropertyAccessExpression(node)) { + if (HOT_MAPS.has(node.name.text)) { + return true + } + if (ts.isIdentifier(node.expression)) { + const value = mod.aliases.get(node.expression.text) + if (value && ts.isObjectLiteralExpression(value)) { + const property = value.properties.find( + (candidate) => + ts.isPropertyAssignment(candidate) && + candidate.name.getText(mod.source) === node.name.text + ) + if (property && ts.isPropertyAssignment(property)) { + return hotMap(property.initializer, seen) + } + } + } + return false + } + if (ts.isElementAccessExpression(node)) { + return ( + ts.isStringLiteral(node.argumentExpression) && HOT_MAPS.has(node.argumentExpression.text) + ) + } + if (ts.isIdentifier(node)) { + if (HOT_MAPS.has(node.text) || tainted.has(node.text)) { + return true + } + if (seen.has(node.text)) { + return false + } + seen.add(node.text) + const alias = mod.aliases.get(node.text) + return alias ? hotMap(alias, seen) : false + } + if ( + ts.isParenthesizedExpression(node) || + ts.isAsExpression(node) || + ts.isNonNullExpression(node) + ) { + return hotMap(node.expression, seen) + } + if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken + ) { + return hotMap(node.left, seen) + } + return false + } + function report(node) { + const line = mod.source.getLineAndCharacterOfPosition(node.getStart(mod.source)).line + 1 + violations.add( + `${rel}:${line}: ${name} enumerates a whole parking input; use the addressed owner or a named source resync.` + ) + } + function visit(node) { + if ( + ts.isFunctionDeclaration(node) && + node.name && + EFFECT_BOUNDARIES.has(`${rel}#${node.name.text}`) + ) { + return + } + if (ts.isForInStatement(node) && hotMap(node.expression)) { + report(node) + } + if (ts.isCallExpression(node)) { + const callee = node.expression + if ( + ts.isPropertyAccessExpression(callee) && + ts.isIdentifier(callee.expression) && + callee.expression.text === 'Object' && + ENUMERATORS.has(callee.name.text) && + node.arguments.some((arg) => hotMap(arg)) && + !(callee.name.text === 'keys' && KEY_DIFFS.has(`${rel}#${name}`)) && + !COLD_RESYNCS.has(`${rel}#${name}`) + ) { + report(node) + } + if (ts.isIdentifier(callee)) { + const target = mod.imports.get(callee.text) ?? { rel, name: callee.text } + if ( + COLD_RESYNCS.has(`${target.rel}#${target.name}`) && + !isColdResyncCall(node, mod.source) + ) { + report(node) + } + if (!STORE_BOUNDARIES.has(target.rel)) { + let targetModule = modules.get(target.rel) + if (!targetModule) { + modules.set(target.rel, (targetModule = readModule(root, target.rel))) + } + const called = targetModule.functions.get(target.name) + const parameters = new Set() + called?.parameters.forEach((parameter, index) => { + if ( + ts.isIdentifier(parameter.name) && + node.arguments[index] && + hotMap(node.arguments[index]) + ) { + parameters.add(parameter.name.text) + } + }) + if (called) { + pending.push({ ...target, tainted: parameters }) + } + } + } + } + ts.forEachChild(node, visit) + } + visit(fn.body) + } + return [...violations].sort() +} + +function collectPublicCoverageViolations(root) { + const rel = `${WATCHERS}parked-terminal-tab-coverage.ts` + const { source } = readModule(root, rel) + const privateNames = new Set([ + 'fallbackParkedPaneCandidates', + 'resolveParkedTerminalPaneCandidates', + 'capturedCoversFallback' + ]) + const violations = [] + for (const statement of source.statements) { + const exported = + ts.canHaveModifiers(statement) && + ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + const leaksDeclaration = + exported && ts.isFunctionDeclaration(statement) && privateNames.has(statement.name?.text) + const leaksNamedExport = + ts.isExportDeclaration(statement) && + statement.exportClause && + ts.isNamedExports(statement.exportClause) && + statement.exportClause.elements.some((element) => + privateNames.has(element.propertyName?.text ?? element.name.text) + ) + if (leaksDeclaration || leaksNamedExport) { + violations.push(`${rel}: raw coverage derivation must stay private to its owner.`) + } + } + return violations +} + +export function main(root = process.cwd()) { + const violations = [ + ...collectParkingOwnershipViolations(root), + ...collectUnaddressedWrites(root), + ...collectPublicCoverageViolations(root) + ] + for (const violation of violations) { + console.error(violation) + } + if (violations.length) { + return 1 + } + console.log( + 'terminal-parking-ownership: addressed consumer paths contain no whole input enumeration' + ) + return 0 +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = main() +} diff --git a/config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs new file mode 100644 index 00000000000..1b41d2349cc --- /dev/null +++ b/config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs @@ -0,0 +1,16 @@ +import { TestRunner } from 'vitest' + +export default class SharedWorkerSetupRunner extends TestRunner { + importFile(filepath, source) { + if (source === 'setup') { + // Warm transforms can key setup roots by a different URL than Vitest invalidates. + const modules = this.moduleRunner.evaluatedModules + for (const node of modules.getModulesByFile(filepath) ?? []) { + if (node.evaluated) { + modules.invalidateModule(node) + } + } + } + return super.importFile(filepath, source) + } +} diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 784ad9f736e..a095551ab09 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -170,7 +170,9 @@ const NODE_RUNTIME_INCLUDE = [ 'config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs', 'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts', 'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts', - // Reopen the WAL-backed dismissal cache read-only through the row cache, which Bun on macOS cannot. + // Reopen WAL-backed row caches read-only, which Bun on macOS cannot. + 'src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts', + 'tests/e2e/helpers/persisted-profile-state.unit.test.ts', 'src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts', 'src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts', 'src/main/ipc/notifications-subject-retirement.test.ts', diff --git a/config/tsconfig.node.json b/config/tsconfig.node.json index 563748d8a33..5702c01cc47 100644 --- a/config/tsconfig.node.json +++ b/config/tsconfig.node.json @@ -23,7 +23,7 @@ "../src/cli/runtime/runtime-access-denied.ts", "../src/cli/runtime/runtime-pid-liveness.ts", "../src/renderer/src/store/slices/worktrees/create/worktree-create-payload.ts", - "../src/renderer/src/lib/orca-hook-trust.ts", + "../src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts", "../src/renderer/src/lib/sha256.ts", "../src/renderer/src/components/native-chat/native-chat-resolution-receipt.ts", "../src/renderer/src/components/native-chat/structured-agent-question-projection.ts", diff --git a/config/vitest.config.ts b/config/vitest.config.ts index eab54372357..bfed0dadfdd 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -153,6 +153,9 @@ const sharedProjects = name: `${runtimeProject.test.name}-shared`, include: sharedWorkerFiles, isolate: false, + runner: resolve( + 'config/scripts/test-runtime/execution-policy/vitest-shared-worker-setup-runner.mjs' + ), setupFiles: [ ...runtimeProject.test.setupFiles, resolve('config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs') diff --git a/config/workspace-record-read-baseline.txt b/config/workspace-record-read-baseline.txt index b5097ed3c6d..e51180253d0 100644 --- a/config/workspace-record-read-baseline.txt +++ b/config/workspace-record-read-baseline.txt @@ -35,7 +35,7 @@ 1 src/renderer/src/runtime/hosts/wsl/local-project-runtime-workspace.ts # P5b-2 must clear: optional state field defaults to empty 1 src/renderer/src/lib/resolved-worktree-execution-host.ts # P5b-2 must clear: loosely typed state param 2 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts # P5b-2 must clear: optional state fields default to empty -2 src/renderer/src/lib/terminal-worktree-route.ts # P5b-2 must clear: the unattributed-twin check reads both catalogs directly +2 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # P5b-2 must clear: the unattributed-twin check reads both catalogs directly 3 src/renderer/src/lib/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field 2 src/renderer/src/lib/unread-badge-count.ts # reads a passed-in copy 1 src/renderer/src/lib/workspace-directory.ts # P5b-2 must clear: optional state field defaults to empty diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index ba532452c05..4ac8bba5cdb 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -27,7 +27,7 @@ import { } from '../src/notifications/push-receive' import { startPushTokenSync } from '../src/notifications/push-registration' import { ensureDesktopNotificationChannel } from '../src/notifications/desktop-notification-channel' -import { loadHostCatalog } from '../src/transport/hosts/host-store' +import { loadHostCatalog } from '../src/host-catalog/host-store' import { usePairingLinks } from '../src/navigation/use-pairing-links' import { consumeInitialLaunchIntent } from '../src/navigation/initial-launch-intent' import { recoverMobileRelayPairing } from '../src/pairing/mobile-relay-pairing-recovery' diff --git a/mobile/app/connection-log.tsx b/mobile/app/connection-log.tsx index 8fbcd0057fa..addd3b182b5 100644 --- a/mobile/app/connection-log.tsx +++ b/mobile/app/connection-log.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from import { View, Text, Pressable } from 'react-native' import { useLocalSearchParams, useRouter } from 'expo-router' import * as Clipboard from 'expo-clipboard' -import { loadHosts } from '../src/transport/hosts/host-store' +import { loadHosts } from '../src/host-catalog/host-store' import { connectionLogStore } from '../src/diagnostics/connection/persisted-connection-log-store' import { useRpcClientContext } from '../src/transport/connection/client-context' import { useHostClient } from '../src/transport/connection/host-client-hooks' @@ -22,7 +22,7 @@ import { connectionDiagnosticsScreenStyles as styles } from '../src/diagnostics/ import { useMobileColorScheme } from '../src/theme/use-mobile-color-scheme' import { NATIVE_APP_LOG_ID } from '../src/diagnostics/native-render-log' import type { ConnectionLogEntry } from '../src/diagnostics/connection/connection-log-types' -import type { HostProfile } from '../src/transport/hosts/host-profile' +import type { HostProfile } from '../src/host-catalog/host-profile' import { pressedStyle } from '../src/theme/mobile-theme' // Keep empty snapshot identity stable or useSyncExternalStore rerenders forever. diff --git a/mobile/app/h/[hostId]/edit.tsx b/mobile/app/h/[hostId]/edit.tsx index 38dc364e575..acd13c84186 100644 --- a/mobile/app/h/[hostId]/edit.tsx +++ b/mobile/app/h/[hostId]/edit.tsx @@ -18,7 +18,7 @@ import { NavBar } from '../../../src/components/nav-bar/NavBar' import { NavBarButton } from '../../../src/components/nav-bar/NavBarButton' import { themedStyleSheet } from '../../../src/theme/themed-styles' import { useMobileColorScheme } from '../../../src/theme/use-mobile-color-scheme' -import { loadHosts, updateHostNameAndEndpoint } from '../../../src/transport/hosts/host-store' +import { loadHosts, updateHostNameAndEndpoint } from '../../../src/host-catalog/host-store' import { displayHostEndpoint } from '../../../src/transport/hosts/host-endpoint' import { resolveHostEndpointEdit } from '../../../src/transport/hosts/host-endpoint-edit' import { @@ -26,12 +26,12 @@ import { usePrimeHosts, useRefreshHostClient } from '../../../src/transport/connection/host-client-hooks' -import { removeHostAndCloseClient } from '../../../src/transport/hosts/host-removal-lifecycle' -import { useHostDisplay } from '../../../src/transport/hosts/use-host-display' +import { removeHostAndCloseClient } from '../../../src/host-catalog/host-removal-lifecycle' +import { useHostDisplay } from '../../../src/host-descriptors/use-host-display' import { leaveHostRoute } from '../../../src/host-route-exit' import { ConfirmModal } from '../../../src/components/ConfirmModal' import { ListGroup, ListRow } from '../../../src/components/list/ListGroup' -import type { HostProfile } from '../../../src/transport/hosts/host-profile' +import type { HostProfile } from '../../../src/host-catalog/host-profile' import { hostOs } from '../../../src/platform/host-os' import { translate } from '../../../src/i18n/mobile-i18n' import { useMobileTranslation } from '../../../src/i18n/use-mobile-translation' diff --git a/mobile/app/terminal-settings.tsx b/mobile/app/terminal-settings.tsx index fbd32b1b284..ef85607d591 100644 --- a/mobile/app/terminal-settings.tsx +++ b/mobile/app/terminal-settings.tsx @@ -12,8 +12,8 @@ import { colors, spacing } from '../src/theme/mobile-theme' import { useMobileColorScheme } from '../src/theme/use-mobile-color-scheme' import type { Translate } from '../src/i18n/mobile-i18n' import { useMobileTranslation } from '../src/i18n/use-mobile-translation' -import { loadHosts, peekHosts } from '../src/transport/hosts/host-store' -import type { HostProfile } from '../src/transport/hosts/host-profile' +import { loadHosts, peekHosts } from '../src/host-catalog/host-store' +import type { HostProfile } from '../src/host-catalog/host-profile' import { useFocusedSettingsHostClients } from '../src/settings/settings-host-client-connections' import type { RpcClient } from '../src/transport/rpc/rpc-client-contract' import { LIST_LEADING_INSET, ListRow } from '../src/components/list/ListGroup' diff --git a/mobile/app/voice-settings.tsx b/mobile/app/voice-settings.tsx index ef3a48ea832..3bdb0a66df0 100644 --- a/mobile/app/voice-settings.tsx +++ b/mobile/app/voice-settings.tsx @@ -1,7 +1,7 @@ import { useEffect, useMemo, useState } from 'react' import { useRouter } from 'expo-router' -import { loadHosts, peekHosts } from '../src/transport/hosts/host-store' -import type { HostProfile } from '../src/transport/hosts/host-profile' +import { loadHosts, peekHosts } from '../src/host-catalog/host-store' +import type { HostProfile } from '../src/host-catalog/host-profile' import { useFocusedSettingsHostClients } from '../src/settings/settings-host-client-connections' import VoiceSettingsScreen from '../src/settings/voice-settings-screen' import { nativeVoiceSettingsOperations } from '../src/settings/native-voice-settings-operations' diff --git a/mobile/rpc-foundation/pilot-scenarios.json b/mobile/rpc-foundation/pilot-scenarios.json index e00d7a8080d..dfd3079e39d 100644 --- a/mobile/rpc-foundation/pilot-scenarios.json +++ b/mobile/rpc-foundation/pilot-scenarios.json @@ -16601,7 +16601,7 @@ "id": "notifications-push-registered", "operation": "notifications.push-registration", "family": "notifications.push-registration", - "sites": ["mobile/src/notifications/push-registration.ts"], + "sites": ["mobile/src/notifications/mobile-push-registration-operations.ts"], "schedules": [], "steps": [ { @@ -16650,7 +16650,7 @@ "id": "notifications-push-gateway-rejected", "operation": "notifications.push-registration", "family": "notifications.push-registration", - "sites": ["mobile/src/notifications/push-registration.ts"], + "sites": ["mobile/src/notifications/mobile-push-registration-operations.ts"], "schedules": [], "steps": [ { diff --git a/mobile/src/accounts/MobileAccountsScreen.tsx b/mobile/src/accounts/MobileAccountsScreen.tsx index 2ea1d8b0c18..a76da2ffa62 100644 --- a/mobile/src/accounts/MobileAccountsScreen.tsx +++ b/mobile/src/accounts/MobileAccountsScreen.tsx @@ -3,7 +3,7 @@ import { View, Text, ScrollView, ActivityIndicator } from 'react-native' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' import { useFocusEffect, useLocalSearchParams } from 'expo-router' import { ChevronLeft, RefreshCw, User } from 'lucide-react-native' -import { loadHosts, peekHosts } from '../transport/hosts/host-store' +import { loadHosts, peekHosts } from '../host-catalog/host-store' import { useForceReconnect, useHostClient } from '../transport/connection/host-client-hooks' import { useHostConnectionInputs } from '../transport/connection/client-context-connection-metrics' import { classifyConnection, isConnectionOutage } from '../transport/connection/connection-health' diff --git a/mobile/src/agent-history/ai-vault-resume-launch.ts b/mobile/src/agent-history/ai-vault-resume-launch.ts index 1926ddaa787..33594d0b2a3 100644 --- a/mobile/src/agent-history/ai-vault-resume-launch.ts +++ b/mobile/src/agent-history/ai-vault-resume-launch.ts @@ -16,7 +16,7 @@ import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agen import { parseWslUncPath } from '../../../src/shared/wsl-paths' import { resolveWindowsShellStartupFamily } from '../../../src/shared/windows-terminal-shell' import { RESUME_RPC_TIMEOUT_MS } from './ai-vault-resume-preparation' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { interpretOrThrowRefusalMessage } from '../transport/rpc/rpc-refusal-message' import { reviewTerminalCreateRun, @@ -78,7 +78,7 @@ export function buildMobileAiVaultResumeLaunch(args: { } export async function resumeAiVaultSessionInTerminal( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, launch: MobileAiVaultResumeLaunch & { clientMutationId?: string diff --git a/mobile/src/agent-history/ai-vault-resume-preparation.ts b/mobile/src/agent-history/ai-vault-resume-preparation.ts index ef8194abb8c..f35d5609657 100644 --- a/mobile/src/agent-history/ai-vault-resume-preparation.ts +++ b/mobile/src/agent-history/ai-vault-resume-preparation.ts @@ -6,7 +6,7 @@ import { } from '../../../src/shared/ai-vault/resume/ai-vault-resume-preparation' import { LOCAL_EXECUTION_HOST_ID } from '../../../src/shared/execution-host' import { aiVaultResumePreparationRun } from './mobile-ai-vault-resume-operations' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { translate } from '../i18n/mobile-i18n' // Why: without an explicit timeout, a socket drop mid-resume parks the request @@ -14,7 +14,7 @@ import { translate } from '../i18n/mobile-i18n' export const RESUME_RPC_TIMEOUT_MS = 30_000 export async function prepareMobileAiVaultSessionResume( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, session: AiVaultSession ): Promise { // Why: per-account repinning runs on the serving host, whose account diff --git a/mobile/src/agent-history/mobile-ai-vault-resume-operations.ts b/mobile/src/agent-history/mobile-ai-vault-resume-operations.ts index e3a0dbc0ef2..879c6fde5e3 100644 --- a/mobile/src/agent-history/mobile-ai-vault-resume-operations.ts +++ b/mobile/src/agent-history/mobile-ai-vault-resume-operations.ts @@ -4,7 +4,6 @@ import '../files/mobile-file-preview-operations' import { aiVaultResumePreparationSchema } from './mobile-ai-vault-resume-reply-schema' import '../browser/mobile-session-browser-reply-schema' import '../files/session-documents/mobile-file-tap-reply-schema' -import '../transport/rpc/rpc-uninterpreted-reply-schemas' // Legacy resume reads unsupported-method refusals raw to fall back to shared home. export const aiVaultResumePreparationRun = bindDeferredRpcOperation( diff --git a/mobile/src/agents/MobileAgentListRows.tsx b/mobile/src/agents/MobileAgentListRows.tsx index 0f5f5b7908b..b564b7d4bdf 100644 --- a/mobile/src/agents/MobileAgentListRows.tsx +++ b/mobile/src/agents/MobileAgentListRows.tsx @@ -12,8 +12,8 @@ import { triggerMediumImpact } from '../platform/haptics' import { colors, spacing } from '../theme/mobile-theme' import { themedStyleSheet } from '../theme/themed-styles' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import type { HostProfile } from '../transport/hosts/host-profile' -import { useHostDisplay } from '../transport/hosts/use-host-display' +import type { HostProfile } from '../host-catalog/host-profile' +import { useHostDisplay } from '../host-descriptors/use-host-display' import { agentStateLabel, formatTimeAgo, type AgentDotState } from '../worktree/agent-row-display' import { isDisclosureOpen, toggleDisclosure } from '../worktree/agent-child-disclosure' import { areStructurallyEqual } from '../worktree/structural-equality' diff --git a/mobile/src/agents/use-agent-list-row-actions.tsx b/mobile/src/agents/use-agent-list-row-actions.tsx index dcd191a4b6c..f5b45eda889 100644 --- a/mobile/src/agents/use-agent-list-row-actions.tsx +++ b/mobile/src/agents/use-agent-list-row-actions.tsx @@ -6,7 +6,7 @@ import { TransientToast, useTransientToast } from '../components/TransientToast' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useClipboardWriter } from '../platform/clipboard' import { useOpenMobileSession } from '../session/use-open-mobile-session' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { AgentActivityChange, AgentListRow } from './agent-list-rows' import type { AgentListRowHandlers } from './MobileAgentListRows' import type { AgentActivityFailure } from './use-agent-activity-writes' diff --git a/mobile/src/automations/MobileAutomationsScreen.tsx b/mobile/src/automations/MobileAutomationsScreen.tsx index 9cb62a41d91..b9efea06339 100644 --- a/mobile/src/automations/MobileAutomationsScreen.tsx +++ b/mobile/src/automations/MobileAutomationsScreen.tsx @@ -9,8 +9,8 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context' import { firstParam } from '../navigation/route-param-reader' import { useRouteHandoff } from '../navigation/route-handoff' import { useHostClient } from '../transport/connection/host-client-hooks' -import { useHostDisplay } from '../transport/hosts/use-host-display' -import { useHostProfile } from '../transport/hosts/use-host-profile' +import { useHostDisplay } from '../host-descriptors/use-host-display' +import { useHostProfile } from '../host-catalog/use-host-profile' import { useHostProtocolGates } from '../components/host-protocol-gates-context' import { NavBar, NavBarTitleButton } from '../components/nav-bar/NavBar' import { NavBarButton } from '../components/nav-bar/NavBarButton' diff --git a/mobile/src/browser/mobile-session-browser-operations.ts b/mobile/src/browser/mobile-session-browser-operations.ts index 597ef6fac7a..2dee93227b4 100644 --- a/mobile/src/browser/mobile-session-browser-operations.ts +++ b/mobile/src/browser/mobile-session-browser-operations.ts @@ -4,7 +4,6 @@ import '../files/mobile-file-preview-operations' import { browserTabCreatedSchema } from './mobile-session-browser-reply-schema' import '../agent-history/mobile-ai-vault-resume-reply-schema' import '../files/session-documents/mobile-file-tap-reply-schema' -import '../transport/rpc/rpc-uninterpreted-reply-schemas' export const sessionBrowserTabCreate = bindDeferredRpcOperation( defineRpcOperation({ diff --git a/mobile/src/components/DragReorderList.test.tsx b/mobile/src/components/DragReorderList.test.tsx index defe697b10a..e70e5fecf88 100644 --- a/mobile/src/components/DragReorderList.test.tsx +++ b/mobile/src/components/DragReorderList.test.tsx @@ -1,13 +1,6 @@ -import { probe, publishLayout, mounted, positions } from './drag-reorder-test-harness.test-fixture' -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import Animated, { useAnimatedRef, useSharedValue } from 'react-native-reanimated' +import { probe, mounted, positions } from './drag-reorder-test-harness.test-fixture' +import { act } from 'react-test-renderer' import { describe, expect, it, vi } from 'vitest' -import { DragReorderList } from './DragReorderList' -import { GripVertical } from 'lucide-react-native' - -import { queuedMessageStyles } from '../session/native-chat/input/mobile-native-chat-queued-message-styles' -import { spacing } from '../theme/mobile-theme' describe('drag completion and cancellation', () => { it('restores original positions and writes nothing when an active drag is cancelled', async () => { @@ -204,74 +197,3 @@ describe('late gesture callbacks', () => { expect(fixture.onReorder).not.toHaveBeenCalled() }) }) - -it('stops scrolling at the viewport edge when rows are replaced', async () => { - const fixture = await mounted() - probe.viewport = { pageY: 0, height: 100 } - await act(async () => { - fixture.gesture.start!({ absoluteY: 90, translationY: 0 }, true) - probe.frame!({ timeSincePreviousFrame: 16 }) - }) - expect(probe.scroll).toHaveBeenCalledTimes(1) - await fixture.updateItems(['b', 'c']) - await act(async () => probe.frame!({ timeSincePreviousFrame: 16 })) - expect(probe.scroll).toHaveBeenCalledTimes(1) - expect(probe.frameActive).toHaveBeenLastCalledWith(false) - await act(async () => fixture.root.unmount()) -}) - -it('keeps measured rows still on hold, restores cancellation, and drops by moved ID plus neighbor', async () => { - const move = vi.fn() - function Harness() { - return createElement(DragReorderList, { - items: ['a', 'b', 'c'], - itemKey: (item) => item, - rowPresentation: 'plain', - renderRow: (item, handle) => createElement('Text', null, item, handle), - onMove: move, - scrollRef: useAnimatedRef(), - scrollOffsetY: useSharedValue(0), - scrollContentHeight: useSharedValue(140) - }) - } - let root: ReturnType - await act(async () => { - root = create(createElement(Harness)) - }) - const handle = root!.root.findAllByType(Animated.View).find((node) => node.props.hitSlop)! - const handleStyle = Object.assign({}, ...handle.props.style) - const gripWidth = handle.findByType(GripVertical).props.size - const width = gripWidth + 2 * handleStyle.paddingHorizontal - const left = queuedMessageStyles.row.paddingLeft - handle.props.hitSlop.left - const right = queuedMessageStyles.row.paddingLeft + width + handle.props.hitSlop.right - expect(handleStyle.paddingHorizontal).toBe(spacing.xs) - expect([left, right]).toEqual([4, 62]) - expect(right - Math.max(0, left)).toBe(58) - const rows = root!.root.findAll( - (node) => node.type === Animated.View && typeof node.props.onLayout === 'function' - ) - await act(async () => - rows.forEach((row, index) => - row.props.onLayout({ nativeEvent: { layout: { height: index === 0 ? 100 : 20 } } }) - ) - ) - await publishLayout() - const gesture = probe.gestures.at(-3)! - const at = (translationY: number) => ({ absoluteY: 100 + translationY, translationY }) - await act(async () => { - gesture.start!(at(0), true) - gesture.update!(at(0), true) - gesture.finalize!(at(0), true) - gesture.start!(at(0), true) - gesture.update!(at(35), true) - gesture.finalize!(at(35), false) - }) - expect(move).not.toHaveBeenCalled() - await act(async () => { - gesture.start!(at(0), true) - gesture.update!(at(35), true) - gesture.finalize!(at(35), true) - }) - expect(move).toHaveBeenCalledExactlyOnceWith({ movedId: 'a', afterId: 'c' }) - await act(async () => root!.unmount()) -}) diff --git a/mobile/src/components/NewWorktreeModal.test.tsx b/mobile/src/components/NewWorktreeModal.test.tsx index 6da85abe6b3..439e4f2014e 100644 --- a/mobile/src/components/NewWorktreeModal.test.tsx +++ b/mobile/src/components/NewWorktreeModal.test.tsx @@ -62,9 +62,9 @@ vi.mock('../host-screen/host-list-queries', () => ({ (hostId && cachedRepos.get(hostId)) || null })) -import '../transport/hosts/host-descriptor-store' +import '../host-descriptors/host-descriptor-store' import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' -import { markRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' + import '../../../src/shared/execution-host' import type { ExecutionHostId } from '../../../src/shared/execution-host' @@ -231,72 +231,6 @@ describe('NewWorktreeModal project targets', () => { expect(runTargetPicker(renderer).props.selectedId).toBe('runtime:env-1') }) - async function submitFromFolder(createReply: () => Promise) { - const serverRepo = { ...repos[0]!, path: '/srv/orca' } - const server = requestsOnly( - vi.fn((method: string) => - method === 'repo.list' - ? replied({ repos: [serverRepo] }) - : method === 'worktree.create' - ? createReply() - : Promise.reject(new Error(`unexpected ${method}`)) - ) - ) - const settle = vi.fn() - - await act(async () => { - renderer = create( - createElement(NewWorktreeModal, { - visible: true, - client: requestsOnly(() => new Promise(() => {})), - serverClients: new Map([['runtime:env-1', server]]), - hostId: 'host-1', - onCreated: () => {}, - onClose: () => {}, - openExternalUrl: () => {}, - folderLaunch: { - repoId: 'repo-1', - executionHostId: 'runtime:env-1', - name: 'payments', - parentWorkspace: 'folder:f-1', - submit: { begin: () => ({ settle }), presenting: () => true } - } - }) - ) - }) - await flushUpdates() - const form = renderer.root.find((node) => typeof node.props.onCreate === 'function') - await act(async () => form.props.onCreate()) - await flushUpdates() - - const creates = vi - .mocked(server.sendRequest) - .mock.calls.filter(([method]) => method === 'worktree.create') - return { creates: creates.map(([, params]) => params), settle } - } - - it('creates from a folder attached to that folder, on its host', async () => { - const { creates, settle } = await submitFromFolder(() => - replied({ worktree: { id: 'repo-1::/srv/w/payments', displayName: 'payments' } }) - ) - expect(creates).toEqual([ - expect.objectContaining({ - repo: 'id:repo-1', - parentWorkspace: 'folder:f-1', - parentWorkspaceOrigin: 'manual' - }) - ]) - expect(settle).toHaveBeenCalledWith('created') - }) - - it("doesn't try another name when a folder create's reply is lost", async () => { - const { creates, settle } = await submitFromFolder(() => - Promise.reject(markRpcDeliveryUnknown(new Error('connection lost'))) - ) - expect(creates).toHaveLength(1) - expect(settle).toHaveBeenCalledWith('uncertain') - }) - it('ignores a stale repo list after the client changes', async () => { let resolveOldList: ((value: unknown) => void) | undefined const oldList = new Promise((resolve) => { diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index ccae8181be7..801655b778c 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -10,7 +10,7 @@ import { deriveRepoSlug, type PasteRepoCandidate } from '../tasks/smart-source-p import { useMobileComposerSource } from '../tasks/use-mobile-composer-source' import { useNewWorktreeRuntimeCapabilities } from '../tasks/worktree-create-capability' import { useWorktreeCreateBasePrefetch } from '../tasks/use-worktree-create-base-prefetch' -import { useHostDescriptor } from '../transport/hosts/host-descriptor-store' +import { useHostDescriptor } from '../host-descriptors/host-descriptor-store' import { isSameMobileWorkspaceRepo } from '../worktree/new-workspace-dialog-repo-selection' import { buildRetiredWorktreeNamesRefreshKey, diff --git a/mobile/src/components/use-connected-host-picker.test.ts b/mobile/src/components/use-connected-host-picker.test.ts index 052c1b4a5f2..d986ef795cb 100644 --- a/mobile/src/components/use-connected-host-picker.test.ts +++ b/mobile/src/components/use-connected-host-picker.test.ts @@ -1,7 +1,7 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import { useConnectedHostPicker } from './use-connected-host-picker' function host(id: string, name: string, endpoint: string): HostProfile { diff --git a/mobile/src/components/use-connected-host-picker.ts b/mobile/src/components/use-connected-host-picker.ts index e6eec0b1e13..2697c9d18b9 100644 --- a/mobile/src/components/use-connected-host-picker.ts +++ b/mobile/src/components/use-connected-host-picker.ts @@ -1,6 +1,6 @@ import { useRef, useState } from 'react' import { hostEndpointLabel } from '../transport/hosts/host-endpoint-label' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' /** Picker rows for desktops, telling apart two that share a name and endpoint. */ export function hostPickerOptions(hosts: HostProfile[]) { diff --git a/mobile/src/components/use-new-workspace-repositories.test.ts b/mobile/src/components/use-new-workspace-repositories.test.ts index 14196e03e81..09ada54c9cf 100644 --- a/mobile/src/components/use-new-workspace-repositories.test.ts +++ b/mobile/src/components/use-new-workspace-repositories.test.ts @@ -44,31 +44,25 @@ afterEach(async () => { }) describe('useNewWorkspaceRepositories initial repo', () => { - it.each([ - { order: 'desktop first', desktopFirst: true }, - { order: 'server first', desktopFirst: false } - ])( - 'picks the named host’s copy of a repo id two hosts share ($order)', - async ({ desktopFirst }) => { - const client = desktopListing(desktopFirst ? [repo()] : []) - let picked: MobileWorkspaceRepo | null = null - mounted = hookMount(() => { - picked = useNewWorkspaceRepositories({ - client, - hostId: 'host-1', - visible: true, - initialRepo: { id: 'api', executionHostId: SERVER } - }).selectedRepo - }) - mounted.mount() - await settleQueryNotifications() - // The desktop's same-id repo must not stand in while the server's listing is on its way. - expect(picked).toBeNull() + it('picks the named host’s copy of a repo id two hosts share', async () => { + const client = desktopListing([repo()]) + let picked: MobileWorkspaceRepo | null = null + mounted = hookMount(() => { + picked = useNewWorkspaceRepositories({ + client, + hostId: 'host-1', + visible: true, + initialRepo: { id: 'api', executionHostId: SERVER } + }).selectedRepo + }) + mounted.mount() + await settleQueryNotifications() + // The desktop's same-id repo must not stand in while the server's listing is on its way. + expect(picked).toBeNull() - servers.repos = new Map([[SERVER, [repo(SERVER)]]]) - act(() => mounted?.update()) - await settleQueryNotifications() - expect(picked).toMatchObject({ id: 'api', executionHostId: SERVER }) - } - ) + servers.repos = new Map([[SERVER, [repo(SERVER)]]]) + act(() => mounted?.update()) + await settleQueryNotifications() + expect(picked).toMatchObject({ id: 'api', executionHostId: SERVER }) + }) }) diff --git a/mobile/src/device-store/device-store.ts b/mobile/src/device-store/device-store.ts index c86b067d79c..adbb20ff677 100644 --- a/mobile/src/device-store/device-store.ts +++ b/mobile/src/device-store/device-store.ts @@ -7,11 +7,11 @@ import type { AESEncryptionKey } from 'expo-crypto' import { Directory, Paths } from 'expo-file-system' import { AppState } from 'react-native' import { createExpoGenerationFileSystem } from '../mobile-web-shell/generation-store-file-system' -import { loadStoredHostProfiles } from '../transport/hosts/host-metadata-store' +import { loadStoredHostProfiles } from '../host-catalog/host-metadata-store' import { readPairingKeychainItem, writePairingKeychainItem -} from '../transport/hosts/pairing-keychain' +} from '../host-credentials/pairing-keychain' import { createRootIndex, DEVICE_STORE_CAPS, diff --git a/mobile/src/diagnostics/connection-diagnostics-report.ts b/mobile/src/diagnostics/connection-diagnostics-report.ts index 3a6dd9728bf..42a9581cb3b 100644 --- a/mobile/src/diagnostics/connection-diagnostics-report.ts +++ b/mobile/src/diagnostics/connection-diagnostics-report.ts @@ -5,7 +5,7 @@ import type { MobileConnectionDiagnosticPath } from './connection/connection-log-types' import type { ConnectionState } from '../transport/connection/connection-state' -import { normalizeHostAppVersion } from '../transport/hosts/host-app-version' +import { normalizeHostAppVersion } from '../host-descriptors/host-app-version' import { formatEndpoint } from './host-reachability' import { diagnoseConnection } from './connection-diagnostics-analysis' import { redactConnectionLogEntry, redactConnectionLogText } from './connection-log-redaction' diff --git a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts index 3a895518657..fa859474b28 100644 --- a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts +++ b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { resolveDiagnosticsHostId } from './connection-diagnostics-screen-data' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' const host = (id: string): HostProfile => ({ id, diff --git a/mobile/src/diagnostics/connection-diagnostics-screen-data.ts b/mobile/src/diagnostics/connection-diagnostics-screen-data.ts index 341044db3da..360b1e437ae 100644 --- a/mobile/src/diagnostics/connection-diagnostics-screen-data.ts +++ b/mobile/src/diagnostics/connection-diagnostics-screen-data.ts @@ -1,6 +1,6 @@ import type { ConnectionLogStore } from './connection/connection-log-buffer' import type { ConnectionLogEntry } from './connection/connection-log-types' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { RpcClientContextValue } from '../transport/connection/rpc-client-context-contract' /** Route identity token: compared by reference to detect navigating away and back, never read. */ diff --git a/mobile/src/diagnostics/mobile-web-bundle-probe-row.tsx b/mobile/src/diagnostics/mobile-web-bundle-probe-row.tsx index 038c7f04810..37ab11331b1 100644 --- a/mobile/src/diagnostics/mobile-web-bundle-probe-row.tsx +++ b/mobile/src/diagnostics/mobile-web-bundle-probe-row.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react' import { View, Text, Pressable, ActivityIndicator } from 'react-native' import { Package } from 'lucide-react-native' -import { loadHosts } from '../transport/hosts/host-store' +import { loadHosts } from '../host-catalog/host-store' import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { troubleshootScreenStyles as styles } from './troubleshoot-screen-styles' @@ -9,7 +9,7 @@ import { useMobileWebBundleProbe, type MobileWebBundleProbeState } from './use-mobile-web-bundle-probe' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { Translate } from '../i18n/mobile-i18n' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { ListGroup, ListRow } from '../components/list/ListGroup' diff --git a/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx b/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx index 526bec82310..78889ea5e51 100644 --- a/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx +++ b/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import { Text, View } from 'react-native' import type { MobileWebShellUpdateFailure } from '../mobile-web-shell/mobile-web-shell-update-failure' import { processGenerationStore } from '../mobile-web-shell/process-generation-store' -import { loadHosts } from '../transport/hosts/host-store' +import { loadHosts } from '../host-catalog/host-store' import { formatUpdateFailure } from './mobile-web-shell-update-failure-copy' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { troubleshootScreenStyles as styles } from './troubleshoot-screen-styles' diff --git a/mobile/src/diagnostics/native-diagnostics-operations.test.ts b/mobile/src/diagnostics/native-diagnostics-operations.test.ts index 38cbb6e3ab2..8f57d41ce43 100644 --- a/mobile/src/diagnostics/native-diagnostics-operations.test.ts +++ b/mobile/src/diagnostics/native-diagnostics-operations.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ConnectionState } from '../transport/connection/connection-state' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import { createNativeDiagnosticsOperations } from './native-diagnostics-operations' const logStore = vi.hoisted(() => ({ diff --git a/mobile/src/diagnostics/native-diagnostics-operations.ts b/mobile/src/diagnostics/native-diagnostics-operations.ts index 0b26bc5f912..5192c6d962d 100644 --- a/mobile/src/diagnostics/native-diagnostics-operations.ts +++ b/mobile/src/diagnostics/native-diagnostics-operations.ts @@ -1,6 +1,6 @@ import { Platform } from 'react-native' import Constants from 'expo-constants' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { RpcClientContextValue } from '../transport/connection/rpc-client-context-contract' import { connectionLogStore } from './connection/persisted-connection-log-store' import { diff --git a/mobile/src/diagnostics/use-troubleshoot-diagnostics.ts b/mobile/src/diagnostics/use-troubleshoot-diagnostics.ts index 2eee9847c73..297addc4ed5 100644 --- a/mobile/src/diagnostics/use-troubleshoot-diagnostics.ts +++ b/mobile/src/diagnostics/use-troubleshoot-diagnostics.ts @@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import type { View } from 'react-native' import { Platform } from 'react-native' import { useMobileTranslation } from '../i18n/use-mobile-translation' -import { loadHostCatalog, loadHosts } from '../transport/hosts/host-store' +import { loadHostCatalog, loadHosts } from '../host-catalog/host-store' import { startDiagnosticFetchTimeout, type DiagnosticFetchTimeout diff --git a/mobile/src/dictation/mobile-dictation-setup.ts b/mobile/src/dictation/mobile-dictation-setup.ts index 61e607ca7a4..9ddcee87e81 100644 --- a/mobile/src/dictation/mobile-dictation-setup.ts +++ b/mobile/src/dictation/mobile-dictation-setup.ts @@ -3,7 +3,7 @@ import { hostDictationErrorMessage } from '../../../src/shared/host-dictation-error-messages' import { translate } from '../i18n/mobile-i18n' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import type { RpcResponse } from '../transport/rpc/rpc-wire-types' import { interpretOrThrowRefusalMessage } from '../transport/rpc/rpc-refusal-message' import '../transport/connection/stable-logical-rpc-client' @@ -128,7 +128,7 @@ export function isDictationSetupRequiredError(message: string): boolean { /** `worktreeId` asks for that repo's dictionary terms too. */ export async function fetchDictationSetup( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId?: string ): Promise { const reply = await requestDictationSetupReply(client, worktreeId ? { worktreeId } : null) @@ -150,7 +150,7 @@ export async function fetchDictationSetup( } async function requestDictationSetupReply( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, params: { worktreeId: string } | null ): Promise { try { @@ -165,7 +165,7 @@ async function requestDictationSetupReply( } export async function downloadDictationModel( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, modelId: string ): Promise { const reply = await dictationModelDownload.request(client, { modelId }) @@ -176,7 +176,7 @@ export async function downloadDictationModel( } export async function deleteDictationModel( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, modelId: string ): Promise { const reply = await dictationModelDelete.request(client, { modelId }) @@ -187,7 +187,7 @@ export async function deleteDictationModel( } export async function setDictationConfig( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, params: { enabled?: boolean modelId?: string diff --git a/mobile/src/dictation/use-mobile-dictation-live.ts b/mobile/src/dictation/use-mobile-dictation-live.ts index 13aa5f5081a..b5b89eff6f0 100644 --- a/mobile/src/dictation/use-mobile-dictation-live.ts +++ b/mobile/src/dictation/use-mobile-dictation-live.ts @@ -1,8 +1,8 @@ import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' -import { useHostDisplay } from '../transport/hosts/use-host-display' -import { useHostProfile } from '../transport/hosts/use-host-profile' +import { useHostDisplay } from '../host-descriptors/use-host-display' +import { useHostProfile } from '../host-catalog/use-host-profile' import type { MobileDictationLive } from './mobile-dictation-live-context' import { dictationFailureReason } from './mobile-dictation-controls-copy' diff --git a/mobile/src/files/mobile-chat-attachment-read.ts b/mobile/src/files/mobile-chat-attachment-read.ts index 5a68f6cc431..c3f2953ff98 100644 --- a/mobile/src/files/mobile-chat-attachment-read.ts +++ b/mobile/src/files/mobile-chat-attachment-read.ts @@ -8,7 +8,7 @@ import { type AttachmentTextRead } from '../../../src/shared/attachment-text/attachment-text-source' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' // Match the shared wire identifier without importing the host capability aggregate into this route. const AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY = 'native-chat.text-attachment-read.v1' @@ -23,7 +23,7 @@ const textRead = bindDeferredRpcOperation( }) ) -type AttachmentReaderClient = RpcOperationSender & +type AttachmentReaderClient = UnvalidatedRpcRequestPort & Pick export function createMobileChatAttachmentReader( diff --git a/mobile/src/files/native-chat-file-search-operations.ts b/mobile/src/files/native-chat-file-search-operations.ts index 44192e60de9..8f39e7d5873 100644 --- a/mobile/src/files/native-chat-file-search-operations.ts +++ b/mobile/src/files/native-chat-file-search-operations.ts @@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/r import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' import '../terminal/terminal-reply-schema' import { workspaceFilePathsSchema } from './workspace-file-paths-reply-schema' -import '../session/agent-launch/mobile-agent-detection-reply-schema' -import './session-documents/mobile-markdown-tab-reply-schema' -import '../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../terminal/session/mobile-session-terminal-reply-schema' -import '../worktree/session-worktree-record-reply-schema' -import '../session/native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../terminal/quick-commands/mobile-quick-command-reply-schema' // Skip refusals to retain suggestions; inspect method_not_found first to fall back from search to inventory. export const nativeChatFileSearchRead = bindDeferredRpcOperation( diff --git a/mobile/src/files/session-documents/mobile-file-tap-open.ts b/mobile/src/files/session-documents/mobile-file-tap-open.ts index 67a654ee852..cabeebe5a3d 100644 --- a/mobile/src/files/session-documents/mobile-file-tap-open.ts +++ b/mobile/src/files/session-documents/mobile-file-tap-open.ts @@ -12,7 +12,7 @@ import { type OpenedMobileSessionTabActivationState } from '../../session/tabs/opened-mobile-session-tab' import { isRendererUnavailableReply } from '../../transport/rpc/renderer-unavailable-reply' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' // Hard-wrap guesses can number in the hundreds; stay far below the page bridge's 64 pending requests. @@ -30,7 +30,7 @@ export type MobileFileTapFailure = { } export type OpenMobileFileTapOptions = { - client: RpcOperationSender + client: UnvalidatedRpcRequestPort hostId: string worktreeId: string worktreeName?: string diff --git a/mobile/src/files/session-documents/mobile-file-tap-operations.ts b/mobile/src/files/session-documents/mobile-file-tap-operations.ts index ce347a864c1..d4da628703a 100644 --- a/mobile/src/files/session-documents/mobile-file-tap-operations.ts +++ b/mobile/src/files/session-documents/mobile-file-tap-operations.ts @@ -4,7 +4,6 @@ import '../mobile-file-preview-operations' import { fileTapOpenedSchema } from './mobile-file-tap-reply-schema' import '../../agent-history/mobile-ai-vault-resume-reply-schema' import '../../browser/mobile-session-browser-reply-schema' -import '../../transport/rpc/rpc-uninterpreted-reply-schemas' // Best-effort taps skip refused opens; explicit Changes-screen opens instead show the host error. export const fileTapOpenRun = bindDeferredRpcOperation( diff --git a/mobile/src/files/session-documents/mobile-markdown-tab-operations.ts b/mobile/src/files/session-documents/mobile-markdown-tab-operations.ts index 6978b9515cf..2d3d4a336d6 100644 --- a/mobile/src/files/session-documents/mobile-markdown-tab-operations.ts +++ b/mobile/src/files/session-documents/mobile-markdown-tab-operations.ts @@ -19,13 +19,6 @@ export const sessionMarkdownNoteCreate = bindDeferredRpcOperation( import '../../terminal/terminal-reply-schema' import { markdownTabDocumentSchema } from './mobile-markdown-tab-reply-schema' -import '../../session/agent-launch/mobile-agent-detection-reply-schema' - -import '../../terminal/session/mobile-session-terminal-reply-schema' -import '../../worktree/session-worktree-record-reply-schema' -import '../../session/native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../workspace-file-paths-reply-schema' // Inspect renderer_unavailable before interpretation so headless hosts can fall back to disk. export const markdownTabRead = bindDeferredRpcOperation( @@ -38,8 +31,6 @@ export const markdownTabRead = bindDeferredRpcOperation( }) ) -import '../../session/tabs/mobile-session-tab-write-reply-schema' - import '../../terminal/quick-commands/mobile-quick-command-operations' export const markdownTabSave = bindDeferredRpcOperation( diff --git a/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts b/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts index ff6dfc7ddfd..31752b15f51 100644 --- a/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts +++ b/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts @@ -6,10 +6,10 @@ import { useWorkspaceRouteHandoff } from '../../navigation/workspace-route-hando import { triggerSelection } from '../../platform/haptics' import { openMobileFileTap, type FileTapSessionTab } from './mobile-file-tap-open' import { openMobileNativeChatFileTap } from '../../session/native-chat/visual/mobile-native-chat-open-file' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' type MobileFileTapHandlerOptions = { - client: RpcOperationSender | null + client: UnvalidatedRpcRequestPort | null hostId: string worktreeId: string worktreeName?: string diff --git a/mobile/src/home/MobileHomeActiveAgents.tsx b/mobile/src/home/MobileHomeActiveAgents.tsx index 4db194940c0..a8f41a222b0 100644 --- a/mobile/src/home/MobileHomeActiveAgents.tsx +++ b/mobile/src/home/MobileHomeActiveAgents.tsx @@ -2,7 +2,7 @@ import { memo } from 'react' import type { AgentListRow } from '../agents/agent-list-rows' import { MobileAgentListRows, type AgentListRowHandlers } from '../agents/MobileAgentListRows' import { useMobileTranslation } from '../i18n/use-mobile-translation' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import { areStructurallyEqual } from '../worktree/structural-equality' import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' diff --git a/mobile/src/home/MobileHomeDesktopRow.tsx b/mobile/src/home/MobileHomeDesktopRow.tsx index 2d8786ddb8a..71fb2e14a4a 100644 --- a/mobile/src/home/MobileHomeDesktopRow.tsx +++ b/mobile/src/home/MobileHomeDesktopRow.tsx @@ -6,10 +6,10 @@ import { statusDotColor } from '../components/StatusDot' import type { ConnectionVerdict } from '../transport/connection/connection-health' import { verdictDisplayLabel } from '../transport/connection/connection-health' import { mobileConnectionPathAccessibilityLabel } from '../transport/connection/mobile-connection-path-label' -import { useHostDisplay } from '../transport/hosts/use-host-display' +import { useHostDisplay } from '../host-descriptors/use-host-display' import type { MobileConnectionPath } from '../transport/connection/stable-logical-rpc-client' import type { ConnectionState } from '../transport/connection/connection-state' -import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' +import type { HostCatalogEntry, HostProfile } from '../host-catalog/host-profile' import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { homeHostWorktreeSummary, type HostWorktreeInfo } from '../worktree/home-worktree-info' diff --git a/mobile/src/home/MobileHomeHostList.tsx b/mobile/src/home/MobileHomeHostList.tsx index ad442bc3472..f336850241d 100644 --- a/mobile/src/home/MobileHomeHostList.tsx +++ b/mobile/src/home/MobileHomeHostList.tsx @@ -7,7 +7,7 @@ import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { classifyConnection } from '../transport/connection/connection-health' import { resolveHomeHostConnectionState } from '../transport/hosts/home-host-auto-connect' import type { ConnectionState } from '../transport/connection/connection-state' -import type { HostCatalogEntry } from '../transport/hosts/host-profile' +import type { HostCatalogEntry } from '../host-catalog/host-profile' import type { HostWorktreeInfo } from '../worktree/home-worktree-info' import type { HomeHostConnections } from './home-host-connection-projection' import { homeListStyles } from './home-list-styles' diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index b54010f1322..048b43c3ee9 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -23,9 +23,9 @@ import { } from '../transport/connection/host-client-hooks' import { hostEndpointLabel } from '../transport/hosts/host-endpoint-label' import { resolveHomeHostConnectionState } from '../transport/hosts/home-host-auto-connect' -import { removeHostAndCloseClient } from '../transport/hosts/host-removal-lifecycle' -import { loadHostCatalog } from '../transport/hosts/host-store' -import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' +import { removeHostAndCloseClient } from '../host-catalog/host-removal-lifecycle' +import { loadHostCatalog } from '../host-catalog/host-store' +import type { HostCatalogEntry, HostProfile } from '../host-catalog/host-profile' import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit' import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label' import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route' diff --git a/mobile/src/home/MobileHomeTasksSection.tsx b/mobile/src/home/MobileHomeTasksSection.tsx index 8df195fc8b7..cb695351164 100644 --- a/mobile/src/home/MobileHomeTasksSection.tsx +++ b/mobile/src/home/MobileHomeTasksSection.tsx @@ -6,7 +6,7 @@ import { PickerModal } from '../components/PickerModal' import { useConnectedHostPicker } from '../components/use-connected-host-picker' import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import { homeListStyles as styles } from './home-list-styles' type HomeHostSectionProps = { diff --git a/mobile/src/home/mobile-home-connection-state.ts b/mobile/src/home/mobile-home-connection-state.ts index 39353be62dd..03e3b95cf9e 100644 --- a/mobile/src/home/mobile-home-connection-state.ts +++ b/mobile/src/home/mobile-home-connection-state.ts @@ -1,6 +1,6 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../transport/connection/connection-state' -import type { HostCatalogEntry } from '../transport/hosts/host-profile' +import type { HostCatalogEntry } from '../host-catalog/host-profile' export type MobileHomeClientEntry = { hostId: string diff --git a/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx b/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx index 04b40720156..778dcb1a621 100644 --- a/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx +++ b/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx @@ -7,8 +7,8 @@ import type { Translate } from '../../i18n/mobile-i18n' import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { colors } from '../../theme/mobile-theme' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import type { HostProfile } from '../../transport/hosts/host-profile' -import { useHostDisplay } from '../../transport/hosts/use-host-display' +import type { HostProfile } from '../../host-catalog/host-profile' +import { useHostDisplay } from '../../host-descriptors/use-host-display' import { MobileHomePill } from './MobileHomeHostPill' const ALL_DESKTOPS = '__all__' diff --git a/mobile/src/home/tabs/MobileHomeAgentsTab.tsx b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx index c31b8a37079..e1029611889 100644 --- a/mobile/src/home/tabs/MobileHomeAgentsTab.tsx +++ b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx @@ -29,8 +29,8 @@ import { useSerializedStoredState } from '../../storage/use-serialized-stored-st import { colors, spacing } from '../../theme/mobile-theme' import { themedStyleSheet } from '../../theme/themed-styles' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import type { HostProfile } from '../../transport/hosts/host-profile' -import { useHostDisplay } from '../../transport/hosts/use-host-display' +import type { HostProfile } from '../../host-catalog/host-profile' +import { useHostDisplay } from '../../host-descriptors/use-host-display' import { formatTimeAgo } from '../../worktree/agent-row-display' import { homeListStyles } from '../home-list-styles' import { MobileHomeSectionHeading } from '../MobileHomeSectionHeading' diff --git a/mobile/src/home/tabs/MobileHomeAutomationsTab.tsx b/mobile/src/home/tabs/MobileHomeAutomationsTab.tsx index b385ac496eb..eeda1071407 100644 --- a/mobile/src/home/tabs/MobileHomeAutomationsTab.tsx +++ b/mobile/src/home/tabs/MobileHomeAutomationsTab.tsx @@ -20,8 +20,8 @@ import { themedStyleSheet } from '../../theme/themed-styles' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { useHostClient } from '../../transport/connection/host-client-hooks' import type { ConnectionState } from '../../transport/connection/connection-state' -import type { HostProfile } from '../../transport/hosts/host-profile' -import { useHostDisplay } from '../../transport/hosts/use-host-display' +import type { HostProfile } from '../../host-catalog/host-profile' +import { useHostDisplay } from '../../host-descriptors/use-host-display' import { homeListStyles as list } from '../home-list-styles' import { MobileHomeSectionHeading } from '../MobileHomeSectionHeading' import { MobileHomeAutomationRow, MobileHomeAutomationRunRow } from './MobileHomeAutomationRows' diff --git a/mobile/src/home/tabs/MobileHomeFeedTab.tsx b/mobile/src/home/tabs/MobileHomeFeedTab.tsx index e3c9b67cd52..3ba20626d9a 100644 --- a/mobile/src/home/tabs/MobileHomeFeedTab.tsx +++ b/mobile/src/home/tabs/MobileHomeFeedTab.tsx @@ -4,7 +4,7 @@ import { useResponsiveLayout } from '../../layout/responsive-layout' import { spacing } from '../../theme/mobile-theme' import { themedStyleSheet } from '../../theme/themed-styles' import type { AgentListRowHandlers } from '../../agents/MobileAgentListRows' -import type { HostCatalogEntry } from '../../transport/hosts/host-profile' +import type { HostCatalogEntry } from '../../host-catalog/host-profile' import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard' import { MobileHomeEmptyState } from '../MobileHomeEmptyState' import { MobileHomeHostList } from '../MobileHomeHostList' diff --git a/mobile/src/home/tabs/MobileHomeHostPill.tsx b/mobile/src/home/tabs/MobileHomeHostPill.tsx index 32897644ad4..7dd2c302d1b 100644 --- a/mobile/src/home/tabs/MobileHomeHostPill.tsx +++ b/mobile/src/home/tabs/MobileHomeHostPill.tsx @@ -10,8 +10,8 @@ import { colors, radii, spacing } from '../../theme/mobile-theme' import { themedStyleSheet } from '../../theme/themed-styles' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import type { ConnectionState } from '../../transport/connection/connection-state' -import type { HostProfile } from '../../transport/hosts/host-profile' -import { useHostDisplay } from '../../transport/hosts/use-host-display' +import type { HostProfile } from '../../host-catalog/host-profile' +import { useHostDisplay } from '../../host-descriptors/use-host-display' /** The desktop a per-desktop tab shows; it stays put until the user picks another or it is unpaired. */ export function useHomeTabHost(hosts: readonly HostProfile[], preferred: readonly HostProfile[]) { diff --git a/mobile/src/home/tabs/MobileHomeUsageTab.tsx b/mobile/src/home/tabs/MobileHomeUsageTab.tsx index 72faf6e8252..3aebd0acebb 100644 --- a/mobile/src/home/tabs/MobileHomeUsageTab.tsx +++ b/mobile/src/home/tabs/MobileHomeUsageTab.tsx @@ -25,8 +25,8 @@ import '../../theme/themed-styles' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { useHostClient } from '../../transport/connection/host-client-hooks' import type { ConnectionState } from '../../transport/connection/connection-state' -import type { HostProfile } from '../../transport/hosts/host-profile' -import { useHostDisplay } from '../../transport/hosts/use-host-display' +import type { HostProfile } from '../../host-catalog/host-profile' +import { useHostDisplay } from '../../host-descriptors/use-host-display' import { formatTimeAgo } from '../../worktree/agent-row-display' import { homeListStyles } from '../home-list-styles' import { MobileHomeSectionHeading } from '../MobileHomeSectionHeading' diff --git a/mobile/src/home/use-mobile-home-data.ts b/mobile/src/home/use-mobile-home-data.ts index a8c150b3c49..a0500640fed 100644 --- a/mobile/src/home/use-mobile-home-data.ts +++ b/mobile/src/home/use-mobile-home-data.ts @@ -30,9 +30,9 @@ import { import { selectConnectableHostProfiles, sortHostsByLastConnected -} from '../transport/hosts/host-catalog-selection' -import { loadHostCatalog } from '../transport/hosts/host-store' -import type { HostCatalogEntry } from '../transport/hosts/host-profile' +} from '../host-catalog/host-catalog-selection' +import { loadHostCatalog } from '../host-catalog/host-store' +import type { HostCatalogEntry } from '../host-catalog/host-profile' import { hostObserverOptions, type HostQuery } from '../query/host-query' import { isHostNotConnectedError } from '../query/host-query-errors' import type { RpcClient } from '../transport/rpc/rpc-client-contract' diff --git a/mobile/src/home/use-mobile-home-host-connections.ts b/mobile/src/home/use-mobile-home-host-connections.ts index 11b26c25c46..cb5838a8510 100644 --- a/mobile/src/home/use-mobile-home-host-connections.ts +++ b/mobile/src/home/use-mobile-home-host-connections.ts @@ -12,7 +12,7 @@ import { usePrimeHosts } from '../transport/connection/host-client-hooks' import { selectHomeAutoConnectHostIds } from '../transport/hosts/home-host-auto-connect' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../transport/connection/connection-state' -import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' +import type { HostCatalogEntry, HostProfile } from '../host-catalog/host-profile' import { useAllHostClients } from '../transport/connection/use-all-host-clients' import { readMobileHomeLastConnected, diff --git a/mobile/src/transport/hosts/host-catalog-credential-join.ts b/mobile/src/host-catalog/host-catalog-credential-join.ts similarity index 92% rename from mobile/src/transport/hosts/host-catalog-credential-join.ts rename to mobile/src/host-catalog/host-catalog-credential-join.ts index 5f7b45e1cc1..be175ff615b 100644 --- a/mobile/src/transport/hosts/host-catalog-credential-join.ts +++ b/mobile/src/host-catalog/host-catalog-credential-join.ts @@ -1,4 +1,4 @@ -import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import type { MobileRelayEndpoint } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import type { HostListSnapshot } from './host-list-load-sharing' import type { HostCatalogEntry, StoredHostProfile } from './host-profile' diff --git a/mobile/src/transport/hosts/host-catalog-selection.ts b/mobile/src/host-catalog/host-catalog-selection.ts similarity index 100% rename from mobile/src/transport/hosts/host-catalog-selection.ts rename to mobile/src/host-catalog/host-catalog-selection.ts diff --git a/mobile/src/host-catalog/host-connection-history.ts b/mobile/src/host-catalog/host-connection-history.ts new file mode 100644 index 00000000000..a34e4289c12 --- /dev/null +++ b/mobile/src/host-catalog/host-connection-history.ts @@ -0,0 +1,17 @@ +import { mutateStoredHosts } from './host-list-mutation-queue' + +export async function updateLastConnected(hostId: string): Promise { + try { + await mutateStoredHosts((hosts) => { + const index = hosts.findIndex((h) => h.id === hostId) + if (index === -1) { + return hosts + } + const next = hosts.slice() + next[index] = { ...next[index]!, lastConnected: Date.now() } + return next + }) + } catch { + // Swallow bookkeeping failures because void callers cannot catch them. + } +} diff --git a/mobile/src/host-catalog/host-connection-history.web.ts b/mobile/src/host-catalog/host-connection-history.web.ts new file mode 100644 index 00000000000..095f18af6dd --- /dev/null +++ b/mobile/src/host-catalog/host-connection-history.web.ts @@ -0,0 +1,2 @@ +// Recency belongs to the native host list, which this page does not show. +export const updateLastConnected = (_hostId: string): Promise => Promise.resolve() diff --git a/mobile/src/transport/hosts/host-list-load-sharing.test.ts b/mobile/src/host-catalog/host-list-load-sharing.test.ts similarity index 100% rename from mobile/src/transport/hosts/host-list-load-sharing.test.ts rename to mobile/src/host-catalog/host-list-load-sharing.test.ts diff --git a/mobile/src/transport/hosts/host-list-load-sharing.ts b/mobile/src/host-catalog/host-list-load-sharing.ts similarity index 100% rename from mobile/src/transport/hosts/host-list-load-sharing.ts rename to mobile/src/host-catalog/host-list-load-sharing.ts diff --git a/mobile/src/transport/hosts/host-list-mutation-queue.ts b/mobile/src/host-catalog/host-list-mutation-queue.ts similarity index 100% rename from mobile/src/transport/hosts/host-list-mutation-queue.ts rename to mobile/src/host-catalog/host-list-mutation-queue.ts diff --git a/mobile/src/transport/hosts/host-metadata-store.ts b/mobile/src/host-catalog/host-metadata-store.ts similarity index 100% rename from mobile/src/transport/hosts/host-metadata-store.ts rename to mobile/src/host-catalog/host-metadata-store.ts diff --git a/mobile/src/transport/hosts/host-name-identity.test.ts b/mobile/src/host-catalog/host-name-identity.test.ts similarity index 96% rename from mobile/src/transport/hosts/host-name-identity.test.ts rename to mobile/src/host-catalog/host-name-identity.test.ts index 0c4878d0ef4..b69bc8d38fb 100644 --- a/mobile/src/transport/hosts/host-name-identity.test.ts +++ b/mobile/src/host-catalog/host-name-identity.test.ts @@ -25,7 +25,7 @@ vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) -vi.mock('./host-credential-cleanup', () => ({ +vi.mock('../host-credentials/host-credential-cleanup', () => ({ cancelPendingHostCredentialCleanup: vi.fn().mockResolvedValue(undefined), recordHostCredentialCleanupIntent: vi.fn().mockResolvedValue(undefined), scheduleHostCredentialCleanup: vi.fn().mockResolvedValue(undefined), @@ -38,7 +38,7 @@ import { savePairedHost, updateHostNameAndEndpoint } from './host-store' -import { updateHostDescriptor } from './host-descriptor-persistence' +import { updateHostDescriptor } from '../host-descriptors/host-descriptor-persistence' import { resetMobileRelayHostOverlayStoreForTests } from './mobile-relay-host-overlay-store' import { StoredHostProfileSchema, type StoredHostProfile } from './host-profile' diff --git a/mobile/src/transport/hosts/host-name-identity.ts b/mobile/src/host-catalog/host-name-identity.ts similarity index 97% rename from mobile/src/transport/hosts/host-name-identity.ts rename to mobile/src/host-catalog/host-name-identity.ts index b87cf1c273f..1b5bdb878e1 100644 --- a/mobile/src/transport/hosts/host-name-identity.ts +++ b/mobile/src/host-catalog/host-name-identity.ts @@ -1,6 +1,6 @@ import { GENERATED_HOST_NAME_PATTERN, getNextHostNameFromHosts } from './host-names' import type { StoredHostProfile } from './host-profile' -import { sameHostMachine, type HostMachine } from '../../../../src/shared/host-machine-line' +import { sameHostMachine, type HostMachine } from '../../../src/shared/host-machine-line' // Resolve name identity inside host-store’s serialized mutation so display name and sources commit together; see withReportedDescriptor’s omission exception. diff --git a/mobile/src/transport/hosts/host-names.ts b/mobile/src/host-catalog/host-names.ts similarity index 100% rename from mobile/src/transport/hosts/host-names.ts rename to mobile/src/host-catalog/host-names.ts diff --git a/mobile/src/transport/hosts/host-profile.ts b/mobile/src/host-catalog/host-profile.ts similarity index 82% rename from mobile/src/transport/hosts/host-profile.ts rename to mobile/src/host-catalog/host-profile.ts index 9fb53ad7404..f74c01a0f79 100644 --- a/mobile/src/transport/hosts/host-profile.ts +++ b/mobile/src/host-catalog/host-profile.ts @@ -1,13 +1,13 @@ import { z } from 'zod' -import '../../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' import { MobileRelayEndpointSchema, type MobileRelayEndpoint -} from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' -import { NODE_PLATFORM_NAMES } from '../connection/mobile-runtime-host-platform' -import { salvagedOptional } from '../../../../src/shared/zod-salvage' -import type { HostMachine } from '../../../../src/shared/host-machine-line' -import { HostMachineSchema } from './host-status-reply-schema' +} from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import { NODE_PLATFORM_NAMES } from '../transport/connection/mobile-runtime-host-platform' +import { salvagedOptional } from '../../../src/shared/zod-salvage' +import type { HostMachine } from '../../../src/shared/host-machine-line' +import { HostMachineSchema } from '../transport/hosts/host-status-reply-schema' export type HostProfile = { id: string diff --git a/mobile/src/transport/hosts/host-removal-lifecycle.ts b/mobile/src/host-catalog/host-removal-lifecycle.ts similarity index 76% rename from mobile/src/transport/hosts/host-removal-lifecycle.ts rename to mobile/src/host-catalog/host-removal-lifecycle.ts index 4349f09127e..65ff0eff370 100644 --- a/mobile/src/transport/hosts/host-removal-lifecycle.ts +++ b/mobile/src/host-catalog/host-removal-lifecycle.ts @@ -1,12 +1,12 @@ import type { QueryClient } from '@tanstack/react-query' -import { wipeHostStore } from '../../device-store/device-store' +import { wipeHostStore } from '../device-store/device-store' import { deleteHostPageCache, forgetHostUpdateFailures -} from '../../mobile-web-shell/removed-host-shell-cache' -import { unregisterPushForRemovedHost } from '../../notifications/push-registration' -import { forgetNativeHostQueries } from '../../query/native-query-persistence' -import { forgetHostDescriptor } from './host-descriptor-store' +} from '../mobile-web-shell/removed-host-shell-cache' +import { unregisterPushForRemovedHost } from '../notifications/push-registration' +import { forgetNativeHostQueries } from '../query/native-query-persistence' +import { forgetHostDescriptor } from '../host-descriptors/host-descriptor-store' import { removeHost } from './host-store' export async function removeHostAndCloseClient( diff --git a/mobile/src/transport/hosts/host-removal-lifecycle.web.ts b/mobile/src/host-catalog/host-removal-lifecycle.web.ts similarity index 100% rename from mobile/src/transport/hosts/host-removal-lifecycle.web.ts rename to mobile/src/host-catalog/host-removal-lifecycle.web.ts diff --git a/mobile/src/transport/hosts/host-store.test.ts b/mobile/src/host-catalog/host-store.test.ts similarity index 55% rename from mobile/src/transport/hosts/host-store.test.ts rename to mobile/src/host-catalog/host-store.test.ts index 04b82058be9..9b2a3a60382 100644 --- a/mobile/src/transport/hosts/host-store.test.ts +++ b/mobile/src/host-catalog/host-store.test.ts @@ -31,24 +31,14 @@ vi.mock('react-native', () => ({ Platform: platformMock })) -vi.mock('./host-credential-cleanup', () => ({ +vi.mock('../host-credentials/host-credential-cleanup', () => ({ cancelPendingHostCredentialCleanup: (...args: unknown[]) => cancelCleanupMock(...args), recordHostCredentialCleanupIntent: (...args: unknown[]) => recordCleanupIntentMock(...args), scheduleHostCredentialCleanup: (...args: unknown[]) => scheduleCleanupMock(...args), retryPendingHostCredentialCleanups: vi.fn() })) -import { - loadHostCatalog, - loadHosts, - RelayRoutingHostRemovedError, - removeHost, - resolvePairingHostIdentity, - resetHostStoreForTests, - savePairedHost, - setRelayRouting, - updateHostNameAndEndpoint -} from './host-store' +import { loadHostCatalog, loadHosts, resetHostStoreForTests, savePairedHost } from './host-store' import { resetMobileRelayHostOverlayStoreForTests } from './mobile-relay-host-overlay-store' const HOSTS_STORAGE_KEY = 'orca:hosts' @@ -67,14 +57,6 @@ const HOST_TWO = { publicKeyB64: 'key-2', lastConnected: 0 } -const HOST_ONE_RELAY = { - v: 1 as const, - directorUrl: 'https://relay.onorca.dev', - cellUrl: 'https://relay-c1.onorca.dev', - assignmentEpoch: 7, - relayHostId: 'AbCdEf0123_-xyZ9', - e2eeFraming: 2 as const -} describe('host-store list mutations', () => { let storedHostsRaw: string @@ -134,13 +116,6 @@ describe('host-store list mutations', () => { expect(profiles.map(({ id }) => id)).toEqual([HOST_TWO.id]) }) - it('fails closed when durable host identity storage is unreadable', async () => { - asyncStorageMock.getItem.mockRejectedValueOnce(new Error('storage unavailable')) - - await expect(resolvePairingHostIdentity('key-new', 'host-new')).rejects.toThrow(/unreadable/) - expect(asyncStorageMock.setItem).not.toHaveBeenCalled() - }) - it('serves a committed replacement token when same-key metadata persistence fails', async () => { const duplicate = { ...HOST_TWO, @@ -164,148 +139,6 @@ describe('host-store list mutations', () => { loadHosts().then((hosts) => hosts.find(({ id }) => id === HOST_ONE.id)?.deviceToken) ).resolves.toBe('replacement-token') }) - - it('refuses an early same-key token write without durable cleanup intent', async () => { - const replacement = { - ...HOST_TWO, - id: 'host-replacement', - publicKeyB64: HOST_ONE.publicKeyB64, - deviceToken: 'replacement-token' - } - recordCleanupIntentMock.mockRejectedValueOnce(new Error('intent storage unavailable')) - - await expect(savePairedHost(replacement)).rejects.toThrow('intent storage unavailable') - - expect(JSON.parse(storedHostsRaw)).toEqual([HOST_ONE, HOST_TWO]) - expect(secureStoreMock.setItemAsync).not.toHaveBeenCalled() - }) - - it('refuses to resurrect a removed host during relay upgrade publication', async () => { - storedHostsRaw = JSON.stringify([HOST_TWO]) - - await expect(setRelayRouting(HOST_ONE.id, HOST_ONE_RELAY)).rejects.toBeInstanceOf( - RelayRoutingHostRemovedError - ) - - expect(JSON.parse(storedHostsRaw)).toEqual([HOST_TWO]) - expect(storedOverlayRaw).toBeNull() - expect(secureStoreMock.setItemAsync).not.toHaveBeenCalled() - }) - - it('applies concurrent rename and remove without clobbering either', async () => { - let releaseReads: (() => void) | undefined - const readsReleased = new Promise((resolve) => { - releaseReads = resolve - }) - let pendingReads = 0 - asyncStorageMock.getItem.mockImplementation(async (key: string) => { - if (key !== HOSTS_STORAGE_KEY) { - return null - } - pendingReads += 1 - if (pendingReads <= 2) { - await readsReleased - } - return storedHostsRaw - }) - - const rename = updateHostNameAndEndpoint(HOST_ONE.id, { personalName: 'Renamed Host' }) - const remove = removeHost(HOST_TWO.id) - // Overlap writers behind one read gate to expose lost updates without serialization. - await vi.waitFor(() => { - expect(pendingReads).toBeGreaterThanOrEqual(1) - }) - releaseReads?.() - await Promise.all([rename, remove]) - - expect(JSON.parse(storedHostsRaw)).toEqual([ - { ...HOST_ONE, name: 'Renamed Host', personalName: 'Renamed Host' } - ]) - }) - - it('does not wipe the host list when storage is unreadable during mutation', async () => { - storedHostsRaw = '{' - await expect(updateHostNameAndEndpoint(HOST_ONE.id, { personalName: 'Nope' })).rejects.toThrow( - /unreadable/ - ) - expect(asyncStorageMock.setItem).not.toHaveBeenCalled() - expect(storedHostsRaw).toBe('{') - }) - - // Park the slow keychain pass while a durable write invalidates it. - function gateKeychainReads(): () => void { - let release: () => void = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - secureStoreMock.getItemAsync.mockImplementation(async (key: string) => { - await gate - return key.endsWith(HOST_ONE.id) || key.endsWith(HOST_TWO.id) ? `token-${key.at(-1)}` : null - }) - return release - } - - it('does not serve a pre-removal snapshot to a load issued after the removal (#8791)', async () => { - const releaseKeychain = gateKeychainReads() - const parkedLoad = loadHosts() - await vi.waitFor(() => { - expect(secureStoreMock.getItemAsync).toHaveBeenCalled() - }) - - await removeHost(HOST_ONE.id) - const afterRemoval = loadHosts() - releaseKeychain() - - await parkedLoad - await expect(afterRemoval.then((hosts) => hosts.map((host) => host.id))).resolves.toEqual([ - HOST_TWO.id - ]) - }) - - it('does not serve a pre-rename snapshot to a load issued after the rename (#8791)', async () => { - const releaseKeychain = gateKeychainReads() - const parkedLoad = loadHosts() - await vi.waitFor(() => { - expect(secureStoreMock.getItemAsync).toHaveBeenCalled() - }) - - await updateHostNameAndEndpoint(HOST_ONE.id, { personalName: 'Living Room Mac' }) - const afterRename = loadHosts() - releaseKeychain() - - await parkedLoad - const hosts = await afterRename - expect(hosts.find((host) => host.id === HOST_ONE.id)?.name).toBe('Living Room Mac') - }) - - it('does not let a late pre-write token read poison the token cache', async () => { - const newHost = { - id: 'host-new', - name: 'New Host', - endpoint: 'ws://127.0.0.1:3', - publicKeyB64: 'key-new', - deviceToken: 'token-new', - lastConnected: 0 - } - storedHostsRaw = JSON.stringify([{ ...newHost, deviceToken: undefined }]) - let resolvePrewriteTokenRead: (token: string) => void = () => {} - secureStoreMock.getItemAsync.mockReturnValue( - new Promise((resolve) => { - resolvePrewriteTokenRead = resolve - }) - ) - - const parkedLoad = loadHosts() - await vi.waitFor(() => { - expect(secureStoreMock.getItemAsync).toHaveBeenCalled() - }) - await savePairedHost(newHost) - resolvePrewriteTokenRead('token-old') - await parkedLoad - - const hosts = await loadHosts() - expect(hosts.find((host) => host.id === newHost.id)?.deviceToken).toBe(newHost.deviceToken) - }) }) describe('host-store pairing save after an Android encryption rejection', () => { diff --git a/mobile/src/transport/hosts/host-store.ts b/mobile/src/host-catalog/host-store.ts similarity index 91% rename from mobile/src/transport/hosts/host-store.ts rename to mobile/src/host-catalog/host-store.ts index 487b1344b13..f8e09c068dd 100644 --- a/mobile/src/transport/hosts/host-store.ts +++ b/mobile/src/host-catalog/host-store.ts @@ -1,4 +1,4 @@ -import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import type { MobileRelayEndpoint } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import { HostProfileSchema } from './host-profile' import type { HostCatalogEntry, HostProfile, StoredHostProfile } from './host-profile' @@ -6,27 +6,30 @@ import { getNextHostNameFromHosts } from './host-names' import { mergeHostNameIdentity, withPersonalName } from './host-name-identity' import * as hostListLoads from './host-list-load-sharing' import { joinHostCatalogCredentials } from './host-catalog-credential-join' -import { resetPairingKeychainForTests } from './pairing-keychain' -import { readHostDeviceToken, writeHostDeviceToken } from './host-device-token-store' +import { resetPairingKeychainForTests } from '../host-credentials/pairing-keychain' +import { + readHostDeviceToken, + writeHostDeviceToken +} from '../host-credentials/host-device-token-store' import { cancelPendingHostCredentialCleanup, recordHostCredentialCleanupIntent, retryPendingHostCredentialCleanups, scheduleHostCredentialCleanup -} from './host-credential-cleanup' +} from '../host-credentials/host-credential-cleanup' import { loadMobileRelayHostRoutingState, removeMobileRelayHostRouting, removeMobileRelayHostRoutings, saveMobileRelayHostRouting } from './mobile-relay-host-overlay-store' -import { scheduleOrphanedMobileRelayCleanup } from '../relay/mobile-relay-orphan-cleanup' +import { scheduleOrphanedMobileRelayCleanup } from '../transport/relay/mobile-relay-orphan-cleanup' import { getHostCredentialWriteRevision, markHostCredentialWrite, resetHostCredentialWriteRevisionsForTests -} from './host-credential-write-revision' -import { createUnpairedHostCredentialDeletion } from '../../pairing/unpaired-host-credential-deletion' +} from '../host-credentials/host-credential-write-revision' +import { createUnpairedHostCredentialDeletion } from '../pairing/unpaired-host-credential-deletion' import { loadStoredHostProfiles, readStoredHostProfilesForMutation, @@ -148,7 +151,7 @@ function removeOrphanOverlayIfUnpaired(hostId: string): Promise { }) } -import './host-descriptor-persistence' +import '../host-descriptors/host-descriptor-persistence' export class RelayRoutingHostRemovedError extends Error {} @@ -315,22 +318,6 @@ export async function updateHostNameAndEndpoint( }) } -export async function updateLastConnected(hostId: string): Promise { - try { - await mutateStoredHosts((hosts) => { - const index = hosts.findIndex((h) => h.id === hostId) - if (index === -1) { - return hosts - } - const next = hosts.slice() - next[index] = { ...next[index]!, lastConnected: Date.now() } - return next - }) - } catch { - // Swallow bookkeeping failures because void callers cannot catch them. - } -} - export function resetHostStoreForTests(): void { resetHostListMutationQueueForTests() tokenCache.clear() diff --git a/mobile/src/transport/hosts/host-store.web.ts b/mobile/src/host-catalog/host-store.web.ts similarity index 77% rename from mobile/src/transport/hosts/host-store.web.ts rename to mobile/src/host-catalog/host-store.web.ts index 3b8e3f33ac8..37475ac40ed 100644 --- a/mobile/src/transport/hosts/host-store.web.ts +++ b/mobile/src/host-catalog/host-store.web.ts @@ -1,5 +1,5 @@ -import { readPageHostProfile } from '../../mobile-web-shell/bridge/page-host-profile' -import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import { readPageHostProfile } from '../mobile-web-shell/bridge/page-host-profile' +import type { MobileRelayEndpoint } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import type { HostCatalogEntry, HostProfile } from './host-profile' // The page gets no device credential or public key; RPC uses the shell’s paired client. @@ -26,9 +26,6 @@ export const setRelayRouting = (_hostId: string, _relay: MobileRelayEndpoint): P export const removeHost = (_hostId: string): Promise => Promise.resolve() -// Recency belongs to the native host list, which this page does not show. -export const updateLastConnected = (_hostId: string): Promise => Promise.resolve() - export function updateHostNameAndEndpoint( _hostId: string, _updates: { personalName?: string | null; endpoint?: string } diff --git a/mobile/src/transport/hosts/mobile-relay-host-overlay-store.test.ts b/mobile/src/host-catalog/mobile-relay-host-overlay-store.test.ts similarity index 78% rename from mobile/src/transport/hosts/mobile-relay-host-overlay-store.test.ts rename to mobile/src/host-catalog/mobile-relay-host-overlay-store.test.ts index 6d4daea98d3..fd4e8f54f2f 100644 --- a/mobile/src/transport/hosts/mobile-relay-host-overlay-store.test.ts +++ b/mobile/src/host-catalog/mobile-relay-host-overlay-store.test.ts @@ -74,22 +74,4 @@ describe('mobile relay host overlay store', () => { await expect(saveMobileRelayHostRouting('host-1', RELAY)).resolves.toBe(true) expect(JSON.parse(stored!)).toEqual([RELAY_ONLY_OVERLAY]) }) - - it('never overlays or resurrects a host whose legacy base was removed', async () => { - stored = JSON.stringify([LEGACY_OVERLAY]) - - await expect(loadMobileRelayHostRoutingState(new Set())).resolves.toEqual({ - relays: new Map(), - orphanHostIds: ['host-1'] - }) - expect(asyncStorage.setItem).not.toHaveBeenCalled() - expect(JSON.parse(stored)).toEqual([LEGACY_OVERLAY]) - }) - - it('refuses to overwrite unreadable overlay storage', async () => { - stored = '{' - - await expect(saveMobileRelayHostRouting('host-1', RELAY)).rejects.toThrow(/unreadable/) - expect(asyncStorage.setItem).not.toHaveBeenCalled() - }) }) diff --git a/mobile/src/transport/hosts/mobile-relay-host-overlay-store.ts b/mobile/src/host-catalog/mobile-relay-host-overlay-store.ts similarity index 96% rename from mobile/src/transport/hosts/mobile-relay-host-overlay-store.ts rename to mobile/src/host-catalog/mobile-relay-host-overlay-store.ts index 8a30cd7219a..3f4da803bd2 100644 --- a/mobile/src/transport/hosts/mobile-relay-host-overlay-store.ts +++ b/mobile/src/host-catalog/mobile-relay-host-overlay-store.ts @@ -1,5 +1,5 @@ import AsyncStorage from '@react-native-async-storage/async-storage' -import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import type { MobileRelayEndpoint } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import { MobileRelayHostOverlaySchema, toStoredMobileRelayHostOverlay, diff --git a/mobile/src/transport/hosts/mobile-relay-host-overlay.ts b/mobile/src/host-catalog/mobile-relay-host-overlay.ts similarity index 92% rename from mobile/src/transport/hosts/mobile-relay-host-overlay.ts rename to mobile/src/host-catalog/mobile-relay-host-overlay.ts index 3e82389cde5..f97d6f7cb2c 100644 --- a/mobile/src/transport/hosts/mobile-relay-host-overlay.ts +++ b/mobile/src/host-catalog/mobile-relay-host-overlay.ts @@ -2,8 +2,8 @@ import { z } from 'zod' import { MobileRelayEndpointSchema, type MobileRelayEndpoint -} from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' -import { relayConnectWebSocketUrl } from '../relay/mobile-relay-connect-url' +} from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import { relayConnectWebSocketUrl } from '../transport/relay/mobile-relay-connect-url' const MobileAccessEndpointSchema = z .object({ diff --git a/mobile/src/transport/hosts/page-host-removal-refusal.ts b/mobile/src/host-catalog/page-host-removal-refusal.ts similarity index 100% rename from mobile/src/transport/hosts/page-host-removal-refusal.ts rename to mobile/src/host-catalog/page-host-removal-refusal.ts diff --git a/mobile/src/transport/hosts/use-host-profile.ts b/mobile/src/host-catalog/use-host-profile.ts similarity index 100% rename from mobile/src/transport/hosts/use-host-profile.ts rename to mobile/src/host-catalog/use-host-profile.ts diff --git a/mobile/src/transport/hosts/host-credential-cleanup.ts b/mobile/src/host-credentials/host-credential-cleanup.ts similarity index 100% rename from mobile/src/transport/hosts/host-credential-cleanup.ts rename to mobile/src/host-credentials/host-credential-cleanup.ts diff --git a/mobile/src/transport/hosts/host-credential-write-revision.ts b/mobile/src/host-credentials/host-credential-write-revision.ts similarity index 100% rename from mobile/src/transport/hosts/host-credential-write-revision.ts rename to mobile/src/host-credentials/host-credential-write-revision.ts diff --git a/mobile/src/transport/hosts/host-device-token-store.ts b/mobile/src/host-credentials/host-device-token-store.ts similarity index 100% rename from mobile/src/transport/hosts/host-device-token-store.ts rename to mobile/src/host-credentials/host-device-token-store.ts diff --git a/mobile/src/transport/hosts/host-device-token-store.web.ts b/mobile/src/host-credentials/host-device-token-store.web.ts similarity index 100% rename from mobile/src/transport/hosts/host-device-token-store.web.ts rename to mobile/src/host-credentials/host-device-token-store.web.ts diff --git a/mobile/src/transport/hosts/mobile-relay-credential-bundle.test.ts b/mobile/src/host-credentials/mobile-relay-credential-bundle.test.ts similarity index 96% rename from mobile/src/transport/hosts/mobile-relay-credential-bundle.test.ts rename to mobile/src/host-credentials/mobile-relay-credential-bundle.test.ts index 48b66a8b2da..37e2f71cbd9 100644 --- a/mobile/src/transport/hosts/mobile-relay-credential-bundle.test.ts +++ b/mobile/src/host-credentials/mobile-relay-credential-bundle.test.ts @@ -19,7 +19,7 @@ vi.mock('expo-secure-store', () => ({ vi.mock('react-native', () => ({ Platform: platform })) import { promotePairingJournalCredential } from './mobile-relay-credential-bundle' -import type { MobileRelayPairingJournal } from '../../pairing/mobile-relay-pairing-journal' +import type { MobileRelayPairingJournal } from '../pairing/mobile-relay-pairing-journal' import { resetPairingKeychainForTests } from './pairing-keychain' const journal = { diff --git a/mobile/src/transport/hosts/mobile-relay-credential-bundle.ts b/mobile/src/host-credentials/mobile-relay-credential-bundle.ts similarity index 93% rename from mobile/src/transport/hosts/mobile-relay-credential-bundle.ts rename to mobile/src/host-credentials/mobile-relay-credential-bundle.ts index 21e103cfc40..f48b5b939d3 100644 --- a/mobile/src/transport/hosts/mobile-relay-credential-bundle.ts +++ b/mobile/src/host-credentials/mobile-relay-credential-bundle.ts @@ -1,7 +1,7 @@ import { Platform } from 'react-native' import { z } from 'zod' -import type { DeviceCredentialInstalled } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' -import type { MobileRelayPairingJournal } from '../../pairing/mobile-relay-pairing-journal' +import type { DeviceCredentialInstalled } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' +import type { MobileRelayPairingJournal } from '../pairing/mobile-relay-pairing-journal' import { deletePairingKeychainItem, readPairingKeychainItem, diff --git a/mobile/src/transport/hosts/pairing-keychain.ts b/mobile/src/host-credentials/pairing-keychain.ts similarity index 100% rename from mobile/src/transport/hosts/pairing-keychain.ts rename to mobile/src/host-credentials/pairing-keychain.ts diff --git a/mobile/src/transport/hosts/host-app-version-store.ts b/mobile/src/host-descriptors/host-app-version-store.ts similarity index 100% rename from mobile/src/transport/hosts/host-app-version-store.ts rename to mobile/src/host-descriptors/host-app-version-store.ts diff --git a/mobile/src/transport/hosts/host-app-version-store.web.ts b/mobile/src/host-descriptors/host-app-version-store.web.ts similarity index 100% rename from mobile/src/transport/hosts/host-app-version-store.web.ts rename to mobile/src/host-descriptors/host-app-version-store.web.ts diff --git a/mobile/src/transport/hosts/host-app-version.ts b/mobile/src/host-descriptors/host-app-version.ts similarity index 100% rename from mobile/src/transport/hosts/host-app-version.ts rename to mobile/src/host-descriptors/host-app-version.ts diff --git a/mobile/src/transport/hosts/host-descriptor-persistence.ts b/mobile/src/host-descriptors/host-descriptor-persistence.ts similarity index 82% rename from mobile/src/transport/hosts/host-descriptor-persistence.ts rename to mobile/src/host-descriptors/host-descriptor-persistence.ts index 12fd0d18d24..dbd342527ed 100644 --- a/mobile/src/transport/hosts/host-descriptor-persistence.ts +++ b/mobile/src/host-descriptors/host-descriptor-persistence.ts @@ -1,5 +1,8 @@ -import { mutateStoredHosts } from './host-list-mutation-queue' -import { withReportedDescriptor, type ReportedHostDescriptor } from './host-name-identity' +import { mutateStoredHosts } from '../host-catalog/host-list-mutation-queue' +import { + withReportedDescriptor, + type ReportedHostDescriptor +} from '../host-catalog/host-name-identity' // Keep authenticated descriptor upkeep best-effort; older hosts omitting both fields must not churn stored rows. export async function updateHostDescriptor( diff --git a/mobile/src/transport/hosts/host-descriptor-persistence.web.ts b/mobile/src/host-descriptors/host-descriptor-persistence.web.ts similarity index 59% rename from mobile/src/transport/hosts/host-descriptor-persistence.web.ts rename to mobile/src/host-descriptors/host-descriptor-persistence.web.ts index 43933095a61..b99ea73eb3c 100644 --- a/mobile/src/transport/hosts/host-descriptor-persistence.web.ts +++ b/mobile/src/host-descriptors/host-descriptor-persistence.web.ts @@ -1,5 +1,5 @@ -import '../../mobile-web-shell/bridge/page-host-profile' -import type { ReportedHostDescriptor } from './host-name-identity' +import '../mobile-web-shell/bridge/page-host-profile' +import type { ReportedHostDescriptor } from '../host-catalog/host-name-identity' // Last-known descriptors belong to the native host list. export function updateHostDescriptor( diff --git a/mobile/src/transport/hosts/host-descriptor-recorder.ts b/mobile/src/host-descriptors/host-descriptor-recorder.ts similarity index 83% rename from mobile/src/transport/hosts/host-descriptor-recorder.ts rename to mobile/src/host-descriptors/host-descriptor-recorder.ts index 0b5ab0e5cdb..49aad137b63 100644 --- a/mobile/src/transport/hosts/host-descriptor-recorder.ts +++ b/mobile/src/host-descriptors/host-descriptor-recorder.ts @@ -1,7 +1,7 @@ import { recordHostDescriptor } from './host-descriptor-store' -import './host-store' +import '../host-catalog/host-store' import { updateHostDescriptor } from './host-descriptor-persistence' -import type { HostStatusReply } from './host-status-reply-schema' +import type { HostStatusReply } from '../transport/hosts/host-status-reply-schema' // Update live rows and persisted last-known descriptors together; best-effort bookkeeping must never gate connection. export function recordHostDescriptorFromStatus(hostId: string, status: HostStatusReply): void { diff --git a/mobile/src/transport/hosts/host-descriptor-store.ts b/mobile/src/host-descriptors/host-descriptor-store.ts similarity index 95% rename from mobile/src/transport/hosts/host-descriptor-store.ts rename to mobile/src/host-descriptors/host-descriptor-store.ts index bb114074164..ad33c055070 100644 --- a/mobile/src/transport/hosts/host-descriptor-store.ts +++ b/mobile/src/host-descriptors/host-descriptor-store.ts @@ -1,5 +1,5 @@ import { useCallback, useSyncExternalStore } from 'react' -import { sameHostMachine, type HostMachine } from '../../../../src/shared/host-machine-line' +import { sameHostMachine, type HostMachine } from '../../../src/shared/host-machine-line' export type HostMachineDescriptor = { machineName: string | null diff --git a/mobile/src/transport/hosts/use-host-display.ts b/mobile/src/host-descriptors/use-host-display.ts similarity index 85% rename from mobile/src/transport/hosts/use-host-display.ts rename to mobile/src/host-descriptors/use-host-display.ts index 0f0e8abefe6..49ab4f235df 100644 --- a/mobile/src/transport/hosts/use-host-display.ts +++ b/mobile/src/host-descriptors/use-host-display.ts @@ -1,10 +1,10 @@ import { resolveHostDisplay, type HostDisplayResolution -} from '../../../../src/shared/host-display-resolution' +} from '../../../src/shared/host-display-resolution' import { useHostDescriptor } from './host-descriptor-store' -import { classifyLegacyHostName } from './host-name-identity' -import type { HostMachine } from '../../../../src/shared/host-machine-line' +import { classifyLegacyHostName } from '../host-catalog/host-name-identity' +import type { HostMachine } from '../../../src/shared/host-machine-line' export type HostDisplaySource = { id: string diff --git a/mobile/src/host-list-action-sheet-actions.ts b/mobile/src/host-list-action-sheet-actions.ts index 036d025d798..ea156122a5a 100644 --- a/mobile/src/host-list-action-sheet-actions.ts +++ b/mobile/src/host-list-action-sheet-actions.ts @@ -1,7 +1,7 @@ import { Activity, Edit3, PowerOff, RefreshCw } from 'lucide-react-native' import type { ActionSheetAction } from './components/ActionSheetModal' import type { ConnectionState } from './transport/connection/connection-state' -import type { HostProfile } from './transport/hosts/host-profile' +import type { HostProfile } from './host-catalog/host-profile' import { translate } from './i18n/mobile-i18n' // Defer navigation and new drawers until this native Modal unmounts; presenting into a live one freezes iOS (#8791). diff --git a/mobile/src/host-screen/host-stored-identity.ts b/mobile/src/host-screen/host-stored-identity.ts index 31d75015e5d..dd02444eb75 100644 --- a/mobile/src/host-screen/host-stored-identity.ts +++ b/mobile/src/host-screen/host-stored-identity.ts @@ -1,4 +1,4 @@ -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { HostMachine } from '../../../src/shared/host-machine-line' export type HostStoredDescriptor = { diff --git a/mobile/src/host-screen/use-host-display-worktrees.ts b/mobile/src/host-screen/use-host-display-worktrees.ts index 84f72fa8a86..517c0924fa2 100644 --- a/mobile/src/host-screen/use-host-display-worktrees.ts +++ b/mobile/src/host-screen/use-host-display-worktrees.ts @@ -1,5 +1,5 @@ import { useMemo } from 'react' -import { useHostDescriptor } from '../transport/hosts/host-descriptor-store' +import { useHostDescriptor } from '../host-descriptors/host-descriptor-store' import type { ConnectionState } from '../transport/connection/connection-state' import { serverHostHealth, diff --git a/mobile/src/host-screen/use-host-screen-controller.ts b/mobile/src/host-screen/use-host-screen-controller.ts index 983fa99eb96..e5ea6277d43 100644 --- a/mobile/src/host-screen/use-host-screen-controller.ts +++ b/mobile/src/host-screen/use-host-screen-controller.ts @@ -28,7 +28,7 @@ import { useHostViewSettings } from './use-host-view-settings' import { countActiveWorkspaceFilters } from '../../../src/shared/workspace-view/workspace-row-filters' import { useHostWorktreeActions } from './use-host-worktree-actions' import { useHostWorktreeCatalog } from './use-host-worktree-catalog' -import { useHostDisplay } from '../transport/hosts/use-host-display' +import { useHostDisplay } from '../host-descriptors/use-host-display' import { classifyConnection } from '../transport/connection/connection-health' export type HostScreenProps = { diff --git a/mobile/src/host-screen/use-host-screen-identity.ts b/mobile/src/host-screen/use-host-screen-identity.ts index f4e10c10019..057a23b8718 100644 --- a/mobile/src/host-screen/use-host-screen-identity.ts +++ b/mobile/src/host-screen/use-host-screen-identity.ts @@ -3,8 +3,9 @@ import { useQueryClient } from '@tanstack/react-query' import { translate } from '../i18n/mobile-i18n' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../src/shared/sidebar-inputs-switch' import { loadPinnedIds } from '../storage/preferences' -import { loadHosts, peekHosts, updateLastConnected } from '../transport/hosts/host-store' -import type { HostProfile } from '../transport/hosts/host-profile' +import { loadHosts, peekHosts } from '../host-catalog/host-store' +import { updateLastConnected } from '../host-catalog/host-connection-history' +import type { HostProfile } from '../host-catalog/host-profile' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { HostScreenState } from './use-host-screen-state' import { storedHostDescriptor } from './host-stored-identity' diff --git a/mobile/src/host-screen/use-host-screen-state.ts b/mobile/src/host-screen/use-host-screen-state.ts index 742a6ac91c5..4f40a1a95bb 100644 --- a/mobile/src/host-screen/use-host-screen-state.ts +++ b/mobile/src/host-screen/use-host-screen-state.ts @@ -4,7 +4,7 @@ import type { ExecutionHostId } from '../../../src/shared/execution-host' import type { ExecutionHostHealth } from '../../../src/shared/execution-host/execution-host-health' import { storedHostDescriptor, type HostStoredDescriptor } from './host-stored-identity' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import { INITIAL_MOBILE_VIEW, type MobileViewState } from '../worktree/workspace-view-settings' import type { Worktree } from '../worktree/workspace-list-sections' import type { ServedProjectSections } from '../worktree/project-sections-operations' diff --git a/mobile/src/host-screen/use-host-worktree-actions.ts b/mobile/src/host-screen/use-host-worktree-actions.ts index 5d2814b1049..d96d2e8c9ab 100644 --- a/mobile/src/host-screen/use-host-worktree-actions.ts +++ b/mobile/src/host-screen/use-host-worktree-actions.ts @@ -6,8 +6,8 @@ import { floatingWorkspaceSessionPath } from '../session/floating-workspace' import { holdSessionLeave } from '../session/session-leave-guard' import { savePinnedIds } from '../storage/preferences' import type { useForgetHostClient } from '../transport/connection/host-client-hooks' -import { removeHostAndCloseClient } from '../transport/hosts/host-removal-lifecycle' -import { isPageHostRemovalUnavailable } from '../transport/hosts/page-host-removal-refusal' +import { removeHostAndCloseClient } from '../host-catalog/host-removal-lifecycle' +import { isPageHostRemovalUnavailable } from '../host-catalog/page-host-removal-refusal' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { rpcClientForExecutionHost, diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index ab13aa29c12..4ace38e5fa1 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -3364,6 +3364,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "Zusammengeführt", + "closed": "Geschlossen", + "conflicts": "Konflikte", + "behind": "Nicht aktuell", + "blocked": "Blockiert", + "checksPending": "Prüfungen ausstehend", + "ableToMerge": "Zusammenführen möglich", + "unknown": "Unbekannt" + }, + "pagination": { + "pageUnreachable": "Seite {{page}} liegt außerhalb des Bereichs der GitHub-Suche.", + "loadPageFailed": "Seite {{page}} konnte nicht von GitHub geladen werden.", + "noMoreResults": "Keine weiteren Ergebnisse auf Seite {{page}}." + }, "composerSource": { "baseFailed": "Der Basis-Branch konnte nicht ermittelt werden.", "forkPushWarning": "Bei diesem PR ist „Allow edits from maintainers“ deaktiviert; GitHub könnte einen Push zum Fork ablehnen." diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index ad24b5ef7c1..f994d2c966b 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -1502,11 +1502,11 @@ "updateRequired": "Actualiza Orca Mobile para abrir archivos PDF" }, "unsavedEditsOffer": { - "changedSince": "Modificado en el escritorio desde tus cambios de las {{time}}", + "changedSince": "Modificado en el ordenador después de tus cambios de {{time}}", "copyMyEdits": "Copiar mis cambios", "discard": "Descartar", "restore": "Restaurar", - "unsavedFrom": "Cambios sin guardar de las {{time}}" + "unsavedFrom": "Cambios sin guardar ({{time}})" } }, "home": { @@ -3452,6 +3452,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "Fusionado", + "closed": "Cerrado", + "conflicts": "Conflictos", + "behind": "Desactualizado", + "blocked": "Bloqueado", + "checksPending": "Comprobaciones pendientes", + "ableToMerge": "Se puede fusionar", + "unknown": "Desconocido" + }, + "pagination": { + "pageUnreachable": "La página {{page}} está fuera del alcance de la búsqueda de GitHub.", + "loadPageFailed": "No se pudo cargar la página {{page}} desde GitHub.", + "noMoreResults": "No hay más resultados en la página {{page}}." + }, "composerSource": { "baseFailed": "No se pudo resolver la rama base.", "forkPushWarning": "Esta PR tiene desactivada la opción \"Allow edits from maintainers\"; GitHub podría rechazar el push al fork." diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index e825464bfe5..966264702ec 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -3452,6 +3452,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "Fusionné", + "closed": "Fermé", + "conflicts": "Conflits", + "behind": "En retard", + "blocked": "Bloqué", + "checksPending": "Vérifications en attente", + "ableToMerge": "Fusion possible", + "unknown": "Inconnu" + }, + "pagination": { + "pageUnreachable": "La page {{page}} dépasse la limite des résultats de recherche GitHub.", + "loadPageFailed": "La page {{page}} n’a pas pu être chargée depuis GitHub.", + "noMoreResults": "Aucun autre résultat sur la page {{page}}." + }, "composerSource": { "baseFailed": "Échec de la résolution de la branche de base.", "forkPushWarning": "L'option « Autoriser les modifications des mainteneurs » est désactivée pour cette PR ; le push vers le fork peut être refusé par GitHub." diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index 85a5d0e8e03..39364412640 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -3440,6 +3440,16 @@ "githubViewControls": { "openView": "GitHub でビューを開く" }, + "hostedMerge": { + "merged": "マージ済み", + "closed": "クローズ済み", + "conflicts": "競合あり", + "behind": "遅れあり", + "blocked": "ブロック中", + "checksPending": "チェック待ち", + "ableToMerge": "マージ可能", + "unknown": "不明" + }, "itemActions": { "changeStatus": "ステータスを変更", "copyGitHubLink": "GitHub リンクをコピーする", @@ -3586,6 +3596,11 @@ "updated": "更新日時", "updatedSortDescription": "アクティビティが新しい順" }, + "pagination": { + "pageUnreachable": "ページ {{page}} は GitHub 検索で取得できる範囲を超えています。", + "loadPageFailed": "ページ {{page}} を GitHub から読み込めませんでした。", + "noMoreResults": "ページ {{page}} にこれ以上の結果はありません。" + }, "pickerProjection": { "allRepos": "すべてのリポジトリ", "allSites": "すべてのサイト", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index b4ccb7ee5d9..c8304776585 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -3360,6 +3360,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "병합됨", + "closed": "닫힘", + "conflicts": "충돌", + "behind": "뒤처짐", + "blocked": "차단됨", + "checksPending": "검사 대기 중", + "ableToMerge": "병합 가능", + "unknown": "알 수 없음" + }, + "pagination": { + "pageUnreachable": "{{page}}페이지는 GitHub 검색에서 반환할 수 있는 범위를 벗어났습니다.", + "loadPageFailed": "GitHub에서 {{page}}페이지를 불러오지 못했습니다.", + "noMoreResults": "{{page}}페이지에 더 이상 결과가 없습니다." + }, "composerSource": { "baseFailed": "기본 브랜치를 확인하지 못했습니다.", "forkPushWarning": "이 PR에서 \"유지 관리자의 수정 허용\"이 꺼져 있어 GitHub에서 포크로의 푸시를 거부할 수 있습니다." diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 105fd84585f..c065a24a76f 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -3452,6 +3452,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "Mesclado", + "closed": "Fechado", + "conflicts": "Conflitos", + "behind": "Desatualizado", + "blocked": "Bloqueado", + "checksPending": "Verificações pendentes", + "ableToMerge": "Pode ser mesclado", + "unknown": "Desconhecido" + }, + "pagination": { + "pageUnreachable": "A página {{page}} está além do que a pesquisa do GitHub pode retornar.", + "loadPageFailed": "A página {{page}} não pôde ser carregada do GitHub.", + "noMoreResults": "Não há mais resultados na página {{page}}." + }, "composerSource": { "baseFailed": "Falha ao determinar a branch base.", "forkPushWarning": "Este PR está com \"Permitir edições de mantenedores\" desativado; o GitHub pode rejeitar o push para o fork." diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index d43bb31d722..1333beff214 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -3540,6 +3540,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "Слито", + "closed": "Закрыто", + "conflicts": "Конфликты", + "behind": "Отстаёт", + "blocked": "Заблокировано", + "checksPending": "Проверки ожидаются", + "ableToMerge": "Можно слить", + "unknown": "Неизвестно" + }, + "pagination": { + "pageUnreachable": "Страница {{page}} выходит за пределы результатов поиска GitHub.", + "loadPageFailed": "Не удалось загрузить страницу {{page}} из GitHub.", + "noMoreResults": "На странице {{page}} больше нет результатов." + }, "composerSource": { "baseFailed": "Не удалось определить базовую ветку.", "forkPushWarning": "В этом PR отключена настройка «Разрешить правки сопровождающим»; GitHub может отклонить отправку в форк." diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index a08a81a9ca4..8c58ec1fe2e 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -1461,11 +1461,11 @@ "updateRequired": "PDF'leri açmak için Orca Mobile'ı güncelleyin" }, "unsavedEditsOffer": { - "changedSince": "{{time}} tarihli düzenlemelerinizden sonra masaüstünde değişti", + "changedSince": "Düzenlemelerinizden ({{time}}) sonra masaüstünde değişti", "copyMyEdits": "Düzenlemelerimi kopyala", "discard": "Vazgeç", "restore": "Geri yükle", - "unsavedFrom": "{{time}} tarihli kaydedilmemiş düzenlemeler" + "unsavedFrom": "Kaydedilmemiş düzenlemeler ({{time}})" } }, "home": { @@ -3364,6 +3364,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "Birleştirildi", + "closed": "Kapatıldı", + "conflicts": "Çakışmalar", + "behind": "Geride", + "blocked": "Engellendi", + "checksPending": "Kontroller bekleniyor", + "ableToMerge": "Birleştirilebilir", + "unknown": "Bilinmiyor" + }, + "pagination": { + "pageUnreachable": "{{page}}. sayfa GitHub aramasının döndürebileceği aralığın dışında.", + "loadPageFailed": "{{page}}. sayfa GitHub’dan yüklenemedi.", + "noMoreResults": "{{page}}. sayfada başka sonuç yok." + }, "composerSource": { "baseFailed": "Temel branch çözümlenemedi.", "forkPushWarning": "Bu PR'da “Allow edits from maintainers” kapalı; fork'a push işlemi GitHub tarafından reddedilebilir." diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 5b00ba4341c..3e4a1c25efc 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -3360,6 +3360,21 @@ } }, "tasks": { + "hostedMerge": { + "merged": "已合併", + "closed": "已關閉", + "conflicts": "有衝突", + "behind": "落後", + "blocked": "已封鎖", + "checksPending": "等待檢查", + "ableToMerge": "可以合併", + "unknown": "未知" + }, + "pagination": { + "pageUnreachable": "第 {{page}} 頁超出 GitHub 搜尋可傳回的範圍。", + "loadPageFailed": "無法從 GitHub 載入第 {{page}} 頁。", + "noMoreResults": "第 {{page}} 頁沒有更多結果。" + }, "composerSource": { "baseFailed": "無法解析基礎分支。", "forkPushWarning": "此 PR 未啟用「允許維護者編輯」;推送至分叉存放庫可能會遭 GitHub 拒絕。" diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index cfda33b5abd..820e95b80a3 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -3440,6 +3440,16 @@ "githubViewControls": { "openView": "在 GitHub 中打开视图" }, + "hostedMerge": { + "merged": "已合并", + "closed": "已关闭", + "conflicts": "有冲突", + "behind": "落后", + "blocked": "已阻止", + "checksPending": "检查待完成", + "ableToMerge": "可以合并", + "unknown": "未知" + }, "itemActions": { "changeStatus": "更改状态", "copyGitHubLink": "复制 GitHub 链接", @@ -3586,6 +3596,11 @@ "updated": "已更新", "updatedSortDescription": "最新活动优先" }, + "pagination": { + "pageUnreachable": "第 {{page}} 页超出了 GitHub 搜索可返回的范围。", + "loadPageFailed": "无法从 GitHub 加载第 {{page}} 页。", + "noMoreResults": "第 {{page}} 页没有更多结果。" + }, "pickerProjection": { "allRepos": "所有仓库", "allSites": "所有站点", diff --git a/mobile/src/mobile-web-shell/ShellDownloadProgress.tsx b/mobile/src/mobile-web-shell/ShellDownloadProgress.tsx index 02b19f0caa6..46093799133 100644 --- a/mobile/src/mobile-web-shell/ShellDownloadProgress.tsx +++ b/mobile/src/mobile-web-shell/ShellDownloadProgress.tsx @@ -1,4 +1,4 @@ -import { useHostDisplay, type HostDisplaySource } from '../transport/hosts/use-host-display' +import { useHostDisplay, type HostDisplaySource } from '../host-descriptors/use-host-display' import type { DownloadProgressFeed } from './download-progress-feed' import { DownloadProgressBar, downloadedMegabytesCaption } from './DownloadProgressBar' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' diff --git a/mobile/src/mobile-web-shell/ShellStateScreen.tsx b/mobile/src/mobile-web-shell/ShellStateScreen.tsx index 01617b74903..d22e7e2c055 100644 --- a/mobile/src/mobile-web-shell/ShellStateScreen.tsx +++ b/mobile/src/mobile-web-shell/ShellStateScreen.tsx @@ -6,7 +6,7 @@ import { themedStyleSheet } from '../theme/themed-styles' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import type { Translate } from '../i18n/mobile-i18n' import { useMobileTranslation } from '../i18n/use-mobile-translation' -import type { HostDisplaySource } from '../transport/hosts/use-host-display' +import type { HostDisplaySource } from '../host-descriptors/use-host-display' import type { DownloadProgressFeed } from './download-progress-feed' import type { MobileWebShellFailureCause, diff --git a/mobile/src/mobile-web-shell/host-area-page-storage.test.tsx b/mobile/src/mobile-web-shell/host-area-page-storage.test.tsx index 1d12bae7036..fe9a34b9777 100644 --- a/mobile/src/mobile-web-shell/host-area-page-storage.test.tsx +++ b/mobile/src/mobile-web-shell/host-area-page-storage.test.tsx @@ -26,7 +26,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ ) } })) -vi.mock('../transport/hosts/host-store', () => ({ +vi.mock('../host-catalog/host-store', () => ({ loadHosts: async () => [{ id: 'host-a', name: 'Host', endpoint: 'ws://h', lastConnected: 1 }] })) diff --git a/mobile/src/mobile-web-shell/use-page-host-snapshot.test.tsx b/mobile/src/mobile-web-shell/use-page-host-snapshot.test.tsx index 98b98f51dfd..0d9b3956c08 100644 --- a/mobile/src/mobile-web-shell/use-page-host-snapshot.test.tsx +++ b/mobile/src/mobile-web-shell/use-page-host-snapshot.test.tsx @@ -46,7 +46,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ getItem: async (key: string) => doubles.store.get(key) ?? null } })) -vi.mock('../transport/hosts/host-store', () => ({ +vi.mock('../host-catalog/host-store', () => ({ loadHosts: async () => { if (doubles.hostsReject) { throw new Error('the keychain would not answer') diff --git a/mobile/src/mobile-web-shell/use-page-host-snapshot.ts b/mobile/src/mobile-web-shell/use-page-host-snapshot.ts index bfba2b5ac7f..55a30b6e8bb 100644 --- a/mobile/src/mobile-web-shell/use-page-host-snapshot.ts +++ b/mobile/src/mobile-web-shell/use-page-host-snapshot.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import { loadHosts } from '../transport/hosts/host-store' +import { loadHosts } from '../host-catalog/host-store' import type { BridgeInitHost } from './bridge/bridge-envelope' import { hydrateMirroredStorage, diff --git a/mobile/src/new-workspace/NewWorkspaceHostPicker.tsx b/mobile/src/new-workspace/NewWorkspaceHostPicker.tsx index 4fdc22c2acf..b9d5cb446bf 100644 --- a/mobile/src/new-workspace/NewWorkspaceHostPicker.tsx +++ b/mobile/src/new-workspace/NewWorkspaceHostPicker.tsx @@ -3,9 +3,9 @@ import { useRouter } from 'expo-router' import { PickerModal } from '../components/PickerModal' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { hostPickerOptions } from '../components/use-connected-host-picker' -import { selectConnectableHostProfiles } from '../transport/hosts/host-catalog-selection' -import { loadHostCatalog } from '../transport/hosts/host-store' -import type { HostProfile } from '../transport/hosts/host-profile' +import { selectConnectableHostProfiles } from '../host-catalog/host-catalog-selection' +import { loadHostCatalog } from '../host-catalog/host-store' +import type { HostProfile } from '../host-catalog/host-profile' // Keep picker and loading drawer in the overlay’s window so the load can start as selection leaves. export function NewWorkspaceHostPicker({ diff --git a/mobile/src/notifications/host-push-registration-state.ts b/mobile/src/notifications/host-push-registration-state.ts index bd7385d568b..30c739f318f 100644 --- a/mobile/src/notifications/host-push-registration-state.ts +++ b/mobile/src/notifications/host-push-registration-state.ts @@ -1,8 +1,8 @@ -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' export type HostPushState = { connection: { - client: RpcOperationSender | null + client: UnvalidatedRpcRequestPort | null support: ReturnType | null } // An unanswered probe is unknown, not unsupported. diff --git a/mobile/src/notifications/mobile-notifications.ts b/mobile/src/notifications/mobile-notifications.ts index a8bee3af321..1200887b82b 100644 --- a/mobile/src/notifications/mobile-notifications.ts +++ b/mobile/src/notifications/mobile-notifications.ts @@ -4,7 +4,7 @@ import type { DismissNotificationEvent } from './desktop-notification-events' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { waitForPushFallback } from './push-fallback' import { getHostPushSupported, getHostPushSupportCompletion } from './push-registration' -import { loadHostCatalog } from '../transport/hosts/host-store' +import { loadHostCatalog } from '../host-catalog/host-store' import { deriveHostFingerprint } from './push-host-fingerprint' import { presentForegroundPush } from './android-foreground-push' import { diff --git a/mobile/src/notifications/mobile-push-registration-operations.ts b/mobile/src/notifications/mobile-push-registration-operations.ts index c9ff7f995e9..6c7f76ae8dd 100644 --- a/mobile/src/notifications/mobile-push-registration-operations.ts +++ b/mobile/src/notifications/mobile-push-registration-operations.ts @@ -1,3 +1,9 @@ +import type { + MobilePushFilter, + MobilePushRegisterInput +} from '../../../src/shared/mobile-push-contract' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' +import type { MobilePushToken } from './push-token' import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' import { @@ -26,3 +32,36 @@ export const pushRouteUnregister = bindDeferredRpcOperation( read: rpcResultVariant('push-unregistered', notificationUnreadReplySchema) }) ) + +const REQUEST_TIMEOUT_MS = 5_000 + +export async function sendRegister( + client: UnvalidatedRpcRequestPort, + token: MobilePushToken, + filter: MobilePushFilter +): Promise { + const params: Omit = { + platform: token.platform, + token: token.token, + ...(token.apnsEnvironment ? { apnsEnvironment: token.apnsEnvironment } : {}), + filter + } + const reply = await pushRouteRegister + .request(client, params, { timeoutMs: REQUEST_TIMEOUT_MS, failWhenDisconnected: true }) + .catch(() => null) + const registration = reply && pushRouteRegister.interpret(reply) + if (!registration?.accepted) { + return false + } + return registration.value?.registered === true +} + +export async function sendUnregister( + client: UnvalidatedRpcRequestPort, + timeoutMs: number +): Promise { + const reply = await pushRouteUnregister + .request(client, null, { timeoutMs, failWhenDisconnected: true }) + .catch(() => null) + return reply !== null && pushRouteUnregister.interpret(reply).accepted +} diff --git a/mobile/src/notifications/notification-reply-schema.test.ts b/mobile/src/notifications/notification-reply-schema.test.ts deleted file mode 100644 index 78f4f1e6fc2..00000000000 --- a/mobile/src/notifications/notification-reply-schema.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { z } from 'zod' -import { - missedNotificationsSchema, - notificationUnreadReplySchema, - PUSH_REGISTER_REFUSAL_REASONS, - PUSH_TEST_REFUSAL_REASONS, - pushDeliveryTestResultSchema, - pushRouteRegistrationSchema -} from './notification-reply-schema' - -function reads(schema: z.ZodType, value: unknown): T { - const parsed = schema.safeParse(value) - if (!parsed.success) { - throw new Error(`expected a readable reply: ${parsed.error.message}`) - } - return parsed.data -} - -function refuses(schema: z.ZodType, value: unknown): boolean { - return !schema.safeParse(value).success -} - -describe('notification replies tolerate the shapes their call sites guard', () => { - it('reads a test-push reply the screen reaches through optional chaining', () => { - expect(reads(pushDeliveryTestResultSchema, { accepted: true })?.accepted).toBe(true) - expect(reads(pushDeliveryTestResultSchema, null)).toBe(null) - expect(reads(pushDeliveryTestResultSchema, undefined)).toBe(undefined) - expect(reads(pushDeliveryTestResultSchema, { error: 'refused' })?.accepted).toBe(undefined) - }) - - // Schema refusal would replace the screen’s generic send-failure copy with a parser error. - it('reads a non-object test-push result as absent, which takes the generic copy', () => { - for (const value of ['garbage', 7, true, []]) { - expect(refuses(pushDeliveryTestResultSchema, value)).toBe(false) - const result = reads(pushDeliveryTestResultSchema, value) - expect(result?.accepted).toBe(undefined) - expect(result?.reason).toBe(undefined) - } - }) - - it('reads a registration reply the reconciler reaches through optional chaining', () => { - expect(reads(pushRouteRegistrationSchema, { registered: true })?.registered).toBe(true) - expect(reads(pushRouteRegistrationSchema, null)).toBe(null) - expect(reads(pushRouteRegistrationSchema, { registered: 'yes' })?.registered).toBe(undefined) - }) - - it('takes every reply at the two sites whose body nothing reads', () => { - expect(refuses(notificationUnreadReplySchema, undefined)).toBe(false) - expect(refuses(notificationUnreadReplySchema, null)).toBe(false) - expect(refuses(notificationUnreadReplySchema, 'anything')).toBe(false) - }) -}) - -describe('closed enums degrade to the copy main showed', () => { - it('keeps a reason the screen branches on and drops one it does not know', () => { - expect( - reads(pushDeliveryTestResultSchema, { accepted: false, reason: 'rate_limited' })?.reason - ).toBe('rate_limited') - expect( - reads(pushDeliveryTestResultSchema, { accepted: false, reason: 'not_registered' })?.reason - ).toBe('not_registered') - expect(reads(pushDeliveryTestResultSchema, { accepted: false, reason: 'quota' })?.reason).toBe( - undefined - ) - }) - - it('keeps a registration reason and drops an unknown one', () => { - const reply = { registered: false, reason: 'throttled' } - expect(reads(pushRouteRegistrationSchema, reply)?.reason).toBe('throttled') - expect( - reads(pushRouteRegistrationSchema, { registered: false, reason: 'moon-phase' })?.reason - ).toBe(undefined) - }) - - // Host-pinned unions cover every arm; these loops prove each survives parsing. - it('keeps every refusal reason the host declares for either route', () => { - for (const reason of PUSH_TEST_REFUSAL_REASONS) { - expect(reads(pushDeliveryTestResultSchema, { accepted: false, reason })?.reason).toBe(reason) - } - for (const reason of PUSH_REGISTER_REFUSAL_REASONS) { - expect(reads(pushRouteRegistrationSchema, { registered: false, reason })?.reason).toBe(reason) - } - }) -}) - -describe('dismissal rows stay opaque', () => { - it('keeps every row for readPushNotificationIdentity to judge', () => { - const rows = [{ notificationId: 'n-1' }, 'not-a-row', 7] - expect(reads(missedNotificationsSchema, { dismissedPushes: rows })?.dismissedPushes).toEqual( - rows - ) - }) - - it('drops a dismissedPushes that is not an array, as Array.isArray did', () => { - expect(reads(missedNotificationsSchema, { dismissedPushes: 'all' })?.dismissedPushes).toBe( - undefined - ) - expect(reads(missedNotificationsSchema, null)).toBe(null) - }) -}) diff --git a/mobile/src/notifications/notification-routing.ts b/mobile/src/notifications/notification-routing.ts index 51a81548b0a..a083798e327 100644 --- a/mobile/src/notifications/notification-routing.ts +++ b/mobile/src/notifications/notification-routing.ts @@ -1,7 +1,7 @@ import { parseExecutionHostId } from '../../../src/shared/execution-host' import type { HostStackRouteTarget } from '../navigation/host-stack-navigation' import { mobileSessionRouteTarget } from '../session/mobile-session-route' -import type { HostCredentialStatus } from '../transport/hosts/host-profile' +import type { HostCredentialStatus } from '../host-catalog/host-profile' export type NotificationNavigationOptions = { knownHostIds?: ReadonlySet diff --git a/mobile/src/notifications/push-dismissal-reconciliation.ts b/mobile/src/notifications/push-dismissal-reconciliation.ts index 6f5c0a5457a..5a77d259d17 100644 --- a/mobile/src/notifications/push-dismissal-reconciliation.ts +++ b/mobile/src/notifications/push-dismissal-reconciliation.ts @@ -1,6 +1,6 @@ import * as Notifications from 'expo-notifications' import { pushMissedSinceRead, type MobilePushDismissalRpcSender } from './push-dismissal-operations' -import { loadHostCatalog } from '../transport/hosts/host-store' +import { loadHostCatalog } from '../host-catalog/host-store' import { resolveHostIdForFingerprint } from './push-host-fingerprint' import { readNativeNotificationData } from './native-notification-data' import { readOrcaPushPayload, type OrcaPushPayload } from './push-payload' diff --git a/mobile/src/notifications/push-receive.test.ts b/mobile/src/notifications/push-receive.test.ts index 9c1b8832c9c..e7d93268bb5 100644 --- a/mobile/src/notifications/push-receive.test.ts +++ b/mobile/src/notifications/push-receive.test.ts @@ -4,8 +4,8 @@ import { setNotificationViewingWorkspace } from './notification-viewing-policy' vi.mock('./push-tray-dismissal', () => ({ dismissPresentedPushNotification: vi.fn() })) import { beforeEach, describe, expect, it, vi } from 'vitest' import { sha256 } from '@noble/hashes/sha256' -import { loadHostCatalog } from '../transport/hosts/host-store' -import type { HostCatalogEntry } from '../transport/hosts/host-profile' +import { loadHostCatalog } from '../host-catalog/host-store' +import type { HostCatalogEntry } from '../host-catalog/host-profile' import { foregroundNotificationBehavior, @@ -19,7 +19,7 @@ async function shouldSuppressForegroundPush(data: unknown): Promise { } vi.mock('react-native', () => ({ AppState: { currentState: 'background' } })) -vi.mock('../transport/hosts/host-store', () => ({ loadHostCatalog: vi.fn() })) +vi.mock('../host-catalog/host-store', () => ({ loadHostCatalog: vi.fn() })) const storage = vi.hoisted(() => new Map()) vi.mock('@react-native-async-storage/async-storage', () => ({ default: { diff --git a/mobile/src/notifications/push-receive.ts b/mobile/src/notifications/push-receive.ts index 44a64e05e09..15d07022d14 100644 --- a/mobile/src/notifications/push-receive.ts +++ b/mobile/src/notifications/push-receive.ts @@ -2,7 +2,7 @@ import { wasPushDismissed } from './push-dismissal-watermarks' import { dismissPresentedPushNotification } from './push-tray-dismissal' import { shouldSuppressNotificationWhileViewing } from './notification-viewing-policy' import { loadPushNotificationsEnabled } from '../storage/preferences' -import { loadHostCatalog } from '../transport/hosts/host-store' +import { loadHostCatalog } from '../host-catalog/host-store' import { resolveHostIdForFingerprint } from './push-host-fingerprint' import { readOrcaPushPayload, type OrcaPushPayload } from './push-payload' import type { NotificationBehavior } from 'expo-notifications' diff --git a/mobile/src/notifications/push-registration.ts b/mobile/src/notifications/push-registration.ts index 5c8267a49d4..853f0329894 100644 --- a/mobile/src/notifications/push-registration.ts +++ b/mobile/src/notifications/push-registration.ts @@ -13,14 +13,10 @@ import { saveNotificationDeliveryPreferences, type NotificationDeliveryPreferences } from './notification-delivery-preferences' -import type { - MobilePushFilter, - MobilePushRegisterInput -} from '../../../src/shared/mobile-push-contract' import { NOTIFICATIONS_REMOTE_PUSH_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' -import type { RpcOperationSender as PushClient } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { startRuntimeCapabilityProbe } from '../transport/connection/runtime-capability-probe' -import { pushRouteRegister, pushRouteUnregister } from './mobile-push-registration-operations' +import { sendRegister, sendUnregister } from './mobile-push-registration-operations' import { loadPushNotificationsEnabled, loadRemotePushHostRegistrations, @@ -44,7 +40,7 @@ export function getHostPushSupported(hostId: string): boolean | null { } export function getHostPushSupportCompletion( hostId: string, - client: PushClient + client: UnvalidatedRpcRequestPort ): HostPushSupportCompletion | null { const connection = hostsById.get(hostId)?.connection return connection?.client === client ? connection.support : null @@ -98,34 +94,6 @@ async function currentToken(): Promise { return tokenPromise } -async function sendRegister( - client: PushClient, - token: MobilePushToken, - filter: MobilePushFilter -): Promise { - const params: Omit = { - platform: token.platform, - token: token.token, - ...(token.apnsEnvironment ? { apnsEnvironment: token.apnsEnvironment } : {}), - filter - } - const reply = await pushRouteRegister - .request(client, params, { timeoutMs: REQUEST_TIMEOUT_MS, failWhenDisconnected: true }) - .catch(() => null) - const registration = reply && pushRouteRegister.interpret(reply) - if (!registration?.accepted) { - return false - } - return registration.value?.registered === true -} - -async function sendUnregister(client: PushClient, timeoutMs: number): Promise { - const reply = await pushRouteUnregister - .request(client, null, { timeoutMs, failWhenDisconnected: true }) - .catch(() => null) - return reply !== null && pushRouteUnregister.interpret(reply).accepted -} - async function reconcileHost(hostId: string): Promise { const state = hostsById.get(hostId) const client = state?.connection.client @@ -222,7 +190,10 @@ async function reconcileAllHosts(): Promise { } // Keep tracked host intent across disconnects; this disposer detaches only its current connected client. -export function attachPushRegistration(hostId: string, client: PushClient): () => void { +export function attachPushRegistration( + hostId: string, + client: UnvalidatedRpcRequestPort +): () => void { const state = hostState(hostId) if (state.connection.client !== client) { state.capabilityProbeStop?.() diff --git a/mobile/src/notifications/push-socket-dismissal.ts b/mobile/src/notifications/push-socket-dismissal.ts index 16a3b560db2..84f548684b8 100644 --- a/mobile/src/notifications/push-socket-dismissal.ts +++ b/mobile/src/notifications/push-socket-dismissal.ts @@ -1,4 +1,4 @@ -import { loadHostCatalog } from '../transport/hosts/host-store' +import { loadHostCatalog } from '../host-catalog/host-store' import { deriveHostFingerprint } from './push-host-fingerprint' import { dismissPresentedPushNotification } from './push-tray-dismissal' import type { DismissNotificationEvent } from './desktop-notification-events' diff --git a/mobile/src/notifications/use-remote-push-capable-hosts.ts b/mobile/src/notifications/use-remote-push-capable-hosts.ts index db86e9d08b2..f7ff991cff1 100644 --- a/mobile/src/notifications/use-remote-push-capable-hosts.ts +++ b/mobile/src/notifications/use-remote-push-capable-hosts.ts @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react' -import { loadHostCatalog } from '../transport/hosts/host-store' +import { loadHostCatalog } from '../host-catalog/host-store' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { startRuntimeCapabilityProbe } from '../transport/connection/runtime-capability-probe' import { useAllHostClients } from '../transport/connection/use-all-host-clients' diff --git a/mobile/src/pairing/mobile-relay-pairing-journal-store.ts b/mobile/src/pairing/mobile-relay-pairing-journal-store.ts index bc885969b67..cbd96e1289c 100644 --- a/mobile/src/pairing/mobile-relay-pairing-journal-store.ts +++ b/mobile/src/pairing/mobile-relay-pairing-journal-store.ts @@ -11,7 +11,7 @@ import { readPairingKeychainItem, resetPairingKeychainForTests, writePairingKeychainItem -} from '../transport/hosts/pairing-keychain' +} from '../host-credentials/pairing-keychain' const JOURNAL_STORAGE_KEY = 'orca:mobile-relay:pairing-journal:v1' const JOURNAL_SECRET_KEY = 'orca.mobile-relay.pairing-journal.v1' diff --git a/mobile/src/pairing/mobile-relay-pairing-recovery.test.ts b/mobile/src/pairing/mobile-relay-pairing-recovery.test.ts index 648a53fd90b..7ad28633fff 100644 --- a/mobile/src/pairing/mobile-relay-pairing-recovery.test.ts +++ b/mobile/src/pairing/mobile-relay-pairing-recovery.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { MobileRelayCredentialBundle } from '../transport/hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../host-credentials/mobile-relay-credential-bundle' import { createMobileRelayPairingJournal } from './mobile-relay-pairing-journal' import { recoverMobileRelayPairing, @@ -10,7 +10,7 @@ import type { connectMobileRelayForPairing, PairingCandidateClient } from './mobile-relay-physical-client' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { RpcResponse } from '../transport/rpc/rpc-wire-types' import type { PairingOffer } from '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' diff --git a/mobile/src/pairing/mobile-relay-pairing-recovery.ts b/mobile/src/pairing/mobile-relay-pairing-recovery.ts index 03fc772c3c0..e375bab0604 100644 --- a/mobile/src/pairing/mobile-relay-pairing-recovery.ts +++ b/mobile/src/pairing/mobile-relay-pairing-recovery.ts @@ -4,13 +4,13 @@ import type { PairingGetEndpointsResult } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import type { PairingRelay } from '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { loadHosts, savePairedHost } from '../transport/hosts/host-store' +import { loadHosts, savePairedHost } from '../host-catalog/host-store' import { promotePairingJournalCredential, readMobileRelayCredentialBundle, writeMobileRelayCredentialBundle, type MobileRelayCredentialBundle -} from '../transport/hosts/mobile-relay-credential-bundle' +} from '../host-credentials/mobile-relay-credential-bundle' import { resolvePairingInviteThroughDirector } from './mobile-relay-invite-director' import type { MobileRelayPairingJournal } from './mobile-relay-pairing-journal' import { diff --git a/mobile/src/pairing/pairing-relay-host.ts b/mobile/src/pairing/pairing-relay-host.ts index ff50da77e7f..a6cd7017273 100644 --- a/mobile/src/pairing/pairing-relay-host.ts +++ b/mobile/src/pairing/pairing-relay-host.ts @@ -3,7 +3,7 @@ import type { MobileRelayEndpoint } from '../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import type { MobileRelayPairingJournal } from './mobile-relay-pairing-journal' -import type { HostProfile } from '../transport/hosts/host-profile' +import type { HostProfile } from '../host-catalog/host-profile' import type { PairingOffer } from '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' export function directHost( diff --git a/mobile/src/pairing/pairing.ts b/mobile/src/pairing/pairing.ts index d4641651478..4f3379efe29 100644 --- a/mobile/src/pairing/pairing.ts +++ b/mobile/src/pairing/pairing.ts @@ -1,4 +1,4 @@ -import '../transport/hosts/host-profile' +import '../host-catalog/host-profile' import { PairingOfferSchema, type PairingOffer diff --git a/mobile/src/pairing/pre-profile-pairing-coordinator.ts b/mobile/src/pairing/pre-profile-pairing-coordinator.ts index f7f8f426ad7..e88d92b7e04 100644 --- a/mobile/src/pairing/pre-profile-pairing-coordinator.ts +++ b/mobile/src/pairing/pre-profile-pairing-coordinator.ts @@ -1,6 +1,6 @@ import { Platform } from 'react-native' import { connect, type ConnectOptions } from '../transport/rpc/direct-rpc-connect' -import { resolvePairingHostIdentity, savePairedHost } from '../transport/hosts/host-store' +import { resolvePairingHostIdentity, savePairedHost } from '../host-catalog/host-store' import type { PairingOffer } from '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' import { isPairingRelayRpcUnavailable } from './pairing-relay-rpc-unavailable' import { @@ -21,7 +21,7 @@ import { settleMobileRelayPairingRecovery } from './mobile-relay-pairing-recover import { promotePairingJournalCredential, writeMobileRelayCredentialBundle -} from '../transport/hosts/mobile-relay-credential-bundle' +} from '../host-credentials/mobile-relay-credential-bundle' import { connectMobileRelayForPairing, type PairingCandidateClient @@ -33,7 +33,7 @@ import { createRecoveringPairingRelayCandidate } from './pairing-relay-candidate import { createPairingRelayLogger } from '../diagnostics/connection/pairing-relay-log' import { redactSocketEndpoint } from '../diagnostics/connection/socket-event-debug' import { assertCommittedInstall, directHost, relayHost } from './pairing-relay-host' -import { recordHostDescriptorFromStatus } from '../transport/hosts/host-descriptor-recorder' +import { recordHostDescriptorFromStatus } from '../host-descriptors/host-descriptor-recorder' import { adoptExchangedToken, exchangePairingTicket } from './pairing-ticket-exchange' import type { HostStatusReply } from '../transport/hosts/host-status-reply-schema' diff --git a/mobile/src/pairing/unpaired-host-credential-deletion.ts b/mobile/src/pairing/unpaired-host-credential-deletion.ts index a7e056764bd..1df85f8f740 100644 --- a/mobile/src/pairing/unpaired-host-credential-deletion.ts +++ b/mobile/src/pairing/unpaired-host-credential-deletion.ts @@ -1,9 +1,9 @@ -import { deleteHostDeviceToken } from '../transport/hosts/host-device-token-store' +import { deleteHostDeviceToken } from '../host-credentials/host-device-token-store' import { clearHostCredentialWriteRevision, getHostCredentialWriteRevision -} from '../transport/hosts/host-credential-write-revision' -import { deleteMobileRelayCredentialBundle } from '../transport/hosts/mobile-relay-credential-bundle' +} from '../host-credentials/host-credential-write-revision' +import { deleteMobileRelayCredentialBundle } from '../host-credentials/mobile-relay-credential-bundle' import { deleteMobileRelayDirectUpgradeJournal } from '../transport/relay/mobile-relay-direct-upgrade-journal' type DeletionDependencies = { diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 06861569071..0400353b3ca 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -25,8 +25,8 @@ import { useMobileSessionContentKeyboardLift } from '../terminal/session/use-mob import { useOpenUrlInOrca } from '../browser/use-open-url-in-orca' import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' import { useOpenHostAccounts } from '../accounts/use-open-mobile-accounts' -import { useHostProfile } from '../transport/hosts/use-host-profile' -import { useHostDisplay } from '../transport/hosts/use-host-display' +import { useHostProfile } from '../host-catalog/use-host-profile' +import { useHostDisplay } from '../host-descriptors/use-host-display' import { FileReader } from '../files/session-documents/MobileSessionFileReader' import { MobileSessionContentState } from './MobileSessionContentState' import { MarkdownReader } from '../files/session-documents/MobileSessionMarkdownReader' diff --git a/mobile/src/session/agent-launch/mobile-agent-detection-operations.ts b/mobile/src/session/agent-launch/mobile-agent-detection-operations.ts index 443525aca2d..3587dbbb98e 100644 --- a/mobile/src/session/agent-launch/mobile-agent-detection-operations.ts +++ b/mobile/src/session/agent-launch/mobile-agent-detection-operations.ts @@ -1,14 +1,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' -import '../../terminal/terminal-reply-schema' import { detectedAgentsSchema, refreshedAgentsSchema } from './mobile-agent-detection-reply-schema' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../../terminal/session/mobile-session-terminal-reply-schema' -import '../../worktree/session-worktree-record-reply-schema' -import '../native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../../files/workspace-file-paths-reply-schema' // Launch detection surfaces host refusals; advisory task-drawer readers intentionally skip them. export const preflightDetectAgentsRead = bindDeferredRpcOperation( diff --git a/mobile/src/session/agent-launch/mobile-new-tab-settings-operations.ts b/mobile/src/session/agent-launch/mobile-new-tab-settings-operations.ts index 1a0627c3289..f7a8ecd5f50 100644 --- a/mobile/src/session/agent-launch/mobile-new-tab-settings-operations.ts +++ b/mobile/src/session/agent-launch/mobile-new-tab-settings-operations.ts @@ -1,6 +1,5 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' import type { RpcCompatibleReader } from '../../transport/rpc/rpc-operation-contract' -import '../../../../src/shared/source-control/listing/source-control-group-order' import { settingsMember } from '../../settings/mobile-settings-projection' // New-tab checks the sibling's refusal before touching settings, but after its own refusal. diff --git a/mobile/src/session/agent-launch/mobile-runtime-repo-operations.ts b/mobile/src/session/agent-launch/mobile-runtime-repo-operations.ts index cb885ee3fc6..0980441d230 100644 --- a/mobile/src/session/agent-launch/mobile-runtime-repo-operations.ts +++ b/mobile/src/session/agent-launch/mobile-runtime-repo-operations.ts @@ -1,14 +1,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' -import '../../terminal/terminal-reply-schema' import { runtimeRepoListSchema } from './mobile-agent-detection-reply-schema' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../../terminal/session/mobile-session-terminal-reply-schema' -import '../../worktree/session-worktree-record-reply-schema' -import '../native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../../files/workspace-file-paths-reply-schema' export type MobileRuntimeRepoSummary = { id: string diff --git a/mobile/src/session/floating-workspace.test.ts b/mobile/src/session/floating-workspace.test.ts deleted file mode 100644 index 8f29646b49b..00000000000 --- a/mobile/src/session/floating-workspace.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - FLOATING_WORKSPACE_WORKTREE_ID, - floatingWorkspaceSessionPath, - isFloatingWorkspaceWorktreeId -} from './floating-workspace' - -describe('floating workspace routing', () => { - it('matches only the desktop sentinel id', () => { - expect(isFloatingWorkspaceWorktreeId('global-floating-terminal')).toBe(true) - expect(isFloatingWorkspaceWorktreeId('repo-1::/worktree')).toBe(false) - expect(isFloatingWorkspaceWorktreeId('folder:group-1')).toBe(false) - expect(isFloatingWorkspaceWorktreeId(undefined)).toBe(false) - expect(isFloatingWorkspaceWorktreeId(null)).toBe(false) - }) - - it('builds the session route with an explicit title seed', () => { - expect(floatingWorkspaceSessionPath('host-1')).toBe( - `/h/host-1/session/${FLOATING_WORKSPACE_WORKTREE_ID}?name=Floating%20Workspace` - ) - }) -}) diff --git a/mobile/src/session/mobile-dictation-session-outcomes.test.tsx b/mobile/src/session/mobile-dictation-session-outcomes.test.tsx index 98ea1ae6c0b..46d24d9a1d9 100644 --- a/mobile/src/session/mobile-dictation-session-outcomes.test.tsx +++ b/mobile/src/session/mobile-dictation-session-outcomes.test.tsx @@ -14,8 +14,6 @@ const seen = vi.hoisted(() => { return { toasts: new Array(), errorHaptics: 0, - setupSheetOpens: 0, - micPermissionRequests: 0, clipboard: new Array(), inputs: new Array(), chat, @@ -30,7 +28,7 @@ vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) // The computer's name only words announcements; the stored host profile pulls in secure storage. -vi.mock('../transport/hosts/use-host-profile', () => ({ useHostProfile: () => null })) +vi.mock('../host-catalog/use-host-profile', () => ({ useHostProfile: () => null })) vi.mock('@orca/expo-two-way-audio', () => ({ addExpoTwoWayAudioEventListener: (name: string, listener: (event: { data: string }) => void) => { seen.audioListeners.set(name, listener) @@ -38,7 +36,6 @@ vi.mock('@orca/expo-two-way-audio', () => ({ }, initialize: () => Promise.resolve(true), requestMicrophonePermissionsAsync: () => { - seen.micPermissionRequests += 1 return Promise.resolve({ granted: true }) }, tearDown: () => {}, @@ -159,11 +156,7 @@ function mount( activeSessionTab: { id: 'tab1', type: 'terminal', terminal: 't1', title: 'Claude Code' }, diffComments: [], diffCommentsRef: useRef([]), - setShowDictationSetup: (next: boolean) => { - if (next) { - seen.setupSheetOpens += 1 - } - }, + setShowDictationSetup: () => {}, setDictationMode: () => {}, dictationEnabled: true, setDictationEnabled: () => {}, @@ -259,8 +252,6 @@ async function startRecording( beforeEach(() => { seen.toasts.length = 0 seen.errorHaptics = 0 - seen.setupSheetOpens = 0 - seen.micPermissionRequests = 0 seen.clipboard.length = 0 seen.inputs.length = 0 seen.chat = { shown: false, scope: null } @@ -268,35 +259,6 @@ beforeEach(() => { seen.audioListeners.clear() }) -describe('a mic tap after the host reported dictation is not set up', () => { - it('opens setup without asking for the microphone, then lets the host judge the tap after the sheet closes', async () => { - const rpc = createFakeRpcClient() - const mounted = mount(rpc) - await act(async () => { - const read = mounted.current().refreshDictationMode() - for (const request of rpc.requests.splice(0)) { - request.resolve({ - id: 'desktop', - ok: true, - result: { enabled: false, selectedModelId: '', dictationMode: 'toggle', models: [] } - }) - } - await read - }) - act(() => mounted.current().handleDictationToggle()) - expect(seen.setupSheetOpens).toBe(1) - expect(seen.micPermissionRequests).toBe(0) - expect(rpc.requests).toEqual([]) - - // Closing the sheet hands the next tap to the host until a fresh read lands. - act(() => mounted.current().closeDictationSetup()) - act(() => mounted.current().handleDictationToggle()) - await settle(rpc, '') - expect(seen.setupSheetOpens).toBe(1) - expect(seen.micPermissionRequests).toBe(1) - }) -}) - describe('a mic tap while the transcript is processing', () => { it('keeps the transcript that comes back', async () => { const rpc = createFakeRpcClient() diff --git a/mobile/src/session/mobile-session-appearance-startup.test.tsx b/mobile/src/session/mobile-session-appearance-startup.test.tsx deleted file mode 100644 index afa67b42404..00000000000 --- a/mobile/src/session/mobile-session-appearance-startup.test.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { MobileSessionRouteScreen } from './MobileSessionRouteScreen' - -// Mocked react-native components are string tags that ReactTestInstance's ElementType omits. -function hostType(node: ReactTestInstance): unknown { - return node.type -} - -const state = vi.hoisted(() => ({ - terminalPreferencesReady: false, - accessoryPreferencesReady: false, - nativeChatController: { sessionViewReady: false } -})) -const mounts = vi.hoisted(() => ({ count: 0 })) -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - Text: 'Text', - View: 'View' -})) -vi.mock('./mobile-session-styles', () => ({ styles: {} })) -vi.mock('./use-mobile-session-controller', () => ({ useMobileSessionController: () => state })) -vi.mock('./MobileSessionSurface', async () => { - const react = await import('react') - return { - MobileSessionSurface: () => { - react.useEffect(() => { - mounts.count += 1 - }, []) - return react.createElement('ReadySession') - } - } -}) - -let renderer: ReactTestRenderer | null = null -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null -}) - -describe('first visible session appearance', () => { - it.each(['terminal', 'accessory', 'chat'] as const)( - 'waits for the saved %s setting before mounting the session', - (waiting) => { - state.terminalPreferencesReady = waiting !== 'terminal' - state.accessoryPreferencesReady = waiting !== 'accessory' - state.nativeChatController.sessionViewReady = waiting !== 'chat' - mounts.count = 0 - const render = () => - act(() => { - if (renderer) { - renderer.update(createElement(MobileSessionRouteScreen)) - } else { - renderer = create(createElement(MobileSessionRouteScreen)) - } - }) - const expectPreparing = () => { - expect(renderer?.root.findAll((node) => hostType(node) === 'ReadySession')).toHaveLength(0) - expect( - renderer?.root.findAll((node) => hostType(node) === 'ActivityIndicator') - ).toHaveLength(1) - expect(mounts.count).toBe(0) - } - render() - expectPreparing() - state.terminalPreferencesReady = true - state.accessoryPreferencesReady = true - state.nativeChatController.sessionViewReady = true - render() - expect(renderer?.root.findAll((node) => hostType(node) === 'ReadySession')).toHaveLength(1) - expect(mounts.count).toBe(1) - render() - expect(mounts.count).toBe(1) - } - ) -}) diff --git a/mobile/src/session/mobile-session-status-result.ts b/mobile/src/session/mobile-session-status-result.ts deleted file mode 100644 index 722e62ab480..00000000000 --- a/mobile/src/session/mobile-session-status-result.ts +++ /dev/null @@ -1,3 +0,0 @@ -export type RuntimeStatusResult = { - capabilities?: string[] -} diff --git a/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts deleted file mode 100644 index b8dcf5eda98..00000000000 --- a/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts +++ /dev/null @@ -1,213 +0,0 @@ -import './MobileNativeChatView.harness.test-fixture' -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { MobileNativeChatView } from './MobileNativeChatView' - -const scrollToEnd = vi.hoisted(() => vi.fn()) -const scrollToOffset = vi.hoisted(() => vi.fn()) - -vi.mock('react-native', async () => { - const React = await import('react') - return { - ...(await import('../../test-support/react-native-motion-stub')).reactNativeMotionStub(), - ActivityIndicator: 'ActivityIndicator', - FlatList: React.forwardRef< - unknown, - { - data: NativeChatMessage[] - renderItem: (row: { item: NativeChatMessage; index: number }) => ReactNode - ListFooterComponent: ReactNode - } - >((props, ref) => { - React.useImperativeHandle(ref, () => ({ scrollToEnd, scrollToOffset }), []) - return React.createElement( - 'FlatList', - props, - props.data.map((item, index) => - React.createElement(React.Fragment, { key: item.id }, props.renderItem({ item, index })) - ), - props.ListFooterComponent - ) - }), - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' - } -}) - -vi.mock('react-native-safe-area-context', () => ({ - useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) -})) - -vi.mock('react-native-gesture-handler', () => { - const chain = { - runOnJS: () => chain, - onStart: () => chain, - onUpdate: () => chain - } - return { - Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain }, - GestureDetector: 'GestureDetector', - GestureHandlerRootView: 'GestureHandlerRootView' - } -}) - -vi.mock('lucide-react-native', () => ({ - ArrowDown: 'ArrowDown', - ChevronsDownUp: 'ChevronsDownUp', - ChevronsUpDown: 'ChevronsUpDown', - Square: 'Square' -})) - -vi.mock('./transcript/MobileNativeChatMessage', () => ({ - MobileNativeChatMessage: 'ChatMessage' -})) -vi.mock('./transcript/MobileNativeChatLiveLine', () => ({ - MobileNativeChatLiveLine: 'LiveStatus' -})) -vi.mock('./input/MobileNativeChatAsk', () => ({ MobileNativeChatAsk: 'ChatAsk' })) -vi.mock('./input/MobileNativeChatPermission', () => ({ - MobileNativeChatPermission: 'ChatPermission' -})) -vi.mock('./input/MobileNativeChatQuestion', () => ({ - MobileNativeChatQuestion: 'ChatQuestion' -})) -vi.mock('../../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' })) - -vi.mock('./composer/MobileNativeChatComposer', async () => { - const { composerStub } = await import('./MobileNativeChatView.render-stubs.test-fixture') - return composerStub() -}) - -type Overrides = { - messages?: Parameters[0]['messages'] - folded?: Parameters[0]['folded'] - streaming?: string | null - sendErrorMessage?: string | null - onClearSendError?: () => void - inputLockReason?: 'disconnected' | 'waiting' | null - onSend?: (text: string) => Promise - pending?: Parameters[0]['pending'] - structuredActivityUi?: boolean - turnIndicator?: Parameters[0]['turnIndicator'] - agentWorking?: boolean - canStop?: boolean - ask?: Parameters[0]['ask'] - question?: Parameters[0]['question'] - permission?: Parameters[0]['permission'] - sendSurfaceId?: string - keyboardInset?: number - hasMore?: boolean - onLoadEarlier?: () => void -} - -function chatViewElement(overrides: Overrides): ReturnType { - return createElement(MobileNativeChatView, { - messages: [], - folded: [], - status: 'ready', - streaming: null, - onSend: vi.fn().mockResolvedValue(true), - sendSurfaceId: 'tab-a', - getSendCompletionGeneration: () => 0, - getComposerEditGeneration: () => 0, - pending: [], - draftKey: null, - onComposerTextChange: vi.fn(), - ...overrides - }) -} - -describe('MobileNativeChatView', () => { - let renderer: ReactTestRenderer | null = null - - beforeEach(() => { - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => - setTimeout(() => callback(0), 0) - ) - vi.stubGlobal('cancelAnimationFrame', (handle: ReturnType) => - clearTimeout(handle) - ) - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - scrollToEnd.mockReset() - scrollToOffset.mockReset() - vi.unstubAllGlobals() - }) - - async function render(overrides: Overrides = {}): Promise { - await act(async () => { - renderer = create(chatViewElement(overrides)) - }) - } - - async function update(overrides: Overrides = {}): Promise { - await act(async () => { - renderer?.update(chatViewElement(overrides)) - }) - } - - function renderedRow(id: string): ReturnType { - return createElement( - 'Row', - renderer!.root.find( - (node) => String(node.type) === 'ChatMessage' && node.props.message.id === id - ).props - ) - } - - describe('structured turn status wiring', () => { - const userTurn = (id: string, text: string): NativeChatMessage => ({ - id, - role: 'user', - blocks: [{ type: 'text', text }], - timestamp: 0, - source: 'transcript' - }) - - function rowProps(id: string): Record { - return (renderedRow(id) as { props: Record }).props - } - - it('does not carry a running turn clock across chat surfaces', async () => { - vi.useFakeTimers() - try { - vi.setSystemTime(1_000) - const firstTab = [userTurn('u1', 'first')] - await render({ - messages: firstTab, - folded: firstTab, - structuredActivityUi: true, - agentWorking: true, - sendSurfaceId: 'host\0worktree\0tab-a' - }) - expect(rowProps('u1').turnStatus).toMatchObject({ startedAt: 1_000 }) - - vi.setSystemTime(12_000) - const secondTab = [userTurn('u2', 'second')] - await update({ - messages: secondTab, - folded: secondTab, - structuredActivityUi: true, - agentWorking: true, - sendSurfaceId: 'host\0worktree\0tab-b' - }) - - expect(rowProps('u2').turnStatus).toMatchObject({ startedAt: 12_000 }) - } finally { - vi.useRealTimers() - } - }) - }) -}) - -vi.mock('./input/MobileQueuedMessageComposer', () => ({ - MobileQueuedMessageComposer: 'QueuedMessageComposer' -})) diff --git a/mobile/src/session/native-chat/agent-session/mobile-native-chat-page-read-operations.ts b/mobile/src/session/native-chat/agent-session/mobile-native-chat-page-read-operations.ts index b91d5156f2d..f7a712d7aba 100644 --- a/mobile/src/session/native-chat/agent-session/mobile-native-chat-page-read-operations.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-native-chat-page-read-operations.ts @@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader' import '../../../terminal/terminal-reply-schema' import { sessionForwardedReplySchema } from '../../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../../agent-launch/mobile-agent-detection-reply-schema' -import '../../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../../terminal/session/mobile-session-terminal-reply-schema' -import '../../../worktree/session-worktree-record-reply-schema' -import '../composer/mobile-native-chat-skill-reply-schema' -import '../../../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../../../files/workspace-file-paths-reply-schema' // Retain the live window on refusal and let the caller offer retry; read the whole legacy error/window union before selecting messages. export const nativeChatSessionPageRead = bindDeferredRpcOperation( diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx index e1cee3abee1..3facb1e14f7 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx @@ -5,7 +5,6 @@ import type * as ReactNative from 'react-native' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MobileNativeChatComposer } from './MobileNativeChatComposer' import { MobileNativeChatLowerRegion } from '../MobileNativeChatLowerRegion.web' -import { NATIVE_CHAT_STEER_CHORD_HOLD_MS } from '../../../../../src/shared/native-chat/input/use-native-chat-steer-chord-preview' vi.mock('react-native', () => vi.importActual('react-native-web')) vi.mock( @@ -189,31 +188,6 @@ describe('mobile composer modifier submit in the paired web page', () => { expect(field().value).toBe(' hello ') }) - it('holding Cmd alone on an empty composer shows Steer queued in Send, lights the head card and sends it on a press', async () => { - vi.spyOn(document, 'hasFocus').mockReturnValue(true) - const steerHead = { steers: () => true, run: vi.fn(() => true), light: vi.fn() } - await render({ value: '', sendFollowUp: { action: 'queue', offersChoice: true }, steerHead }) - const preview = () => container.querySelector('[data-preview]') - vi.useFakeTimers() - try { - await act(async () => { - field().dispatchEvent(new KeyboardEvent('keydown', { key: 'Meta', bubbles: true })) - }) - await act(async () => vi.advanceTimersByTime(NATIVE_CHAT_STEER_CHORD_HOLD_MS)) - } finally { - vi.useRealTimers() - } - expect(preview()?.dataset.preview).toBe('steer-queued') - expect(steerHead.light).toHaveBeenLastCalledWith(true) - await act(async () => preview()?.click()) - expect(steerHead.run).toHaveBeenCalledExactlyOnceWith(true) - await act(async () => { - field().dispatchEvent(new KeyboardEvent('keyup', { key: 'Meta', bubbles: true })) - }) - expect(preview()).toBeNull() - expect(steerHead.light).toHaveBeenLastCalledWith(false) - }) - it.each([ { value: '@rea', expected: '@README.md ', filePaths: ['README.md', 'src/read.ts'] }, { value: '/comp', expected: '/compact ', filePaths: [] } diff --git a/mobile/src/session/native-chat/composer/mobile-draft-inputs-scaling.test.ts b/mobile/src/session/native-chat/composer/mobile-draft-inputs-scaling.test.ts deleted file mode 100644 index 8155332bd37..00000000000 --- a/mobile/src/session/native-chat/composer/mobile-draft-inputs-scaling.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import { afterEach, expect, it, vi } from 'vitest' -import { useMobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments' -import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments' -import { - useMobileNativeChatDraft, - setMobileNativeChatDraftText, - resetMobileNativeChatDraftStoreForTests -} from './mobile-native-chat-draft-store' -import { - subscribeMobileNativeChatDraftInputs, - updateMobileNativeChatDraftInputs, - closeMobileNativeChatEditInputs, - useMobileNativeChatDraftInputs -} from './mobile-native-chat-draft-inputs' - -const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() })) -vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => picker })) -afterEach(resetMobileNativeChatDraftStoreForTests) - -it.each([20, 200])( - 'isolates mounted text, input, image and file consumers across %i other scopes', - async (count) => { - const scopes = [ - 'own-host:target', - ...Array.from({ length: count }, (_, i) => `other-host:${i}`) - ] - const own = scopes[0] - const renders = scopes.map(() => ({ text: 0, input: 0, image: 0, file: 0 })) - const values: { - text: string - pending: number - images: readonly string[] - files: readonly string[] - }[] = scopes.map(() => ({ text: '', pending: 0, images: [], files: [] })) - const upstream = scopes.map(() => vi.fn()) - const releases = scopes.map((scope, i) => - subscribeMobileNativeChatDraftInputs(scope, upstream[i]) - ) - function Text({ index }: { index: number }) { - values[index].text = useMobileNativeChatDraft(scopes[index]) - renders[index].text++ - return null - } - function Input({ index }: { index: number }) { - values[index].pending = useMobileNativeChatDraftInputs(scopes[index]).pending ?? 0 - renders[index].input++ - return null - } - function File({ index }: { index: number }) { - const file = useMobileNativeChatFileAttachments({ - client: null, - sessionId: null, - scopeKey: scopes[index], - enabled: false, - showToast: vi.fn() - }) - values[index].files = file.files.map((entry) => entry.path ?? '') - renders[index].file++ - return null - } - function Image({ index }: { index: number }) { - const image = useMobileNativeChatImageAttachments({ - client: null, - agent: 'codex', - activeHandleRef: { current: null }, - deviceTokenRef: { current: null }, - getActiveWorktreeConnectionId: async () => null, - connState: 'disconnected', - scopeKey: scopes[index], - enabled: false, - structuredNativeChat: true, - showToast: vi.fn(), - onSendError: vi.fn(), - baseSend: async () => 'rejected', - readSeededLaunchDraft: () => null - }) - values[index].images = image.attachments.map((entry) => entry.path) - renders[index].image++ - return null - } - let view: ReturnType | undefined - await act(async () => { - view = create( - createElement( - 'fixture', - {}, - scopes.flatMap((_, index) => [ - createElement(Text, { key: `t${index}`, index }), - createElement(Input, { key: `p${index}`, index }), - createElement(File, { key: `f${index}`, index }), - createElement(Image, { key: `i${index}`, index }) - ]) - ) - ) - }) - renders.forEach((entry) => { - entry.text = entry.input = entry.image = entry.file = 0 - }) - try { - await act(async () => setMobileNativeChatDraftText(own, 'own text')) - expect(values[0].text).toBe('own text') - expect(renders[0]).toEqual({ text: 1, input: 0, image: 0, file: 0 }) - await act(async () => - updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 1 })) - ) - expect(values[0].pending).toBe(1) - await act(async () => - updateMobileNativeChatDraftInputs(own, (current) => ({ - ...current, - images: [{ id: 'image', path: '/saved.png', previewUri: 'file:///saved.png' }] - })) - ) - expect(values[0].images).toEqual(['/saved.png']) - await act(async () => - updateMobileNativeChatDraftInputs(own, (current) => ({ - ...current, - files: [ - { id: 'file', path: '/saved.txt', name: 'saved.txt', mime: 'text/plain', byteLength: 1 } - ] - })) - ) - expect(values[0].files).toEqual(['/saved.txt']) - expect(renders[0]).toEqual({ text: 1, input: 3, image: 2, file: 1 }) - expect(upstream[0]).toHaveBeenCalledTimes(3) - for (let index = 1; index < scopes.length; index++) { - expect(renders[index]).toEqual({ text: 0, input: 0, image: 0, file: 0 }) - expect(upstream[index]).not.toHaveBeenCalled() - } - } finally { - await act(async () => view?.unmount()) - releases.forEach((release) => release()) - } - await act(async () => - updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 0 })) - ) - expect(renders[0]).toEqual({ text: 1, input: 3, image: 2, file: 1 }) - expect(upstream[0]).toHaveBeenCalledTimes(3) - } -) -it.each([20, 200])( - 'notifies only affected scopes across %i retained input subscribers and retires listeners', - (count) => { - const idle = vi.fn() - const releases = Array.from({ length: count }, (_, index) => - subscribeMobileNativeChatDraftInputs(`idle-${index}`, idle) - ) - const source = vi.fn() - const destination = vi.fn() - releases.push( - subscribeMobileNativeChatDraftInputs('queued-edit:one', source), - subscribeMobileNativeChatDraftInputs('bottom', destination) - ) - updateMobileNativeChatDraftInputs('queued-edit:one', (inputs) => ({ ...inputs, pending: 1 })) - expect(source).toHaveBeenCalledTimes(1) - expect(idle).not.toHaveBeenCalled() - closeMobileNativeChatEditInputs('queued-edit:one', 'bottom') - expect(source).toHaveBeenCalledTimes(2) - expect(destination).toHaveBeenCalledTimes(1) - expect(idle).not.toHaveBeenCalled() - releases.forEach((release) => release()) - updateMobileNativeChatDraftInputs('bottom', (inputs) => ({ ...inputs, pending: 0 })) - expect(destination).toHaveBeenCalledTimes(1) - } -) diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts index 337c2995584..c6f5e4d0f6a 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts @@ -225,13 +225,6 @@ export function captureMobileNativeChatTextDestination(): return focusedScope ? textDestinations.get(focusedScope)?.() : undefined } -export function resetMobileNativeChatDraftInputsForTests(): void { - drafts.clear() - destinations.clear() - textDestinations.clear() - focusedScope = null -} - export function pruneMobileNativeChatDraftSkills( scope: string, text: string, diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-persistence.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-persistence.ts index 80a77014ac6..68c3989edac 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-persistence.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-persistence.ts @@ -19,7 +19,6 @@ import { deviceStoreDraftBackend, durableDraftRow, durableDraftRowKey, - resetDurableDraftRowsForTests, type DurableDraftRow, type DurableDraftRowBackend } from '../../../drafts/durable-draft-rows' @@ -204,8 +203,3 @@ export function closeSavedMobileNativeChatDraft(scope: string): void { tab.workspace.row.save('immediate') } } - -export function resetMobileNativeChatDraftPersistenceForTests(): void { - resetDurableDraftRowsForTests() - workspaces.clear() -} diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts index c4bf647ba36..1ea977b8fdc 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.test.ts @@ -1,13 +1,20 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { - resetMobileNativeChatDraftStoreForTests, + closeMobileNativeChatTabDraft, useMobileNativeChatDraft } from './mobile-native-chat-draft-store' -import { resetMobileNativeChatDraftInputsForTests } from './mobile-native-chat-draft-inputs' + +import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = + await import('../../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) type DraftState = ReturnType & { composerText: string } @@ -15,10 +22,12 @@ describe('mobile native-chat draft store', () => { let renderer: ReactTestRenderer | null = null let state: DraftState | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) - resetMobileNativeChatDraftStoreForTests() - resetMobileNativeChatDraftInputsForTests() + await loadMobileNativeChatDrafts('host', 'worktree') + closeMobileNativeChatTabDraft('host\0worktree\0a') + closeMobileNativeChatTabDraft('host\0worktree\0b') + await loadMobileNativeChatDrafts('host', 'worktree') renderer = null state = null }) diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts index 565990929b3..ba17d73c0d9 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-store.ts @@ -2,7 +2,6 @@ import { useSyncExternalStore, type SetStateAction } from 'react' import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import { appendReturnedDraftText } from '../../../../../src/shared/returned-draft-text' import { - resetMobileNativeChatDraftInputsForTests, returnMobileNativeChatDraftAttachments, closeMobileNativeChatEditInputs, mobileNativeChatDraftDestination, @@ -18,7 +17,6 @@ import { readMobileNativeChatInFlightSend, readMobileNativeChatInFlightSendsByScope, registerSavedMobileNativeChatInFlightSends, - resetMobileNativeChatInFlightSendsForTests, retireMobileNativeChatInFlightSends, restoredImages, restoredFiles, @@ -28,13 +26,11 @@ import { import { dropMobileNativeChatOfflineSends, mobileNativeChatOfflineSendScopes, - resetMobileNativeChatOfflineSendsForTests, restoreMobileNativeChatOfflineSends, savedMobileNativeChatOfflineSends } from './mobile-native-chat-offline-sends' import { closeSavedMobileNativeChatDraft, - resetMobileNativeChatDraftPersistenceForTests, retainSavedMobileNativeChatDrafts, saveMobileNativeChatDraft, setMobileNativeChatDraftSource @@ -306,15 +302,6 @@ export function useMobileNativeChatDraft(draftKey: string | null): string { return useSyncExternalStore(subscribe, read, read) } -export function resetMobileNativeChatDraftStoreForTests(): void { - resetMobileNativeChatDraftInputsForTests() - drafts.clear() - resetMobileNativeChatInFlightSendsForTests() - resetMobileNativeChatOfflineSendsForTests() - mobileNativeChatLaunchDraftSeeds.clear() - resetMobileNativeChatDraftPersistenceForTests() -} - export type MobileComposerWriter = ((text: string) => boolean) & { captureOrigin?: () => (text: string) => boolean } diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.test.ts index c6a04295615..6a373e8674f 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.test.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-file-attachment.test.ts @@ -1,26 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - MobileFileTooLargeError, - type PickedMobileFile -} from '../../../platform/media-picker-contract' -import { - nativeChatTextWithFileReferences, - uploadPickedNativeChatFiles, - type PendingNativeChatFile -} from './mobile-native-chat-file-attachment' - -function picked(name: string): PickedMobileFile { - return { name, mime: 'text/plain', byteLength: 1, base64: 'YQ==' } -} - -async function* pickedFiles(files: PickedMobileFile[], thenThrow?: Error) { - for (const file of files) { - yield file - } - if (thenThrow) { - throw thenThrow - } -} +import { nativeChatTextWithFileReferences } from './mobile-native-chat-file-attachment' describe('nativeChatTextWithFileReferences', () => { it('references each stored file on a line after the text', () => { @@ -39,64 +18,3 @@ describe('nativeChatTextWithFileReferences', () => { expect(nativeChatTextWithFileReferences('hi', [])).toBe('hi') }) }) - -describe('uploadPickedNativeChatFiles', () => { - function run(files: AsyncIterable, failName?: string) { - const chips = new Map() - const errors: string[] = [] - const pickedChips: PendingNativeChatFile[] = [] - let id = 0 - const done = uploadPickedNativeChatFiles({ - picked: files, - upload: async (file) => { - if (file.name === failName) { - throw new Error('host refused') - } - return { path: `/store/${file.name}`, name: file.name, byteLength: 1 } - }, - nextId: () => `file-${(id += 1)}`, - onPicked: (file) => { - pickedChips.push(file) - chips.set(file.id, file) - }, - onStored: (fileId, stored) => { - const chip = chips.get(fileId) - if (chip) { - chips.set(fileId, { ...chip, path: stored.path }) - } - }, - onFailed: (fileId) => chips.delete(fileId), - onError: (message) => errors.push(message) - }) - return { chips, errors, pickedChips, done } - } - - it('keeps every stored file as a chip with its host path', async () => { - const { chips, errors, pickedChips, done } = run( - pickedFiles([picked('a.txt'), picked('b.txt')]) - ) - await done - expect(pickedChips).toEqual([ - { id: 'file-1', name: 'a.txt', mime: 'text/plain', byteLength: 1, path: null }, - { id: 'file-2', name: 'b.txt', mime: 'text/plain', byteLength: 1, path: null } - ]) - expect([...chips.values()].map((chip) => chip.path)).toEqual(['/store/a.txt', '/store/b.txt']) - expect(errors).toEqual([]) - }) - - it('drops the chip of a failed upload, says which file, and carries on', async () => { - const { chips, errors, done } = run(pickedFiles([picked('a.txt'), picked('b.txt')]), 'a.txt') - await done - expect([...chips.values()].map((chip) => chip.name)).toEqual(['b.txt']) - expect(errors).toEqual(["Couldn't upload a.txt"]) - }) - - it('keeps what was stored before the picker refused an oversized file', async () => { - const { chips, errors, done } = run( - pickedFiles([picked('a.txt')], new MobileFileTooLargeError('clip.mov')) - ) - await done - expect([...chips.values()].map((chip) => chip.name)).toEqual(['a.txt']) - expect(errors).toEqual([new MobileFileTooLargeError('clip.mov').message]) - }) -}) diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-image-scope-state.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-image-scope-state.ts deleted file mode 100644 index 3429717ed67..00000000000 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-image-scope-state.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment' - -export const NO_NATIVE_CHAT_IMAGE_ATTACHMENTS: PendingNativeChatImage[] = [] - -export type MobileNativeChatImagesByScope = Record - -export function withScopeAttachments( - byScope: Readonly>, - scope: string, - next: List -): Record { - if (next.length > 0) { - return { ...byScope, [scope]: next } - } - const remaining = { ...byScope } - delete remaining[scope] - return remaining -} diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts index f4d9d025cf0..d979ebb5d35 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts @@ -215,7 +215,3 @@ export function retireMobileNativeChatInFlightSends(scope: string): void { } } } - -export function resetMobileNativeChatInFlightSendsForTests(): void { - inFlightSends.clear() -} diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts index 6d74c9bfa40..bb086a110ab 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts @@ -7,7 +7,7 @@ import { updateMobileNativeChatDraftInputs } from './mobile-native-chat-draft-inputs' import { - resetMobileNativeChatDraftStoreForTests, + closeMobileNativeChatTabDraft, setMobileNativeChatDraftText, useMobileNativeChatDraft } from './mobile-native-chat-draft-store' @@ -17,7 +17,7 @@ let text = '' afterEach(() => { act(() => renderer?.unmount()) - resetMobileNativeChatDraftStoreForTests() + closeMobileNativeChatTabDraft('scope') renderer = null }) diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-offline-sends.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-offline-sends.ts index 53ab4be9eb2..e2e74e4acc8 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-offline-sends.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-offline-sends.ts @@ -186,7 +186,3 @@ export function useMobileNativeChatOfflineSends( }, []) return useSyncExternalStore(subscribe, () => readMobileNativeChatOfflineSends(scope)) } - -export function resetMobileNativeChatOfflineSendsForTests(): void { - queues.clear() -} diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-skill-operations.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-skill-operations.ts index fc06f8e0be0..de98372945e 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-skill-operations.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-skill-operations.ts @@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader' import '../../../terminal/terminal-reply-schema' import { skillDiscoveryReplySchema } from './mobile-native-chat-skill-reply-schema' -import '../../agent-launch/mobile-agent-detection-reply-schema' -import '../../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../../../terminal/session/mobile-session-terminal-reply-schema' -import '../../../worktree/session-worktree-record-reply-schema' -import '../../../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../../../files/workspace-file-paths-reply-schema' // Mobile names the workspace and lets the host resolve and scan it; see SKILL_DISCOVER_WORKSPACE_CAPABILITY. export const nativeChatSkillDiscoveryRead = bindDeferredRpcOperation( diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts index 201a3072094..1db30d2be50 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts @@ -1,14 +1,22 @@ import { createElement } from 'react' import { act, create } from 'react-test-renderer' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { - resetMobileNativeChatDraftStoreForTests, + closeMobileNativeChatTabDraft, useMobileNativeChatDraft } from './mobile-native-chat-draft-store' +import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = + await import('../../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) + type DraftState = ReturnType & { composerText: string } type TestRenderer = { unmount(): void @@ -39,9 +47,11 @@ describe('useMobileNativeChatDrafts glued pending sends', () => { let renderer: TestRenderer | null = null let state: DraftState | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) - resetMobileNativeChatDraftStoreForTests() + await loadMobileNativeChatDrafts('host', 'worktree') + closeMobileNativeChatTabDraft('host\0worktree\0tab') + await loadMobileNativeChatDrafts('host', 'worktree') renderer = null state = null }) diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-launch-draft.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-launch-draft.test.ts index a6b9e635071..34fbb34186e 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-launch-draft.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-launch-draft.test.ts @@ -1,14 +1,22 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { - resetMobileNativeChatDraftStoreForTests, + closeMobileNativeChatTabDraft, useMobileNativeChatDraft } from './mobile-native-chat-draft-store' +import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = + await import('../../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) + type DraftState = ReturnType & { composerText: string } function userTextMessage(id: string, text: string): NativeChatMessage { @@ -25,9 +33,12 @@ describe('useMobileNativeChatDrafts launch draft', () => { let renderer: ReactTestRenderer | null = null let state: DraftState | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) - resetMobileNativeChatDraftStoreForTests() + await loadMobileNativeChatDrafts('host', 'worktree') + closeMobileNativeChatTabDraft('host\0worktree\0a') + closeMobileNativeChatTabDraft('host\0worktree\0b') + await loadMobileNativeChatDrafts('host', 'worktree') renderer = null state = null }) diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts index 69def691118..1bea79e1632 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts @@ -1,19 +1,29 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { - resetMobileNativeChatDraftStoreForTests, + closeMobileNativeChatTabDraft, useMobileNativeChatDraft } from './mobile-native-chat-draft-store' +import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = + await import('../../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) + describe('useMobileNativeChatDrafts with queued cards', () => { let renderer: ReactTestRenderer | null = null let state: (ReturnType & { composerText: string }) | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) - resetMobileNativeChatDraftStoreForTests() + await loadMobileNativeChatDrafts('host', 'worktree') + closeMobileNativeChatTabDraft('host\0worktree\0a') + await loadMobileNativeChatDrafts('host', 'worktree') renderer = null state = null }) diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.test.ts index 3545d6e078a..f5bd3751aae 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.test.ts @@ -4,10 +4,18 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { - resetMobileNativeChatDraftStoreForTests, + closeMobileNativeChatTabDraft, useMobileNativeChatDraft } from './mobile-native-chat-draft-store' +import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = + await import('../../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) + type DraftState = ReturnType & { composerText: string } function userTextMessage(id: string, text: string): NativeChatMessage { @@ -34,11 +42,15 @@ describe('useMobileNativeChatDrafts', () => { let renderer: ReactTestRenderer | null = null let state: DraftState | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) - resetMobileNativeChatDraftStoreForTests() + await loadMobileNativeChatDrafts('host', 'worktree') + closeMobileNativeChatTabDraft('host\0worktree\0a') + closeMobileNativeChatTabDraft('host\0worktree\0b') + await loadMobileNativeChatDrafts('host', 'worktree') renderer = null state = null + vi.useRealTimers() }) function Harness({ @@ -195,7 +207,8 @@ describe('useMobileNativeChatDrafts', () => { ) expect(state?.composerText).toBe('') } finally { - vi.useRealTimers() + act(() => renderer?.unmount()) + renderer = null } }) @@ -354,52 +367,6 @@ describe('useMobileNativeChatDrafts', () => { expect(state?.composerText).toBe(' /clear') }) - it('reconciles an image-only unconfirmed send against the next user turn (no false warning)', async () => { - vi.useFakeTimers() - try { - await mount('a') - await act(async () => - renderer?.update( - createElement(Harness, { tabId: 'a', messages: [assistantTextMessage('a1', 'hi')] }) - ) - ) - const origin = state?.captureSendOrigin('') - const onUnconfirmed = vi.fn() - act(() => { - if (origin) { - state?.holdUnconfirmedSend(origin, '', onUnconfirmed) - } - }) - - await act(async () => - renderer?.update( - createElement(Harness, { - tabId: 'a', - messages: [assistantTextMessage('a1', 'hi'), assistantTextMessage('a2', 'ok')] - }) - ) - ) - await act(async () => - renderer?.update( - createElement(Harness, { - tabId: 'a', - messages: [ - assistantTextMessage('a1', 'hi'), - assistantTextMessage('a2', 'ok'), - userTextMessage('u1', '') - ] - }) - ) - ) - act(() => { - vi.advanceTimersByTime(30_000) - }) - expect(onUnconfirmed).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - it('clears image-only echoes one per landed user turn, not all at once', async () => { await mount('a') await act(async () => @@ -430,59 +397,6 @@ describe('useMobileNativeChatDrafts', () => { expect(state?.pending.map((pending) => pending.images)).toEqual([['file:///b.jpg']]) }) - it('registers no deadline when the transcript echo beat the ambiguous RPC rejection', async () => { - vi.useFakeTimers() - try { - await mount('a') - const origin = state?.captureSendOrigin('ping') - const onUnconfirmed = vi.fn() - - await act(async () => - renderer?.update( - createElement(Harness, { tabId: 'a', messages: [userTextMessage('m1', 'ping')] }) - ) - ) - act(() => { - if (origin) { - state?.holdUnconfirmedSend(origin, 'ping', onUnconfirmed) - } - }) - - expect(vi.getTimerCount()).toBe(0) - act(() => { - vi.advanceTimersByTime(30_000) - }) - expect(onUnconfirmed).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) - - it('surfaces uncertainty when no echo lands before the deadline', async () => { - vi.useFakeTimers() - try { - await mount('a') - const origin = state?.captureSendOrigin('ping') - const onUnconfirmed = vi.fn() - act(() => { - if (origin) { - state?.holdUnconfirmedSend(origin, 'ping', onUnconfirmed) - } - }) - - act(() => { - vi.advanceTimersByTime(19_999) - }) - expect(onUnconfirmed).not.toHaveBeenCalled() - act(() => { - vi.advanceTimersByTime(1) - }) - expect(onUnconfirmed).toHaveBeenCalledTimes(1) - } finally { - vi.useRealTimers() - } - }) - it('does not confirm an unconfirmed send against an older identical turn', async () => { vi.useFakeTimers() try { @@ -516,7 +430,8 @@ describe('useMobileNativeChatDrafts', () => { }) expect(onUnconfirmed).toHaveBeenCalledTimes(1) } finally { - vi.useRealTimers() + act(() => renderer?.unmount()) + renderer = null } }) @@ -552,64 +467,8 @@ describe('useMobileNativeChatDrafts', () => { }) expect(onUnconfirmed).toHaveBeenCalledTimes(1) } finally { - vi.useRealTimers() - } - }) - - it('requires one new transcript echo per repeated unconfirmed send', async () => { - vi.useFakeTimers() - try { - await mount('a') - act(() => state?.setComposerText('ping')) - const origin = state?.captureSendOrigin('ping') - const firstUnconfirmed = vi.fn() - const secondUnconfirmed = vi.fn() - act(() => { - if (origin) { - state?.holdUnconfirmedSend(origin, 'ping', firstUnconfirmed) - state?.holdUnconfirmedSend(origin, 'ping', secondUnconfirmed) - } - }) - - await act(async () => - renderer?.update( - createElement(Harness, { tabId: 'a', messages: [userTextMessage('echo-1', 'ping')] }) - ) - ) - act(() => { - vi.advanceTimersByTime(30_000) - }) - - expect(firstUnconfirmed).not.toHaveBeenCalled() - expect(secondUnconfirmed).toHaveBeenCalledTimes(1) - } finally { - vi.useRealTimers() - } - }) - - it('does not retain a deadline when an ambiguous send settles after unmount', async () => { - vi.useFakeTimers() - try { - await mount('a') - const origin = state?.captureSendOrigin('ping') - const holdUnconfirmedSend = state?.holdUnconfirmedSend - const onUnconfirmed = vi.fn() act(() => renderer?.unmount()) renderer = null - - act(() => { - if (origin) { - holdUnconfirmedSend?.(origin, 'ping', onUnconfirmed) - } - }) - - expect(vi.getTimerCount()).toBe(0) - act(() => { - vi.advanceTimersByTime(30_000) - }) - expect(onUnconfirmed).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() } }) @@ -661,7 +520,8 @@ describe('useMobileNativeChatDrafts', () => { }) expect(onUnconfirmed).toHaveBeenCalledTimes(1) } finally { - vi.useRealTimers() + act(() => renderer?.unmount()) + renderer = null } }) diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts index c9af74ba808..cdae2e0d6e9 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts @@ -1,4 +1,4 @@ -import { resetMobileNativeChatDraftInputsForTests } from './mobile-native-chat-draft-inputs' +import { closeMobileNativeChatEditInputs } from './mobile-native-chat-draft-inputs' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import '../../../../../src/shared/agent-launch/startup/agent-tui-input-clear' @@ -79,6 +79,8 @@ function baseArgs(overrides: Partial & Pick): Hook describe('useMobileNativeChatImageAttachments', () => { let renderer: ReactTestRenderer | null = null let hook: Hook | null = null + let releaseConnection: ((id: string | null) => void) | null = null + let firstAttach: Promise | null = null function Harness({ args }: { args: HookArgs }): null { hook = useMobileNativeChatImageAttachments(args) @@ -86,14 +88,20 @@ describe('useMobileNativeChatImageAttachments', () => { } beforeEach(() => { - resetMobileNativeChatDraftInputsForTests() ids.next = 0 pick.mockReset() resetMobileNativeChatStaleInputForTests() resetMobileNativeChatTerminalWritesForTests() }) - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) + closeMobileNativeChatEditInputs(SCOPE_A) + await act(async () => { + releaseConnection?.(null) + await firstAttach + }) + releaseConnection = null + firstAttach = null renderer = null hook = null }) @@ -106,7 +114,6 @@ describe('useMobileNativeChatImageAttachments', () => { it('keeps isAttaching true when a cancelled pick overlaps a genuine in-flight upload', async () => { // Hold a real upload after its counter increment; a concurrent cancelled pick must not decrement work it never started. - let releaseConnection: ((id: string | null) => void) | null = null const client = makeClient([methodNotFound('start'), ok('save', '/tmp/a.png')]) const args = baseArgs({ client: client as unknown as RpcClient, @@ -118,7 +125,6 @@ describe('useMobileNativeChatImageAttachments', () => { mount(args) pick.mockResolvedValue([{ base64: 'AAAA', uri: 'file:///a.jpg' }]) - let firstAttach: Promise | null = null await act(async () => { firstAttach = hook!.attachImage('library') for (let i = 0; i < 50 && !releaseConnection; i++) { diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts index 4700cd63d6b..a47686107f4 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts @@ -3,16 +3,21 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import type { MobileNativeChatInputLockReason } from '../MobileNativeChatView' -import { resetMobileNativeChatDraftStoreForTests } from './mobile-native-chat-draft-store' -import { - readMobileNativeChatOfflineSends, - resetMobileNativeChatOfflineSendsForTests -} from './mobile-native-chat-offline-sends' +import { closeMobileNativeChatTabDraft } from './mobile-native-chat-draft-store' +import { readMobileNativeChatOfflineSends } from './mobile-native-chat-offline-sends' import { useMobileNativeChatOfflineQueue, type MobileNativeChatOfflineQueue } from './use-mobile-native-chat-offline-sends' +import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = + await import('../../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) + const SCOPE = 'host\0worktree\0tab' type Send = (text: string, intent?: MobileNativeChatSendIntent) => Promise @@ -20,6 +25,8 @@ type Send = (text: string, intent?: MobileNativeChatSendIntent) => Promise { let renderer: ReactTestRenderer | null = null let queue: MobileNativeChatOfflineQueue | null = null + let releasePending: (() => void) | null = null + let pendingSend: Promise | null = null function Harness({ lock, send }: { lock: MobileNativeChatInputLockReason | null; send: Send }) { queue = useMobileNativeChatOfflineQueue({ @@ -41,12 +48,19 @@ describe('useMobileNativeChatOfflineQueue', () => { await act(async () => renderer?.update(createElement(Harness, { lock: null, send }))) } - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) renderer = null queue = null - resetMobileNativeChatOfflineSendsForTests() - resetMobileNativeChatDraftStoreForTests() + await loadMobileNativeChatDrafts('host', 'worktree') + closeMobileNativeChatTabDraft('host\0worktree\0tab') + await act(async () => { + releasePending?.() + await pendingSend + }) + releasePending = null + pendingSend = null + await loadMobileNativeChatDrafts('host', 'worktree') }) it('pauses a queued message whose send fails and holds later sends behind it until Resume', async () => { @@ -84,13 +98,16 @@ describe('useMobileNativeChatOfflineQueue', () => { it('keeps a pending send single across remounts and drains later messages when it settles', async () => { const delivered: string[] = [] let finishFirst: ((sent: boolean) => void) | undefined - const send: Send = async (text) => { + const send: Send = (text) => { delivered.push(text) - return text === 'first' - ? new Promise((resolve) => { - finishFirst = resolve - }) - : true + pendingSend = + text === 'first' + ? new Promise((resolve) => { + finishFirst = resolve + releasePending = () => resolve(false) + }) + : Promise.resolve(true) + return pendingSend } await mount('disconnected', send) await act(async () => { diff --git a/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.test.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.test.ts deleted file mode 100644 index e7fb01c9d07..00000000000 --- a/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { mobileNativeChatDraftDestination } from './mobile-native-chat-draft-inputs' -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { StructuredAgentId } from '../../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' -import type { MobileNativeChatSendOrigin } from '../transcript/mobile-native-chat-pending-echo' - -import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge' -import { - recordMobileNativeChatSkillPick, - resetMobileNativeChatDraftStoreForTests -} from './mobile-native-chat-draft-store' - -const ORIGIN: MobileNativeChatSendOrigin = { - draftKey: 'draft', - draftDestination: mobileNativeChatDraftDestination('draft'), - draftEditGeneration: 0, - pendingKey: 'pending', - normalizedText: 'command', - boundary: { afterMessageId: null }, - sentAt: 0 -} - -describe('useMobileStructuredNativeChatSendBridge', () => { - let renderer: ReactTestRenderer | null = null - let sendWithOutcome: ReturnType['sendWithOutcome'] - const captureSendOrigin = vi.fn(() => ORIGIN) - const clearDraftForSend = vi.fn() - const onSendError = vi.fn() - const restoreRejectedDraft = vi.fn() - const sendStructured = vi.fn() - const holdUnconfirmed = vi.fn<(clientMessageId: string, onUnconfirmed: () => void) => void>() - - function Harness({ agent }: { agent: StructuredAgentId }): null { - sendWithOutcome = useMobileStructuredNativeChatSendBridge({ - agent, - captureSendOrigin, - clearDraftForSend, - onSendError, - restoreRejectedDraft, - sendStructured, - holdUnconfirmed - }).sendWithOutcome - return null - } - - function mount(agent: StructuredAgentId): void { - act(() => { - renderer = create(createElement(Harness, { agent })) - }) - } - - beforeEach(() => { - vi.clearAllMocks() - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - resetMobileNativeChatDraftStoreForTests() - }) - - it('puts a host command whose reply was lost back in the box', async () => { - sendStructured.mockResolvedValue('unknown') - mount('codex') - - await expect(sendWithOutcome('/compact')).resolves.toBe('unknown') - - expect(holdUnconfirmed).not.toHaveBeenCalled() - expect(restoreRejectedDraft).toHaveBeenCalledWith(ORIGIN, '/compact', { - preserveConversationCommands: true - }) - }) - - it('sends a queued message with its own skills and leaves the composer alone when refused', async () => { - recordMobileNativeChatSkillPick(ORIGIN.draftKey, { - token: '$draft', - path: '/skills/draft/SKILL.md' - }) - sendStructured.mockResolvedValue('rejected') - mount('codex') - const queuedSkill = { name: 'review', path: '/skills/review/SKILL.md' } - - await expect( - sendWithOutcome('$review the PR', undefined, undefined, undefined, undefined, { - queued: { - id: 'queued-1', - images: [], - files: [], - skills: [queuedSkill], - skillOrigin: '$review' - } - }) - ).resolves.toBe('rejected') - - expect(sendStructured.mock.calls[0]![4]).toEqual([queuedSkill]) - expect(clearDraftForSend).not.toHaveBeenCalled() - expect(restoreRejectedDraft).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.test.tsx index 8e39cddc41d..55bd4868066 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.test.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.test.tsx @@ -52,7 +52,6 @@ type Props = Parameters[0] type StopResult = Awaited> const REJECTED: StopResult = { status: 'rejected' } -const UNCONFIRMED: StopResult = { status: 'unknown' } const STOPPED: StopResult = { status: 'accepted', value: { cancelled: true }, sameFence: true } const NOTHING_STOPPED: StopResult = { status: 'accepted', @@ -98,20 +97,6 @@ describe('MobileNativeChatBackgroundTasks', () => { return mounted } - function styleOf(node: ReactTestInstance): Record { - const rendered: unknown = - typeof node.props.style === 'function' - ? node.props.style({ pressed: false }) - : node.props.style - const parts = Array.isArray(rendered) ? rendered : [rendered] - return Object.assign( - {}, - ...parts.filter( - (part): part is Record => typeof part === 'object' && part !== null - ) - ) - } - function header(mounted: ReactTestRenderer): ReactTestInstance { return mounted.root.findAll( (node) => @@ -132,31 +117,6 @@ describe('MobileNativeChatBackgroundTasks', () => { ) } - it('stops one row by its provider id and holds its button while the Stop is on its way', async () => { - let finish: (result: StopResult) => void = () => {} - const stop = vi.fn(() => new Promise((resolve) => (finish = resolve))) - const mounted = mount( - tasksFor( - { - state: 'monitoring', - supportsTaskStop: true, - children: [view('a'), view('b', { stoppable: false })] - }, - { stop } - ) - ) - expand(mounted) - const buttons = stopButtons(mounted) - expect(buttons.map((button) => button.props.accessibilityLabel)).toEqual(['Stop review a']) - act(() => buttons[0]!.props.onPress()) - act(() => buttons[0]!.props.onPress()) - expect(stop).toHaveBeenCalledTimes(1) - expect(stop).toHaveBeenCalledWith('task-a') - expect(stopButtons(mounted)[0]!.props.disabled).toBe(true) - await act(async () => finish(UNCONFIRMED)) - expect(stopButtons(mounted)[0]!.props.disabled).toBe(false) - }) - it('keeps a confirmed Stop held until its row leaves, and offers it again if the row comes back', async () => { let finish: (result: StopResult) => void = () => {} const stop = vi.fn(() => new Promise((resolve) => (finish = resolve))) @@ -206,30 +166,4 @@ describe('MobileNativeChatBackgroundTasks', () => { }) expect(stopButtons(mounted)[0]!.props.disabled).toBe(false) }) - - it('offers Stop all only to a host with no per-row stop that still accepts one', async () => { - let finish: (result: StopResult) => void = () => {} - const stop = vi.fn(() => new Promise((resolve) => (finish = resolve))) - const fallback = mount(tasksFor({ state: 'monitoring', children: [view('a')] }, { stop })) - expand(fallback) - expect(stopButtons(fallback).map((button) => button.props.accessibilityLabel)).toEqual([ - 'Stop background tasks' - ]) - const button = stopButtons(fallback)[0]! - expect(styleOf(button)).toMatchObject({ minHeight: 32, minWidth: 44 }) - expect(button.props.hitSlop).toBe(6) - expect(Number(styleOf(button).minHeight) + 2 * button.props.hitSlop).toBe(44) - act(() => button.props.onPress()) - act(() => button.props.onPress()) - expect(stop).toHaveBeenCalledTimes(1) - expect(stop).toHaveBeenCalledWith(undefined) - expect(stopButtons(fallback)[0]!.props.disabled).toBe(true) - await act(async () => finish(STOPPED)) - expect(stopButtons(fallback)[0]!.props.disabled).toBe(false) - const none = mount( - tasksFor({ state: 'monitoring', supportsStopAll: false, children: [view('a')] }) - ) - expand(none) - expect(stopButtons(none)).toEqual([]) - }) }) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx index d047b82d231..2aa3100d182 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx @@ -3,25 +3,12 @@ import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' import { createElement } from 'react' -import type * as QueuedCardRowModule from './MobileQueuedMessageCardRow' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import { MobileNativeChatQueuedMessages } from './MobileNativeChatQueuedMessages' -const rowRenders = vi.hoisted(() => ({ count: 0 })) -vi.mock('./MobileQueuedMessageCardRow', async (importOriginal) => { - const original = await importOriginal() - return { - MobileQueuedMessageCardRow: ( - props: Parameters[0] - ) => { - rowRenders.count++ - return createElement(original.MobileQueuedMessageCardRow, props) - } - } -}) let fontScale = 1 vi.mock('../../../components/DragReorderList', () => ({ DragReorderList: 'DragReorderList' })) vi.mock('react-native-reanimated', async () => { diff --git a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts index dee922e54dd..f43f8762553 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts +++ b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts @@ -148,31 +148,6 @@ describe('MobileNativeChatSessionOptionPickers', () => { renderer = null }) - it('toggles a Fast-only Codex speed on the same Fast mode switch as Claude', async () => { - const speed: SessionOptionDescriptor = { - id: 'serviceTier', - label: 'Speed', - kind: { - type: 'select', - currentValue: 'default', - choices: [ - { value: 'default', label: 'Standard' }, - { value: 'priority', label: 'Fast' } - ] - }, - valueSource: 'reported', - transport: 'catalog', - settable: true - } - mount([MODEL_DESCRIPTOR, speed], false, 'model') - const toggle = findAllByHostType(renderer!.root, 'Switch').find( - (node) => node.props.accessibilityLabel === 'Fast mode' - ) - expect(toggle?.props.value).toBe(false) - await act(async () => toggle!.props.onValueChange(true)) - expect(setOption).toHaveBeenCalledWith('serviceTier', 'priority') - }) - it('consumes a refused page without replay, then permits a fresh open and permission pick', async () => { const placeholder: SessionOptionDescriptor = { ...MODEL_DESCRIPTOR, diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-answer-stepping.test.ts b/mobile/src/session/native-chat/input/mobile-native-chat-answer-stepping.test.ts deleted file mode 100644 index ed8d3c730ea..00000000000 --- a/mobile/src/session/native-chat/input/mobile-native-chat-answer-stepping.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - mobileNativeChatQuestionOffsets, - scheduleMobileClaudeAnswer, - MOBILE_NATIVE_CHAT_ADVANCE_BUFFER_MS, - MOBILE_NATIVE_CHAT_SUBMIT_DELAY_MS -} from './mobile-native-chat-answer-stepping' - -describe('mobileNativeChatQuestionOffsets', () => { - it('paces each question a full step apart, Enter 500ms after its body', () => { - expect(mobileNativeChatQuestionOffsets(0)).toEqual({ bodyAt: 0, enterAt: 500 }) - expect(mobileNativeChatQuestionOffsets(1)).toEqual({ bodyAt: 1000, enterAt: 1500 }) - expect(mobileNativeChatQuestionOffsets(2)).toEqual({ bodyAt: 2000, enterAt: 2500 }) - }) -}) - -describe('scheduleMobileClaudeAnswer', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('writes each question body then its Enter, paced per step, one Enter per line', () => { - const events: string[] = [] - const timers = scheduleMobileClaudeAnswer( - ['', 'b', 'c'], - (line) => events.push(`body:${line}`), - () => events.push('enter') - ) - expect(timers).toHaveLength(6) - - vi.advanceTimersByTime(0) - expect(events).toEqual(['body:']) - vi.advanceTimersByTime(MOBILE_NATIVE_CHAT_SUBMIT_DELAY_MS - 1) - expect(events).toEqual(['body:']) - vi.advanceTimersByTime(1) - expect(events).toEqual(['body:', 'enter']) - vi.advanceTimersByTime(MOBILE_NATIVE_CHAT_ADVANCE_BUFFER_MS) - expect(events).toEqual(['body:', 'enter', 'body:b']) - - vi.runAllTimers() - expect(events).toEqual(['body:', 'enter', 'body:b', 'enter', 'body:c', 'enter']) - }) - - it('cancelling the returned timers stops all pending writes', () => { - const events: string[] = [] - const timers = scheduleMobileClaudeAnswer( - ['a', 'b'], - (line) => events.push(`body:${line}`), - () => events.push('enter') - ) - for (const timer of timers) { - clearTimeout(timer) - } - vi.runAllTimers() - expect(events).toEqual([]) - }) -}) diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-answer-stepping.ts b/mobile/src/session/native-chat/input/mobile-native-chat-answer-stepping.ts deleted file mode 100644 index ad105d55a74..00000000000 --- a/mobile/src/session/native-chat/input/mobile-native-chat-answer-stepping.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { - nativeChatQuestionOffsets, - scheduleNativeChatAnswer, - NATIVE_CHAT_ADVANCE_BUFFER_MS, - NATIVE_CHAT_QUESTION_STEP_MS, - NATIVE_CHAT_SUBMIT_DELAY_MS -} from '../../../../../src/shared/native-chat/input/native-chat-answer-stepping' - -export const MOBILE_NATIVE_CHAT_ADVANCE_BUFFER_MS = NATIVE_CHAT_ADVANCE_BUFFER_MS -export const MOBILE_NATIVE_CHAT_QUESTION_STEP_MS = NATIVE_CHAT_QUESTION_STEP_MS -export const MOBILE_NATIVE_CHAT_SUBMIT_DELAY_MS = NATIVE_CHAT_SUBMIT_DELAY_MS -export const mobileNativeChatQuestionOffsets = nativeChatQuestionOffsets -export const scheduleMobileClaudeAnswer = scheduleNativeChatAnswer diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-answered-prompts.test-fixture.ts b/mobile/src/session/native-chat/input/mobile-native-chat-answered-prompts.test-fixture.ts deleted file mode 100644 index 829ffd49bda..00000000000 --- a/mobile/src/session/native-chat/input/mobile-native-chat-answered-prompts.test-fixture.ts +++ /dev/null @@ -1,261 +0,0 @@ -// A structured Claude chat on the desktop, read back with `agentSession.history` after its owner -// approved a Bash call and answered an AskUserQuestion (Claude Code 2.1.300, 2026-10-15). - -import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' - -export const ANSWERED_PROMPT_ITEMS: AgentJournalRenderItem[] = [ - { - itemId: 'orca:1792024009236-87ed41e5430c47008ef7978ca5d60505', - revision: 0, - body: { - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: 'Run the bash command: echo receipt-check > receipt.txt' - } - ] - }, - sequence: 43, - observedAt: 1792024010442, - turnScope: { - kind: 'thread' - } - }, - { - itemId: - 'orca:claude-tool%3A2ee61cec-1207-4f44-a915-b6adbcbf169b%3Atoolu_01FhhC72BuRiD3d9hXkAsURD', - revision: 2, - body: { - kind: 'tool-call', - name: 'Bash', - input: { - command: 'echo receipt-check > receipt.txt', - description: 'Write receipt-check to receipt.txt' - }, - callId: 'toolu_01FhhC72BuRiD3d9hXkAsURD', - state: 'completed', - output: { - head: '(Bash completed with no output)', - byteLength: 31, - digest: 'cac1685585590361647e7a27b58a25a590f335bfcd0ab70fcdc0424e40c20843', - truncated: false - } - }, - sequence: 46, - observedAt: 1792024014854, - turnScope: { - kind: 'turn', - turnItemId: - 'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A6a80bc01-4be4-466f-bd98-5cae8368ed1d' - } - }, - { - itemId: - 'orca:claude-prompt%3Aclaude_c65b4304_2acf_4eec_a749_e06876328e0c%3A79c45210-730e-482c-82bd-db0708c992e5', - revision: 2, - body: { - kind: 'approval', - title: 'Allow Bash?', - displayName: 'Bash', - description: 'Write receipt-check to receipt.txt', - blockedPath: '/private/tmp/mnw-scratch/receipt.txt', - detail: - '{\n "command": "echo receipt-check > receipt.txt",\n "description": "Write receipt-check to receipt.txt"\n}', - options: [ - { - id: 'allow', - label: 'Allow' - }, - { - id: 'allowForSession', - label: 'Allow for this session' - }, - { - id: 'deny', - label: 'Deny' - } - ], - resolution: { - state: 'resolved', - selectedOptionId: 'allow', - resolvedBy: 'desktop-renderer', - resolvedAt: 1792024037937 - } - }, - sequence: 48, - observedAt: 1792024014910, - turnScope: { - kind: 'turn', - turnItemId: - 'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A6a80bc01-4be4-466f-bd98-5cae8368ed1d' - } - }, - { - itemId: 'claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:4408cf7b-bbe2-4a5d-aa80-6471db6d9c18', - revision: 2, - body: { - kind: 'message', - role: 'assistant', - blocks: [ - { - type: 'text', - text: 'I ran the command. `receipt.txt` in `/private/tmp/mnw-scratch` now holds the line `receipt-check`.' - } - ] - }, - sequence: 51, - observedAt: 1792024040901, - turnScope: { - kind: 'turn', - turnItemId: - 'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A6a80bc01-4be4-466f-bd98-5cae8368ed1d' - } - }, - { - itemId: 'orca:1792024048049-e58989ce33eb411a970225d03d2e4a18', - revision: 0, - body: { - kind: 'message', - role: 'user', - blocks: [ - { - type: 'text', - text: 'Use the AskUserQuestion tool to ask me whether I prefer tea or coffee, then reply with my answer in one short sentence.' - } - ] - }, - sequence: 57, - observedAt: 1792024048075, - turnScope: { - kind: 'thread' - } - }, - { - itemId: - 'orca:claude-tool%3A2ee61cec-1207-4f44-a915-b6adbcbf169b%3Atoolu_01WByTgphD4HFByq9zPKXn2J', - revision: 2, - body: { - kind: 'tool-call', - name: 'AskUserQuestion', - input: { - questions: [ - { - question: 'Do you prefer tea or coffee?', - header: 'Drink', - multiSelect: false, - options: [ - { - label: 'Tea', - description: 'You prefer tea.' - }, - { - label: 'Coffee', - description: 'You prefer coffee.' - } - ] - } - ] - }, - callId: 'toolu_01WByTgphD4HFByq9zPKXn2J', - state: 'completed', - output: { - head: 'Your questions have been answered: "Do you prefer tea or coffee?"="Coffee". You can now continue with these answers in mind.', - byteLength: 124, - digest: '65dfb0af315c9ab1c70fc26c6c6bfb4ef0138216e35c89cf332927d10cbb629d', - truncated: false - } - }, - sequence: 60, - observedAt: 1792024052205, - turnScope: { - kind: 'turn', - turnItemId: - 'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A1ea7cf09-10c6-4635-93bb-8d4b16fb1c60' - } - }, - { - itemId: - 'orca:claude-prompt%3Aclaude_c65b4304_2acf_4eec_a749_e06876328e0c%3A6fd8be6a-830f-44b4-a3ef-a7f044cd4a4f', - revision: 2, - body: { - kind: 'question', - question: 'Do you prefer tea or coffee?', - options: [ - { - id: 'q1:choice-1', - label: 'Tea', - description: 'You prefer tea.' - }, - { - id: 'q1:choice-2', - label: 'Coffee', - description: 'You prefer coffee.' - } - ], - freeTextQuestionId: 'q1', - questions: [ - { - id: 'q1', - question: 'Do you prefer tea or coffee?', - header: 'Drink', - multiSelect: false, - options: [ - { - id: 'q1:choice-1', - label: 'Tea', - description: 'You prefer tea.' - }, - { - id: 'q1:choice-2', - label: 'Coffee', - description: 'You prefer coffee.' - } - ], - freeTextQuestionId: 'q1' - } - ], - resolution: { - state: 'resolved', - selectedOptionId: 'question-group:[{"questionId":"q1","optionIds":["q1:choice-2"]}]', - answers: [ - { - questionId: 'q1', - optionIds: ['q1:choice-2'] - } - ], - resolvedBy: 'desktop-renderer', - resolvedAt: 1792024081980 - } - }, - sequence: 62, - observedAt: 1792024052228, - turnScope: { - kind: 'turn', - turnItemId: - 'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A1ea7cf09-10c6-4635-93bb-8d4b16fb1c60' - } - }, - { - itemId: 'claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:32c8a879-b68c-41ba-9a9e-4b844fa07890', - revision: 2, - body: { - kind: 'message', - role: 'assistant', - blocks: [ - { - type: 'text', - text: 'You prefer coffee.' - } - ] - }, - sequence: 65, - observedAt: 1792024084176, - turnScope: { - kind: 'turn', - turnItemId: - 'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A1ea7cf09-10c6-4635-93bb-8d4b16fb1c60' - } - } -] diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts index 96460626c77..c14ccdac4fd 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts @@ -8,7 +8,7 @@ import { import type { AskAnswerSelection } from '../../../../../src/shared/native-chat/input/native-chat-ask-answer' import type { AskPrompt } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping' +import { NATIVE_CHAT_QUESTION_STEP_MS } from '../../../../../src/shared/native-chat/input/native-chat-answer-stepping' import { openMobileNativeChatSendBudget, sendMobileNativeChatMessageWithOutcome @@ -229,11 +229,11 @@ export function useMobileNativeChatAnswerSend(args: { return fail() } if (index < groups.length - 1) { - if (!(await wait(MOBILE_NATIVE_CHAT_QUESTION_STEP_MS))) { + if (!(await wait(NATIVE_CHAT_QUESTION_STEP_MS))) { return false } // Pacing is deliberate, not transport latency — don't charge it to the budget. - deadline += MOBILE_NATIVE_CHAT_QUESTION_STEP_MS + deadline += NATIVE_CHAT_QUESTION_STEP_MS } } return groups.length > 0 && writeTurnsRef.current.get(handle) === turn diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts index 5feb142b26d..94978c32671 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts @@ -1,10 +1,10 @@ +import { randomUUID } from 'node:crypto' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' import { - clearMobileSessionOptionRecordsForTests, useMobileNativeChatSessionOptions, type MobileNativeChatSessionOptionsController } from './use-mobile-native-chat-session-options' @@ -15,6 +15,8 @@ describe('useMobileNativeChatSessionOptions', () => { let renderer: ReactTestRenderer | null = null let api: MobileNativeChatSessionOptionsController | null = null let hookArgs: HookArgs + let hostId: string + const scopeKey = (tabId: string): string => `${hostId}\0worktree\0${tabId}` const dispatchCommand = vi.fn() const onAgentPicker = vi.fn() @@ -26,7 +28,7 @@ describe('useMobileNativeChatSessionOptions', () => { const mount = (overrides: Partial = {}): void => { hookArgs = { agent: 'claude', - scopeKey: 'host\0worktree\0tab', + scopeKey: scopeKey('tab'), reportedModel: null, dispatchCommand, onAgentPicker, @@ -45,7 +47,7 @@ describe('useMobileNativeChatSessionOptions', () => { } beforeEach(() => { - clearMobileSessionOptionRecordsForTests() + hostId = `mobile-session-options-test-${randomUUID()}` dispatchCommand.mockReset() dispatchCommand.mockResolvedValue('accepted') onAgentPicker.mockReset() @@ -107,8 +109,8 @@ describe('useMobileNativeChatSessionOptions', () => { picked = api!.setOption('model', 'opus') await Promise.resolve() }) - update({ scopeKey: 'host\0worktree\0other-tab' }) - update({ scopeKey: 'host\0worktree\0tab' }) + update({ scopeKey: scopeKey('other-tab') }) + update({ scopeKey: scopeKey('tab') }) await act(async () => { resolveModel('accepted') await picked @@ -143,8 +145,8 @@ describe('useMobileNativeChatSessionOptions', () => { }) expect(api!.snapshot[0]!.kind).toMatchObject({ currentValue: 'opus' }) // Re-entering repeats session-start evidence that predates later user picks. - update({ scopeKey: 'host\0worktree\0other' }) - update({ scopeKey: 'host\0worktree\0tab' }) + update({ scopeKey: scopeKey('other') }) + update({ scopeKey: scopeKey('tab') }) expect(api!.snapshot[0]).toMatchObject({ valueSource: 'dispatched' }) expect(api!.snapshot[0]!.kind).toMatchObject({ currentValue: 'opus' }) }) @@ -156,8 +158,8 @@ describe('useMobileNativeChatSessionOptions', () => { }) // Repeatedly touch the live tab while exceeding capacity so insertion-order eviction would lose it. for (let index = 0; index < 40; index += 1) { - update({ scopeKey: `host\0worktree\0overflow-${index}` }) - update({ scopeKey: 'host\0worktree\0tab' }) + update({ scopeKey: scopeKey(`overflow-${index}`) }) + update({ scopeKey: scopeKey('tab') }) } expect(api!.snapshot[0]).toMatchObject({ valueSource: 'dispatched' }) expect(api!.snapshot[0]!.kind).toMatchObject({ currentValue: 'opus' }) @@ -209,7 +211,7 @@ describe('useMobileNativeChatSessionOptions', () => { queued = api!.setOption('model', 'opus') await Promise.resolve() }) - update({ scopeKey: 'host\0worktree\0other-tab' }) + update({ scopeKey: scopeKey('other-tab') }) await act(async () => { resolveFirst('accepted') await first diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts index e9f38403cc5..f5351f62cfa 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts @@ -25,7 +25,6 @@ import { type NativeChatPtySessionOptionsSurface } from '../../../../../src/shared/native-chat/input/native-chat-pty-session-options' import { - clearNativeChatSessionOptionCacheForTests, readNativeChatSessionOptionCache, writeNativeChatSessionOptionCache } from '../../../../../src/shared/native-chat/input/native-chat-session-option-cache' @@ -84,11 +83,6 @@ const getEmptySnapshot = (): SessionOptionDescriptor[] => EMPTY_SNAPSHOT // Kept across remounts: a repeated hook model is not fresh evidence, and reapplying it would revert a newer pick. const appliedReportByScope = new Map() -export function clearMobileSessionOptionRecordsForTests(): void { - clearNativeChatSessionOptionCacheForTests() - appliedReportByScope.clear() -} - /** A tab that runs another agent starts over: a new session there carries none of the old one's picks. */ function startScopeOverForAgent(scopeKey: string, agent: string): void { const cachedAgent = readNativeChatSessionOptionCache(scopeKey)?.agent diff --git a/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.chat-return.test.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.chat-return.test.ts deleted file mode 100644 index 572915f7b60..00000000000 --- a/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.chat-return.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// One phone chat view serves every chat tab, so returning to a chat must not wait on its next read. - -import { act } from 'react-test-renderer' -import { expect, it } from 'vitest' -import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' -import { - BASE, - OPTIONS, - accepted, - currentValueOf, - deferred, - mountOptions, - optionsClient, - recordingMutate, - settle -} from './use-mobile-structured-agent-options.test-fixture' - -const COMMAND = 'compact' -const CHAT_A: AgentSessionOptionsResult = { - ...OPTIONS, - acceptsImages: true, - conversationCommands: [COMMAND], - current: { - model: 'gpt-fast', - effort: 'low', - permissionMode: 'own', - reportedPermissionMode: 'ask', - acceptedInputSources: { model: 'saved', effort: 'saved' } - } -} -const CHAT_B: AgentSessionOptionsResult = { - ...OPTIONS, - acceptsImages: false, - current: { model: 'gpt-live', effort: 'high', permissionMode: 'ask' } -} - -/** Host replies per chat; later reads for chat A wait until the test answers them. */ -function chats() { - const later: ReturnType>[] = [] - let readsOfA = 0 - let readingB = false - const client = optionsClient(() => { - if (readingB) { - return Promise.resolve(CHAT_B) - } - if (readsOfA++ === 0) { - return Promise.resolve(CHAT_A) - } - const reply = deferred() - later.push(reply) - return reply.promise - }) - const send = client.client.sendRequest - client.client.sendRequest = (method, params, options) => { - if (method === 'agentSession.options') { - readingB = JSON.stringify(params).includes('chat-b') - } - return send(method, params, options) - } - return { client, later } -} - -it("shows a chat's last answer on return, without its reports, until its new read lands", async () => { - const { client, later } = chats() - const { mutate } = recordingMutate(async () => accepted({ key: 'model', value: 'x' }, true)) - const harness = await mountOptions({ - ...BASE, - sessionId: 'chat-a', - fence: 1, - client: client.client, - mutate, - permissionOwn: true, - sendSelection: true - }) - await harness.rerender({ sessionId: 'chat-b', fence: 7 }) - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('gpt-live') - const commitsOnB = harness.commits.length - await harness.rerender({ sessionId: 'chat-a', fence: 2 }) - expect(later).toHaveLength(1) - // From the first commit on return, not only after a later effect catches up. - for (const commit of harness.commits.slice(commitsOnB)) { - expect(currentValueOf(commit.optionSnapshot, 'model')).toBe('gpt-fast') - } - const shown = harness.current() - expect(currentValueOf(shown.optionSnapshot, 'model')).toBe('gpt-fast') - expect(currentValueOf(shown.optionSnapshot, 'effort')).toBe('low') - expect(shown.conversationCommands).toEqual([COMMAND]) - expect(shown.acceptsImages).toBe(true) - // Saved permission intent survives a restart independently of runtime reports. - expect(currentValueOf(shown.optionSnapshot, 'permissionMode')).toBe('own') - expect(shown.sendSelection()).toEqual({ selection: {} }) - - await act(async () => { - later[0].resolve({ - ...CHAT_A, - conversationCommands: [], - current: { ...CHAT_A.current, model: 'gpt-live' } - }) - }) - await settle() - const answered = harness.current() - expect(currentValueOf(answered.optionSnapshot, 'model')).toBe('gpt-live') - expect(currentValueOf(answered.optionSnapshot, 'permissionMode')).toBe('own') - expect(answered.conversationCommands).toEqual([]) - expect(answered.sendSelection()).toEqual({ selection: { model: 'gpt-live', effort: 'low' } }) - await harness.unmount() -}) diff --git a/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts index 15196cf15f9..7c813e1409e 100644 --- a/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts @@ -369,57 +369,6 @@ it('accepts a typed literal at an attached fence while options refresh with no m await view.unmount() }) -import type { PiRefreshFixtureModule } from '../../../../../src/shared/agent-session/options/structured-agent-session-option-refresh.test-fixture-contract' -const { piOptionRefreshContract } = await vi.importActual( - '../../../../../src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture' -) - -describe('Pi catalog refresh completion', () => { - piOptionRefreshContract( - async (host) => { - const first = optionsClient( - () => host.options(), - () => host.catalog() - ) - const second = optionsClient( - () => host.options(), - () => host.catalog() - ) - const { mutate } = recordingMutate(async (_call, fields) => { - if (typeof fields.value !== 'string') { - throw new Error('missing effort') - } - return accepted(await host.acceptEffort(fields.value), true) - }) - const harness = await mountOptions({ - ...BASE, - agent: 'pi', - sendSelection: true, - sessionId: host.record.sessionId, - client: first.client, - mutate - }) - return { - snapshot: () => harness.current().optionSnapshot, - capture: () => harness.current().sendSelection().selection, - demand: () => harness.current().optionSurface.demandModelCatalog?.(), - pick: (value) => harness.current().setStructuredOption('effort', value), - replace: async (fence, otherHost) => - harness.rerender({ fence, client: otherHost ? second.client : first.client }), - close: () => harness.unmount() - } - }, - async (work) => { - await act(async () => { - work() - await Promise.resolve() - await Promise.resolve() - }) - await settle() - } - ) -}) - it('refreshes saved planning intent from the same host status stamp without remounting', async () => { let interactionMode: 'default' | 'plan' = 'default' const client = optionsClient(async () => ({ diff --git a/mobile/src/session/native-chat/mobile-native-chat-diff.test.ts b/mobile/src/session/native-chat/mobile-native-chat-diff.test.ts deleted file mode 100644 index cb2936e8c51..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-diff.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { diffFromText } from '../../../../src/shared/native-chat/tools/native-chat-diff' - -describe('diffFromText', () => { - it('caps large diffs before creating render rows', () => { - const text = Array.from( - { length: 1_000 }, - (_unused, index) => `${index % 2 === 0 ? '+' : '-'}line-${index}` - ).join('\n') - const lines = diffFromText(text) - - expect(lines).toHaveLength(120) - expect(lines?.at(-1)).toEqual({ kind: 'meta', text: '… diff truncated …' }) - }) - - it('honors a smaller caller-owned aggregate row budget', () => { - const text = Array.from( - { length: 100 }, - (_unused, index) => `${index % 2 === 0 ? '+' : '-'}line-${index}` - ).join('\n') - - expect(diffFromText(text, 20)).toHaveLength(20) - }) -}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-lower-region-context.ts b/mobile/src/session/native-chat/mobile-native-chat-lower-region-context.ts index d0a7e8a5591..7f509992cf1 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-lower-region-context.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-lower-region-context.ts @@ -1,5 +1,4 @@ -import { createContext, useContext, useLayoutEffect, useRef } from 'react' -import type { View } from 'react-native' +import { createContext, useContext } from 'react' export type MobileNativeChatLowerRegion = { getViewport: () => unknown @@ -30,17 +29,3 @@ export const MobileNativeChatComposerPresenceContext = createContext(true) export function useMobileNativeChatLowerGeometry() { return useContext(MobileNativeChatLowerGeometryContext) } - -export function useMobileNativeChatComposerRegion(shown: boolean, focused: boolean) { - const groupRef = useRef(null) - const lowerRegion = useMobileNativeChatLowerRegion() - const menuWasShown = useRef(false) - useLayoutEffect(() => { - lowerRegion?.layoutChanged() - if (shown !== menuWasShown.current && focused) { - lowerRegion?.reveal(groupRef.current, shown ? 'menu' : 'edit') - } - menuWasShown.current = shown - }) - return groupRef -} diff --git a/mobile/src/session/native-chat/mobile-native-chat-merge.test.ts b/mobile/src/session/native-chat/mobile-native-chat-merge.test.ts deleted file mode 100644 index 3b922e822f0..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-merge.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { mergeNativeChatMessages } from '../../../../src/shared/native-chat/native-chat-merge' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' - -function msg(id: string, overrides: Partial = {}): NativeChatMessage { - return { - id, - role: 'assistant', - blocks: [{ type: 'text', text: id }], - timestamp: 0, - source: 'transcript', - ...overrides - } -} - -describe('mergeNativeChatMessages', () => { - it('appends new ids in arrival order', () => { - const merged = mergeNativeChatMessages([msg('a')], [msg('b'), msg('c')]) - expect(merged.map((m) => m.id)).toEqual(['a', 'b', 'c']) - }) - - it('replaces a re-emitted id in place without reordering', () => { - const merged = mergeNativeChatMessages( - [msg('a'), msg('b'), msg('c')], - [msg('b', { blocks: [{ type: 'text', text: 'updated' }] })] - ) - expect(merged.map((m) => m.id)).toEqual(['a', 'b', 'c']) - expect(merged[1]!.blocks).toEqual([{ type: 'text', text: 'updated' }]) - }) - - it('does not let a lower-priority source overwrite a higher one', () => { - const merged = mergeNativeChatMessages( - [msg('a', { source: 'transcript', blocks: [{ type: 'text', text: 'real' }] })], - [msg('a', { source: 'scrape', blocks: [{ type: 'text', text: 'scraped' }] })] - ) - expect(merged[0]!.blocks).toEqual([{ type: 'text', text: 'real' }]) - }) - - it('returns the existing array unchanged for an empty batch', () => { - const existing = [msg('a')] - expect(mergeNativeChatMessages(existing, [])).toBe(existing) - }) - - it('does not mutate the existing array', () => { - const existing = [msg('a')] - mergeNativeChatMessages(existing, [msg('b')]) - expect(existing.map((m) => m.id)).toEqual(['a']) - }) -}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-merger-oracle.test.ts b/mobile/src/session/native-chat/mobile-native-chat-merger-oracle.test.ts deleted file mode 100644 index d0f7b928f97..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-merger-oracle.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { - applyAppend, - createNativeChatMerger, - mergeNativeChatMessages, - replaceList -} from '../../../../src/shared/native-chat/native-chat-merge' - -function msg(id: string, overrides: Partial = {}): NativeChatMessage { - return { - id, - role: 'assistant', - blocks: [{ type: 'text', text: id }], - timestamp: 0, - source: 'transcript', - ...overrides - } -} - -// Compare each adversarial prefix with the pure merger so cached indexes cannot diverge from a full rebuild. -describe('mobile stateful merger — oracle vs pure merge', () => { - const base = [msg('a'), msg('b', { source: 'hook' })] - const batches: NativeChatMessage[][] = [ - [msg('c')], - [], - [msg('b', { source: 'transcript', blocks: [{ type: 'text', text: 'final' }] })], - [msg('b', { source: 'scrape' })], - [msg('a')], - [msg('d'), msg('e')] - ] - - it('matches the pure merge for every prefix', () => { - const merger = createNativeChatMerger() - replaceList(merger, base) - let pure = mergeNativeChatMessages(base, []) - expect(merger.list).toEqual(pure) - for (const batch of batches) { - const out = applyAppend(merger, batch) - pure = mergeNativeChatMessages(pure, batch) - expect(out).toEqual(pure) - } - }) - - it('keeps prior row identity on a pure tail append', () => { - const merger = createNativeChatMerger() - replaceList(merger, base) - const before = merger.list - const tail = msg('z') - const after = applyAppend(merger, [tail]) - expect(after).not.toBe(before) - expect(after[0]).toBe(before[0]) - expect(after[after.length - 1]).toBe(tail) - }) - - it('bounds live appends and rebuilds the cached indexes for the retained tail', () => { - const merger = createNativeChatMerger() - replaceList(merger, [msg('a'), msg('b'), msg('c')]) - - expect(applyAppend(merger, [msg('d'), msg('e')], 3).map((m) => m.id)).toEqual(['c', 'd', 'e']) - expect(merger.indexById.has('a')).toBe(false) - expect(merger.indexById.get('c')).toBe(0) - expect( - applyAppend(merger, [msg('d', { blocks: [{ type: 'text', text: 'updated' }] })], 3)[1] - ).toMatchObject({ id: 'd', blocks: [{ type: 'text', text: 'updated' }] }) - }) -}) diff --git a/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts index d7499d5314b..d33af3fd738 100644 --- a/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts +++ b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts @@ -1,6 +1,5 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport/rpc/rpc-operation' import type { RpcCompatibleReader } from '../../../transport/rpc/rpc-operation-contract' -import '../../../../../src/shared/source-control/listing/source-control-group-order' import { settingsMember, settingsField } from '../../../settings/mobile-settings-projection' // Missing reports let the caller tell an older host's absence from a reported value. diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx index 57f217b8611..5bd9a52d583 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.test.tsx @@ -165,50 +165,6 @@ describe('ToolRun', () => { }) }) - it('follows new work at the end of a live run, but holds still when the reader opens a row', () => { - const live = (blocks: NativeChatBlock[]) => - createElement(ToolRun, { - blocks, - activeTurnIsWorking: true, - trailing: true - }) - const first: NativeChatBlock[] = [ - { type: 'tool-call', name: 'Bash', input: { command: 'ls' }, state: 'completed' }, - { type: 'tool-result', output: 'a.ts' } - ] - act(() => { - renderer = create(live(first)) - }) - openRun(renderer!) - const box = () => renderer!.root.findAll((node) => String(node.type) === 'ScrollView')[0]! - act(() => { - box().props.onContentSizeChange() - }) - scrolls.toEnd.mockClear() - act(() => { - renderer!.root - .findAll((node) => String(node.type) === 'Pressable') - .findLast((node) => textIn(node).includes('ls'))! - .props.onPress() - }) - act(() => { - box().props.onContentSizeChange() - }) - expect(scrolls.toEnd).not.toHaveBeenCalled() - act(() => { - renderer!.update( - live([ - ...first, - { type: 'tool-call', name: 'Bash', input: { command: 'pwd' }, state: 'running' } - ]) - ) - }) - act(() => { - box().props.onContentSizeChange() - }) - expect(scrolls.toEnd).toHaveBeenCalledTimes(1) - }) - it('does not save a follow for a later row opening when new work left the height unchanged', () => { const live = (blocks: NativeChatBlock[]) => createElement(ToolRun, { diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.test.ts deleted file mode 100644 index 52ae2dd631a..00000000000 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppStateStatus } from 'react-native' - -const appState = vi.hoisted(() => ({ - current: 'active', - listeners: new Set<(state: AppStateStatus) => void>() -})) - -vi.mock('react-native', async () => { - const React = await import('react') - const Text = ({ children, ...props }: { children?: ReactNode }): unknown => - React.createElement('Text', props, children) - return { - AppState: { - get currentState() { - return appState.current - }, - addEventListener: (_event: string, listener: (state: AppStateStatus) => void) => { - appState.listeners.add(listener) - return { - remove: () => { - appState.listeners.delete(listener) - } - } - } - }, - ActivityIndicator: (props: Record) => - React.createElement('ActivityIndicator', props), - Pressable: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Pressable', props, children), - Text, - View: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('View', props, children), - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 } - } -}) -vi.mock('lucide-react-native', () => ({ ChevronRight: 'ChevronRight' })) - -import { MobileNativeChatTurnStatus } from './MobileNativeChatTurnStatus' -import { findAllByHostType } from '../../../test-support/react-test-renderer-host-nodes' - -const labels = (node: ReactTestInstance): string[] => - findAllByHostType(node, 'Text').map((text) => String(text.children.join(''))) - -let renderer: ReactTestRenderer | null = null - -beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-09-04T00:00:00Z')) - appState.current = 'active' - appState.listeners.clear() -}) - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - vi.restoreAllMocks() - vi.useRealTimers() -}) - -describe('MobileNativeChatTurnStatus', () => { - function changeAppState(state: AppStateStatus) { - act(() => { - appState.current = state - for (const listener of appState.listeners) { - listener(state) - } - }) - } - function render(props: { - startedAt: number | null - workedSeconds?: number | null - verdict?: 'interruption' | 'cancellation' - expanded?: boolean - onToggleExpanded?: () => void - }): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileNativeChatTurnStatus, props)) - }) - return renderer! - } - - it('stops clock callbacks in the background and catches up immediately on resume', () => { - const tree = render({ startedAt: Date.now() }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(labels(tree.root)).toEqual(['Working for 2s']) - - changeAppState('background') - const clockReads = vi.spyOn(Date, 'now') - act(() => { - vi.advanceTimersByTime(60_000) - }) - expect(clockReads).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - expect(labels(tree.root)).toEqual(['Working for 2s']) - - changeAppState('active') - expect(labels(tree.root)).toEqual(['Working for 1m 2s']) - expect(vi.getTimerCount()).toBe(1) - act(() => { - vi.advanceTimersByTime(1_000) - }) - expect(labels(tree.root)).toEqual(['Working for 1m 3s']) - }) - - it('keeps the original pre-stamp epoch through background and settlement transitions', () => { - const tree = render({ startedAt: null }) - act(() => { - vi.advanceTimersByTime(3_000) - }) - expect(labels(tree.root)).toEqual(['Working for 3s']) - changeAppState('background') - act(() => { - vi.advanceTimersByTime(10_000) - }) - act(() => - tree.update(createElement(MobileNativeChatTurnStatus, { startedAt: null, workedSeconds: 8 })) - ) - changeAppState('active') - expect(labels(tree.root)).toEqual(['Worked for 8s']) - expect(vi.getTimerCount()).toBe(0) - - act(() => tree.update(createElement(MobileNativeChatTurnStatus, { startedAt: null }))) - expect(labels(tree.root)).toEqual(['Working for 13s']) - expect(vi.getTimerCount()).toBe(1) - act(() => tree.unmount()) - expect(vi.getTimerCount()).toBe(0) - expect(appState.listeners.size).toBe(0) - }) - - it('creates no clock while initially backgrounded and uses a supplied start time on resume', () => { - appState.current = 'background' - const startedAt = Date.now() - 5_000 - const tree = render({ startedAt }) - expect(vi.getTimerCount()).toBe(0) - act(() => { - vi.advanceTimersByTime(15_000) - }) - changeAppState('active') - expect(labels(tree.root)).toEqual(['Working for 20s']) - expect(vi.getTimerCount()).toBe(1) - }) -}) diff --git a/mobile/src/session/native-chat/transcript/mobile-agent-message-renderer.test-fixture.ts b/mobile/src/session/native-chat/transcript/mobile-agent-message-renderer.test-fixture.ts index 301d7c57d18..abb586ea7d8 100644 --- a/mobile/src/session/native-chat/transcript/mobile-agent-message-renderer.test-fixture.ts +++ b/mobile/src/session/native-chat/transcript/mobile-agent-message-renderer.test-fixture.ts @@ -63,15 +63,11 @@ vi.mock('lucide-react-native', () => ({ Wrench: 'Wrench', Terminal: 'Terminal' })) -const proseRenders = vi.hoisted(() => ({ count: 0 })) -export function proseRenderCount() { - return proseRenders.count -} + vi.mock('../../../components/MobileMarkdown', async () => { const React = await import('react') return { MobileMarkdown: (props: ComponentProps) => { - proseRenders.count++ return React.createElement('MobileMarkdown', props) } } diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.test.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.test.ts new file mode 100644 index 00000000000..59938201fe1 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { + createNativeChatMerger, + replaceList +} from '../../../../../src/shared/native-chat/native-chat-merge' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { applyMobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame' + +function message(id: string): NativeChatMessage { + return { + id, + role: 'assistant', + blocks: [{ type: 'text', text: id }], + timestamp: 0, + source: 'transcript' + } +} + +describe('applyMobileNativeChatStreamFrame', () => { + it('replaces a partially overlapping replay that no longer extends the retained tail', () => { + const merger = createNativeChatMerger() + replaceList(merger, ['old-1', 'shared', 'old-tail'].map(message)) + + // Keep hasMore true so only the contiguity check can reject the interleaved row. + const replay = [message('shared'), message('compacted-summary'), message('old-tail')] + expect( + applyMobileNativeChatStreamFrame({ + merger, + frame: { type: 'snapshot', messages: replay, hasMore: true, beforeOffset: 9 }, + limit: 100, + replaceSnapshot: false + }) + ).toEqual({ + kind: 'messages', + messages: replay, + hasMore: true, + beforeOffset: 9, + windowReplaced: true + }) + }) + + it('replaces retained history when replay metadata says no earlier rows remain', () => { + const merger = createNativeChatMerger() + replaceList(merger, ['removed-1', 'removed-2', 'a', 'b'].map(message)) + + const replay = [message('a'), message('b')] + expect( + applyMobileNativeChatStreamFrame({ + merger, + frame: { type: 'snapshot', messages: replay, hasMore: false, beforeOffset: 0 }, + limit: 100, + replaceSnapshot: false + }) + ).toEqual({ + kind: 'messages', + messages: replay, + hasMore: false, + beforeOffset: 0, + windowReplaced: true + }) + }) +}) diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-turn-diff.test-fixture.tsx b/mobile/src/session/native-chat/transcript/mobile-native-chat-turn-diff.test-fixture.tsx deleted file mode 100644 index 31a7a6e29d1..00000000000 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-turn-diff.test-fixture.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import './mobile-agent-message-renderer.test-fixture' -import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import type { ReactTestInstance } from 'react-test-renderer' -import { vi } from 'vitest' -import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure' -import { MobileNativeChatRowContent } from './MobileNativeChatRowItemSource' -import { findAllByHostType } from '../../../test-support/react-test-renderer-host-nodes' - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} } -})) - -export const messages: NativeChatMessage[] = [ - { - id: 'u', - role: 'user', - source: 'transcript', - timestamp: 1, - blocks: [{ type: 'text', text: 'Fix the greeting' }] - }, - { - id: 'edit', - role: 'assistant', - source: 'transcript', - timestamp: 2, - blocks: [ - { - type: 'tool-call', - name: 'Bash', - state: 'completed', - input: { command: 'inspect-diagnostic' } - }, - { type: 'tool-result', output: 'diagnostic-output' }, - { - type: 'tool-call', - name: 'Edit', - state: 'completed', - input: { - file_path: '/repo/greeting.ts', - old_string: 'helloOld()', - new_string: 'helloNew()' - } - }, - { type: 'tool-result', output: 'The file /repo/greeting.ts has been updated successfully.' }, - { type: 'tool-call', name: 'Diff', input: { path: 'status.ts' } }, - { type: 'tool-result', output: '@@ -1 +1 @@\n-statusOld()\n+statusNew()' } - ] - }, - { - id: 'answer', - role: 'assistant', - source: 'transcript', - timestamp: 3, - blocks: [{ type: 'text', text: 'Updated the greeting.' }] - } -] -const settled = new Map([['u', { startedAt: 1, workedSeconds: 2 }]]) -export function Transcript({ - rows = messages, - working = false -}: { - rows?: NativeChatMessage[] - working?: boolean -}) { - const turns = useMobileNativeChatTurnDisclosure({ - messages: rows, - enabled: true, - isWorking: working, - settledTurns: working ? undefined : settled, - scopeKey: 'test' - }) - return ( - <> - {turns.listMessages.map((message, index) => ( - - ))} - - ) -} -export function textIn(node: ReactTestInstance): string[] { - return findAllByHostType(node, 'Text').map((text) => String(text.children.join(''))) -} diff --git a/mobile/src/session/native-chat/transcript/native-chat-tool-run-words.test.ts b/mobile/src/session/native-chat/transcript/native-chat-tool-run-words.test.ts deleted file mode 100644 index 3258cc79084..00000000000 --- a/mobile/src/session/native-chat/transcript/native-chat-tool-run-words.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { SupportedUiLocale } from '../../../../../src/shared/ui-locale' -import { - joinNativeChatToolRunClauses, - nativeChatToolRunSentence -} from '../../../../../src/shared/native-chat/tools/native-chat-tool-run-sentence' -import { getMobileUiLocale } from '../../../i18n/mobile-i18n' -import { nativeChatToolRunWords } from './native-chat-tool-run-words' - -vi.mock('../../../i18n/mobile-i18n', () => ({ - getMobileUiLocale: vi.fn(() => 'en') -})) - -const joiners = { - pair: (first: string, second: string) => `${first} | ${second}`, - list: (leading: readonly string[], last: string) => [...leading, last].join(' | ') -} - -function mobileWords(locale: SupportedUiLocale) { - vi.mocked(getMobileUiLocale).mockReturnValue(locale) - return { ...nativeChatToolRunWords((_key, fallback) => fallback), ...joiners } -} - -describe('mobile tool-run sentence continuations', () => { - it('keeps German noun capitalization through the sentence formatter', () => { - const words = mobileWords('de') - expect( - nativeChatToolRunSentence( - [ - { type: 'tool-call', name: 'read', input: {} }, - { type: 'tool-call', name: 'Bash', input: { command: 'orca snapshot --page p1' } } - ], - {}, - { - ...words, - clause: (category) => (category === 'browser' ? 'Browser verwendet' : 'Datei gelesen') - } - ) - ).toBe('Datei gelesen | Browser verwendet') - }) - - it('uses Turkish casing for both dotted and dotless I in later clauses', () => { - expect(joinNativeChatToolRunClauses(['Başladı', 'İnceledi', 'Isındı'], mobileWords('tr'))).toBe( - 'Başladı | inceledi | ısındı' - ) - }) -}) diff --git a/mobile/src/session/native-chat/transcript/native-chat-turn-draw-order-scaling.test.ts b/mobile/src/session/native-chat/transcript/native-chat-turn-draw-order-scaling.test.ts deleted file mode 100644 index 33e322c37ea..00000000000 --- a/mobile/src/session/native-chat/transcript/native-chat-turn-draw-order-scaling.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { expect, it } from 'vitest' -import { nativeChatTurnDrawOrder } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-grouping' -import { nativeChatTurnMembership } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-membership' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' - -it.each([10, 100])( - 'reads turn ownership linearly for %i queued openers and earlier-turn rows', - (count) => { - const messages = [ - { id: 'first', role: 'user' as const }, - ...Array.from({ length: count }, (_, index) => ({ - id: `queued-${index}`, - role: 'user' as const - })), - ...Array.from({ length: count }, (_, index) => ({ - id: `tail-${index}`, - role: 'assistant' as const - })), - ...Array.from({ length: count }, (_, index) => ({ - id: `answer-${index}`, - role: 'assistant' as const - })) - ] - const keys = [ - 'first', - ...Array.from({ length: count }, (_, index) => `queued-${index}`), - ...Array.from({ length: count }, () => 'first'), - ...Array.from({ length: count }, (_, index) => `queued-${index}`) - ] - const openers = new Set(keys.slice(0, count + 1)) - let reads = 0 - keys.forEach((key, index) => { - Object.defineProperty(keys, index, { - get: () => { - reads += 1 - return key - } - }) - }) - const order = nativeChatTurnDrawOrder(messages, keys, openers) - const visits = reads - expect(order?.map((index) => messages[index]?.id)).toEqual([ - 'first', - ...Array.from({ length: count }, (_, index) => `tail-${index}`), - ...Array.from({ length: count }, (_, index) => [`queued-${index}`, `answer-${index}`]).flat() - ]) - const journalItems: AgentJournalRenderItem[] = [] - const append = (itemId: string, body: AgentJournalItemBody, turnItemId: string) => { - const sequence = journalItems.length + 1 - journalItems.push({ - itemId, - body, - revision: 0, - sequence, - observedAt: sequence, - turnScope: { kind: 'turn', turnItemId } - }) - } - append('first', { kind: 'message', role: 'user', blocks: [] }, 'turn-first') - append( - 'turn-first', - { kind: 'turn', turnId: 'first', state: 'completed', userItemId: 'first' }, - 'turn-first' - ) - for (let index = 0; index < count; index += 1) { - append(`queued-${index}`, { kind: 'message', role: 'user', blocks: [] }, `turn-${index}`) - } - for (let index = 0; index < count; index += 1) { - append(`tail-${index}`, { kind: 'message', role: 'assistant', blocks: [] }, 'turn-first') - } - for (let index = 0; index < count; index += 1) { - append( - `turn-${index}`, - { kind: 'turn', turnId: `t${index}`, state: 'completed', userItemId: `queued-${index}` }, - `turn-${index}` - ) - append(`answer-${index}`, { kind: 'message', role: 'assistant', blocks: [] }, `turn-${index}`) - } - const membership = nativeChatTurnMembership(messages, { items: journalItems, submissions: [] }) - expect(membership.turnKeys).toEqual(keys) - expect(membership.drawOrder).toEqual(order) - expect(visits).toBeLessThanOrEqual(messages.length * 4) - } -) diff --git a/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.test.tsx b/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.test.tsx deleted file mode 100644 index 5e024daf652..00000000000 --- a/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalRenderItem, - AgentJournalSubmission, - AgentJournalTurnLifecycle -} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' -import { agentJournalTurnBody } from '../../../../../src/shared/agent-session/lifecycle/agent-session-turn-record' -import { useMobileStructuredAgentTurnTiming } from './use-mobile-structured-agent-turn-timing' - -// Skew the host clock by an hour so unconverted timestamp leakage is obvious. -const HOST_START = 3_600_000_000 -const CLIENT_NOW = 12_345_000 - -function user(itemId: string, sequence: number): AgentJournalRenderItem { - return { - itemId, - revision: 0, - sequence, - observedAt: HOST_START + sequence, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: itemId }] } - } -} - -function lifecycle( - turnId: string, - sequence: number, - turn: Omit, - observedAt: number -): AgentJournalRenderItem { - return { - itemId: `lifecycle-${turnId}`, - revision: 1, - sequence, - observedAt, - body: agentJournalTurnBody({ turnId, ...turn }) - } -} - -type Timing = ReturnType -const NO_SUBMISSIONS: readonly AgentJournalSubmission[] = [] - -describe('useMobileStructuredAgentTurnTiming', () => { - let renderer: ReactTestRenderer | null = null - let timing: Timing | null = null - - function Harness({ - items, - submissions = NO_SUBMISSIONS, - turnId, - hostClock - }: { - items: readonly AgentJournalRenderItem[] - submissions?: readonly AgentJournalSubmission[] - turnId: string | null - hostClock?: { hostNow: number; receivedAt: number } - }): null { - timing = useMobileStructuredAgentTurnTiming({ items, submissions, hostClock }, turnId) - return null - } - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - timing = null - vi.useRealTimers() - }) - - it('leaves the anchor null when an older host records no start', () => { - vi.useFakeTimers() - vi.setSystemTime(CLIENT_NOW) - const items = [user('u1', 1), lifecycle('t1', 2, { state: 'running' }, HOST_START)] - act(() => { - renderer = create(createElement(Harness, { items, turnId: 't1' })) - }) - expect(timing?.workingStartedAt).toBeNull() - expect(timing?.settledTurns.size).toBe(0) - }) -}) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts b/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts index 8865ab41830..d8ad6f990d2 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-markdown-links.ts @@ -21,7 +21,7 @@ import { type MobileMarkdownLinks } from '../../components/mobile-markdown-links-context' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import { isMobileMethodUnavailableError } from '../../transport/rpc/mobile-method-unavailable' import { isFilePathCodeSpan } from '../../components/markdown-file-path-detection' import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' @@ -42,7 +42,7 @@ const chatPathsExistRead = bindDeferredRpcOperation( /** Paths in a chat's text, checked in batches against the chat's workspace on its host. */ export function createMobileNativeChatFileLinkExistence( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, worktreePath: string ): NativeChatFileLinkExistence { diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts b/mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts index daa4e74a737..084b090f152 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts @@ -5,19 +5,13 @@ import { useMobileNativeChatTerminalStream } from './use-mobile-native-chat-term describe('useMobileNativeChatTerminalStream', () => { let renderer: ReactTestRenderer | null = null - let harnessRenderCount = 0 const subscriptionsRef = { current: new Map void>() } const subscribingRef = { current: new Set() } const leaseOnlyRef = { current: new Set() } const webReadyRef = { current: new Set(['terminal-1']) } - let subscribeOpensLeaseOnly = false const registerSubscription = (handle: string): boolean => { subscriptionsRef.current.set(handle, () => {}) - if (subscribeOpensLeaseOnly) { - leaseOnlyRef.current.add(handle) - } else { - leaseOnlyRef.current.delete(handle) - } + leaseOnlyRef.current.delete(handle) return true } const subscribe = vi.fn(registerSubscription) @@ -25,7 +19,6 @@ describe('useMobileNativeChatTerminalStream', () => { subscriptionsRef.current.delete(handle) leaseOnlyRef.current.delete(handle) }) - const notifyWebReadyRef = { current: (_handle: string, _wasAlreadyReady: boolean): void => {} } const notifyListedHandlesRef = { current: (_liveHandles: ReadonlySet): void => {} } const hasTabsRecoveryNeedRef = { current: (): boolean => false } @@ -33,9 +26,7 @@ describe('useMobileNativeChatTerminalStream', () => { subscriptionsRef.current = new Map([['terminal-1', () => {}]]) subscribingRef.current = new Set() leaseOnlyRef.current = new Set() - subscribeOpensLeaseOnly = false webReadyRef.current = new Set(['terminal-1']) - harnessRenderCount = 0 subscribe.mockClear() unsubscribe.mockClear() }) @@ -56,7 +47,6 @@ describe('useMobileNativeChatTerminalStream', () => { leaseReady?: boolean streamRevision?: number }): null { - harnessRenderCount += 1 const stream = useMobileNativeChatTerminalStream({ showNativeChat, activeHandle, @@ -70,7 +60,6 @@ describe('useMobileNativeChatTerminalStream', () => { subscribe, unsubscribe }) - notifyWebReadyRef.current = stream.notifyWebReady notifyListedHandlesRef.current = stream.notifyListedHandles hasTabsRecoveryNeedRef.current = stream.hasTabsRecoveryNeed return null @@ -95,244 +84,6 @@ describe('useMobileNativeChatTerminalStream', () => { }) } - // A synchronous tab switch still sees old chat coverage and opens the incoming terminal as lease-only. - function handOffToTerminalTwo(): void { - subscribeOpensLeaseOnly = true - subscribe('terminal-2') - subscribeOpensLeaseOnly = false - subscribe.mockClear() - unsubscribe.mockClear() - } - - it('trades a lease-only stream for output when a chat tab hands off to a terminal tab', async () => { - webReadyRef.current.add('terminal-2') - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - handOffToTerminalTwo() - - await act(async () => { - renderer?.update( - createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' }) - ) - }) - - expect(unsubscribe).toHaveBeenCalledWith('terminal-2') - expect(subscribe).toHaveBeenCalledWith('terminal-2') - expect(leaseOnlyRef.current.has('terminal-2')).toBe(false) - }) - - it('repairs a lease-only stream once its WebView reports ready', async () => { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - handOffToTerminalTwo() - await act(async () => { - renderer?.update( - createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' }) - ) - }) - - // A cold WebView must wait; its normal ready path skips already-live lease subscriptions. - expect(subscribe).not.toHaveBeenCalled() - - await act(async () => { - webReadyRef.current.add('terminal-2') - notifyWebReadyRef.current('terminal-2', false) - }) - - expect(unsubscribe).toHaveBeenCalledWith('terminal-2') - expect(subscribe).toHaveBeenCalledWith('terminal-2') - }) - - it.each([true, false])( - 'stops rearming a handle whose stream never comes back (covered: %s, #10681)', - async (showNativeChat) => { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat })) - }) - subscribe.mockClear() - // Dead PTYs answer subscribed/end repeatedly; rearm must stop rather than loop through host waits. - for (let revision = 1; revision <= 6; revision += 1) { - subscriptionsRef.current.delete('terminal-1') - await act(async () => { - renderer?.update( - createElement(Harness, { - showNativeChat, - leaseReady: false, - streamRevision: revision - }) - ) - }) - } - - expect(subscribe.mock.calls.length).toBeLessThanOrEqual(3) - } - ) - - it('does not charge the rearm budget for a subscribe its own gates turned away', async () => { - try { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - subscribe.mockClear() - // Locally rejected subscribes never reached the host and must not spend real attempts. - subscribe.mockImplementation(() => false) - for (let revision = 1; revision <= 5; revision += 1) { - subscriptionsRef.current.delete('terminal-1') - await act(async () => { - renderer?.update( - createElement(Harness, { - showNativeChat: true, - leaseReady: false, - streamRevision: revision - }) - ) - }) - } - - expect(subscribe).toHaveBeenCalledTimes(5) - } finally { - subscribe.mockImplementation(registerSubscription) - } - }) - - it('charges the rearm budget for a subscribe the bridge refused before returning', async () => { - try { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: false })) - }) - subscribe.mockClear() - // A synchronous refusal ends the stream inside subscribe, so no ref ever shows it was sent. - subscribe.mockImplementation(() => true) - for (let revision = 1; revision <= 5; revision += 1) { - subscriptionsRef.current.delete('terminal-1') - await act(async () => { - renderer?.update( - createElement(Harness, { - showNativeChat: false, - leaseReady: false, - streamRevision: revision - }) - ) - }) - } - - expect(subscribe).toHaveBeenCalledTimes(3) - } finally { - subscribe.mockImplementation(registerSubscription) - } - }) - - it.each([true, false])( - 'refills the rearm budget when terminal.list reports the handle again (covered: %s, #10681)', - async (showNativeChat) => { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat })) - }) - for (let revision = 1; revision <= 5; revision += 1) { - subscriptionsRef.current.delete('terminal-1') - await act(async () => { - renderer?.update( - createElement(Harness, { - showNativeChat, - leaseReady: false, - streamRevision: revision - }) - ) - }) - } - subscribe.mockClear() - await act(async () => { - renderer?.update( - createElement(Harness, { showNativeChat, leaseReady: false, streamRevision: 6 }) - ) - }) - expect(subscribe).not.toHaveBeenCalled() - - // Still-listed dead handles must not refill on every inventory refresh. - await act(async () => { - notifyListedHandlesRef.current(new Set(['terminal-1'])) - notifyListedHandlesRef.current(new Set(['terminal-1'])) - }) - expect(subscribe).not.toHaveBeenCalled() - - await act(async () => { - notifyListedHandlesRef.current(new Set()) - notifyListedHandlesRef.current(new Set(['terminal-1'])) - }) - - expect(subscribe).toHaveBeenCalledWith('terminal-1') - } - ) - - it('does not let a dead PTY buy a new budget with its own `subscribed` ack', async () => { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - subscribe.mockClear() - // Subscribed is only half a dead-PTY reply; clearing attempts there would refill the loop forever. - for (let revision = 1; revision <= 6; revision += 1) { - await playDeadPtyRoundTrip(revision) - } - - expect(subscribe.mock.calls.length).toBeLessThanOrEqual(3) - }) - - it('refills the budget for a rearmed stream that outlives the teardown window', async () => { - vi.useFakeTimers() - try { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - subscribe.mockClear() - for (let revision = 1; revision <= 3; revision += 1) { - await playDeadPtyRoundTrip(revision) - } - expect(subscribe).toHaveBeenCalledTimes(3) - - subscribe.mockClear() - subscriptionsRef.current.set('terminal-1', () => {}) - await act(async () => { - renderer?.update( - createElement(Harness, { showNativeChat: true, leaseReady: true, streamRevision: 4 }) - ) - }) - await act(async () => { - vi.advanceTimersByTime(5_000) - }) - await playDeadPtyRoundTrip(5) - - expect(subscribe).toHaveBeenCalledWith('terminal-1') - } finally { - vi.useRealTimers() - } - }) - - it('keeps an absence marker observed before the budget ran out', async () => { - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - for (let revision = 1; revision <= 2; revision += 1) { - await playDeadPtyRoundTrip(revision) - } - // Preserve absence markers until exhaustion actually consumes them; early consumption can permanently lock a still-listed handle. - await act(async () => { - notifyListedHandlesRef.current(new Set()) - notifyListedHandlesRef.current(new Set(['terminal-1'])) - }) - await playDeadPtyRoundTrip(3) - subscribe.mockClear() - await playDeadPtyRoundTrip(4) - expect(subscribe).not.toHaveBeenCalled() - - await act(async () => { - notifyListedHandlesRef.current(new Set(['terminal-1'])) - }) - - expect(subscribe).toHaveBeenCalledWith('terminal-1') - }) - it('keeps asking until a tab snapshot replaces the exhausted handle', async () => { await act(async () => { renderer = create(createElement(Harness, { showNativeChat: true })) @@ -364,25 +115,4 @@ describe('useMobileNativeChatTerminalStream', () => { }) expect(hasTabsRecoveryNeedRef.current()).toBe(false) }) - - it('resumes a cold-start lease-only stream when WebView readiness arrives late', async () => { - webReadyRef.current.clear() - await act(async () => { - renderer = create(createElement(Harness, { showNativeChat: true })) - }) - await act(async () => { - renderer?.update(createElement(Harness, { showNativeChat: false })) - }) - - expect(unsubscribe).toHaveBeenCalledOnce() - expect(subscribe).toHaveBeenCalledOnce() - - webReadyRef.current.add('terminal-1') - await act(async () => { - notifyWebReadyRef.current('terminal-1', false) - }) - - expect(unsubscribe).toHaveBeenNthCalledWith(2, 'terminal-1') - expect(subscribe).toHaveBeenNthCalledWith(2, 'terminal-1') - }) }) diff --git a/mobile/src/session/tabs/mobile-session-tab-read-operations.ts b/mobile/src/session/tabs/mobile-session-tab-read-operations.ts index fe0c2f30db2..c1a9bb6ffc8 100644 --- a/mobile/src/session/tabs/mobile-session-tab-read-operations.ts +++ b/mobile/src/session/tabs/mobile-session-tab-read-operations.ts @@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' import '../../terminal/terminal-reply-schema' import { sessionForwardedReplySchema } from '../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../agent-launch/mobile-agent-detection-reply-schema' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../terminal/session/mobile-session-terminal-reply-schema' -import '../../worktree/session-worktree-record-reply-schema' -import '../native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../../files/workspace-file-paths-reply-schema' // Leave replies raw until the controller’s generation, barrier and application-revision guards pass. export const sessionTabsListRead = bindDeferredRpcOperation( diff --git a/mobile/src/session/tabs/mobile-session-tab-write-operations.ts b/mobile/src/session/tabs/mobile-session-tab-write-operations.ts index a450d1f6a6e..856c3323fa8 100644 --- a/mobile/src/session/tabs/mobile-session-tab-write-operations.ts +++ b/mobile/src/session/tabs/mobile-session-tab-write-operations.ts @@ -1,7 +1,5 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../worktree/session-worktree-record-reply-schema' import '../../terminal/terminal-reply-schema' import { sessionCreatedTerminalTabSchema } from '../../terminal/session/mobile-session-terminal-reply-schema' import { sessionTabCloseReplySchema } from './mobile-session-tab-write-reply-schema' diff --git a/mobile/src/session/tabs/mobile-session-tab-write-reply-schema.ts b/mobile/src/session/tabs/mobile-session-tab-write-reply-schema.ts index 245fe3f5f02..009b0d95835 100644 --- a/mobile/src/session/tabs/mobile-session-tab-write-reply-schema.ts +++ b/mobile/src/session/tabs/mobile-session-tab-write-reply-schema.ts @@ -1,5 +1,4 @@ import * as z from 'zod' -import '../../../../src/shared/zod-salvage' // Bare legacy success and delegated closes do not prove permanent retirement. export const sessionTabCloseReplySchema = z diff --git a/mobile/src/session/tabs/use-mobile-session-close-actions.test.tsx b/mobile/src/session/tabs/use-mobile-session-close-actions.test.tsx index a9077c5e1e9..f7c61750b6f 100644 --- a/mobile/src/session/tabs/use-mobile-session-close-actions.test.tsx +++ b/mobile/src/session/tabs/use-mobile-session-close-actions.test.tsx @@ -14,7 +14,14 @@ import { readMobileNativeChatDraftInputs, updateMobileNativeChatDraftInputs } from '../native-chat/composer/mobile-native-chat-draft-inputs' -import { resetMobileNativeChatDraftStoreForTests } from '../native-chat/composer/mobile-native-chat-draft-store' +import { closeMobileNativeChatTabDraft } from '../native-chat/composer/mobile-native-chat-draft-store' + +import { loadMobileNativeChatDrafts } from '../native-chat/composer/mobile-native-chat-draft-persistence' + +vi.mock('@react-native-async-storage/async-storage', async () => { + const { createInMemoryAsyncStorage } = await import('../../test-support/in-memory-async-storage') + return { default: createInMemoryAsyncStorage() } +}) const initial: Terminal[] = ['a', 'b', 'c'].map((handle) => ({ handle, @@ -24,10 +31,16 @@ const initial: Terminal[] = ['a', 'b', 'c'].map((handle) => ({ describe('legacy terminal close acknowledgments', () => { let renderer: ReactTestRenderer | null = null - afterEach(() => { + let queries: ReturnType | null = null + afterEach(async () => { act(() => renderer?.unmount()) renderer = null - resetMobileNativeChatDraftStoreForTests() + await queries?.end() + queries = null + await loadMobileNativeChatDrafts('host', 'workspace') + closeMobileNativeChatTabDraft('queued-editor') + closeMobileNativeChatTabDraft('host\0workspace\0closed') + await loadMobileNativeChatDrafts('host', 'workspace') }) async function mount(renameTarget: Terminal | null = null) { @@ -127,8 +140,9 @@ describe('legacy terminal close acknowledgments', () => { } return null } + queries = documentQueryClient() await act(async () => { - renderer = create(documentQueryClient().wrap(createElement(Harness))) + renderer = create(queries!.wrap(createElement(Harness))) }) return { read() { diff --git a/mobile/src/session/use-missing-worktree-bounce.test.ts b/mobile/src/session/use-missing-worktree-bounce.test.ts index a697bbfb905..49600fd89d8 100644 --- a/mobile/src/session/use-missing-worktree-bounce.test.ts +++ b/mobile/src/session/use-missing-worktree-bounce.test.ts @@ -1,12 +1,6 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { WorktreeShowResolution } from '../worktree/worktree-show-resolution' +import { describe, expect, it } from 'vitest' import { isSyntheticWorkspaceRoute } from './synthetic-workspace-route' -import { - shouldBounceMissingWorktree, - useMissingWorktreeBounce -} from './use-missing-worktree-bounce' +import { shouldBounceMissingWorktree } from './use-missing-worktree-bounce' describe('shouldBounceMissingWorktree', () => { it('bounces only a host-proven missing worktree', () => { @@ -21,60 +15,3 @@ describe('shouldBounceMissingWorktree', () => { expect(shouldBounceMissingWorktree('global-floating-terminal', 'missing')).toBe(false) }) }) - -describe('useMissingWorktreeBounce', () => { - let renderer: ReactTestRenderer | null = null - const bounce = vi.fn() - - beforeEach(() => { - bounce.mockReset() - renderer = null - }) - - function Harness(props: { worktreeId: string; resolution: WorktreeShowResolution }): null { - useMissingWorktreeBounce({ - hostId: 'host-1', - worktreeId: props.worktreeId, - resolution: props.resolution, - bounce - }) - return null - } - - function render(worktreeId: string, resolution: WorktreeShowResolution): void { - act(() => { - const element = createElement(Harness, { worktreeId, resolution }) - if (renderer) { - renderer.update(element) - } else { - renderer = create(element) - } - }) - } - - it('bounces exactly once per worktree even across re-renders', () => { - render('repo::wt', 'unknown') - expect(bounce).not.toHaveBeenCalled() - - render('repo::wt', 'missing') - expect(bounce).toHaveBeenCalledExactlyOnceWith('host-1') - - // Why: navigation lands after the render, so the pre-unmount renders must not re-fire. - render('repo::wt', 'missing') - render('repo::wt', 'unknown') - render('repo::wt', 'missing') - expect(bounce).toHaveBeenCalledTimes(1) - act(() => renderer?.unmount()) - }) - - it('re-arms for a different worktree on the reused screen', () => { - render('repo::wt-1', 'missing') - expect(bounce).toHaveBeenCalledTimes(1) - - render('repo::wt-2', 'unknown') - expect(bounce).toHaveBeenCalledTimes(1) - render('repo::wt-2', 'missing') - expect(bounce).toHaveBeenCalledTimes(2) - act(() => renderer?.unmount()) - }) -}) diff --git a/mobile/src/session/use-mobile-default-session-view-preference.test.ts b/mobile/src/session/use-mobile-default-session-view-preference.test.ts index 084164b6a40..53891f46444 100644 --- a/mobile/src/session/use-mobile-default-session-view-preference.test.ts +++ b/mobile/src/session/use-mobile-default-session-view-preference.test.ts @@ -68,52 +68,6 @@ describe('useMobileDefaultSessionViewPreference', () => { expect(saveDefaultSessionView).toHaveBeenCalledWith('chat') }) - it('submits every change immediately so shared persistence preserves event order', async () => { - const firstSave = deferred() - vi.mocked(saveDefaultSessionView) - .mockImplementationOnce(() => firstSave.promise) - .mockResolvedValue(undefined) - await mount() - - act(() => preference?.setDefaultView('chat')) - await act(async () => { - await Promise.resolve() - }) - act(() => preference?.setDefaultView('terminal')) - act(() => preference?.setDefaultView('chat')) - await act(async () => { - await Promise.resolve() - }) - expect(saveDefaultSessionView).toHaveBeenCalledTimes(3) - expect(saveDefaultSessionView).toHaveBeenNthCalledWith(2, 'terminal') - expect(saveDefaultSessionView).toHaveBeenNthCalledWith(3, 'chat') - - await act(async () => { - firstSave.resolve() - await firstSave.promise - await Promise.resolve() - }) - expect(saveDefaultSessionView).toHaveBeenCalledTimes(3) - }) - - it('reloads the persisted value when the latest write fails', async () => { - vi.mocked(loadDefaultSessionView) - .mockResolvedValueOnce('terminal') - .mockResolvedValueOnce('terminal') - vi.mocked(saveDefaultSessionView).mockRejectedValue(new Error('storage unavailable')) - await mount() - - await act(async () => { - preference?.setDefaultView('chat') - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() - }) - - expect(preference?.defaultView).toBe('terminal') - expect(loadDefaultSessionView).toHaveBeenCalledTimes(2) - }) - it('does not let an older failed write roll back a newer choice', async () => { const recoveryLoad = deferred() vi.mocked(loadDefaultSessionView) @@ -140,27 +94,4 @@ describe('useMobileDefaultSessionViewPreference', () => { expect(preference?.defaultView).toBe('terminal') expect(saveDefaultSessionView).toHaveBeenNthCalledWith(2, 'terminal') }) - - it('submits the latest write before the Settings route unmounts', async () => { - const firstSave = deferred() - vi.mocked(saveDefaultSessionView) - .mockImplementationOnce(() => firstSave.promise) - .mockResolvedValueOnce(undefined) - await mount() - - act(() => preference?.setDefaultView('chat')) - await act(async () => { - await Promise.resolve() - }) - act(() => preference?.setDefaultView('terminal')) - expect(saveDefaultSessionView).toHaveBeenNthCalledWith(2, 'terminal') - act(() => renderer?.unmount()) - renderer = null - - await act(async () => { - firstSave.resolve() - await firstSave.promise - await Promise.resolve() - }) - }) }) diff --git a/mobile/src/session/use-mobile-session-lifecycle.ts b/mobile/src/session/use-mobile-session-lifecycle.ts index 30dd15eb573..0db31f4d6b9 100644 --- a/mobile/src/session/use-mobile-session-lifecycle.ts +++ b/mobile/src/session/use-mobile-session-lifecycle.ts @@ -4,7 +4,7 @@ import { settleSessionPreferenceRead } from './session-preference-read' import { useEffect, useRef, useCallback, useState } from 'react' import { AppState, type AppStateStatus, Platform } from 'react-native' import { useFocusEffect } from 'expo-router' -import { loadHosts } from '../transport/hosts/host-store' +import { loadHosts } from '../host-catalog/host-store' import { loadTerminalAccessoryLayout, saveTerminalSmartRail diff --git a/mobile/src/session/use-mobile-session-view-mode.test.ts b/mobile/src/session/use-mobile-session-view-mode.test.ts index ad3edfa01bb..a0bb2a5fc72 100644 --- a/mobile/src/session/use-mobile-session-view-mode.test.ts +++ b/mobile/src/session/use-mobile-session-view-mode.test.ts @@ -146,19 +146,6 @@ describe('useMobileSessionViewMode', () => { expect(controller?.ready).toBe(true) }) - it('toggles from the effective view and persists the override', async () => { - await mount({ defaultView: 'chat' }) - - await act(async () => { - controller?.toggleTabChatView('t1') - await Promise.resolve() - }) - - expect(updateSessionViewOverride).toHaveBeenLastCalledWith('h', 'w', 't1', 'terminal') - expect(controller?.isTabChatView('t1')).toBe(false) - expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(1) - }) - it('toggles a terminal-default tab into chat', async () => { await mount({ defaultView: 'terminal' }) @@ -293,108 +280,6 @@ describe('useMobileSessionViewMode', () => { }) }) - it('submits rapid mutations in event order', async () => { - await mount({ defaultView: 'terminal' }) - act(() => controller?.toggleTabChatView('t1')) - act(() => controller?.toggleTabChatView('t2')) - - expect(updateSessionViewOverride).toHaveBeenNthCalledWith(1, 'h', 'w', 't1', 'chat') - expect(updateSessionViewOverride).toHaveBeenNthCalledWith(2, 'h', 'w', 't2', 'chat') - }) - - it('reconciles the latest optimistic override when persistence fails', async () => { - vi.mocked(updateSessionViewOverride).mockRejectedValue(new Error('storage unavailable')) - vi.mocked(readSessionViewOverridesPreference) - .mockResolvedValueOnce({ - overrides: new Map([['t1', 'terminal']]), - loaded: true - }) - .mockResolvedValueOnce({ - overrides: new Map([['t1', 'terminal']]), - loaded: true - }) - await mount({ - defaultView: 'terminal', - overrides: new Map([['t1', 'terminal']]) - }) - - await act(async () => { - controller?.toggleTabChatView('t1') - await Promise.resolve() - await Promise.resolve() - }) - - expect(controller?.isTabChatView('t1')).toBe(false) - expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(2) - }) - - it('does not let an older failed override roll back a newer choice', async () => { - const recoveryLoad = deferred>() - vi.mocked(updateSessionViewOverride) - .mockRejectedValueOnce(new Error('storage unavailable')) - .mockResolvedValueOnce(undefined) - await mount({ defaultView: 'terminal' }) - vi.mocked(readSessionViewOverridesPreference).mockReturnValueOnce( - recoveryLoad.promise.then((overrides) => ({ overrides, loaded: true })) - ) - - await act(async () => { - controller?.toggleTabChatView('t1') - await Promise.resolve() - }) - act(() => controller?.toggleTabChatView('t1')) - - await act(async () => { - recoveryLoad.resolve(new Map([['t1', 'chat']])) - await recoveryLoad.promise - await Promise.resolve() - }) - - expect(controller?.isTabChatView('t1')).toBe(false) - expect(updateSessionViewOverride).toHaveBeenNthCalledWith(2, 'h', 'w', 't1', 'terminal') - }) - - it('fails closed when both an override write and its recovery read fail', async () => { - vi.mocked(loadDefaultSessionView).mockResolvedValue('chat') - vi.mocked(updateSessionViewOverride).mockRejectedValue(new Error('storage unavailable')) - vi.mocked(readSessionViewOverridesPreference) - .mockResolvedValueOnce({ - overrides: new Map([['t1', 'terminal']]), - loaded: true - }) - .mockResolvedValueOnce({ overrides: new Map(), loaded: false }) - await mount({ - defaultView: 'chat', - overrides: new Map([['t1', 'terminal']]) - }) - - await act(async () => { - controller?.toggleTabChatView('t1') - await Promise.resolve() - await Promise.resolve() - }) - - expect(controller?.isTabChatView('t1')).toBe(false) - expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(2) - }) - - it('does not reload a failed override after the route unmounts', async () => { - const failedWrite = deferred() - vi.mocked(updateSessionViewOverride).mockReturnValue(failedWrite.promise) - await mount({ defaultView: 'terminal' }) - - act(() => controller?.toggleTabChatView('t1')) - act(() => renderer?.unmount()) - renderer = null - await act(async () => { - failedWrite.reject(new Error('storage unavailable')) - await Promise.resolve() - await Promise.resolve() - }) - - expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(1) - }) - it('fails closed to terminal when overrides cannot be read under a chat default', async () => { vi.mocked(loadDefaultSessionView).mockResolvedValue('chat') vi.mocked(readSessionViewOverridesPreference).mockResolvedValue({ diff --git a/mobile/src/settings/notification-display-test.tsx b/mobile/src/settings/notification-display-test.tsx index 51280f27047..ecb737e0e5c 100644 --- a/mobile/src/settings/notification-display-test.tsx +++ b/mobile/src/settings/notification-display-test.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react' import { ListRow } from '../components/list/ListGroup' import { useAllHostClients } from '../transport/connection/use-all-host-clients' -import { loadHostCatalog } from '../transport/hosts/host-store' +import { loadHostCatalog } from '../host-catalog/host-store' import { pushDeliveryTest } from '../notifications/mobile-push-delivery-test-operations' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { useMobileTranslation } from '../i18n/use-mobile-translation' diff --git a/mobile/src/settings/pending-credential-cleanup-card.tsx b/mobile/src/settings/pending-credential-cleanup-card.tsx index af0a91ce081..0ef2d84df8e 100644 --- a/mobile/src/settings/pending-credential-cleanup-card.tsx +++ b/mobile/src/settings/pending-credential-cleanup-card.tsx @@ -9,8 +9,8 @@ import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { loadPendingHostCredentialCleanup, subscribePendingHostCredentialCleanup -} from '../transport/hosts/host-credential-cleanup' -import { retryPendingHostCredentialCleanup } from '../transport/hosts/host-store' +} from '../host-credentials/host-credential-cleanup' +import { retryPendingHostCredentialCleanup } from '../host-catalog/host-store' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { SettingsSection } from './settings-screen-frame' diff --git a/mobile/src/source-control/folder/MobileFolderSourceControlPanel.test.tsx b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.test.tsx deleted file mode 100644 index 102d52bad8b..00000000000 --- a/mobile/src/source-control/folder/MobileFolderSourceControlPanel.test.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { FolderListRow } from './mobile-folder-attached-worktrees' - -const seen = vi.hoisted(() => { - const state: { covered: boolean; membersObserving: boolean[]; rowsSubscribed: boolean[] } = { - covered: false, - membersObserving: [], - rowsSubscribed: [] - } - return state -}) -vi.mock('react-native', () => ({ ScrollView: 'ScrollView', View: 'View' })) -vi.mock('lucide-react-native', () => ({ GitBranch: 'GitBranch' })) -vi.mock('expo-router', () => ({ useFocusEffect: () => {} })) -vi.mock('react-native-safe-area-context', () => ({ - SafeAreaView: 'SafeAreaView', - useSafeAreaInsets: () => ({ bottom: 0 }) -})) -vi.mock('../../components/MobileStateView', () => ({ - MobileLoadErrorState: 'MobileLoadErrorState', - MobileOfflineState: 'MobileOfflineState', - MobileStateView: 'MobileStateView' -})) -vi.mock('../../transport/connection/connection-retry-action', () => ({ - connectionRetryAction: () => () => {} -})) -vi.mock('../../transport/connection/host-client-hooks', () => ({ - useForceReconnect: () => () => {} -})) -vi.mock('../../components/bottom-drawer/BottomDrawer', () => ({ - OptionPager: ({ main }: { main: ReactNode }) => main, - useOptionPager: () => ({ page: null, open: () => {}, close: () => {} }) -})) -vi.mock('../../components/list/ListGroup', () => ({ ListGroup: 'ListGroup' })) -vi.mock('../../i18n/use-mobile-translation', () => ({ - useMobileTranslation: () => (_key: string, fallback: string) => fallback -})) -vi.mock('../../navigation/use-back-claim', () => ({ useBackClaim: () => {} })) -vi.mock('../../navigation/workspace-route-handoff', () => ({ - useWorkspaceRouteHandoff: () => ({ back: () => {} }) -})) -vi.mock('../../navigation/workspace-route', () => ({ - WorkspaceExecutionScope: 'WorkspaceExecutionScope' -})) -vi.mock('../../theme/mobile-theme', () => ({ colors: {}, spacing: { lg: 16 } })) -vi.mock('../../theme/themed-styles', () => ({ - themedStyleSheet: (styles: () => unknown) => styles() -})) -vi.mock('../../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => {} })) -vi.mock('../MobileSourceControlHeader', () => ({ - MobileSourceControlHeader: 'MobileSourceControlHeader' -})) -vi.mock('../MobileSourceControlPanel', () => ({ MobileSourceControlPanel: 'Panel' })) -vi.mock('../mobile-source-control-styles', () => ({ styles: {} })) -vi.mock('./MobileFolderEmptyState', () => ({ MobileFolderEmptyState: 'EmptyState' })) -vi.mock('../../components/host-protocol-gates-context', () => ({ - useOptionalHostProtocolGates: () => null -})) -vi.mock('./use-folder-create-flow', () => ({ - useFolderCreateFlow: () => ({ - onCreate: async () => {}, - covered: seen.covered, - composerElement: null, - toastElement: null - }) -})) -vi.mock('./MobileFolderWorktreeRow', () => ({ - MobileFolderWorktreeRow: (props: { subscribed: boolean }) => { - seen.rowsSubscribed.push(props.subscribed) - return null - } -})) -vi.mock('./use-mobile-folder-attached-worktrees', () => ({ - useMobileFolderAttachedWorktrees: (_hostId: string, _folderId: string, observing: boolean) => { - seen.membersObserving.push(observing) - return { - folder: { worktreeId: 'folder:f-1', repoId: 'folder-workspace:f-1', displayName: 'payments' }, - worktrees: [ROW], - desktopCapabilities: [], - serverHosts: [], - connState: 'connected', - loadError: null, - refetch: () => {} - } - } -})) - -import { MobileFolderSourceControlPanel } from './MobileFolderSourceControlPanel' - -const ROW: FolderListRow = { - worktreeId: 'repo-1::/w/payments', - repoId: 'repo-1', - repo: 'orca', - displayName: 'payments', - branch: 'payments' -} - -let renderer: ReactTestRenderer | null = null -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - seen.covered = false - seen.membersObserving = [] - seen.rowsSubscribed = [] -}) - -describe('MobileFolderSourceControlPanel', () => { - it('pauses row status under the create form while the folder members stay live', () => { - seen.covered = true - act(() => { - renderer = create( - createElement(MobileFolderSourceControlPanel, { - hostId: 'host-1', - folderWorktreeId: 'folder:f-1', - name: 'payments', - embedded: true - }) - ) - }) - - expect(seen.rowsSubscribed.at(-1)).toBe(false) - expect(seen.membersObserving.at(-1)).toBe(true) - }) -}) diff --git a/mobile/src/source-control/folder/folder-source-repos-query.test.ts b/mobile/src/source-control/folder/folder-source-repos-query.test.ts index 523143d4bc8..89c1dcda79d 100644 --- a/mobile/src/source-control/folder/folder-source-repos-query.test.ts +++ b/mobile/src/source-control/folder/folder-source-repos-query.test.ts @@ -1,16 +1,6 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' -import { useHostQuery } from '../../query/host-query' -import { scopeRpcClientToExecutionHost } from '../../worktree/execution-host-scoped-rpc-client' -import { - documentQueryClient, - settleQueryNotifications -} from '../../test-support/rpc-recording/hook-mount' +import { describe, expect, it, vi } from 'vitest' import { FakeSession } from '../../transport/connection/mobile-endpoint-supervisor-test-fakes' import { - folderSourceCatalogQuery, serverFolderSourceCatalogQuery, selectFolderSourceRepos } from './folder-source-repos-query' @@ -64,61 +54,3 @@ describe('folder source repositories', () => { expect(selectFolderSourceRepos(catalog, 'group-1').map((found) => found.id)).toEqual(['api']) }) }) - -describe('folder source catalog reads', () => { - let renderer: ReactTestRenderer | null = null - const queries = documentQueryClient() - afterEach(async () => { - act(() => renderer?.unmount()) - renderer = null - await queries.end() - }) - - it.each([true, false])( - "reads a server folder's catalog on the desktop's one event stream (subscribed: %s)", - async (subscribed) => { - let eventStreams = 0 - const desktop = stubRpcClient({ - getLastConnectedAt: () => 1, - sendRequest: async (method) => ({ - id: '1', - ok: true, - result: method === 'repo.list' ? { repos: [] } : { groups: [GROUP] }, - _meta: { runtimeId: 'r' } - }), - subscribe: (method) => { - if (method === 'runtime.clientEvents.subscribe') { - eventStreams += 1 - } - return () => {} - } - }) - const server = scopeRpcClientToExecutionHost(desktop, 'runtime:env-1') - function Harness(): null { - useHostQuery( - folderSourceCatalogQuery, - { hostId: 'host-1', client: desktop }, - { exec: 'local' }, - {}, - { - subscribed: true - } - ) - useHostQuery( - serverFolderSourceCatalogQuery, - { hostId: 'host-1', client: server }, - { exec: 'runtime:env-1' }, - {}, - { subscribed } - ) - return null - } - await act(async () => { - renderer = create(queries.wrap(createElement(Harness))) - }) - await settleQueryNotifications() - - expect(eventStreams).toBe(1) - } - ) -}) diff --git a/mobile/src/source-control/mobile-branch-base-ref.ts b/mobile/src/source-control/mobile-branch-base-ref.ts index 49723877146..af5338c8344 100644 --- a/mobile/src/source-control/mobile-branch-base-ref.ts +++ b/mobile/src/source-control/mobile-branch-base-ref.ts @@ -3,7 +3,7 @@ import { refusedRpcMessageOrFallback } from '../transport/rpc/rpc-refusal-messag import { getRepoIdFromWorktreeId } from '../../../src/shared/worktree/id' import { isMobileGitUnavailableReply } from './mobile-git-status' import { repoBaseRefListRead, repoDefaultBaseRefRead } from './mobile-repo-base-ref-operations' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import type { RpcResponse } from '../transport/rpc/rpc-wire-types' import { worktreeSummaryRead } from './mobile-worktree-metadata-operations' import { @@ -18,7 +18,7 @@ export type MobileBranchCompareTarget = { } export async function resolveMobileBranchCompareBaseRef( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, compare?: MobileBranchCompareTarget, // A `worktree.show` reply the caller already asked for, so one open reads the worktree once. @@ -36,7 +36,7 @@ export type MobileBranchBaseRefs = { // Desktop's pair: the compare base can be the upstream, while PRs and rebases target the effective base. export async function resolveMobileBranchBaseRefs( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, compare?: MobileBranchCompareTarget, worktreeShow?: Promise @@ -84,7 +84,7 @@ export async function resolveMobileBranchBaseRefs( } async function readDefaultBaseRef( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, repoId: string ): Promise { const defaultReply = await repoDefaultBaseRefRead.request(client, { repo: `id:${repoId}` }) diff --git a/mobile/src/source-control/mobile-branch-compare-outcome.ts b/mobile/src/source-control/mobile-branch-compare-outcome.ts index ae5ea1d6a01..d7294be1806 100644 --- a/mobile/src/source-control/mobile-branch-compare-outcome.ts +++ b/mobile/src/source-control/mobile-branch-compare-outcome.ts @@ -1,5 +1,5 @@ import { translate } from '../i18n/mobile-i18n' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { refusedRpcMessageOrFallback } from '../transport/rpc/rpc-refusal-message' import { resolveMobileBranchBaseRefs, @@ -22,7 +22,7 @@ export type BranchCompareAttempt = BranchCompareOutcome & { // Return failures because callers void this load. export async function readBranchCompareOutcome( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, compare?: MobileBranchCompareTarget ): Promise { @@ -40,7 +40,7 @@ export async function readBranchCompareOutcome( } async function readCompare( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, baseRef: string | null ): Promise { diff --git a/mobile/src/source-control/mobile-commit-message-ai.ts b/mobile/src/source-control/mobile-commit-message-ai.ts index d0710dbd32a..11521f5e667 100644 --- a/mobile/src/source-control/mobile-commit-message-ai.ts +++ b/mobile/src/source-control/mobile-commit-message-ai.ts @@ -5,13 +5,13 @@ import { gitGenerateCommitMessageRun, type MobileGenerateCommitMessageResult } from './mobile-git-mutation-operations' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' export type { MobileGenerateCommitMessageResult } // Collapse refusals and malformed payloads to the same failed-generation verdict. export async function requestMobileCommitMessage( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { const reply = await gitGenerateCommitMessageRun.request(client, { @@ -34,7 +34,7 @@ export async function requestMobileCommitMessage( } export async function cancelMobileCommitMessage( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { const reply = await gitCancelGenerateCommitMessageRun.request(client, { diff --git a/mobile/src/source-control/mobile-git-history.ts b/mobile/src/source-control/mobile-git-history.ts index f51514fa65e..e1a5bf7ce2c 100644 --- a/mobile/src/source-control/mobile-git-history.ts +++ b/mobile/src/source-control/mobile-git-history.ts @@ -7,7 +7,7 @@ import type { } from './git-history-reply-schema' import { refusedRpcMessageOrFallback } from '../transport/rpc/rpc-refusal-message' import { gitHistoryRead } from './mobile-git-read-operations' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' export const MOBILE_GIT_HISTORY_PAGE_SIZE = 50 @@ -89,7 +89,7 @@ export type MobileGitHistoryPageRequest = { } export async function fetchMobileGitHistory( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, page?: MobileGitHistoryPageRequest ): Promise { diff --git a/mobile/src/source-control/mobile-hosted-review-create-intent-runner.ts b/mobile/src/source-control/mobile-hosted-review-create-intent-runner.ts index 4d663ce8d19..f57c7d4f0e2 100644 --- a/mobile/src/source-control/mobile-hosted-review-create-intent-runner.ts +++ b/mobile/src/source-control/mobile-hosted-review-create-intent-runner.ts @@ -10,7 +10,7 @@ import { prepareMobileHostedReviewCreateIntent, type MobileHostedReviewCreateIntentProgress } from './mobile-hosted-review-create-intent' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' type RunInput = { branch: string @@ -50,7 +50,7 @@ export function isMobileHostedReviewCommitFailure( } export async function runMobileHostedReviewCreateIntent( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: RunInput ): Promise { diff --git a/mobile/src/source-control/mobile-hosted-review-create-intent.ts b/mobile/src/source-control/mobile-hosted-review-create-intent.ts index 93d8a3bb50c..00e33f2943d 100644 --- a/mobile/src/source-control/mobile-hosted-review-create-intent.ts +++ b/mobile/src/source-control/mobile-hosted-review-create-intent.ts @@ -12,7 +12,7 @@ import { stageMobileHostedReviewPaths } from './mobile-hosted-review-git-preparation' import { applyMobileHostedReviewRemotePrerequisite } from './mobile-hosted-review-remote-prerequisite' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' export { mobileHostedReviewCreateIntentProgressMessage } from './hosted-review-copy' @@ -60,7 +60,7 @@ function hasUnresolvedConflicts(status: MobileGitStatusResult | null): boolean { } async function resolvePrefillFromStatus( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: Pick, status: MobileGitStatusResult | null @@ -74,7 +74,7 @@ async function resolvePrefillFromStatus( } async function ensureLocalChangesCommitted( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: PrepareInput, currentStatus: MobileGitStatusResult | null @@ -211,7 +211,7 @@ async function ensureLocalChangesCommitted( } export async function prepareMobileHostedReviewCreateIntent( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: PrepareInput ): Promise { diff --git a/mobile/src/source-control/mobile-hosted-review-git-preparation.ts b/mobile/src/source-control/mobile-hosted-review-git-preparation.ts index 94c4c652a16..b6d1c40d04c 100644 --- a/mobile/src/source-control/mobile-hosted-review-git-preparation.ts +++ b/mobile/src/source-control/mobile-hosted-review-git-preparation.ts @@ -13,7 +13,7 @@ import { } from './mobile-git-mutation-operations' import { gitStatusProjectionRead } from './mobile-git-read-operations' import type { MobileGitStatusResult } from './mobile-git-status' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' export type MobileHostedReviewStatusReadResult = | { ok: true; status: MobileGitStatusResult | null } @@ -22,7 +22,7 @@ export type MobileHostedReviewStatusReadResult = export type MobileHostedReviewMutationResult = { ok: true } | { ok: false; error: string } export async function readMobileHostedReviewGitStatus( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { const reply = await gitStatusProjectionRead.request(client, { worktree: `id:${worktreeId}` }) @@ -71,7 +71,7 @@ async function settleMobileHostedReviewMutation( } export function pushMobileHostedReviewBranch( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, params: RpcSendParams<'git.push'>, fallback: string ): Promise { @@ -83,7 +83,7 @@ export function pushMobileHostedReviewBranch( } export function fastForwardMobileHostedReviewBranch( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { return settleMobileHostedReviewMutation( @@ -97,7 +97,7 @@ export function fastForwardMobileHostedReviewBranch( } export function stageMobileHostedReviewPaths( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, filePaths: string[] ): Promise { @@ -109,7 +109,7 @@ export function stageMobileHostedReviewPaths( } export async function commitMobileHostedReviewStagedChanges( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, message: string ): Promise { diff --git a/mobile/src/source-control/mobile-hosted-review-remote-prerequisite.ts b/mobile/src/source-control/mobile-hosted-review-remote-prerequisite.ts index e3226f56593..d44b7a8acc9 100644 --- a/mobile/src/source-control/mobile-hosted-review-remote-prerequisite.ts +++ b/mobile/src/source-control/mobile-hosted-review-remote-prerequisite.ts @@ -8,7 +8,7 @@ import { pushMobileHostedReviewBranch } from './mobile-hosted-review-git-preparation' import { readBranchCompareOutcome } from './mobile-branch-compare-outcome' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' type RemotePrerequisiteInput = { status: MobileGitStatusResult | null @@ -17,7 +17,7 @@ type RemotePrerequisiteInput = { // Desktop publishes only a branch with commits beyond its base; read them only when that decides it. async function readBranchCommitsAhead( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { const compare = await readBranchCompareOutcome(client, worktreeId) @@ -27,7 +27,7 @@ async function readBranchCommitsAhead( } export async function applyMobileHostedReviewRemotePrerequisite( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, prefill: MobilePrPrefill, input: RemotePrerequisiteInput diff --git a/mobile/src/source-control/mobile-hosted-review-service.ts b/mobile/src/source-control/mobile-hosted-review-service.ts index 46f4f35a546..34c5d7111f6 100644 --- a/mobile/src/source-control/mobile-hosted-review-service.ts +++ b/mobile/src/source-control/mobile-hosted-review-service.ts @@ -11,7 +11,7 @@ import { } from './mobile-hosted-review-operations' import { pushMobileHostedReviewBranch } from './mobile-hosted-review-git-preparation' import { linkMobileHostedReview } from './mobile-pr-link' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' // Mobile ids combine repo::path; hosted-review RPCs need separate selectors. export function mobileRepoSelectorFromWorktreeId(worktreeId: string): string { @@ -30,7 +30,7 @@ export type MobileHostedReviewEligibilityInput = { } export async function fetchMobileHostedReviewEligibility( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: MobileHostedReviewEligibilityInput ): Promise { @@ -67,7 +67,7 @@ export type MobileHostedReviewPrefill = { } export async function resolveMobileHostedReviewPrefill( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { branch: string | undefined @@ -166,7 +166,7 @@ export type MobileHostedReviewCreateOutcome = // The form intentionally uses one actionable fallback for all push failures. async function pushMobileBranchBeforeCreate( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise<{ ok: true } | { ok: false; error: string }> { const error = translate( @@ -200,7 +200,7 @@ function formatMobileHostedReviewCreateError( } async function finishMobileHostedReviewCreateSuccess( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: MobileHostedReviewCreateInput, result: { number: number; url: string }, @@ -221,7 +221,7 @@ async function finishMobileHostedReviewCreateSuccess( } export async function createMobileHostedReview( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: MobileHostedReviewCreateInput ): Promise { diff --git a/mobile/src/source-control/mobile-pr-create-draft.ts b/mobile/src/source-control/mobile-pr-create-draft.ts index 66efde5aa68..d2431ffabde 100644 --- a/mobile/src/source-control/mobile-pr-create-draft.ts +++ b/mobile/src/source-control/mobile-pr-create-draft.ts @@ -1,6 +1,6 @@ import { translate } from '../i18n/mobile-i18n' import { refusedRpcMessageOrFallback } from '../transport/rpc/rpc-refusal-message' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { resolveCreateReviewSeedFromCommits } from '../../../src/shared/source-control/hosted-review/hosted-review-create-seed' import { normalizeCreateReviewBaseSearchResults, @@ -41,7 +41,7 @@ const HOSTED_PROVIDERS: readonly HostedReviewProvider[] = [ // The host's prefill decides provider, base and blockers; the branch's commits seed the text. export async function loadMobilePrCreateDraft( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: { branch: string; status: MobileGitStatusResult | null; commitsAhead?: number | null } ): Promise { @@ -84,7 +84,7 @@ function commitBody(message: string | undefined): string { } export async function generateMobilePrFields( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, input: { base: string; title: string; body: string; draft: boolean; provider: string } ): Promise { @@ -116,7 +116,7 @@ export async function generateMobilePrFields( // The host runs one generation per lane, so an abandoned one would delay the next. export async function cancelMobilePrFields( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { const reply = await gitCancelGeneratePullRequestFieldsRun.request(client, { @@ -126,7 +126,7 @@ export async function cancelMobilePrFields( } export async function searchMobilePrBaseRefs( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, query: string ): Promise { diff --git a/mobile/src/source-control/mobile-pr-link.ts b/mobile/src/source-control/mobile-pr-link.ts index ceef26f3649..90b7673f6b8 100644 --- a/mobile/src/source-control/mobile-pr-link.ts +++ b/mobile/src/source-control/mobile-pr-link.ts @@ -2,7 +2,7 @@ import { translate } from '../i18n/mobile-i18n' import type { RpcSendParams } from '../../../src/shared/rpc-contract/rpc-send-params' import { CLEARED_HOSTED_REVIEW_SELECTION_UPDATES } from '../../../src/shared/worktree/hosted-review-links' import { refusedRpcMessageOrFallback } from '../transport/rpc/rpc-refusal-message' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { worktreeLinkSet, worktreeSummaryRead, @@ -54,7 +54,7 @@ export function buildWorktreeSetHostedReviewLinkParams( // Refusal without a message uses screen copy; transport errors retain their own message. async function setWorktreeReviewLink( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, params: RpcSendParams<'worktree.set'>, fallback: string ): Promise { @@ -73,7 +73,7 @@ async function setWorktreeReviewLink( } export function linkMobilePr( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, prNumber: number ): Promise { @@ -88,7 +88,7 @@ export function linkMobilePr( } export async function linkMobileHostedReview( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, provider: string, number: number, @@ -108,7 +108,7 @@ export async function linkMobileHostedReview( // Like desktop, suppress the unlinked PR so branch discovery does not bring it straight back. export function unlinkMobilePr( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, prNumber: number ): Promise { @@ -130,7 +130,7 @@ const NO_GITHUB_PR_LINK: WorktreeGitHubPRLink = { // Desktop's durable clear for a link the branch has moved past; a failed write only repeats the check next load. export async function clearMobileWorktreeReviewLink( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, shouldApply: (worktree: MobileWorktreeSummary) => boolean ): Promise { @@ -151,14 +151,14 @@ export async function clearMobileWorktreeReviewLink( // Persisted links recover closed/merged PRs that branch lookup no longer returns. export async function fetchWorktreeGitHubPRLink( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { return (await readWorktreeSummary(client, worktreeId)) ?? NO_GITHUB_PR_LINK } async function readWorktreeSummary( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise { try { diff --git a/mobile/src/source-control/review/github-pr-draft-mutations.ts b/mobile/src/source-control/review/github-pr-draft-mutations.ts index 0839693ff53..58326da4894 100644 --- a/mobile/src/source-control/review/github-pr-draft-mutations.ts +++ b/mobile/src/source-control/review/github-pr-draft-mutations.ts @@ -1,11 +1,11 @@ -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import { githubPrRequestParams, type GitHubPrRepoSlug } from './github-pr-repo-slug' import { githubPrDraftMark, githubPrReadyForReviewMark } from './github-pr-mutation-operations' import { settleGithubPrMutation, type GitHubPrMutationOutcome } from './github-pr-mutation-outcome' // Ready for review and Mark as draft: the same toggle on GitHub, one RPC each. export function fetchMarkPRReadyForReview( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -23,7 +23,7 @@ export function fetchMarkPRReadyForReview( } export function fetchMarkPRDraft( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; prRepo?: GitHubPrRepoSlug | null } ): Promise { diff --git a/mobile/src/source-control/review/github-pr-mutations.ts b/mobile/src/source-control/review/github-pr-mutations.ts index d31ed5f29f1..0c2ba0cd587 100644 --- a/mobile/src/source-control/review/github-pr-mutations.ts +++ b/mobile/src/source-control/review/github-pr-mutations.ts @@ -24,11 +24,11 @@ import { githubPrRequestParams, type GitHubPrRepoSlug } from './github-pr-repo-slug' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import { translate } from '../../i18n/mobile-i18n' export function fetchMergePR( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; method?: GitHubPRMergeMethod; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -47,7 +47,7 @@ export function fetchMergePR( } export function fetchUpdatePRTitle( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; title: string; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -66,7 +66,7 @@ export function fetchUpdatePRTitle( } export function fetchUpdatePRBody( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; body: string; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -81,7 +81,7 @@ export function fetchUpdatePRBody( } export function fetchSetPRAutoMerge( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number @@ -105,7 +105,7 @@ export function fetchSetPRAutoMerge( } export function fetchUpdatePRState( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; state: 'open' | 'closed'; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -123,7 +123,7 @@ export function fetchUpdatePRState( } export function fetchRequestPRReviewers( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -141,7 +141,7 @@ export function fetchRequestPRReviewers( } export function fetchRemovePRReviewers( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -159,7 +159,7 @@ export function fetchRemovePRReviewers( } export function fetchRerunPRChecks( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number @@ -186,7 +186,7 @@ export function fetchRerunPRChecks( } export function fetchAddPRReviewCommentReply( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number @@ -223,7 +223,7 @@ export function fetchAddPRReviewCommentReply( } export function fetchAddIssueComment( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number; body: string; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -244,7 +244,7 @@ export function fetchAddIssueComment( // Thread resolution returns boolean confirmation; do not apply status-envelope void-success semantics. export function fetchResolveReviewThread( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { threadId: string; resolve: boolean; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -269,7 +269,7 @@ export function fetchResolveReviewThread( // Issue comment edits use owner/repo/commentId rather than worktree-scoped params. export function fetchUpdateIssueComment( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, args: { owner: string; repo: string; host?: string; commentId: number; body: string } ): Promise { return settleGithubPrMutation(githubPrIssueCommentEdit, () => @@ -282,7 +282,7 @@ export function fetchUpdateIssueComment( } export function fetchDeleteIssueComment( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, args: { owner: string; repo: string; host?: string; commentId: number } ): Promise { return settleGithubPrMutation(githubPrIssueCommentDelete, () => diff --git a/mobile/src/source-control/review/github-pr-review-line-mutations.ts b/mobile/src/source-control/review/github-pr-review-line-mutations.ts index a7ccdc46fde..574ef37470a 100644 --- a/mobile/src/source-control/review/github-pr-review-line-mutations.ts +++ b/mobile/src/source-control/review/github-pr-review-line-mutations.ts @@ -5,14 +5,14 @@ import { type GitHubPrMutationOutcome } from './github-pr-mutation-outcome' import { githubPrRequestParams, type GitHubPrRepoSlug } from './github-pr-repo-slug' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import { translate } from '../../i18n/mobile-i18n' // The diff screen's writes on a PR file: a new line comment and its viewed mark. // A new line comment on the PR's head commit; GitHub only accepts lines inside the file's diff hunks. export function fetchAddPRReviewComment( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number @@ -45,7 +45,7 @@ export function fetchAddPRReviewComment( } export function fetchSetPRFileViewed( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { pullRequestId: string diff --git a/mobile/src/source-control/review/github-pr-rpc.ts b/mobile/src/source-control/review/github-pr-rpc.ts index 0b46be0adc6..5c5e340a562 100644 --- a/mobile/src/source-control/review/github-pr-rpc.ts +++ b/mobile/src/source-control/review/github-pr-rpc.ts @@ -28,7 +28,7 @@ import { } from './github-pr-read-operations' import type { GitHubPrSettleableOperation } from './github-pr-mutation-outcome' import { githubPrRequestParams, type GitHubPrRepoSlug } from './github-pr-repo-slug' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import { translate } from '../../i18n/mobile-i18n' export type GitHubPrReadOutcome = { ok: true; result: T } | { ok: false; error: string } @@ -64,7 +64,7 @@ async function settleGithubPrRead( // Gate the PR icon on a GitHub remote independently of whether this branch has an open PR. export function fetchGithubRepoSlug( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string ): Promise> { return settleGithubPrRead(githubPrRepoSlugRead, () => @@ -76,7 +76,7 @@ export function fetchGithubRepoSlug( } export function fetchHostedReviewForBranch( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { branch: string; linkedGitHubPR?: number | null } ): Promise> { @@ -94,7 +94,7 @@ export function fetchHostedReviewForBranch( // Raise decoded upstream-error here so the sidebar retains host text; it is not a protocol decode failure. export async function fetchPRForBranch( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { branch: string @@ -224,7 +224,7 @@ export async function fetchWorkItemDetails( } export function fetchPRChecks( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { prNumber: number @@ -251,7 +251,7 @@ export function fetchPRChecks( } export function fetchPRCheckDetails( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, worktreeId: string, args: { checkRunId?: number diff --git a/mobile/src/source-control/review/mobile-review-notes-operations.ts b/mobile/src/source-control/review/mobile-review-notes-operations.ts index ed7d8688140..3a70976f334 100644 --- a/mobile/src/source-control/review/mobile-review-notes-operations.ts +++ b/mobile/src/source-control/review/mobile-review-notes-operations.ts @@ -1,11 +1,7 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' import { sessionWorktreeRecordSchema } from '../../worktree/session-worktree-record-reply-schema' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' import '../../terminal/terminal-reply-schema' -import '../../terminal/session/mobile-session-terminal-reply-schema' -import '../../session/tabs/mobile-session-tab-write-reply-schema' -import '../../transport/rpc/rpc-uninterpreted-reply-schemas' import '../../terminal/quick-commands/mobile-quick-command-operations' // Preserve host refusal text for optimistic rollback; the reply's record carries the host's merged notes. diff --git a/mobile/src/source-control/review/pr-check-observation-contract.ts b/mobile/src/source-control/review/pr-check-observation-contract.ts index 432cbd30dab..761c6486c7a 100644 --- a/mobile/src/source-control/review/pr-check-observation-contract.ts +++ b/mobile/src/source-control/review/pr-check-observation-contract.ts @@ -1,7 +1,9 @@ import * as z from 'zod' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import type { SendRequestOptions } from '../../transport/rpc/unvalidated-rpc-request-port' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { + SendRequestOptions, + UnvalidatedRpcRequestPort +} from '../../transport/rpc/unvalidated-rpc-request-port' import { captureGitHubInvocation, supportsExactGitHubOperations } from './github-target-invocation' import { readRuntimeStatusProbe, @@ -97,7 +99,7 @@ function statusFor(client: RpcClient, refresh: boolean): Promise { const { worktreeId, prRepo, write } = vars diff --git a/mobile/src/source-control/review/use-mobile-pr-actions.ts b/mobile/src/source-control/review/use-mobile-pr-actions.ts index 2bd5b017177..740864512d4 100644 --- a/mobile/src/source-control/review/use-mobile-pr-actions.ts +++ b/mobile/src/source-control/review/use-mobile-pr-actions.ts @@ -12,7 +12,7 @@ import { } from './github-pr-mutations' import { fetchMarkPRDraft, fetchMarkPRReadyForReview } from './github-pr-draft-mutations' import type { GitHubPrRepoSlug } from './github-pr-repo-slug' -import type { RpcOperationSender } from '../../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' import { PrActionsEngine, type PrActionBusyKey } from './pr-actions-engine' import './pr-action-mutation-contract' import type { PrActionMutations } from './pr-action-mutation-contract' @@ -28,7 +28,7 @@ export type PrActionsInput = { mutations?: PrActionMutations } -function realMutations(client: RpcOperationSender, worktreeId: string): PrActionMutations { +function realMutations(client: UnvalidatedRpcRequestPort, worktreeId: string): PrActionMutations { return { mergePR: (args) => fetchMergePR(client, worktreeId, args), setPRAutoMerge: (args) => fetchSetPRAutoMerge(client, worktreeId, args), diff --git a/mobile/src/tasks/jira-mobile-connection.ts b/mobile/src/tasks/jira-mobile-connection.ts index 0bd5fefac7b..d461d07d48c 100644 --- a/mobile/src/tasks/jira-mobile-connection.ts +++ b/mobile/src/tasks/jira-mobile-connection.ts @@ -1,5 +1,5 @@ import type { JiraSite, JiraSiteSelection } from '../../../src/shared/jira/jira-types' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import type { RpcResponse } from '../transport/rpc/rpc-wire-types' import { jiraConnectionStatusSchema } from './jira-reply-schema' import { jiraConnectionStatusProbe, jiraConnectionStatusRead } from './mobile-jira-operations' @@ -88,7 +88,7 @@ function resolveJiraSiteSelection( // Explicit refreshes surface failures instead of presenting a setup prompt. export async function readJiraConnection( - client: RpcOperationSender + client: UnvalidatedRpcRequestPort ): Promise { return extractJiraConnection( jiraConnectionStatusRead.interpret(await jiraConnectionStatusRead.request(client)) diff --git a/mobile/src/tasks/jira-mobile-url-lookup.test.ts b/mobile/src/tasks/jira-mobile-url-lookup.test.ts index 22a2163fd24..30c5e2cbee9 100644 --- a/mobile/src/tasks/jira-mobile-url-lookup.test.ts +++ b/mobile/src/tasks/jira-mobile-url-lookup.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { JiraIssue, JiraSite } from '../../../src/shared/jira/jira-types' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { lookupJiraIssueByUrl } from './jira-mobile-url-lookup' const acme: JiraSite = { @@ -29,7 +29,7 @@ function issue(overrides: Partial = {}): JiraIssue { } } -function clientReturning(result: unknown, sendRequest = vi.fn()): RpcOperationSender { +function clientReturning(result: unknown, sendRequest = vi.fn()): UnvalidatedRpcRequestPort { sendRequest.mockResolvedValue({ ok: true, result }) return { sendRequest } } diff --git a/mobile/src/tasks/jira-mobile-url-lookup.ts b/mobile/src/tasks/jira-mobile-url-lookup.ts index e2155e6b330..0db57d4197b 100644 --- a/mobile/src/tasks/jira-mobile-url-lookup.ts +++ b/mobile/src/tasks/jira-mobile-url-lookup.ts @@ -4,12 +4,12 @@ import { isResolvedJiraIssueMatch, parseJiraIssueUrl } from '../../../src/shared/jira/jira-issue-url' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { jiraIssueRead } from './mobile-jira-operations' // Match a connected site before resolving keys that may exist on several sites. export async function lookupJiraIssueByUrl( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, value: string, sites: readonly JiraSite[] ): Promise { diff --git a/mobile/src/tasks/mobile-jira-task-source.ts b/mobile/src/tasks/mobile-jira-task-source.ts index ae640eeede6..f0d44602ffd 100644 --- a/mobile/src/tasks/mobile-jira-task-source.ts +++ b/mobile/src/tasks/mobile-jira-task-source.ts @@ -3,7 +3,7 @@ import type { JiraIssueFilter, JiraSiteSelection } from '../../../src/shared/jira/jira-types' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { toJiraDetailComments } from './jira-mobile-issue-read' import { jiraIssueCommentsRead, @@ -18,7 +18,7 @@ const DETAIL_TIMEOUT_MS = 30_000 // Raw JQL replaces the selected preset, matching desktop. export async function fetchJiraTaskIssues( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, args: { jql: string; filter: JiraIssueFilter; siteId: JiraSiteSelection | null } ): Promise { const jql = args.jql.trim() @@ -41,7 +41,7 @@ export async function fetchJiraTaskIssues( } export async function fetchJiraIssueDetail( - client: RpcOperationSender, + client: UnvalidatedRpcRequestPort, args: { key: string; siteId?: string } ): Promise<{ issue: JiraIssue; comments: ReturnType }> { const params = { key: args.key, siteId: args.siteId } diff --git a/mobile/src/tasks/mobile-tasks-host-subtitle.tsx b/mobile/src/tasks/mobile-tasks-host-subtitle.tsx index e6cf9004e64..07d2a20cc03 100644 --- a/mobile/src/tasks/mobile-tasks-host-subtitle.tsx +++ b/mobile/src/tasks/mobile-tasks-host-subtitle.tsx @@ -1,7 +1,7 @@ import { StyleSheet, Text } from 'react-native' import { hostScreenStyles } from '../host-screen/host-screen-styles' -import { useHostProfile } from '../transport/hosts/use-host-profile' -import { useHostDisplay } from '../transport/hosts/use-host-display' +import { useHostProfile } from '../host-catalog/use-host-profile' +import { useHostDisplay } from '../host-descriptors/use-host-display' import { useMobileColorScheme } from './mobile-tasks-dependencies' export function MobileTasksHostSubtitle({ hostId }: { hostId: string }) { diff --git a/mobile/src/tasks/mobile-tasks-list-state.tsx b/mobile/src/tasks/mobile-tasks-list-state.tsx index b190e73ba31..35879dcb433 100644 --- a/mobile/src/tasks/mobile-tasks-list-state.tsx +++ b/mobile/src/tasks/mobile-tasks-list-state.tsx @@ -9,8 +9,8 @@ import { } from '../components/MobileStateView' import { useForceReconnect } from '../transport/connection/host-client-hooks' import { isConnectionOutage } from '../transport/connection/connection-health' -import { useHostDisplay } from '../transport/hosts/use-host-display' -import { useHostProfile } from '../transport/hosts/use-host-profile' +import { useHostDisplay } from '../host-descriptors/use-host-display' +import { useHostProfile } from '../host-catalog/use-host-profile' import { spacing } from '../theme/mobile-theme' import { translate } from '../i18n/mobile-i18n' import type { ConnectionPresentationModel } from './use-mobile-tasks-connection-presentation' diff --git a/mobile/src/tasks/use-task-host-repos.ts b/mobile/src/tasks/use-task-host-repos.ts index 2fa9010fd1a..e91ef7df7d3 100644 --- a/mobile/src/tasks/use-task-host-repos.ts +++ b/mobile/src/tasks/use-task-host-repos.ts @@ -1,7 +1,7 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { ExecutionHostId } from '../../../src/shared/execution-host' import type { HostContextLabelSources } from '../../../src/shared/worktree/host-context-labels' -import { useHostDescriptor } from '../transport/hosts/host-descriptor-store' +import { useHostDescriptor } from '../host-descriptors/host-descriptor-store' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../transport/connection/connection-state' import { withServerHosts } from '../worktree/server-workspaces' diff --git a/mobile/src/terminal/mobile-terminal-query-reply.ts b/mobile/src/terminal/mobile-terminal-query-reply.ts index c6e5d6c1e6a..7273a2225db 100644 --- a/mobile/src/terminal/mobile-terminal-query-reply.ts +++ b/mobile/src/terminal/mobile-terminal-query-reply.ts @@ -1,6 +1,6 @@ import { isTerminalQueryReply } from '../../../src/shared/terminal/protocol/queries/terminal-query-reply' import { PROGRAM_STATUS_OSC_PREFIX } from '../../../src/shared/program-status/protocol' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import { terminalInputSend } from './mobile-terminal-operations' type TerminalSubscriptionRegistry = { @@ -9,7 +9,7 @@ type TerminalSubscriptionRegistry = { type MobileTerminalQueryReplyOptions = { bytes: string - client: RpcOperationSender | null + client: UnvalidatedRpcRequestPort | null clientId: string | null connected: boolean handle: string diff --git a/mobile/src/terminal/quick-commands/QuickCommandRow.test.ts b/mobile/src/terminal/quick-commands/QuickCommandRow.test.ts deleted file mode 100644 index 3728dff5c4f..00000000000 --- a/mobile/src/terminal/quick-commands/QuickCommandRow.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalQuickCommand } from '../../../../src/shared/terminal/quick-commands/terminal-quick-command-types' -import { QuickCommandRow } from './QuickCommandRow' - -const clipboard = vi.hoisted(() => ({ setStringAsync: vi.fn(() => Promise.resolve(true)) })) -const haptics = vi.hoisted(() => ({ notificationAsync: vi.fn(() => Promise.resolve()) })) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - StyleSheet: { create: (styles: T) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' -})) - -vi.mock('lucide-react-native', () => ({ - Check: 'Check', - Copy: 'Copy', - Pencil: 'Pencil', - Play: 'Play', - Trash2: 'Trash2' -})) - -vi.mock('expo-clipboard', () => clipboard) - -vi.mock('expo-haptics', () => ({ - ...haptics, - performAndroidHapticsAsync: vi.fn(() => Promise.resolve()), - AndroidHaptics: { Reject: 'reject' }, - NotificationFeedbackType: { Error: 'error', Success: 'success' } -})) - -vi.mock('../../components/MobileAgentIcon', () => ({ MobileAgentIcon: 'MobileAgentIcon' })) - -const COMMAND: TerminalQuickCommand = { - id: 'qc-1', - label: 'Run tests', - command: 'run the tests', - appendEnter: true -} - -// Require visible error feedback and haptics when clipboard writes reject; a failed write must never show Copied. -describe('the quick-command row when the pasteboard refuses the text', () => { - let renderer: ReactTestRenderer | null = null - - beforeEach(() => { - clipboard.setStringAsync.mockReset() - haptics.notificationAsync.mockReset() - haptics.notificationAsync.mockImplementation(() => Promise.resolve()) - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - // Find by every copy-state label so feedback transitions cannot make the control disappear from assertions. - const COPY_LABELS = new Set([ - `Copy ${COMMAND.label}`, - 'Copied', - "Couldn't copy", - 'Nothing to copy' - ]) - - function copyButton() { - const button = renderer!.root - .findAll((node) => node.props.accessibilityRole === 'button') - .find((node) => COPY_LABELS.has(String(node.props.accessibilityLabel))) - if (button === undefined) { - throw new Error('the row has no copy button') - } - return button - } - - function rowProps() { - return { - command: COMMAND, - first: true, - onLaunch: vi.fn(), - onEdit: vi.fn(), - onDelete: vi.fn(), - disabled: false - } - } - - it('emits nothing at all when the row is gone before the refusal arrives', async () => { - // Unmount before rejection; feedback without a surviving row would buzz with no explanation. - let refuse: ((error: Error) => void) | undefined - clipboard.setStringAsync.mockImplementation( - () => - new Promise((_resolve, reject) => { - refuse = reject - }) - ) - await act(async () => { - renderer = create(createElement(QuickCommandRow, rowProps())) - }) - await act(async () => { - copyButton().props.onPress() - }) - act(() => renderer?.unmount()) - renderer = null - await act(async () => { - refuse?.(new Error('pasteboard refused')) - }) - expect(haptics.notificationAsync).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/terminal/quick-commands/mobile-quick-command-operations.ts b/mobile/src/terminal/quick-commands/mobile-quick-command-operations.ts index c019aa7e9c2..f3f9eee7fb8 100644 --- a/mobile/src/terminal/quick-commands/mobile-quick-command-operations.ts +++ b/mobile/src/terminal/quick-commands/mobile-quick-command-operations.ts @@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' import '../terminal-reply-schema' import { terminalQuickCommandsSchema } from './mobile-quick-command-reply-schema' -import '../../session/agent-launch/mobile-agent-detection-reply-schema' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' -import '../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../session/mobile-session-terminal-reply-schema' -import '../../worktree/session-worktree-record-reply-schema' -import '../../session/native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../../files/workspace-file-paths-reply-schema' export const quickCommandsReader = rpcResultVariant( 'terminal-quick-commands', @@ -26,8 +19,6 @@ export const quickCommandsRead = bindDeferredRpcOperation( }) ) -import '../../session/tabs/mobile-session-tab-write-reply-schema' - export const quickCommandsWrite = bindDeferredRpcOperation( defineRpcOperation({ name: 'settings.quick-commands-write', diff --git a/mobile/src/terminal/quick-commands/mobile-quick-command-reply-schema.ts b/mobile/src/terminal/quick-commands/mobile-quick-command-reply-schema.ts index fb6a6ac66c1..2be3e0b35ca 100644 --- a/mobile/src/terminal/quick-commands/mobile-quick-command-reply-schema.ts +++ b/mobile/src/terminal/quick-commands/mobile-quick-command-reply-schema.ts @@ -1,5 +1,4 @@ import * as z from 'zod' -import '../../../../src/shared/zod-salvage' // Preserve null for unreadable canonical command lists so load/save cannot erase host commands with an invented empty list. export const terminalQuickCommandsSchema = z diff --git a/mobile/src/terminal/session/MobileTerminalRenameModal.tsx b/mobile/src/terminal/session/MobileTerminalRenameModal.tsx index ec26c4d9d95..50408efcc77 100644 --- a/mobile/src/terminal/session/MobileTerminalRenameModal.tsx +++ b/mobile/src/terminal/session/MobileTerminalRenameModal.tsx @@ -2,8 +2,8 @@ import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer' import { TextInputSheetContent } from '../../components/TextInputModal' import { useDraftRenameSheet } from '../../components/use-draft-rename-sheet' import { useMobileTranslation } from '../../i18n/use-mobile-translation' -import { useHostDisplay } from '../../transport/hosts/use-host-display' -import { useHostProfile } from '../../transport/hosts/use-host-profile' +import { useHostDisplay } from '../../host-descriptors/use-host-display' +import { useHostProfile } from '../../host-catalog/use-host-profile' import type { MobileSessionController } from '../../session/use-mobile-session-controller' export function MobileTerminalRenameModal({ diff --git a/mobile/src/terminal/session/mobile-session-terminal-operations.ts b/mobile/src/terminal/session/mobile-session-terminal-operations.ts index 5de3473f24c..505d6058da8 100644 --- a/mobile/src/terminal/session/mobile-session-terminal-operations.ts +++ b/mobile/src/terminal/session/mobile-session-terminal-operations.ts @@ -2,13 +2,7 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' import { terminalComposerDraftSchema, terminalSendAcceptedSchema } from '../terminal-reply-schema' import { sessionTerminalInventorySchema } from './mobile-session-terminal-reply-schema' -import '../../session/agent-launch/mobile-agent-detection-reply-schema' -import '../../files/session-documents/mobile-markdown-tab-reply-schema' import { sessionWriteUnreadReplySchema } from '../../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../../worktree/session-worktree-record-reply-schema' -import '../../session/native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../quick-commands/mobile-quick-command-reply-schema' -import '../../files/workspace-file-paths-reply-schema' export const nativeChatTerminalDraftRead = bindDeferredRpcOperation( defineRpcOperation({ @@ -31,7 +25,6 @@ export const sessionTerminalListRead = bindDeferredRpcOperation( }) ) -import '../../session/tabs/mobile-session-tab-write-reply-schema' import '../quick-commands/mobile-quick-command-operations' // Keep chat writes distinct from query/accessory responders: losing a reply here means unknown delivery and forbids automatic retry. diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send.ts b/mobile/src/terminal/terminal-live-accessory-raw-send.ts index 69dd43a379b..6ee6773c962 100644 --- a/mobile/src/terminal/terminal-live-accessory-raw-send.ts +++ b/mobile/src/terminal/terminal-live-accessory-raw-send.ts @@ -1,12 +1,12 @@ import { getTerminalLiveAccessoryRawSendTarget } from './terminal-live-accessory-raw-send-target' import { buildTerminalSendParams, TERMINAL_INPUT_SEND_OPTIONS } from './terminal-send-request' import { terminalInputSend } from './mobile-terminal-operations' -import type { RpcOperationSender } from '../transport/rpc/rpc-operation-sender' +import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' import type { ConnectionState } from '../transport/connection/connection-state' type TerminalLiveAccessoryRawSendArgs = { readonly sendTerminalUserInput: typeof terminalInputSend.request - readonly client: RpcOperationSender | null + readonly client: UnvalidatedRpcRequestPort | null readonly targetHandle: string readonly activeHandle: string | null readonly activeSessionTabType: string | null diff --git a/mobile/src/test-support/in-memory-async-storage.ts b/mobile/src/test-support/in-memory-async-storage.ts new file mode 100644 index 00000000000..b20d0954d6e --- /dev/null +++ b/mobile/src/test-support/in-memory-async-storage.ts @@ -0,0 +1,16 @@ +import type AsyncStorage from '@react-native-async-storage/async-storage' + +type InMemoryAsyncStorage = Pick + +export function createInMemoryAsyncStorage(): InMemoryAsyncStorage { + const values = new Map() + return { + getItem: async (key: string) => values.get(key) ?? null, + setItem: async (key: string, value: string) => { + values.set(key, value) + }, + removeItem: async (key: string) => { + values.delete(key) + } + } +} diff --git a/mobile/src/test-support/rpc-recording/adapters/mounted-operation-modules.ts b/mobile/src/test-support/rpc-recording/adapters/mounted-operation-modules.ts index fb8830d44cb..961b9bcb272 100644 --- a/mobile/src/test-support/rpc-recording/adapters/mounted-operation-modules.ts +++ b/mobile/src/test-support/rpc-recording/adapters/mounted-operation-modules.ts @@ -39,10 +39,7 @@ import { newWorkspaceRepositoryMountAdapters } from './new-workspace-repository- import { pairingJournalMountAdapters } from './pairing-journal-mount-adapters' import { prSidebarMountAdapters } from './pr-sidebar-mount-adapters' import { pushDismissalMountAdapters } from './push-dismissal-mount-adapters' -import { - pushRegistrationMountAdapters, - pushRegistrationMountExposures -} from './push-registration-mount-adapters' +import { pushRegistrationMountAdapters } from './push-registration-mount-adapters' import { relayCredentialMountAdapters } from './relay-credential-mount-adapters' import { sessionNotesMountAdapters } from './session-notes-mount-adapters' import { sessionScreenReadMountAdapters } from './session-screen-read-mount-adapters' @@ -143,8 +140,7 @@ export const MOUNTED_OPERATION_MODULES: readonly MountedOperationModule[] = [ { source: 'push-dismissal-mount-adapters.ts', mounts: pushDismissalMountAdapters }, { source: 'push-registration-mount-adapters.ts', - mounts: pushRegistrationMountAdapters, - exposes: pushRegistrationMountExposures + mounts: pushRegistrationMountAdapters }, { source: 'relay-credential-mount-adapters.ts', mounts: relayCredentialMountAdapters }, { source: 'session-notes-mount-adapters.ts', mounts: sessionNotesMountAdapters }, diff --git a/mobile/src/test-support/rpc-recording/adapters/push-registration-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/push-registration-mount-adapters.ts index bcb701e5751..d24c73efe26 100644 --- a/mobile/src/test-support/rpc-recording/adapters/push-registration-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/push-registration-mount-adapters.ts @@ -1,14 +1,6 @@ -import type { OperationExposure, operationModuleLoader } from '../operation-module-loader' +import type { operationModuleLoader } from '../operation-module-loader' import type { MountAdapter } from '../recording-scenario' -// Expose private senders to record wire behavior without inventing keychain and device-token storage in substitutes. -export const pushRegistrationMountExposures: readonly OperationExposure[] = [ - [ - 'notifications/push-registration.ts', - '\nexports.sendRegister = sendRegister;\nexports.sendUnregister = sendUnregister;' - ] -] - const REGISTER_TIMEOUT_MS = 5_000 export function pushRegistrationMountAdapters( @@ -19,7 +11,7 @@ export function pushRegistrationMountAdapters( const push = modules.load<{ sendRegister: (client: unknown, token: unknown, filter: unknown) => Promise sendUnregister: (client: unknown, timeoutMs: number) => Promise - }>('mobile/src/notifications/push-registration.ts') + }>('mobile/src/notifications/mobile-push-registration-operations.ts') const results: Record = {} return { action(name, args) { diff --git a/mobile/src/test-support/rpc-recording/relay-pairing-fixtures.ts b/mobile/src/test-support/rpc-recording/relay-pairing-fixtures.ts index 9217c4ce6bd..9938506c06b 100644 --- a/mobile/src/test-support/rpc-recording/relay-pairing-fixtures.ts +++ b/mobile/src/test-support/rpc-recording/relay-pairing-fixtures.ts @@ -1,5 +1,5 @@ import type * as MobileRelayCredentialHashModule from '../../transport/relay/mobile-relay-credential-hash' -import type { MobileRelayCredentialBundle } from '../../transport/hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import type { MobileRelayPairingJournal } from '../../pairing/mobile-relay-pairing-journal' import type { MountContext } from './recording-scenario' import type { operationModuleLoader } from './operation-module-loader' diff --git a/mobile/src/transport/connection/client-context.test.ts b/mobile/src/transport/connection/client-context.test.ts index 8688ab11863..4d0097b6f53 100644 --- a/mobile/src/transport/connection/client-context.test.ts +++ b/mobile/src/transport/connection/client-context.test.ts @@ -23,7 +23,7 @@ vi.mock('./runtime-status-probe', () => ({ startRuntimeStatusProbe: (client: unknown, onStatus: (status: unknown) => void) => descriptorProbe.start(client, onStatus) })) -vi.mock('../hosts/host-descriptor-recorder', () => ({ +vi.mock('../../host-descriptors/host-descriptor-recorder', () => ({ recordHostDescriptorFromStatus: (...args: unknown[]) => descriptorProbe.record(...args) })) @@ -36,7 +36,7 @@ vi.mock('../rpc/direct-rpc-connect', () => ({ vi.mock('./host-logical-client', () => ({ openHostLogicalClient: (...args: unknown[]) => connectMock(...args) })) -vi.mock('../hosts/host-store', () => ({ +vi.mock('../../host-catalog/host-store', () => ({ loadHosts: () => loadHostsMock() })) vi.mock('../../diagnostics/connection/connection-revival-triggers', () => ({ diff --git a/mobile/src/transport/connection/client-context.tsx b/mobile/src/transport/connection/client-context.tsx index 5bb222dd2e9..f368d8136fd 100644 --- a/mobile/src/transport/connection/client-context.tsx +++ b/mobile/src/transport/connection/client-context.tsx @@ -36,7 +36,7 @@ import { type CloseEntryOptions } from './host-client-context-state' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import type { RpcClientContextValue } from './rpc-client-context-contract' type StoreEntry = HostClientStoreEntry diff --git a/mobile/src/transport/connection/client-context.web.tsx b/mobile/src/transport/connection/client-context.web.tsx index 547f5c2ee06..b93af825038 100644 --- a/mobile/src/transport/connection/client-context.web.tsx +++ b/mobile/src/transport/connection/client-context.web.tsx @@ -3,7 +3,7 @@ import { createContext, useContext, useMemo, useRef, type ReactNode } from 'reac import type { BridgeRpcClient } from '../../mobile-web-shell/bridge/bridge-rpc-client' import { BRIDGE_PAGE_CLIENT_ID } from '../../mobile-web-shell/bridge/bridge-page-client-identity' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import type { RpcClientContextValue } from './rpc-client-context-contract' const Ctx = createContext(null) diff --git a/mobile/src/transport/connection/host-client-context-state.ts b/mobile/src/transport/connection/host-client-context-state.ts index 11732d99f66..879090e7569 100644 --- a/mobile/src/transport/connection/host-client-context-state.ts +++ b/mobile/src/transport/connection/host-client-context-state.ts @@ -4,7 +4,7 @@ import type { HostClientStoreEntry } from './host-entry-opener' import type { RelayHostReachability } from '../relay/relay-host-reachability' import type { MobileConnectionPath, StableLogicalRpcClient } from './stable-logical-rpc-client' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' export type CloseEntryOptions = { forgetPrimedHost: boolean diff --git a/mobile/src/transport/connection/host-client-hooks.ts b/mobile/src/transport/connection/host-client-hooks.ts index 97822e2f823..77bf0d169b1 100644 --- a/mobile/src/transport/connection/host-client-hooks.ts +++ b/mobile/src/transport/connection/host-client-hooks.ts @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react' import type { RpcClient } from '../rpc/rpc-client-contract' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import type { HostClientAcquisition } from './host-client-acquisition-registry' import type { ForceReconnect } from './rpc-client-context-contract' import { useRpcClientContext } from './client-context' diff --git a/mobile/src/transport/connection/host-entry-opener.ts b/mobile/src/transport/connection/host-entry-opener.ts index 32f15c23b7b..45ef9d3abad 100644 --- a/mobile/src/transport/connection/host-entry-opener.ts +++ b/mobile/src/transport/connection/host-entry-opener.ts @@ -1,18 +1,18 @@ import { attachPushRegistration } from '../../notifications/push-registration' -import { recordHostDescriptorFromStatus } from '../hosts/host-descriptor-recorder' +import { recordHostDescriptorFromStatus } from '../../host-descriptors/host-descriptor-recorder' import { startRuntimeStatusProbe } from './runtime-status-probe' import { connectionLogStore, recordConnectionClientSessionStart } from '../../diagnostics/connection/persisted-connection-log-store' -import { loadHosts } from '../hosts/host-store' +import { loadHosts } from '../../host-catalog/host-store' import { openHostLogicalClient } from './host-logical-client' import type { HostClientOpenRegistry } from './host-client-open-registry' import type { HostOpenRetryScheduler } from './host-open-retry-scheduler' import type { RpcClient } from '../rpc/rpc-client-contract' import type { StableLogicalRpcClient } from './stable-logical-rpc-client' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' export type HostClientStoreEntry = { client: RpcClient diff --git a/mobile/src/transport/connection/host-logical-client.ts b/mobile/src/transport/connection/host-logical-client.ts index 0474f2f4bc2..33c04a48610 100644 --- a/mobile/src/transport/connection/host-logical-client.ts +++ b/mobile/src/transport/connection/host-logical-client.ts @@ -4,7 +4,7 @@ import { connect } from '../rpc/direct-rpc-connect' import type { RpcClient } from '../rpc/rpc-client-contract' import { createStableLogicalRpcClient } from './stable-logical-rpc-client' import type { ConnectionLogSink } from '../../diagnostics/connection/connection-log-types' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import { directPathForEndpoint } from '../relay/mobile-direct-endpoint-probe' import { startMobileEndpointLifecycle } from './mobile-endpoint-lifecycle' import { watchHostRevocation } from './host-revocation-watch' diff --git a/mobile/src/transport/connection/host-status-gates.test.ts b/mobile/src/transport/connection/host-status-gates.test.ts index 270066f69de..ca1182cafaf 100644 --- a/mobile/src/transport/connection/host-status-gates.test.ts +++ b/mobile/src/transport/connection/host-status-gates.test.ts @@ -6,13 +6,13 @@ import { useHostStatusGates, type HostStatusGates } from './host-status-gates' const recordHostAppVersionMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)) -vi.mock('../hosts/host-app-version-store', () => ({ +vi.mock('../../host-descriptors/host-app-version-store', () => ({ recordHostAppVersion: (...args: unknown[]) => recordHostAppVersionMock(...args) })) const recordDescriptorFromStatusMock = vi.hoisted(() => vi.fn()) -vi.mock('../hosts/host-descriptor-recorder', () => ({ +vi.mock('../../host-descriptors/host-descriptor-recorder', () => ({ recordHostDescriptorFromStatus: (...args: unknown[]) => recordDescriptorFromStatusMock(...args) })) diff --git a/mobile/src/transport/connection/host-status-gates.ts b/mobile/src/transport/connection/host-status-gates.ts index efb53eb46d9..053fe99c095 100644 --- a/mobile/src/transport/connection/host-status-gates.ts +++ b/mobile/src/transport/connection/host-status-gates.ts @@ -3,9 +3,9 @@ import type { RpcClient } from '../rpc/rpc-client-contract' import type { ConnectionState } from './connection-state' import { evaluateCompat, type CompatVerdict } from './protocol-compat' import { hostStatusSchema, type HostStatusReply } from '../hosts/host-status-reply-schema' -import { normalizeHostAppVersion } from '../hosts/host-app-version' -import { recordHostAppVersion } from '../hosts/host-app-version-store' -import { recordHostDescriptorFromStatus } from '../hosts/host-descriptor-recorder' +import { normalizeHostAppVersion } from '../../host-descriptors/host-app-version' +import { recordHostAppVersion } from '../../host-descriptors/host-app-version-store' +import { recordHostDescriptorFromStatus } from '../../host-descriptors/host-descriptor-recorder' import { readConnectionStatusProbe, startRuntimeStatusProbe } from './runtime-status-probe' export type HostStatusGates = { diff --git a/mobile/src/transport/connection/mobile-endpoint-lifecycle.ts b/mobile/src/transport/connection/mobile-endpoint-lifecycle.ts index b635b808ec5..d1e0db84585 100644 --- a/mobile/src/transport/connection/mobile-endpoint-lifecycle.ts +++ b/mobile/src/transport/connection/mobile-endpoint-lifecycle.ts @@ -1,7 +1,7 @@ import * as ExpoCrypto from 'expo-crypto' import type { ConnectionLogSink } from '../../diagnostics/connection/connection-log-types' import type { ForegroundNudgeReason } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import { connect } from '../rpc/direct-rpc-connect' import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor' @@ -10,8 +10,8 @@ import { resolveMobileRelayEndpoint } from '../relay/mobile-relay-resume-directo import { readMobileRelayCredentialBundle, writeMobileRelayCredentialBundle -} from '../hosts/mobile-relay-credential-bundle' -import { setRelayRouting } from '../hosts/host-store' +} from '../../host-credentials/mobile-relay-credential-bundle' +import { setRelayRouting } from '../../host-catalog/host-store' import { lastGoodPathWasDirectHere, readLocalNetworkFingerprint, diff --git a/mobile/src/transport/connection/mobile-endpoint-supervisor-contract.ts b/mobile/src/transport/connection/mobile-endpoint-supervisor-contract.ts index 36b984aa29b..ea3b258b000 100644 --- a/mobile/src/transport/connection/mobile-endpoint-supervisor-contract.ts +++ b/mobile/src/transport/connection/mobile-endpoint-supervisor-contract.ts @@ -1,7 +1,7 @@ import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' import type { RelayHostCloseReason } from '../../../../src/shared/relay-host-close-reason' import type { HostGoodPath } from './host-path-memory' -import type { MobileRelayCredentialBundle } from '../hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import type { MobileRelayRpcSession } from '../relay/mobile-relay-rpc-session-contract' import type { resolveMobileRelayEndpoint } from '../relay/mobile-relay-resume-director' import type { RpcClient } from '../rpc/rpc-client-contract' diff --git a/mobile/src/transport/connection/mobile-endpoint-supervisor-test-fakes.ts b/mobile/src/transport/connection/mobile-endpoint-supervisor-test-fakes.ts index 8ba5f3bb97d..2a36822bb9a 100644 --- a/mobile/src/transport/connection/mobile-endpoint-supervisor-test-fakes.ts +++ b/mobile/src/transport/connection/mobile-endpoint-supervisor-test-fakes.ts @@ -1,5 +1,5 @@ import { vi } from 'vitest' -import type { MobileRelayCredentialBundle } from '../hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import type { MobileRelayRpcSession } from '../relay/mobile-relay-rpc-session-contract' import { RelayDialStageTracker, type RelayDialStage } from '../relay/relay-dial-stage' import { defaultCancelTimer, defaultScheduleTimer } from '../../platform/timer-scheduler' @@ -9,7 +9,7 @@ import type { SendRequestOptions } from '../rpc/unvalidated-rpc-request-port' import type { RelayHostReachability } from '../relay/relay-host-reachability' import type { MobileConnectionPath, StableLogicalRpcClient } from './stable-logical-rpc-client' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import type { RpcResponse } from '../rpc/rpc-wire-types' export class FakeSession implements RpcClient { diff --git a/mobile/src/transport/connection/mobile-endpoint-supervisor.ts b/mobile/src/transport/connection/mobile-endpoint-supervisor.ts index afaaf820b14..9df18632cd9 100644 --- a/mobile/src/transport/connection/mobile-endpoint-supervisor.ts +++ b/mobile/src/transport/connection/mobile-endpoint-supervisor.ts @@ -13,7 +13,7 @@ import { mobileRelayCredentialNeedsRotation, rotateMobileRelayCredential } from '../relay/mobile-relay-credential-rotation' -import type { MobileRelayCredentialBundle } from '../hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import { MobileEndpointNudgeRouter } from './mobile-endpoint-nudge-router' import { MobileRelayDirectGraceTimer } from '../relay/mobile-relay-direct-grace-timer' import { MobileRelaySessionEstablisher } from '../relay/mobile-relay-session-establisher' diff --git a/mobile/src/transport/connection/rpc-client-context-contract.ts b/mobile/src/transport/connection/rpc-client-context-contract.ts index 0db36f943e7..5675916e30b 100644 --- a/mobile/src/transport/connection/rpc-client-context-contract.ts +++ b/mobile/src/transport/connection/rpc-client-context-contract.ts @@ -3,7 +3,7 @@ import type { RpcClient } from '../rpc/rpc-client-contract' import type { RelayHostReachability } from '../relay/relay-host-reachability' import type { MobileConnectionPath } from './stable-logical-rpc-client' import type { ConnectionState } from './connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' /** Re-dials one host. `null` where this document cannot dial: the page's shell owns the connection. */ export type ForceReconnect = ((hostId: string) => Promise) | null diff --git a/mobile/src/transport/hosts/home-host-auto-connect.ts b/mobile/src/transport/hosts/home-host-auto-connect.ts index 08e69879865..53a67400cd8 100644 --- a/mobile/src/transport/hosts/home-host-auto-connect.ts +++ b/mobile/src/transport/hosts/home-host-auto-connect.ts @@ -1,5 +1,5 @@ import type { ConnectionState } from '../connection/connection-state' -import type { HostProfile } from './host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' export const HOME_AUTO_CONNECT_LIMIT = 3 diff --git a/mobile/src/transport/hosts/host-open-recovery.test.tsx b/mobile/src/transport/hosts/host-open-recovery.test.tsx index 782f2c348f9..9ff6210e629 100644 --- a/mobile/src/transport/hosts/host-open-recovery.test.tsx +++ b/mobile/src/transport/hosts/host-open-recovery.test.tsx @@ -20,7 +20,7 @@ vi.mock('../connection/runtime-status-probe', () => ({ vi.mock('../connection/host-logical-client', () => ({ openHostLogicalClient: (...args: unknown[]) => openHostLogicalClientMock(...args) })) -vi.mock('./host-store', () => ({ +vi.mock('../../host-catalog/host-store', () => ({ loadHosts: () => loadHostsMock() })) vi.mock('../../diagnostics/connection/connection-revival-triggers', () => ({ diff --git a/mobile/src/transport/hosts/pairing-keychain.test.ts b/mobile/src/transport/hosts/pairing-keychain.test.ts deleted file mode 100644 index 1bc92703683..00000000000 --- a/mobile/src/transport/hosts/pairing-keychain.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const asyncStorageMock = vi.hoisted(() => ({ - getItem: vi.fn(), - setItem: vi.fn(), - removeItem: vi.fn() -})) - -const secureStoreMock = vi.hoisted(() => ({ - deleteItemAsync: vi.fn(), - getItemAsync: vi.fn(), - setItemAsync: vi.fn() -})) -const platformMock = vi.hoisted(() => ({ OS: 'android' })) - -vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorageMock })) - -vi.mock('expo-secure-store', () => ({ - WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY', - ...secureStoreMock -})) -vi.mock('react-native', () => ({ Platform: platformMock })) - -import { resetPairingKeychainForTests, writePairingKeychainItem } from './pairing-keychain' - -const GENERATION_KEY = 'orca:pairing-keychain-generation' -const TOKEN_KEY = 'orca.host-token.host-1782629088232' - -// Preserve Expo’s null-message Android GeneralSecurityException shape from #6600. -const ENCRYPT_REJECTION = new Error( - `Could not encrypt the value for key '${TOKEN_KEY}' under keychain 'key_v1'. Caused by: unknown` -) - -describe('pairing keychain', () => { - let generationRecord: string | null - - beforeEach(() => { - vi.clearAllMocks() - resetPairingKeychainForTests() - platformMock.OS = 'android' - generationRecord = null - asyncStorageMock.getItem.mockImplementation(async (key: string) => - key === GENERATION_KEY ? generationRecord : null - ) - asyncStorageMock.setItem.mockImplementation(async (key: string, raw: string) => { - if (key === GENERATION_KEY) { - generationRecord = raw - } - }) - secureStoreMock.setItemAsync.mockResolvedValue(undefined) - secureStoreMock.deleteItemAsync.mockResolvedValue(undefined) - secureStoreMock.getItemAsync.mockResolvedValue(null) - }) - - it('surfaces the original error when a rotated write also fails', async () => { - secureStoreMock.setItemAsync.mockRejectedValue(ENCRYPT_REJECTION) - - await expect(writePairingKeychainItem(TOKEN_KEY, 'token')).rejects.toBe(ENCRYPT_REJECTION) - expect(generationRecord).toBe('1:pending') - expect(secureStoreMock.deleteItemAsync).not.toHaveBeenCalled() - }) - - it('does not rotate from a guessed generation when the record is unreadable', async () => { - const storageError = new Error('storage unavailable') - asyncStorageMock.getItem.mockRejectedValueOnce(storageError) - - await expect(writePairingKeychainItem(TOKEN_KEY, 'token')).rejects.toBe(storageError) - - expect(asyncStorageMock.setItem).not.toHaveBeenCalled() - expect(secureStoreMock.setItemAsync).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/transport/relay/mobile-relay-credential-rotation.ts b/mobile/src/transport/relay/mobile-relay-credential-rotation.ts index e15157dfdd9..a9ff541f02f 100644 --- a/mobile/src/transport/relay/mobile-relay-credential-rotation.ts +++ b/mobile/src/transport/relay/mobile-relay-credential-rotation.ts @@ -6,7 +6,7 @@ import type { import { MobileRelayCredentialBundleSchema, type MobileRelayCredentialBundle -} from '../hosts/mobile-relay-credential-bundle' +} from '../../host-credentials/mobile-relay-credential-bundle' import { hashMobileRelayCredential } from './mobile-relay-credential-hash' import { relayCredentialProvision, diff --git a/mobile/src/transport/relay/mobile-relay-credential-selection.ts b/mobile/src/transport/relay/mobile-relay-credential-selection.ts index 8d216028ca0..8952401e8b5 100644 --- a/mobile/src/transport/relay/mobile-relay-credential-selection.ts +++ b/mobile/src/transport/relay/mobile-relay-credential-selection.ts @@ -1,4 +1,4 @@ -import type { MobileRelayCredentialBundle } from '../hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import type { RelayReconnectController } from './mobile-relay-reconnect-controller' // Adopt durable state only when it restores a dialable credential; fresh renewals/re-pairing do not reliably increase version. diff --git a/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.test.ts b/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.test.ts index 2864cb76633..6e6b18fe684 100644 --- a/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.test.ts +++ b/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.test.ts @@ -3,7 +3,7 @@ import { MobileRelayDirectUpgradeController } from './mobile-relay-direct-upgrad import type { MobileRelayDirectUpgradeResult } from './mobile-relay-direct-upgrade' import type { StableLogicalRpcClient } from '../connection/stable-logical-rpc-client' import type { ConnectionState } from '../connection/connection-state' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' const directHost: HostProfile = { id: 'host-direct', diff --git a/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.ts b/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.ts index 28c1d1816ce..81b8fd9a9c2 100644 --- a/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.ts +++ b/mobile/src/transport/relay/mobile-relay-direct-upgrade-controller.ts @@ -1,6 +1,6 @@ import type { MobileRelayDirectUpgradeResult } from './mobile-relay-direct-upgrade' import type { StableLogicalRpcClient } from '../connection/stable-logical-rpc-client' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' type Dependencies = { upgrade: ( diff --git a/mobile/src/transport/relay/mobile-relay-direct-upgrade-journal.ts b/mobile/src/transport/relay/mobile-relay-direct-upgrade-journal.ts index abab5a05ca5..8d963663eff 100644 --- a/mobile/src/transport/relay/mobile-relay-direct-upgrade-journal.ts +++ b/mobile/src/transport/relay/mobile-relay-direct-upgrade-journal.ts @@ -5,8 +5,8 @@ import { deletePairingKeychainItem, readPairingKeychainItem, writePairingKeychainItem -} from '../hosts/pairing-keychain' -import { markHostCredentialWrite } from '../hosts/host-credential-write-revision' +} from '../../host-credentials/pairing-keychain' +import { markHostCredentialWrite } from '../../host-credentials/host-credential-write-revision' const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) diff --git a/mobile/src/transport/relay/mobile-relay-direct-upgrade.ts b/mobile/src/transport/relay/mobile-relay-direct-upgrade.ts index 6fc49039c16..f4cb7d6ad6b 100644 --- a/mobile/src/transport/relay/mobile-relay-direct-upgrade.ts +++ b/mobile/src/transport/relay/mobile-relay-direct-upgrade.ts @@ -4,13 +4,13 @@ import type { MobileRelayEndpoint, PairingGetEndpointsResult } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' -import { RelayRoutingHostRemovedError, setRelayRouting } from '../hosts/host-store' +import { RelayRoutingHostRemovedError, setRelayRouting } from '../../host-catalog/host-store' import { MobileRelayCredentialBundleSchema, deleteMobileRelayCredentialBundle, writeMobileRelayCredentialBundle, type MobileRelayCredentialBundle -} from '../hosts/mobile-relay-credential-bundle' +} from '../../host-credentials/mobile-relay-credential-bundle' import { createMobileRelayDirectUpgradeJournal, deleteMobileRelayDirectUpgradeJournal, @@ -23,7 +23,7 @@ import { relayPairingEndpointsRead } from '../../pairing/mobile-relay-pairing-operations' import type { RpcClient } from '../rpc/rpc-client-contract' -import type { HostProfile } from '../hosts/host-profile' +import type { HostProfile } from '../../host-catalog/host-profile' import { isPairingRelayRpcUnavailable } from '../../pairing/pairing-relay-rpc-unavailable' export type MobileRelayDirectUpgradeResult = { diff --git a/mobile/src/transport/relay/mobile-relay-orphan-cleanup.ts b/mobile/src/transport/relay/mobile-relay-orphan-cleanup.ts index 0b909a2940a..9d5a984139e 100644 --- a/mobile/src/transport/relay/mobile-relay-orphan-cleanup.ts +++ b/mobile/src/transport/relay/mobile-relay-orphan-cleanup.ts @@ -1,5 +1,5 @@ -import { scheduleHostCredentialCleanup } from '../hosts/host-credential-cleanup' -import { removeMobileRelayHostRouting } from '../hosts/mobile-relay-host-overlay-store' +import { scheduleHostCredentialCleanup } from '../../host-credentials/host-credential-cleanup' +import { removeMobileRelayHostRouting } from '../../host-catalog/mobile-relay-host-overlay-store' export async function scheduleOrphanedMobileRelayCleanup(args: { hostIds: string[] diff --git a/mobile/src/transport/relay/mobile-relay-recovery-presentation.ts b/mobile/src/transport/relay/mobile-relay-recovery-presentation.ts index e83994e7411..54da4de3edd 100644 --- a/mobile/src/transport/relay/mobile-relay-recovery-presentation.ts +++ b/mobile/src/transport/relay/mobile-relay-recovery-presentation.ts @@ -1,4 +1,4 @@ -import type { MobileRelayCredentialBundle } from '../hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import type { RelayReconnectController } from './mobile-relay-reconnect-controller' import type { StableLogicalRpcClient } from '../connection/stable-logical-rpc-client' import type { ConnectionState } from '../connection/connection-state' diff --git a/mobile/src/transport/relay/mobile-relay-session-establisher.ts b/mobile/src/transport/relay/mobile-relay-session-establisher.ts index f370b56af89..ab0a580b764 100644 --- a/mobile/src/transport/relay/mobile-relay-session-establisher.ts +++ b/mobile/src/transport/relay/mobile-relay-session-establisher.ts @@ -7,7 +7,7 @@ import { import { encodeBase64Url } from '../encryption/mobile-session-id-encoding' import { persistResumeConfirmation } from './mobile-relay-credential-rotation' import { relayFailureAllowsGraceRetry } from './relay-credential-eligibility' -import type { MobileRelayCredentialBundle } from '../hosts/mobile-relay-credential-bundle' +import type { MobileRelayCredentialBundle } from '../../host-credentials/mobile-relay-credential-bundle' import type { RelayReconnectController } from './mobile-relay-reconnect-controller' import type { StableLogicalRpcClient } from '../connection/stable-logical-rpc-client' import type { MobileRelayEndpoint } from '../../../../src/shared/remote-runtime/relay/mobile-relay-credential-contract' diff --git a/mobile/src/transport/rpc/rpc-operation-contract.ts b/mobile/src/transport/rpc/rpc-operation-contract.ts index d7c49f89ec5..4434da3bfa9 100644 --- a/mobile/src/transport/rpc/rpc-operation-contract.ts +++ b/mobile/src/transport/rpc/rpc-operation-contract.ts @@ -2,8 +2,6 @@ import type { RpcAcceptedResult } from './rpc-accepted-result' import type { RpcMethodName } from '../../../../src/shared/rpc-contract/rpc-params-catalog.generated' import type { RpcFailure, RpcResponse, RpcSuccess } from './rpc-wire-types' -export type { RpcAcceptedResult } - // Fix method, acceptance and interpretation barrier per family so callers cannot drift in decoding or settlement order. export type RpcAcceptanceName = diff --git a/mobile/src/transport/rpc/rpc-operation-sender.ts b/mobile/src/transport/rpc/rpc-operation-sender.ts deleted file mode 100644 index 1d39f8ff9c7..00000000000 --- a/mobile/src/transport/rpc/rpc-operation-sender.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { settingsRead } from '../../settings/mobile-settings-read-operations' - -// Derive the operation’s sender without exposing the raw port or requiring a complete RpcClient in tests. -export type RpcOperationSender = Parameters[0] diff --git a/mobile/src/transport/rpc/rpc-uninterpreted-reply-schemas.ts b/mobile/src/transport/rpc/rpc-uninterpreted-reply-schemas.ts index e99fdbad5bb..87f8b84d347 100644 --- a/mobile/src/transport/rpc/rpc-uninterpreted-reply-schemas.ts +++ b/mobile/src/transport/rpc/rpc-uninterpreted-reply-schemas.ts @@ -1,5 +1,4 @@ import * as z from 'zod' -import '../../../../src/shared/zod-salvage' // Leave unread replies opaque; structured creates/probes require raw-envelope uncertainty checks at their callers. export const sessionLaunchUnreadReplySchema = z.unknown() diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts index 2df9a40a4e7..6561607b409 100644 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts +++ b/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts @@ -56,7 +56,6 @@ function brotliHost() { totalBytes: assets.reduce((total, entry) => total + entry.byteLength, 0), assets } - const methods: string[] = [] const answer = (method: string, params: Record): unknown => { if (method === 'mobileWeb.bundle.manifest') { return { manifest, chunkBytes: RANGE_BYTES, rangeBytes: RANGE_BYTES } @@ -79,7 +78,6 @@ function brotliHost() { } const client: RpcClient = { sendRequest: vi.fn(async (method: string, params?: unknown): Promise => { - methods.push(method) const fields: Record = Object(params) return { id: 'rpc-1', ok: true, result: answer(method, fields), _meta: { runtimeId: 'r' } } }), @@ -92,7 +90,7 @@ function brotliHost() { notifyForeground: vi.fn(), close: vi.fn() } - return { client, methods } + return { client } } describe('fetchMobileWebBundle from a host that ships brotli copies', () => { @@ -107,10 +105,6 @@ describe('fetchMobileWebBundle from a host that ships brotli copies', () => { expect(new TextDecoder().decode(fetched.assets.get('assets/script.js'))).toBe(SCRIPT) expect(new TextDecoder().decode(fetched.assets.get('index.html'))).toBe(MARK) - expect(host.methods.filter((method) => method === 'mobileWeb.bundle.brotliRange')).toHaveLength( - 3 - ) - expect(host.methods.filter((method) => method === 'mobileWeb.bundle.range')).toHaveLength(1) // The 46-byte copy plus the 12-byte mark, not the 1,332 bytes they inflate to. expect(progress.at(-1)).toMatchObject({ receivedBytes: 58, totalBytes: 58 }) }) diff --git a/mobile/src/worktree/session-worktree-record-operations.ts b/mobile/src/worktree/session-worktree-record-operations.ts index 5931ca217e6..b2d75f24af1 100644 --- a/mobile/src/worktree/session-worktree-record-operations.ts +++ b/mobile/src/worktree/session-worktree-record-operations.ts @@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/r import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' import '../terminal/terminal-reply-schema' import { sessionWorktreeRecordSchema } from './session-worktree-record-reply-schema' -import '../session/agent-launch/mobile-agent-detection-reply-schema' -import '../files/session-documents/mobile-markdown-tab-reply-schema' -import '../transport/rpc/rpc-uninterpreted-reply-schemas' -import '../terminal/session/mobile-session-terminal-reply-schema' -import '../session/native-chat/composer/mobile-native-chat-skill-reply-schema' -import '../terminal/quick-commands/mobile-quick-command-reply-schema' -import '../files/workspace-file-paths-reply-schema' // Read the whole worktree for notes and live title; unlike mutation readers, absent records need no error or wrong-host fallback. export const sessionWorktreeRecordRead = bindDeferredRpcOperation( diff --git a/mobile/web-entry/web-overrides.json b/mobile/web-entry/web-overrides.json index 954c12892fb..52e4bca5ba5 100644 --- a/mobile/web-entry/web-overrides.json +++ b/mobile/web-entry/web-overrides.json @@ -26,19 +26,23 @@ "reason": "The page is one document standing in for one screen, so a route it does not render has to be handed to the app that does. The native file is the router; this one posts a navigate notify for a target outside the page's routes and pushes locally for one inside them." }, { - "file": "src/transport/hosts/host-store.web.ts", + "file": "src/host-catalog/host-store.web.ts", "reason": "expo-secure-store resolves to {} on web, so the real store answers loadHosts() with an empty array and every screen that looks this host up paints \"Host not found\" over the host the shell just opened. This one serves the profile init carried, without the credential the bridge already holds." }, { - "file": "src/transport/hosts/host-descriptor-persistence.web.ts", + "file": "src/host-catalog/host-connection-history.web.ts", + "reason": "Recency belongs to the native host list. The host-served page retains the existing no-op and imports no native metadata mutation queue." + }, + { + "file": "src/host-descriptors/host-descriptor-persistence.web.ts", "reason": "Last-known descriptors belong to the native host list; the page owns no descriptor persistence." }, { - "file": "src/transport/hosts/host-removal-lifecycle.web.ts", + "file": "src/host-catalog/host-removal-lifecycle.web.ts", "reason": "Removing a host is pairing work and the page holds neither the host list nor the credential, so the real lifecycle's removeHost resolved without doing anything and the screen reported success for a host that was still paired. This one refuses with PageHostRemovalUnavailableError, whose message names the app's host list. It is also the fence that keeps push-registration.ts out of the page bundle: the native file's import of it was that subsystem's only path into a page route, and the page has neither the device token nor the gateway client push needs." }, { - "file": "src/transport/hosts/host-device-token-store.web.ts", + "file": "src/host-credentials/host-device-token-store.web.ts", "reason": "expo-secure-store resolves to {} on web, and the bridge carries the RPC, so the page holds no device token." }, { @@ -198,7 +202,7 @@ "reason": "react-native-web's keydown handler withholds onSubmitEditing whenever the Enter keydown reports a composition — nativeEvent.isComposing, or the Android keyCode 229 that stands for it — which is a soft keyboard's normal state mid-word, so Enter on the page neither sent the line nor cleared the field while native Android's editor action fired as it always does. Both terminal fields reach their send through onSubmitEditing alone and both are bound here: the live input's carriage return, and the buffered command field's draft. The native file binds nothing, because that editor action needs no help; this one listens for beforeinput and acts on insertLineBreak and insertParagraph, the browser's own end-of-line signals. react-native-web calls preventDefault on every keydown it does submit on, so those events exist only in the cases it dropped and never produce a second carriage return; an IME still choosing a candidate reports insertCompositionText and is left alone." }, { - "file": "src/transport/hosts/host-app-version-store.web.ts", + "file": "src/host-descriptors/host-app-version-store.web.ts", "reason": "The page keeps no record of the host's status.get app version because nothing in it reads one — the reader is the native troubleshoot screen's — and a key the page only writes is not page state, so it is not admitted through page-storage-keys.ts and every mount's write was refused and logged instead." }, { diff --git a/package.json b/package.json index 79d88915ab6..784cd2650f5 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "check:repo-host-read-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-repo-host-read-ratchet.mjs", "check:workspace-record-read-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-workspace-record-read-ratchet.mjs", "check:tab-map-seam-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs", + "check:terminal-parking-ownership-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs", "check:worktree-id-composer-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-worktree-id-composer-ratchet.mjs", "check:direct-link-open-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-direct-link-open-ratchet.mjs", "check:e2e-typecheck-ratchet": "node config/scripts/typecheck/e2e-admission/check-e2e-typecheck-ratchet.mjs", diff --git a/src/main/__mocks__/worktree-create-preparation.ts b/src/main/__mocks__/worktree-create-preparation.ts index 56ca76c48c4..56a77a58b19 100644 --- a/src/main/__mocks__/worktree-create-preparation.ts +++ b/src/main/__mocks__/worktree-create-preparation.ts @@ -34,14 +34,18 @@ const mocks: { export { mocks } -vi.mock('node:fs/promises', () => ({ mkdir: mocks.mkdir })) +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal>()), + mkdir: mocks.mkdir +})) vi.mock('../orcad/orcad-data-root-locality', () => ({ orcadDataRootIsOnLocalDisk: () => true })) vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ ...(await importOriginal>()), listWorktreeGraph: mocks.listWorktreeGraph })) -vi.mock('../git/worktrees/creation/worktree-create-preparation', () => ({ +vi.mock('../git/worktrees/creation/worktree-create-preparation', async (importOriginal) => ({ + ...(await importOriginal>()), prepareWorktreeCreateCheckout: mocks.prepareCheckout, finalizePreparedWorktree: mocks.finalize, discardPreparedWorktree: mocks.discard, @@ -90,10 +94,14 @@ export const store = { getSettings: () => ({}) } as unknown as Store beforeEach(() => { mocks.mkdir.mockReset().mockResolvedValue(undefined) mocks.listWorktreeGraph.mockReset().mockResolvedValue([]) - mocks.prepareCheckout.mockReset().mockResolvedValue(undefined) + mocks.prepareCheckout + .mockReset() + .mockImplementation(async (repo, path, _base, reason, _options, _barrier, operation) => { + operation?.setDiscard((options) => mocks.discard(repo, path, options, reason, null)) + }) mocks.refreshTip.mockReset().mockResolvedValue(undefined) mocks.finalize.mockReset().mockResolvedValue({}) - mocks.discard.mockReset().mockResolvedValue(undefined) + mocks.discard.mockReset().mockResolvedValue('removed') mocks.unlock.mockReset().mockResolvedValue(undefined) mocks.getWorktreeOptions.mockReset().mockReturnValue({}) mocks.measureDivergence.mockReset().mockResolvedValue('within') diff --git a/src/main/claude/claude-child-work-roster-performance.test.ts b/src/main/claude/claude-child-work-roster-performance.test.ts deleted file mode 100644 index 36f68abfa97..00000000000 --- a/src/main/claude/claude-child-work-roster-performance.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { expect, it } from 'vitest' -import { ClaudeChildWorkDecoder } from './claude-child-work-decoder' -import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store' -import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission' -import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation' -import { parent } from './claude-child-work-producer-harness.test-fixture' - -it('emits only new or changed roster facts at10 and100 live tasks', () => { - for (const count of [10, 100]) { - const decoder = new ClaudeChildWorkDecoder() - const store = createAgentStatusStore({ epoch: 'roster-perf', mode: 'authority' }) - store.applyMutation({ parent: { subject: parent } }) - let minted = 0 - const admission = createAgentChildWorkAdmission(store, { - mintChildWorkId: () => `child-${++minted}` - }) - let clock = 1_700_000_000_000 - let rosterEdges = 0 - let rosterWrites = 0 - const feed = (message: Record, rosterBound = 0) => { - decoder.observe({ type: 'system', ...message }) - const evidence = decoder.drain(++clock) - const before = store.getSnapshot().revision - reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence }) - const writes = store.getSnapshot().revision - before - if (message.subtype === 'background_tasks_changed') { - const live = evidence.filter((edge) => edge.type === 'live').length - expect(live).toBeLessThanOrEqual(rosterBound) - expect(writes).toBeLessThanOrEqual(rosterBound) - rosterEdges += live - rosterWrites += writes - } - } - const owner = { - task_id: 'owner', - task_type: 'local_agent', - tool_use_id: 'tool-owner', - is_backgrounded: true - } - feed({ subtype: 'task_started', ...owner }) - let shellOwner = 'owner' - const shell = (id: number) => ({ - task_id: `shell-${id}`, - task_type: 'local_bash', - description: `shell${id}`, - parent_task_id: shellOwner - }) - const live: number[] = [] - for (let id = 0; id < count; id++) { - live.push(id) - const roster = { subtype: 'background_tasks_changed', tasks: [owner, ...live.map(shell)] } - // Only one task is newly present; unchanged replacement rosters need no host writes. - feed(roster, 1) - feed({ - subtype: 'task_started', - ...shell(id), - tool_use_id: `tool-${id}`, - is_backgrounded: true - }) - feed(roster) - } - // The introductions above need at most one edge/write each, independent of full-roster size. - expect(rosterEdges).toBeLessThanOrEqual(count) - expect(rosterWrites).toBeLessThanOrEqual(count) - rosterEdges = 0 - rosterWrites = 0 - feed({ subtype: 'task_started', ...owner, task_id: 'owner-second', tool_use_id: 'tool-second' }) - shellOwner = 'owner-second' - // A real owner change invalidates exactly the affected children, then its duplicate invalidates none. - feed({ subtype: 'background_tasks_changed', tasks: live.map(shell) }, count) - feed({ subtype: 'background_tasks_changed', tasks: live.map(shell) }) - for (let id = 0; id < count; id++) { - feed({ - subtype: 'task_notification', - task_id: `shell-${id}`, - tool_use_id: `tool-${id}`, - status: 'completed' - }) - live.shift() - feed({ subtype: 'background_tasks_changed', tasks: [owner, ...live.map(shell)] }) - } - // N introductions require at most N live edges and N store writes, independent of roster size. - expect(rosterEdges).toBeLessThanOrEqual(count) - expect(rosterWrites).toBeLessThanOrEqual(count) - expect(store.getChildren(parent).filter((child) => child.kind === 'command')).toHaveLength( - count - ) - } -}) diff --git a/src/main/claude/structured/claude-conversation-title-owner.test.ts b/src/main/claude/structured/claude-conversation-title-owner.test.ts index 5a31653bbd5..5b7c3d8e9d1 100644 --- a/src/main/claude/structured/claude-conversation-title-owner.test.ts +++ b/src/main/claude/structured/claude-conversation-title-owner.test.ts @@ -71,27 +71,6 @@ it('reads only cached support and rejects a retired acquisition or changed accou } }) -it.each(['unknown', 'unsupported'] as const)( - 'keeps %s CLIs on the existing generator path', - async (support) => { - const cli = fakeClaude() - const adapter = await acquired(cli, { cliFlag: async () => support }) - try { - const record = agentSessionRecordFixture() - record.sessionId = 'session-1' - record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID - const generate = vi.fn(async () => 'Do not use') - cli.connections[0]!.generateSessionTitle = generate - const owner = adapter.captureConversationTitleOwner(record)! - expect(await owner.generate('Repair login', () => true)).toBeNull() - expect(generate).not.toHaveBeenCalled() - } finally { - await adapter.closeAll() - cli.dispose() - } - } -) - it('retains retirement knowledge when the optional title method is missing', async () => { const cli = fakeClaude() const adapter = await acquired(cli) diff --git a/src/main/daemon/admission/automatic-work-run-marker-store.ts b/src/main/daemon/admission/automatic-work-run-marker-store.ts index f9d3a0cbfcd..c3d929a8a8c 100644 --- a/src/main/daemon/admission/automatic-work-run-marker-store.ts +++ b/src/main/daemon/admission/automatic-work-run-marker-store.ts @@ -62,9 +62,13 @@ export class AutomaticWorkRunMarker { const previous = readPreviousMarker(this.path) this.currentMode = decideStartupAutomaticWorkMode(previous, boot, now) if (this.currentMode.kind === 'paused') { + // A carried-over pause names an earlier death; previousExit says whether this start follows one. this.log('automatic-work-paused', { reason: this.currentMode.reason, - carriedOver: previous?.mode.kind === 'paused' + carriedOver: previous?.mode.kind === 'paused', + pausedSince: new Date(this.currentMode.since).toISOString(), + previousExit: + previous === null ? 'none' : previous.state === 'running' ? 'unclean' : 'clean' }) } this.writeSync(this.armRequested ? 'running' : 'clean-exit') diff --git a/src/main/daemon/admission/testing/automatic-work-run-marker-store.test.ts b/src/main/daemon/admission/testing/automatic-work-run-marker-store.test.ts index 478ca7c4713..7db544a1a3f 100644 --- a/src/main/daemon/admission/testing/automatic-work-run-marker-store.test.ts +++ b/src/main/daemon/admission/testing/automatic-work-run-marker-store.test.ts @@ -57,6 +57,23 @@ describe('AutomaticWorkRunMarker', () => { expect(paused.mode.kind).toBe('paused') }) + // #40328: a pause carried over a clean restart must not read as a fresh crash in the log. + it('logs whether the start that carries a pause followed a clean exit', () => { + open().arm() + open(20).markCleanExit() + logger.log.mockClear() + + expect(open(30).mode).toMatchObject({ kind: 'paused', reason: 'unclean_host_death' }) + expect(logger.log).toHaveBeenCalledWith( + 'automatic-work-paused', + expect.objectContaining({ + carriedOver: true, + previousExit: 'clean', + pausedSince: new Date(20).toISOString() + }) + ) + }) + it('never reads an outside stop as a crash, even when the exit is then cut short', () => { const stopped = open() stopped.arm() diff --git a/src/main/daemon/protocol/daemon-protocol-version.ts b/src/main/daemon/protocol/daemon-protocol-version.ts index d105b2de723..ddb82c4e367 100644 --- a/src/main/daemon/protocol/daemon-protocol-version.ts +++ b/src/main/daemon/protocol/daemon-protocol-version.ts @@ -1,4 +1,5 @@ // Why: daemons survive app updates, so wire behavior must be version-gated. +// v56 accepts `reportFocusLost`; v55 daemons from 1.4.251 predate it and reject the request. // v55 observes the foreground group at the physical PTY owner. // v54 reads the macOS process table in process instead of forking setuid ps on every poll (#31783). // v53 rolls the daemon-side terminal fixes since v1.4.241 (foreground confirmation for chat continuation, ConPTY reflow, WSL malloc tunables) into a fresh daemon. @@ -13,7 +14,8 @@ // v43 dropped it with the revert); v41 stages long startup commands as sourced scripts; v40 rolled // the #25130/#24636 shell-wrapper changes and the wider agent list into a fresh daemon; older owners // stay attachable. -export const PROTOCOL_VERSION = 55 +export const PROTOCOL_VERSION = 56 +export const FOCUS_LOSS_REPORT_PROTOCOL_VERSION = 56 export const PTY_FOREGROUND_OBSERVATION_PROTOCOL_VERSION = 55 export const FENCED_TERMINATION_PROTOCOL_VERSION = 51 export const CLAUDE_ACCOUNT_FUNCTION_DAEMON_PROTOCOL_VERSION = 42 @@ -50,7 +52,7 @@ export const MODE_2031_UNSUBSCRIBE_FACT_PROTOCOL_VERSION = 29 export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, - 52, 53, 54 + 52, 53, 54, 55 ] as const export function supportsColorQueryReplyColors(protocolVersion: number): boolean { @@ -64,3 +66,13 @@ export function supportsPtyStartupIngress(protocolVersion: number): boolean { export function supportsMode2031UnsubscribeFact(protocolVersion: number): boolean { return protocolVersion >= MODE_2031_UNSUBSCRIBE_FACT_PROTOCOL_VERSION } + +export type DaemonRequestSupport = 'supported' | 'unsupported' | 'ask' + +/** `reportFocusLost` shipped inside v55 (1.4.252) without a bump, so only a v55 daemon can tell. */ +export function focusLossReportSupport(protocolVersion: number): DaemonRequestSupport { + if (protocolVersion >= FOCUS_LOSS_REPORT_PROTOCOL_VERSION) { + return 'supported' + } + return protocolVersion === FOCUS_LOSS_REPORT_PROTOCOL_VERSION - 1 ? 'ask' : 'unsupported' +} diff --git a/src/main/daemon/protocol/daemon-rpc-contract.ts b/src/main/daemon/protocol/daemon-rpc-contract.ts index 16d9f117b96..583c1fb41d5 100644 --- a/src/main/daemon/protocol/daemon-rpc-contract.ts +++ b/src/main/daemon/protocol/daemon-rpc-contract.ts @@ -175,7 +175,7 @@ export type TerminalBufferActionRequest = { } } -// Viewers live above the daemon on orcad; an older daemon rejects this, which callers ignore. +// Viewers live above the daemon on orcad; gated by focusLossReportSupport (v56, some v55). export type ReportFocusLostRequest = { id: string type: 'reportFocusLost' diff --git a/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts b/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts index 549b224a66f..17a5682b972 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-connection-lifecycle.ts @@ -70,8 +70,9 @@ export abstract class DaemonPtyConnectionLifecycle extends DaemonPtyEventSubscri return } if (previous) { - // Recheck capabilities for each incarnation: the replacement may support getSize. + // Recheck capabilities for each incarnation: the replacement may support them. this.getSizeUnsupported = false + this.focusLossReportRejected = false } this.lastAuthenticatedIdentity = { ...current } this.exactDaemonIncarnation = exactDaemonIncarnationForPidRecord(current, this.pidRecord) diff --git a/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts b/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts index f0b27ba2992..b6df8de284a 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-runtime-state.ts @@ -123,6 +123,7 @@ export abstract class DaemonPtyRuntimeState { }) protected activeSessionIds = new Set() protected getSizeUnsupported = false + protected focusLossReportRejected = false protected sessionsAwaitingDaemonRecovery = new Set() protected sessionIncarnations = new Map() protected readonly ptyInventory = new DaemonPtyInventoryObservation( diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts index dbcc32fec7e..636ce242edf 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-focus-loss.test.ts @@ -1,34 +1,47 @@ import '../../../pty-subprocess/testing/mock-descendant-sweep' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { rmSync } from 'node:fs' -import type { DaemonServer } from '../../../server/daemon-server' +import { DaemonServer } from '../../../server/daemon-server' import type { DaemonPtyAdapter } from '../daemon-pty-adapter' -import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' +import { + createMockSubprocess, + startDaemonAdapterHarness, + type DaemonAdapterHarness +} from './daemon-pty-adapter-test-harness' const FOCUS_IN = '\x1b[I' const FOCUS_OUT = '\x1b[O' +// 1.4.251 shipped v55 without the request; 1.4.252 added it inside v55. +const UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION = 55 describe('DaemonPtyAdapter.reportFocusLost', () => { - let dir: string - let server: DaemonServer - let adapter: DaemonPtyAdapter + let harness: DaemonAdapterHarness | undefined + let server: DaemonServer | undefined let subprocess: ReturnType - beforeEach(async () => { - const harness = await startDaemonAdapterHarness(() => { - subprocess = createMockSubprocess() - return subprocess - }) - ;({ dir, server, adapter } = harness) - }) + async function start(protocolVersion?: number): Promise { + harness = await startDaemonAdapterHarness( + () => { + subprocess = createMockSubprocess() + return subprocess + }, + protocolVersion === undefined ? {} : { protocolVersion } + ) + server = harness.server + return harness.adapter + } afterEach(async () => { - adapter?.dispose() + harness?.adapter.dispose() await server?.shutdown() - rmSync(dir, { recursive: true, force: true }) + if (harness) { + rmSync(harness.dir, { recursive: true, force: true }) + } + harness = undefined + server = undefined }) - async function focusedSession(): Promise { + async function focusedSession(adapter: DaemonPtyAdapter): Promise { const { id } = await adapter.spawn({ cols: 80, rows: 24 }) subprocess._simulateData('\x1b[?1004h') adapter.write(id, FOCUS_IN) @@ -36,19 +49,11 @@ describe('DaemonPtyAdapter.reportFocusLost', () => { return id } - it('tells the program focus is gone', async () => { - const id = await focusedSession() - - await adapter.reportFocusLost(id) - - expect(subprocess.write).toHaveBeenLastCalledWith(FOCUS_OUT) - }) - - it('leaves a daemon that predates the request, and its session, working', async () => { - const id = await focusedSession() + /** Stands in for a daemon whose router predates the request and rejects it as unknown. */ + function rejectFocusLossReports(daemon: DaemonServer): ReturnType { const router = // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: stands in for an older daemon's router, whose default branch rejects unknown types. - (server as unknown as { requestRouter: { route: (...args: never[]) => unknown } }) + (daemon as unknown as { requestRouter: { route: (...args: never[]) => unknown } }) .requestRouter const route = router.route.bind(router) const rejected = vi.fn() @@ -60,14 +65,62 @@ describe('DaemonPtyAdapter.reportFocusLost', () => { } return route(clientId, request) } + return rejected + } + + it('tells the program focus is gone', async () => { + const adapter = await start() + const id = await focusedSession(adapter) + + await adapter.reportFocusLost(id) + + expect(subprocess.write).toHaveBeenLastCalledWith(FOCUS_OUT) + }) + + it('never asks a daemon from before the request existed', async () => { + const adapter = await start(UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION - 1) + const id = await focusedSession(adapter) + const rejected = rejectFocusLossReports(server!) await expect(adapter.reportFocusLost(id)).resolves.toBeUndefined() - await expect(adapter.reportFocusLost(id)).resolves.toBeUndefined() - adapter.write(id, 'ls\n') - await vi.waitFor(() => expect(subprocess.write).toHaveBeenLastCalledWith('ls\n')) - expect(subprocess.write).not.toHaveBeenCalledWith(FOCUS_OUT) - // The rejection is remembered for this client, so no further requests reach the old daemon. + expect(rejected).not.toHaveBeenCalled() + }) + + it('stops asking a v55 daemon that rejects the request, but asks its replacement', async () => { + const adapter = await start(UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION) + const firstId = await focusedSession(adapter) + const rejected = rejectFocusLossReports(server!) + + await expect(adapter.reportFocusLost(firstId)).resolves.toBeUndefined() + await expect(adapter.reportFocusLost(firstId)).resolves.toBeUndefined() expect(rejected).toHaveBeenCalledTimes(1) + expect(subprocess.write).not.toHaveBeenCalledWith(FOCUS_OUT) + + // A v55 daemon from a later build accepts the request at the same endpoint. + const firstIdentity = adapter.getLastAuthenticatedDaemonIdentity() + await server!.shutdown() + server = new DaemonServer({ + socketPath: harness!.socketPath, + tokenPath: harness!.tokenPath, + protocolVersion: UNVERSIONED_FOCUS_LOSS_PROTOCOL_VERSION, + launchNonce: 'replacement-launch', + startedAtMs: (firstIdentity?.startedAtMs ?? 0) + 10_000, + log: harness!.daemonLog, + spawnSubprocess: () => { + subprocess = createMockSubprocess() + return subprocess + } + }) + await server.start() + await vi.waitFor(async () => { + await adapter.listProcesses() + expect(adapter.getLastAuthenticatedDaemonIdentity()?.launchNonce).toBe('replacement-launch') + }) + const replacementId = await focusedSession(adapter) + + await adapter.reportFocusLost(replacementId) + + expect(subprocess.write).toHaveBeenLastCalledWith(FOCUS_OUT) }) }) diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts index eba2692c31d..d68a8b1834d 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-test-harness.ts @@ -85,7 +85,7 @@ export async function startDaemonAdapterHarness( spawnSubprocess: SpawnSubprocess, adapterOptions: Pick< DaemonPtyAdapterOptions, - 'readRunningWslDistros' | 'historyPath' | 'wslBridgeBootIdentity' + 'readRunningWslDistros' | 'historyPath' | 'wslBridgeBootIdentity' | 'protocolVersion' > = {}, serverOptions: { onPtySessionExit?: (sessionId: string) => void } = {} ): Promise { @@ -102,6 +102,10 @@ export async function startDaemonAdapterHarness( tokenPath, log: daemonLog, spawnSubprocess, + // A daemon and the adapter that reaches it speak the same protocol generation. + ...(adapterOptions.protocolVersion !== undefined + ? { protocolVersion: adapterOptions.protocolVersion } + : {}), ...serverOptions }) await server.start() diff --git a/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts b/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts index c353e9bb36f..3786b13b3c0 100644 --- a/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts +++ b/src/main/daemon/providers/checkpointing/daemon-pty-buffer-snapshots.ts @@ -3,7 +3,7 @@ import { parseTerminalKittyKeyboardFlags } from '../../../../shared/terminal/pro import { boundSnapshot } from './daemon-durable-history-snapshot' import { DaemonPtySessionControl } from '../adapter/daemon-pty-session-control' import { isUnknownRequestTypeError } from '../../endpoint/identity/daemon-endpoint-errors' -import type { DaemonClient } from '../../transport/client/daemon-client' +import { focusLossReportSupport } from '../../protocol/daemon-protocol-version' import { DAEMON_SESSION_SCROLLBACK_ROWS } from '../../sessions/daemon-session-scrollback-window' import type { GetSnapshotResult } from '../../protocol/daemon-rpc-contract' import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' @@ -11,8 +11,6 @@ import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider- const DURABLE_HISTORY_OVERLAY_DEADLINE_MS = 5_000 export abstract class DaemonPtyBufferSnapshots extends DaemonPtySessionControl { - private focusLossUnsupportedBy: DaemonClient | null = null - async getBufferSnapshot( id: string, opts: { scrollbackRows?: number } = {} @@ -186,18 +184,18 @@ export abstract class DaemonPtyBufferSnapshots extends DaemonPtySessionControl { } async reportFocusLost(id: string): Promise { - const client = this.client - if (this.focusLossUnsupportedBy === client) { + const support = focusLossReportSupport(this.protocolVersion) + if (support === 'unsupported' || (support === 'ask' && this.focusLossReportRejected)) { return } try { - await client.request('reportFocusLost', { sessionId: id }) + await this.client.request('reportFocusLost', { sessionId: id }) } catch (error) { - if (!isUnknownRequestTypeError(error)) { + if (support !== 'ask' || !isUnknownRequestTypeError(error)) { throw error } - // Shipped without a protocol bump; recheck once a new client reaches a replacement daemon. - this.focusLossUnsupportedBy = client + // A v55 daemon from 1.4.251 predates the request; its replacement is asked again. + this.focusLossReportRejected = true } } diff --git a/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts b/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts index 0d915631436..1489f753f31 100644 --- a/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts @@ -560,7 +560,7 @@ describe('prepared worktree creation with real Git', () => { controller.abort() await expect( discardPreparedWorktree(repoPath, preparedPath, { signal: controller.signal }, lockReason) - ).resolves.toBeUndefined() + ).resolves.toBe('removed') expect(await listWorktrees(repoPath, { includeCreatePreparations: true })).toHaveLength(1) }) @@ -621,3 +621,65 @@ describe('prepared worktree creation with real Git', () => { ) }) }) + +it.each(['replacement', 'permission'])( + 'preserves the requested path when rollback loses %s authority', + async (kind) => { + const { repoPath, root } = await createRepo() + const prepared = join(root, 'prepared-rollback-authority') + const target = join(root, 'rollback-target') + const preserved = join(root, 'preserved-original') + const reason = createWorktreePreparationLockReason('rollback-authority') + await prepareWorktreeCreateCheckout(repoPath, prepared, 'main', reason) + const originalLock = git(prepared, ['rev-parse', '--git-path', 'locked']) + const failure = new Error('move rewrote pointers but rejected') + const run = gitRunner.gitExecFileAsync + let allowed = true + let replaced = false + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args.includes('move')) { + await run(args, options) + if (kind === 'permission') { + allowed = false + } + throw failure + } + if ( + kind === 'replacement' && + args[0] === 'symbolic-ref' && + options.cwd === target && + !replaced + ) { + replaced = true + git(repoPath, ['worktree', 'move', '-f', '-f', target, preserved]) + git(repoPath, ['worktree', 'add', '--detach', target, 'HEAD']) + git(repoPath, ['worktree', 'lock', '--reason', reason, target]) + await writeFile(join(target, 'user.txt'), 'preserve replacement\n') + } + return run(args, options) + }) + try { + await expect( + finalizePreparedWorktree( + repoPath, + prepared, + target, + 'rollback-authority', + 'main', + false, + { canStart: () => allowed }, + reason + ) + ).rejects.toBe(failure) + expect(await readFile(join(target, 'version.txt'), 'utf8')).toBe('one\n') + if (kind === 'replacement') { + expect(replaced).toBe(true) + expect(await readFile(join(target, 'user.txt'), 'utf8')).toBe('preserve replacement\n') + expect(await readFile(join(preserved, 'version.txt'), 'utf8')).toBe('one\n') + } + expect(await readFile(originalLock, 'utf8')).toBe(`${reason}\n`) + } finally { + vi.restoreAllMocks() + } + } +) diff --git a/src/main/git/worktrees/creation/worktree-create-preparation.ts b/src/main/git/worktrees/creation/worktree-create-preparation.ts index 68c840bf54b..a4f51be50b6 100644 --- a/src/main/git/worktrees/creation/worktree-create-preparation.ts +++ b/src/main/git/worktrees/creation/worktree-create-preparation.ts @@ -1,3 +1,5 @@ +import { runStandalonePreparation } from './worktree-preparation-standalone' +import { performPreparedWorktreeFinalization } from './worktree-preparation-finalization-work' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref' @@ -11,28 +13,20 @@ import { resolveWorktreeAddTimeoutMs, WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS } from '../worktree-operation-options' -import { - configurePushAutoSetupRemote, - persistWorktreeCreationBase, - resolveWorktreeAddBaseContext, - trackSameNameRemoteBase -} from './worktree-add' import { bumpWorktreeScanGeneration as notifyPreparedWorktreeMutation } from '../catalog/worktree-scan-cache' -import { gitCleanupOptions, removeFailedFinalization } from './worktree-preparation-discard' -import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe' import { - runStandalonePreparation, - type WorktreePreparationOperation -} from './worktree-preparation-operation' + gitCleanupOptions, + removeFailedFinalization, + reconcilePreparationLocation, + discardPreparedWorktree as discardOwnedPreparation +} from './worktree-preparation-discard' +import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe' +import { WorktreePreparationOperation } from './worktree-preparation-operation' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' -import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' import { unlockWorktreePreparation, - unlockWorktreePreparationAtPath, - verifyWorktreePreparationLock, - verifyWorktreePreparationLockAtPath, - WorktreePreparationLockOwnershipError + verifyWorktreePreparationLockAtPath } from './worktree-preparation-lock' import { addLockedWorktreePreparation } from './worktree-preparation-add' @@ -139,6 +133,12 @@ export type FinalizedPreparedWorktree = AddWorktreeResult & { preparedHeadReset: boolean } +export class PreparedWorktreeFinalizationPendingError extends Error { + constructor(readonly originalError: unknown) { + super('The prepared checkout still has an unverified target writer.', { cause: originalError }) + } +} + export async function finalizePreparedWorktree( repoPath: string, preparedPath: string, @@ -147,149 +147,110 @@ export async function finalizePreparedWorktree( baseBranch: string, refreshLocalBaseRef = false, options: AddWorktreeOptions = {}, - expectedLockReason: string + expectedLockReason: string, + operation?: WorktreePreparationOperation ): Promise { - const finalizeGitOptions: AddWorktreeOptions = { - ...options, - timeout: options.timeout ?? resolveWorktreeAddTimeoutMs() + const owner = operation ?? new WorktreePreparationOperation(options) + let pendingTarget = false + const captured: { lockPath?: string; targetWriter: boolean } = { targetWriter: false } + if (!operation) { + owner.setDiscard((cleanupOptions) => + discardOwnedPreparation(repoPath, preparedPath, cleanupOptions, expectedLockReason) + ) } try { - return await runWithGitReadCacheInvalidation(async () => { - const lockPath = await verifyWorktreePreparationLock( + const result = await owner.supervise(options, (ownedOptions) => + performPreparedWorktreeFinalization( + repoPath, preparedPath, + worktreePath, + branch, + baseBranch, + refreshLocalBaseRef, + { ...options, ...ownedOptions }, expectedLockReason, - finalizeGitOptions + owner, + captured ) - const verifyOwnership = (): Promise => - verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, finalizeGitOptions.signal) - const [targetResult, preparedResult] = await Promise.allSettled([ - (async () => { - const baseContext = await resolveWorktreeAddBaseContext( - repoPath, - baseBranch, - refreshLocalBaseRef, - finalizeGitOptions, - branch - ) - const targetHead = - baseContext.effectiveBaseOid ?? - ( - await gitExecFileAsync( - ['rev-parse', '--verify', `${baseContext.effectiveBase}^{commit}`], - gitExecOptions(repoPath, finalizeGitOptions) - ) - ).stdout.trim() - return { baseContext, targetHead } - })(), - gitExecFileAsync( - ['rev-parse', '--verify', 'HEAD'], - gitExecOptions(preparedPath, finalizeGitOptions) - ) - ]) - // Settle both reads before failure cleanup can remove the prepared checkout. - if (targetResult.status === 'rejected') { - throw targetResult.reason - } - const { baseContext, targetHead } = targetResult.value - if (preparedResult.status === 'rejected') { - await baseContext.pendingLocalBaseRefRefresh - throw preparedResult.reason - } - const preparedHeadReset = preparedResult.value.stdout.trim() !== targetHead - if (preparedHeadReset) { - await verifyOwnership() - await gitExecFileAsync( - [ - ...(await checkoutWorkersGitArgs(preparedPath, finalizeGitOptions)), - ...windowsLongPathGitArgs(preparedPath), - 'reset', - '--hard', - targetHead - ], - gitExecOptions(preparedPath, finalizeGitOptions) - ) - } - - let moved = false - try { - try { - await verifyOwnership() - // Git >= 2.25 needs two force flags to move a locked preparation without losing its lock reason. - await gitExecFileAsync( - [ - ...windowsLongPathGitArgs(repoPath), - 'worktree', - 'move', - '-f', - '-f', - preparedPath, - worktreePath - ], - gitExecOptions(repoPath, finalizeGitOptions) - ) - moved = true - } finally { - // The move rewrites both `.git` markers, and a failure can have rewritten one. - invalidateWslLinkedWorktreeGitRouting(preparedPath) - invalidateWslLinkedWorktreeGitRouting(worktreePath) + ) + await owner.physicalSettlement() + owner.finishFinalization('disposed') + return result + } catch (error) { + const settled = await owner.waitForPhysicalSettlement() + if (captured.lockPath) { + owner.setDiscard(async (cleanupOptions) => { + if (!captured.lockPath) { + return 'revoked' } - await verifyOwnership() - await gitExecFileAsync( - [ - ...windowsLongPathGitArgs(worktreePath), - 'checkout', - '--no-track', - '-b', - branch, - targetHead - ], - gitExecOptions(worktreePath, finalizeGitOptions) - ) - await verifyOwnership() - await persistWorktreeCreationBase( + const location = await reconcilePreparationLocation( + captured.lockPath, + preparedPath, worktreePath, - branch, - baseContext.effectiveBase, - finalizeGitOptions - ) - await trackSameNameRemoteBase( - worktreePath, - branch, - baseBranch, - baseContext.effectiveBase, - finalizeGitOptions - ) - await configurePushAutoSetupRemote(worktreePath, finalizeGitOptions) - await unlockWorktreePreparationAtPath( - lockPath, expectedLockReason, - finalizeGitOptions.signal + cleanupOptions ) - } catch (error) { - if (!(error instanceof WorktreePreparationLockOwnershipError)) { - await removeFailedFinalization( + if (location === 'hidden') { + return discardOwnedPreparation( repoPath, - moved ? worktreePath : preparedPath, - branch, - moved, - finalizeGitOptions, - expectedLockReason + preparedPath, + cleanupOptions, + expectedLockReason, + captured.lockPath ) } - await baseContext.pendingLocalBaseRefRefresh - throw error + return location === 'target' || location === 'unknown' ? 'revoked' : location + }) + } + if (settled && captured.lockPath) { + const location = await reconcilePreparationLocation( + captured.lockPath, + preparedPath, + worktreePath, + expectedLockReason, + options + ) + if (location === 'target') { + let eligible = true + const rollback = owner.supervise( + { + ...options, + signal: undefined, + canStart: () => eligible && options.canStart?.() !== false + }, + (rollbackOptions) => + removeFailedFinalization( + repoPath, + worktreePath, + branch, + true, + rollbackOptions, + expectedLockReason, + captured.lockPath + ), + true + ) + void rollback.catch(() => {}) + pendingTarget = !(await owner.waitForPhysicalSettlement(() => { + eligible = false + })) + eligible = false + if (!pendingTarget && (await rollback.catch(() => false))) { + owner.finishFinalization('disposed') + } } - // Advisory refresh may settle after finalization; it does not determine checkout contents. - const localBaseRefRefresh = await baseContext.pendingLocalBaseRefRefresh - return { - preparedHeadReset, - ...(localBaseRefRefresh ? { localBaseRefRefresh } : {}), - ...(baseContext.localBaseRefUpdateSuggestion - ? { localBaseRefUpdateSuggestion: baseContext.localBaseRefUpdateSuggestion } - : {}) - } - }) + } else { + pendingTarget = captured.targetWriter + } + owner.finishFinalization(!settled || pendingTarget ? 'pending' : 'failed') + if (!operation) { + await owner.discard() + } + if (pendingTarget && operation) { + throw new PreparedWorktreeFinalizationPendingError(error) + } + throw error } finally { - notifyPreparedWorktreeMutation(repoPath) + owner.finishFinalization() } } diff --git a/src/main/git/worktrees/creation/worktree-preparation-add.ts b/src/main/git/worktrees/creation/worktree-preparation-add.ts index 41bd1315650..55c8f66e11b 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-add.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-add.ts @@ -1,3 +1,4 @@ +import { runStandalonePreparation } from './worktree-preparation-standalone' import { lstat } from 'node:fs/promises' import { isUnsupportedWorktreeAddLockReasonError } from '../../../../shared/git/worktrees/git-worktree-command-capabilities' import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' @@ -11,11 +12,11 @@ import { WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, type GitWorktreeExecOptions } from '../worktree-operation-options' +import type { WorktreePreparationOperation } from './worktree-preparation-operation' import { - runStandalonePreparation, - type WorktreePreparationOperation -} from './worktree-preparation-operation' -import { discardPreparedWorktree } from './worktree-preparation-discard' + discardPreparedWorktree, + type PreparationRemovalOutcome +} from './worktree-preparation-discard' import { lockWorktreePreparation, verifyWorktreePreparationLock, @@ -39,6 +40,14 @@ async function isAbsent(worktreePath: string, options: GitWorktreeExecOptions): } } +/** The owner has fenced its raw work and no add was issued for this unique path. */ +export async function discardUnmaterializedPreparation( + path: string, + options: GitWorktreeExecOptions +): Promise { + return (await isAbsent(path, options)) ? 'removed' : 'revoked' +} + export async function addLockedWorktreePreparation( repoPath: string, worktreePath: string, @@ -61,32 +70,50 @@ export async function addLockedWorktreePreparation( ) ) } - const add = async (lockArgs: string[]): Promise => { - options.signal?.throwIfAborted() - try { - await gitExecFileAsync( - [ - ...windowsLongPathGitArgs(repoPath), - 'worktree', - 'add', - '--detach', - '--no-checkout', - ...lockArgs, - worktreePath, - baseRef - ], - gitExecOptions(repoPath, options) - ) - } finally { - invalidateWslLinkedWorktreeGitRouting(worktreePath) - } - } return withLocalGitCapabilityCacheForExecution( { cwd: repoPath, wslDistro: options.wslDistro, signal: options.signal }, async (capabilities) => { options.signal?.throwIfAborted() const initiallyAbsent = await isAbsent(worktreePath, options) options.signal?.throwIfAborted() + let issued = false + const add = async (lockArgs: string[]): Promise => { + options.signal?.throwIfAborted() + try { + await gitExecFileAsync( + [ + ...windowsLongPathGitArgs(repoPath), + 'worktree', + 'add', + '--detach', + '--no-checkout', + ...lockArgs, + worktreePath, + baseRef + ], + { + ...gitExecOptions(repoPath, options), + observeChildTermination: (terminated, writes) => { + if (writes) { + issued = true + operation.setDiscard((cleanupOptions) => + discardPreparedWorktree( + repoPath, + worktreePath, + cleanupOptions, + lockReason, + initiallyAbsent ? null : undefined + ) + ) + } + options.observeChildTermination?.(terminated, writes) + } + } + ) + } finally { + invalidateWslLinkedWorktreeGitRouting(worktreePath) + } + } return capabilities.runWithFallback( 'worktree-add-lock-reason', async () => { @@ -96,10 +123,13 @@ export async function addLockedWorktreePreparation( added = true const lockPath = await verifyWorktreePreparationLock(worktreePath, lockReason, options) operation.setDiscard((cleanupOptions) => - discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason) + discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason, lockPath) ) return lockPath } catch (error) { + if (!issued) { + throw error + } operation.setDiscard() // A canceled add can leave its marker; a pre-existing checkout is never ours to remove. if ( @@ -108,7 +138,13 @@ export async function addLockedWorktreePreparation( !(error instanceof WorktreePreparationLockOwnershipError) ) { operation.setDiscard((cleanupOptions) => - discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason) + discardPreparedWorktree( + repoPath, + worktreePath, + cleanupOptions, + lockReason, + initiallyAbsent ? null : undefined + ) ) } throw error @@ -126,10 +162,13 @@ export async function addLockedWorktreePreparation( operation ) operation.setDiscard((cleanupOptions) => - discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason) + discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason, lockPath) ) return lockPath } catch (error) { + if (!issued) { + throw error + } operation.setDiscard() if ( added && diff --git a/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts b/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts index 73adf59e55b..dc6901098aa 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-discard-real-git.test.ts @@ -56,7 +56,7 @@ it('removes only the owned registration after external deletion of its checkout' ['rev-parse', '--git-path', 'locked', '--git-common-dir'], ['worktree', 'remove', '--force', '--force', prepared] ]) - expect(spy.mock.calls[1]?.[1]).toEqual({ + expect(spy.mock.calls[1]?.[1]).toMatchObject({ cwd: repo, timeout: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS }) @@ -168,3 +168,42 @@ it.runIf(process.platform !== 'win32')('does not follow a symlink ownership mark expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false) expect(await readFile(externalLock, 'utf8')).toBe(`${reason}\n`) }) + +it('preserves a replacement even when its ownership text was copied', async () => { + const { repo, prepared, lock, reason } = await fixture() + const replacement = join(dirname(repo), 'replacement') + await runner.gitExecFileAsync(['worktree', 'add', '--detach', replacement, 'HEAD'], { cwd: repo }) + await runner.gitExecFileAsync(['worktree', 'lock', '--reason', reason, replacement], { + cwd: repo + }) + const pointer = await readFile(join(replacement, '.git'), 'utf8') + await writeFile(join(prepared, '.git'), pointer) + await writeFile(join(prepared, 'user.txt'), 'preserve replacement\n') + await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason, lock)).rejects.toThrow( + 'lock owner changed' + ) + expect(await readFile(join(prepared, 'user.txt'), 'utf8')).toBe('preserve replacement\n') + expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) +}) + +it('preserves a different missing-checkout registration with copied ownership text', async () => { + const { repo, prepared, lock, reason } = await fixture() + const preserved = join(dirname(repo), 'preserved-original') + await runner.gitExecFileAsync(['worktree', 'move', '-f', '-f', prepared, preserved], { + cwd: repo + }) + await runner.gitExecFileAsync( + ['worktree', 'add', '--detach', '--no-checkout', prepared, 'HEAD'], + { cwd: repo } + ) + await runner.gitExecFileAsync(['worktree', 'lock', '--reason', reason, prepared], { cwd: repo }) + const replacementLock = ( + await runner.gitExecFileAsync(['rev-parse', '--git-path', 'locked'], { cwd: prepared }) + ).stdout.trim() + await rm(prepared, { recursive: true }) + await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason, lock)).rejects.toThrow( + 'lock owner changed' + ) + expect(await readFile(replacementLock, 'utf8')).toBe(`${reason}\n`) + expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`) +}) diff --git a/src/main/git/worktrees/creation/worktree-preparation-discard.ts b/src/main/git/worktrees/creation/worktree-preparation-discard.ts index 4e60a2d22a5..0e750c75b17 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-discard.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-discard.ts @@ -1,9 +1,14 @@ import { bumpWorktreeScanGeneration } from '../catalog/worktree-scan-cache' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' -import { lstat } from 'node:fs/promises' -import { join } from 'node:path' +import { lstat, readFile, realpath } from 'node:fs/promises' +import { dirname, join } from 'node:path' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' -import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import { parseGitdirMarkerPayload } from '../../../../shared/git/metadata/gitdir-marker-payload' +import { canonicalWorktreePath } from '../catalog/worktree-path-comparison' +import { + resolveGitMetadataPath, + resolveWorktreeHostPath +} from '../../../../shared/git/metadata/git-metadata-path' import { findLinkedWorktreeGitDirectory } from '../../../../shared/git/worktrees/git-worktree-admin' import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' import { toHostFilesystemPath } from '../../../filesystem/host-tree-removal' @@ -16,6 +21,7 @@ import { type GitWorktreeExecOptions } from '../worktree-operation-options' import { + verifyOriginalPreparationDirectory, verifyWorktreePreparationLock, verifyWorktreePreparationLockAtPath, WorktreePreparationLockOwnershipError @@ -34,14 +40,23 @@ async function verifyDiscardPreparationOwner( repoPath: string, worktreePath: string, expectedLockReason: string, - options: GitExecOptionsForWorktree -): Promise { + options: GitExecOptionsForWorktree, + originalLockPath?: string | null +): Promise { try { - await verifyWorktreePreparationLock(worktreePath, expectedLockReason, options) - } catch (error) { - if (error instanceof WorktreePreparationLockOwnershipError) { - throw error + const gitDir = dirname( + await verifyWorktreePreparationLock(worktreePath, expectedLockReason, options) + ) + if (originalLockPath) { + await verifyOriginalPreparationDirectory(gitDir, originalLockPath) } + await verifyWorktreePreparationLockAtPath( + join(gitDir, 'locked'), + expectedLockReason, + options.signal + ) + return gitDir + } catch (error) { const hostPath = resolveWorktreeHostPath(worktreePath, options) const hostRepo = resolveWorktreeHostPath(repoPath, options) if (!hostPath || !hostRepo) { @@ -65,8 +80,17 @@ async function verifyDiscardPreparationOwner( } const gitDir = await findLinkedWorktreeGitDirectory(hostRepo, hostPath, { ...options, signal }) if (!gitDir) { + if ( + originalLockPath === null || + (originalLockPath && (await pathAbsent(dirname(originalLockPath)))) + ) { + return null + } throw new WorktreePreparationLockOwnershipError(error) } + if (originalLockPath) { + await verifyOriginalPreparationDirectory(gitDir, originalLockPath) + } const lockPath = toHostFilesystemPath(join(gitDir, 'locked')) const marker = await waitForPromiseWithSignal(lstat(lockPath), signal).catch( (failure: unknown) => { @@ -80,6 +104,87 @@ async function verifyDiscardPreparationOwner( verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, signal), signal ) + return gitDir + } +} + +export type PreparationRemovalOutcome = 'removed' | 'skipped' | 'ownership-lost' | 'revoked' + +async function pathAbsent(path: string, options: GitWorktreeExecOptions = {}): Promise { + const hostPath = resolveWorktreeHostPath(path, options) + if (!hostPath) { + throw new Error('Cannot resolve the prepared checkout path.') + } + return lstat(toHostFilesystemPath(hostPath)).then( + () => false, + (error: unknown) => { + if (getErrorCode(error) === 'ENOENT') { + return true + } + throw error + } + ) +} + +export type PreparationLocation = 'hidden' | 'target' | 'removed' | 'ownership-lost' | 'unknown' + +/** Both pointers and the original marker must agree before failed finalization can remove a path. */ +export async function reconcilePreparationLocation( + lockPath: string, + hiddenPath: string, + targetPath: string, + lockReason: string, + options: GitWorktreeExecOptions +): Promise { + const gitDir = dirname(lockPath) + const signal = AbortSignal.timeout(options.timeout ?? WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS) + const read = (work: Promise): Promise => waitForPromiseWithSignal(work, signal) + try { + const [hiddenAbsent, targetAbsent, adminAbsent] = await read( + Promise.all([ + pathAbsent(hiddenPath, options), + pathAbsent(targetPath, options), + pathAbsent(gitDir) + ]) + ) + if (hiddenAbsent && targetAbsent && adminAbsent) { + return 'removed' + } + if (adminAbsent) { + return 'unknown' + } + await read(verifyWorktreePreparationLockAtPath(lockPath, lockReason, signal)) + const backlink = await read(readFile(join(gitDir, 'gitdir'), 'utf8')) + const gitFile = resolveGitMetadataPath(gitDir, backlink, options) + if (!gitFile) { + return 'unknown' + } + const path = dirname(gitFile) + const key = async (value: string): Promise => + canonicalWorktreePath(await read(realpath(toHostFilesystemPath(value))).catch(() => value)) + const hidden = resolveWorktreeHostPath(hiddenPath, options) + const target = resolveWorktreeHostPath(targetPath, options) + const location = + hidden && (await key(path)) === (await key(hidden)) + ? 'hidden' + : target && (await key(path)) === (await key(target)) + ? 'target' + : undefined + if (!location || (await key(gitFile)) !== (await key(join(path, '.git')))) { + return 'unknown' + } + const pointer = await read(readFile(toHostFilesystemPath(gitFile), 'utf8')) + const marker = parseGitdirMarkerPayload(pointer) + const pointedAdmin = marker && resolveGitMetadataPath(path, marker, options) + if (!pointedAdmin || (await key(pointedAdmin)) !== (await key(gitDir))) { + return 'unknown' + } + await read(verifyWorktreePreparationLockAtPath(lockPath, lockReason, signal)) + return location + } catch (error) { + return error instanceof WorktreePreparationLockOwnershipError && error.replaced + ? 'ownership-lost' + : 'unknown' } } @@ -87,23 +192,36 @@ export async function performDiscardPreparedWorktree( repoPath: string, worktreePath: string, options: GitWorktreeExecOptions, - expectedLockReason?: string -): Promise { + expectedLockReason?: string, + originalLockPath?: string | null +): Promise { + const writers: Promise[] = [] const cleanupGitOptions = { ...gitCleanupOptions(repoPath, options), - timeout: options.timeout ?? WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS + timeout: options.timeout ?? WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, + observeChildTermination: (terminated: Promise, writes: boolean) => { + options.observeChildTermination?.(terminated, writes) + if (writes) { + writers.push(terminated) + } + } } try { + let gitDir: string | null = null if (expectedLockReason !== undefined) { - await verifyDiscardPreparationOwner( + gitDir = await verifyDiscardPreparationOwner( repoPath, worktreePath, expectedLockReason, - cleanupGitOptions + cleanupGitOptions, + originalLockPath ) + if (gitDir === null) { + return 'removed' + } } if (cleanupGitOptions.canStart?.() === false) { - return + return 'skipped' } // Double force requires a freshly verified ownership marker. await gitExecFileAsync( @@ -117,6 +235,11 @@ export async function performDiscardPreparedWorktree( ], cleanupGitOptions ) + await Promise.allSettled(writers) + if (!(await pathAbsent(worktreePath, options)) || (gitDir && !(await pathAbsent(gitDir)))) { + throw new Error('The prepared checkout or its registration remains after removal.') + } + return 'removed' } finally { invalidateWslLinkedWorktreeGitRouting(worktreePath) } @@ -128,8 +251,9 @@ export async function removeFailedFinalization( branch: string, moved: boolean, options: GitWorktreeExecOptions, - expectedLockReason?: string -): Promise { + expectedLockReason?: string, + originalLockPath?: string +): Promise { let branchAttached = false if (moved) { try { @@ -146,13 +270,14 @@ export async function removeFailedFinalization( repoPath, cleanupPath, options, - expectedLockReason + expectedLockReason, + originalLockPath ).then( - () => true, + (outcome) => outcome === 'removed', () => false ) if (!removed) { - return + return false } if (branchAttached) { await gitExecFileAsync( @@ -160,17 +285,25 @@ export async function removeFailedFinalization( gitCleanupOptions(repoPath, options) ).catch(() => {}) } + return true } export async function discardPreparedWorktree( repoPath: string, worktreePath: string, options: GitWorktreeExecOptions = {}, - expectedLockReason?: string -): Promise { + expectedLockReason?: string, + originalLockPath?: string | null +): Promise { try { - await runWithGitReadCacheInvalidation(() => - performDiscardPreparedWorktree(repoPath, worktreePath, options, expectedLockReason) + return await runWithGitReadCacheInvalidation(() => + performDiscardPreparedWorktree( + repoPath, + worktreePath, + options, + expectedLockReason, + originalLockPath + ) ) } finally { bumpWorktreeScanGeneration(repoPath) diff --git a/src/main/git/worktrees/creation/worktree-preparation-disposal.ts b/src/main/git/worktrees/creation/worktree-preparation-disposal.ts new file mode 100644 index 00000000000..ed4693a28c9 --- /dev/null +++ b/src/main/git/worktrees/creation/worktree-preparation-disposal.ts @@ -0,0 +1,210 @@ +import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' +import { WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS } from '../worktree-operation-options' +import type { PreparationRemovalOutcome } from './worktree-preparation-discard' + +export type SettledPreparationDiscard = { + status: PreparationRemovalOutcome | 'failed' + attempted: boolean + error?: unknown +} +export type PreparationDiscardResult = + | SettledPreparationDiscard + | { + status: 'pending' + settled: Promise + } + +export abstract class WorktreePreparationDisposal { + private discardAttempt?: Promise + private disposalState: + | 'owned' + | 'finalizing' + | 'pending' + | 'active' + | 'parked' + | 'terminal' + | 'released' = 'owned' + private attempts = 0 + private wake?: object + private disposalOwner?: { + current: () => boolean + before: () => Promise + schedule: (work: () => Promise) => Promise + disposed: () => void + } + + abstract physicalSettlement(): Promise + + async waitForPhysicalSettlement(onAbandon?: () => void): Promise { + return sharedPromiseSettlementWaiters(this.physicalSettlement()) + .wait({ + timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, + onAbandon + }) + .then( + () => true, + () => false + ) + } + + protected abstract retire(): Promise + protected abstract physicalDiscard( + eligible: () => boolean, + before: () => Promise, + leaseRetirement: AbortSignal + ): Promise + protected abstract complete(): void + + protected beginFinalization(rollback: boolean): void { + if ( + !this.current() || + (this.disposalState !== 'owned' && !(rollback && this.disposalState === 'finalizing')) + ) { + throw new Error('The prepared checkout is no longer available for finalization.') + } + this.disposalState = 'finalizing' + } + + finishFinalization(outcome: 'disposed' | 'pending' | 'failed' = 'failed'): void { + if (outcome === 'disposed') { + this.disposalOwner?.disposed() + this.release() + } else if (this.disposalState === 'finalizing') { + if (outcome === 'pending') { + this.acceptDiscard({ + status: 'pending', + settled: this.physicalSettlement().then(() => ({ status: 'skipped', attempted: false })) + }) + } else { + this.disposalState = 'pending' + } + } + } + setDisposalOwner(owner: NonNullable): void { + this.disposalOwner = owner + } + + get needsDiscardRetry(): boolean { + return this.disposalState === 'pending' + } + + release(): void { + this.disposalState = 'released' + this.wake = undefined + this.complete() + } + + protected current(): boolean { + return this.disposalState !== 'released' && this.disposalOwner?.current() !== false + } + + discard(): Promise { + if ( + !this.current() || + this.disposalState === 'finalizing' || + this.disposalState === 'parked' || + this.disposalState === 'terminal' + ) { + return Promise.resolve() + } + if (this.discardAttempt) { + return this.discardAttempt + } + this.disposalState = 'active' + const run = async (): Promise => this.acceptDiscard(await this.discardOnce()) + const attempt = this.disposalOwner ? this.disposalOwner.schedule(run) : run() + this.discardAttempt = attempt + void attempt.then(() => { + if (this.discardAttempt === attempt) { + this.discardAttempt = undefined + } + }) + return attempt + } + + private acceptDiscard(result: PreparationDiscardResult): void { + if (!this.current()) { + return + } + if (result.status !== 'pending') { + this.finishDiscard(result, false) + return + } + const token = {} + this.wake = token + this.disposalState = 'parked' + void result.settled.then((settled) => { + if (!this.current() || this.disposalState !== 'parked' || this.wake !== token) { + return + } + this.wake = undefined + this.finishDiscard(settled, true) + }) + } + + private finishDiscard(result: SettledPreparationDiscard, wake: boolean): void { + if (!this.current()) { + return + } + if (result.attempted) { + this.attempts += 1 + } + if (result.status === 'removed' || result.status === 'ownership-lost') { + this.disposalOwner?.disposed() + this.release() + return + } + if (result.status === 'revoked' || this.attempts >= 3) { + this.disposalState = 'terminal' + console.warn( + '[worktree-create] prepared checkout remains; automatic cleanup stopped', + result.error + ) + return + } + this.disposalState = 'pending' + if (wake) { + void (this.discardAttempt ?? Promise.resolve()).then(() => { + if (this.current() && this.needsDiscardRetry) { + void this.discard() + } + }) + } + } + + private async discardOnce(): Promise { + const retirement = this.retire() + const retired = await sharedPromiseSettlementWaiters(retirement) + .wait({ + timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS + }) + .then( + () => true, + () => false + ) + if (!retired) { + return { + status: 'pending', + settled: retirement.then(() => ({ status: 'skipped', attempted: false })) + } + } + let eligible = true + const leaseRetirement = new AbortController() + const settled = this.physicalDiscard( + () => eligible && this.current(), + () => this.disposalOwner?.before() ?? Promise.resolve(true), + leaseRetirement.signal + ) + const result = await sharedPromiseSettlementWaiters(settled) + .wait({ + timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, + onAbandon: () => { + eligible = false + leaseRetirement.abort() + } + }) + .catch(() => ({ status: 'pending' as const, settled })) + eligible = false + return result + } +} diff --git a/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts new file mode 100644 index 00000000000..25d8169354d --- /dev/null +++ b/src/main/git/worktrees/creation/worktree-preparation-finalization-work.ts @@ -0,0 +1,179 @@ +import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args' +import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args' +import type { AddWorktreeOptions } from '../worktree-operation-options' +import { gitExecOptions, resolveWorktreeAddTimeoutMs } from '../worktree-operation-options' +import { + configurePushAutoSetupRemote, + persistWorktreeCreationBase, + resolveWorktreeAddBaseContext, + trackSameNameRemoteBase +} from './worktree-add' +import { bumpWorktreeScanGeneration as notifyPreparedWorktreeMutation } from '../catalog/worktree-scan-cache' +import type { WorktreePreparationOperation } from './worktree-preparation-operation' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' +import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' +import { + unlockWorktreePreparationAtPath, + verifyWorktreePreparationLock, + verifyWorktreePreparationLockAtPath +} from './worktree-preparation-lock' +import type { FinalizedPreparedWorktree } from './worktree-create-preparation' + +export async function performPreparedWorktreeFinalization( + repoPath: string, + preparedPath: string, + worktreePath: string, + branch: string, + baseBranch: string, + refreshLocalBaseRef = false, + options: AddWorktreeOptions = {}, + expectedLockReason: string, + operation: WorktreePreparationOperation, + captured: { lockPath?: string; targetWriter: boolean } +): Promise { + const finalizeGitOptions: AddWorktreeOptions = { + ...options, + timeout: options.timeout ?? resolveWorktreeAddTimeoutMs() + } + try { + return await runWithGitReadCacheInvalidation(async () => { + const lockPath = await verifyWorktreePreparationLock( + preparedPath, + expectedLockReason, + finalizeGitOptions + ) + captured.lockPath = lockPath + const verifyOwnership = (): Promise => + verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, finalizeGitOptions.signal) + const [targetResult, preparedResult] = await Promise.allSettled([ + (async () => { + const baseContext = await resolveWorktreeAddBaseContext( + repoPath, + baseBranch, + refreshLocalBaseRef, + finalizeGitOptions, + branch + ) + if (baseContext.pendingLocalBaseRefRefresh) { + operation.trackWriter(baseContext.pendingLocalBaseRefRefresh) + } + const targetHead = + baseContext.effectiveBaseOid ?? + ( + await gitExecFileAsync( + ['rev-parse', '--verify', `${baseContext.effectiveBase}^{commit}`], + gitExecOptions(repoPath, finalizeGitOptions) + ) + ).stdout.trim() + return { baseContext, targetHead } + })(), + gitExecFileAsync( + ['rev-parse', '--verify', 'HEAD'], + gitExecOptions(preparedPath, finalizeGitOptions) + ) + ]) + // Settle both reads before failure cleanup can remove the prepared checkout. + if (targetResult.status === 'rejected') { + throw targetResult.reason + } + const { baseContext, targetHead } = targetResult.value + if (preparedResult.status === 'rejected') { + await baseContext.pendingLocalBaseRefRefresh + throw preparedResult.reason + } + const preparedHeadReset = preparedResult.value.stdout.trim() !== targetHead + if (preparedHeadReset) { + await verifyOwnership() + await gitExecFileAsync( + [ + ...(await checkoutWorkersGitArgs(preparedPath, finalizeGitOptions)), + ...windowsLongPathGitArgs(preparedPath), + 'reset', + '--hard', + targetHead + ], + gitExecOptions(preparedPath, finalizeGitOptions) + ) + } + + try { + try { + await verifyOwnership() + // Git >= 2.25 needs two force flags to move a locked preparation without losing its lock reason. + await gitExecFileAsync( + [ + ...windowsLongPathGitArgs(repoPath), + 'worktree', + 'move', + '-f', + '-f', + preparedPath, + worktreePath + ], + { + ...gitExecOptions(repoPath, finalizeGitOptions), + observeChildTermination: (terminated, writes) => { + if (writes) { + captured.targetWriter = true + } + finalizeGitOptions.observeChildTermination?.(terminated, writes) + } + } + ) + } finally { + // The move rewrites both `.git` markers, and a failure can have rewritten one. + invalidateWslLinkedWorktreeGitRouting(preparedPath) + invalidateWslLinkedWorktreeGitRouting(worktreePath) + } + await verifyOwnership() + await gitExecFileAsync( + [ + ...windowsLongPathGitArgs(worktreePath), + 'checkout', + '--no-track', + '-b', + branch, + targetHead + ], + gitExecOptions(worktreePath, finalizeGitOptions) + ) + await verifyOwnership() + await persistWorktreeCreationBase( + worktreePath, + branch, + baseContext.effectiveBase, + finalizeGitOptions + ) + await trackSameNameRemoteBase( + worktreePath, + branch, + baseBranch, + baseContext.effectiveBase, + finalizeGitOptions + ) + await configurePushAutoSetupRemote(worktreePath, finalizeGitOptions) + await unlockWorktreePreparationAtPath( + lockPath, + expectedLockReason, + finalizeGitOptions.signal, + operation + ) + } catch (error) { + await baseContext.pendingLocalBaseRefRefresh + throw error + } + // Advisory refresh may settle after finalization; it does not determine checkout contents. + const localBaseRefRefresh = await baseContext.pendingLocalBaseRefRefresh + return { + preparedHeadReset, + ...(localBaseRefRefresh ? { localBaseRefRefresh } : {}), + ...(baseContext.localBaseRefUpdateSuggestion + ? { localBaseRefUpdateSuggestion: baseContext.localBaseRefUpdateSuggestion } + : {}) + } + }) + } finally { + notifyPreparedWorktreeMutation(repoPath) + } +} diff --git a/src/main/git/worktrees/creation/worktree-preparation-lock.ts b/src/main/git/worktrees/creation/worktree-preparation-lock.ts index 4a161f93cfc..1650e2b742f 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-lock.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-lock.ts @@ -1,6 +1,7 @@ +import { canonicalWorktreePath } from '../catalog/worktree-path-comparison' import type { WorktreePreparationOperation } from './worktree-preparation-operation' -import { readFile, unlink, writeFile } from 'node:fs/promises' -import { posix, win32 } from 'node:path' +import { readFile, realpath, unlink, writeFile } from 'node:fs/promises' +import { dirname, posix, win32 } from 'node:path' import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path' import { resolveGitMetadataPath, @@ -15,7 +16,10 @@ import { } from '../worktree-operation-options' export class WorktreePreparationLockOwnershipError extends Error { - constructor(cause?: unknown) { + constructor( + cause?: unknown, + readonly replaced = false + ) { super('The prepared worktree lock owner changed', { cause }) } } @@ -106,10 +110,12 @@ export async function unlockWorktreePreparation( export async function unlockWorktreePreparationAtPath( lockPath: string, expectedLockReason: string, - signal?: AbortSignal + signal?: AbortSignal, + operation?: WorktreePreparationOperation ): Promise { await verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, signal) - await unlink(lockPath).catch((error: unknown) => { + const writing = unlink(lockPath) + await (operation ? operation.trackWriter(writing) : writing).catch((error: unknown) => { throw new WorktreePreparationLockOwnershipError(error) }) } @@ -133,7 +139,20 @@ export async function verifyWorktreePreparationLockAtPath( throw new WorktreePreparationLockOwnershipError(error) }) if (lockReason !== `${expectedLockReason}\n`) { - throw new WorktreePreparationLockOwnershipError() + throw new WorktreePreparationLockOwnershipError(undefined, true) } signal?.throwIfAborted() } + +export async function verifyOriginalPreparationDirectory( + gitDir: string, + originalLockPath: string +): Promise { + const [actual, original] = await Promise.all([ + realpath(gitDir), + realpath(dirname(originalLockPath)) + ]) + if (canonicalWorktreePath(actual) !== canonicalWorktreePath(original)) { + throw new WorktreePreparationLockOwnershipError(undefined, true) + } +} diff --git a/src/main/git/worktrees/creation/worktree-preparation-operation.ts b/src/main/git/worktrees/creation/worktree-preparation-operation.ts index 7fa082b60e4..f8a5f7d62d0 100644 --- a/src/main/git/worktrees/creation/worktree-preparation-operation.ts +++ b/src/main/git/worktrees/creation/worktree-preparation-operation.ts @@ -1,27 +1,20 @@ +import { + WorktreePreparationDisposal, + type SettledPreparationDiscard +} from './worktree-preparation-disposal' +import type { PreparationRemovalOutcome } from './worktree-preparation-discard' import { WorktreePreparationLockOwnershipError } from './worktree-preparation-lock' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' -import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' -import { GIT_READ_TIMEOUT_MS } from '../../../../shared/git/commands/git-command-timeout' import { getLocalRepoRefMaintenance } from '../../refs/maintenance/local-repo-ref-maintenance' import { - resolveWorktreeAddTimeoutMs, - WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, + WORKTREE_CREATE_PREPARATION_TTL_MS, + preparationWorkBudget, type GitWorktreeExecOptions } from '../worktree-operation-options' -export const WORKTREE_CREATE_PREPARATION_TTL_MS = 5 * 60_000 +export { WORKTREE_CREATE_PREPARATION_TTL_MS } from '../worktree-operation-options' -export function preparationWorkBudget(options: GitWorktreeExecOptions, refresh: boolean): number { - const checkout = resolveWorktreeAddTimeoutMs() - const read = options.timeout ?? GIT_READ_TIMEOUT_MS - // Include old-Git registration and direct-WSL read fallbacks, each with its own child budget. - return ( - WORKTREE_CREATE_PREPARATION_TTL_MS + - (refresh ? 9 * (options.timeout ?? checkout) : 6 * read + 7 * checkout) - ) -} - -export class WorktreePreparationOperation { +export class WorktreePreparationOperation extends WorktreePreparationDisposal { readonly controller = new AbortController() readonly signal: AbortSignal private readonly transferred = Promise.withResolvers() @@ -31,15 +24,17 @@ export class WorktreePreparationOperation { private timer?: NodeJS.Timeout private workUntil?: number private claimed = false - private retirement?: Promise - private discardAttempt?: Promise + private retirement?: Promise + private revoked: PreparationRemovalOutcome = 'revoked' + private authorityRevoked = false private maintenance?: { release: () => void; signal: AbortSignal; finished: boolean } - private discardCheckout?: (options: GitWorktreeExecOptions) => Promise + private discardCheckout?: (options: GitWorktreeExecOptions) => Promise constructor( private readonly options: GitWorktreeExecOptions, private readonly expired: () => void = () => {} ) { + super() this.signal = options.signal ? AbortSignal.any([options.signal, this.controller.signal]) : this.controller.signal @@ -66,8 +61,12 @@ export class WorktreePreparationOperation { this.signal.removeEventListener('abort', this.onAbort) } - setDiscard(discard?: (options: GitWorktreeExecOptions) => Promise): void { - this.discardCheckout = discard + setDiscard( + discard?: (options: GitWorktreeExecOptions) => Promise + ): void { + if (!this.authorityRevoked || !discard) { + this.discardCheckout = discard + } } get isClaimed(): boolean { @@ -84,7 +83,7 @@ export class WorktreePreparationOperation { return { ...this.options, signal: this.signal, - canStart: () => !this.signal.aborted && this.options.canStart?.() !== false, + canStart: () => this.current() && !this.signal.aborted && this.options.canStart?.() !== false, observeChildTermination: (terminated, writes) => { this.options.observeChildTermination?.(terminated, writes) this.observeChildTermination(terminated, writes) @@ -106,15 +105,22 @@ export class WorktreePreparationOperation { this.releaseMaintenanceIfSafe() } - private releaseMaintenanceIfSafe(): void { - const held = this.maintenance - if (held && (held.finished || held.signal.aborted) && this.writers.size === 0) { + private releaseMaintenanceIfSafe(held = this.maintenance): void { + if ( + held && + this.maintenance === held && + (held.finished || held.signal.aborted) && + this.writers.size === 0 + ) { held.release() this.maintenance = undefined } } - async withMaintenancePaused(run: () => Promise, signal = this.signal): Promise { + async withMaintenancePaused( + run: () => Promise, + signal: AbortSignal | undefined = this.signal + ): Promise { const acquiring = getLocalRepoRefMaintenance().pause('worktree-prepare') const release = await waitForPromiseWithSignal(acquiring, signal).catch((error: unknown) => { void acquiring.then( @@ -123,20 +129,28 @@ export class WorktreePreparationOperation { ) throw error }) + return this.runWithMaintenanceLease(run, release, signal) + } + + private async runWithMaintenanceLease( + run: () => Promise, + release: () => void, + signal: AbortSignal + ): Promise { if (signal.aborted) { release() signal.throwIfAborted() } const held = { release, signal, finished: false } this.maintenance = held - const onAbort = (): void => this.releaseMaintenanceIfSafe() + const onAbort = (): void => this.releaseMaintenanceIfSafe(held) signal.addEventListener('abort', onAbort, { once: true }) try { return await run() } finally { held.finished = true signal.removeEventListener('abort', onAbort) - this.releaseMaintenanceIfSafe() + this.releaseMaintenanceIfSafe(held) } } @@ -160,7 +174,9 @@ export class WorktreePreparationOperation { this.signal.throwIfAborted() } catch (error) { if (error instanceof WorktreePreparationLockOwnershipError) { + this.authorityRevoked = true this.setDiscard(undefined) + this.revoked = error.replaced ? 'ownership-lost' : 'revoked' } this.controller.abort(error) throw error @@ -192,107 +208,114 @@ export class WorktreePreparationOperation { this.timer.unref() } - retire(): Promise { - if (this.retirement) { - return this.retirement + supervise( + options: GitWorktreeExecOptions, + work: (options: GitWorktreeExecOptions) => Promise, + rollback = false + ): Promise { + if (!rollback) { + this.signal.throwIfAborted() } - this.controller.abort() - const proof = this.raw + this.complete() + this.beginFinalization(rollback) + this.retirement = undefined + let eligible = true + const result = Promise.resolve() + .then(() => + work({ + ...options, + canStart: () => eligible && this.current() && options.canStart?.() !== false, + observeChildTermination: (terminated, writes) => { + options.observeChildTermination?.(terminated, writes) + this.observeChildTermination(terminated, writes) + } + }) + ) + .catch((error: unknown) => { + if (error instanceof WorktreePreparationLockOwnershipError) { + this.authorityRevoked = true + this.setDiscard(undefined) + this.revoked = error.replaced ? 'ownership-lost' : 'revoked' + } + throw error + }) + .finally(() => { + eligible = false + }) + this.raw = result.then( + () => {}, + () => {} + ) + return result + } + + physicalSettlement(): Promise { + return this.raw .catch(() => {}) .then(async () => { await Promise.allSettled(this.writers) }) - this.retirement = sharedPromiseSettlementWaiters(proof) - .wait({ - timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS - }) - .then( - () => true, - () => false - ) + } + + retire(): Promise { + if (!this.retirement) { + this.controller.abort() + this.retirement = this.physicalSettlement() + } return this.retirement } - discard(): Promise { - if (!this.discardAttempt) { - this.discardAttempt = this.discardOnce() - void this.discardAttempt.catch(() => { - this.discardAttempt = undefined - }) - } - return this.discardAttempt - } - - private async discardOnce(): Promise { - if (!(await this.retire())) { - return - } + protected async physicalDiscard( + eligible: () => boolean, + before: () => Promise, + leaseRetirement: AbortSignal + ): Promise { const discard = this.discardCheckout if (!discard) { - return + return { status: this.revoked, attempted: false } } - let eligible = true - const cleanupController = new AbortController() - const cleanup = this.withMaintenancePaused( - () => - discard({ - ...this.options, - signal: undefined, - canStart: () => eligible, - observeChildTermination: this.observeChildTermination - }), - cleanupController.signal - ) - // A rejection is not physical completion; retries also require all writer receipts. - const settled = cleanup - .then( - () => ({ error: undefined }), - (error: unknown) => ({ error }) + let attempted = false + // Lease retirement cannot replace the original acquisition's physical settlement. + const acquiring = getLocalRepoRefMaintenance().pause('worktree-prepare') + const cleanup = acquiring.then((release) => + this.runWithMaintenanceLease( + async () => { + if (!eligible() || !(await before()) || !eligible()) { + return 'skipped' as const + } + return discard({ + ...this.options, + admissionTier: 'background', + signal: undefined, + canStart: eligible, + observeChildTermination: (terminated, writes) => { + if (writes) { + attempted = true + } + this.observeChildTermination(terminated, writes) + } + }) + }, + release, + leaseRetirement ) - .then(async (result) => { - await Promise.allSettled(this.writers) - return result + ) + const result = await cleanup.then( + (status): SettledPreparationDiscard => ({ status, attempted }), + (error: unknown): SettledPreparationDiscard => ({ + status: + !eligible() && !attempted + ? 'skipped' + : error instanceof WorktreePreparationLockOwnershipError + ? error.replaced + ? 'ownership-lost' + : 'revoked' + : 'failed', + attempted: attempted || eligible(), + error }) - try { - const result = await sharedPromiseSettlementWaiters(settled).wait({ - timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS, - onAbandon: () => { - eligible = false - cleanupController.abort() - } - }) - if (result.error !== undefined) { - throw result.error - } - } catch (error) { - if (!eligible) { - this.retirement = Promise.resolve(false) - return - } - throw error - } finally { - eligible = false - } - } -} - -export async function runStandalonePreparation( - options: GitWorktreeExecOptions, - work: (operation: WorktreePreparationOperation) => Promise -): Promise { - const operation = new WorktreePreparationOperation(options) - // A direct caller still owns its fetch barrier; only pool handoff supersedes it. - operation.claim(false) - let result!: T - try { - await operation.run(async () => { - result = await work(operation) - }) - return result - } catch (error) { - await operation.discard().catch(() => {}) - throw error - } finally { - operation.complete() + ) + await Promise.allSettled(this.writers) + return { ...result, attempted: result.attempted || attempted } } } diff --git a/src/main/git/worktrees/creation/worktree-preparation-standalone.ts b/src/main/git/worktrees/creation/worktree-preparation-standalone.ts new file mode 100644 index 00000000000..419b2ed855b --- /dev/null +++ b/src/main/git/worktrees/creation/worktree-preparation-standalone.ts @@ -0,0 +1,23 @@ +import type { GitWorktreeExecOptions } from '../worktree-operation-options' +import { WorktreePreparationOperation } from './worktree-preparation-operation' + +export async function runStandalonePreparation( + options: GitWorktreeExecOptions, + work: (operation: WorktreePreparationOperation) => Promise +): Promise { + const operation = new WorktreePreparationOperation(options) + // A direct caller still owns its fetch barrier; only pool handoff supersedes it. + operation.claim(false) + let result!: T + try { + await operation.run(async () => { + result = await work(operation) + }) + return result + } catch (error) { + await operation.discard().catch(() => {}) + throw error + } finally { + operation.complete() + } +} diff --git a/src/main/git/worktrees/movement/worktree-mutation-route-invalidation.test.ts b/src/main/git/worktrees/movement/worktree-mutation-route-invalidation.test.ts index e8016852f73..07505949215 100644 --- a/src/main/git/worktrees/movement/worktree-mutation-route-invalidation.test.ts +++ b/src/main/git/worktrees/movement/worktree-mutation-route-invalidation.test.ts @@ -1,3 +1,6 @@ +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join } from 'node:path' // Worktree add/move/remove/rollback rewrite the `.git` marker the WSL Git route was derived from. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -57,8 +60,8 @@ vi.mock('../catalog/worktree-scan-cache', () => ({ vi.mock('../creation/worktree-preparation-lock', async (importOriginal) => ({ ...(await importOriginal()), - lockWorktreePreparation: vi.fn(async () => '/owned-lock'), - verifyWorktreePreparationLock: vi.fn(async () => '/owned-lock'), + lockWorktreePreparation: vi.fn(async () => ownedLockPath), + verifyWorktreePreparationLock: vi.fn(async () => ownedLockPath), verifyWorktreePreparationLockAtPath: vi.fn(), unlockWorktreePreparationAtPath: vi.fn() })) @@ -77,6 +80,8 @@ import { usesHostGitForWslLinkedWorktree } from '../../command-runner/wsl-linked-worktree-git-routing' +const ownedLockPath = join(tmpdir(), `orca-route-invalidation-${randomUUID()}`, 'locked') + const REPO = String.raw`C:\repo` const LINKED = String.raw`C:\ws\linked` const MOVED = String.raw`C:\ws\moved` diff --git a/src/main/git/worktrees/worktree-operation-options.ts b/src/main/git/worktrees/worktree-operation-options.ts index 2f7fcf13486..66a1b90e6e0 100644 --- a/src/main/git/worktrees/worktree-operation-options.ts +++ b/src/main/git/worktrees/worktree-operation-options.ts @@ -1,3 +1,4 @@ +import { GIT_READ_TIMEOUT_MS } from '../../../shared/git/commands/git-command-timeout' import type { LocalBaseRefRefreshResult, LocalBaseRefUpdateSuggestion @@ -63,6 +64,18 @@ export const WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS = 30_000 // A wedged shared scan would otherwise stall every later listing. export const WORKTREE_LIST_TIMEOUT_MS = 30_000 +export const WORKTREE_CREATE_PREPARATION_TTL_MS = 5 * 60_000 + +export function preparationWorkBudget(options: GitWorktreeExecOptions, refresh: boolean): number { + const checkout = resolveWorktreeAddTimeoutMs() + const read = options.timeout ?? GIT_READ_TIMEOUT_MS + // Include old-Git registration and direct-WSL read fallbacks, each with its own child budget. + return ( + WORKTREE_CREATE_PREPARATION_TTL_MS + + (refresh ? 9 * (options.timeout ?? checkout) : 6 * read + 7 * checkout) + ) +} + /** Clamp ORCA_WORKTREE_ADD_TIMEOUT_MS; warn for nonblank rejected/clamped values, not fractional truncation. */ export function resolveWorktreeAddTimeoutMs(env: NodeJS.ProcessEnv = process.env): number { const raw = env.ORCA_WORKTREE_ADD_TIMEOUT_MS?.trim() diff --git a/src/main/github/client/fetch/get-work-item.ts b/src/main/github/client/fetch/get-work-item.ts index 271af5a93df..3f3222036aa 100644 --- a/src/main/github/client/fetch/get-work-item.ts +++ b/src/main/github/client/fetch/get-work-item.ts @@ -1,6 +1,12 @@ import { withGitHubRepoExecution } from '../../github-repository-identity' import type { IssueSourcePreference } from '../../../../shared/repo-types' -import { acquire, release, classifyGhError, type LocalGitExecOptions } from '../../gh-utils' +import { + acquire, + release, + classifyGhError, + extractExecError, + type LocalGitExecOptions +} from '../../gh-utils' import { resolveGitHubApiRepository, resolveGitHubApiRepositoryCandidates, @@ -214,7 +220,12 @@ export async function getWorkItemByOwnerRepo( connectionId, localGitOptions ) - } catch { + } catch (err) { + // Only the failure class is logged: stderr and the command line name the repository. + const stderr = extractExecError(err).stderr || (err instanceof Error ? err.message : '') + console.warn( + `getWorkItemByOwnerRepo ${options.preview ? 'preview' : type} lookup failed: ${classifyGhError(stderr).type}` + ) return null } finally { release() diff --git a/src/main/ipc/runtime-environments/runtime-environment-transport-generation.ts b/src/main/ipc/runtime-environments/runtime-environment-transport-generation.ts index fd210c5e7cd..d9b44299c4f 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-transport-generation.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-transport-generation.ts @@ -2,6 +2,16 @@ const generationByEnvironment = new Map() const MAX_TRACKED_ENVIRONMENTS = 512 let generationSequence = 0 let evictedGeneration = 0 +const retirementListeners = new Set<(environmentId: string) => void>() + +/** Streams opened under an earlier generation can no longer deliver (their frames are discarded), + * so whoever owns them must close them when the generation moves on. */ +export function onRuntimeEnvironmentTransportGenerationRetired( + listener: (environmentId: string) => void +): () => void { + retirementListeners.add(listener) + return () => retirementListeners.delete(listener) +} export function getRuntimeEnvironmentTransportGeneration(environmentId: string): number { return generationByEnvironment.get(environmentId) ?? evictedGeneration @@ -18,6 +28,9 @@ export function advanceRuntimeEnvironmentTransportGeneration(environmentId: stri evictedGeneration = Math.max(evictedGeneration, generationByEnvironment.get(oldest.value) ?? 0) generationByEnvironment.delete(oldest.value) } + for (const listener of retirementListeners) { + listener(environmentId) + } } export function _getRuntimeEnvironmentTransportGenerationCacheSize(): number { diff --git a/src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts b/src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts index ed19056d5f2..8e09a9237d2 100644 --- a/src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts +++ b/src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts @@ -1,4 +1,5 @@ import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' +import { advanceRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -186,4 +187,45 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) expect(close).toHaveBeenCalled() }) + + // #39926: a rebuilt control connection advances the transport generation, after which every + // frame of an existing stream was discarded without a close, so a chat view sat on a silent stream. + it('closes and reports a stream whose transport generation was retired', async () => { + registerRuntimeEnvironmentHandlers(store as never) + const close = vi.fn() + subscribeRemoteRuntimeRequestMock.mockResolvedValue({ + requestId: 'stream-1', + close, + sendBinary: vi.fn() + }) + const add = handler< + { name: string; pairingCode: string }, + { environment: { id: string; name: string } } + >('runtimeEnvironments:addFromPairingCode') + const { environment } = await add(null, { name: 'desk', pairingCode: pairingCode() }) + const send = vi.fn() + const subscribe = handler< + { selector: string; method: string; params?: unknown; subscriptionId?: string }, + { subscriptionId: string; requestId: string } + >('runtimeEnvironments:subscribe') + await subscribe( + { + sender: { id: 1, isDestroyed: () => false, send, on: vi.fn(), removeListener: vi.fn() } + }, + { + selector: 'desk', + method: 'agentSession.subscribe', + params: { sessionId: 'chat-1' }, + subscriptionId: 'chat-sub' + } + ) + + advanceRuntimeEnvironmentTransportGeneration(environment.id) + + expect(close).toHaveBeenCalled() + expect(send).toHaveBeenCalledWith('runtimeEnvironments:subscriptionEvent', { + subscriptionId: 'chat-sub', + type: 'close' + }) + }) }) diff --git a/src/main/ipc/runtime-environments/runtime-environments.ts b/src/main/ipc/runtime-environments/runtime-environments.ts index fb21fb8e798..cf205a1a3c1 100644 --- a/src/main/ipc/runtime-environments/runtime-environments.ts +++ b/src/main/ipc/runtime-environments/runtime-environments.ts @@ -29,7 +29,10 @@ import { setManagedOrcadPairingRepairedListener } from '../../managed-server/lif import { forgetManagedOrcadAutomaticFailures } from '../../managed-server/lifecycle/orcad-managed-tunnel' import { registerRuntimeEnvironmentRecoveryHandler } from './runtime-environment-recovery-handler' import { registerRuntimeEnvironmentRepairHandler } from './runtime-environment-repair-handler' -import { advanceRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' +import { + advanceRuntimeEnvironmentTransportGeneration, + onRuntimeEnvironmentTransportGenerationRetired +} from './runtime-environment-transport-generation' import { resetSharedControlSupport } from './runtime-environment-shared-control-support' import { RUNTIME_ENVIRONMENT_HANDLER_CHANNELS } from './runtime-environment-handler-channels' import { registerOrcadRuntimeLifecycleHandlers } from './orcad-runtime-lifecycle-handlers' @@ -59,11 +62,17 @@ function closeSubscriptionsForEnvironment(environmentId: string): void { pending.close() } } + closeEstablishedSubscriptionsForEnvironment(environmentId) +} + +function closeEstablishedSubscriptionsForEnvironment(environmentId: string): number { + let closed = 0 // Removed runtimes must release terminal/browser sockets before renderer teardown. for (const [subscriptionId, subscription] of remoteRuntimeSubscriptions) { if (subscription.environmentId !== environmentId) { continue } + closed += 1 remoteRuntimeSubscriptions.delete(subscriptionId) // Isolate close and notification failures so neither strands this environment's sibling subscriptions. try { @@ -78,7 +87,20 @@ function closeSubscriptionsForEnvironment(environmentId: string): void { console.warn('[runtime-environments] subscription close notice failed:', error) } } + return closed } +// A retired generation's frames are discarded (runtime-environment-subscription-handlers.ts), so its +// streams must close and tell their renderers, which resubscribe from where they left off. Streams +// still being set up fail their own generation check instead. +onRuntimeEnvironmentTransportGenerationRetired((environmentId) => { + const closed = closeEstablishedSubscriptionsForEnvironment(environmentId) + if (closed > 0) { + console.warn(`[runtime-environments] transport retired; reopening ${closed} stream(s)`, { + environmentId + }) + } +}) + /** Returns once the environment's client-hosted browser pages have been released. */ export function invalidateRuntimeEnvironmentTransport(environmentId: string): Promise { // Same-ID re-pairing must retire every transport authenticated as the former peer. diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-actual.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-actual.test-fixture.ts deleted file mode 100644 index 65795488db0..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-actual.test-fixture.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { - PiRpcOptionObservations, - applyPiRpcSessionOption, - type PiRpcOptionProof -} from '../../../../pi/rpc-options' -import { captureStructuredExecutionOptions } from '../../options/structured-agent-session-execution-options' -import { StructuredAgentRegistry } from '../../providers/structured-agent-registry' -import { PI_RPC_AGENT } from '../../../../pi/rpc-agent-definition' -import { PiRpcSessionAdapter } from '../../../../pi/rpc-session-adapter' -import { createStructuredAgentSessionLogger } from '../structured-agent-session-logger' -import { expect, it } from 'vitest' -import type { piOptionRefreshHost } from './structured-agent-session-option-refresh.test-fixture' -import type { - PiRefreshHarness, - PiRefreshMount -} from '../../../../../shared/agent-session/options/structured-agent-session-option-refresh.test-fixture-contract' - -const precise = ['off', 'minimal', 'low', 'high', 'xhigh'].map((value) => ({ value, label: value })) -const effort = (view: PiRefreshHarness) => view.snapshot().find((entry) => entry.id === 'effort') - -export function piOptionActualContract( - makeHost: typeof piOptionRefreshHost, - mount: PiRefreshMount, - flush: (work: () => void) => Promise -): void { - it('keeps cold matched actual display separate from raw capture through equal picks and context replacement', async () => { - const host = makeHost() - host.record.options.effort = 'off' - const proof: PiRpcOptionProof = { current: new Map(), writes: new Map() } - const setters: string[] = [] - const rpc = { - request: async (command: string) => { - setters.push(command) - return {} - } - } - await applyPiRpcSessionOption(rpc, new Map(), 'model', host.record.options.model, {}, proof) - await applyPiRpcSessionOption(rpc, new Map(), 'effort', 'off', {}, proof) - const observations = new PiRpcOptionObservations(proof, () => true) - const observe = (effort: string) => { - observations.prepare()({ - models: host.home.models, - current: { - model: host.record.options.model, - effort, - confirmed: ['model', 'effort'] - } - }) - host.live = observations.read() - } - observe('minimal') - const answer = await host.read() - expect(answer.current).toMatchObject({ effort: 'off', reportedEffort: 'minimal' }) - expect(answer.current.confirmed).not.toContain('effort') - host.hostReads = 0 - const view = await mount(host) - expect(effort(view)).toMatchObject({ - valueSource: 'reported', - kind: { currentValue: 'minimal', choices: precise } - }) - expect(view.capture()?.effort).toBe('off') - observe('low') - await flush(() => host.initialCatalog.resolve(host.home)) - await flush(() => host.finish(0)) - expect(effort(view)).toMatchObject({ - valueSource: 'reported', - kind: { currentValue: 'low', choices: precise } - }) - await flush(() => { - void view.pick('off') - }) - expect(effort(view)?.valueSource).not.toBe('reported') - expect(view.capture()?.effort).toBe('off') - await flush(() => host.finish(1)) - expect(host.requests.length).toBeLessThanOrEqual(3) - if (host.requests.length === 3) { - await flush(() => host.finish(2)) - } - expect(effort(view)?.kind.currentValue).toBe('low') - const frozen = view.capture()! - host.record.options.effort = 'high' - const accepted = captureStructuredExecutionOptions( - { - agent: 'pi', - agents: new StructuredAgentRegistry([ - { - definition: PI_RPC_AGENT, - adapter: new PiRpcSessionAdapter({ - logger: createStructuredAgentSessionLogger(), - onLifecycle: () => {}, - onSettled: () => {}, - resolveLaunch: async () => { - throw new Error('capture does not launch') - } - }) - } - ]), - persistedOptions: host.record.options - }, - undefined, - frozen - ) - expect(accepted).toMatchObject({ options: { effort: 'off' } }) - expect(proof.current.get('effort')).toBe('off') - expect(setters).toEqual(['set_model', 'set_thinking_level']) - host.record.options.effort = 'off' - host.live = { - models: host.home.models, - current: { model: host.record.options.model, effort: 'off' } - } - const replacement = host.requests.length - await view.replace(3) - expect(effort(view)?.kind.currentValue).not.toBe('low') - await flush(() => host.finish(replacement)) - expect(effort(view)?.valueSource).not.toBe('reported') - expect(view.capture()?.effort).toBe('off') - await view.close() - }) -} diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture.ts index e8448e327ea..bc258adeaed 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture.ts @@ -1,14 +1,9 @@ -import { expect, it } from 'vitest' -import { piOptionActualContract } from './structured-agent-session-option-actual.test-fixture' +import { expect } from 'vitest' import type { AgentSessionModelCatalogResult, AgentSessionOptionResult } from '../../../../../shared/agent-session/agent-session-wire' import type { AgentSessionOptionsResult } from '../../../../../shared/agent-session/options/agent-session-options-result' -import type { - PiRefreshHarness, - PiRefreshMount -} from '../../../../../shared/agent-session/options/structured-agent-session-option-refresh.test-fixture-contract' import type { AgentModelCatalogService } from '../../../agent-model-catalog/agent-model-catalog-service-contract' import type { StructuredAgentSessionMutationContext } from '../../operations/structured-agent-session-mutation-context' import type { StructuredAgentSessionLiveOptions } from '../../options/structured-agent-session-option-models' @@ -129,167 +124,3 @@ export function piOptionRefreshHost(sessionId = 'session-1') { } return host } - -function effort(view: PiRefreshHarness) { - return view.snapshot().find((entry) => entry.id === 'effort') -} -function assertView(view: PiRefreshHarness, selected: string, choices = gap) { - expect(effort(view)).toMatchObject({ - settable: true, - kind: { currentValue: selected, choices } - }) - expect(effort(view)?.valueSource).not.toBe('reported') -} - -export function piOptionRefreshContract( - mount: PiRefreshMount, - flush: (work: () => void) => Promise -): void { - piOptionActualContract(piOptionRefreshHost, mount, flush) - it('completes a catalog burst through the host with one active and one trailing read per owner at 6 and 60 owners', async () => { - const counts: number[] = [] - for (const population of [6, 60]) { - const hosts = Array.from({ length: population }, (_, index) => - piOptionRefreshHost(`refresh-${index}`) - ) - const views: PiRefreshHarness[] = [] - for (const host of hosts) { - views.push(await mount(host)) - } - for (const view of views) { - assertView(view, 'xhigh') - expect(view.capture()?.effort).toBe('medium') - } - await flush(() => hosts.forEach((host) => host.initialCatalog.resolve(host.home))) - expect(hosts.map((host) => host.requests.length)).toEqual(Array(population).fill(1)) - for (let burst = 0; burst < 3; burst += 1) { - await flush(() => views.forEach((view) => view.demand())) - } - for (const view of views) { - assertView(view, 'xhigh') - } - expect( - hosts.every((host) => host.hostReads === 2 && host.record.options.effort === 'medium') - ).toBe(true) - hosts.forEach((host) => { - host.models = host.home.models - }) - await flush(() => hosts.forEach((host) => host.finish(0))) - expect(hosts.every((host) => host.requests.length === 2)).toBe(true) - for (const view of views) { - assertView(view, 'xhigh') - } - await flush(() => hosts.forEach((host) => host.finish(1))) - for (const view of views) { - assertView(view, 'high', precise) - } - counts.push(hosts.reduce((count, host) => count + host.hostReads, 0)) - expect( - hosts.every( - (host) => host.hostReads === 3 && host.catalogReads <= 6 && host.passiveReads === 0 - ) - ).toBe(true) - expect(hosts.every((host) => host.record.options.effort === 'medium')).toBe(true) - for (const view of views) { - await view.close() - } - } - expect(counts).toEqual([18, 180]) - }) - - it('releases failed reads, retains last-good without an invented retry, and drops queued work on teardown', async () => { - const host = piOptionRefreshHost() - const view = await mount(host) - await flush(() => host.initialCatalog.resolve(host.home)) - await flush(() => host.requests[0]!.reject(new Error('read failed'))) - assertView(view, 'xhigh') - expect(host.hostReads).toBe(2) - await flush(() => {}) - expect(host.hostReads).toBe(2) - await flush(() => view.demand()) - await flush(() => view.demand()) - host.models = host.home.models - await flush(() => host.requests[1]!.reject(new Error('read timeout'))) - expect(host.requests).toHaveLength(3) - await flush(() => host.finish(2)) - assertView(view, 'high', precise) - expect(host.record.options.effort).toBe('medium') - await flush(() => view.demand()) - await flush(() => view.demand()) - const dispatched = host.hostReads - await view.close() - await flush(() => host.finish(3)) - expect(host.hostReads).toBe(dispatched) - }) - - it('preserves a newer accepted High across an old answer, write parking, and a live-home refresh', async () => { - const host = piOptionRefreshHost() - host.models = host.home.models - const view = await mount(host) - await flush(() => host.initialCatalog.resolve(host.home)) - host.blockWrite = true - await flush(() => { - void view.pick('high') - }) - await flush(() => view.demand()) - await flush(() => host.finish(0)) - // Reads may complete while a controller write is pending; the raw overlay still wins. - expect(host.requests).toHaveLength(2) - expect(view.capture()?.effort).toBe('high') - await flush(() => host.write.resolve()) - assertView(view, 'high', precise) - expect(host.record.options.effort).toBe('high') - await flush(() => host.finish(1)) - expect(host.requests).toHaveLength(3) - // A held live answer carries future raw High, with no claim that the provider applied it. - host.live = { - models: [{ ...host.models[0]!, efforts: precise }], - current: { model: host.record.options.model, effort: 'high' } - } - await flush(() => host.finish(2)) - assertView(view, 'high', precise) - host.home = { ...host.home, models: [{ ...host.models[0]!, efforts: levels(['minimal']) }] } - await flush(() => view.demand()) - await flush(() => host.finish(3)) - assertView(view, 'high', precise) - expect(host.passiveReads).toBe(1) - await view.close() - }) - - it('fences old and queued answers across child replacement and host/context replacement', async () => { - const host = piOptionRefreshHost() - const view = await mount(host) - await flush(() => host.initialCatalog.resolve(host.home)) - await flush(() => view.demand()) - host.models = host.home.models - host.live = { - models: host.models, - current: { model: host.record.options.model, effort: 'medium' } - } - await view.replace(2) - const afterReplacement = host.hostReads - await flush(() => host.finish(0)) - expect(host.hostReads).toBe(afterReplacement) - await view.replace(3) - const beforeOldChild = view.snapshot() - await flush(() => host.finish(1)) - expect(view.snapshot()).toEqual(beforeOldChild) - // Phase equality is not child identity; then live-to-rest also changes host/client. - host.live = null - await view.replace(4, true) - const afterHostChange = host.hostReads - const beforeOldHost = view.snapshot() - await flush(() => host.finish(2)) - expect(host.hostReads).toBe(afterHostChange) - expect(view.snapshot()).toEqual(beforeOldHost) - await flush(() => host.finish(3)) - // A new host's catalog completion can supersede its first options read once. - expect(host.requests.length).toBeLessThanOrEqual(5) - if (host.requests.length === 5) { - await flush(() => host.finish(4)) - } - assertView(view, 'high', precise) - expect(host.record.options.effort).toBe('medium') - await view.close() - }) -} diff --git a/src/main/native-chat/agent-session-wire/publication/subscribers/agent-session-subscribe-input.ts b/src/main/native-chat/agent-session-wire/publication/subscribers/agent-session-subscribe-input.ts index 9dd5194b84f..b61ce30fa86 100644 --- a/src/main/native-chat/agent-session-wire/publication/subscribers/agent-session-subscribe-input.ts +++ b/src/main/native-chat/agent-session-wire/publication/subscribers/agent-session-subscribe-input.ts @@ -10,6 +10,8 @@ export type AgentSessionSubscribeInput = { id: string sessionId: string emit: (event: AgentSessionSubscribeEvent) => void + /** Ends the subscriber's stream once the host stops delivering to it, so the client resubscribes. */ + end?: (cause: unknown) => void cursor?: AgentJournalCursor /** Bound each frame to the phone bridge’s limit; RPC enables this for every phone. */ boundedFrames?: boolean @@ -26,6 +28,7 @@ export type AgentSessionSubscriberEmit = (event: AgentSessionSubscribeEvent) => export type Subscriber = { id: string emit: AgentSessionSubscriberEmit + end?: (cause: unknown) => void cursor: AgentJournalCursor fence: number forkMarkerView?: string diff --git a/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-subscribers.ts b/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-subscribers.ts index 99e49d59fdd..0f27517ec4b 100644 --- a/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-subscribers.ts +++ b/src/main/native-chat/agent-session-wire/publication/subscribers/structured-agent-session-subscribers.ts @@ -307,8 +307,10 @@ export class AgentSessionSubscribers { if (options?.historyView !== undefined && this.isActive(subscriber)) { subscriber.historyView = options.historyView } - } catch { + } catch (error) { + // A dropped subscriber gets no more frames, so end its stream or the client never resubscribes. this.drop(subscriber) + subscriber.end?.(error) } } diff --git a/src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-subscriber-failed-frame.test.ts b/src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-subscriber-failed-frame.test.ts new file mode 100644 index 00000000000..0ad0cc7dc0e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-subscriber-failed-frame.test.ts @@ -0,0 +1,66 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' +import { claudeProviderHandle } from '../../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import type { AgentSessionSubscribeEvent } from '../../../../../../shared/agent-session/agent-session-wire' +import { createTrackedJournalOpener } from '../../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { AgentSessionSubscribers } from '../structured-agent-session-subscribers' + +const SESSION = 'failed-frame-session' +let root: string +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-subscriber-failed-frame-')) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) + +afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +// #39926: a frame that failed to send dropped the subscriber but left its stream open, so the chat +// view sat on a healthy-looking, silent stream until the tab was reopened. +it('ends the stream of a subscriber dropped after a frame fails to send', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('provider-1', null) + }, + stateDirectory: join(root, 'journal') + }) + const subscribers = new AgentSessionSubscribers() + const received: AgentSessionSubscribeEvent['type'][] = [] + const end = vi.fn() + subscribers.open({ + id: 'chat-pane', + sessionId: SESSION, + journal, + fence: 1, + end, + emit: (event) => { + if (event.type === 'batch') { + throw new Error('frame could not be sent') + } + received.push(event.type) + } + }) + expect(received).toEqual(['snapshot']) + + await journal.appendItem( + { provider: 'orca', clientMessageId: 'reply' }, + { kind: 'status', text: 'reply' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(subscribers.subscriberCountForTests(SESSION)).toBe(0) + expect(end).toHaveBeenCalledTimes(1) +}) diff --git a/src/main/native-chat/structured-chat-naming-title.test.ts b/src/main/native-chat/structured-chat-naming-title.test.ts index c83dbaab30a..fbc58ba7566 100644 --- a/src/main/native-chat/structured-chat-naming-title.test.ts +++ b/src/main/native-chat/structured-chat-naming-title.test.ts @@ -117,18 +117,3 @@ it.each(['owner', 'same-text rename'] as const)( ) } ) - -it('uses current naming settings if they change while the title write is queued', async () => { - let eligible = true - const generate = vi.fn( - async (_record, _prompt, _current, automatic) => - automatic ? { name: 'CLI title', shouldApply: () => eligible } : { name: 'Configured title' } - ) - const state = rig(generate) - state.beforeWrite(async () => { - eligible = false - }) - state.start() - await state.done() - expect(state.record().conversationName).toBe('Configured title') -}) diff --git a/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts b/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts index 1f1485f1a2e..530e7c5a9b6 100644 --- a/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts +++ b/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts @@ -7,7 +7,6 @@ import { symlinkDirectorySync } from '../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { getFloatingWorkspaceFileRoots } from '../../ipc/floating-workspace-directory' import { rmSync, mkdtempSync, mkdirSync, realpathSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' @@ -92,27 +91,6 @@ describe('floating workspace trust on load', () => { }) }) - it('still loads a profile whose floating cwd is not a string', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { - floatingTerminalCwd: 42, - floatingTerminalCwdMigratedToAppWorkspace: true - }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - - expect(store.getSettings().floatingTerminalCwd).toBe('~') - // File authorization reads the cwd on every check, so it must keep working for this profile. - expect(getFloatingWorkspaceFileRoots(store).exactRoots).toEqual([]) - }) - it('never re-points a trusted folder through a link on load', async () => { const trustedTarget = join(testState.dir, 'trusted-target') const trustedLink = join(testState.dir, 'trusted-link') diff --git a/src/main/runtime/orchestration/crew/crew-recipient-dispatches.ts b/src/main/runtime/orchestration/crew/crew-recipient-dispatches.ts index a0183f3e79b..16c9f212fd3 100644 --- a/src/main/runtime/orchestration/crew/crew-recipient-dispatches.ts +++ b/src/main/runtime/orchestration/crew/crew-recipient-dispatches.ts @@ -3,7 +3,7 @@ import { dispatchAssigneeCoordinatorKey, selectRunBoundDispatchRecipient } from '../../rpc/methods/orchestration/messaging/recipient-routing' -import { federatedControlMailRefusal } from '../../rpc/methods/orchestration/messaging/send-control-mail' +import { federatedControlMailRefusal } from '../legacy-remote-home/legacy-remote-home' import type { createLineageRunningSessionResolver } from '../addressing/session-lineage/structured-session-lineage' import type { DispatchInput } from './crew-recipient-owner-queries' import type { CrewRecipientTerminal } from './crew-recipient-inputs' diff --git a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts index a8d353e63a1..7d5bc369062 100644 --- a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts @@ -7,17 +7,9 @@ import { attachDispatchContextStore } from './dispatch-context/dispatch-context- import { attachDispatchLookup } from './dispatch-context/dispatch-lookup' import { attachDispatchDepth } from './dispatch-depth' import { attachWorkerReportSettlement } from './dispatch-context/worker-report-settlement' -import { attachFederatedDispatchStore } from './federation/federated-dispatch-store' -import { attachFederatedDispatchObservationFence } from './federation/federated-dispatch-observation-fence' import { attachFederationRelayAck } from './federation/federation-relay-ack' -import { attachFederationRelayEnqueue } from './federation/federation-relay-enqueue' -import { attachFederationRelayImport } from './federation/federation-relay-import' -import { attachFederationRelayItem } from './federation/federation-relay-item' -import { attachRemoteDispatchAttachmentAuthority } from './federation/remote-dispatch-attachment-authority' -import { attachRemoteDispatchAttachmentCreate } from './federation/remote-dispatch-attachment-create' -import { attachRemoteDispatchAttachmentRelease } from './federation/remote-dispatch-attachment-release' -import { attachRemoteDispatchAttachmentStop } from './federation/remote-dispatch-attachment-stop' -import { attachRemoteQuestionStore } from './federation/remote-question-store' +import { attachLegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods' +import { attachLegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods' import { attachPeerMailStore } from './federation/peer-mail-store' import { attachLegacyAskOperation } from './legacy/legacy-ask-operation' import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates' @@ -54,7 +46,6 @@ import { attachSchemaMigrate } from './schema/migrate' import { attachSchemaColumnProbes } from './schema/schema-column-probes' import { attachTaskStore } from './tasks/task-store' import { attachTaskStatusTransition } from './tasks/task-status-transition' -import { attachFederatedWorkerStartReconcile } from './worker-dispatch/federated-worker-start-reconcile' import { attachWorkerDispatchAbandon } from './worker-dispatch/worker-dispatch-abandon' import { attachWorkerDispatchAuthority } from './worker-dispatch/worker-dispatch-authority' import { attachWorkerDispatchOutcome } from './worker-dispatch/worker-dispatch-outcome' @@ -109,22 +100,13 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void attachWorkerDispatchStage(ctor) attachWorkerDispatchAuthority(ctor) attachWorkerDispatchOutcome(ctor) - attachFederatedWorkerStartReconcile(ctor) attachWorkerTerminalRecovery(ctor) attachWorkerDispatchStop(ctor) attachWorkerDispatchAbandon(ctor) - attachFederatedDispatchStore(ctor) - attachFederatedDispatchObservationFence(ctor) - attachRemoteDispatchAttachmentCreate(ctor) - attachRemoteDispatchAttachmentAuthority(ctor) - attachRemoteDispatchAttachmentRelease(ctor) - attachRemoteDispatchAttachmentStop(ctor) - attachFederationRelayEnqueue(ctor) + attachLegacyRemoteHomeDbMethods(ctor) + attachLegacyRemoteDbMethods(ctor) attachFederationRelayAck(ctor) - attachFederationRelayImport(ctor) - attachRemoteQuestionStore(ctor) attachPeerMailStore(ctor) - attachFederationRelayItem(ctor) attachWorkerTerminalResourceStore(ctor) attachWorkerTerminalTransfer(ctor) attachWorkerTerminalRelease(ctor) diff --git a/src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts b/src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts index 314c4d269e5..229fa21a593 100644 --- a/src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts +++ b/src/main/runtime/orchestration/db/federated-worker-report-outcome.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { parseFederatedWorkerReportOutcome } from './federated-worker-report-outcome' +import { parseFederatedWorkerReportOutcome } from '../legacy-remote/federated-worker-report-outcome' describe('federated-worker-report-outcome', () => { it('reads succeeded or failed from a nested report payload', () => { diff --git a/src/main/runtime/orchestration/db/federation/federation-relay-ack.ts b/src/main/runtime/orchestration/db/federation/federation-relay-ack.ts index 9029bbc7c3a..53ee477953d 100644 --- a/src/main/runtime/orchestration/db/federation/federation-relay-ack.ts +++ b/src/main/runtime/orchestration/db/federation/federation-relay-ack.ts @@ -1,36 +1,7 @@ -import type { - WorkerReportOutcome, - FederationRelayDirection, - FederationRelayItemRow -} from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { parseFederatedWorkerReportOutcome } from '../federated-worker-report-outcome' +import type { FederationRelayDirection, FederationRelayItemRow } from '../orchestration-records' +import type { FederationRelayAcknowledgment } from '../../legacy-remote/legacy-remote-db-methods' import type { OrchestrationDb } from '../orchestration-db' -export function listFederationRelay( - this: OrchestrationDb, - params: { - dispatchId: string - direction: FederationRelayDirection - afterSequence: number - limit?: number - } -): FederationRelayItemRow[] { - return this.db - .prepare( - `SELECT * FROM federation_relay_items - WHERE dispatch_id = ? AND direction = ? AND sequence > ? - ORDER BY sequence LIMIT ?` - ) - .all( - params.dispatchId, - params.direction, - params.afterSequence, - Math.min(Math.max(params.limit ?? 50, 1), 50) - ) as FederationRelayItemRow[] -} - export function listPendingFederationRelay( this: OrchestrationDb, dispatchId: string, @@ -48,78 +19,11 @@ export function listPendingFederationRelay( export function acknowledgeFederationRelay( this: OrchestrationDb, - params: { - dispatchId: string - direction: FederationRelayDirection - throughSequence: number - settleRemoteReports?: { sequence: number; outcome?: WorkerReportOutcome }[] - // Only the home's acceptance proves settlement; arm after it, never at queue time. - armAutoRelease?: boolean - } + params: FederationRelayAcknowledgment ): void { this.db.exec('BEGIN IMMEDIATE') try { - const settledReports = params.settleRemoteReports ?? [] - for (const settledReport of settledReports) { - const report = this.getFederationRelayItem( - params.dispatchId, - params.direction, - settledReport.sequence - ) - if ( - params.direction !== 'to_home' || - settledReport.sequence > params.throughSequence || - report?.kind !== 'worker_done' || - (settledReport.outcome !== undefined && - parseFederatedWorkerReportOutcome(report.payload) !== settledReport.outcome) - ) { - throw new OrchestrationError( - 'request_mismatch', - `Federation acknowledgment for ${params.dispatchId} does not match its queued worker_done.` - ) - } - } - const attachment = this.getRemoteDispatchAttachment(params.dispatchId) - if ( - params.direction === 'to_home' && - attachment !== undefined && - attachment.protocol_version >= ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION - ) { - const acknowledgedReports = this.db - .prepare( - `SELECT sequence FROM federation_relay_items - WHERE dispatch_id = ? AND direction = 'to_home' AND kind = 'worker_done' - AND acked_at IS NULL AND sequence <= ?` - ) - .all(params.dispatchId, params.throughSequence) as { sequence: number }[] - const settledSequences = new Set(settledReports.map((report) => report.sequence)) - if (acknowledgedReports.some((report) => !settledSequences.has(report.sequence))) { - throw new OrchestrationError( - 'request_mismatch', - `Federation acknowledgment for ${params.dispatchId} omits a worker_done settlement.` - ) - } - } - const terminalOutcomes = new Set( - settledReports.flatMap((report) => (report.outcome ? [report.outcome] : [])) - ) - if (terminalOutcomes.size > 1) { - throw new OrchestrationError( - 'request_mismatch', - `Federation acknowledgment for ${params.dispatchId} contains conflicting settlements.` - ) - } - const terminalOutcome = settledReports.find((report) => report.outcome)?.outcome - if (terminalOutcome) { - this.settleRemoteAttachmentInRelayTransaction( - params.dispatchId, - terminalOutcome, - 'worker_report_settled' - ) - if (params.armAutoRelease) { - this.armWorkerTerminalAutoReleaseStatement(params.dispatchId) - } - } + this.settleRemoteReportsInRelayAcknowledgment(params) this.db .prepare( `UPDATE federation_relay_items SET acked_at = COALESCE(acked_at, datetime('now')) @@ -133,93 +37,14 @@ export function acknowledgeFederationRelay( } } -export function setFederatedHomeImportSequence( - this: OrchestrationDb, - dispatchId: string, - sequence: number -): void { - this.db - .prepare( - `UPDATE federated_dispatches - SET to_home_imported_sequence = ?, updated_at = datetime('now') - WHERE dispatch_id = ? AND to_home_imported_sequence < ?` - ) - .run(sequence, dispatchId, sequence) -} - -export function recordFederatedHomeAcknowledgment( - this: OrchestrationDb, - params: { - dispatchId: string - remoteRuntimeEpoch: string - sequence: number - } -): void { - const federated = this.getFederatedDispatch(params.dispatchId) - if ( - !federated || - !Number.isInteger(params.sequence) || - params.sequence < 0 || - params.sequence > federated.to_home_imported_sequence - ) { - throw new OrchestrationError( - 'request_mismatch', - `Federation acknowledgment for ${params.dispatchId} exceeds imported relay state.` - ) - } - this.db - .prepare( - `UPDATE federated_dispatches - SET remote_runtime_epoch = ?, - to_home_acknowledged_sequence = CASE - WHEN remote_runtime_epoch = ? - THEN MAX(to_home_acknowledged_sequence, ?) - ELSE ? - END, - updated_at = datetime('now') - WHERE dispatch_id = ?` - ) - .run( - params.remoteRuntimeEpoch, - params.remoteRuntimeEpoch, - params.sequence, - params.sequence, - params.dispatchId - ) -} - -/** A worker_done queued for the Run home that it has not acknowledged. */ -export function hasPendingFederatedWorkerReport( - this: OrchestrationDb, - dispatchId: string -): boolean { - return ( - this.db - .prepare( - `SELECT 1 FROM federation_relay_items - WHERE dispatch_id = ? AND direction = 'to_home' AND kind = 'worker_done' - AND acked_at IS NULL LIMIT 1` - ) - .get(dispatchId) !== undefined - ) -} - export type FederationRelayAckMethods = { - listFederationRelay: typeof listFederationRelay listPendingFederationRelay: typeof listPendingFederationRelay acknowledgeFederationRelay: typeof acknowledgeFederationRelay - setFederatedHomeImportSequence: typeof setFederatedHomeImportSequence - recordFederatedHomeAcknowledgment: typeof recordFederatedHomeAcknowledgment - hasPendingFederatedWorkerReport: typeof hasPendingFederatedWorkerReport } export function attachFederationRelayAck(ctor: { prototype: object }): void { Object.assign(ctor.prototype, { - listFederationRelay, listPendingFederationRelay, - acknowledgeFederationRelay, - setFederatedHomeImportSequence, - recordFederatedHomeAcknowledgment, - hasPendingFederatedWorkerReport + acknowledgeFederationRelay }) } diff --git a/src/main/runtime/orchestration/db/orchestration-db-methods.ts b/src/main/runtime/orchestration/db/orchestration-db-methods.ts index 824b031a2ee..0e06a05191d 100644 --- a/src/main/runtime/orchestration/db/orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/orchestration-db-methods.ts @@ -6,17 +6,9 @@ import type { DispatchContextStoreMethods } from './dispatch-context/dispatch-co import type { DispatchLookupMethods } from './dispatch-context/dispatch-lookup' import type { DispatchDepthMethods } from './dispatch-depth' import type { WorkerReportSettlementMethods } from './dispatch-context/worker-report-settlement' -import type { FederatedDispatchStoreMethods } from './federation/federated-dispatch-store' -import type { FederatedDispatchObservationFenceMethods } from './federation/federated-dispatch-observation-fence' import type { FederationRelayAckMethods } from './federation/federation-relay-ack' -import type { FederationRelayEnqueueMethods } from './federation/federation-relay-enqueue' -import type { FederationRelayImportMethods } from './federation/federation-relay-import' -import type { FederationRelayItemMethods } from './federation/federation-relay-item' -import type { RemoteDispatchAttachmentAuthorityMethods } from './federation/remote-dispatch-attachment-authority' -import type { RemoteDispatchAttachmentCreateMethods } from './federation/remote-dispatch-attachment-create' -import type { RemoteDispatchAttachmentReleaseMethods } from './federation/remote-dispatch-attachment-release' -import type { RemoteDispatchAttachmentStopMethods } from './federation/remote-dispatch-attachment-stop' -import type { RemoteQuestionStoreMethods } from './federation/remote-question-store' +import type { LegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods' +import type { LegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods' import type { PeerMailStoreMethods } from './federation/peer-mail-store' import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation' import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates' @@ -52,7 +44,6 @@ import type { SchemaMigrateMethods } from './schema/migrate' import type { SchemaColumnProbesMethods } from './schema/schema-column-probes' import type { TaskStoreMethods } from './tasks/task-store' import type { TaskStatusTransitionMethods } from './tasks/task-status-transition' -import type { FederatedWorkerStartReconcileMethods } from './worker-dispatch/federated-worker-start-reconcile' import type { WorkerDispatchAbandonMethods } from './worker-dispatch/worker-dispatch-abandon' import type { WorkerDispatchAuthorityMethods } from './worker-dispatch/worker-dispatch-authority' import type { WorkerDispatchOutcomeMethods } from './worker-dispatch/worker-dispatch-outcome' @@ -106,22 +97,13 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods & WorkerDispatchStageMethods & WorkerDispatchAuthorityMethods & WorkerDispatchOutcomeMethods & - FederatedWorkerStartReconcileMethods & WorkerTerminalRecoveryMethods & WorkerDispatchStopMethods & WorkerDispatchAbandonMethods & - FederatedDispatchStoreMethods & - FederatedDispatchObservationFenceMethods & - RemoteDispatchAttachmentCreateMethods & - RemoteDispatchAttachmentAuthorityMethods & - RemoteDispatchAttachmentReleaseMethods & - RemoteDispatchAttachmentStopMethods & - FederationRelayEnqueueMethods & + LegacyRemoteHomeDbMethods & + LegacyRemoteDbMethods & FederationRelayAckMethods & - FederationRelayImportMethods & - RemoteQuestionStoreMethods & PeerMailStoreMethods & - FederationRelayItemMethods & StructuredMailSendStoreMethods & WorkerTerminalResourceStoreMethods & WorkerTerminalTransferMethods & diff --git a/src/main/runtime/orchestration/db/schema/federated-home-run-migration.test.ts b/src/main/runtime/orchestration/db/schema/federated-home-run-migration.test.ts index addc3ca0f9a..7446896e749 100644 --- a/src/main/runtime/orchestration/db/schema/federated-home-run-migration.test.ts +++ b/src/main/runtime/orchestration/db/schema/federated-home-run-migration.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { OrchestrationDb } from '../orchestration-db' import { SCHEMA_VERSION, federatedStubHomeRunId } from '../contract-constants' -import { importFederatedControlMessage } from '../../federation/relay/federation-control-message' +import { importFederatedControlMessage } from '../../legacy-remote/federation-control-message' describe('federated home Run migration', () => { let db: OrchestrationDb diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts index 40173d37937..fc6dcdb86c3 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-auto-release.ts @@ -174,72 +174,6 @@ export function admitWorkerChatReleaseClose( return changes > 0 } -/** Only for a host that cannot release on its own; arms once, so a retain or release before settlement still wins. */ -export function armFederatedHomeAutoRelease( - this: OrchestrationDb, - dispatchId: string, - nowMs = Date.now() -): void { - const { changes } = this.db - .prepare( - `UPDATE federated_dispatches - SET home_auto_release_at = ?, home_auto_release_state = 'armed', updated_at = datetime('now') - WHERE dispatch_id = ? AND home_auto_release_state IS NULL` - ) - .run(toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS), dispatchId) - if (changes > 0) { - this.workerTerminalAutoReleaseListener?.() - } -} - -/** A retain, an explicit release or the host's answer to an attempt ends the home deadline for good. */ -export function endFederatedHomeAutoRelease(this: OrchestrationDb, dispatchId: string): void { - this.db - .prepare( - `UPDATE federated_dispatches - SET home_auto_release_at = NULL, home_auto_release_state = 'ended', updated_at = datetime('now') - WHERE dispatch_id = ? AND home_auto_release_state IS NOT 'ended'` - ) - .run(dispatchId) -} - -/** Claiming postpones the deadline instead of hiding it, so an attempt cut short by a crash or failure runs again. */ -export function claimDueFederatedHomeAutoReleases(this: OrchestrationDb, nowMs: number): string[] { - if (this.workerAutoReleaseEnabled?.() === false) { - return [] - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SELECT names exactly this one column. - const due = this.db - .prepare( - `SELECT dispatch_id FROM federated_dispatches - WHERE home_auto_release_state = 'armed' AND home_auto_release_at <= ?` - ) - .all(toSqliteUtcTimestamp(nowMs)) as { dispatch_id: string }[] - const claim = this.db.prepare( - `UPDATE federated_dispatches - SET home_auto_release_at = ?, updated_at = datetime('now') - WHERE dispatch_id = ? AND home_auto_release_state = 'armed' AND home_auto_release_at <= ?` - ) - const retryAt = toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS) - return due.flatMap(({ dispatch_id }) => - claim.run(retryAt, dispatch_id, toSqliteUtcTimestamp(nowMs)).changes > 0 ? [dispatch_id] : [] - ) -} - -export function isFederatedHomeAutoReleaseArmed( - this: OrchestrationDb, - dispatchId: string -): boolean { - return ( - this.db - .prepare( - `SELECT 1 FROM federated_dispatches - WHERE dispatch_id = ? AND home_auto_release_state = 'armed'` - ) - .get(dispatchId) !== undefined - ) -} - export function nextWorkerTerminalAutoReleaseAtMs(this: OrchestrationDb): number | null { // Off: nothing is due, so no timer runs until the setting turns back on. if (this.workerAutoReleaseEnabled?.() === false) { @@ -276,10 +210,6 @@ export type WorkerTerminalAutoReleaseMethods = { claimDueWorkerTerminalAutoReleases: typeof claimDueWorkerTerminalAutoReleases admitWorkerChatReleaseClose: typeof admitWorkerChatReleaseClose nextWorkerTerminalAutoReleaseAtMs: typeof nextWorkerTerminalAutoReleaseAtMs - armFederatedHomeAutoRelease: typeof armFederatedHomeAutoRelease - endFederatedHomeAutoRelease: typeof endFederatedHomeAutoRelease - claimDueFederatedHomeAutoReleases: typeof claimDueFederatedHomeAutoReleases - isFederatedHomeAutoReleaseArmed: typeof isFederatedHomeAutoReleaseArmed } export function attachWorkerTerminalAutoRelease(ctor: { prototype: object }): void { @@ -291,10 +221,6 @@ export function attachWorkerTerminalAutoRelease(ctor: { prototype: object }): vo deferWorkerTerminalAutoRelease, claimDueWorkerTerminalAutoReleases, admitWorkerChatReleaseClose, - nextWorkerTerminalAutoReleaseAtMs, - armFederatedHomeAutoRelease, - endFederatedHomeAutoRelease, - claimDueFederatedHomeAutoReleases, - isFederatedHomeAutoReleaseArmed + nextWorkerTerminalAutoReleaseAtMs }) } diff --git a/src/main/runtime/orchestration/federation/relay/federation-relay-prefix.ts b/src/main/runtime/orchestration/federation/relay/federation-relay-prefix.ts index 8de849f6d82..f3023c17c13 100644 --- a/src/main/runtime/orchestration/federation/relay/federation-relay-prefix.ts +++ b/src/main/runtime/orchestration/federation/relay/federation-relay-prefix.ts @@ -1,7 +1,7 @@ import type { RuntimeRequestPreparation } from '../../../../../shared/runtime-rpc-envelope' import { REMOTE_RUNTIME_MAX_INBOUND_REQUEST_JSON_BYTES } from '../../../../../shared/remote-runtime/remote-runtime-memory-limits' import { OrchestrationError } from '../../orchestration-error' -import type { federationRelayWireItem } from './federation-relay-wire' +import type { federationRelayWireItem } from '../../legacy-remote/legacy-remote' /** Fit only this already-selected page, using the actual sending socket's complete serializer. */ export function federationRelayPrefix( diff --git a/src/main/runtime/orchestration/federation/runtime-orchestration-federation.ts b/src/main/runtime/orchestration/federation/runtime-orchestration-federation.ts index f22d5f315ea..8dfcbf50083 100644 --- a/src/main/runtime/orchestration/federation/runtime-orchestration-federation.ts +++ b/src/main/runtime/orchestration/federation/runtime-orchestration-federation.ts @@ -19,16 +19,16 @@ import type { import { OrchestrationError } from '../orchestration-error' import { clearFederationAckCheckpoints, - releaseFederationAckCheckpoint -} from './synchronization/federation-ack-checkpoints' -import { syncFederatedDispatch } from './synchronization/federation-sync' + releaseFederationAckCheckpoint, + syncFederatedDispatch, + FederationAcknowledgmentRecovery +} from '../legacy-remote-home/legacy-remote-home' import type { OrchestrationDb } from '../db/orchestration-db' import type { FederationRuntime } from './federation-runtime' import { FederationRelayScheduler, type FederationRelayTickOutcome } from './relay/federation-relay-scheduler' -import { FederationAcknowledgmentRecovery } from './relay/federation-acknowledgment-recovery' export class RuntimeOrchestrationFederation { private readonly relays = new FederationRelayScheduler((dispatchId) => this.relayTick(dispatchId)) diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts b/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts index 1a0a797b607..950c34586cd 100644 --- a/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts +++ b/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts @@ -6,7 +6,7 @@ import { getFederationAckedThrough, recordFederationAckCheckpoint, type FederationAckIdentity -} from './federation-ack-checkpoints' +} from '../../legacy-remote-home/federation-ack-checkpoints' describe('federation acknowledgment checkpoints', () => { it('matches checkpoints only to their exact remote identity and never moves backward', () => { diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts b/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts index c5c70557a30..d43957bdd3c 100644 --- a/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts +++ b/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' import { createIdleSyncHarness } from './federation-sync-test-harness' -import { armHomeAutoReleaseForOlderHost } from './federation-sync-capability' +import { armHomeAutoReleaseForOlderHost } from '../../legacy-remote-home/federation-sync-capability' function releasableTerminalWorker() { const harness = createIdleSyncHarness() diff --git a/src/main/runtime/orchestration/legacy-remote-entry-points.test.ts b/src/main/runtime/orchestration/legacy-remote-entry-points.test.ts new file mode 100644 index 00000000000..82e347aef52 --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote-entry-points.test.ts @@ -0,0 +1,89 @@ +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { dirname, join, relative, resolve, sep } from 'node:path' +import { describe, expect, it } from 'vitest' + +const SRC = resolve(import.meta.dirname, '../../..') +// Each folder has one entry module, plus a DB-only one so the DB layer never loads rpc code. +// The two folders are one frozen unit and may import each other directly. +const DB_LAYER = 'main/runtime/orchestration/db/' +const LEGACY_ENTRIES_BY_FOLDER = { + 'main/runtime/orchestration/legacy-remote/': { + entry: 'main/runtime/orchestration/legacy-remote/legacy-remote.ts', + dbEntry: 'main/runtime/orchestration/legacy-remote/legacy-remote-db-methods.ts' + }, + 'main/runtime/orchestration/legacy-remote-home/': { + entry: 'main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts', + dbEntry: 'main/runtime/orchestration/legacy-remote-home/legacy-remote-home-db-methods.ts' + } +} +// Legacy starts load the worker list, so it bypasses the entry module to stay out of an import cycle. +const DIRECT_IMPORTS = new Set([ + 'main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts -> main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts' +]) +const IMPORT_SPECIFIER = + /(?:from\s+|import\s*\(\s*|import\s+|require\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g + +function productionSources(dir: string, out: string[] = []): string[] { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name) + if (entry.isDirectory()) { + if (entry.name !== 'node_modules') { + productionSources(path, out) + } + } else if ( + /\.tsx?$/.test(entry.name) && + !/\.(test|spec)\.|test-support|harness/.test(entry.name) + ) { + out.push(path) + } + } + return out +} + +function srcPath(file: string): string { + return relative(SRC, file).split(sep).join('/') +} + +function resolveSpecifier(fromFile: string, specifier: string): string | undefined { + const base = resolve(dirname(fromFile), specifier) + return [base, `${base}.ts`, `${base}.tsx`, join(base, 'index.ts')].find( + (candidate) => existsSync(candidate) && statSync(candidate).isFile() + ) +} + +describe('legacy remote-attachment folders', () => { + it('are imported from outside only through their entry module', () => { + const violations: string[] = [] + const entryImporters = new Set() + for (const file of productionSources(SRC)) { + const from = srcPath(file) + for (const match of readFileSync(file, 'utf8').matchAll(IMPORT_SPECIFIER)) { + const target = resolveSpecifier(file, match[1]) + if (!target) { + continue + } + const to = srcPath(target) + for (const [folder, { entry, dbEntry }] of Object.entries(LEGACY_ENTRIES_BY_FOLDER)) { + if ( + to.startsWith(folder) && + !Object.keys(LEGACY_ENTRIES_BY_FOLDER).some((f) => from.startsWith(f)) + ) { + if (to === entry || (to === dbEntry && from.startsWith(DB_LAYER))) { + entryImporters.add(`${from} -> ${to}`) + } else if (!DIRECT_IMPORTS.has(`${from} -> ${to}`)) { + violations.push(`${from} -> ${to}`) + } + } + } + } + } + expect(violations).toEqual([]) + // The capability branch on each side: legacy worker starts and the legacy federation methods. + expect(entryImporters).toContain( + 'main/runtime/rpc/methods/orchestration/worker/workers.ts -> main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts' + ) + expect(entryImporters).toContain( + 'main/runtime/rpc/methods/orchestration/federation/federation-methods.ts -> main/runtime/orchestration/legacy-remote/legacy-remote.ts' + ) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts index 6fac7950954..69767a4c3b9 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-attach-receipt.ts @@ -1,4 +1,4 @@ -import type { OrchestrationWorkerLaunchReceipt } from '../worker/worker-launch-preferences' +import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences' export type RemoteFederatedWorkerStartReceipt = { dispatchId: string diff --git a/src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-dispatch-store.ts similarity index 71% rename from src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-dispatch-store.ts index 4a0bf9c11f4..f2cf2a85589 100644 --- a/src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-dispatch-store.ts @@ -1,6 +1,6 @@ -import type { FederatedDispatchRow } from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import type { OrchestrationDb } from '../orchestration-db' +import type { FederatedDispatchRow } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' export function getFederatedDispatch( this: OrchestrationDb, @@ -125,6 +125,61 @@ export function updateFederatedDispatchRuntimeEpoch( .run(remoteRuntimeEpoch, dispatchId, remoteRuntimeEpoch) } +export function setFederatedHomeImportSequence( + this: OrchestrationDb, + dispatchId: string, + sequence: number +): void { + this.db + .prepare( + `UPDATE federated_dispatches + SET to_home_imported_sequence = ?, updated_at = datetime('now') + WHERE dispatch_id = ? AND to_home_imported_sequence < ?` + ) + .run(sequence, dispatchId, sequence) +} + +export function recordFederatedHomeAcknowledgment( + this: OrchestrationDb, + params: { + dispatchId: string + remoteRuntimeEpoch: string + sequence: number + } +): void { + const federated = this.getFederatedDispatch(params.dispatchId) + if ( + !federated || + !Number.isInteger(params.sequence) || + params.sequence < 0 || + params.sequence > federated.to_home_imported_sequence + ) { + throw new OrchestrationError( + 'request_mismatch', + `Federation acknowledgment for ${params.dispatchId} exceeds imported relay state.` + ) + } + this.db + .prepare( + `UPDATE federated_dispatches + SET remote_runtime_epoch = ?, + to_home_acknowledged_sequence = CASE + WHEN remote_runtime_epoch = ? + THEN MAX(to_home_acknowledged_sequence, ?) + ELSE ? + END, + updated_at = datetime('now') + WHERE dispatch_id = ?` + ) + .run( + params.remoteRuntimeEpoch, + params.remoteRuntimeEpoch, + params.sequence, + params.sequence, + params.dispatchId + ) +} + export type FederatedDispatchStoreMethods = { getFederatedDispatch: typeof getFederatedDispatch listFederatedDispatchesByIds: typeof listFederatedDispatchesByIds @@ -133,6 +188,8 @@ export type FederatedDispatchStoreMethods = { isFederatedDispatchRelayEligible: typeof isFederatedDispatchRelayEligible updateFederatedDispatchResources: typeof updateFederatedDispatchResources updateFederatedDispatchRuntimeEpoch: typeof updateFederatedDispatchRuntimeEpoch + setFederatedHomeImportSequence: typeof setFederatedHomeImportSequence + recordFederatedHomeAcknowledgment: typeof recordFederatedHomeAcknowledgment } export function attachFederatedDispatchStore(ctor: { prototype: object }): void { @@ -143,6 +200,8 @@ export function attachFederatedDispatchStore(ctor: { prototype: object }): void findNextTerminalFederatedDispatchPendingAcknowledgment, isFederatedDispatchRelayEligible, updateFederatedDispatchResources, - updateFederatedDispatchRuntimeEpoch + updateFederatedDispatchRuntimeEpoch, + setFederatedHomeImportSequence, + recordFederatedHomeAcknowledgment }) } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-fleet-host-groups.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-host-groups.ts similarity index 77% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-fleet-host-groups.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-fleet-host-groups.ts index 445e6d80293..f2ebbb2145e 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-fleet-host-groups.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-host-groups.ts @@ -1,7 +1,7 @@ -import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import type { OrchestrationDb } from '../db/orchestration-db' +import type { FederatedDispatchRow } from '../db/orchestration-records' +import type { OrcaRuntimeService } from '../../orca-runtime' type HostGroup = { environmentId: string diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-fleet-snapshot.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts similarity index 91% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-fleet-snapshot.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts index 409fe4ff625..c8e71b5e7ad 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-fleet-snapshot.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts @@ -1,18 +1,18 @@ import { groupFederatedDispatches } from './federated-fleet-host-groups' -import { mapWithConcurrency } from '../../../../../../shared/map-with-concurrency' -import { ORCHESTRATION_FEDERATION_FLEET_SNAPSHOT_RUNTIME_CAPABILITY } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' +import { ORCHESTRATION_FEDERATION_FLEET_SNAPSHOT_RUNTIME_CAPABILITY } from '../../../../shared/orchestration/orchestration-runtime-capabilities' import { refreshOrchestrationFleetLivenessAttention, type FleetDurableWorker, type OrchestrationFleetPage -} from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' -import { projectFleetNextAction } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection' -import { getOrchestrationPeerCapabilityCache } from '../../../../orchestration/federation/orchestration-peer-capability-cache' -import { liveFederatedHomeAutoReleaseAt } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { resolvePinnedFederatedServer } from '../worker/pinned-federated-server' +} from '../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import { projectFleetNextAction } from '../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection' +import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration-peer-capability-cache' +import { liveFederatedHomeAutoReleaseAt } from '../terminal-authority/release/worker-terminal-ownership' +import type { OrchestrationDb } from '../db/orchestration-db' +import { OrchestrationError } from '../orchestration-error' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' import { applyConfirmedFederatedReleaseHomeProjection } from './federated-worker-release' const FLEET_HOST_CONCURRENCY = 4 diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-home-auto-release-store.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-home-auto-release-store.ts new file mode 100644 index 00000000000..208131ecbbc --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-home-auto-release-store.ts @@ -0,0 +1,85 @@ +import type { OrchestrationDb } from '../db/orchestration-db' +import { toSqliteUtcTimestamp } from '../db/utc-timestamp' +import { WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS } from '../db/worker-terminal/worker-terminal-auto-release' + +/** Only for a host that cannot release on its own; arms once, so a retain or release before settlement still wins. */ +export function armFederatedHomeAutoRelease( + this: OrchestrationDb, + dispatchId: string, + nowMs = Date.now() +): void { + const { changes } = this.db + .prepare( + `UPDATE federated_dispatches + SET home_auto_release_at = ?, home_auto_release_state = 'armed', updated_at = datetime('now') + WHERE dispatch_id = ? AND home_auto_release_state IS NULL` + ) + .run(toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS), dispatchId) + if (changes > 0) { + this.workerTerminalAutoReleaseListener?.() + } +} + +/** A retain, an explicit release or the host's answer to an attempt ends the home deadline for good. */ +export function endFederatedHomeAutoRelease(this: OrchestrationDb, dispatchId: string): void { + this.db + .prepare( + `UPDATE federated_dispatches + SET home_auto_release_at = NULL, home_auto_release_state = 'ended', updated_at = datetime('now') + WHERE dispatch_id = ? AND home_auto_release_state IS NOT 'ended'` + ) + .run(dispatchId) +} + +/** Claiming postpones the deadline instead of hiding it, so an attempt cut short by a crash or failure runs again. */ +export function claimDueFederatedHomeAutoReleases(this: OrchestrationDb, nowMs: number): string[] { + if (this.workerAutoReleaseEnabled?.() === false) { + return [] + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SELECT names exactly this one column. + const due = this.db + .prepare( + `SELECT dispatch_id FROM federated_dispatches + WHERE home_auto_release_state = 'armed' AND home_auto_release_at <= ?` + ) + .all(toSqliteUtcTimestamp(nowMs)) as { dispatch_id: string }[] + const claim = this.db.prepare( + `UPDATE federated_dispatches + SET home_auto_release_at = ?, updated_at = datetime('now') + WHERE dispatch_id = ? AND home_auto_release_state = 'armed' AND home_auto_release_at <= ?` + ) + const retryAt = toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS) + return due.flatMap(({ dispatch_id }) => + claim.run(retryAt, dispatch_id, toSqliteUtcTimestamp(nowMs)).changes > 0 ? [dispatch_id] : [] + ) +} + +export function isFederatedHomeAutoReleaseArmed( + this: OrchestrationDb, + dispatchId: string +): boolean { + return ( + this.db + .prepare( + `SELECT 1 FROM federated_dispatches + WHERE dispatch_id = ? AND home_auto_release_state = 'armed'` + ) + .get(dispatchId) !== undefined + ) +} + +export type FederatedHomeAutoReleaseStoreMethods = { + armFederatedHomeAutoRelease: typeof armFederatedHomeAutoRelease + endFederatedHomeAutoRelease: typeof endFederatedHomeAutoRelease + claimDueFederatedHomeAutoReleases: typeof claimDueFederatedHomeAutoReleases + isFederatedHomeAutoReleaseArmed: typeof isFederatedHomeAutoReleaseArmed +} + +export function attachFederatedHomeAutoReleaseStore(ctor: { prototype: object }): void { + Object.assign(ctor.prototype, { + armFederatedHomeAutoRelease, + endFederatedHomeAutoRelease, + claimDueFederatedHomeAutoReleases, + isFederatedHomeAutoReleaseArmed + }) +} diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts similarity index 73% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts index 8c90bf47eac..e0249544e10 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts @@ -1,11 +1,11 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { readCallerStoreInstallationId } from '../../../../hosts/platform-probe/host-descriptor' -import { getCanonicalUserDataPath } from '../../../../../persistence/loading-store/user-data-path' -import type { CrossStoreParentRef } from '../../../../../../shared/worktree/lineage-types' -import { supportsCrossStoreLineage } from '../../../../../../shared/worktree-runtime-capabilities' -import { resolveDispatchCallerWorktreeId } from '../orchestration-caller-workspace' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity' +import { OrchestrationError } from '../orchestration-error' +import { readCallerStoreInstallationId } from '../../hosts/platform-probe/host-descriptor' +import { getCanonicalUserDataPath } from '../../../persistence/loading-store/user-data-path' +import type { CrossStoreParentRef } from '../../../../shared/worktree/lineage-types' +import { supportsCrossStoreLineage } from '../../../../shared/worktree-runtime-capabilities' +import { resolveDispatchCallerWorktreeId } from '../../rpc/methods/orchestration/orchestration-caller-workspace' /** * `--on --worktree new-child`: the server's new worktree nests under the coordinator's diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-home-auto-release.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts similarity index 80% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-home-auto-release.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts index 622685198eb..db9125181dc 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-home-auto-release.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-home-auto-release.ts @@ -1,5 +1,5 @@ -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import { resolvePinnedFederatedServer } from '../worker/worker-observation' +import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' +import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' import { releaseFederatedWorker } from './federated-worker-release' /** The home's deadline for a host that did not arm its own; the host's takeover and ownership checks still refuse it. */ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-read.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts similarity index 82% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-read.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts index 87700f6a9c2..1cf73b35ea8 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-read.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-read.ts @@ -1,15 +1,15 @@ import type { ORCHESTRATION_WORKER_READ_SOURCES, OrchestrationWorkerReadResult -} from '../../../../../../shared/orchestration/workers/orchestration-worker-output' -import { ORCHESTRATION_FEDERATION_STRUCTURED_READ_RUNTIME_CAPABILITY } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { getOrchestrationPeerCapabilityCache } from '../../../../orchestration/federation/orchestration-peer-capability-cache' -import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { readLegacyFederatedTerminal } from '../worker/worker-legacy-federated-read' -import type { resolvePinnedFederatedServer } from '../worker/worker-observation' +} from '../../../../shared/orchestration/workers/orchestration-worker-output' +import { ORCHESTRATION_FEDERATION_STRUCTURED_READ_RUNTIME_CAPABILITY } from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { OrchestrationDb } from '../db/orchestration-db' +import { OrchestrationError } from '../orchestration-error' +import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration-peer-capability-cache' +import type { FederatedDispatchRow } from '../db/orchestration-records' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { readLegacyFederatedTerminal } from './worker-legacy-federated-read' +import type { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' export async function readFederatedWorkerOutput(args: { runtime: OrcaRuntimeService diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-ready-record.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-ready-record.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-ready-record.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-ready-record.ts index 812a59d67c5..1a66e784843 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-ready-record.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-ready-record.ts @@ -1,4 +1,4 @@ -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationDb } from '../db/orchestration-db' import type { ReadyRemoteFederatedWorkerStartReceipt } from './federated-attach-receipt' /** Records where a ready remote worker lives and that the server accepted its input. */ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-release.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-release.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts index 8d53875ad06..a9965dfafba 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-release.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-release.ts @@ -1,17 +1,17 @@ import { ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_AUTO_RELEASE_RUNTIME_CAPABILITY -} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { RuntimeStatus } from '../../../../../../shared/runtime-session-contracts' +} from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' import { z } from 'zod' -import { getOrchestrationPeerCapabilityCache } from '../../../../orchestration/federation/orchestration-peer-capability-cache' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import type { WorkerReleaseReceipt } from '../worker/worker-release-completion' -import { releaseUnknownRecovery } from '../worker/worker-release-unknown-recovery' -import type { resolvePinnedFederatedServer } from '../worker/worker-observation' +import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration-peer-capability-cache' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' +import type { FederatedDispatchRow } from '../db/orchestration-records' +import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' +import type { WorkerReleaseReceipt } from '../../rpc/methods/orchestration/worker/worker-release-completion' +import { releaseUnknownRecovery } from '../../rpc/methods/orchestration/worker/worker-release-unknown-recovery' +import type { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' type RemoteReleaseReceipt = Omit & { archive?: WorkerReleaseReceipt['archive'] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts similarity index 87% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts index 69f5a61421b..b8e9b89d78d 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-show.ts @@ -1,20 +1,17 @@ -import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { exposeDispatchContext } from '../worker/dispatch-context-exposure' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { liveFederatedHomeAutoReleaseAt } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import type { - DispatchContextRow, - FederatedDispatchRow -} from '../../../../orchestration/db/orchestration-records' -import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationFleetWorker } from '../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import type { OrchestrationDb } from '../db/orchestration-db' +import { exposeDispatchContext } from '../../rpc/methods/orchestration/worker/dispatch-context-exposure' +import { OrchestrationError } from '../orchestration-error' +import { liveFederatedHomeAutoReleaseAt } from '../terminal-authority/release/worker-terminal-ownership' +import type { DispatchContextRow, FederatedDispatchRow } from '../db/orchestration-records' +import type { OrcaRuntimeService } from '../../orca-runtime' import { callFederatedWorkerShow, exposeFederatedWorkerObservation, exposeWorker, - projectFleetWorkerPage, - resolvePinnedFederatedServer -} from '../worker/worker-observation' + projectFleetWorkerPage +} from '../../rpc/methods/orchestration/worker/worker-observation' +import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' import { applyFederatedFleetObservations } from './federated-fleet-snapshot' import { applyConfirmedFederatedReleaseHomeProjection } from './federated-worker-release' diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-receipts.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts similarity index 93% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-receipts.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts index 692caf380f6..da38e2ab909 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-receipts.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-receipts.ts @@ -1,4 +1,4 @@ -import type { OrchestrationWorkerLaunchReceipt } from '../worker/worker-launch-preferences' +import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences' export function isKnownRemoteStartFailure(code: string): boolean { return [ diff --git a/src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-reconcile.ts similarity index 94% rename from src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-reconcile.ts index 157f21e3845..63d117468c9 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/federated-worker-start-reconcile.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-reconcile.ts @@ -1,13 +1,13 @@ -import type { WorkerDispatchRow } from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import type { OrchestrationDb } from '../orchestration-db' -import { reconcileTaskAfterDispatchInterruption } from '../dispatch-context/task-dispatch-reconciliation' +import type { WorkerDispatchRow } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' +import { reconcileTaskAfterDispatchInterruption } from '../db/dispatch-context/task-dispatch-reconciliation' import { beginLifecycleWriteTransaction, commitLifecycleWriteTransaction, rollbackLifecycleWriteTransaction, transitionLifecycleWithDb -} from '../lifecycle-transition' +} from '../db/lifecycle-transition' export function reconcileFederatedWorkerStart( this: OrchestrationDb, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-request.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts similarity index 54% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-request.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts index fe511658ee6..21dd2d80613 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start-request.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts @@ -1,8 +1,8 @@ -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { WorkerStartInput } from '../worker/worker-start-schema' -import type { WorkerStartMutation } from '../worker/worker-start-mutation' +import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { OrchestrationDb } from '../db/orchestration-db' +import type { WorkerStartInput } from '../../rpc/methods/orchestration/worker/worker-start-schema' +import type { WorkerStartMutation } from '../../rpc/methods/orchestration/worker/worker-start-mutation' export type FederatedWorkerStartRequest = { params: WorkerStartInput diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts rename to src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts index 2d97909ae01..9e5d31b50ef 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start.ts @@ -1,6 +1,6 @@ import type { FederatedWorkerStartRequest } from './federated-worker-start-request' -import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' -import type { RuntimeStatus } from '../../../../../../shared/runtime-session-contracts' +import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' import { ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION, @@ -9,37 +9,37 @@ import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_RUNTIME_CAPABILITY, ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_TURN_STOP_REPORTS_RUNTIME_CAPABILITY -} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { orchestrationMigrationData } from '../../../../../../shared/orchestration/orchestration-rpc-contract' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +} from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import { orchestrationMigrationData } from '../../../../shared/orchestration/orchestration-rpc-contract' +import { OrchestrationError } from '../orchestration-error' import { assertWorkerLaunchPreferencesRuntimeSupported, assertWorkerLaunchPreferencesCreateTerminal, createPendingWorkerLaunchReceipt, resolveFederatedWorkerLaunchReceipt -} from '../worker/worker-launch-preferences' -import { validateFederatedWorkerStartPlacement } from '../worker/worker-start-validation' -import { resolveFederatedWorkerStartBudgets } from '../worker/worker-start-budgets' -import { resolveDispatchCreator } from '../runs/dispatch-creator' +} from '../../rpc/methods/orchestration/worker/worker-launch-preferences' +import { validateFederatedWorkerStartPlacement } from '../../rpc/methods/orchestration/worker/worker-start-validation' +import { resolveFederatedWorkerStartBudgets } from '../../rpc/methods/orchestration/worker/worker-start-budgets' +import { resolveDispatchCreator } from '../../rpc/methods/orchestration/runs/dispatch-creator' import { isReadyRemoteFederatedWorkerStartReceipt, parseRemoteFederatedWorkerStartReceipt } from './federated-attach-receipt' -import { isWorkerStartTimeoutWithinTimerLimit } from '../../../../../../shared/orchestration/orchestration-timing-budgets' +import { isWorkerStartTimeoutWithinTimerLimit } from '../../../../shared/orchestration/orchestration-timing-budgets' import { federatedFailedReceipt, federatedUnknownReceipt, isKnownRemoteStartFailure } from './federated-worker-start-receipts' -import { releaseRetriedWorkerTerminal } from '../worker/retried-worker-terminal-release' -import { withWorkerStartNext } from '../receipt-next' +import { releaseRetriedWorkerTerminal } from '../../rpc/methods/orchestration/worker/retried-worker-terminal-release' +import { withWorkerStartNext } from '../../rpc/methods/orchestration/receipt-next' import { recordReadyFederatedDispatch } from './federated-worker-ready-record' import { resolveFederatedChildParent } from './federated-worker-child-parent' -import { prepareWorkerStartCard } from '../../../../orchestration/workers/launch/worker-start-card' +import { prepareWorkerStartCard } from '../workers/launch/worker-start-card' import { recordWorkerLaunchObservation, workerLaunchAgent -} from '../../../../orchestration/workers/launch/worker-launch-observation' +} from '../workers/launch/worker-launch-observation' export async function startFederatedWorker(args: FederatedWorkerStartRequest): Promise { const { params, runtime, db, task, orchestrationMutation } = args diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-ack-checkpoints.ts similarity index 100% rename from src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-ack-checkpoints.ts diff --git a/src/main/runtime/orchestration/federation/relay/federation-acknowledgment-recovery.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-acknowledgment-recovery.ts similarity index 97% rename from src/main/runtime/orchestration/federation/relay/federation-acknowledgment-recovery.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-acknowledgment-recovery.ts index cbc5b5b3e03..5ea1b77a324 100644 --- a/src/main/runtime/orchestration/federation/relay/federation-acknowledgment-recovery.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federation-acknowledgment-recovery.ts @@ -1,4 +1,4 @@ -import { federationRelayRetryDelayMs } from './federation-relay-scheduler' +import { federationRelayRetryDelayMs } from '../federation/relay/federation-relay-scheduler' type PendingAcknowledgmentRow = { dispatchId: string; rowId: number } diff --git a/src/main/runtime/orchestration/db/federation/federation-relay-import.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-relay-import.ts similarity index 96% rename from src/main/runtime/orchestration/db/federation/federation-relay-import.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-relay-import.ts index c90f6d718e3..4fc44d31b5f 100644 --- a/src/main/runtime/orchestration/db/federation/federation-relay-import.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federation-relay-import.ts @@ -4,9 +4,9 @@ import type { MessageRow, WorkerReportOutcome, WorkerReportSettlement -} from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import type { OrchestrationDb } from '../orchestration-db' +} from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' export function importFederatedRelayItem( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-sync-capability.ts similarity index 79% rename from src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-sync-capability.ts index efc383fa472..8d5778da911 100644 --- a/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federation-sync-capability.ts @@ -1,17 +1,17 @@ -import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' -import '../../../../../shared/protocol-version' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' +import '../../../../shared/protocol-version' import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION, ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_RUNTIME_CAPABILITY, ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_AUTO_RELEASE_RUNTIME_CAPABILITY -} from '../../../../../shared/orchestration/orchestration-runtime-capabilities' -import type { RuntimeCapability } from '../../../../../shared/protocol-version' -import { STRUCTURED_WORKER_HANDLE_PREFIX } from '../../../../../shared/orchestration/workers/structured-worker-handle' -import type { FederationRuntime } from '../federation-runtime' -import type { FederatedDispatchRow } from '../../db/orchestration-records' -import { getOrchestrationPeerCapabilityCache } from '../orchestration-peer-capability-cache' -import { WORKER_RELEASABLE_STATES } from '../../terminal-authority/release/worker-terminal-ownership' +} from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RuntimeCapability } from '../../../../shared/protocol-version' +import { STRUCTURED_WORKER_HANDLE_PREFIX } from '../../../../shared/orchestration/workers/structured-worker-handle' +import type { FederationRuntime } from '../federation/federation-runtime' +import type { FederatedDispatchRow } from '../db/orchestration-records' +import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration-peer-capability-cache' +import { WORKER_RELEASABLE_STATES } from '../terminal-authority/release/worker-terminal-ownership' export async function resolveFederatedLifecycleSettlementCapability( runtime: FederationRuntime, diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-sync-message.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-sync-message.ts similarity index 94% rename from src/main/runtime/orchestration/federation/synchronization/federation-sync-message.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-sync-message.ts index a23a0686e70..27966b13842 100644 --- a/src/main/runtime/orchestration/federation/synchronization/federation-sync-message.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federation-sync-message.ts @@ -4,9 +4,9 @@ import { type MessagePriority, type MessageType, type WorkerReportOutcome -} from '../../db/orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import { parseFederatedWorkerReportPayload } from '../relay/federation-worker-report-payload' +} from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import { parseFederatedWorkerReportPayload } from './federation-worker-report-payload' export type RelayedMessage = { from: string diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-sync.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-sync.ts similarity index 93% rename from src/main/runtime/orchestration/federation/synchronization/federation-sync.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-sync.ts index ad2b28c2113..7fdcb78c919 100644 --- a/src/main/runtime/orchestration/federation/synchronization/federation-sync.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federation-sync.ts @@ -1,21 +1,21 @@ -import { federationRelayPrefix } from '../relay/federation-relay-prefix' -import { federationRelayWireItem } from '../relay/federation-relay-wire' -import type { FederationRuntime } from '../federation-runtime' -import type { FederatedLifecycleSettlement } from '../federation-lifecycle-settlement' -import '../../../../../shared/protocol-version' -import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { OrchestrationError } from '../../orchestration-error' +import { federationRelayPrefix } from '../federation/relay/federation-relay-prefix' +import { federationRelayWireItem } from '../legacy-remote/federation-relay-wire' +import type { FederationRuntime } from '../federation/federation-runtime' +import type { FederatedLifecycleSettlement } from '../legacy-remote/federation-lifecycle-settlement' +import '../../../../shared/protocol-version' +import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import { OrchestrationError } from '../orchestration-error' import { acquireFederationAckLease, getFederationAckedThrough, recordFederationAckCheckpoint } from './federation-ack-checkpoints' -import { bindCoordinatorMutationPayload } from '../../workers/reports/dispatch-message-binding' +import { bindCoordinatorMutationPayload } from '../workers/reports/dispatch-message-binding' import { armHomeAutoReleaseForOlderHost, resolveFederatedLifecycleSettlementCapability } from './federation-sync-capability' -import { getOrchestrationPeerCapabilityCache } from '../orchestration-peer-capability-cache' +import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration-peer-capability-cache' import { parseFederatedLifecycle, parseRelayedMessage, diff --git a/src/main/runtime/orchestration/federation/relay/federation-worker-report-payload.ts b/src/main/runtime/orchestration/legacy-remote-home/federation-worker-report-payload.ts similarity index 89% rename from src/main/runtime/orchestration/federation/relay/federation-worker-report-payload.ts rename to src/main/runtime/orchestration/legacy-remote-home/federation-worker-report-payload.ts index 2a05d293471..6ace3b99041 100644 --- a/src/main/runtime/orchestration/federation/relay/federation-worker-report-payload.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federation-worker-report-payload.ts @@ -1,5 +1,5 @@ -import type { WorkerReportOutcome } from '../../db/orchestration-records' -import { OrchestrationError } from '../../orchestration-error' +import type { WorkerReportOutcome } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' export function parseFederatedWorkerReportPayload(payload: string | null): { taskId: string diff --git a/src/main/runtime/orchestration/legacy-remote-home/legacy-remote-home-db-methods.ts b/src/main/runtime/orchestration/legacy-remote-home/legacy-remote-home-db-methods.ts new file mode 100644 index 00000000000..048054b8fea --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote-home/legacy-remote-home-db-methods.ts @@ -0,0 +1,21 @@ +// The DB layer's only way into this folder; keep it free of rpc and runtime imports. +import { attachFederatedDispatchStore } from './federated-dispatch-store' +import type { FederatedDispatchStoreMethods } from './federated-dispatch-store' +import { attachFederatedHomeAutoReleaseStore } from './federated-home-auto-release-store' +import type { FederatedHomeAutoReleaseStoreMethods } from './federated-home-auto-release-store' +import { attachFederatedWorkerStartReconcile } from './federated-worker-start-reconcile' +import type { FederatedWorkerStartReconcileMethods } from './federated-worker-start-reconcile' +import { attachFederationRelayImport } from './federation-relay-import' +import type { FederationRelayImportMethods } from './federation-relay-import' + +export type LegacyRemoteHomeDbMethods = FederatedWorkerStartReconcileMethods & + FederatedDispatchStoreMethods & + FederationRelayImportMethods & + FederatedHomeAutoReleaseStoreMethods + +export function attachLegacyRemoteHomeDbMethods(ctor: { prototype: object }): void { + attachFederatedWorkerStartReconcile(ctor) + attachFederatedDispatchStore(ctor) + attachFederationRelayImport(ctor) + attachFederatedHomeAutoReleaseStore(ctor) +} diff --git a/src/main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts b/src/main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts new file mode 100644 index 00000000000..3cfe495500f --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts @@ -0,0 +1,18 @@ +// Run-home half of today's remote attachments (`worker-start --on` drives a worker on a paired Orca). +// Frozen: bug fixes only. Code outside this folder imports it only through this module, +// except the DB layer (legacy-remote-home-db-methods.ts) and worker-list-projection.ts, which +// legacy starts load, so it imports federated-fleet-snapshot.ts directly to avoid an import cycle. +/** The one place a worker start leaves the local path: `worker-start --on `. */ +export { startFederatedWorker } from './federated-worker-start' + +export { releaseFederatedWorkerAtHomeDeadline } from './federated-worker-home-auto-release' +export { readFederatedWorkerOutput } from './federated-worker-read' +export { releaseFederatedWorker, retainFederatedWorker } from './federated-worker-release' +export { showFederatedWorker } from './federated-worker-show' +export { + clearFederationAckCheckpoints, + releaseFederationAckCheckpoint +} from './federation-ack-checkpoints' +export { FederationAcknowledgmentRecovery } from './federation-acknowledgment-recovery' +export { syncFederatedDispatch } from './federation-sync' +export { federatedControlMailRefusal, sendFederatedControlMail } from './send-control-mail' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts b/src/main/runtime/orchestration/legacy-remote-home/send-control-mail.ts similarity index 84% rename from src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts rename to src/main/runtime/orchestration/legacy-remote-home/send-control-mail.ts index 247d31b3568..ee07baa780d 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/send-control-mail.ts @@ -1,15 +1,12 @@ -import type { - MessagePriority, - MessageType -} from '../../../../orchestration/db/orchestration-records' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { encodeFederatedControlMessage } from '../../../../orchestration/federation/relay/federation-control-message' -import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { recordReceiptBeforeNudge } from './mutation-replay-nudge' -import type { SendParams } from './send-params' -import type { SendRecipientWarning } from './recipient-routing' +import type { MessagePriority, MessageType } from '../db/orchestration-records' +import type { OrchestrationDb } from '../db/orchestration-db' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { OrchestrationError } from '../orchestration-error' +import { encodeFederatedControlMessage } from '../legacy-remote/federation-control-message' +import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import { recordReceiptBeforeNudge } from '../../rpc/methods/orchestration/messaging/mutation-replay-nudge' +import type { SendParams } from '../../rpc/methods/orchestration/messaging/send-params' +import type { SendRecipientWarning } from '../../rpc/methods/orchestration/messaging/recipient-routing' import type { z } from 'zod' type SendParamsInput = z.infer diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-legacy-federated-read.ts b/src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts similarity index 87% rename from src/main/runtime/rpc/methods/orchestration/worker/worker-legacy-federated-read.ts rename to src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts index b472f0af417..05c44fc1633 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-legacy-federated-read.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/worker-legacy-federated-read.ts @@ -1,12 +1,12 @@ -import type { ORCHESTRATION_WORKER_READ_SOURCES } from '../../../../../../shared/orchestration/workers/orchestration-worker-output' -import type { RuntimeTerminalRead } from '../../../../../../shared/runtime-terminal-contracts' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { ORCHESTRATION_WORKER_READ_SOURCES } from '../../../../shared/orchestration/workers/orchestration-worker-output' +import type { RuntimeTerminalRead } from '../../../../shared/runtime-terminal-contracts' +import { OrchestrationError } from '../orchestration-error' import { createWorkerOutputSourceIdentity, decodeWorkerOutputCursor, encodeWorkerOutputCursor -} from '../../../../orchestration/workers/transcripts/worker-output-cursor' -import type { resolvePinnedFederatedServer } from './worker-observation' +} from '../workers/transcripts/worker-output-cursor' +import type { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server' // Old peers expose only terminal reads; retain fences and cursor scope instead of silently degrading transcript cursors. export async function readLegacyFederatedTerminal(args: { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/ask-remote.ts b/src/main/runtime/orchestration/legacy-remote/ask-remote.ts similarity index 78% rename from src/main/runtime/rpc/methods/orchestration/messaging/ask-remote.ts rename to src/main/runtime/orchestration/legacy-remote/ask-remote.ts index f400a60ff99..b18edd2e418 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/ask-remote.ts +++ b/src/main/runtime/orchestration/legacy-remote/ask-remote.ts @@ -1,14 +1,14 @@ import type { z } from 'zod' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { WorkerDispatchState } from '../../../../orchestration/db/orchestration-records' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { clampOrchestrationAskTimeoutMs } from '../../../../../../shared/orchestration/mailbox/orchestration-ask-timeout' -import type { AskParams } from '../../../../../../shared/rpc-contract/orchestration-params' -import { assertWorkerCanReport } from '../../../../orchestration/workers/reports/worker-report-admission' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { WorkerDispatchState } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import { clampOrchestrationAskTimeoutMs } from '../../../../shared/orchestration/mailbox/orchestration-ask-timeout' +import type { AskParams } from '../../../../shared/rpc-contract/orchestration-params' +import { assertWorkerCanReport } from '../workers/reports/worker-report-admission' import { askedQuestionReceipt, waitForQuestionAnswer -} from '../../../../orchestration/mailbox/questions/question-answer-delivery' +} from '../mailbox/questions/question-answer-delivery' export async function askRemoteRunHome(args: { params: z.infer diff --git a/src/main/runtime/orchestration/db/federation/federated-dispatch-observation-fence.ts b/src/main/runtime/orchestration/legacy-remote/federated-dispatch-observation-fence.ts similarity index 97% rename from src/main/runtime/orchestration/db/federation/federated-dispatch-observation-fence.ts rename to src/main/runtime/orchestration/legacy-remote/federated-dispatch-observation-fence.ts index 4bb532cc0d1..ba73af37928 100644 --- a/src/main/runtime/orchestration/db/federation/federated-dispatch-observation-fence.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-dispatch-observation-fence.ts @@ -1,9 +1,9 @@ -import type { OrchestrationDb } from '../orchestration-db' +import type { OrchestrationDb } from '../db/orchestration-db' import { beginLifecycleWriteTransaction, commitLifecycleWriteTransaction, rollbackLifecycleWriteTransaction -} from '../lifecycle-transition' +} from '../db/lifecycle-transition' export type FederatedDispatchObservationFence = { dispatch_id: string diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts similarity index 86% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts rename to src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts index 060cb204d08..3699d1ade1d 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-agent-launch.ts @@ -1,22 +1,22 @@ -import type { RuntimeTerminalCreate } from '../../../../../../shared/runtime-terminal-create-contract' +import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract' /** Execute terminalOnly on the receiving host with federation's agent-first worktree/background-terminal factories. The dispatch brief is delivered later. */ -import type { AgentLaunchPreferences } from '../../../../../../shared/agent-session/agent-session-host-authority' -import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' -import { executeAgentLaunch } from '../../../../../agent-launch/agent-launch-executor' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { resolveUnattendedSetupDecision } from '../../../../../workspace-hooks/effective-hook-config' -import { WORKER_START_VOCABULARY } from '../structured-workers/orchestration-worker-start-mode' -import type { WorkerSetupReceipt } from '../worker/worker-topology' -import { resolveWorkerWorktreeName } from '../worker/worker-worktree-creation' +import type { AgentLaunchPreferences } from '../../../../shared/agent-session/agent-session-host-authority' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import { executeAgentLaunch } from '../../../agent-launch/agent-launch-executor' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { OrchestrationDb } from '../db/orchestration-db' +import { resolveUnattendedSetupDecision } from '../../../workspace-hooks/effective-hook-config' +import { WORKER_START_VOCABULARY } from '../../rpc/methods/orchestration/structured-workers/orchestration-worker-start-mode' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' +import { resolveWorkerWorktreeName } from '../../rpc/methods/orchestration/worker/worker-worktree-creation' import { appendFederationSetupEffect, appendFederationTerminalEffects, type FederationEffect } from './federation-effects' -import type { FederationAttachStartInput } from '../../../../../../shared/rpc-contract/orchestration-federation-start-params' -import type { Worktree } from '../../../../../../shared/worktree/types' +import type { FederationAttachStartInput } from '../../../../shared/rpc-contract/orchestration-federation-start-params' +import type { Worktree } from '../../../../shared/worktree/types' const TERMINAL_ONLY_MESSAGE = 'A federated worker starts a terminal agent only.' diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-release-host.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-release-host.ts rename to src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts index 00b409bcdb7..1739ab48fcd 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-release-host.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-release-host.ts @@ -1,29 +1,29 @@ -import { describeUnconfirmedAgentStop } from '../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' -import type { RemoteDispatchAttachmentRow } from '../../../../orchestration/db/orchestration-records' +import { describeUnconfirmedAgentStop } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' import type { WorkerTerminalArchiveRow, WorkerTerminalResourceRow, WorkerTerminalRetainedReason -} from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +} from '../terminal-authority/release/worker-terminal-ownership' import { captureWorkerOutputArchive, releaseCommitFieldsForCapturedArchive, releaseCommitFieldsForStoredArchive, summarizeWorkerOutputArchive -} from '../../../../orchestration/workers/archives/worker-output-archive' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' +} from '../workers/archives/worker-output-archive' +import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' import { readRemoteAttachmentArchive } from './remote-attachment-archive-read' -import { WorkerTerminalReleaseSingleFlight } from '../worker/worker-terminal-release-single-flight' -import { yieldAutoReleaseToWorkingAgent } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-working-yield' -import { archiveSummary } from '../worker/worker-terminal-resource-presentation' -import type { WorkerReleaseReceipt } from '../worker/worker-release-completion' -import { releaseUnknownRecovery } from '../worker/worker-release-unknown-recovery' -import { orchestrationTimestampToMs } from '../worker/worker-output' +import { WorkerTerminalReleaseSingleFlight } from '../../rpc/methods/orchestration/worker/worker-terminal-release-single-flight' +import { yieldAutoReleaseToWorkingAgent } from '../terminal-authority/release/worker-terminal-auto-release-working-yield' +import { archiveSummary } from '../../rpc/methods/orchestration/worker/worker-terminal-resource-presentation' +import type { WorkerReleaseReceipt } from '../../rpc/methods/orchestration/worker/worker-release-completion' +import { releaseUnknownRecovery } from '../../rpc/methods/orchestration/worker/worker-release-unknown-recovery' +import { orchestrationTimestampToMs } from '../../rpc/methods/orchestration/worker/worker-output' import type { inspectRemoteAttachment } from './federation-attachment-observation' import { classifyWorkerTerminalCloseError, TRANSIENT_WORKER_RELEASE_RECOVERY -} from '../worker/worker-release-close-error' +} from '../../rpc/methods/orchestration/worker/worker-release-close-error' type RemoteAttachmentReleaseArgs = { runtime: WorkerTerminalReleaseRuntime diff --git a/src/main/runtime/orchestration/db/federated-worker-report-outcome.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-report-outcome.ts similarity index 87% rename from src/main/runtime/orchestration/db/federated-worker-report-outcome.ts rename to src/main/runtime/orchestration/legacy-remote/federated-worker-report-outcome.ts index 41914694db0..7cf45cafb3e 100644 --- a/src/main/runtime/orchestration/db/federated-worker-report-outcome.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-report-outcome.ts @@ -1,4 +1,4 @@ -import type { WorkerReportOutcome } from './orchestration-records' +import type { WorkerReportOutcome } from '../db/orchestration-records' export function parseFederatedWorkerReportOutcome( payload: string diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-stop-host.ts b/src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts similarity index 86% rename from src/main/runtime/rpc/methods/orchestration/federation/federated-worker-stop-host.ts rename to src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts index d73f42f565a..5ec5bfe4af0 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-stop-host.ts +++ b/src/main/runtime/orchestration/legacy-remote/federated-worker-stop-host.ts @@ -1,7 +1,7 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { WorkerStopReceipt } from '../../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' -import { archiveWorkerOutputBeforeStop } from '../worker/worker-stop-archive' -import { describeUnconfirmedAgentStop } from '../../../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { WorkerStopReceipt } from '../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' +import { archiveWorkerOutputBeforeStop } from '../../rpc/methods/orchestration/worker/worker-stop-archive' +import { describeUnconfirmedAgentStop } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import { inspectRemoteAttachment } from './federation-attachment-observation' /** Close the exact attached worker this host runs for its home. */ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-attachment-authority.ts b/src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-attachment-authority.ts rename to src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts index 28448ff5991..a91511e3e03 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-attachment-authority.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-attachment-authority.ts @@ -1,7 +1,7 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { OrchestrationDb } from '../db/orchestration-db' import type { FederationEffect } from './federation-effects' -import type { WorkerSetupReceipt } from '../worker/worker-topology' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' export function prepareFederatedAttachmentAuthority(args: { runtime: OrcaRuntimeService diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-attachment-observation.ts b/src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts similarity index 90% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-attachment-observation.ts rename to src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts index cddf8efcfa7..470c9b55df6 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-attachment-observation.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-attachment-observation.ts @@ -1,9 +1,9 @@ -import type { RuntimeTerminalInteractiveWait } from '../../../../../../shared/runtime-terminal-contracts' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { parseWorkerTerminalHostScope } from '../../../../../../shared/orchestration/workers/worker-terminal-host-scope' -import type { RemoteDispatchAttachmentRow } from '../../../../orchestration/db/orchestration-records' -import { orchestrationTimestampToMs } from '../worker/worker-output' +import type { RuntimeTerminalInteractiveWait } from '../../../../shared/runtime-terminal-contracts' +import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' +import { OrchestrationError } from '../orchestration-error' +import { parseWorkerTerminalHostScope } from '../../../../shared/orchestration/workers/worker-terminal-host-scope' +import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' +import { orchestrationTimestampToMs } from '../../rpc/methods/orchestration/worker/worker-output' export function requireHomeAttachment( runtime: WorkerTerminalReleaseRuntime, diff --git a/src/main/runtime/orchestration/federation/relay/federation-control-message.ts b/src/main/runtime/orchestration/legacy-remote/federation-control-message.ts similarity index 93% rename from src/main/runtime/orchestration/federation/relay/federation-control-message.ts rename to src/main/runtime/orchestration/legacy-remote/federation-control-message.ts index 204dafba2fa..62776c88775 100644 --- a/src/main/runtime/orchestration/federation/relay/federation-control-message.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-control-message.ts @@ -1,10 +1,6 @@ -import { - MESSAGE_TYPES, - type MessagePriority, - type MessageType -} from '../../db/orchestration-records' -import type { OrchestrationDb } from '../../db/orchestration-db' -import { OrchestrationError } from '../../orchestration-error' +import { MESSAGE_TYPES, type MessagePriority, type MessageType } from '../db/orchestration-records' +import type { OrchestrationDb } from '../db/orchestration-db' +import { OrchestrationError } from '../orchestration-error' const MESSAGE_TYPE_SET = new Set(MESSAGE_TYPES) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts b/src/main/runtime/orchestration/legacy-remote/federation-control.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts rename to src/main/runtime/orchestration/legacy-remote/federation-control.ts index aa3430ec5bf..d0bb1171c76 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-control.ts @@ -1,11 +1,11 @@ -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { RemoteDispatchAttachmentRow } from '../../../../orchestration/db/orchestration-records' -import { defineMethod } from '../../../core' -import { isUserKeptWorkerTerminalOwner } from '../../../../orchestration/db/worker-terminal/worker-terminal-user-keep' -import { mapWithConcurrency } from '../../../../../../shared/map-with-concurrency' -import { readExactWorkerOutput } from '../worker/worker-output' -import { exposeWorkerRetainReceipt } from '../worker/worker-terminal-resource-presentation' -import { withStoppedHelpers } from '../worker/worker-stop' +import { OrchestrationError } from '../orchestration-error' +import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' +import { defineOrchestrationMethod } from '../../rpc/methods/orchestration/access/orchestration-method-access' +import { isUserKeptWorkerTerminalOwner } from '../db/worker-terminal/worker-terminal-user-keep' +import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' +import { readExactWorkerOutput } from '../../rpc/methods/orchestration/worker/worker-output' +import { exposeWorkerRetainReceipt } from '../../rpc/methods/orchestration/worker/worker-terminal-resource-presentation' +import { withStoppedHelpers } from '../../rpc/methods/orchestration/worker/worker-stop' import { stopRemoteAttachment } from './federated-worker-stop-host' import { inspectRemoteAttachment, @@ -19,11 +19,12 @@ import { FederationFleetSnapshotParams, FederationOutputReadParams, FederationReadParams -} from '../../../../../../shared/rpc-contract/orchestration-federation-control-params' +} from '../../../../shared/rpc-contract/orchestration-federation-control-params' export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationFleetSnapshot', + access: { kind: 'localOnly', targets: { dispatchIds: 'dispatch' } }, permission: 'workspace', params: FederationFleetSnapshotParams, handler: async (params, { runtime, authenticatedCallerFingerprint }) => { @@ -58,8 +59,9 @@ export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ return { runtimeEpoch: runtime.getRuntimeId(), items } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationRelease', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationDispatchParams, handler: async (params, { runtime, authenticatedCallerFingerprint }) => { @@ -72,8 +74,9 @@ export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ return releaseRemoteAttachment({ runtime, attachment, observation }) } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationRetain', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationDispatchParams, handler: (params, { runtime, authenticatedCallerFingerprint }) => { @@ -84,8 +87,9 @@ export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ ) } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationShow', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationDispatchParams, handler: async (params, { runtime, authenticatedCallerFingerprint }) => { @@ -113,8 +117,9 @@ export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationRead', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationReadParams, handler: async (params, { runtime, authenticatedCallerFingerprint }) => { @@ -137,8 +142,9 @@ export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationReadOutput', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationOutputReadParams, handler: async (params, { runtime, authenticatedCallerFingerprint }) => { @@ -221,8 +227,9 @@ export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationStop', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationDispatchParams, handler: async (params, { runtime, authenticatedCallerFingerprint, orchestrationMutation }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-effects.ts b/src/main/runtime/orchestration/legacy-remote/federation-effects.ts similarity index 100% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-effects.ts rename to src/main/runtime/orchestration/legacy-remote/federation-effects.ts diff --git a/src/main/runtime/orchestration/federation/federation-lifecycle-settlement.ts b/src/main/runtime/orchestration/legacy-remote/federation-lifecycle-settlement.ts similarity index 100% rename from src/main/runtime/orchestration/federation/federation-lifecycle-settlement.ts rename to src/main/runtime/orchestration/legacy-remote/federation-lifecycle-settlement.ts diff --git a/src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts b/src/main/runtime/orchestration/legacy-remote/federation-relay-enqueue.ts similarity index 95% rename from src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts rename to src/main/runtime/orchestration/legacy-remote/federation-relay-enqueue.ts index bee9edce5bc..e8cd0503d7c 100644 --- a/src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-relay-enqueue.ts @@ -1,16 +1,16 @@ -import { readAnswerSenderRelayReport } from '../../mailbox/senders/answer-sender-relay-report' +import { readAnswerSenderRelayReport } from '../mailbox/senders/answer-sender-relay-report' import type { WorkerReportOutcome, FederationRelayDirection, FederationRelayItemRow -} from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import { generateId } from '../generated-id' -import type { OrchestrationDb } from '../orchestration-db' +} from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import { generateId } from '../db/generated-id' +import type { OrchestrationDb } from '../db/orchestration-db' import { isWorkerStateIn, SETTLEABLE_WORKER_STATES -} from '../../workers/reports/worker-report-admission' +} from '../workers/reports/worker-report-admission' export function enqueueFederationRelay( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/db/federation/federation-relay-item.ts b/src/main/runtime/orchestration/legacy-remote/federation-relay-item.ts similarity index 90% rename from src/main/runtime/orchestration/db/federation/federation-relay-item.ts rename to src/main/runtime/orchestration/legacy-remote/federation-relay-item.ts index cf731c719cb..3079962739d 100644 --- a/src/main/runtime/orchestration/db/federation/federation-relay-item.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-relay-item.ts @@ -2,13 +2,13 @@ import type { WorkerReportOutcome, FederationRelayDirection, FederationRelayItemRow -} from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import type { OrchestrationDb } from '../orchestration-db' +} from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' import { isWorkerStateIn, SETTLEABLE_WORKER_STATES -} from '../../workers/reports/worker-report-admission' +} from '../workers/reports/worker-report-admission' export function getFederationRelayItem( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/legacy-remote/federation-relay-report-acknowledgment.ts b/src/main/runtime/orchestration/legacy-remote/federation-relay-report-acknowledgment.ts new file mode 100644 index 00000000000..a737d7c8f26 --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote/federation-relay-report-acknowledgment.ts @@ -0,0 +1,139 @@ +import type { + WorkerReportOutcome, + FederationRelayDirection, + FederationRelayItemRow +} from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' +import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import { parseFederatedWorkerReportOutcome } from './federated-worker-report-outcome' + +export function listFederationRelay( + this: OrchestrationDb, + params: { + dispatchId: string + direction: FederationRelayDirection + afterSequence: number + limit?: number + } +): FederationRelayItemRow[] { + return this.db + .prepare( + `SELECT * FROM federation_relay_items + WHERE dispatch_id = ? AND direction = ? AND sequence > ? + ORDER BY sequence LIMIT ?` + ) + .all( + params.dispatchId, + params.direction, + params.afterSequence, + Math.min(Math.max(params.limit ?? 50, 1), 50) + ) as FederationRelayItemRow[] +} + +/** A worker_done queued for the Run home that it has not acknowledged. */ +export function hasPendingFederatedWorkerReport( + this: OrchestrationDb, + dispatchId: string +): boolean { + return ( + this.db + .prepare( + `SELECT 1 FROM federation_relay_items + WHERE dispatch_id = ? AND direction = 'to_home' AND kind = 'worker_done' + AND acked_at IS NULL LIMIT 1` + ) + .get(dispatchId) !== undefined + ) +} + +export type FederationRelayAcknowledgment = { + dispatchId: string + direction: FederationRelayDirection + throughSequence: number + settleRemoteReports?: { sequence: number; outcome?: WorkerReportOutcome }[] + // Only the home's acceptance proves settlement; arm after it, never at queue time. + armAutoRelease?: boolean +} + +/** Runs inside acknowledgeFederationRelay's transaction, before the items are marked acked. */ +export function settleRemoteReportsInRelayAcknowledgment( + this: OrchestrationDb, + params: FederationRelayAcknowledgment +): void { + const settledReports = params.settleRemoteReports ?? [] + for (const settledReport of settledReports) { + const report = this.getFederationRelayItem( + params.dispatchId, + params.direction, + settledReport.sequence + ) + if ( + params.direction !== 'to_home' || + settledReport.sequence > params.throughSequence || + report?.kind !== 'worker_done' || + (settledReport.outcome !== undefined && + parseFederatedWorkerReportOutcome(report.payload) !== settledReport.outcome) + ) { + throw new OrchestrationError( + 'request_mismatch', + `Federation acknowledgment for ${params.dispatchId} does not match its queued worker_done.` + ) + } + } + const attachment = this.getRemoteDispatchAttachment(params.dispatchId) + if ( + params.direction === 'to_home' && + attachment !== undefined && + attachment.protocol_version >= ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION + ) { + const acknowledgedReports = this.db + .prepare( + `SELECT sequence FROM federation_relay_items + WHERE dispatch_id = ? AND direction = 'to_home' AND kind = 'worker_done' + AND acked_at IS NULL AND sequence <= ?` + ) + .all(params.dispatchId, params.throughSequence) as { sequence: number }[] + const settledSequences = new Set(settledReports.map((report) => report.sequence)) + if (acknowledgedReports.some((report) => !settledSequences.has(report.sequence))) { + throw new OrchestrationError( + 'request_mismatch', + `Federation acknowledgment for ${params.dispatchId} omits a worker_done settlement.` + ) + } + } + const terminalOutcomes = new Set( + settledReports.flatMap((report) => (report.outcome ? [report.outcome] : [])) + ) + if (terminalOutcomes.size > 1) { + throw new OrchestrationError( + 'request_mismatch', + `Federation acknowledgment for ${params.dispatchId} contains conflicting settlements.` + ) + } + const terminalOutcome = settledReports.find((report) => report.outcome)?.outcome + if (terminalOutcome) { + this.settleRemoteAttachmentInRelayTransaction( + params.dispatchId, + terminalOutcome, + 'worker_report_settled' + ) + if (params.armAutoRelease) { + this.armWorkerTerminalAutoReleaseStatement(params.dispatchId) + } + } +} + +export type FederationRelayReportAcknowledgmentMethods = { + listFederationRelay: typeof listFederationRelay + hasPendingFederatedWorkerReport: typeof hasPendingFederatedWorkerReport + settleRemoteReportsInRelayAcknowledgment: typeof settleRemoteReportsInRelayAcknowledgment +} + +export function attachFederationRelayReportAcknowledgment(ctor: { prototype: object }): void { + Object.assign(ctor.prototype, { + listFederationRelay, + hasPendingFederatedWorkerReport, + settleRemoteReportsInRelayAcknowledgment + }) +} diff --git a/src/main/runtime/orchestration/federation/relay/federation-relay-wire.ts b/src/main/runtime/orchestration/legacy-remote/federation-relay-wire.ts similarity index 69% rename from src/main/runtime/orchestration/federation/relay/federation-relay-wire.ts rename to src/main/runtime/orchestration/legacy-remote/federation-relay-wire.ts index c4ce10c5bdb..a480a1ce455 100644 --- a/src/main/runtime/orchestration/federation/relay/federation-relay-wire.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-relay-wire.ts @@ -1,5 +1,5 @@ -import type { FederationRelayItemRow } from '../../db/orchestration-records' -import { readAnswerSenderRelayReport } from '../../mailbox/senders/answer-sender-relay-report' +import type { FederationRelayItemRow } from '../db/orchestration-records' +import { readAnswerSenderRelayReport } from '../mailbox/senders/answer-sender-relay-report' export function federationRelayWireItem(row: FederationRelayItemRow) { const answerSenderReport = readAnswerSenderRelayReport(row.answer_sender_report) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts b/src/main/runtime/orchestration/legacy-remote/federation-relay.ts similarity index 89% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts rename to src/main/runtime/orchestration/legacy-remote/federation-relay.ts index 9d64727eb92..5982444fd7c 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-relay.ts @@ -1,23 +1,25 @@ -import { federationRelayWireItem } from '../../../../orchestration/federation/relay/federation-relay-wire' -import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { deliverQuestionAnswer } from '../../../../orchestration/mailbox/questions/question-answer-delivery' -import { importFederatedControlMessage } from '../../../../orchestration/federation/relay/federation-control-message' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { federationRelayWireItem } from './federation-relay-wire' +import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import { deliverQuestionAnswer } from '../mailbox/questions/question-answer-delivery' +import { importFederatedControlMessage } from './federation-control-message' +import { OrchestrationError } from '../orchestration-error' import { areFederatedLifecycleSettlementsEqual, publishFederatedLifecycleSettlement, type FederatedLifecycleSettlement -} from '../../../../orchestration/federation/federation-lifecycle-settlement' -import { defineMethod, type RpcMethod } from '../../../core' +} from './federation-lifecycle-settlement' +import type { RpcMethod } from '../../rpc/core' +import { defineOrchestrationMethod } from '../../rpc/methods/orchestration/access/orchestration-method-access' import { FederationAckParams, FederationImportParams, FederationPullParams -} from '../../../../../../shared/rpc-contract/orchestration-federation-relay-params' +} from '../../../../shared/rpc-contract/orchestration-federation-relay-params' export const ORCHESTRATION_FEDERATION_RELAY_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationPull', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationPullParams, handler: (params, { runtime, authenticatedCallerFingerprint }) => { @@ -39,8 +41,9 @@ export const ORCHESTRATION_FEDERATION_RELAY_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationAck', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationAckParams, handler: (params, { runtime, authenticatedCallerFingerprint }) => { @@ -105,8 +108,9 @@ export const ORCHESTRATION_FEDERATION_RELAY_METHODS = [ return { dispatchId: params.dispatchId, acknowledgedThrough: params.throughSequence } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationImport', + access: { kind: 'localOnly', targets: { dispatchId: 'dispatch' } }, permission: 'workspace', params: FederationImportParams, handler: (params, { runtime, authenticatedCallerFingerprint }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-setup.ts b/src/main/runtime/orchestration/legacy-remote/federation-setup.ts similarity index 92% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-setup.ts rename to src/main/runtime/orchestration/legacy-remote/federation-setup.ts index b4dc2c5e86b..ddf87653e11 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-setup.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-setup.ts @@ -1,6 +1,9 @@ -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import { applyWaitForSetupOutcome, type WorkerSetupReceipt } from '../worker/worker-topology' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { OrchestrationDb } from '../db/orchestration-db' +import { + applyWaitForSetupOutcome, + type WorkerSetupReceipt +} from '../../rpc/methods/orchestration/worker/worker-topology' import { isFederationResidualEffect, type FederationEffect } from './federation-effects' type FederationSetupStageArgs = { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-start-receipt.ts b/src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts similarity index 73% rename from src/main/runtime/rpc/methods/orchestration/federation/federation-start-receipt.ts rename to src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts index 096314727db..c0c00eef44e 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-start-receipt.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation-start-receipt.ts @@ -1,8 +1,8 @@ -import { formatTerminalStartFailure } from '../../../../../../shared/terminal/pty/lifecycle/terminal-start-failure' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { formatTerminalStartFailure } from '../../../../shared/terminal/pty/lifecycle/terminal-start-failure' +import type { OrchestrationDb } from '../db/orchestration-db' import { isFederationEffectUnknown } from './federation-effects' -import type { WorkerSetupReceipt } from '../worker/worker-topology' -import type { OrchestrationWorkerLaunchReceipt } from '../worker/worker-launch-preferences' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' +import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences' export function failFederatedAttachmentWithReceipt(args: { db: OrchestrationDb diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation.ts b/src/main/runtime/orchestration/legacy-remote/federation.ts similarity index 85% rename from src/main/runtime/rpc/methods/orchestration/federation/federation.ts rename to src/main/runtime/orchestration/legacy-remote/federation.ts index 995d88ddb8b..6a803cc1ac5 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation.ts +++ b/src/main/runtime/orchestration/legacy-remote/federation.ts @@ -1,36 +1,40 @@ -import type { RuntimeTerminalCreate } from '../../../../../../shared/runtime-terminal-create-contract' -import { waitForWorkerAgentReady } from '../../../../terminal/wait/launched-agent-composer-readiness' -import { describeTerminalWaitBlockedReason } from '../../../../../../shared/terminal/runtime-policy/terminal-wait-blocked-reason-legacy-alias' -import { buildDispatchPreamble } from '../../../../orchestration/workers/launch/worker-dispatch-preamble' -import { sendAgentTurn } from '../../../../orchestration/turn-delivery/send-agent-turn' -import { createWorkerBriefWriteGuard } from '../../../../terminal/wait/launched-agent-write-guard' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod } from '../../../core' -import { assertOrchestrationWorktreeCreationSupported } from '../worker/folder-worktree-placement' +import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract' +import { waitForWorkerAgentReady } from '../../terminal/wait/launched-agent-composer-readiness' +import { describeTerminalWaitBlockedReason } from '../../../../shared/terminal/runtime-policy/terminal-wait-blocked-reason-legacy-alias' +import { buildDispatchPreamble } from '../workers/launch/worker-dispatch-preamble' +import { sendAgentTurn } from '../turn-delivery/send-agent-turn' +import { createWorkerBriefWriteGuard } from '../../terminal/wait/launched-agent-write-guard' +import { OrchestrationError } from '../orchestration-error' +import { defineOrchestrationMethod } from '../../rpc/methods/orchestration/access/orchestration-method-access' +import { assertOrchestrationWorktreeCreationSupported } from '../../rpc/methods/orchestration/worker/folder-worktree-placement' import type { FederationEffect } from './federation-effects' import { launchFederatedWorkerAgent } from './federated-worker-agent-launch' -import type { WorkerSetupReceipt } from '../worker/worker-topology' +import type { WorkerSetupReceipt } from '../../rpc/methods/orchestration/worker/worker-topology' import { monitorFederatedSetup, persistFederatedReadinessStage, persistFederatedSetupSpawnFailure, persistFederatedSetupWaitOutcome } from './federation-setup' -import { FederationAttachStartParams } from '../../../../../../shared/rpc-contract/orchestration-federation-start-params' +import { FederationAttachStartParams } from '../../../../shared/rpc-contract/orchestration-federation-start-params' import { failFederatedAttachmentWithReceipt } from './federation-start-receipt' -import { prepareFederationWorkerLaunchOnHost } from '../worker/worker-opencode-model-preflight' +import { prepareFederationWorkerLaunchOnHost } from '../../rpc/methods/orchestration/worker/worker-opencode-model-preflight' import { isWorkerStartTimeoutWithinTimerLimit, resolveWorkerStartReadinessTimeoutMs -} from '../../../../../../shared/orchestration/orchestration-timing-budgets' -import { assertWorkerStartTaskSpecWithinPromptBudget } from '../worker/worker-start-prompt-budget' +} from '../../../../shared/orchestration/orchestration-timing-budgets' +import { assertWorkerStartTaskSpecWithinPromptBudget } from '../../rpc/methods/orchestration/worker/worker-start-prompt-budget' import { prepareFederatedAttachmentAuthority } from './federation-attachment-authority' -import { resolveRpcWorkspaceCreatorProvenance } from '../../../workspace-creator-context' -import { claimTerminalForRemoteAttach } from '../../../../orchestration/db/worker-dispatch/worker-terminal-claim' +import { resolveRpcWorkspaceCreatorProvenance } from '../../rpc/workspace-creator-context' +import { claimTerminalForRemoteAttach } from '../db/worker-dispatch/worker-terminal-claim' export const ORCHESTRATION_FEDERATION_ATTACH_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.federationAttachStart', + access: { + kind: 'localOnly', + targets: { runId: 'run', dispatchId: 'dispatch', taskId: 'task', terminal: 'worker' } + }, requires: ['accounts'], permission: 'workspace', params: FederationAttachStartParams, diff --git a/src/main/runtime/orchestration/legacy-remote/legacy-remote-db-methods.ts b/src/main/runtime/orchestration/legacy-remote/legacy-remote-db-methods.ts new file mode 100644 index 00000000000..2eb2092a3df --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote/legacy-remote-db-methods.ts @@ -0,0 +1,43 @@ +// The DB layer's only way into this folder; keep it free of rpc and runtime imports. +import { attachFederatedDispatchObservationFence } from './federated-dispatch-observation-fence' +import type { FederatedDispatchObservationFenceMethods } from './federated-dispatch-observation-fence' +import { attachFederationRelayEnqueue } from './federation-relay-enqueue' +import type { FederationRelayEnqueueMethods } from './federation-relay-enqueue' +import { attachFederationRelayItem } from './federation-relay-item' +import type { FederationRelayItemMethods } from './federation-relay-item' +import { attachFederationRelayReportAcknowledgment } from './federation-relay-report-acknowledgment' +import type { FederationRelayReportAcknowledgmentMethods } from './federation-relay-report-acknowledgment' +import { attachRemoteDispatchAttachmentAuthority } from './remote-dispatch-attachment-authority' +import type { RemoteDispatchAttachmentAuthorityMethods } from './remote-dispatch-attachment-authority' +import { attachRemoteDispatchAttachmentCreate } from './remote-dispatch-attachment-create' +import type { RemoteDispatchAttachmentCreateMethods } from './remote-dispatch-attachment-create' +import { attachRemoteDispatchAttachmentRelease } from './remote-dispatch-attachment-release' +import type { RemoteDispatchAttachmentReleaseMethods } from './remote-dispatch-attachment-release' +import { attachRemoteDispatchAttachmentStop } from './remote-dispatch-attachment-stop' +import type { RemoteDispatchAttachmentStopMethods } from './remote-dispatch-attachment-stop' +import { attachRemoteQuestionStore } from './remote-question-store' +import type { RemoteQuestionStoreMethods } from './remote-question-store' + +export type { FederationRelayAcknowledgment } from './federation-relay-report-acknowledgment' + +export type LegacyRemoteDbMethods = FederatedDispatchObservationFenceMethods & + RemoteDispatchAttachmentCreateMethods & + RemoteDispatchAttachmentAuthorityMethods & + RemoteDispatchAttachmentReleaseMethods & + RemoteDispatchAttachmentStopMethods & + FederationRelayEnqueueMethods & + RemoteQuestionStoreMethods & + FederationRelayItemMethods & + FederationRelayReportAcknowledgmentMethods + +export function attachLegacyRemoteDbMethods(ctor: { prototype: object }): void { + attachFederatedDispatchObservationFence(ctor) + attachRemoteDispatchAttachmentCreate(ctor) + attachRemoteDispatchAttachmentAuthority(ctor) + attachRemoteDispatchAttachmentRelease(ctor) + attachRemoteDispatchAttachmentStop(ctor) + attachFederationRelayEnqueue(ctor) + attachRemoteQuestionStore(ctor) + attachFederationRelayItem(ctor) + attachFederationRelayReportAcknowledgment(ctor) +} diff --git a/src/main/runtime/orchestration/legacy-remote/legacy-remote.ts b/src/main/runtime/orchestration/legacy-remote/legacy-remote.ts new file mode 100644 index 00000000000..30084b63c4a --- /dev/null +++ b/src/main/runtime/orchestration/legacy-remote/legacy-remote.ts @@ -0,0 +1,14 @@ +// Worker-server half of today's remote attachments (a paired Orca drives a worker here). +// Frozen: bug fixes only. Code outside this folder imports it only through this module, +// except the DB layer, which uses legacy-remote-db-methods.ts. +/** The `orchestration.federation*` methods a paired Run home calls on this server. */ +export { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './federation' +export { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './federation-control' +export { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './federation-relay' + +export { askRemoteRunHome } from './ask-remote' +export { releaseRemoteAttachment } from './federated-worker-release-host' +export { inspectRemoteAttachment } from './federation-attachment-observation' +export { federationRelayWireItem } from './federation-relay-wire' +export { replyToRemoteRunHome } from './reply-remote' +export { sendRemoteMessage } from './send-remote' diff --git a/src/main/runtime/rpc/methods/orchestration/federation/remote-attachment-archive-read.ts b/src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts similarity index 75% rename from src/main/runtime/rpc/methods/orchestration/federation/remote-attachment-archive-read.ts rename to src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts index 806c101f41c..f49421c3a87 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/remote-attachment-archive-read.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-attachment-archive-read.ts @@ -1,6 +1,6 @@ -import type { RemoteDispatchAttachmentRow } from '../../../../orchestration/db/orchestration-records' -import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' -import { readArchivedWorkerOutput } from '../worker/worker-archive-read' +import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' +import type { WorkerTerminalReleaseRuntime } from '../terminal-authority/release/worker-terminal-release-runtime' +import { readArchivedWorkerOutput } from '../../rpc/methods/orchestration/worker/worker-archive-read' export async function readRemoteAttachmentArchive(args: { runtime: WorkerTerminalReleaseRuntime diff --git a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-authority.ts similarity index 96% rename from src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts rename to src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-authority.ts index 93bc2e6f86f..8fd661a579f 100644 --- a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-authority.ts @@ -1,7 +1,7 @@ -import type { RemoteDispatchAttachmentRow } from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import { isEquivalentPaneKey } from '../pane-key-match' -import type { OrchestrationDb } from '../orchestration-db' +import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import { isEquivalentPaneKey } from '../db/pane-key-match' +import type { OrchestrationDb } from '../db/orchestration-db' export function prepareRemoteAttachmentAuthority( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-create.ts similarity index 93% rename from src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts rename to src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-create.ts index c8c7a5a3ef6..4ba74d68966 100644 --- a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-create.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-create.ts @@ -1,10 +1,10 @@ -import type { WorkerDispatchState, RemoteDispatchAttachmentRow } from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import { ensureMutationReceiptCapacity } from '../mutation-receipts/mutation-receipt-capacity' -import type { OrchestrationDb } from '../orchestration-db' -import { federatedStubHomeRunId } from '../contract-constants' -import { insertRemoteDispatchAttachmentRow } from '../dispatch-row-writer' -import { REMOTE_DISPATCH_ATTACHMENT_COLUMN_LIST } from '../row-column-lists' +import type { WorkerDispatchState, RemoteDispatchAttachmentRow } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import { ensureMutationReceiptCapacity } from '../db/mutation-receipts/mutation-receipt-capacity' +import type { OrchestrationDb } from '../db/orchestration-db' +import { federatedStubHomeRunId } from '../db/contract-constants' +import { insertRemoteDispatchAttachmentRow } from '../db/dispatch-row-writer' +import { REMOTE_DISPATCH_ATTACHMENT_COLUMN_LIST } from '../db/row-column-lists' export function createRemoteDispatchAttachment( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-release.ts b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-release.ts similarity index 95% rename from src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-release.ts rename to src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-release.ts index d7e844a0336..829abe1736e 100644 --- a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-release.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-release.ts @@ -4,9 +4,9 @@ import { WORKER_TERMINAL_RELEASABLE_ROW_SQL, type WorkerTerminalResourceRow, type WorkerTerminalRetainedReason -} from '../../terminal-authority/release/worker-terminal-ownership' -import { OrchestrationError } from '../../orchestration-error' -import type { OrchestrationDb } from '../orchestration-db' +} from '../terminal-authority/release/worker-terminal-ownership' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' export function requestRemoteAttachmentTerminalRelease( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-stop.ts similarity index 87% rename from src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts rename to src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-stop.ts index fd613bd45d4..cfd5f241deb 100644 --- a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-dispatch-attachment-stop.ts @@ -1,11 +1,14 @@ -import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' -import type { RemoteDispatchAttachmentRow } from '../orchestration-records' -import { OrchestrationError } from '../../orchestration-error' -import { paneKeyMatchSuffix, REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL } from '../pane-key-match' -import type { OrchestrationDb } from '../orchestration-db' -import { potentiallyLiveRemoteAttachmentSql } from './remote-attachment-liveness' -import { REMOTE_DISPATCH_ATTACHMENT_COLUMN_LIST } from '../row-column-lists' -import { refuseStopWhileKeptOpen } from '../worker-terminal/worker-terminal-user-keep' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { RemoteDispatchAttachmentRow } from '../db/orchestration-records' +import { OrchestrationError } from '../orchestration-error' +import { + paneKeyMatchSuffix, + REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL +} from '../db/pane-key-match' +import type { OrchestrationDb } from '../db/orchestration-db' +import { potentiallyLiveRemoteAttachmentSql } from '../db/federation/remote-attachment-liveness' +import { REMOTE_DISPATCH_ATTACHMENT_COLUMN_LIST } from '../db/row-column-lists' +import { refuseStopWhileKeptOpen } from '../db/worker-terminal/worker-terminal-user-keep' export function beginRemoteAttachmentStop( this: OrchestrationDb, diff --git a/src/main/runtime/orchestration/db/federation/remote-question-store.ts b/src/main/runtime/orchestration/legacy-remote/remote-question-store.ts similarity index 96% rename from src/main/runtime/orchestration/db/federation/remote-question-store.ts rename to src/main/runtime/orchestration/legacy-remote/remote-question-store.ts index 6b94a89e88e..d3904c1382c 100644 --- a/src/main/runtime/orchestration/db/federation/remote-question-store.ts +++ b/src/main/runtime/orchestration/legacy-remote/remote-question-store.ts @@ -1,6 +1,6 @@ -import { importedAnswerSenderSnapshot } from '../../mailbox/senders/answer-sender-relay-report' -import { OrchestrationError } from '../../orchestration-error' -import type { OrchestrationDb } from '../orchestration-db' +import { importedAnswerSenderSnapshot } from '../mailbox/senders/answer-sender-relay-report' +import { OrchestrationError } from '../orchestration-error' +import type { OrchestrationDb } from '../db/orchestration-db' export function getRemoteQuestion( this: OrchestrationDb, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-remote.ts b/src/main/runtime/orchestration/legacy-remote/reply-remote.ts similarity index 84% rename from src/main/runtime/rpc/methods/orchestration/messaging/reply-remote.ts rename to src/main/runtime/orchestration/legacy-remote/reply-remote.ts index 3c579ecd6f5..64de965a635 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-remote.ts +++ b/src/main/runtime/orchestration/legacy-remote/reply-remote.ts @@ -1,7 +1,7 @@ -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' -import type { MessageRow } from '../../../../orchestration/db/orchestration-records' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { remoteRunHomeUnreachable } from '../routing' +import type { OrchestrationDb } from '../db/orchestration-db' +import type { MessageRow } from '../db/orchestration-records' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { remoteRunHomeUnreachable } from '../../rpc/methods/orchestration/routing' import { sendRemoteMessage } from './send-remote' /** Reply to mirrored remote-Run mail only at its home, through this pane's own Dispatch link. */ diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-remote.ts b/src/main/runtime/orchestration/legacy-remote/send-remote.ts similarity index 77% rename from src/main/runtime/rpc/methods/orchestration/messaging/send-remote.ts rename to src/main/runtime/orchestration/legacy-remote/send-remote.ts index 5b3c961fa88..7faa347787a 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-remote.ts +++ b/src/main/runtime/orchestration/legacy-remote/send-remote.ts @@ -1,20 +1,17 @@ -import type { - MessageType, - WorkerDispatchState -} from '../../../../orchestration/db/orchestration-records' -import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { MessageType, WorkerDispatchState } from '../db/orchestration-records' +import type { OrchestrationDb } from '../db/orchestration-db' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { waitForFederatedLifecycleSettlement } from '../../../../orchestration/federation/federation-lifecycle-settlement' -import { bindCoordinatorMutationPayload } from '../../../../orchestration/workers/reports/dispatch-message-binding' -import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { OrchestrationError } from '../orchestration-error' +import { waitForFederatedLifecycleSettlement } from './federation-lifecycle-settlement' +import { bindCoordinatorMutationPayload } from '../workers/reports/dispatch-message-binding' +import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../shared/orchestration/orchestration-runtime-capabilities' import type { z } from 'zod' -import { parseRemoteWorkerPayload } from './message-payload' -import type { SendParams } from './send-params' -import { rejectFederatedExplicitTarget } from '../routing' -import { WORKER_DONE_RECORDED_NEXT } from '../receipt-next' -import { assertWorkerCanReport } from '../../../../orchestration/workers/reports/worker-report-admission' +import { parseRemoteWorkerPayload } from '../../rpc/methods/orchestration/messaging/message-payload' +import type { SendParams } from '../../rpc/methods/orchestration/messaging/send-params' +import { rejectFederatedExplicitTarget } from '../../rpc/methods/orchestration/routing' +import { WORKER_DONE_RECORDED_NEXT } from '../../rpc/methods/orchestration/receipt-next' +import { assertWorkerCanReport } from '../workers/reports/worker-report-admission' type SendParamsInput = z.infer diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler.ts index d6743a5ca51..7e8e25ced01 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler.ts @@ -1,6 +1,6 @@ import type { WorkerTerminalReleaseRuntime } from './worker-terminal-release-runtime' import { reconcileRequestedWorkerTerminalReleases } from './worker-terminal-release-reconciliation' -import { releaseFederatedWorkerAtHomeDeadline } from '../../../rpc/methods/orchestration/federation/federated-worker-home-auto-release' +import { releaseFederatedWorkerAtHomeDeadline } from '../../legacy-remote-home/legacy-remote-home' const MAX_TIMER_DELAY_MS = 2_147_483_647 diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts index e48729769c7..0d5555937df 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-reconciliation.ts @@ -1,6 +1,5 @@ import type { WorkerTerminalReleaseRuntime } from './worker-terminal-release-runtime' -import { inspectRemoteAttachment } from '../../../rpc/methods/orchestration/federation/federation-attachment-observation' -import { releaseRemoteAttachment } from '../../../rpc/methods/orchestration/federation/federated-worker-release-host' +import { inspectRemoteAttachment, releaseRemoteAttachment } from '../../legacy-remote/legacy-remote' import { completeWorkerTerminalRelease } from '../../../rpc/methods/orchestration/worker/worker-release-completion' export type WorkerTerminalReleaseReconciliationResult = { diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index e252387ad04..729f5cf8e54 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -26,6 +26,10 @@ import type { OrcadPeerDesktopsResult } from '../../../shared/orcad-peer-desktop import type { RpcBinarySender } from './rpc-binary-sender' import type { RpcMethodPermission } from './rpc-method-permission' import type { OrcadFeatureRequirement } from './orcad-feature-readiness' +import { + runsOrchestrationAccessCheck, + type OrchestrationMethodAccessDeclaration +} from './methods/orchestration/access/orchestration-method-access' import type { RegisterDeviceKeyParams, RegisterDeviceKeyResult @@ -234,6 +238,8 @@ type RpcMethodWithParams

= { readonly permission: RpcMethodPermission readonly params: ZodType | null readonly requires?: OrcadFeatureRequirement

+ // Set only by defineOrchestrationMethod, whose checked handler the registry requires. + readonly orchestrationAccess?: OrchestrationMethodAccessDeclaration readonly handler: (params: P, ctx: RpcContext) => unknown } @@ -242,6 +248,7 @@ type RpcStreamingMethodWithParams

= { readonly permission: RpcMethodPermission readonly params: ZodType | null readonly requires?: OrcadFeatureRequirement

+ readonly orchestrationAccess?: OrchestrationMethodAccessDeclaration readonly stream: true readonly handler: (params: P, ctx: RpcContext, emit: (result: unknown) => void) => Promise } @@ -288,6 +295,10 @@ export function buildRegistry(methods: readonly RpcAnyMethodDeclaration[]): RpcR if (registry.has(method.name)) { throw new Error(`duplicate_rpc_method:${method.name}`) } + // No orchestration method exists without its access check. + if (method.name.startsWith('orchestration.') && !runsOrchestrationAccessCheck(method)) { + throw new Error(`orchestration_method_without_access:${method.name}`) + } registry.set(method.name, method) } return registry diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts new file mode 100644 index 00000000000..0165250f962 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts @@ -0,0 +1,493 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import '../../../../orchestration/db/contract-constants' +import '../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../orchestration/db/dispatch-row-writer' +import '../../../../orchestration/db/attempt-outcome-projection' +import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' +import { eraseRpcMethods, type RpcResponse } from '../../../core' +import { RpcDispatcher } from '../../../dispatcher' +import { ORCHESTRATION_METHODS } from '../orchestration' + +const PANES: Record = { + term_owner: 'tab_owner:11111111-1111-4111-8111-111111111111', + term_other: 'tab_other:22222222-2222-4222-8222-222222222222', + term_lone: 'tab_lone:33333333-3333-4333-8333-333333333333', + term_worker: 'tab_worker:44444444-4444-4444-8444-444444444444', + term_helper: 'tab_helper:55555555-5555-4555-8555-555555555555' +} + +/** Two Runs, a dispatched Task with a worker, a question to the Run, a helper's question to that worker, a gate and plain mail. */ +async function createFixture() { + const db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => PANES[handle] ?? null) + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => PANES[handle] ?? null) + vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) => + PANES[handle] ? `process:${handle}` : null + ) + vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => {}) + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + // Startup recovery runs on the first call; seed after it so it cannot settle the fixture's workers. + await dispatcher.dispatch({ + id: 'rpc_warm', + authToken: 'token', + method: 'orchestration.runList', + params: {}, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }) + const owned = db.createRun({ + objective: 'owned', + coordinatorHandle: 'term_owner', + coordinatorPaneKey: PANES.term_owner + }) + const foreign = db.createRun({ + objective: 'foreign', + coordinatorHandle: 'term_other', + coordinatorPaneKey: PANES.term_other + }) + const task = db.createTask({ runId: owned.id, spec: 'work' }) + const dispatch = createRootDispatch( + db, + task.id, + 'term_worker', + PANES.term_worker, + undefined, + 'process:term_worker' + ) + const helperTask = db.createTask({ runId: owned.id, spec: 'helper work' }) + const helper = createRootDispatch( + db, + helperTask.id, + 'term_helper', + PANES.term_helper, + undefined, + 'process:term_helper' + ) + const question = db.createQuestion({ + runId: owned.id, + dispatchId: dispatch.id, + askerHandle: 'term_worker', + question: 'Which way?' + }).message + const helperQuestion = db.createQuestion({ + runId: owned.id, + dispatchId: helper.id, + askerHandle: 'term_helper', + question: 'Helper asks its creator', + to: `dispatch:${dispatch.id}` + }).message + const mail = db.insertMessage({ + from: 'term_lone', + to: 'term_owner', + subject: 'hello', + body: 'plain mail', + runId: owned.id + }) + const readyTask = db.createTask({ runId: owned.id, spec: 'ready work' }) + const foreignTask = db.createTask({ runId: foreign.id, spec: 'foreign work' }) + // A gate on the dispatched Task would settle its Dispatch. + const gate = db.createGate({ taskId: readyTask.id, question: 'Proceed?' }) + const ids = { + owned: owned.id, + foreign: foreign.id, + task: task.id, + readyTask: readyTask.id, + foreignTask: foreignTask.id, + dispatch: dispatch.id, + question: question.id, + helperQuestion: helperQuestion.id, + mail: mail.id, + gate: gate.id + } + return { db, runtime, ids, dispatcher } +} + +type Ids = Awaited>['ids'] +type Case = { method: string; params: (caller: string, ids: Ids) => unknown } + +/** One call per method (several where its own rule has several paths), each made by every caller. */ +const CASES = { + ask: { + method: 'orchestration.ask', + params: (from) => ({ to: 'term_lone', question: 'q', wait: false, from }) + }, + callerShow: { method: 'orchestration.callerShow', params: () => undefined }, + check: { method: 'orchestration.check', params: (terminal) => ({ terminal }) }, + checkRun: { + method: 'orchestration.check', + params: (terminal, ids) => ({ terminal, run: ids.owned, peek: true }) + }, + crewSubscribe: { + method: 'orchestration.crewSubscribe', + params: (address) => ({ party: { address } }) + }, + dispatch: { + method: 'orchestration.dispatch', + params: (from, ids) => ({ task: ids.readyTask, to: 'term_lone', from, dryRun: true }) + }, + dispatchForeign: { + method: 'orchestration.dispatch', + params: (from, ids) => ({ task: ids.foreignTask, to: 'term_lone', from, dryRun: true }) + }, + dispatchShow: { + method: 'orchestration.dispatchShow', + params: (from, ids) => ({ task: ids.task, from }) + }, + federationAck: { + method: 'orchestration.federationAck', + params: (_, ids) => ({ dispatchId: ids.dispatch, throughSequence: 0 }) + }, + federationAttachStart: { + method: 'orchestration.federationAttachStart', + params: (_, ids) => ({ + dispatchId: ids.dispatch, + taskId: ids.task, + taskSpec: 'work', + protocolVersion: 3, + worktree: 'current' + }) + }, + federationFleetSnapshot: { + method: 'orchestration.federationFleetSnapshot', + params: (_, ids) => ({ dispatchIds: [ids.dispatch] }) + }, + federationImport: { + method: 'orchestration.federationImport', + params: (_, ids) => ({ dispatchId: ids.dispatch, items: [] }) + }, + federationPull: { + method: 'orchestration.federationPull', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + federationRead: { + method: 'orchestration.federationRead', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + federationReadOutput: { + method: 'orchestration.federationReadOutput', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + federationRelease: { + method: 'orchestration.federationRelease', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + federationRetain: { + method: 'orchestration.federationRetain', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + federationShow: { + method: 'orchestration.federationShow', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + federationStop: { + method: 'orchestration.federationStop', + params: (_, ids) => ({ dispatchId: ids.dispatch }) + }, + gateCreate: { + method: 'orchestration.gateCreate', + params: (from, ids) => ({ task: ids.task, question: 'q', from }) + }, + gateCreateBadOptions: { + method: 'orchestration.gateCreate', + params: (from, ids) => ({ task: ids.task, question: 'q', options: 'not json', from }) + }, + gateCreateForeign: { + method: 'orchestration.gateCreate', + params: (from, ids) => ({ task: ids.foreignTask, question: 'q', from }) + }, + gateList: { method: 'orchestration.gateList', params: (from) => ({ from }) }, + gateListRun: { + method: 'orchestration.gateList', + params: (from, ids) => ({ from, run: ids.owned }) + }, + gateResolve: { + method: 'orchestration.gateResolve', + params: (from, ids) => ({ id: ids.gate, resolution: 'yes', from }) + }, + inbox: { method: 'orchestration.inbox', params: (terminal) => ({ terminal }) }, + partyLocation: { method: 'orchestration.partyLocation', params: (address) => ({ address }) }, + partyOpen: { method: 'orchestration.partyOpen', params: (address) => ({ address }) }, + peerMailAck: { method: 'orchestration.peerMailAck', params: () => ({ acknowledgments: [] }) }, + peerMailDeliver: { + method: 'orchestration.peerMailDeliver', + params: (to) => ({ + conversationId: 'peerconv_x', + messageId: 'msg_peer', + to, + senderLabel: 'A', + subject: 's' + }) + }, + peerMailPull: { method: 'orchestration.peerMailPull', params: () => ({ waitMs: 0 }) }, + replyHelperQuestion: { + method: 'orchestration.reply', + params: (from, ids) => ({ id: ids.helperQuestion, body: 'a', from }) + }, + replyMail: { + method: 'orchestration.reply', + params: (from, ids) => ({ id: ids.mail, body: 'a', from }) + }, + replyQuestion: { + method: 'orchestration.reply', + params: (from, ids) => ({ id: ids.question, body: 'a', from }) + }, + replyQuestionOtherRun: { + method: 'orchestration.reply', + params: (from, ids) => ({ id: ids.question, body: 'a', from, run: ids.foreign }) + }, + requestShow: { method: 'orchestration.requestShow', params: () => ({ request: 'req_unknown' }) }, + reset: { method: 'orchestration.reset', params: () => ({ messages: true }) }, + run: { method: 'orchestration.run', params: (from) => ({ spec: 's', from }) }, + runCreate: { method: 'orchestration.runCreate', params: (from) => ({ objective: 'o', from }) }, + runCurrent: { method: 'orchestration.runCurrent', params: (from) => ({ from }) }, + runList: { method: 'orchestration.runList', params: () => ({}) }, + runShow: { method: 'orchestration.runShow', params: (from, ids) => ({ id: ids.owned, from }) }, + runStop: { method: 'orchestration.runStop', params: () => ({}) }, + runUse: { method: 'orchestration.runUse', params: (from, ids) => ({ id: ids.owned, from }) }, + send: { + method: 'orchestration.send', + params: (from) => ({ to: 'term_lone', subject: 's', body: 'b', from }) + }, + sessionAddress: { + method: 'orchestration.sessionAddress', + params: () => ({ sessionId: 'not-a-session' }) + }, + taskCreate: { + method: 'orchestration.taskCreate', + params: (callerTerminalHandle) => ({ spec: 's', callerTerminalHandle }) + }, + taskCreateBadDeps: { + method: 'orchestration.taskCreate', + params: (callerTerminalHandle) => ({ spec: 's', deps: 'not json', callerTerminalHandle }) + }, + taskCreateOtherRun: { + method: 'orchestration.taskCreate', + params: (callerTerminalHandle, ids) => ({ spec: 's', callerTerminalHandle, run: ids.foreign }) + }, + taskList: { + method: 'orchestration.taskList', + params: (callerTerminalHandle) => ({ callerTerminalHandle }) + }, + taskListRun: { + method: 'orchestration.taskList', + params: (callerTerminalHandle, ids) => ({ callerTerminalHandle, run: ids.foreign }) + }, + taskUpdate: { + method: 'orchestration.taskUpdate', + params: (callerTerminalHandle, ids) => ({ + id: ids.readyTask, + status: 'blocked', + callerTerminalHandle + }) + }, + taskUpdateForeign: { + method: 'orchestration.taskUpdate', + params: (callerTerminalHandle, ids) => ({ + id: ids.foreignTask, + status: 'blocked', + callerTerminalHandle + }) + }, + workerAbandon: { + method: 'orchestration.workerAbandon', + params: (_, ids) => ({ dispatch: ids.dispatch }) + }, + workerAutoClose: { + method: 'orchestration.workerAutoClose', + params: () => ({ terminal: 'term_worker' }) + }, + workerChatTouch: { + method: 'orchestration.workerChatTouch', + params: () => ({ terminal: 'term_worker' }) + }, + workerKeepOpen: { + method: 'orchestration.workerKeepOpen', + params: () => ({ terminal: 'term_worker', keep: true }) + }, + workerList: { method: 'orchestration.workerList', params: () => ({}) }, + workerRead: { + method: 'orchestration.workerRead', + params: (_, ids) => ({ dispatch: ids.dispatch }) + }, + workerRelease: { + method: 'orchestration.workerRelease', + params: (_, ids) => ({ dispatch: ids.dispatch }) + }, + workerRetain: { + method: 'orchestration.workerRetain', + params: (_, ids) => ({ dispatch: ids.dispatch }) + }, + workerShow: { + method: 'orchestration.workerShow', + params: (_, ids) => ({ dispatch: ids.dispatch }) + }, + workerStart: { + method: 'orchestration.workerStart', + params: (from) => ({ task: 'task_missing', from }) + }, + workerStop: { + method: 'orchestration.workerStop', + params: (_, ids) => ({ dispatch: ids.dispatch }) + }, + workerTerminalUserInput: { + method: 'orchestration.workerTerminalUserInput', + params: () => ({ terminal: 'term_worker' }) + } +} + +/** Recorded on main before the access check existed; every row must stay the same. Callers: term_owner, term_other, term_lone, term_worker. */ +const EXPECTED: Record & Record = { + ask: 'dispatch_inactive dispatch_inactive dispatch_inactive dispatch_run_mismatch', + callerShow: 'ok ok ok ok', + check: 'ok ok ok ok', + checkRun: 'ok consumer_fenced consumer_fenced worker_cannot_coordinate_own_run', + crewSubscribe: 'invalid_argument invalid_argument invalid_argument invalid_argument', + dispatch: 'ok task_not_found run_required run_required', + dispatchForeign: 'task_not_found ok run_required run_required', + dispatchShow: 'ok ok ok ok', + federationAck: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationAttachStart: 'invalid_argument invalid_argument invalid_argument invalid_argument', + federationFleetSnapshot: 'ok ok ok ok', + federationImport: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationPull: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationRead: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationReadOutput: + 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationRelease: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationRetain: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationShow: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + federationStop: 'dispatch_not_found dispatch_not_found dispatch_not_found dispatch_not_found', + gateCreate: 'ok task_not_found run_required run_required', + gateCreateBadOptions: 'runtime_error runtime_error runtime_error runtime_error', + gateCreateForeign: 'task_not_found ok run_required run_required', + gateList: 'ok ok run_required run_required', + gateListRun: 'ok ok ok ok', + gateResolve: 'ok runtime_error run_required run_required', + inbox: 'ok ok ok ok', + partyLocation: 'ok ok ok ok', + partyOpen: 'ok ok ok ok', + peerMailAck: + 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', + peerMailDeliver: + 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', + peerMailPull: + 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', + replyHelperQuestion: 'ok consumer_fenced consumer_fenced ok', + replyMail: 'ok ok ok ok', + replyQuestion: 'ok consumer_fenced consumer_fenced worker_cannot_coordinate_own_run', + replyQuestionOtherRun: 'consumer_fenced question_not_found consumer_fenced consumer_fenced', + requestShow: 'ok ok ok ok', + reset: 'ok ok ok ok', + run: 'orchestration_migration_required orchestration_migration_required orchestration_migration_required orchestration_migration_required', + runCreate: 'ok ok ok ok', + runCurrent: 'ok ok ok ok', + runList: 'ok ok ok ok', + runShow: 'ok ok ok ok', + runStop: + 'orchestration_migration_required orchestration_migration_required orchestration_migration_required orchestration_migration_required', + runUse: 'ok ok ok worker_cannot_coordinate_own_run', + send: 'ok ok ok ok', + sessionAddress: 'ok ok ok ok', + taskCreate: 'ok ok run_required run_required', + taskCreateBadDeps: 'runtime_error runtime_error runtime_error runtime_error', + taskCreateOtherRun: 'consumer_fenced ok consumer_fenced consumer_fenced', + taskList: 'ok ok run_required run_required', + taskListRun: 'ok ok ok ok', + taskUpdate: 'ok task_not_found run_required run_required', + taskUpdateForeign: 'task_not_found ok run_required run_required', + workerAbandon: 'ok ok ok ok', + workerAutoClose: 'ok ok ok ok', + workerChatTouch: 'ok ok ok ok', + workerKeepOpen: 'ok ok ok ok', + workerList: 'ok ok ok ok', + workerRead: + 'worker_identity_changed worker_identity_changed worker_identity_changed worker_identity_changed', + workerRelease: 'dispatch_inactive dispatch_inactive dispatch_inactive dispatch_inactive', + workerRetain: 'dispatch_inactive dispatch_inactive dispatch_inactive dispatch_inactive', + workerShow: 'ok ok ok ok', + workerStart: 'task_not_found task_not_found consumer_fenced task_not_found', + workerStop: 'ok ok ok ok', + workerTerminalUserInput: 'ok ok ok ok' +} + +const CALLERS = ['term_owner', 'term_other', 'term_lone', 'term_worker'] as const + +async function outcome({ method, params }: Case, caller: string): Promise { + const { db, dispatcher, ids } = await createFixture() + try { + const response: RpcResponse = await dispatcher.dispatch({ + id: `rpc_${method}`, + authToken: 'token', + method, + params: params(caller, ids), + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }) + return response.ok ? 'ok' : response.error.code + } finally { + db.close() + } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('orchestration access outcomes', () => { + it('covers every orchestration method', () => { + const covered = new Set(Object.values(CASES).map((entry) => entry.method)) + const methods = eraseRpcMethods(ORCHESTRATION_METHODS).map((method) => method.name) + expect(methods.filter((method) => !covered.has(method))).toEqual([]) + }) + + it.each(Object.entries(CASES))( + '%s keeps its allow/refuse outcome for every caller', + async (name, entry: Case) => { + const row: string[] = [] + for (const caller of CALLERS) { + row.push(await outcome(entry, caller)) + } + expect(row.join(' ')).toBe(EXPECTED[name]) + }, + // The first call starts lazy host setup. + 30_000 + ) +}) + +describe('orchestration access on replay', () => { + it('replays an accepted reply after its caller loses the Run, refusing only new requests', async () => { + const { db, dispatcher, ids } = await createFixture() + try { + const reply = (requestId: string) => + dispatcher.dispatch({ + id: `rpc_${requestId}`, + authToken: 'token', + method: 'orchestration.reply', + params: { id: ids.question, body: 'go left', from: 'term_owner' }, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: requestId + }) + const accepted = await reply('req_answer') + expect(accepted).toMatchObject({ ok: true }) + // Another terminal now coordinates the Run. + db.db + .prepare('UPDATE runs SET coordinator_handle = ?, coordinator_pane_key = ? WHERE id = ?') + .run('term_lone', PANES.term_lone, ids.owned) + expect(await reply('req_new')).toMatchObject({ + ok: false, + error: { code: 'consumer_fenced' } + }) + const answer = db.getQuestion(ids.question)?.answer_message_id + expect(answer).toBeTruthy() + expect(await reply('req_answer')).toMatchObject({ + ok: true, + result: { message: { id: answer }, mutation: { replayed: true } } + }) + } finally { + db.close() + } + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.test.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.test.ts new file mode 100644 index 00000000000..51f4015ef3b --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { buildRegistry, defineMethod, type RpcContext } from '../../../core' +import { attachMutationReplayNudge } from '../../../orchestration-mutation-receipt' +import { ORCHESTRATION_SEND_METHODS } from '../messaging/send-methods' +import { defineOrchestrationMethod } from './orchestration-method-access' + +const refuse = (): never => { + throw new Error('refused') +} + +const ctx: RpcContext = { runtime: new OrcaRuntimeService() } + +describe('orchestration method access declarations', () => { + it('refuses to register an orchestration method without one', () => { + const undeclared = defineMethod({ + name: 'orchestration.undeclared', + permission: 'workspace', + params: null, + handler: () => null + }) + expect(() => buildRegistry([undeclared])).toThrow( + 'orchestration_method_without_access:orchestration.undeclared' + ) + }) + + it('refuses a declaration whose rule its handler never runs', () => { + const bypass = { + ...defineMethod({ + name: 'orchestration.bypass', + permission: 'workspace', + params: null, + handler: () => 'effect' + }), + orchestrationAccess: { kind: 'writes', targets: {}, rule: refuse } + } as const + expect(() => buildRegistry([bypass])).toThrow( + 'orchestration_method_without_access:orchestration.bypass' + ) + }) + + it('refuses a checked handler registered without its own declaration', () => { + const [send] = ORCHESTRATION_SEND_METHODS + const redeclared = defineMethod({ + name: send.name, + permission: send.permission, + params: send.params, + handler: send.handler + }) + expect(() => buildRegistry([redeclared])).toThrow( + 'orchestration_method_without_access:orchestration.send' + ) + }) + + it('keeps a refusal a rejected promise for async handlers and a throw for sync ones', async () => { + const asyncMethod = defineOrchestrationMethod({ + name: 'orchestration.asyncProbe', + permission: 'workspace', + params: null, + access: { kind: 'writes', targets: {}, rule: refuse }, + handler: async () => 'effect' + }) + const syncMethod = defineOrchestrationMethod({ + name: 'orchestration.syncProbe', + permission: 'workspace', + params: null, + access: { kind: 'writes', targets: {}, rule: refuse }, + handler: () => 'effect' + }) + let pending: Promise | undefined + expect(() => { + pending = asyncMethod.handler(undefined, ctx) + }).not.toThrow() + await expect(pending).rejects.toThrow('refused') + expect(() => syncMethod.handler(undefined, ctx)).toThrow('refused') + }) + + it('replays an accepted call before any rule, so a replay is never authorized again', () => { + const method = defineOrchestrationMethod({ + name: 'orchestration.replayProbe', + permission: 'workspace', + params: null, + access: { kind: 'writes', targets: {}, rule: refuse }, + replay: (_params, { replayedMutationReceipt }) => ({ receipt: replayedMutationReceipt }), + handler: () => 'effect' + }) + expect(method.handler(undefined, { ...ctx, replayedMutationReceipt: 'accepted' })).toBe( + 'accepted' + ) + expect(() => method.handler(undefined, ctx)).toThrow('refused') + }) + + it("keeps send's replay a promise, rejected when redelivering its nudge fails", async () => { + const db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'notifyMessageArrived').mockImplementation(() => { + throw new Error('nudge failed') + }) + const [send] = ORCHESTRATION_SEND_METHODS + const receipt = attachMutationReplayNudge( + { message: { id: 'msg_accepted' } }, + { kind: 'messages', targets: [{ to: 'term_x', type: 'status' }] } + ) + let pending: Promise | undefined + expect(() => { + pending = send.handler(send.params.parse({ subject: 's', from: 'term_x' }), { + runtime, + replayedMutationReceipt: receipt + }) + }).not.toThrow() + await expect(pending).rejects.toThrow('nudge failed') + db.close() + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts new file mode 100644 index 00000000000..01c58ffda86 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts @@ -0,0 +1,198 @@ +/** One access declaration on every orchestration method, checked where its handler runs; + * the registry refuses an orchestration method without one. */ +import { types } from 'node:util' +import type { ZodType } from 'zod' +import type { RpcContext, RpcTypedMethod, RpcTypedStreamingMethod } from '../../../core' + +type ParsedParams = TSchema extends ZodType + ? TSchema['_output'] + : void + +/** `localOnly` methods act on this Orca as a whole (reset, Run binding, the federation wire). */ +export type OrchestrationAccessKind = 'reads' | 'writes' | 'localOnly' + +/** What a target field names; a terminal, pane or session field naming a worker is `worker`, + * and send's JSON `payload` names the Dispatch its `dispatchId` selects. */ +export type OrchestrationSubjectKind = + | 'dispatch' + | 'task' + | 'message' + | 'gate' + | 'run' + | 'worker' + | 'party' + | 'session' + | 'request' + | 'conversation' + +/** A field naming who is calling, as opposed to what the call acts on. */ +export type OrchestrationCallerField = 'from' | 'terminal' | 'callerTerminalHandle' + +type FieldOf

= P extends object ? Extract : never + +export type OrchestrationAccessRuleInput

= { + params: P + ctx: RpcContext + /** The declared caller field's value. */ + caller: string | undefined +} + +/** A named function holding a method's own authorization; its grant is what the handler acts with. */ +export type OrchestrationAccessRule = (input: OrchestrationAccessRuleInput

) => G + +export type OrchestrationMethodAccess = { + readonly kind: OrchestrationAccessKind + readonly caller?: Extract, OrchestrationCallerField> + /** Every field naming something the call acts on, kept apart from the caller field. */ + readonly targets: Readonly, OrchestrationSubjectKind>>> + /** A read returning a collection; a narrower caller restricts its query, never its page. */ + readonly collection?: true + readonly rule?: OrchestrationAccessRule +} + +/** The erased declaration the registry keeps for the dispatcher and the session-caller binding. */ +export type OrchestrationMethodAccessDeclaration = { + readonly kind: OrchestrationAccessKind + readonly caller?: OrchestrationCallerField + readonly targets: Readonly>> + readonly collection?: true + readonly rule?: OrchestrationAccessRule +} + +/** The one access check: every caller on this Orca is held to the method's own rule. */ +export function checkOrchestrationAccess( + access: OrchestrationMethodAccess, + params: P, + ctx: RpcContext +): G { + if (!access.rule) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: G defaults to undefined exactly when a method declares no rule. + return undefined as G + } + return access.rule({ params, ctx, caller: declaredCaller(access.caller, params) }) +} + +function declaredCaller

( + field: Extract, OrchestrationCallerField> | undefined, + params: P +): string | undefined { + if (field === undefined) { + return undefined + } + const value: unknown = params[field] + return typeof value === 'string' ? value : undefined +} + +type RpcHandler = (...args: never[]) => unknown + +// Each handler these factories built, with the declaration it checks; the registry refuses any other pairing. +const checkedHandlers = new WeakMap() + +/** Whether this handler runs the check for exactly this registered declaration. */ +export function runsOrchestrationAccessCheck(method: { + readonly handler: RpcHandler + readonly orchestrationAccess?: OrchestrationMethodAccessDeclaration +}): boolean { + const declared = method.orchestrationAccess + return declared !== undefined && checkedHandlers.get(method.handler) === declared +} + +/** A promise-returning handler's refusal or replay stays a rejected or resolved promise, a sync handler's a throw. */ +function checked( + handler: RpcHandler, + access: OrchestrationMethodAccessDeclaration, + run: (...args: A) => R +): (...args: A) => R { + const promised = types.isAsyncFunction(handler) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only an async handler's wrapper is async, so R is already a promise of the same awaited value. + const wrapped = promised ? ((async (...args: A) => await run(...args)) as (...args: A) => R) : run + checkedHandlers.set(wrapped, access) + return wrapped +} + +type OrchestrationMethodSpec< + TName extends `orchestration.${string}`, + TSchema extends ZodType | null, + TResult, + G +> = Omit, 'handler'> & { + readonly access: OrchestrationMethodAccess, G> + /** How the executor's observation of an accepted call's replay redelivers its nudge; it runs + * before any rule, since an accepted call is never authorized again. Undefined: nothing to redeliver. */ + readonly replay?: ( + params: ParsedParams, + ctx: RpcContext + ) => { receipt: unknown } | undefined + readonly handler: (params: ParsedParams, ctx: RpcContext, access: G) => TResult +} + +export type OrchestrationMethod< + TName extends string, + TSchema extends ZodType | null, + TResult +> = RpcTypedMethod & { + readonly orchestrationAccess: OrchestrationMethodAccessDeclaration +} + +/** Every orchestration method is defined here, so its access is checked before its handler acts. */ +export function defineOrchestrationMethod< + TName extends `orchestration.${string}`, + TSchema extends ZodType | null, + TResult, + G = undefined +>( + spec: OrchestrationMethodSpec +): OrchestrationMethod { + const { access, replay, handler, ...method } = spec + const declaration: OrchestrationMethodAccessDeclaration = access + return { + ...method, + orchestrationAccess: declaration, + handler: checked(handler, declaration, (params: ParsedParams, ctx: RpcContext) => { + const replayed = ctx.replayedMutationReceipt === undefined ? undefined : replay?.(params, ctx) + if (replayed) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a replay returns the receipt this handler produced when the call was accepted; a promise-returning handler's wrapper is async. + return replayed.receipt as TResult + } + return handler(params, ctx, checkOrchestrationAccess(access, params, ctx)) + }) + } +} + +export type OrchestrationStreamingMethod< + TName extends string, + TSchema extends ZodType | null +> = RpcTypedStreamingMethod & { + readonly orchestrationAccess: OrchestrationMethodAccessDeclaration +} + +export function defineOrchestrationStreamingMethod< + TName extends `orchestration.${string}`, + TSchema extends ZodType | null, + G = undefined +>( + spec: Omit, 'stream' | 'handler'> & { + readonly access: OrchestrationMethodAccess, G> + readonly handler: ( + params: ParsedParams, + ctx: RpcContext, + emit: (result: unknown) => void, + access: G + ) => Promise + } +): OrchestrationStreamingMethod { + const { access, handler, ...method } = spec + const declaration: OrchestrationMethodAccessDeclaration = access + return { + ...method, + stream: true, + orchestrationAccess: declaration, + // Streaming methods have no replay hook: the executor never observes a streaming receipt. + handler: checked( + handler, + declaration, + (params: ParsedParams, ctx: RpcContext, emit: (result: unknown) => void) => + handler(params, ctx, emit, checkOrchestrationAccess(access, params, ctx)) + ) + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/access/run-access-rules.ts b/src/main/runtime/rpc/methods/orchestration/access/run-access-rules.ts new file mode 100644 index 00000000000..171dca396e3 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/run-access-rules.ts @@ -0,0 +1,130 @@ +import type { RunRow, TaskRow } from '../../../../orchestration/db/orchestration-records' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { taskNotFoundError } from '../../../../orchestration/coordinator/dispatch/task-dispatch-refusal' +import { resolveRunScope } from '../runs/run-scope' +import { parseOrchestrationTaskDepsFlag } from '../../../../orchestration/coordinator/dispatch/task-deps-flag' +import type { OrchestrationAccessRuleInput } from './orchestration-method-access' + +/** The Run a Run-scoped method acts in, under the one Run-binding rule tasks and gates share. */ +export type RunAccess = { run: RunRow } + +type RunScopedParams = { run?: string } + +function callerRun( + { ctx, caller }: OrchestrationAccessRuleInput, + runId: string | undefined, + requireCurrentConsumer: boolean +): RunRow { + return resolveRunScope(ctx.runtime, { + runId, + callerTerminalHandle: caller, + requireCurrentConsumer, + legacyCoordinatorRunId: ctx.legacyCoordinatorRunId, + callerEvidence: ctx.orchestrationCompatibilityEvidence, + callerSession: ctx.orchestrationCaller + }) +} + +/** The caller must coordinate the Run it names, or be bound to one. */ +export function coordinatedRunAccess( + input: OrchestrationAccessRuleInput +): RunAccess { + return { run: callerRun(input, input.params.run, true) } +} + +/** An explicit Run, legacy included, is inspectable; without one the caller reads its own. */ +export function inspectedRunAccess( + input: OrchestrationAccessRuleInput +): RunAccess { + const { run: runId } = input.params + const explicit = runId ? input.ctx.runtime.getOrchestrationDb().getRun(runId) : undefined + if (explicit?.legacy === 1) { + return { run: explicit } + } + return { run: callerRun(input, runId, runId === undefined) } +} + +/** Malformed --deps is refused before the Run is checked, as before. */ +export function taskCreateAccess( + input: OrchestrationAccessRuleInput +): RunAccess & { deps: string[] | undefined } { + const deps = input.params.deps ? parseOrchestrationTaskDepsFlag(input.params.deps) : undefined + return { ...coordinatedRunAccess(input), deps } +} + +export function taskUpdateAccess( + input: OrchestrationAccessRuleInput +): RunAccess { + const { run } = coordinatedRunAccess(input) + const existing = input.ctx.runtime.getOrchestrationDb().getTask(input.params.id) + if (!existing || existing.run_id !== run.id) { + throw new OrchestrationError( + 'task_not_found', + `Task ${input.params.id} was not found in Run ${run.id}.` + ) + } + return { run } +} + +export function dispatchAccess( + input: OrchestrationAccessRuleInput +): RunAccess & { task: TaskRow } { + const task = input.ctx.runtime.getOrchestrationDb().getTask(input.params.task) + if (!task) { + throw taskNotFoundError(`Task not found: ${input.params.task}`, { taskId: input.params.task }) + } + const { run } = coordinatedRunAccess(input) + if (task.run_id !== run.id) { + throw taskNotFoundError(`Task ${task.id} was not found in Run ${run.id}.`, { + taskId: task.id, + runId: run.id + }) + } + return { run, task } +} + +/** Malformed --options is refused before the Task and Run are checked, as before. */ +export function gateCreateAccess( + input: OrchestrationAccessRuleInput +): RunAccess & { options: string[] | undefined } { + const options = input.params.options ? parseGateOptions(input.params.options) : undefined + const task = input.ctx.runtime.getOrchestrationDb().getTask(input.params.task) + if (!task) { + throw new Error(`Task not found: ${input.params.task}`) + } + const { run } = coordinatedRunAccess(input) + if (task.run_id !== run.id) { + throw taskNotFoundError(`Task ${input.params.task} was not found in Run ${run.id}.`, { + taskId: input.params.task, + runId: run.id + }) + } + return { run, options } +} + +function parseGateOptions(raw: string): string[] { + try { + const parsed: unknown = JSON.parse(raw) + if (!Array.isArray(parsed) || !parsed.every((option) => typeof option === 'string')) { + throw new Error('not an array of strings') + } + return parsed + } catch { + throw new Error('Invalid --options: must be a JSON array of strings') + } +} + +export function gateResolveAccess( + input: OrchestrationAccessRuleInput +): RunAccess { + const existing = input.ctx.runtime.getOrchestrationDb().getGate(input.params.id) + if (!existing) { + throw new Error(`Gate not found: ${input.params.id}`) + } + const { run } = coordinatedRunAccess(input) + // Hide foreign gates as missing so probes cannot map other Runs. + if (existing.run_id !== run.id) { + throw new Error(`Gate not found: ${input.params.id}`) + } + return { run } +} diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index 1b34a65bf3c..9ee58a20e4d 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -18,7 +18,8 @@ import { locateOrchestrationParty } from '../../../orchestration/addressing/orch import { readAgentSessionRecordStore } from '../../../orchestration/addressing/session-lineage/structured-session-lineage' import type { z } from 'zod' import type { OrchestrationDb } from '../../../orchestration/db/orchestration-db' -import { defineMethod, type RpcContext } from '../../core' +import type { RpcContext } from '../../core' +import { defineOrchestrationMethod } from './access/orchestration-method-access' import { openClosedWorkerTerminal } from './worker/closed-worker-terminal' import { ensureStructuredHostInstalled } from '../structured-sessions/creation/structured-agent-session-gate' @@ -64,8 +65,9 @@ function closedWorkerHandle( } export const ORCHESTRATION_CALLER_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.callerShow', + access: { kind: 'reads', targets: {} }, permission: 'workspace', params: null, // Dispatch already admitted the environment's session; do not resolve another caller from params. @@ -84,8 +86,9 @@ export const ORCHESTRATION_CALLER_METHODS = [ }) !== null }) }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.sessionAddress', + access: { kind: 'reads', targets: { sessionId: 'session' } }, permission: 'workspace', params: SessionAddressParams, // Only host records know the chat's /clear root. @@ -101,15 +104,17 @@ export const ORCHESTRATION_CALLER_METHODS = [ return { orcaSessionId: formatOrcaSessionAddress(party.orcaSessionId) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.partyLocation', + access: { kind: 'reads', targets: { address: 'party', messageIds: 'message' } }, permission: 'workspace', params: PartyLocationParams, // Resolve the chat sender's live /clear successor on its owning host. handler: (params, ctx): Promise => locateParty(params, ctx) }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.partyOpen', + access: { kind: 'localOnly', targets: { address: 'party', messageIds: 'message' } }, permission: 'workspace', params: PartyLocationParams, // The lookup, except that a terminal worker Orca closed resumes its conversation in a new terminal. diff --git a/src/main/runtime/rpc/methods/orchestration/crew-methods.ts b/src/main/runtime/rpc/methods/orchestration/crew-methods.ts index 668a838f24d..bb25a26a26a 100644 --- a/src/main/runtime/rpc/methods/orchestration/crew-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/crew-methods.ts @@ -1,11 +1,12 @@ import { CrewSubscribeParams } from '../../../../../shared/orchestration/orchestration-crew' import { subscribeCrew } from '../../../orchestration/crew/crew-stream' -import { defineStreamingMethod } from '../../core' +import { defineOrchestrationStreamingMethod } from './access/orchestration-method-access' let sequence = 0 export const ORCHESTRATION_CREW_METHODS = [ - defineStreamingMethod({ + defineOrchestrationStreamingMethod({ name: 'orchestration.crewSubscribe', + access: { kind: 'localOnly', targets: { party: 'party' } }, permission: 'workspace', params: CrewSubscribeParams, handler: async ({ party }, { runtime, signal, connectionId }, emit) => { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.test.ts index ee64d429046..4c6b8551cb8 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-attach-receipt.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { parseRemoteFederatedWorkerStartReceipt } from './federated-attach-receipt' +import { parseRemoteFederatedWorkerStartReceipt } from '../../../../orchestration/legacy-remote-home/federated-attach-receipt' describe('remote federated worker start receipt', () => { it.each([ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts index f99dbeac8a9..571b6eb881d 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-transport-safety.test.ts @@ -7,10 +7,10 @@ import { OrcaRuntimeService } from '../../../../orca-runtime' import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' -import './federated-worker-read' -import { releaseFederatedWorker } from './federated-worker-release' +import '../../../../orchestration/legacy-remote-home/federated-worker-read' +import { releaseFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-release' import '../worker/worker-observation' -import '../../../../orchestration/federation/synchronization/federation-sync' +import '../../../../orchestration/legacy-remote-home/federation-sync' import { ORCHESTRATION_WORKER_STOP_METHODS } from '../worker/worker-stop' const server = { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-effects.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-effects.test.ts index 6dc7ee03dd3..c6897f7b696 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-effects.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-effects.test.ts @@ -3,7 +3,7 @@ import { appendFederationSetupEffect, appendFederationTerminalEffects, type FederationEffect -} from './federation-effects' +} from '../../../../orchestration/legacy-remote/federation-effects' describe('orchestration federation effects', () => { it('uses exact terminal handles instead of display titles for setup identity', () => { diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts index dcefbdce963..9ffc18d5dd9 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts @@ -12,7 +12,7 @@ import '../../../../orchestration/db/messages/mailbox-routing-page' import '../../../../orchestration/db/dispatch-row-writer' import '../../../../orchestration/db/attempt-outcome-projection' import type { OrchestrationEnvironmentTransport } from '../../../../orchestration/federation/environment-transport' -import '../../../../orchestration/federation/federation-lifecycle-settlement' +import '../../../../orchestration/legacy-remote/federation-lifecycle-settlement' import { RpcDispatcher } from '../../../dispatcher' import { ORCHESTRATION_METHODS } from '../orchestration' import { createFederationWorkerStartRequest as startRequest } from './federation-request.test-support' diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts index 39c02e08332..c0e0e2f50a8 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts @@ -1,6 +1,8 @@ -import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './federation-control' -import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './federation-relay' -import { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './federation' +import { + ORCHESTRATION_FEDERATION_ATTACH_METHODS, + ORCHESTRATION_FEDERATION_CONTROL_METHODS, + ORCHESTRATION_FEDERATION_RELAY_METHODS +} from '../../../../orchestration/legacy-remote/legacy-remote' import { ORCHESTRATION_PEER_MAIL_METHODS } from './peer-mail-methods' export const ORCHESTRATION_FEDERATION_METHODS = [ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-setup.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-setup.test.ts index f89b2d9483d..a69ca2b2740 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-setup.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-setup.test.ts @@ -6,7 +6,7 @@ import '../../../../orchestration/db/messages/mailbox-routing-page' import '../../../../orchestration/db/dispatch-row-writer' import '../../../../orchestration/db/attempt-outcome-projection' import { ORCHESTRATION_METHODS } from '../orchestration' -import { monitorFederatedSetup } from './federation-setup' +import { monitorFederatedSetup } from '../../../../orchestration/legacy-remote/federation-setup' describe('orchestration federated setup evidence', () => { const databases: OrchestrationDb[] = [] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts index da5ac7c2209..6d79a0577dd 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -1,4 +1,5 @@ -import { defineMethod, type RpcContext } from '../../../core' +import type { RpcContext } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { isGeneratedId } from '../../../../orchestration/db/generated-id' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' @@ -48,8 +49,17 @@ function pendingReplies(db: OrchestrationDb, peerFingerprint: string): Federatio } export const ORCHESTRATION_PEER_MAIL_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.peerMailDeliver', + access: { + kind: 'localOnly', + targets: { + conversationId: 'conversation', + messageId: 'message', + to: 'party', + threadId: 'message' + } + }, permission: 'workspace', params: PeerMailDeliverParams, handler: async (params, ctx) => { @@ -134,8 +144,9 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ return { message: { id: params.messageId, to } } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.peerMailPull', + access: { kind: 'localOnly', targets: {} }, permission: 'workspace', params: PeerMailPullParams, handler: async (params, ctx) => { @@ -157,8 +168,9 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.peerMailAck', + access: { kind: 'localOnly', targets: {} }, permission: 'workspace', params: PeerMailAckParams, handler: (params, ctx) => { diff --git a/src/main/runtime/rpc/methods/orchestration/gates/gates.ts b/src/main/runtime/rpc/methods/orchestration/gates/gates.ts index 4a5a866ef93..7f1556a2edc 100644 --- a/src/main/runtime/rpc/methods/orchestration/gates/gates.ts +++ b/src/main/runtime/rpc/methods/orchestration/gates/gates.ts @@ -1,8 +1,7 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { gateCreateAccess, gateResolveAccess, inspectedRunAccess } from '../access/run-access-rules' import type { GateStatus } from '../../../../orchestration/db/orchestration-records' import { Coordinator } from '../../../../orchestration/coordinator/coordinator' -import { resolveRunScope } from '../runs/run-scope' -import { taskNotFoundError } from '../../../../orchestration/coordinator/dispatch/task-dispatch-refusal' import { GateCreateParams, GateListParams, @@ -16,10 +15,11 @@ let activeCoordinator: Coordinator | null = null export const ORCHESTRATION_GATE_METHODS = [ // Return the run id immediately; callers query persisted progress while coordination runs in the background. - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.run', permission: 'workspace', params: RunParams, + access: { kind: 'localOnly', targets: {} }, handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() @@ -56,10 +56,11 @@ export const ORCHESTRATION_GATE_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.runStop', permission: 'workspace', params: RunStopParams, + access: { kind: 'localOnly', targets: {} }, handler: (_params, { runtime }) => { const db = runtime.getOrchestrationDb() const run = db.getActiveCoordinatorRun() @@ -76,45 +77,18 @@ export const ORCHESTRATION_GATE_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.gateCreate', permission: 'workspace', params: GateCreateParams, - handler: ( - params, - { orchestrationCompatibilityEvidence, orchestrationCaller, runtime, legacyCoordinatorRunId } - ) => { + access: { + kind: 'localOnly', + caller: 'from', + targets: { task: 'task', run: 'run' }, + rule: gateCreateAccess + }, + handler: (params, { runtime }, { options }) => { const db = runtime.getOrchestrationDb() - let options: string[] | undefined - if (params.options) { - try { - const parsed = JSON.parse(params.options) - if (!Array.isArray(parsed) || !parsed.every((option) => typeof option === 'string')) { - throw new Error('not an array of strings') - } - options = parsed - } catch { - throw new Error('Invalid --options: must be a JSON array of strings') - } - } - const task = db.getTask(params.task) - if (!task) { - throw new Error(`Task not found: ${params.task}`) - } - const run = resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.from, - requireCurrentConsumer: true, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - if (task.run_id !== run.id) { - throw taskNotFoundError(`Task ${params.task} was not found in Run ${run.id}.`, { - taskId: params.task, - runId: run.id - }) - } const gate = db.createGate({ taskId: params.task, question: params.question, @@ -124,31 +98,18 @@ export const ORCHESTRATION_GATE_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.gateResolve', permission: 'workspace', params: GateResolveParams, - handler: ( - params, - { orchestrationCompatibilityEvidence, orchestrationCaller, runtime, legacyCoordinatorRunId } - ) => { + access: { + kind: 'writes', + caller: 'from', + targets: { id: 'gate', run: 'run' }, + rule: gateResolveAccess + }, + handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() - const existing = db.getGate(params.id) - if (!existing) { - throw new Error(`Gate not found: ${params.id}`) - } - const run = resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.from, - requireCurrentConsumer: true, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - // Hide foreign gates as missing so probes cannot map other Runs. - if (existing.run_id !== run.id) { - throw new Error(`Gate not found: ${params.id}`) - } const gate = db.resolveGate(params.id, params.resolution) if (!gate) { throw new Error(`Gate not found: ${params.id}`) @@ -157,28 +118,20 @@ export const ORCHESTRATION_GATE_METHODS = [ } }), - defineMethod({ + // Match taskList: an explicit Run is inspectable; absence means the caller's own. + defineOrchestrationMethod({ name: 'orchestration.gateList', permission: 'workspace', params: GateListParams, - handler: ( - params, - { orchestrationCompatibilityEvidence, orchestrationCaller, runtime, legacyCoordinatorRunId } - ) => { + access: { + kind: 'reads', + caller: 'from', + targets: { task: 'task', run: 'run' }, + collection: true, + rule: inspectedRunAccess + }, + handler: (params, { runtime }, { run }) => { const db = runtime.getOrchestrationDb() - const explicitRun = params.run ? db.getRun(params.run) : undefined - // Match taskList: an explicit Run is inspectable; absence means the caller's own. - const run = - explicitRun?.legacy === 1 - ? explicitRun - : resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.from, - requireCurrentConsumer: params.run === undefined, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) const gates = db .listGates({ taskId: params.task, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts index 1f0ed7f5783..791ac442381 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts @@ -1,11 +1,11 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { clampOrchestrationAskTimeoutMs } from '../../../../../../shared/orchestration/mailbox/orchestration-ask-timeout' import { isGroupAddress } from '../../../../orchestration/addressing/groups/group-addressing' import { dispatchReportMailbox } from '../../../../orchestration/workers/reports/dispatch-report-mailbox' import { AskParams } from '../../../../../../shared/rpc-contract/orchestration-params' import { rejectFederatedExplicitTarget } from '../routing' -import { askRemoteRunHome } from './ask-remote' +import { askRemoteRunHome } from '../../../../orchestration/legacy-remote/legacy-remote' import { mailboxAddressOf, runCoordinatorKey @@ -21,8 +21,13 @@ import { } from '../../../../orchestration/mailbox/questions/question-answer-delivery' export const ORCHESTRATION_ASK_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.ask', + access: { + kind: 'writes', + caller: 'from', + targets: { to: 'party', resume: 'message', run: 'run' } + }, permission: 'workspace', params: AskParams, handler: async ( diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts index 504e15b9fc2..cc9251aeff5 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' import { parseMessageTypes } from '../routing' @@ -17,8 +17,14 @@ import { } from './dispatch-mailbox-fence' export const ORCHESTRATION_CHECK_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.check', + access: { + kind: 'writes', + caller: 'terminal', + targets: { run: 'run', ack: 'message' }, + collection: true + }, permission: 'workspace', params: CheckParams, handler: async ( diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts index e23fbf55b72..8086a1cb488 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts @@ -13,7 +13,7 @@ import { OrcaRuntimeService } from '../../../../orca-runtime' import { encodeFederatedControlMessage, importFederatedControlMessage -} from '../../../../orchestration/federation/relay/federation-control-message' +} from '../../../../orchestration/legacy-remote/federation-control-message' const DISPATCH_ID = 'ctx_federated_worker_1' const WORKER_HANDLE = 'term_federated_worker' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts index 3e34978d4b1..027c7f424e3 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts @@ -1,10 +1,9 @@ import { ORCHESTRATION_REPLY_METHOD } from './reply-method' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { inspectedRunAccess, taskCreateAccess, taskUpdateAccess } from '../access/run-access-rules' import type { TaskStatus } from '../../../../orchestration/db/orchestration-records' -import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { abbreviateOrchestrationTasks } from '../../../../../../shared/orchestration/orchestration-task-summary' -import { parseOrchestrationTaskDepsFlag } from '../../../../orchestration/coordinator/dispatch/task-deps-flag' -import { orchestrationCallerIdentity, resolveRunScope } from '../runs/run-scope' +import { orchestrationCallerIdentity } from '../runs/run-scope' import { resolveOrchestrationParty } from '../../../../orchestration/addressing/orchestration-party' import { InboxParams, @@ -15,10 +14,11 @@ import { TaskUpdateParams } from './task-update-params' export const ORCHESTRATION_MESSAGE_METHODS = [ ORCHESTRATION_REPLY_METHOD, - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.inbox', permission: 'workspace', params: InboxParams, + access: { kind: 'reads', targets: { terminal: 'party' }, collection: true }, handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() // Return empty for stale/unknown handles because historical mail outlives handle deletion (design doc §3.3). @@ -35,24 +35,18 @@ export const ORCHESTRATION_MESSAGE_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.taskCreate', permission: 'workspace', params: TaskCreateParams, - handler: ( - params, - { orchestrationCompatibilityEvidence, orchestrationCaller, runtime, legacyCoordinatorRunId } - ) => { + access: { + kind: 'writes', + caller: 'callerTerminalHandle', + targets: { run: 'run', parent: 'task', deps: 'task' }, + rule: taskCreateAccess + }, + handler: (params, { orchestrationCaller, runtime }, { run, deps }) => { const db = runtime.getOrchestrationDb() - const deps = params.deps ? parseOrchestrationTaskDepsFlag(params.deps) : undefined - const run = resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.callerTerminalHandle, - requireCurrentConsumer: true, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) // A handle-less session creates root Tasks: Task lineage is recorded by terminal only. const creatorHandle = params.callerTerminalHandle ? orchestrationCallerIdentity(runtime, { @@ -84,27 +78,19 @@ export const ORCHESTRATION_MESSAGE_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.taskList', permission: 'workspace', params: TaskListParams, - handler: ( - params, - { orchestrationCompatibilityEvidence, orchestrationCaller, runtime, legacyCoordinatorRunId } - ) => { + access: { + kind: 'reads', + caller: 'callerTerminalHandle', + targets: { run: 'run' }, + collection: true, + rule: inspectedRunAccess + }, + handler: (params, { runtime }, { run }) => { const db = runtime.getOrchestrationDb() - const explicitRun = params.run ? db.getRun(params.run) : undefined - const run = - explicitRun?.legacy === 1 - ? explicitRun - : resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.callerTerminalHandle, - requireCurrentConsumer: params.run === undefined, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) // Add nullable assignee_handle/dispatch_id without changing legacy non-dispatched rows. const joined = db.listTasksWithDispatch({ status: params.status as TaskStatus, @@ -127,30 +113,18 @@ export const ORCHESTRATION_MESSAGE_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.taskUpdate', permission: 'workspace', params: TaskUpdateParams, - handler: ( - params, - { orchestrationCompatibilityEvidence, orchestrationCaller, runtime, legacyCoordinatorRunId } - ) => { + access: { + kind: 'writes', + caller: 'callerTerminalHandle', + targets: { id: 'task', run: 'run' }, + rule: taskUpdateAccess + }, + handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() - const run = resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.callerTerminalHandle, - requireCurrentConsumer: true, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - const existing = db.getTask(params.id) - if (!existing || existing.run_id !== run.id) { - throw new OrchestrationError( - 'task_not_found', - `Task ${params.id} was not found in Run ${run.id}.` - ) - } const task = db.updateTaskStatus(params.id, params.status, params.result) if (!task) { throw new Error(`Task not found: ${params.id}`) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts index 9001cb57a7d..a9fa69344b3 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts @@ -13,7 +13,6 @@ import { import type { RpcContext } from '../../../core' import { recordReceiptBeforeNudge } from './mutation-replay-nudge' import type { SendParams } from './send-params' -import type { ORCHESTRATION_SEND_METHODS } from './send-methods' const NOTHING_SENT = { effectsApplied: false } as const @@ -108,26 +107,25 @@ export async function sendPeerMail(args: { ) } -/** `orchestration.send` with `on` set goes to the paired server; every other send runs unchanged. */ -export function withPeerMailSend( - methods: typeof ORCHESTRATION_SEND_METHODS -): typeof ORCHESTRATION_SEND_METHODS { - return methods.map((method) => ({ - ...method, - handler: (params: Parameters[0], ctx: RpcContext) => { - const on = params.on - if (on === undefined || ctx.replayedMutationReceipt !== undefined) { - return method.handler(params, ctx) - } - const attested = ctx.orchestrationCompatibilityCallerAuthority - return sendPeerMail({ - params: { ...params, on }, - runtime: ctx.runtime, - orchestrationCaller: ctx.orchestrationCaller, - attestedCaller: attested?.terminalHandle === params.from ? attested : undefined, - orchestrationMutation: ctx.orchestrationMutation, - recordMutationReceipt: ctx.recordMutationReceipt - }) +type SendInput = z.infer + +/** `send --on` goes to the paired server; every other send, and every replay, runs `send`. */ +export function withPeerMailSend( + send: (params: SendInput, ctx: RpcContext) => Promise +): (params: SendInput, ctx: RpcContext) => Promise { + return async (params, ctx) => { + const on = params.on + if (on === undefined || ctx.replayedMutationReceipt !== undefined) { + return await send(params, ctx) } - })) + const attested = ctx.orchestrationCompatibilityCallerAuthority + return await sendPeerMail({ + params: { ...params, on }, + runtime: ctx.runtime, + orchestrationCaller: ctx.orchestrationCaller, + attestedCaller: attested?.terminalHandle === params.from ? attested : undefined, + orchestrationMutation: ctx.orchestrationMutation, + recordMutationReceipt: ctx.recordMutationReceipt + }) + } } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts new file mode 100644 index 00000000000..963250d6044 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-access.ts @@ -0,0 +1,83 @@ +import type { z } from 'zod' +import type { + MessageRow, + QuestionRow, + RunRow +} from '../../../../orchestration/db/orchestration-records' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../../shared/orchestration/orchestration-rpc-contract' +import type { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import { resolveRunScope } from '../runs/run-scope' +import type { OrchestrationAccessRuleInput } from '../access/orchestration-method-access' +import { helperQuestionAnswerer } from './helper-question-answerer' + +/** Who may answer: the helper a question was asked of, the Run's current consumer, or anyone for plain mail. */ +export type ReplyAccess = + | { + kind: 'helper' + original: MessageRow + question: QuestionRow + answerer: { dispatchId: string; consumerGeneration: number } + } + | { kind: 'run'; original: MessageRow; question: QuestionRow; run: RunRow } + | { kind: 'message'; original: MessageRow } + +export function replyAccess({ + params, + ctx, + caller +}: OrchestrationAccessRuleInput>): ReplyAccess { + const { runtime, legacyCoordinatorRunId } = ctx + const db = runtime.getOrchestrationDb() + const original = db.getMessageById(params.id) + if (!original) { + throw new Error(`Message not found: ${params.id}`) + } + if ( + legacyCoordinatorRunId && + (original.run_id !== legacyCoordinatorRunId || + (params.run !== undefined && params.run !== legacyCoordinatorRunId)) + ) { + throw new OrchestrationError( + 'request_mismatch', + `Message ${params.id} does not belong to this adopted Run.`, + { effectsApplied: false } + ) + } + if ( + original.run_id === ORCHESTRATION_LEGACY_RUN_ID || + original.delivery_contract === 'legacy_direct' || + original.delivery_contract === 'audit_only' + ) { + throw new OrchestrationError( + 'legacy_read_only', + 'Legacy orchestration messages are inspect-only; no reply was applied.', + { effectsApplied: false } + ) + } + const question = db.getQuestion(params.id) + if (!question) { + return { kind: 'message', original } + } + const answerer = + params.run === undefined || params.run === question.run_id + ? helperQuestionAnswerer(runtime, { + question: original, + from: caller, + session: ctx.orchestrationCaller, + evidence: ctx.orchestrationCompatibilityEvidence + }) + : undefined + if (answerer) { + return { kind: 'helper', original, question, answerer } + } + const run = resolveRunScope(runtime, { + runId: params.run ?? question.run_id, + callerTerminalHandle: caller, + requireCurrentConsumer: true, + legacyCoordinatorRunId, + callerEvidence: ctx.orchestrationCompatibilityEvidence, + callerSession: ctx.orchestrationCaller + }) + return { kind: 'run', original, question, run } +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts index f0ea51d87e7..94e0996ac2d 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -1,10 +1,9 @@ import { acceptedAnswerSender } from '../../../../orchestration/mailbox/senders/accepted-answer-sender' import { answerSenderRelayReport } from '../../../../orchestration/mailbox/senders/answer-sender-relay-report' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { deliverQuestionAnswer } from '../../../../orchestration/mailbox/questions/question-answer-delivery' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../../shared/orchestration/orchestration-rpc-contract' -import { orchestrationCallerIdentity, resolveRunScope } from '../runs/run-scope' +import { orchestrationCallerIdentity } from '../runs/run-scope' import { readMutationReplayNudge, stripMutationReplayNudge @@ -12,8 +11,8 @@ import { import { exposeMessage } from './mailbox-message-receipt' import { recordReceiptBeforeNudge, replayMutationNudge } from './mutation-replay-nudge' import { resolveReplyRecipient } from './recipient-routing' -import { helperQuestionAnswerer } from './helper-question-answerer' -import { replyToRemoteRunHome } from './reply-remote' +import { replyAccess } from './reply-access' +import { replyToRemoteRunHome } from '../../../../orchestration/legacy-remote/legacy-remote' import { replyOverPeerMail } from './peer-mail-reply' import { withAnswerNext } from '../receipt-next' import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' @@ -23,74 +22,40 @@ import { } from '../../../../orchestration/workers/reports/report-follow-up-action' import { formatFinishedReportReplyRefusal } from '../../../../../../shared/orchestration/mailbox/orchestration-report-follow-up' -export const ORCHESTRATION_REPLY_METHOD = defineMethod({ +export const ORCHESTRATION_REPLY_METHOD = defineOrchestrationMethod({ name: 'orchestration.reply', permission: 'workspace', params: ReplyParams, + access: { + kind: 'writes', + caller: 'from', + targets: { id: 'message', run: 'run' }, + rule: replyAccess + }, + replay: (_params, { runtime, replayedMutationReceipt }) => { + const nudge = readMutationReplayNudge(replayedMutationReceipt) + if (!nudge) { + return undefined + } + replayMutationNudge(runtime, nudge) + return { receipt: stripMutationReplayNudge(replayedMutationReceipt) } + }, handler: async ( params, - { - orchestrationCompatibilityEvidence, - orchestrationCaller, - runtime, - legacyCoordinatorRunId, - recordMutationReceipt, - replayedMutationReceipt, - orchestrationMutation, - signal - } + { orchestrationCaller, runtime, recordMutationReceipt, orchestrationMutation, signal }, + access ) => { - const replayNudge = readMutationReplayNudge(replayedMutationReceipt) - if (replayNudge) { - replayMutationNudge(runtime, replayNudge) - return stripMutationReplayNudge(replayedMutationReceipt) - } const db = runtime.getOrchestrationDb() - const original = db.getMessageById(params.id) - if (!original) { - throw new Error(`Message not found: ${params.id}`) - } - if ( - legacyCoordinatorRunId && - (original.run_id !== legacyCoordinatorRunId || - (params.run !== undefined && params.run !== legacyCoordinatorRunId)) - ) { - throw new OrchestrationError( - 'request_mismatch', - `Message ${params.id} does not belong to this adopted Run.`, - { effectsApplied: false } - ) - } - if ( - original.run_id === ORCHESTRATION_LEGACY_RUN_ID || - original.delivery_contract === 'legacy_direct' || - original.delivery_contract === 'audit_only' - ) { - throw new OrchestrationError( - 'legacy_read_only', - 'Legacy orchestration messages are inspect-only; no reply was applied.', - { effectsApplied: false } - ) - } - - const question = db.getQuestion(params.id) - const creatorAnswerer = - question && (params.run === undefined || params.run === question.run_id) - ? helperQuestionAnswerer(runtime, { - question: original, - from: params.from, - session: orchestrationCaller, - evidence: orchestrationCompatibilityEvidence - }) - : undefined - if (question && creatorAnswerer) { + const { original } = access + if (access.kind === 'helper') { + const { question, answerer } = access const answered = db.answerQuestion({ messageId: question.message_id, runId: question.run_id, - answeredBy: creatorAnswerer, + answeredBy: answerer, captureSender: acceptedAnswerSender( runtime, - `dispatch:${creatorAnswerer.dispatchId}`, + `dispatch:${answerer.dispatchId}`, orchestrationCallerIdentity(runtime, { handle: params.from ?? '', session: orchestrationCaller, @@ -105,15 +70,8 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ () => deliverQuestionAnswer(runtime, question) ) } - if (question) { - const run = resolveRunScope(runtime, { - runId: params.run ?? question.run_id, - callerTerminalHandle: params.from, - requireCurrentConsumer: true, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) + if (access.kind === 'run') { + const { question, run } = access const answered = db.answerQuestion({ messageId: question.message_id, runId: run.id, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index 4c40eac6996..1d9c485e919 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { isGroupAddress } from '../../../../orchestration/addressing/groups/group-addressing' import { @@ -16,18 +16,13 @@ import { resolveRunBoundDispatchRecipient, type SendRecipientWarning } from './recipient-routing' -import { - readMutationReplayNudge, - readWorkerDoneReplayNudge, - stripMutationReplayNudge -} from '../../../orchestration-mutation-receipt' -import { replayMutationNudge } from './mutation-replay-nudge' -import { handBackReplayTargets } from '../../../../orchestration/db/messages/helper-mailbox-hand-back' -import { sendRemoteMessage } from './send-remote' +import { replayAcceptedSend } from './send-replay' +import { sendRemoteMessage } from '../../../../orchestration/legacy-remote/legacy-remote' +import { withPeerMailSend } from './peer-mail-send' import { mayNameSession } from './session-recipient' import { sendPointToPointMessage } from './send-point-to-point' import { sendGroupMessage } from './send-group' -import { sendFederatedControlMail } from './send-control-mail' +import { sendFederatedControlMail } from '../../../../orchestration/legacy-remote-home/legacy-remote-home' import { orchestrationCallerIdentity } from '../runs/run-scope' import { assertLifecycleCallerIsNotAnotherParty } from './lifecycle-caller-fence' import { planWorkerFollowUp, startWorkerFollowUp } from './worker-follow-up' @@ -38,273 +33,261 @@ import { settledDispatchId } from './settled-worker-follow-through' -// `send --on ` is carried by withPeerMailSend (peer-mail-send.ts) before this handler runs. export const ORCHESTRATION_SEND_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.send', + access: { + kind: 'writes', + caller: 'from', + targets: { to: 'party', threadId: 'message', run: 'run', payload: 'dispatch' } + }, permission: 'workspace', params: SendParams, - handler: async ( - params, - { - runtime, - legacyCoordinatorRunId, - revalidateLegacyCoordinator, - orchestrationCompatibilityCallerAuthority, - recordMutationReceipt, - markWorkerDoneMutationEffectFree, - replayedMutationReceipt, - orchestrationCaller, - orchestrationCompatibilityEvidence, - orchestrationMutation, - signal - } - ) => { - const db = runtime.getOrchestrationDb() - const legacyReplayNudge = readWorkerDoneReplayNudge( - 'orchestration.send', + replay: (params, { runtime, replayedMutationReceipt }) => + replayAcceptedSend(runtime, params, replayedMutationReceipt), + handler: withPeerMailSend( + async ( params, - replayedMutationReceipt - ) - const replayNudge = - readMutationReplayNudge(replayedMutationReceipt) ?? - (legacyReplayNudge - ? { kind: 'messages' as const, targets: [legacyReplayNudge] } - : undefined) - if (replayNudge) { - replayMutationNudge(runtime, replayNudge) - const settled = - params.type === 'worker_done' ? settledDispatchId(replayedMutationReceipt) : undefined - // Why: derived, since the executor's receipt rewrites drop stored hand-back targets. - for (const target of settled ? handBackReplayTargets(db, settled) : []) { - runtime.notifyMessageArrived(target.to, target.type) - } - followThroughWorkerReport(runtime, db, settled) - return stripMutationReplayNudge(replayedMutationReceipt) - } - const from = params.from ?? 'unknown' - const attestedCaller = - orchestrationCompatibilityCallerAuthority?.terminalHandle === from - ? orchestrationCompatibilityCallerAuthority - : undefined - // Why: attested hook identity survives graph remount; caller params never supply lifecycle authority. - const sender = orchestrationCallerIdentity(runtime, { - handle: from, - session: orchestrationCaller, - paneKey: attestedCaller?.paneKey ?? runtime.getTerminalPaneKey(from) - }) - const senderPaneKey = sender.paneKey ?? undefined - // Why: a session caller was already bound to its own identity at the dispatch entry. - if (isDispatchMutationMessageType(params.type) && !orchestrationCaller) { - assertLifecycleCallerIsNotAnotherParty(runtime, { - from, - fromPaneKey: senderPaneKey, - evidence: orchestrationCompatibilityEvidence - }) - } - const processIncarnation = () => - attestedCaller?.processIncarnation ?? - runtime.getTerminalProcessIncarnation(from) ?? - undefined - const remoteAttachment = senderPaneKey - ? db.findActiveRemoteAttachmentForPane(senderPaneKey) - : undefined - if (remoteAttachment && senderPaneKey) { - return sendRemoteMessage({ - params, + { runtime, - db, - from, - senderPaneKey, - remoteAttachment, - processIncarnation: processIncarnation(), + legacyCoordinatorRunId, + revalidateLegacyCoordinator, + orchestrationCompatibilityCallerAuthority, + recordMutationReceipt, + markWorkerDoneMutationEffectFree, + orchestrationCaller, + orchestrationCompatibilityEvidence, + orchestrationMutation, signal - }) - } - - refuseFinishedRemoteWorker(db, senderPaneKey, params.to) - const runGroup = - params.to && isGroupAddress(params.to) && !params.to.toLowerCase().startsWith('@worktree:') - // Run groups validate their own audience; message scope cannot select a parent Dispatch. - let routing = resolveMessageRun(runtime, { - sender, - to: params.to, - runId: runGroup ? undefined : params.run, - payload: runGroup ? undefined : params.payload, - type: params.type - }) - const finished = runGroup - ? undefined - : finishedWorkerSend(db, { ...sender, processIncarnation }, routing, params) - ;({ params, routing } = finished ?? { params, routing }) - if ( - params.type === 'worker_done' && - !isWorkerReportOutcome(parseRemoteWorkerPayload(params.payload).outcome) - ) { - throw new OrchestrationError( - 'invalid_argument', - 'worker_done requires outcome=succeeded|failed for a current Dispatch.' - ) - } - if (params.to?.startsWith('task:')) { - throw new OrchestrationError( - 'invalid_argument', - 'Task recipients are intentionally unsupported; use run: or dispatch:.' - ) - } - - let to = params.to - if ( - routing.run && - (!to || - ((params.type === 'worker_done' || params.type === 'heartbeat') && routing.dispatchId)) - ) { - const reporting = - routing.dispatchId && isDispatchReportType(params.type) - ? db.getDispatchContextById(routing.dispatchId) + } + ) => { + const db = runtime.getOrchestrationDb() + const from = params.from ?? 'unknown' + const attestedCaller = + orchestrationCompatibilityCallerAuthority?.terminalHandle === from + ? orchestrationCompatibilityCallerAuthority : undefined - to = reporting ? dispatchReportMailbox(db, reporting) : `run:${routing.run.id}` - } - if (!to) { - throw new OrchestrationError( - 'run_required', - 'No recipient or active Dispatch Run could be resolved. No effects were applied.', - orchestrationSkillRecoveryData() - ) - } - - const sendWarnings: SendRecipientWarning[] = [] - let messageRunId = routing.run?.id - if (!isGroupAddress(to) && !to.startsWith('run:') && !to.startsWith('dispatch:')) { - if (mayNameSession(to)) { - // Recipient routing reads the session record store, which the host opens lazily. - await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) - } - const recipient = resolveBareOrchestrationRecipient({ - runtime, - db, - handle: to, - senderRunId: routing.run?.id, - explicitRunId: params.run + // Why: attested hook identity survives graph remount; caller params never supply lifecycle authority. + const sender = orchestrationCallerIdentity(runtime, { + handle: from, + session: orchestrationCaller, + paneKey: attestedCaller?.paneKey ?? runtime.getTerminalPaneKey(from) }) - if (!recipient.ok) { - throw new OrchestrationError(recipient.code, recipient.message) + const senderPaneKey = sender.paneKey ?? undefined + // Why: a session caller was already bound to its own identity at the dispatch entry. + if (isDispatchMutationMessageType(params.type) && !orchestrationCaller) { + assertLifecycleCallerIsNotAnotherParty(runtime, { + from, + fromPaneKey: senderPaneKey, + evidence: orchestrationCompatibilityEvidence + }) } - to = recipient.to - messageRunId = recipient.runId - if (recipient.warning) { - sendWarnings.push(recipient.warning) - } - } - const withSendWarnings = ( - receipt: T - ): T & { warnings?: SendRecipientWarning[] } => - sendWarnings.length > 0 ? { ...receipt, warnings: sendWarnings } : receipt - - if (!isGroupAddress(to)) { - let addressedDispatchId = to.startsWith('dispatch:') - ? to.slice('dispatch:'.length) + const processIncarnation = () => + attestedCaller?.processIncarnation ?? + runtime.getTerminalProcessIncarnation(from) ?? + undefined + const remoteAttachment = senderPaneKey + ? db.findActiveRemoteAttachmentForPane(senderPaneKey) : undefined - const federatedTarget = - addressedDispatchId && to === `dispatch:${addressedDispatchId}` - ? db.getFederatedDispatch(addressedDispatchId) - : undefined - // Federated targets perform their own liveness check before relaying. - if (addressedDispatchId && !federatedTarget) { - const plan = planWorkerFollowUp(db, addressedDispatchId, params.type ?? 'status') - // Only a settled worker awaits; mail to a working one stays synchronous until it is inserted. - const followUp = - plan?.kind === 'start' - ? await startWorkerFollowUp({ - ctx: { - runtime, - orchestrationCompatibilityEvidence, - orchestrationCaller, - orchestrationMutation - }, - db, - plan, - from, - message: params - }) - : plan - // A dispatch: address carries no recipient warnings, so `next` stays last. - if (followUp?.kind === 'started') { - if (typeof followUp.receipt.dispatchId === 'string') { - passHeldWorkerMail(runtime, db, followUp.receipt.dispatchId) - } - return followUp.receipt - } - if (followUp) { - addressedDispatchId = followUp.dispatchId - to = `dispatch:${addressedDispatchId}` - } - assertDispatchMailboxDeliverable(runtime, db, addressedDispatchId) - const runBound = resolveRunBoundDispatchRecipient( + if (remoteAttachment && senderPaneKey) { + return sendRemoteMessage({ + params, runtime, db, - addressedDispatchId, - params.run + from, + senderPaneKey, + remoteAttachment, + processIncarnation: processIncarnation(), + signal + }) + } + + refuseFinishedRemoteWorker(db, senderPaneKey, params.to) + const runGroup = + params.to && + isGroupAddress(params.to) && + !params.to.toLowerCase().startsWith('@worktree:') + // Run groups validate their own audience; message scope cannot select a parent Dispatch. + let routing = resolveMessageRun(runtime, { + sender, + to: params.to, + runId: runGroup ? undefined : params.run, + payload: runGroup ? undefined : params.payload, + type: params.type + }) + const finished = runGroup + ? undefined + : finishedWorkerSend(db, { ...sender, processIncarnation }, routing, params) + ;({ params, routing } = finished ?? { params, routing }) + if ( + params.type === 'worker_done' && + !isWorkerReportOutcome(parseRemoteWorkerPayload(params.payload).outcome) + ) { + throw new OrchestrationError( + 'invalid_argument', + 'worker_done requires outcome=succeeded|failed for a current Dispatch.' ) - if (runBound) { - to = runBound.to - messageRunId = runBound.runId - sendWarnings.push(runBound.warning) + } + if (params.to?.startsWith('task:')) { + throw new OrchestrationError( + 'invalid_argument', + 'Task recipients are intentionally unsupported; use run: or dispatch:.' + ) + } + + let to = params.to + if ( + routing.run && + (!to || + ((params.type === 'worker_done' || params.type === 'heartbeat') && routing.dispatchId)) + ) { + const reporting = + routing.dispatchId && isDispatchReportType(params.type) + ? db.getDispatchContextById(routing.dispatchId) + : undefined + to = reporting ? dispatchReportMailbox(db, reporting) : `run:${routing.run.id}` + } + if (!to) { + throw new OrchestrationError( + 'run_required', + 'No recipient or active Dispatch Run could be resolved. No effects were applied.', + orchestrationSkillRecoveryData() + ) + } + + const sendWarnings: SendRecipientWarning[] = [] + let messageRunId = routing.run?.id + if (!isGroupAddress(to) && !to.startsWith('run:') && !to.startsWith('dispatch:')) { + if (mayNameSession(to)) { + // Recipient routing reads the session record store, which the host opens lazily. + await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + } + const recipient = resolveBareOrchestrationRecipient({ + runtime, + db, + handle: to, + senderRunId: routing.run?.id, + explicitRunId: params.run + }) + if (!recipient.ok) { + throw new OrchestrationError(recipient.code, recipient.message) + } + to = recipient.to + messageRunId = recipient.runId + if (recipient.warning) { + sendWarnings.push(recipient.warning) } } - const federatedControl = sendFederatedControlMail({ + const withSendWarnings = ( + receipt: T + ): T & { warnings?: SendRecipientWarning[] } => + sendWarnings.length > 0 ? { ...receipt, warnings: sendWarnings } : receipt + + if (!isGroupAddress(to)) { + let addressedDispatchId = to.startsWith('dispatch:') + ? to.slice('dispatch:'.length) + : undefined + const federatedTarget = + addressedDispatchId && to === `dispatch:${addressedDispatchId}` + ? db.getFederatedDispatch(addressedDispatchId) + : undefined + // Federated targets perform their own liveness check before relaying. + if (addressedDispatchId && !federatedTarget) { + const plan = planWorkerFollowUp(db, addressedDispatchId, params.type ?? 'status') + // Only a settled worker awaits; mail to a working one stays synchronous until it is inserted. + const followUp = + plan?.kind === 'start' + ? await startWorkerFollowUp({ + ctx: { + runtime, + orchestrationCompatibilityEvidence, + orchestrationCaller, + orchestrationMutation + }, + db, + plan, + from, + message: params + }) + : plan + // A dispatch: address carries no recipient warnings, so `next` stays last. + if (followUp?.kind === 'started') { + if (typeof followUp.receipt.dispatchId === 'string') { + passHeldWorkerMail(runtime, db, followUp.receipt.dispatchId) + } + return followUp.receipt + } + if (followUp) { + addressedDispatchId = followUp.dispatchId + to = `dispatch:${addressedDispatchId}` + } + assertDispatchMailboxDeliverable(runtime, db, addressedDispatchId) + const runBound = resolveRunBoundDispatchRecipient( + runtime, + db, + addressedDispatchId, + params.run + ) + if (runBound) { + to = runBound.to + messageRunId = runBound.runId + sendWarnings.push(runBound.warning) + } + } + const federatedControl = sendFederatedControlMail({ + params, + runtime, + db, + from, + to, + messageRunId, + revalidateLegacyCoordinator, + recordMutationReceipt, + withSendWarnings + }) + if (federatedControl !== undefined) { + return federatedControl + } + const sent = sendPointToPointMessage({ + params, + runtime, + db, + from, + to, + dispatchId: routing.dispatchId, + messageRunId, + senderPaneKey, + legacyCoordinatorRunId, + resolveProcessIncarnation: processIncarnation, + revalidateLegacyCoordinator, + recordMutationReceipt, + markWorkerDoneMutationEffectFree, + withSendWarnings: (sent) => + finished?.receipt(withSendWarnings(sent)) ?? withSendWarnings(sent) + }) + followThroughWorkerReport( + runtime, + db, + params.type === 'worker_done' ? settledDispatchId(sent) : undefined + ) + return sent + } + return sendGroupMessage({ params, runtime, db, from, - to, - messageRunId, + groupAddress: to, + sender, + senderPaneKey, + senderRunId: routing.run?.id, + explicitRunId: params.run, + legacyCoordinatorRunId, revalidateLegacyCoordinator, recordMutationReceipt, withSendWarnings }) - if (federatedControl !== undefined) { - return federatedControl - } - const sent = sendPointToPointMessage({ - params, - runtime, - db, - from, - to, - dispatchId: routing.dispatchId, - messageRunId, - senderPaneKey, - legacyCoordinatorRunId, - resolveProcessIncarnation: processIncarnation, - revalidateLegacyCoordinator, - recordMutationReceipt, - markWorkerDoneMutationEffectFree, - withSendWarnings: (sent) => - finished?.receipt(withSendWarnings(sent)) ?? withSendWarnings(sent) - }) - followThroughWorkerReport( - runtime, - db, - params.type === 'worker_done' ? settledDispatchId(sent) : undefined - ) - return sent } - return sendGroupMessage({ - params, - runtime, - db, - from, - groupAddress: to, - sender, - senderPaneKey, - senderRunId: routing.run?.id, - explicitRunId: params.run, - legacyCoordinatorRunId, - revalidateLegacyCoordinator, - recordMutationReceipt, - withSendWarnings - }) - } + ) }) ] diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts new file mode 100644 index 00000000000..8d471f1ef85 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-replay.ts @@ -0,0 +1,40 @@ +import type { z } from 'zod' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import { handBackReplayTargets } from '../../../../orchestration/db/messages/helper-mailbox-hand-back' +import { + readMutationReplayNudge, + readWorkerDoneReplayNudge, + stripMutationReplayNudge +} from '../../../orchestration-mutation-receipt' +import { replayMutationNudge } from './mutation-replay-nudge' +import type { SendParams } from './send-params' +import { followThroughWorkerReport, settledDispatchId } from './settled-worker-follow-through' + +/** An accepted send's replay redelivers its nudge and follow-through; undefined when it carries none. */ +export function replayAcceptedSend( + runtime: OrcaRuntimeService, + params: z.infer, + replayedMutationReceipt: unknown +): { receipt: unknown } | undefined { + const legacyReplayNudge = readWorkerDoneReplayNudge( + 'orchestration.send', + params, + replayedMutationReceipt + ) + const replayNudge = + readMutationReplayNudge(replayedMutationReceipt) ?? + (legacyReplayNudge ? { kind: 'messages' as const, targets: [legacyReplayNudge] } : undefined) + if (!replayNudge) { + return undefined + } + const db = runtime.getOrchestrationDb() + replayMutationNudge(runtime, replayNudge) + const settled = + params.type === 'worker_done' ? settledDispatchId(replayedMutationReceipt) : undefined + // Why: derived, since the executor's receipt rewrites drop stored hand-back targets. + for (const target of settled ? handBackReplayTargets(db, settled) : []) { + runtime.notifyMessageArrived(target.to, target.type) + } + followThroughWorkerReport(runtime, db, settled) + return { receipt: stripMutationReplayNudge(replayedMutationReceipt) } +} diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration.ts b/src/main/runtime/rpc/methods/orchestration/orchestration.ts index a9d551e8555..377058c7526 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration.ts @@ -5,7 +5,6 @@ import { ORCHESTRATION_WORKER_METHODS } from './worker/worker-methods' import { ORCHESTRATION_FEDERATION_METHODS } from './federation/federation-methods' import { ORCHESTRATION_MUTATION_REQUEST_METHODS } from './runs/mutation-request-show' import { ORCHESTRATION_SEND_METHODS } from './messaging/send-methods' -import { withPeerMailSend } from './messaging/peer-mail-send' import { ORCHESTRATION_CHECK_METHODS } from './messaging/check-methods' import { ORCHESTRATION_MESSAGE_METHODS } from './messaging/message-methods' import { ORCHESTRATION_DISPATCH_METHODS } from './runs/dispatch-methods' @@ -13,6 +12,7 @@ import { ORCHESTRATION_ASK_METHODS } from './messaging/ask-methods' import { ORCHESTRATION_GATE_METHODS } from './gates/gates' import { ORCHESTRATION_RESET_METHODS } from './runs/reset-methods' import { ORCHESTRATION_CALLER_METHODS } from './caller-show' +import type { OrchestrationMethodAccessDeclaration } from './access/orchestration-method-access' // Every orchestration method reads the authority restored at startup. export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ @@ -21,7 +21,7 @@ export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ ...ORCHESTRATION_WORKER_METHODS, ...ORCHESTRATION_FEDERATION_METHODS, ...ORCHESTRATION_MUTATION_REQUEST_METHODS, - ...withPeerMailSend(ORCHESTRATION_SEND_METHODS), + ...ORCHESTRATION_SEND_METHODS, ...ORCHESTRATION_CHECK_METHODS, ...ORCHESTRATION_MESSAGE_METHODS, ...ORCHESTRATION_DISPATCH_METHODS, @@ -29,4 +29,4 @@ export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ ...ORCHESTRATION_GATE_METHODS, ...ORCHESTRATION_RESET_METHODS, ...ORCHESTRATION_CALLER_METHODS -]) +] satisfies readonly { readonly orchestrationAccess: OrchestrationMethodAccessDeclaration }[]) diff --git a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts index 30c7dbc827d..0910402a660 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts @@ -1,14 +1,13 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { dispatchAccess } from '../access/run-access-rules' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { buildDispatchPreamble } from '../../../../orchestration/workers/launch/worker-dispatch-preamble' import { sendAgentTurn } from '../../../../orchestration/turn-delivery/send-agent-turn' import { resolveDispatchCreator } from './dispatch-creator' import { injectRejectedError, - taskNotFoundError, taskNotStartableError } from '../../../../orchestration/coordinator/dispatch/task-dispatch-refusal' -import { resolveRunScope } from './run-scope' import { DispatchParams, DispatchShowParams @@ -26,40 +25,22 @@ import { sendChatTask } from '../chat-task-delivery' import { dispatchTaskSource } from '../../../../orchestration/coordinator/dispatch/dispatch-task-source' export const ORCHESTRATION_DISPATCH_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.dispatch', permission: 'workspace', params: DispatchParams, + access: { + kind: 'writes', + caller: 'from', + targets: { task: 'task', to: 'party', run: 'run' }, + rule: dispatchAccess + }, handler: async ( params, - { - orchestrationCompatibilityEvidence, - orchestrationCaller, - runtime, - legacyCoordinatorRunId, - revalidateLegacyCoordinator, - orchestrationMutation - } + { orchestrationCaller, runtime, revalidateLegacyCoordinator, orchestrationMutation }, + { task } ) => { const db = runtime.getOrchestrationDb() - const task = db.getTask(params.task) - if (!task) { - throw taskNotFoundError(`Task not found: ${params.task}`, { taskId: params.task }) - } - const run = resolveRunScope(runtime, { - runId: params.run, - callerTerminalHandle: params.from, - requireCurrentConsumer: true, - legacyCoordinatorRunId, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - if (task.run_id !== run.id) { - throw taskNotFoundError(`Task ${task.id} was not found in Run ${run.id}.`, { - taskId: task.id, - runId: run.id - }) - } const assigneeParty = params.to ? resolveDispatchAssigneeParty(params.to, db) : undefined const assignee = assigneeParty?.address // A chat has no pane, process or agent to probe: it is reached as mail to it is. @@ -226,10 +207,11 @@ export const ORCHESTRATION_DISPATCH_METHODS = [ } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.dispatchShow', permission: 'workspace', params: DispatchShowParams, + access: { kind: 'reads', targets: { task: 'task' } }, handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() if (!params.task) { diff --git a/src/main/runtime/rpc/methods/orchestration/runs/migration-behavior.test.ts b/src/main/runtime/rpc/methods/orchestration/runs/migration-behavior.test.ts index e8508c3ccdd..36b7801b97f 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/migration-behavior.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/migration-behavior.test.ts @@ -13,7 +13,7 @@ import '../../../../orchestration/db/attempt-outcome-projection' import { RpcDispatcher } from '../../../dispatcher' import { ORCHESTRATION_METHODS } from '../orchestration' -import { startFederatedWorker } from '../federation/federated-worker-start' +import { startFederatedWorker } from '../../../../orchestration/legacy-remote-home/federated-worker-start' import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' describe('orchestration migration behavior', () => { diff --git a/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts b/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts index 2e1d1f82804..f36db68f630 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts @@ -2,12 +2,13 @@ import { describeMutationRequestState, type OrchestrationMutationRequestShowResult } from '../../../../../../shared/orchestration/orchestration-mutation-request' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { RequestShowParams } from '../../../../../../shared/rpc-contract/orchestration-runs-mutation-request-show-params' export const ORCHESTRATION_MUTATION_REQUEST_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.requestShow', + access: { kind: 'reads', targets: { request: 'request' } }, permission: 'workspace', params: RequestShowParams, // Read durable receipts without writing/mutating again; keep this recovery query outside ORCHESTRATION_MUTATION_METHODS. diff --git a/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts b/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts index 7f2ebcb935c..5adb7bf5959 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts @@ -1,9 +1,10 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { ResetParams } from '../../../../../../shared/rpc-contract/orchestration-params' export const ORCHESTRATION_RESET_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.reset', + access: { kind: 'localOnly', targets: {} }, permission: 'workspace', params: ResetParams, handler: (params, { runtime }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts index 63c33e22b44..12289a6b700 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts @@ -1,4 +1,4 @@ -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { readRunRemovedWork } from '../../../../orchestration/db/reset/removed-orchestration-work-read' import { boundRunWorkerNext } from '../../../../orchestration/db/runs/worker-run-binding' @@ -48,8 +48,9 @@ export function createBoundRun( } export const ORCHESTRATION_RUN_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.runCreate', + access: { kind: 'localOnly', caller: 'from', targets: {} }, permission: 'workspace', params: RunCreateParams, handler: (params, { orchestrationCompatibilityEvidence, orchestrationCaller, runtime }) => { @@ -62,8 +63,9 @@ export const ORCHESTRATION_RUN_METHODS = [ return { run: exposeRun(createBoundRun(runtime, caller, params.from, params.objective)) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.runUse', + access: { kind: 'localOnly', caller: 'from', targets: { id: 'run' } }, permission: 'workspace', params: RunUseParams, handler: ( @@ -128,8 +130,9 @@ export const ORCHESTRATION_RUN_METHODS = [ return { run: exposeRun(run) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.runCurrent', + access: { kind: 'reads', caller: 'from', targets: {} }, permission: 'workspace', params: RunCurrentParams, handler: (params, { orchestrationCompatibilityEvidence, orchestrationCaller, runtime }) => { @@ -148,8 +151,9 @@ export const ORCHESTRATION_RUN_METHODS = [ return { run: exposeRun(run), ...(next ? { next } : {}) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.runList', + access: { kind: 'reads', targets: {}, collection: true }, permission: 'workspace', params: RunListParams, handler: (params, { runtime }) => { @@ -157,8 +161,9 @@ export const ORCHESTRATION_RUN_METHODS = [ return { ...listed, runs: listed.runs.map(exposeRun) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.runShow', + access: { kind: 'reads', targets: { id: 'run' } }, permission: 'workspace', params: RunShowParams, handler: (params, { runtime }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts index ee8849d323d..91e9c55d3b3 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts @@ -1,7 +1,7 @@ import { exposeDispatchContext } from './dispatch-context-exposure' import { contextOnlyAbandonWarning } from '../../../../orchestration/workers/lifecycle/context-only-dispatch-release' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { exposeObservation, exposeWorker, @@ -17,16 +17,19 @@ import { sessionIdFromStructuredWorkerIncarnation } from '../../../../orchestrat import { readExactWorkerOutput } from './worker-output' import { exposeWorkerTerminalResource } from './worker-terminal-resource-presentation' import { liveWorkerTerminalAutoReleaseAt } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' -import { readFederatedWorkerOutput } from '../federation/federated-worker-read' -import { showFederatedWorker } from '../federation/federated-worker-show' +import { + readFederatedWorkerOutput, + showFederatedWorker +} from '../../../../orchestration/legacy-remote-home/legacy-remote-home' import { WorkerDispatchParams, WorkerReadParams } from '../../../../../../shared/rpc-contract/orchestration-worker-control-params' export const ORCHESTRATION_WORKER_CONTROL_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerShow', + access: { kind: 'reads', targets: { dispatch: 'dispatch' } }, permission: 'workspace', params: WorkerDispatchParams, handler: async (params, { runtime }) => { @@ -80,8 +83,9 @@ export const ORCHESTRATION_WORKER_CONTROL_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerRead', + access: { kind: 'reads', targets: { dispatch: 'dispatch' } }, permission: 'workspace', params: WorkerReadParams, handler: async (params, { runtime }) => { @@ -199,8 +203,9 @@ export const ORCHESTRATION_WORKER_CONTROL_METHODS = [ return { ...output, projection: projectFleetWorker(runtime, db, params.dispatch) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerAbandon', + access: { kind: 'writes', targets: { dispatch: 'dispatch' } }, permission: 'workspace', params: WorkerDispatchParams, handler: (params, { runtime, orchestrationCaller, orchestrationCompatibilityEvidence }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts index d2460b26e7a..8d5f269f1eb 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-keep-open.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-runtime' import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records' @@ -12,8 +12,12 @@ import { } from '../../../../../../shared/rpc-contract/orchestration-worker-release-params' export const ORCHESTRATION_WORKER_KEEP_OPEN_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerAutoClose', + access: { + kind: 'reads', + targets: { paneKey: 'worker', sessionId: 'worker', terminal: 'worker' } + }, permission: 'workspace', params: OrchestrationWorkerSubjectParams, handler: (params, { runtime }) => { @@ -23,8 +27,12 @@ export const ORCHESTRATION_WORKER_KEEP_OPEN_METHODS = [ } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerKeepOpen', + access: { + kind: 'writes', + targets: { paneKey: 'worker', sessionId: 'worker', terminal: 'worker' } + }, permission: 'workspace', params: OrchestrationWorkerKeepOpenParams, handler: (params, { runtime }) => { @@ -43,15 +51,23 @@ export const ORCHESTRATION_WORKER_KEEP_OPEN_METHODS = [ return { autoClose: db.getWorkerAutoCloseState(paneKey) } } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerTerminalUserInput', + access: { + kind: 'writes', + targets: { paneKey: 'worker', sessionId: 'worker', terminal: 'worker' } + }, permission: 'workspace', params: OrchestrationWorkerSubjectParams, // Older clients still report typing; only Keep open keeps a worker now, so this records nothing. handler: () => ({ changed: 0 }) }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerChatTouch', + access: { + kind: 'writes', + targets: { paneKey: 'worker', sessionId: 'worker', terminal: 'worker' } + }, permission: 'workspace', params: OrchestrationWorkerSubjectParams, // Older clients still report viewing; answered like typing, without `pending`, so they stop retrying. diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts index efc7c57fc62..b506a17124f 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts @@ -4,7 +4,7 @@ import type { OrchestrationDb } from '../../../../orchestration/db/orchestration import { WORKER_LIST_CURSOR_EXPIRED_MESSAGE } from '../../../../orchestration/db/worker-terminal/worker-terminal-listing' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { decodeWorkerListCursor, encodeWorkerListCursor, @@ -29,8 +29,9 @@ const emptyWorkerListPage = (limit: number) => ({ page: { limit, total: 0, hasMore: false, nextCursor: null } }) -export const ORCHESTRATION_WORKER_LIST_METHOD = defineMethod({ +export const ORCHESTRATION_WORKER_LIST_METHOD = defineOrchestrationMethod({ name: 'orchestration.workerList', + access: { kind: 'reads', targets: { run: 'run' }, collection: true }, permission: 'workspace', params: WorkerListParams, handler: async (params, { runtime }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts index 7ec92f45a9d..df87127d9ca 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts @@ -14,7 +14,7 @@ import { createSessionWorkerLivenessReader } from '../../../../orchestration/wor import { applyFederatedFleetObservations, readFederatedFleetSnapshots -} from '../federation/federated-fleet-snapshot' +} from '../../../../orchestration/legacy-remote-home/federated-fleet-snapshot' import { ensureSessionWorkerRecords } from './session-worker-observation' export type WorkerListPageParams = { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts index d71b7813645..309748d4017 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts @@ -1,9 +1,9 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { releaseFederatedWorker, retainFederatedWorker -} from '../federation/federated-worker-release' +} from '../../../../orchestration/legacy-remote-home/legacy-remote-home' import { ORCHESTRATION_WORKER_LIST_METHOD } from './worker-list-method' import { resolvePinnedFederatedServer } from './worker-observation' import { archiveSummary, exposeWorkerRetainReceipt } from './worker-terminal-resource-presentation' @@ -18,8 +18,9 @@ import { import { ORCHESTRATION_WORKER_KEEP_OPEN_METHODS } from './worker-keep-open' export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerRelease', + access: { kind: 'writes', targets: { dispatch: 'dispatch' } }, permission: 'workspace', params: WorkerDispatchParams, handler: async (params, { runtime, orchestrationMutation }): Promise => { @@ -91,8 +92,9 @@ export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ }) } }), - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerRetain', + access: { kind: 'writes', targets: { dispatch: 'dispatch' } }, permission: 'workspace', params: WorkerRetainParams, handler: async (params, { runtime, orchestrationMutation }): Promise => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts index e679ee2d650..fccc693d70a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts @@ -1,5 +1,5 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' import { mapWithConcurrency } from '../../../../../../shared/map-with-concurrency' import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' @@ -12,8 +12,9 @@ import type { import { stopSingleWorker, type StopMutation } from './single-worker-stop' export const ORCHESTRATION_WORKER_STOP_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerStop', + access: { kind: 'writes', targets: { dispatch: 'dispatch' } }, permission: 'workspace', params: WorkerDispatchParams, handler: (params, { runtime, orchestrationMutation }) => diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index b5e1c0a2eea..dcf2e63ef94 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -1,8 +1,9 @@ import { stopHelperAfterStart } from './worker-stop' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import type { z } from 'zod' -import { defineMethod, type RpcContext } from '../../../core' -import { startFederatedWorker } from '../federation/federated-worker-start' +import type { RpcContext } from '../../../core' +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { startFederatedWorker } from '../../../../orchestration/legacy-remote-home/legacy-remote-home' import { startLocalWorker } from './local-worker-start' import type { WorkerFollowUp } from './worker-follow-up-placement' import { withWorkerStartNext } from '../receipt-next' @@ -34,8 +35,20 @@ type WorkerStartContext = Pick< > export const ORCHESTRATION_WORKER_START_METHODS = [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerStart', + access: { + kind: 'writes', + caller: 'from', + targets: { + task: 'task', + parent: 'task', + deps: 'task', + run: 'run', + retryOf: 'dispatch', + terminal: 'worker' + } + }, requires: ['accounts'], permission: 'workspace', params: WorkerStartParams, diff --git a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-status-stream.ts b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-status-stream.ts index ffc5121bb0b..4e493fdce88 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-status-stream.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-status-stream.ts @@ -15,7 +15,7 @@ export function bindStructuredAgentSessionStream( ctx: RpcContext, subscriptionId: string, onClose: () => void -): { isClosed: () => boolean } { +): { isClosed: () => boolean; close: () => void } { let closed = false let releaseTransportSubscription = (): void => {} const onTransportAbort = (): void => releaseTransportSubscription() @@ -40,7 +40,7 @@ export function bindStructuredAgentSessionStream( if (ctx.signal?.aborted) { onTransportAbort() } - return { isClosed: () => closed } + return { isClosed: () => closed, close: () => releaseTransportSubscription() } } export const STRUCTURED_AGENT_SESSION_STATUS_METHODS = [ diff --git a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts index a09545a50bd..8e3046fb5cc 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-subscribe-method.ts @@ -49,6 +49,18 @@ export const STRUCTURED_AGENT_SESSION_SUBSCRIBE_METHOD = defineStreamingMethod({ ctx ) ), + end: (cause) => { + if (stream.isClosed()) { + return + } + console.warn('[agent-session] ending stream after a failed frame', params.sessionId, cause) + try { + emitFrame({ type: 'end' }) + } catch { + // The transport is gone; releasing the stream below is all that is left to do. + } + stream.close() + }, ...(params.cursor ? { cursor: params.cursor } : {}), snapshotCatchUp: clientSupportsSnapshotCatchUp(ctx), // Every phone's app, whatever its version, ends a stream over a frame its bridge cannot carry. diff --git a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-unsubscribe.test.ts b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-unsubscribe.test.ts index 90656512b8c..1890ac6ed5e 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-unsubscribe.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/subscriptions/structured-agent-session-unsubscribe.test.ts @@ -80,3 +80,37 @@ it('drops the subscriber a client unsubscribes, and keeps its sibling (U-02)', a await vi.waitFor(() => expect(kept.length).toBeGreaterThan(1)) expect(ended.slice(before).every((frame) => JSON.stringify(frame).includes('"end"'))).toBe(true) }) + +// #39926: a frame the transport fails to send must end the stream, never leave it open and silent. +// The opening catch-up already sends a batch after the snapshot, so this covers a failure inside open. +it('ends the stream once when a frame fails to send', async () => { + await foundRestTestChat(rig) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const frames: RpcResponse[] = [] + await dispatcher.dispatchStreaming( + { + id: 'frame-a', + authToken: 'token', + method: 'agentSession.subscribe', + params: { sessionId: SESSION } + }, + (raw) => { + if (raw.includes('"type":"batch"')) { + throw new Error('frame could not be sent') + } + frames.push(JSON.parse(raw)) + }, + CLIENT + ) + + expect(subscriberCount()).toBe(0) + expect(frames.map((frame) => JSON.stringify(frame).match(/"type":"(\w+)"/)?.[1])).toEqual([ + 'snapshot', + 'end' + ]) + + // Later publications reach no one and end nothing twice. + const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence + await rig.host.send(CALLER, restTestSend('after the failed frame', fence)) + expect(frames.filter((frame) => JSON.stringify(frame).includes('"type":"end"'))).toHaveLength(1) +}) diff --git a/src/main/runtime/rpc/orchestration-contract-fence.test.ts b/src/main/runtime/rpc/orchestration-contract-fence.test.ts index 3dc5244abd5..7478d83cb03 100644 --- a/src/main/runtime/rpc/orchestration-contract-fence.test.ts +++ b/src/main/runtime/rpc/orchestration-contract-fence.test.ts @@ -7,7 +7,8 @@ import '../orchestration/db/contract-constants' import '../orchestration/db/messages/mailbox-routing-page' import '../orchestration/db/dispatch-row-writer' import '../orchestration/db/attempt-outcome-projection' -import { defineMethod, type RpcRequest } from './core' +import type { RpcRequest } from './core' +import { defineOrchestrationMethod } from './methods/orchestration/access/orchestration-method-access' import { RpcDispatcher } from './dispatcher' describe('orchestration contract fence', () => { @@ -19,7 +20,7 @@ describe('orchestration contract fence', () => { } }) - function createHarness(method = 'orchestration.send') { + function createHarness(method: `orchestration.${string}` = 'orchestration.send') { const database = new OrchestrationDb(':memory:') databases.push(database) const runtime = new OrcaRuntimeService() @@ -28,9 +29,10 @@ describe('orchestration contract fence', () => { const dispatcher = new RpcDispatcher({ runtime, methods: [ - defineMethod({ + defineOrchestrationMethod({ name: method, permission: 'workspace', + access: { kind: 'writes', targets: {} }, params: z.object({ subject: z.string() }), handler: effect }) @@ -82,7 +84,7 @@ describe('orchestration contract fence', () => { } ) - it.each(['orchestration.run', 'orchestration.runStop'])( + it.each(['orchestration.run', 'orchestration.runStop'] as const)( 'retires %s even when the caller sends the current contract', async (method) => { const { dispatcher, effect } = createHarness(method) diff --git a/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts b/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts index f1df214a9bd..de2976dc20a 100644 --- a/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts +++ b/src/main/runtime/rpc/orchestration-mutation-ledger.test.ts @@ -11,7 +11,8 @@ import '../orchestration/db/contract-constants' import '../orchestration/db/messages/mailbox-routing-page' import '../orchestration/db/dispatch-row-writer' import '../orchestration/db/attempt-outcome-projection' -import { defineMethod, type RpcRequest } from './core' +import type { RpcRequest } from './core' +import { defineOrchestrationMethod } from './methods/orchestration/access/orchestration-method-access' import { RpcDispatcher } from './dispatcher' import { ORCHESTRATION_METHODS } from './methods/orchestration/orchestration' import { createRootDispatch } from '../orchestration/db/root-dispatch-test-fixture' @@ -53,9 +54,10 @@ describe('durable orchestration mutation ledger', () => { const dispatcher = new RpcDispatcher({ runtime, methods: [ - defineMethod({ + defineOrchestrationMethod({ name: 'orchestration.workerStart', permission: 'workspace', + access: { kind: 'writes', targets: {} }, params: z.object({ from: z.string(), task: z.string() }), handler: effect }) diff --git a/src/main/runtime/rpc/orchestration-session-caller.ts b/src/main/runtime/rpc/orchestration-session-caller.ts index f1e5093d9e6..10a82436696 100644 --- a/src/main/runtime/rpc/orchestration-session-caller.ts +++ b/src/main/runtime/rpc/orchestration-session-caller.ts @@ -26,27 +26,7 @@ import type { AgentSessionRecordStore } from '../agent-session/records/agent-ses import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { structuredWorkerHostScope } from '../orchestration/terminal-authority/structured-sessions/structured-worker-identity' import type { RpcRequest } from './core' - -type CallerParam = 'from' | 'terminal' | 'callerTerminalHandle' - -/** Add each caller-reading method here with a test; unlisted methods still validate session claims but carry no caller identity. */ -export const ORCHESTRATION_CALLER_PARAM: Readonly> = { - 'orchestration.runCreate': 'from', - 'orchestration.runUse': 'from', - 'orchestration.runCurrent': 'from', - 'orchestration.check': 'terminal', - 'orchestration.send': 'from', - 'orchestration.reply': 'from', - 'orchestration.ask': 'from', - 'orchestration.dispatch': 'from', - 'orchestration.gateCreate': 'from', - 'orchestration.gateResolve': 'from', - 'orchestration.gateList': 'from', - 'orchestration.taskCreate': 'callerTerminalHandle', - 'orchestration.taskList': 'callerTerminalHandle', - 'orchestration.taskUpdate': 'callerTerminalHandle', - 'orchestration.workerStart': 'from' -} +import type { OrchestrationCallerField } from './methods/orchestration/access/orchestration-method-access' export type OrchestrationRequestRoute = { /** Set only by the paired WebSocket route: the request came from another host's client. */ @@ -71,18 +51,23 @@ const NEEDS_RUNNING_AGENT: ReadonlySet = new Set([ ]) /** Detect session evidence or a declared session caller synchronously so terminal calls avoid another async hop. */ -export function needsOrchestrationCallerResolution(request: RpcRequest): boolean { +export function needsOrchestrationCallerResolution( + request: RpcRequest, + callerField: OrchestrationCallerField | undefined +): boolean { if (!request.method.startsWith('orchestration.')) { return false } return ( request.orchestrationCompatibilityEvidence?.agentSessionId !== undefined || - declaredSessionAddress(request) !== undefined + declaredSessionAddress(request, callerField) !== undefined ) } -function declaredSessionAddress(request: RpcRequest): string | undefined { - const name = ORCHESTRATION_CALLER_PARAM[request.method] +function declaredSessionAddress( + request: RpcRequest, + name: OrchestrationCallerField | undefined +): string | undefined { const params: unknown = request.params if (!name || !params || typeof params !== 'object' || Array.isArray(params)) { return undefined @@ -96,11 +81,15 @@ function declaredSessionAddress(request: RpcRequest): string | undefined { export async function resolveOrchestrationSessionCaller( runtime: OrcaRuntimeService, request: RpcRequest, - route: OrchestrationRequestRoute | undefined + route: OrchestrationRequestRoute | undefined, + /** The method's declared caller field (its access declaration), if it reads one. */ + callerField: OrchestrationCallerField | undefined ): Promise { const evidence = request.orchestrationCompatibilityEvidence if (evidence?.agentSessionId === undefined) { - return { request: bindDeclaredSessionAddress(runtime.getOrchestrationDb(), request) } + return { + request: bindDeclaredSessionAddress(runtime.getOrchestrationDb(), request, callerField) + } } const claimed: unknown = evidence?.agentSessionId if (route?.pairedDeviceId !== undefined) { @@ -132,7 +121,7 @@ export async function resolveOrchestrationSessionCaller( return { request: { ...request, - params: bindDeclaredCaller(request.method, request.params, caller, db), + params: bindDeclaredCaller(callerField, request.params, caller, db), // Session identity wins; discard terminal attestation on the same request. orchestrationCompatibilityEvidence: { agentSessionId: sessionId } }, @@ -202,9 +191,12 @@ function assertSessionCanAct(sessionId: string, record: AgentSessionRecord, meth } /** A request with no session id that declares an `orca_session_id:` caller: a worker's is its handle. */ -function bindDeclaredSessionAddress(db: OrchestrationDb, request: RpcRequest): RpcRequest { - const name = ORCHESTRATION_CALLER_PARAM[request.method] - const declared = declaredSessionAddress(request) +function bindDeclaredSessionAddress( + db: OrchestrationDb, + request: RpcRequest, + name: OrchestrationCallerField | undefined +): RpcRequest { + const declared = declaredSessionAddress(request, name) const params: unknown = request.params if (!name || declared === undefined || !params || typeof params !== 'object') { return request @@ -234,12 +226,11 @@ function declaredNamesCaller( /** The declared caller, if any, must name this session; it is then replaced by its address. */ function bindDeclaredCaller( - method: string, + name: OrchestrationCallerField | undefined, params: unknown, caller: OrchestrationSessionCaller, db: OrchestrationDb ): unknown { - const name = ORCHESTRATION_CALLER_PARAM[method] if (!name || !params || typeof params !== 'object' || Array.isArray(params)) { return params } diff --git a/src/main/runtime/rpc/rpc-request-admission-prologue.ts b/src/main/runtime/rpc/rpc-request-admission-prologue.ts index 2d98d2c78c9..ee6560cea66 100644 --- a/src/main/runtime/rpc/rpc-request-admission-prologue.ts +++ b/src/main/runtime/rpc/rpc-request-admission-prologue.ts @@ -77,9 +77,11 @@ export function admitRpcRequest( return { method, request, caller, params: parsedParams.value } } // Resolve once before parse and unary/streaming branching so both see the same caller. - return needsOrchestrationCallerResolution(rawRequest) - ? resolveOrchestrationSessionCaller(runtime, rawRequest, options).then(admitResolved, (error) => - reject(mapDispatcherError(rawRequest, meta, error)) + const callerField = method.orchestrationAccess?.caller + return needsOrchestrationCallerResolution(rawRequest, callerField) + ? resolveOrchestrationSessionCaller(runtime, rawRequest, options, callerField).then( + admitResolved, + (error) => reject(mapDispatcherError(rawRequest, meta, error)) ) : admitResolved({ request: rawRequest }) } diff --git a/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts b/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts index f415aea8caf..e9c6fc64037 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts @@ -7,7 +7,8 @@ import { describe, expect, it, vi } from 'vitest' import type { WebSocket } from 'ws' import { DeviceRegistry } from './pairing/device-registry' import { OrcaRuntimeService } from '../../orca-runtime' -import { defineStreamingMethod } from '../core' +import { defineStreamingMethod, type RpcContext } from '../core' +import { defineOrchestrationStreamingMethod } from '../methods/orchestration/access/orchestration-method-access' import { OrcaRuntimeRpcServer } from './runtime-rpc' import { withCurrentOrchestrationContract } from './runtime-rpc-test-harness' @@ -108,23 +109,24 @@ describe('runtime RPC browser-host admission', () => { it('keeps a wait slot when asks and browser hosts fill their shared budget', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-browser-host-wait-reserve-')) - const blockingMethod = ( - name: 'browser.clientHost.attach' | 'orchestration.ask' | 'terminal.wait' - ) => - defineStreamingMethod({ - name, - permission: 'workspace', - params: null, - handler: async (_params, { signal }) => - await new Promise((resolve) => signal?.addEventListener('abort', () => resolve())) - }) + const block = async (_params: void, { signal }: RpcContext) => + await new Promise((resolve) => signal?.addEventListener('abort', () => resolve())) + const blockingMethod = (name: 'browser.clientHost.attach' | 'terminal.wait') => + defineStreamingMethod({ name, permission: 'workspace', params: null, handler: block }) + const blockingAsk = defineOrchestrationStreamingMethod({ + name: 'orchestration.ask', + permission: 'workspace', + params: null, + access: { kind: 'writes', targets: {} }, + handler: block + }) const server = new OrcaRuntimeRpcServer({ runtime: new OrcaRuntimeService(), userDataPath, longPollCap: 4, methods: [ blockingMethod('browser.clientHost.attach'), - blockingMethod('orchestration.ask'), + blockingAsk, blockingMethod('terminal.wait') ] }) diff --git a/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.test.ts b/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.test.ts new file mode 100644 index 00000000000..5e00fe47b5d --- /dev/null +++ b/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.test.ts @@ -0,0 +1,24 @@ +import { expect, it } from 'vitest' +import { describeClientConnection } from './runtime-rpc-client-connection-log' + +it('names the connecting device without its credentials', () => { + const described = describeClientConnection({ + connectionId: 'conn-1', + transport: { transport: 'direct' }, + device: { + deviceId: 'device-1', + scope: 'mobile', + clientId: 'bearer-secret', + callerFingerprint: 'fingerprint', + credentialRevision: 1, + deviceToken: 'token-secret' + } + }) + + expect(described).toEqual({ + deviceId: 'device-1', + scope: 'mobile', + transport: 'direct', + connectionId: 'conn-1' + }) +}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts b/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts new file mode 100644 index 00000000000..e6452f65399 --- /dev/null +++ b/src/main/runtime/rpc/server/runtime-rpc-client-connection-log.ts @@ -0,0 +1,21 @@ +import type { AuthenticatedMobileSocket } from '../mobile-socket-wiring' + +/** Who connected, without credentials: a phone's clientId can be its bearer token, so it is never logged. */ +export function describeClientConnection( + socket: Pick +): Record { + return { + deviceId: socket.device.deviceId, + scope: socket.device.scope, + transport: socket.transport.transport, + connectionId: socket.connectionId + } +} + +// One line per authenticated socket, so a host's log shows which client was attached when (#40328). +export function logClientConnection( + event: 'connected' | 'disconnected', + socket: Pick +): void { + console.info(`[runtime-rpc] client ${event}`, describeClientConnection(socket)) +} diff --git a/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts b/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts index 9a6c89046ab..dcbec116c0f 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts @@ -35,6 +35,7 @@ import { ensureDaemonSocketDir } from '../../../daemon/endpoint/publication/daemon-socket-endpoint-path' import { errorMessage } from '../../../../shared/error-message' +import { logClientConnection } from './runtime-rpc-client-connection-log' import { loadHostDescriptor, publishHostDescriptor @@ -282,6 +283,7 @@ export class RuntimeRpcLifecycle extends RuntimeRpcWebSocketDispatch { this.handleWebSocketBinaryMessage(bytes, socket.ws) }, onReady: (socket) => { + logClientConnection('connected', socket) if (socket.transport.transport === 'direct') { this.authenticatedSourceRecorder.note(socket.transport.sourceClass) } @@ -313,6 +315,7 @@ export class RuntimeRpcLifecycle extends RuntimeRpcWebSocketDispatch { void this.runtime.stagedFileSaves?.abortConnection(socket.connectionId) this.binaryMessageRouter.deleteConnection(socket.connectionId) this.declaredDesktopClients.forget(socket.connectionId) + logClientConnection('disconnected', socket) if (!hasOtherConnections) { this.runtime.onClientDisconnected(socket.device.clientId) } diff --git a/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts b/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts index 32883637bc4..2886782aae8 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts @@ -18,7 +18,7 @@ import { OrcaRuntimeRpcServer } from './runtime-rpc' import { DeviceRegistry } from './pairing/device-registry' import { sendRequest, withCurrentOrchestrationContract } from './runtime-rpc-test-harness' import { STATUS_METHODS } from '../methods/host-management/status' -import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from '../methods/orchestration/federation/federation-control' +import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from '../../orchestration/legacy-remote/federation-control' import { ORCHESTRATION_RESET_METHODS } from '../methods/orchestration/runs/reset-methods' import { SESSION_TAB_METHODS } from '../methods/session-tabs/session-tabs' import { FILE_MUTATION_METHODS } from '../methods/files/files-mutation-methods' diff --git a/src/main/runtime/terminal/recovery/closed-tab-pane-resolution.test.ts b/src/main/runtime/terminal/recovery/closed-tab-pane-resolution.test.ts new file mode 100644 index 00000000000..e797537f36b --- /dev/null +++ b/src/main/runtime/terminal/recovery/closed-tab-pane-resolution.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { + LEAF_ID, + PTY_ID, + TAB_ID, + WORKTREE_ID +} from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' +import { createHarness } from '../../__fixtures__/orca-runtime-terminal-close-continuity-fixtures' + +// #9194: a paired client asks for a pane by key; a tab the host closed after its agent exited must +// read as gone, or the client keeps the closed tab forever. +async function exitedPaneWithoutTab() { + const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) + harness.runtime.setNotifier(null) + harness.syncEmptyGraph() + harness.removeVictimFromInventory() + const before = harness.getSession() + // With no desktop window, the exit itself closes the tab's last pane and so the tab. + await harness.runtime.onPtyExit(PTY_ID, 0) + expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([]) + return { harness, before } +} + +const resolve = (harness: Awaited>['harness']) => + harness.runtime.resolveTerminalPane(makePaneKey(TAB_ID, LEAF_ID), WORKTREE_ID) + +describe('resolving a pane of a tab the host closed', () => { + it('answers terminal_not_found once the exited pane has no tab', async () => { + const { harness } = await exitedPaneWithoutTab() + expect(() => resolve(harness)).toThrow('terminal_not_found') + }) + + it('still resolves an exited pane whose tab the host keeps', async () => { + const { harness, before } = await exitedPaneWithoutTab() + harness.editSession(() => before) + expect(resolve(harness)).toMatchObject({ connected: false }) + }) + + it('still resolves the pane while the host session is unreadable', async () => { + const { harness } = await exitedPaneWithoutTab() + harness.makeSessionUnavailable() + expect(resolve(harness)).toMatchObject({ connected: false }) + }) +}) diff --git a/src/main/runtime/terminal/recovery/resolve-terminal-pane.ts b/src/main/runtime/terminal/recovery/resolve-terminal-pane.ts index 9b6dabc6b2d..14e92443c81 100644 --- a/src/main/runtime/terminal/recovery/resolve-terminal-pane.ts +++ b/src/main/runtime/terminal/recovery/resolve-terminal-pane.ts @@ -24,6 +24,7 @@ import { import { getTerminalState } from '../wait/terminal-wait-results' import { readStructuredWorkerTerminal } from '../../orchestration/terminal-authority/structured-sessions/structured-worker-terminal-read' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { workspaceSessionListsTerminalTab } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close' export abstract class OrcaRuntimeWithResolveTerminalPane extends OrcaRuntimeWithRestoredHandlePaneStart { protected abstract assertLiveTerminalHandleTargetsPty(handle: string, expectedPtyId: string): void @@ -79,6 +80,17 @@ export abstract class OrcaRuntimeWithResolveTerminalPane extends OrcaRuntimeWith // Why: pane coordinates restored by a paired client must not cross workspace ownership. throw new Error('terminal_not_found') } + if (parsed && !leaf && pty && !pty.connected && worktreeId) { + // An exited PTY outlives its tab; once the host closed that tab the pane is gone, and a client + // must not read the leftover record as a pane the host still owns (#9194). + const session = this.getWorkspaceSessionForWorktree(worktreeId) + if ( + session?.tabsByWorktree[worktreeId] && + !workspaceSessionListsTerminalTab(session, worktreeId, parsed.tabId) + ) { + throw new Error('terminal_not_found') + } + } return { handle, tabId: parsed?.tabId ?? record?.tabId ?? '', diff --git a/src/main/server/serve-stdout-boundary.test.ts b/src/main/server/serve-stdout-boundary.test.ts new file mode 100644 index 00000000000..7168bccdc25 --- /dev/null +++ b/src/main/server/serve-stdout-boundary.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it, vi } from 'vitest' +import { reserveServeStdoutForReadiness } from './serve-stdout-boundary' + +describe('reserveServeStdoutForReadiness', () => { + // #40328: unstamped serve diagnostics could not be lined up with daemon or kernel logs. + it('sends diagnostics to stderr with an ISO timestamp', () => { + const target = { debug: vi.fn(), error: vi.fn(), info: vi.fn(), log: vi.fn(), warn: vi.fn() } + const { error, warn } = target + const stamp = new Date('2026-11-09T12:00:00.000Z') + + reserveServeStdoutForReadiness(target, () => stamp) + target.log('[runtime] client connected', { clientId: 'device-1' }) + target.warn('[daemon] exited', 'SIGABRT') + + expect(error).toHaveBeenCalledWith('2026-11-09T12:00:00.000Z', '[runtime] client connected', { + clientId: 'device-1' + }) + expect(warn).toHaveBeenCalledWith('2026-11-09T12:00:00.000Z', '[daemon] exited', 'SIGABRT') + }) +}) diff --git a/src/main/server/serve-stdout-boundary.ts b/src/main/server/serve-stdout-boundary.ts index cdf03dab6e8..1c43f723b04 100644 --- a/src/main/server/serve-stdout-boundary.ts +++ b/src/main/server/serve-stdout-boundary.ts @@ -1,11 +1,22 @@ import type { BrowserIdentityModeStatus } from '../../shared/browser-user-agent-mode' -type DiagnosticConsole = Pick +type DiagnosticConsole = Pick type StderrTarget = Pick -export function reserveServeStdoutForReadiness(target: DiagnosticConsole = console): void { +export function reserveServeStdoutForReadiness( + target: DiagnosticConsole = console, + now: () => Date = () => new Date() +): void { + // Stamp each diagnostic so headless logs line up with daemon and kernel logs (#40328). + const stamped = + (write: (...args: unknown[]) => void) => + (...args: unknown[]): void => + write(now().toISOString(), ...args) + const writeWarning = stamped(target.warn.bind(target)) // Why: stdout is the serve readiness API; route incidental diagnostics to stderr so JSON stays parseable. - const writeDiagnostic = target.error.bind(target) + const writeDiagnostic = stamped(target.error.bind(target)) + target.warn = writeWarning + target.error = writeDiagnostic target.debug = writeDiagnostic target.info = writeDiagnostic target.log = writeDiagnostic diff --git a/src/main/speech/model-manager.test.ts b/src/main/speech/model-manager.test.ts index ddcd490e104..d4942058d35 100644 --- a/src/main/speech/model-manager.test.ts +++ b/src/main/speech/model-manager.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -76,6 +76,58 @@ describe('ModelManager', () => { } }) + it('keeps the old files after a cancelled or failed update, so the update is offered again', async () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) + try { + const modelId = 'parakeet-tdt-0.6b-v2-int8' + const manager = new ModelManager(dir, openElectronSpeechDownloadRequest) + const modelDir = manager.getModelDir(modelId) + mkdirSync(modelDir, { recursive: true }) + for (const [name, size] of [ + ['encoder.int8.onnx', 652_184_296], + ['decoder.int8.onnx', 7_257_753], + ['joiner.int8.onnx', 1_739_080], + ['tokens.txt', 9_384] + ] as const) { + writeFileSync(join(modelDir, name), '') + truncateSync(join(modelDir, name), size) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the test stubs the protected file download step. + const internals = manager as unknown as { + downloadModelFiles: ( + manifest: unknown, + stagingDir: string, + modelId: string, + isAborted: () => boolean, + signal: AbortSignal + ) => Promise + } + + internals.downloadModelFiles = (_manifest, _stagingDir, _modelId, _isAborted, signal) => + new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(new Error('aborted'))) + }) + const cancelled = manager.downloadModel(modelId) + manager.cancelDownload(modelId) + await expect(cancelled).resolves.toBeUndefined() + expect((await manager.getModelState(modelId)).needsUpdate).toBe(true) + + const failed = new ModelManager(dir, openElectronSpeechDownloadRequest) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. + ;(failed as unknown as typeof internals).downloadModelFiles = async () => { + throw new Error('network down') + } + await expect(failed.downloadModel(modelId)).rejects.toThrow('network down') + expect(existsSync(`${modelDir}.partial`)).toBe(false) + const state = await new ModelManager(dir, openElectronSpeechDownloadRequest).getModelState( + modelId + ) + expect(state.needsUpdate).toBe(true) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('aborts an in-flight model download request when cancelled', async () => { const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) try { diff --git a/src/main/speech/model-manager.ts b/src/main/speech/model-manager.ts index 8e530065f6d..4e35bd631c8 100644 --- a/src/main/speech/model-manager.ts +++ b/src/main/speech/model-manager.ts @@ -184,6 +184,8 @@ export class ModelManager extends SpeechModelDownloadTransport { } } this.activeDownloads.set(modelId, handle) + // Until the swap starts, modelDir holds only the old files, which are how the update is found again. + let replacingModelDir = false try { await this.downloadModelFiles( @@ -198,6 +200,7 @@ export class ModelManager extends SpeechModelDownloadTransport { return } + replacingModelDir = true await rm(modelDir, { recursive: true, force: true }) await rename(stagingDir, modelDir) this.updateState(modelId, 'ready') @@ -209,7 +212,9 @@ export class ModelManager extends SpeechModelDownloadTransport { console.error('[speech] Model download failed:', modelId, err) this.updateState(modelId, 'error', undefined, String(err)) } - removeModelDownloadFiles(modelDir, stagingDir, legacyArchivePath) + if (replacingModelDir) { + removeModelDownloadFiles(modelDir, stagingDir, legacyArchivePath) + } if (!aborted) { // Settings awaits real failures; cancellation stays quiet. throw err diff --git a/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts b/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts index 679155ab77e..200f800fce4 100644 --- a/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts @@ -8,10 +8,7 @@ import { import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnectionManager } from './ssh-connection-manager' -import { - recordSshCredentialDeclined, - resetSshCredentialDeclinesForTests -} from '../authentication/ssh-credential-decline' +import { recordSshCredentialDeclined } from '../authentication/ssh-credential-decline' vi.mock('../authentication/ssh2-module-load', async () => (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() @@ -66,7 +63,6 @@ describe('SshConnectionManager on a password host', () => { beforeEach(async () => { resetSshConnectionMocks() - resetSshCredentialDeclinesForTests() vi.stubEnv('SSH_AUTH_SOCK', '') onCredentialRequest.mockClear() manager = new SshConnectionManager(createCallbacks({ onCredentialRequest })) diff --git a/src/main/ssh/connection/ssh-connection-manager.test.ts b/src/main/ssh/connection/ssh-connection-manager.test.ts index 455b1a06b53..c01e0735bdd 100644 --- a/src/main/ssh/connection/ssh-connection-manager.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { SshTarget } from '../../../shared/ssh-types' type MockConnectionRecord = { @@ -58,6 +58,11 @@ import { isAuthError } from './reconnect/ssh-reconnect-error-classification' import './ssh-session-start-failure' import { recordSshUserDisconnected, resetSshUserDisconnectsForTests } from './ssh-user-disconnect' +beforeEach(resetSshCredentialDeclinesForTests) +beforeEach(resetSshUserDisconnectsForTests) +afterEach(resetSshCredentialDeclinesForTests) +afterEach(resetSshUserDisconnectsForTests) + const target = { id: 'target-1', label: 'Target 1', @@ -185,7 +190,6 @@ describe('SshConnectionManager after a cancelled sign-in', () => { beforeEach(() => { mockState.connectResults.length = 0 mockState.instances.length = 0 - resetSshCredentialDeclinesForTests() }) it('refuses an automatic dial as an auth failure without opening a connection', async () => { @@ -227,7 +231,6 @@ describe('SshConnectionManager after a user Disconnect', () => { beforeEach(() => { mockState.connectResults.length = 0 mockState.instances.length = 0 - resetSshUserDisconnectsForTests() }) it('refuses the background dials that revived the host, without opening a connection', async () => { diff --git a/src/main/ssh/connection/ssh-connection-wake-retry.test.ts b/src/main/ssh/connection/ssh-connection-wake-retry.test.ts index d00bc4305a7..cd2858d5801 100644 --- a/src/main/ssh/connection/ssh-connection-wake-retry.test.ts +++ b/src/main/ssh/connection/ssh-connection-wake-retry.test.ts @@ -17,7 +17,7 @@ import { SshConnection } from './ssh-connection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' import { RECONNECT_BACKOFF_MS } from './ssh-connection-timing' -import { recordSshUserDisconnected, resetSshUserDisconnectsForTests } from './ssh-user-disconnect' +import { recordSshUserDisconnected } from './ssh-user-disconnect' vi.mock('../authentication/ssh2-module-load', async () => (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() @@ -86,7 +86,6 @@ async function spendLadderWhileAsleep(conn: SshConnection): Promise { describe('SshConnection retry after wake or network return', () => { beforeEach(() => { resetSshConnectionMocks() - resetSshUserDisconnectsForTests() vi.useFakeTimers() }) afterEach(() => { diff --git a/src/main/ssh/connection/testing/ssh-connection-test-harness.ts b/src/main/ssh/connection/testing/ssh-connection-test-harness.ts index 97897ebb59b..6805936f6d5 100644 --- a/src/main/ssh/connection/testing/ssh-connection-test-harness.ts +++ b/src/main/ssh/connection/testing/ssh-connection-test-harness.ts @@ -11,6 +11,7 @@ import type * as SystemSshFileBinaryTransfer from '../../system-transport/file-t import type * as SystemSshFileTransfer from '../../system-transport/file-transfer/system-ssh-file-transfer' import type * as SshGConfigResolution from '../../config/ssh-g-config-resolution' import { resetSsh2ClientState, ssh2Mock } from './ssh-connection-test-client' +import { resetSshCredentialDeclinesForTests } from '../../authentication/ssh-credential-decline' import { resetSshUserDisconnectsForTests } from '../ssh-user-disconnect' export type SystemSshBinaryModuleMock = { findSystemSsh: typeof findSystemSshMock } @@ -106,6 +107,8 @@ export function withSshGConfigResolutionMocks(actual: typeof SshGConfigResolutio } export function resetSshConnectionMocks(): void { + // Session holds are module state that outlives a file in a shared worker; a stale hold refuses the next suite's dial. + resetSshCredentialDeclinesForTests() resetSshUserDisconnectsForTests() resetSsh2ClientState() getOrcaControlSocketPathMock.mockReset() diff --git a/src/main/startup/synthetic-title-runtime.test.ts b/src/main/startup/synthetic-title-runtime.test.ts new file mode 100644 index 00000000000..42e6c0bf972 --- /dev/null +++ b/src/main/startup/synthetic-title-runtime.test.ts @@ -0,0 +1,88 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { ingestSyntheticTitleFrame } = vi.hoisted(() => ({ + ingestSyntheticTitleFrame: vi.fn((_ptyId: string, _data: string) => {}) +})) + +vi.mock('../ipc/pty/pane/key-state', () => ({ + registerPaneKeyTeardownListener: vi.fn(), + getPtyIdForPaneKey: (paneKey: string) => `pty:${paneKey}` +})) +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: {} })) +vi.mock('./main-process-state', () => ({ + mainProcessState: { + mainWindow: null, + store: null, + runtime: { ingestSyntheticTitleFrame, getTrackedPtyTitle: () => null } + } +})) + +import { + driveSyntheticTitleFromHookStatus, + stopSyntheticTitleSpinner +} from './synthetic-title-runtime' + +const PANE = 'tab-1:leaf-1' +const QUESTION = JSON.stringify({ questions: [{ title: 'Which database?' }] }) + +function codexStatus( + state: 'working' | 'waiting' | 'done', + interactivePrompt?: string, + toolName = 'request_user_input_async' +) { + driveSyntheticTitleFromHookStatus({ + paneKey: PANE, + payload: { + state, + agentType: 'codex', + ...(interactivePrompt ? { toolName, interactivePrompt } : {}) + } + }) +} + +// Codex's PermissionRequest hook carries no request id; two approvals can look identical. +const APPROVAL = JSON.stringify({ approval: { command: 'pnpm tc' } }) + +function bellCount(): number { + return ingestSyntheticTitleFrame.mock.calls.filter(([, data]) => data.endsWith('\x07\x07')).length +} + +describe('synthetic title BEL', () => { + beforeEach(() => { + ingestSyntheticTitleFrame.mockClear() + stopSyntheticTitleSpinner(PANE) + }) + + it('rings once while hooks keep restating the same open question', () => { + // Codex restates waiting on every tool call while its async question stays open. + for (let i = 0; i < 20; i += 1) { + codexStatus('waiting', QUESTION) + } + expect(bellCount()).toBe(1) + // The permission title is still reasserted, only without a bell. + expect(ingestSyntheticTitleFrame).toHaveBeenCalledTimes(20) + }) + + it('rings again for a new prompt and after the wait ends', () => { + codexStatus('waiting', QUESTION) + codexStatus('waiting', JSON.stringify({ questions: [{ title: 'Which table name?' }] })) + codexStatus('waiting', QUESTION) + expect(bellCount()).toBe(2) + + codexStatus('done') + codexStatus('waiting', QUESTION) + expect(bellCount()).toBe(3) + + codexStatus('working') + codexStatus('waiting', QUESTION) + expect(bellCount()).toBe(4) + }) + it('rings for each approval during an open question, but not for the question again', () => { + codexStatus('waiting', QUESTION) + codexStatus('waiting', APPROVAL, 'Bash') + // Approved: Codex keeps working and restates the still-open question. + codexStatus('waiting', QUESTION) + codexStatus('waiting', APPROVAL, 'Bash') + expect(bellCount()).toBe(3) + }) +}) diff --git a/src/main/startup/synthetic-title-runtime.ts b/src/main/startup/synthetic-title-runtime.ts index 7c5d24652bb..717b9bea6cf 100644 --- a/src/main/startup/synthetic-title-runtime.ts +++ b/src/main/startup/synthetic-title-runtime.ts @@ -15,6 +15,7 @@ import { import { shouldSendSyntheticTitleFrame } from '../runtime/terminal/title/synthetic-title-visibility' import { shouldCopySyntheticTitleFrameToPtyData } from '../runtime/terminal/title/synthetic-title-frame-routing' import { mainProcessState as state } from './main-process-state' +import { CODEX_ASYNC_QUESTION_TOOL } from '../../shared/codex-async-question-input' // Cursor redraws overwrite one-shot OSC titles; reassert at Pi's 80ms cadence and share the animation with OpenCode. const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] @@ -24,6 +25,16 @@ const syntheticTitleSpinnerByPaneKey = new Map< SyntheticTitleSpinnerEntry >() let syntheticTitleSpinnerTimer: ReturnType | null = null +/** What one pane's current needs-input stretch has already rung for. */ +type NeedsInputBellState = { + /** The prompt the last needs-input frame showed; restating it is not a new request. */ + lastPromptKey: string + /** Async questions stay open across the turn, so one that resurfaces after an approval stays rung. */ + rungAsyncQuestionKeys: Set +} +// Why: hooks restate a held wait on every event (Codex re-sends one per tool call while an async +// question stays open), so ringing on each restatement becomes an OS notification every few seconds. +const needsInputBellByPaneKey = new Map() function isSyntheticTitleWindowVisible(): boolean { const window = state.mainWindow @@ -64,6 +75,7 @@ function canSendDecorativeSyntheticTitle(): boolean { } export function stopSyntheticTitleSpinner(paneKey: string): void { + needsInputBellByPaneKey.delete(paneKey) if (syntheticTitleSpinnerByPaneKey.delete(paneKey)) { stopSyntheticTitleSpinnerTimerIfIdle() } @@ -117,15 +129,28 @@ export function resumeSyntheticTitleSpinnerTimer(): void { ensureSyntheticTitleSpinnerTimer() } +function isNeedsInputState(agentState: AgentStatusState): boolean { + return agentState === 'blocked' || agentState === 'waiting' +} + export function driveSyntheticTitleFromHook( paneKey: string, agentState: AgentStatusState, - profile: SyntheticAgentTitleProfile + profile: SyntheticAgentTitleProfile, + /** Identifies what the agent is waiting on; a new prompt in the same wait rings again. */ + needsInput: { promptKey: string; asyncQuestion: boolean } = { + promptKey: '', + asyncQuestion: false + } ): void { const ptyId = getPtyIdForPaneKey(paneKey) if (!ptyId) { return } + const needsUserInput = isNeedsInputState(agentState) + if (!needsUserInput) { + needsInputBellByPaneKey.delete(paneKey) + } if (agentState === 'working') { // Emit immediately so visible startup does not wait for the next 80ms tick. const existing = syntheticTitleSpinnerByPaneKey.get(paneKey) @@ -143,10 +168,22 @@ export function driveSyntheticTitleFromHook( return } // Stop before the next tick can restore working; only permission frames ring BEL, completion owns its own notifications. + const bell = needsInputBellByPaneKey.get(paneKey) stopSyntheticTitleSpinner(paneKey) - const needsUserInput = agentState === 'blocked' || agentState === 'waiting' const label = needsUserInput ? profile.permissionLabel : profile.idleLabel - sendSyntheticTitle(ptyId, `\x1b]0;${label}\x07${needsUserInput ? '\x07' : ''}`, { force: true }) + let ringsBell = false + if (needsUserInput) { + const next = bell ?? { lastPromptKey: '', rungAsyncQuestionKeys: new Set() } + // Approvals carry no request id (Codex PermissionRequest), so a repeat after another prompt is new. + ringsBell = bell === undefined || next.lastPromptKey !== needsInput.promptKey + if (needsInput.asyncQuestion) { + ringsBell &&= !next.rungAsyncQuestionKeys.has(needsInput.promptKey) + next.rungAsyncQuestionKeys.add(needsInput.promptKey) + } + next.lastPromptKey = needsInput.promptKey + needsInputBellByPaneKey.set(paneKey, next) + } + sendSyntheticTitle(ptyId, `\x1b]0;${label}\x07${ringsBell ? '\x07' : ''}`, { force: true }) } // Why: a profile that leaves working titles to the agent never overwrites the rest label Orca @@ -187,7 +224,13 @@ export function initializeSyntheticTitleRuntime(): void { export function driveSyntheticTitleFromHookStatus(event: { paneKey: string - payload: { state: AgentStatusState; agentType?: string } + payload: { + state: AgentStatusState + agentType?: string + toolName?: string + toolInput?: string + interactivePrompt?: string + } providerSessionOnly?: boolean structuredHost?: unknown }): void { @@ -200,8 +243,16 @@ export function driveSyntheticTitleFromHookStatus(event: { if (!profile) { return } + // Profiles that leave working titles to the agent never reach the drive below on working. + if (!isNeedsInputState(event.payload.state)) { + needsInputBellByPaneKey.delete(event.paneKey) + } if (shouldDriveSyntheticAgentTitleFromHook(event.payload.agentType, event.payload.state)) { - driveSyntheticTitleFromHook(event.paneKey, event.payload.state, profile) + const { toolName, toolInput, interactivePrompt } = event.payload + driveSyntheticTitleFromHook(event.paneKey, event.payload.state, profile, { + promptKey: JSON.stringify([toolName ?? null, interactivePrompt ?? toolInput ?? null]), + asyncQuestion: toolName === CODEX_ASYNC_QUESTION_TOOL + }) } else if (event.payload.state === 'working' && profile.synthesizeTerminalTitle !== false) { retractSyntheticRestTitle(event.paneKey, profile) } diff --git a/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts b/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts index 8a52338b972..5be81369820 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getSetupTrustContent } from '../../shared/orca-hook-setup-config' -import '../../renderer/src/lib/orca-hook-trust' +import '../../renderer/src/runtime/repo-hooks/orca-hook-trust' import '../runtime/repositories/runtime-repository-hooks-commands' import { loadHooks } from './hooks' import { hashOrcaHookTrustContent } from './created-worktree-setup-trust' diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts index 3b1ca6f8849..47d75854e94 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts @@ -1,114 +1,31 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as WorktreeLogic from '../../../ipc/worktree-logic' -import type { Store } from '../../../persistence/loading-store/store' +import { + mocks, + repo, + store, + flushBackgroundWork +} from '../../../__mocks__/worktree-create-preparation' +import { describe, expect, it, vi } from 'vitest' import { WORKTREE_CREATE_PREPARATION_TTL_MS } from './worktree-create-preparation-pool' -import type { Repo } from '../../../../shared/repo-types' -import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref' - -const mocks = vi.hoisted(() => ({ - mkdir: vi.fn(), - listWorktreeGraph: vi.fn(), - prepareCheckout: vi.fn(), - finalize: vi.fn(), - discard: vi.fn(), - unlock: vi.fn(), - getWorktreeOptions: vi.fn(), - computeWorkspaceRoot: vi.fn(), - computeWorkspaceRootAsync: vi.fn(), - resolveBaseRef: vi.fn(), - measureDivergence: vi.fn() -})) - -vi.mock('node:fs/promises', () => ({ mkdir: mocks.mkdir })) - -vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ - ...(await importOriginal>()), - listWorktreeGraph: mocks.listWorktreeGraph -})) -vi.mock('../../../git/worktrees/creation/worktree-create-preparation', () => ({ - prepareWorktreeCreateCheckout: mocks.prepareCheckout, - finalizePreparedWorktree: mocks.finalize, - discardPreparedWorktree: mocks.discard, - unlockPreparedWorktree: mocks.unlock -})) -vi.mock('../../../git/worktrees/creation/worktree-base-ref-probe', () => ({ - resolveLocalWorktreeBaseRef: mocks.resolveBaseRef -})) -vi.mock('../../../git/worktrees/creation/worktree-base-divergence', () => ({ - measureRetargetDivergence: mocks.measureDivergence -})) -vi.mock('../../execution-host/project-runtime-git-options', () => ({ - getLocalProjectWorktreeGitOptions: mocks.getWorktreeOptions, - getWorktreeMirrorDistro: () => undefined -})) -vi.mock('../../../ipc/worktree-logic', async (importOriginal) => ({ - isOrphanedWorktreeError: (await importOriginal()).isOrphanedWorktreeError, - computeWorkspaceRoot: mocks.computeWorkspaceRoot, - computeWorkspaceRootAsync: mocks.computeWorkspaceRootAsync, - getWorktreePathSettings: () => ({ - workspaceDir: process.platform === 'win32' ? 'C:\\workspace' : '/workspace', - nestWorkspaces: false - }) -})) import { - _resetWorktreeCreatePreparationsForTests, consumePreparedWorktreeCreate, prepareWorktreeCreateForRepo } from './worktree-create-preparation' -// Evictions and retries are fire-and-forget, so let them settle before asserting. -function flushBackgroundWork(ms = 0): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -const EXISTING_REFS = new Set([ - 'refs/heads/main', - 'refs/remotes/origin/main', - 'refs/remotes/origin/release' -]) -const repo = { id: 'repo-1', path: '/repo' } as Repo -const store = { getSettings: () => ({}) } as unknown as Store - -beforeEach(() => { - mocks.mkdir.mockReset().mockResolvedValue(undefined) - mocks.listWorktreeGraph.mockReset().mockResolvedValue([]) - mocks.prepareCheckout.mockReset().mockResolvedValue(undefined) - mocks.finalize.mockReset().mockResolvedValue({}) - mocks.discard.mockReset().mockResolvedValue(undefined) - mocks.unlock.mockReset().mockResolvedValue(undefined) - mocks.getWorktreeOptions.mockReset().mockReturnValue({}) - mocks.measureDivergence.mockReset().mockResolvedValue('within') - mocks.resolveBaseRef - .mockReset() - .mockImplementation((_repoPath: string, baseRef: string) => - resolveWorktreeAddBaseRef(baseRef, async (candidate) => EXISTING_REFS.has(candidate)) - ) - mocks.computeWorkspaceRoot.mockReset().mockImplementation(() => { - throw new Error('synchronous workspace-root lookup must not run on the main thread') - }) - mocks.computeWorkspaceRootAsync - .mockReset() - .mockImplementation(async (repoPath: string) => - process.platform === 'win32' && /^[A-Za-z]:[\\/]/.test(repoPath) - ? 'C:\\workspace' - : '/workspace' - ) -}) - -afterEach(async () => { - await _resetWorktreeCreatePreparationsForTests() -}) - describe('worktree create preparation cancellation', () => { it('cancels an evicted checkout and cleans up with the original options', async () => { let signal: AbortSignal | undefined - mocks.prepareCheckout.mockImplementationOnce((_repo, _path, _base, _lock, options) => { - signal = options.signal - return new Promise((_resolve, reject) => { - signal!.addEventListener('abort', () => reject(signal!.reason), { once: true }) - }) - }) + mocks.prepareCheckout.mockImplementationOnce( + (repoPath, path, _base, reason, options, _barrier, operation) => { + operation.setDiscard((cleanupOptions) => + mocks.discard(repoPath, path, cleanupOptions, reason, null) + ) + signal = options.signal + return new Promise((_resolve, reject) => { + signal!.addEventListener('abort', () => reject(signal!.reason), { once: true }) + }) + } + ) const obsolete = prepareWorktreeCreateForRepo(store, repo, 'origin/main') const settled = Promise.allSettled([obsolete]) await flushBackgroundWork() @@ -123,7 +40,8 @@ describe('worktree create preparation cancellation', () => { repo.path, obsoletePath, expect.objectContaining({ signal: undefined }), - expect.any(String) + expect.any(String), + null ) }) @@ -149,7 +67,26 @@ describe('worktree create preparation cancellation', () => { 'fulfilled', 'fulfilled' ]) - expect(mocks.prepareCheckout).toHaveBeenCalledTimes(3) + for (const base of ['one', 'two', 'three']) { + await expect( + consumePreparedWorktreeCreate({ + repoPath: repo.path, + workspaceRoot: '/workspace', + worktreePath: `/workspace/${base}`, + branch: base, + baseBranch: `origin/${base}` + }) + ).resolves.toMatchObject({ status: 'hit' }) + } + expect(mocks.prepareCheckout).not.toHaveBeenCalledWith( + repo.path, + expect.any(String), + 'refs/remotes/origin/main', + expect.any(String), + expect.anything(), + undefined, + expect.anything() + ) await flushBackgroundWork() expect(mocks.discard).not.toHaveBeenCalled() }) diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts index 140d0ac33f0..c0570d5d264 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-pool.ts @@ -1,3 +1,11 @@ +import { discardUnmaterializedPreparation } from '../../../git/worktrees/creation/worktree-preparation-add' +import { + cancelPreparationAdmissions, + waitForPreparationAdmission, + canPrepare, + selectPreparationVictim, + type StartPreparationArgs +} from './worktree-preparation-admission-intents' import { worktreePreparationGit } from '../../../git/worktrees/creation/worktree-create-git-executor' import { randomUUID } from 'node:crypto' import { mkdir } from 'node:fs/promises' @@ -8,10 +16,7 @@ import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' -import { - prepareWorktreeCreateCheckout, - discardPreparedWorktree -} from '../../../git/worktrees/creation/worktree-create-preparation' +import { prepareWorktreeCreateCheckout } from '../../../git/worktrees/creation/worktree-create-preparation' import { queuePreparedWorktreeTipRefresh } from './worktree-preparation-refresh-queue' import { toHostFilesystemPath } from '../../../filesystem/host-tree-removal' import { createPreparationActivity } from './worktree-create-preparation-activity' @@ -35,12 +40,16 @@ import { import { discardPreparationEntry, preparationHostKey, + preparationCapacityUsed, + registerPreparationObligation, + retryPendingPreparationDiscards, resetPendingPreparationDiscardsForTests, trackPreparationDiscard } from './worktree-preparation-discard-retry' import { WorktreePreparationOperation } from '../../../git/worktrees/creation/worktree-preparation-operation' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +export type { StartPreparationArgs } from './worktree-preparation-admission-intents' export { WORKTREE_CREATE_PREPARATION_TTL_MS } from '../../../git/worktrees/creation/worktree-preparation-operation' export const WORKTREE_CREATE_PREPARATION_LIMIT = 3 @@ -63,30 +72,22 @@ export type PreparationEntry = { activity: PreparationActivity } -export type StartPreparationArgs = { - repoPath: string - workspaceRoot: string - baseBranch: string - canonicalBase: string - options: AddWorktreeOptions - beforeMaterialization?: Promise -} - const preparations = new Map() export function hasPendingPreparations(): boolean { return preparations.size > 0 || hasClaims() || hasPendingStalePreparationCleanup() } -function discardEntryInBackground(entry: PreparationEntry): void { - // Let test reset await background discards before clearing the registry. - trackPreparationDiscard(worktreePreparationGit.run(() => discardPreparationEntry(entry))) +function discardEntryInBackground(entry: PreparationEntry): Promise { + const work = worktreePreparationGit.run(() => discardPreparationEntry(entry)) + trackPreparationDiscard(work) + return work } -function evictEntry(entry: PreparationEntry): void { +function evictEntry(entry: PreparationEntry): Promise { preparations.delete(entry.key) entry.operation.controller.abort() - discardEntryInBackground(entry) + return discardEntryInBackground(entry) } function expireEntry(entry: PreparationEntry): void { @@ -97,6 +98,7 @@ function expireEntry(entry: PreparationEntry): void { /** A removed project has no create left to claim its armed checkouts. */ export function discardRepoPreparations(repoPathKey: string): void { + cancelPreparationAdmissions(repoPathKey) for (const entry of preparations.values()) { if (entry.repoPathKey === repoPathKey) { evictEntry(entry) @@ -104,28 +106,6 @@ export function discardRepoPreparations(repoPathKey: string): void { } } -/** Bound full-checkout disk use, evicting the requesting workspace's oldest preparation first. */ -function enforcePreparationLimit( - repoPathKey: string, - workspaceRootKey: string, - wslDistro: string -): void { - while (preparations.size >= WORKTREE_CREATE_PREPARATION_LIMIT) { - const byAge = [...preparations.values()].sort((left, right) => left.createdAt - right.createdAt) - const victim = - byAge.find( - (entry) => - entry.repoPathKey === repoPathKey && - entry.workspaceRootKey === workspaceRootKey && - entry.wslDistro === wslDistro - ) ?? byAge[0] - if (!victim) { - return - } - evictEntry(victim) - } -} - export function listPreparations(): PreparationEntry[] { return [...preparations.values()] } @@ -157,10 +137,13 @@ export function takePreparation( return registerClaim(entry, requestedKey) } -export function startPreparation( +function reusePreparation( args: StartPreparationArgs, - kind: DeferredPreparation['kind'] = 'explicit' -): Promise { + kind: DeferredPreparation['kind'] +): Promise | undefined { + if (!canPrepare(args)) { + return Promise.resolve() + } const existing = findPreparation( preparationPathKey(args.repoPath), preparationPathKey(args.workspaceRoot), @@ -175,10 +158,42 @@ export function startPreparation( ? refreshPreparationTip(existing, args.beforeMaterialization) : existing.ready } - if (deferPreparationForClaim(args, kind)) { - return Promise.resolve() + return deferPreparationForClaim(args, kind) ? Promise.resolve() : undefined +} + +export function startPreparation( + args: StartPreparationArgs, + kind: DeferredPreparation['kind'] = 'explicit' +): Promise { + const full = preparationCapacityUsed() >= WORKTREE_CREATE_PREPARATION_LIMIT + const retries = retryPendingPreparationDiscards( + full + ? undefined + : preparationHostKey(preparationPathKey(args.repoPath), args.options.wslDistro ?? '') + ) + void retries.catch((error) => + console.warn('[worktree-create] preparation cleanup retry failed', error) + ) + const reused = reusePreparation(args, kind) + if (reused) { + return reused } - return worktreePreparationGit.run(() => startBackgroundPreparation({ ...args, kind })) + if (!full) { + return worktreePreparationGit.run(() => startBackgroundPreparation({ ...args, kind })) + } + return worktreePreparationGit.run(() => + waitForPreparationAdmission(args, kind, WORKTREE_CREATE_PREPARATION_LIMIT, { + retry: retries, + reuse: reusePreparation, + hasCapacity: () => preparationCapacityUsed() < WORKTREE_CREATE_PREPARATION_LIMIT, + evict: (request) => { + const victim = selectPreparationVictim(preparations.values(), request) + return victim ? evictEntry(victim) : undefined + }, + start: (request, requestedKind) => + startBackgroundPreparation({ ...request, kind: requestedKind }) + }) + ) } function refreshPreparationTip( @@ -204,20 +219,25 @@ function refreshPreparationTip( return ready } -function startBackgroundPreparation({ - repoPath, - workspaceRoot, - baseBranch, - canonicalBase, - options, - beforeMaterialization, - kind -}: StartPreparationArgs & { kind: DeferredPreparation['kind'] }): Promise { +function startBackgroundPreparation( + args: StartPreparationArgs & { kind: DeferredPreparation['kind'] } +): Promise { + const { + repoPath, + workspaceRoot, + baseBranch, + canonicalBase, + options, + beforeMaterialization, + kind + } = args const repoPathKey = preparationPathKey(repoPath) const workspaceRootKey = preparationPathKey(workspaceRoot) const wslDistro = options.wslDistro ?? '' const key = preparationEntryKey(repoPathKey, workspaceRootKey, canonicalBase, wslDistro) - enforcePreparationLimit(repoPathKey, workspaceRootKey, wslDistro) + if (!canPrepare(args) || preparationCapacityUsed() >= WORKTREE_CREATE_PREPARATION_LIMIT) { + return Promise.resolve() + } const preparationId = `${process.pid}-${randomUUID()}` const lockReason = createWorktreePreparationLockReason( preparationId, @@ -242,13 +262,14 @@ function startBackgroundPreparation({ options, createdAt: Date.now(), operation, - checkoutStarted: false, + checkoutStarted: true, activity: createPreparationActivity(kind), ready: Promise.resolve() } operation.setDiscard((cleanupOptions) => - discardPreparedWorktree(repoPath, preparedPath, cleanupOptions, lockReason) + discardUnmaterializedPreparation(preparedPath, cleanupOptions) ) + registerPreparationObligation(entry) entry.ready = operation.run(async () => { await waitForPromiseWithSignal( startStalePreparationCleanup(preparationHostKey(repoPathKey, wslDistro), repoPath, options), @@ -257,7 +278,6 @@ function startBackgroundPreparation({ signal.throwIfAborted() await operation.trackWriter(mkdir(toHostFilesystemPath(preparationRoot), { recursive: true })) signal.throwIfAborted() - entry.checkoutStarted = true await prepareWorktreeCreateCheckout( repoPath, preparedPath, @@ -281,6 +301,7 @@ function startBackgroundPreparation({ } export async function _resetPreparationPoolForTests(): Promise { + cancelPreparationAdmissions() const entries = [...preparations.values()] preparations.clear() resetClaimsForTests() diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts index 7ac8fea5ffa..0619cb0dd59 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts @@ -64,12 +64,12 @@ export async function startStalePreparationCleanup( repoPath: string, options: AddWorktreeOptions ): Promise { + void retryPendingPreparationDiscards(cleanupKey) const existing = staleCleanupInFlight.get(cleanupKey) if (existing) { await existing.scanned.catch(() => {}) return } - void retryPendingPreparationDiscards(cleanupKey) // Reclaim in background to avoid blocking creates; retain caller priority for the scan they await. const reclaimOptions: AddWorktreeOptions = { ...options, admissionTier: 'background' } const scan = listWorktreeGraph(repoPath, { diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts index f0f3a1c4071..3beddbfdfc6 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts @@ -8,7 +8,6 @@ import { describe, expect, it } from 'vitest' import type { Repo } from '../../../../shared/repo-types' import { hasPendingStalePreparationCleanup } from './worktree-create-preparation-stale-cleanup' import '../../../../shared/worktree/create-preparation' -import { WorktreePreparationLockOwnershipError } from '../../../git/worktrees/creation/worktree-preparation-lock' import { _resetWorktreeCreatePreparationsForTests, consumePreparedWorktreeCreate, @@ -62,7 +61,8 @@ describe('worktree create preparation registry', () => { 'main', undefined, {}, - mocks.prepareCheckout.mock.calls[0]?.[3] + mocks.prepareCheckout.mock.calls[0]?.[3], + expect.anything() ) }) @@ -189,7 +189,8 @@ describe('worktree create preparation registry', () => { repo.path, armedPath, expect.objectContaining({ signal: undefined }), - expect.any(String) + expect.any(String), + null ) expect(mocks.discard).toHaveBeenCalledWith( repo.path, @@ -309,36 +310,4 @@ describe('worktree create preparation registry', () => { expect(mocks.unlock).not.toHaveBeenCalled() expect(mocks.discard).not.toHaveBeenCalled() }) - - it('cleans up and reports a finalize miss so normal add can run', async () => { - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - mocks.finalize.mockRejectedValueOnce(new Error('submodules prevent worktree move')) - - await expect( - consumePreparedWorktreeCreate({ - repoPath: repo.path, - workspaceRoot: '/workspace', - worktreePath: '/workspace/final', - branch: 'feature/test', - baseBranch: 'origin/main' - }) - ).resolves.toMatchObject({ status: 'miss', reason: 'finalize_failed' }) - expect(mocks.mkdir).toHaveBeenCalledWith('/workspace', { recursive: true }) - expect(mocks.discard).toHaveBeenCalledTimes(1) - }) - - it('preserves another owner’s checkout when finalization loses its lock', async () => { - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - mocks.finalize.mockRejectedValueOnce(new WorktreePreparationLockOwnershipError()) - await expect( - consumePreparedWorktreeCreate({ - repoPath: repo.path, - workspaceRoot: '/workspace', - worktreePath: '/workspace/final', - branch: 'feature/test', - baseBranch: 'origin/main' - }) - ).resolves.toMatchObject({ status: 'miss', reason: 'finalize_failed' }) - expect(mocks.discard).not.toHaveBeenCalled() - }) }) diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation.ts index f832a983b81..7ab008843c8 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation.ts @@ -1,7 +1,8 @@ import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' import { discardPreparationEntry, - trackPreparationDiscard + trackPreparationDiscard, + releasePreparationObligation } from './worktree-preparation-discard-retry' import { worktreePreparationGit } from '../../../git/worktrees/creation/worktree-create-git-executor' import { mkdir } from 'node:fs/promises' @@ -20,7 +21,6 @@ import type { AddWorktreeOptions, AddWorktreeResult } from '../../../git/worktrees/worktree-operation-options' -import { WorktreePreparationLockOwnershipError } from '../../../git/worktrees/creation/worktree-preparation-lock' import { _resetPreparationPoolForTests, hasPendingPreparations, @@ -38,7 +38,7 @@ import { type ReservedPreparation } from './worktree-create-preparation-reservation' import { - discardPreparedWorktree, + PreparedWorktreeFinalizationPendingError, finalizePreparedWorktree } from '../../../git/worktrees/creation/worktree-create-preparation' import { @@ -127,8 +127,7 @@ async function prepareWorktreeCreateInBackground( return } const options = getLocalProjectWorktreeGitOptions(store, repo) - // Resolve WSL homes asynchronously to avoid freezing the composer while wsl.exe runs. - // Match createLocalWorktree's mirror distro so preparation and consume use the same root key. + // Resolve WSL homes asynchronously with createLocalWorktree's mirror distro and root key. const workspaceRoot = await computeWorkspaceRootAsync( repo.path, getWorktreePathSettings(repo, store.getSettings(), getWorktreeMirrorDistro(store, repo)) @@ -144,7 +143,8 @@ async function prepareWorktreeCreateInBackground( baseBranch, canonicalBase, options, - beforeMaterialization + beforeMaterialization, + canPrepare: () => !store.getRepo || Boolean(store.getRepo(repo.id)) }) } @@ -250,10 +250,7 @@ export async function consumePreparedWorktreeCreate( } function preparedCheckoutReset(retargeted: boolean, headReset: boolean): PreparedCheckoutReset { - if (!headReset) { - return 'none' - } - return retargeted ? 'retargeted' : 'base_moved' + return headReset ? (retargeted ? 'retargeted' : 'base_moved') : 'none' } async function attemptPreparedWorktreeCreate( @@ -283,10 +280,12 @@ async function attemptPreparedWorktreeCreate( args.baseBranch, args.refreshLocalBaseRef, options, - entry.lockReason + entry.lockReason, + entry.operation ) } ) + releasePreparationObligation(entry) const rearm = deferRearmPreparation(entry, reservation, args.baseBranch, claim.canonicalBase) return { status: 'hit', @@ -298,16 +297,15 @@ async function attemptPreparedWorktreeCreate( rearm } } catch (error) { - // Another owner holds the preparation's lock, so it is not ours to remove. - if (!(error instanceof WorktreePreparationLockOwnershipError)) { - await timePhase(args, 'prepared_checkout_discard', () => - discardPreparedWorktree(args.repoPath, entry.preparedPath, options, entry.lockReason) - ).catch(() => {}) - } + trackPreparationDiscard(worktreePreparationGit.run(() => discardPreparationEntry(entry))) if (options.signal?.aborted) { releaseClaimAfterCreate(reservation)() options.signal.throwIfAborted() } + if (error instanceof PreparedWorktreeFinalizationPendingError) { + releaseClaimAfterCreate(reservation)() + throw error.originalError + } console.warn( '[worktree-create] prepared checkout could not be finalized; using normal add', error diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-admission-intents.ts b/src/main/workspaces/creation/preparation/worktree-preparation-admission-intents.ts new file mode 100644 index 00000000000..c54cb0b3679 --- /dev/null +++ b/src/main/workspaces/creation/preparation/worktree-preparation-admission-intents.ts @@ -0,0 +1,184 @@ +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { preparationEntryKey, preparationPathKey } from './worktree-create-preparation-claim' +import type { DeferredPreparation } from './worktree-create-preparation-claim-registry' +import type { PreparationEntry } from './worktree-create-preparation-pool' +import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' + +export type StartPreparationArgs = { + repoPath: string + workspaceRoot: string + baseBranch: string + canonicalBase: string + options: AddWorktreeOptions + beforeMaterialization?: Promise + canPrepare?: () => boolean +} + +export function selectPreparationVictim( + entries: Iterable, + args: StartPreparationArgs +): PreparationEntry | undefined { + const byAge = [...entries].sort((left, right) => left.createdAt - right.createdAt) + return ( + byAge.find( + (entry) => + entry.repoPathKey === preparationPathKey(args.repoPath) && + entry.workspaceRootKey === preparationPathKey(args.workspaceRoot) && + entry.wslDistro === (args.options.wslDistro ?? '') + ) ?? byAge[0] + ) +} + +type PreparationAdmissionIntent = { + args: StartPreparationArgs + kind: DeferredPreparation['kind'] + ready: Promise + signal: AbortSignal + current(): boolean + release(): void + wait(work: Promise): Promise + cancel(): void +} + +const intents = new Map() + +function joinPreparationAdmission( + args: StartPreparationArgs, + kind: DeferredPreparation['kind'], + limit: number, + run: (intent: PreparationAdmissionIntent) => Promise, + reuse: () => Promise | undefined +): Promise { + const key = preparationEntryKey( + preparationPathKey(args.repoPath), + preparationPathKey(args.workspaceRoot), + args.canonicalBase, + args.options.wslDistro ?? '' + ) + const existing = intents.get(key) + if (existing) { + if (kind === 'explicit' || existing.kind !== 'explicit') { + existing.kind = kind + if (args.beforeMaterialization) { + existing.args.beforeMaterialization = args.beforeMaterialization + } + } + return existing.ready.then(() => (existing.signal.aborted ? undefined : reuse())) + } + if (intents.size >= limit) { + return Promise.resolve() + } + const controller = new AbortController() + const signal = args.options.signal + ? AbortSignal.any([controller.signal, args.options.signal]) + : controller.signal + const completion = Promise.withResolvers() + const intent: PreparationAdmissionIntent = { + args: { ...args }, + kind, + ready: completion.promise, + signal, + current: () => intents.get(key) === intent && !signal.aborted, + release: () => { + if (intents.get(key) === intent) { + intents.delete(key) + } + }, + wait: (work) => waitForPromiseWithSignal(work, signal), + cancel: () => { + controller.abort() + intent.release() + } + } + intents.set(key, intent) + void run(intent) + .catch((error) => { + if (!signal.aborted) { + throw error + } + }) + .then(completion.resolve, completion.reject) + .finally(intent.release) + return intent.ready +} + +export function cancelPreparationAdmissions(repoPathKey?: string): void { + for (const intent of intents.values()) { + if (!repoPathKey || preparationPathKey(intent.args.repoPath) === repoPathKey) { + intent.cancel() + } + } +} + +type AdmissionActions = { + retry: Promise + reuse: ( + args: StartPreparationArgs, + kind: DeferredPreparation['kind'] + ) => Promise | undefined + hasCapacity: () => boolean + evict: (args: StartPreparationArgs) => Promise | undefined + start: (args: StartPreparationArgs, kind: DeferredPreparation['kind']) => Promise +} + +export function canPrepare(args: StartPreparationArgs): boolean { + return ( + !args.options.signal?.aborted && + args.options.canStart?.() !== false && + args.canPrepare?.() !== false + ) +} + +export function waitForPreparationAdmission( + args: StartPreparationArgs, + kind: DeferredPreparation['kind'], + limit: number, + actions: AdmissionActions +): Promise { + return joinPreparationAdmission( + args, + kind, + limit, + (intent) => recoverPreparationCapacity(intent, actions), + () => (canPrepare(args) ? actions.reuse(args, kind) : undefined) + ) +} + +async function recoverPreparationCapacity( + intent: PreparationAdmissionIntent, + actions: AdmissionActions +): Promise { + const { args } = intent + const valid = (): boolean => intent.current() && canPrepare(args) + const hostAvailable = (): Promise => + intent + .wait(blockedWslDistroForPath(args.repoPath, args.options.wslDistro)) + .then((blocked) => !blocked) + await intent.wait(actions.retry) + if (!valid() || !(await hostAvailable()) || !valid()) { + return + } + let reused = actions.reuse(args, intent.kind) + if (reused) { + intent.release() + return reused + } + if (!actions.hasCapacity()) { + const removal = actions.evict(args) + if (!removal) { + return + } + await intent.wait(removal) + if (!valid() || !(await hostAvailable()) || !valid()) { + return + } + reused = actions.reuse(args, intent.kind) + if (reused) { + intent.release() + return reused + } + } + intent.release() + return actions.start(args, intent.kind) +} diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-discard-retry.ts b/src/main/workspaces/creation/preparation/worktree-preparation-discard-retry.ts index c8b65032454..0ce0d4b20db 100644 --- a/src/main/workspaces/creation/preparation/worktree-preparation-discard-retry.ts +++ b/src/main/workspaces/creation/preparation/worktree-preparation-discard-retry.ts @@ -1,101 +1,88 @@ -import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' -import { discardPreparedWorktree } from '../../../git/worktrees/creation/worktree-create-preparation' -import { WorktreePreparationLockOwnershipError } from '../../../git/worktrees/creation/worktree-preparation-lock' -import { isOrphanedWorktreeError } from '../../../ipc/worktree-logic' +import { worktreePreparationGit } from '../../../git/worktrees/creation/worktree-create-git-executor' import { trackPreparationWork } from '../worktree-create-concurrency' -import type { WorktreePreparationOperation } from '../../../git/worktrees/creation/worktree-preparation-operation' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' import type { PreparationEntry } from './worktree-create-preparation-pool' -// Retry live-owner discard failures on later preparations; stale cleanup only reclaims dead owners. -const PREPARATION_DISCARD_ATTEMPT_LIMIT = 3 - -export type PreparationDiscardTarget = { - hostKey: string - repoPath: string - preparedPath: string - lockReason: string - options: AddWorktreeOptions - operation?: WorktreePreparationOperation -} - -const pendingDiscards = new Map() +const obligations = new Map() const inFlightDiscards = new Set>() export function preparationHostKey(repoPathKey: string, wslDistro: string): string { return `${repoPathKey}\0${wslDistro}` } +function obligationKey(entry: PreparationEntry): string { + return `${preparationHostKey(entry.repoPathKey, entry.wslDistro)}\0${entry.preparedPath}` +} + +export function preparationCapacityUsed(): number { + return obligations.size +} + +export function registerPreparationObligation(entry: PreparationEntry): void { + const key = obligationKey(entry) + obligations.set(key, entry) + entry.operation.setDisposalOwner({ + current: () => obligations.get(key) === entry, + before: async () => !(await blockedWslDistroForPath(entry.repoPath, entry.options.wslDistro)), + schedule: (run) => { + const work = trackPreparationWork(worktreePreparationGit.run(run)) + trackPreparationDiscard(work) + return work + }, + disposed: () => { + if (obligations.get(key) === entry) { + obligations.delete(key) + } + } + }) +} + +export function releasePreparationObligation(entry: PreparationEntry): void { + const key = obligationKey(entry) + if (obligations.get(key) !== entry) { + return + } + obligations.delete(key) + entry.operation.release() +} + export async function discardPreparationEntry(entry: PreparationEntry): Promise { if (!entry.checkoutStarted) { return } - // Claim cleanup before yielding so queued refresh failures cannot discard the same checkout. + // Claim submission before yielding; the capacity owner survives this claim. entry.checkoutStarted = false - await discardPreparationWithRetry({ - hostKey: preparationHostKey(entry.repoPathKey, entry.wslDistro), - repoPath: entry.repoPath, - preparedPath: entry.preparedPath, - lockReason: entry.lockReason, - options: entry.options, - operation: entry.operation - }) -} - -/** Let test reset await detached discards before clearing the registry. */ -export function trackPreparationDiscard(work: Promise): void { - inFlightDiscards.add(work) - void work.finally(() => inFlightDiscards.delete(work)) -} - -function pendingKey(target: PreparationDiscardTarget): string { - return `${target.hostKey}\0${target.preparedPath}` -} - -async function runDiscard(target: PreparationDiscardTarget, attempts: number): Promise { - try { - const discard = (options: AddWorktreeOptions): Promise => - discardPreparedWorktree(target.repoPath, target.preparedPath, options, target.lockReason) - await (target.operation ? target.operation.discard() : discard(target.options)) - } catch (error) { - // Checkout failure may already have removed the registration; do not retry missing or foreign entries. - if (error instanceof WorktreePreparationLockOwnershipError || isOrphanedWorktreeError(error)) { - return - } - // Bounded: a path that never becomes removable must not tax every later preparation. - if (attempts >= PREPARATION_DISCARD_ATTEMPT_LIMIT) { - console.warn( - `[worktree-create] prepared checkout could not be discarded in ${attempts} attempts; ${target.preparedPath} stays registered until this process exits`, - error - ) - return - } - pendingDiscards.set(pendingKey(target), { ...target, attempts }) + if (obligations.get(obligationKey(entry)) === entry) { + await entry.operation.discard() } } -/** Record failed discards for bounded retries. */ -export function discardPreparationWithRetry( - target: PreparationDiscardTarget, - attempts = 1 -): Promise { - // Claim the record so an overlapping retry pass cannot run the same discard twice. - pendingDiscards.delete(pendingKey(target)) - const discard = trackPreparationWork(runDiscard(target, attempts)) - trackPreparationDiscard(discard) - return discard +export function trackPreparationDiscard(work: Promise): void { + inFlightDiscards.add(work) + void work.then( + () => inFlightDiscards.delete(work), + () => inFlightDiscards.delete(work) + ) } -export function retryPendingPreparationDiscards(hostKey: string): Promise { - const pending = [...pendingDiscards.values()].filter((target) => target.hostKey === hostKey) +export function retryPendingPreparationDiscards(hostKey?: string): Promise { return Promise.all( - pending.map(({ attempts, ...target }) => discardPreparationWithRetry(target, attempts + 1)) + [...obligations.values()] + .filter( + (entry) => + entry.operation.needsDiscardRetry && + (!hostKey || preparationHostKey(entry.repoPathKey, entry.wslDistro) === hostKey) + ) + .map((entry) => entry.operation.discard()) ).then(() => undefined) } -/** Settle background discards before clearing their registry. */ export async function resetPendingPreparationDiscardsForTests(): Promise { while (inFlightDiscards.size > 0) { - await Promise.all(inFlightDiscards) + await Promise.allSettled(inFlightDiscards) } - pendingDiscards.clear() + for (const entry of obligations.values()) { + entry.operation.release() + } + obligations.clear() } diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-fetch-barrier.test.ts b/src/main/workspaces/creation/preparation/worktree-preparation-fetch-barrier.test.ts index 13f9e2e4e5c..2cc102b5fe1 100644 --- a/src/main/workspaces/creation/preparation/worktree-preparation-fetch-barrier.test.ts +++ b/src/main/workspaces/creation/preparation/worktree-preparation-fetch-barrier.test.ts @@ -81,7 +81,8 @@ describe('prepared checkout shared fetch barrier', () => { repo.path, entry.preparedPath, expect.objectContaining({ signal: undefined }), - entry.lockReason + entry.lockReason, + null ) expect(listPreparations()).toEqual([]) } finally { diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-lifetime-real-git.test.ts b/src/main/workspaces/creation/preparation/worktree-preparation-lifetime-real-git.test.ts index 029738ac333..f8d573bfac3 100644 --- a/src/main/workspaces/creation/preparation/worktree-preparation-lifetime-real-git.test.ts +++ b/src/main/workspaces/creation/preparation/worktree-preparation-lifetime-real-git.test.ts @@ -1,13 +1,17 @@ -import { execFileSync } from 'node:child_process' +import { fixture, git, removeLifetimeFixtures } from './worktree-preparation-lifetime.test-fixture' +import type * as FilePromises from 'node:fs/promises' +import { toHostFilesystemPath } from '../../../filesystem/host-tree-removal' +import * as gitReadCache from '../../../git/source-control/git-read-cache-invalidation' +import * as gitAdmin from '../../../../shared/git/metadata/git-common-directory' +import { preparationPathKey } from './worktree-create-preparation-claim' +import * as staleCleanup from './worktree-create-preparation-stale-cleanup' import { existsSync } from 'node:fs' -import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import type { RuntimeStore } from '../../../runtime/construction/runtime-store-contract' -import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' +import * as wslGate from '../../../wsl/filesystem/wsl-unc-access-gate' +import { preparationCapacityUsed } from './worktree-preparation-discard-retry' import * as gitRunner from '../../../git/command-runner/git-exec-file' -import { createRuntimeLocalGitWorktree } from '../../../runtime/workspaces/creation/runtime-local-git-worktree-create' import { createWorktreeCreateTimingRecorder } from '../worktree-create-timing' import { _resetWorktreeCreatePreparationsForTests } from './worktree-create-preparation' import { @@ -16,94 +20,29 @@ import { startPreparation } from './worktree-create-preparation-pool' -const roots: string[] = [] -function git(cwd: string, ...args: string[]): string { - return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: 'pipe' }).trim() -} - -async function fixture() { - const root = await realpath(await mkdtemp(join(tmpdir(), 'orca-preparation-lifetime-'))) - roots.push(root) - const repoPath = join(root, 'repo') - execFileSync('git', ['init', '--quiet', repoPath]) - git(repoPath, 'symbolic-ref', 'HEAD', 'refs/heads/main') - git(repoPath, 'config', 'user.email', 'test@example.com') - git(repoPath, 'config', 'user.name', 'Test User') - git(repoPath, 'config', 'core.autocrlf', 'false') - await writeFile(join(repoPath, 'version.txt'), 'original\n') - git(repoPath, 'add', '.') - git(repoPath, 'commit', '--quiet', '-m', 'initial') - const repo = { - id: 'lifetime-repo', - path: repoPath, - displayName: 'Repo', - addedAt: 0, - badgeColor: '' - } - const arm = ( - beforeMaterialization?: Promise, - options: AddWorktreeOptions = {}, - baseBranch = 'main' - ) => - startPreparation({ - repoPath, - workspaceRoot: root, - baseBranch, - canonicalBase: baseBranch === 'origin/main' ? 'refs/remotes/origin/main' : 'refs/heads/main', - options, - beforeMaterialization - }) - const create = async ( - branch: string, - baseBranch = 'main', - options: AddWorktreeOptions = {}, - waiting?: () => void, - timing = createWorktreeCreateTimingRecorder() - ) => { - const time = timing.time.bind(timing) - timing.time = (phase, operation) => { - if (phase === 'prepared_checkout_wait') { - waiting?.() +const rootMkdirFailure = vi.hoisted((): { path?: string } => ({})) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + mkdir: (...args: Parameters) => { + if (String(args[0]) === rootMkdirFailure.path) { + return Promise.reject( + Object.assign(new Error('read-only workspace root'), { code: 'EACCES' }) + ) } - return time(phase, operation) - } - const rearm = { fire: () => {} } - try { - return await createRuntimeLocalGitWorktree({ - request: { repoSelector: repo.id, name: branch }, - repo, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: no metadata/push/name-retirement operation is requested at this Git-only host boundary. - store: {} as RuntimeStore, - settings: { - workspaceDir: root, - nestWorkspaces: false, - refreshLocalBaseRefOnWorktreeCreate: false - }, - base: { baseBranch, remoteTrackingBase: null, deferredRefresh: null }, - workspaceRoot: root, - branchName: branch, - worktreePath: join(root, branch), - checkoutExistingBranch: false, - localWorktreeGitOptions: options, - // Foreground freshness already completed; the obsolete speculative barrier is independent. - baseRefRefresh: { finish: async () => {} }, - rearm, - timing - }) - } finally { - timing.finish() - rearm.fire() + return actual.mkdir(...args) } } - return { root, repoPath, arm, create } -} +}) afterEach(async () => { vi.useRealTimers() vi.restoreAllMocks() + rootMkdirFailure.path = undefined vi.unstubAllEnvs() await _resetWorktreeCreatePreparationsForTests() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) + await removeLifetimeFixtures() }) it.each(['initial', 'queued'])( @@ -203,7 +142,7 @@ it('propagates caller cancellation without falling back to a phantom worktree', expect(await readFile(join(root, 'after-cancel', 'version.txt'), 'utf8')).toBe('original\n') }) -it('keeps a locked artifact after writer termination cannot be verified, even when proof arrives late', async () => { +it('parks an unproven writer and autonomously removes its hidden checkout after late proof', async () => { const { root, arm, create } = await fixture() const failed = Promise.withResolvers() const started = Promise.withResolvers() @@ -230,27 +169,32 @@ it('keeps a locked artifact after writer termination cannot be verified, even wh await creation await preparation await vi.advanceTimersByTimeAsync(30_000) + expect(existsSync(join(preparedPath, '.git'))).toBe(true) + // Repeated requests cannot revive or wait again on the same parked writer. + await arm() + await arm() terminated.resolve() + await vi.waitFor(() => expect(existsSync(preparedPath)).toBe(false)) await create('after-writer') expect(await readFile(join(root, 'writer-fallback', 'version.txt'), 'utf8')).toBe('original\n') - expect(existsSync(join(preparedPath, '.git'))).toBe(true) - expect(existsSync(join(preparedPath, 'version.txt'))).toBe(false) - expect(git(preparedPath, 'worktree', 'list', '--porcelain')).toContain( - 'locked orca-create-preparation:' + expect(git(root, '-C', join(root, 'repo'), 'worktree', 'list', '--porcelain')).not.toContain( + preparedPath ) }) -it('never spawns a destructive remove queued beyond retirement abandonment', async () => { +it('revokes an expired queued remove and admits fresh owned cleanup on its exact wake', async () => { const { repoPath, arm, create } = await fixture() const queued = Promise.withResolvers() const admitted = Promise.withResolvers() const attempted = Promise.withResolvers() + let first = true vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) await arm() const [entry] = listPreparations() const run = gitRunner.gitExecFileAsync vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { - if (args.includes('remove')) { + if (args.includes('remove') && first) { + first = false queued.resolve() await admitted.promise try { @@ -266,7 +210,523 @@ it('never spawns a destructive remove queued beyond retirement abandonment', asy await vi.advanceTimersByTimeAsync(30_000) admitted.resolve() await attempted.promise + await vi.waitFor(() => expect(existsSync(entry.preparedPath)).toBe(false)) await create('after-abandoned-discard') - expect(await readFile(join(entry.preparedPath, 'version.txt'), 'utf8')).toBe('original\n') - expect(git(repoPath, 'worktree', 'list', '--porcelain')).toContain(entry.lockReason) + expect(git(repoPath, 'worktree', 'list', '--porcelain')).not.toContain(entry.lockReason) }) + +it.each([3, 30])( + 'bounds physical preparations under %i requests while cleanup is exhausted', + async (requests) => { + const owners = await Promise.all([fixture(), fixture(), fixture()]) + for (const owner of owners) { + await owner.arm() + } + const entries = listPreparations() + const run = gitRunner.gitExecFileAsync + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args.includes('remove')) { + throw new Error('checkout temporarily locked') + } + return run(args, options) + }) + for (const entry of entries) { + discardRepoPreparations(entry.repoPathKey) + } + const other = await fixture() + for (let index = 0; index < requests; index += 1) { + await other.arm() + } + expect( + entries.filter((entry) => existsSync(join(entry.preparedPath, 'version.txt'))) + ).toHaveLength(3) + expect(listPreparations()).toHaveLength(0) + await other.create('normal-create') + expect(await readFile(join(other.root, 'normal-create', 'version.txt'), 'utf8')).toBe( + 'original\n' + ) + } +) + +it('retries another repository before declining a full-pool request', async () => { + const owners = await Promise.all([fixture(), fixture(), fixture()]) + for (const owner of owners) { + await owner.arm() + } + const entries = listPreparations() + const run = gitRunner.gitExecFileAsync + let fail = true + const failed = Promise.withResolvers() + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args.includes('remove') && fail) { + failed.resolve() + throw new Error('transient checkout lock') + } + return run(args, options) + }) + discardRepoPreparations(entries[0].repoPathKey) + await failed.promise + await entries[0].operation.discard() + fail = false + const other = await fixture() + await other.arm() + expect(existsSync(entries[0].preparedPath)).toBe(false) + expect(listPreparations().some((entry) => entry.repoPath === other.repoPath)).toBe(true) +}) + +it.each(['hidden', 'moved', 'unproven-target'])( + 'preserves finalization recovery for %s failure through the create consumer', + async (kind) => { + const { root, repoPath, arm, create } = await fixture() + await arm() + const [entry] = listPreparations() + if (kind === 'hidden') { + await writeFile(join(repoPath, 'version.txt'), 'requested\n') + git(repoPath, 'commit', '--quiet', '-am', 'new base') + } + const target = join(root, 'finalization-recovery') + const proof = Promise.withResolvers() + const failed = Promise.withResolvers() + const originalError = new Error('prepared finalization failed') + const run = gitRunner.gitExecFileAsync + let injected = false + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + const selected = + kind === 'hidden' + ? args.includes('reset') + : kind === 'moved' + ? args.includes('checkout') + : args.includes('move') + if (selected && !injected) { + injected = true + if (kind !== 'moved') { + options.observeChildTermination?.(proof.promise, true) + } + if (kind !== 'hidden') { + await run(args, options) + } + failed.resolve() + throw originalError + } + return run(args, options) + }) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + const creating = create('finalization-recovery') + const outcome = + kind === 'unproven-target' ? expect(creating).rejects.toBe(originalError) : creating + await failed.promise + if (kind !== 'moved') { + await vi.advanceTimersByTimeAsync(30_000) + } + await outcome + if (kind === 'moved') { + expect(await readFile(join(target, 'version.txt'), 'utf8')).toBe('original\n') + expect(git(target, 'branch', '--show-current')).toBe('finalization-recovery') + } else { + if (kind === 'unproven-target') { + expect(git(repoPath, 'branch', '--list', 'finalization-recovery')).toBe('') + } else { + expect(await readFile(join(target, 'version.txt'), 'utf8')).toBe('requested\n') + expect(existsSync(entry.preparedPath)).toBe(true) + } + proof.resolve() + if (kind === 'hidden') { + await vi.waitFor(() => expect(existsSync(entry.preparedPath)).toBe(false)) + } else { + await writeFile(join(target, 'user.txt'), 'preserve returned target\n') + await arm() + expect(await readFile(join(target, 'user.txt'), 'utf8')).toBe('preserve returned target\n') + } + } + } +) + +it.each(['missing', 'foreign', 'unregistered'])( + 'retains unknown capacity but releases affirmative %s authority', + async (kind) => { + const { arm } = await fixture() + await arm() + const [entry] = listPreparations() + const lock = git(entry.preparedPath, 'rev-parse', '--git-path', 'locked') + await (kind === 'foreign' + ? writeFile(lock, 'replacement owner\n') + : rm(kind === 'unregistered' ? dirname(lock) : lock, { recursive: true })) + discardRepoPreparations(entry.repoPathKey) + await entry.operation.discard() + expect(existsSync(join(entry.preparedPath, 'version.txt'))).toBe(true) + expect(preparationCapacityUsed()).toBe(kind === 'foreign' ? 0 : 1) + } +) + +it('leaves stopped hosts untouched and retries only after the host becomes eligible', async () => { + const { arm } = await fixture() + await arm() + const [entry] = listPreparations() + const blocked = vi + .spyOn(wslGate, 'blockedWslDistroForPath') + .mockResolvedValue({ distro: 'stopped', state: 'stopped' }) + discardRepoPreparations(entry.repoPathKey) + await entry.operation.discard() + expect(existsSync(join(entry.preparedPath, 'version.txt'))).toBe(true) + await arm() + expect(existsSync(entry.preparedPath)).toBe(true) + blocked.mockResolvedValue(null) + await arm() + await vi.waitFor(() => expect(existsSync(entry.preparedPath)).toBe(false)) +}) + +it('releases exhausted capacity when the final admitted removal completes late', async () => { + const { arm } = await fixture() + await arm() + const [entry] = listPreparations() + const run = gitRunner.gitExecFileAsync + const admitted = Promise.withResolvers() + const proof = Promise.withResolvers() + let failures = 0 + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args.includes('remove')) { + if (failures++ < 2) { + throw new Error('temporary file lock') + } + const result = await run(args, options) + options.observeChildTermination?.(proof.promise, true) + admitted.resolve() + return result + } + return run(args, options) + }) + discardRepoPreparations(entry.repoPathKey) + await entry.operation.discard() + await entry.operation.discard() + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + const cleanup = entry.operation.discard() + await admitted.promise + await vi.advanceTimersByTimeAsync(30_000) + await cleanup + expect(preparationCapacityUsed()).toBe(1) + proof.resolve() + await vi.waitFor(() => expect(preparationCapacityUsed()).toBe(0)) +}) + +it('coalesces healthy fourth-key admission until eviction is proven, then consumes its requested tip', async () => { + const owners = await Promise.all([fixture(), fixture(), fixture()]) + for (const owner of owners) { + await owner.arm() + } + const entries = listPreparations() + const fourth = await fixture() + const removing = Promise.withResolvers() + const proof = Promise.withResolvers() + const obsoleteFetch = Promise.withResolvers() + const run = gitRunner.gitExecFileAsync + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { + if (args.includes('remove') && options.cwd === owners[0].repoPath) { + removing.resolve() + return run(args, { + ...options, + observeChildTermination: (terminated, writes) => + options.observeChildTermination?.( + writes ? Promise.all([terminated, proof.promise]).then(() => {}) : terminated, + writes + ) + }) + } + return run(args, options) + }) + const first = startPreparation( + { + repoPath: fourth.repoPath, + workspaceRoot: fourth.root, + baseBranch: 'main', + canonicalBase: 'refs/heads/main', + options: {}, + beforeMaterialization: obsoleteFetch.promise + }, + 'automatic' + ) + try { + await removing.promise + const joined = fourth.arm(Promise.resolve()) + expect(preparationCapacityUsed()).toBe(3) + expect(listPreparations().map((entry) => entry.preparedPath)).toEqual( + entries.slice(1).map((entry) => entry.preparedPath) + ) + proof.resolve() + await Promise.all([first, joined]) + expect(listPreparations()).toHaveLength(3) + const timing = createWorktreeCreateTimingRecorder() + await fourth.create('fourth-hit', 'main', {}, undefined, timing) + expect(timing.finish().preparedCheckout).toMatchObject({ status: 'hit', origin: 'prefetch' }) + expect(git(join(fourth.root, 'fourth-hit'), 'branch', '--show-current')).toBe('fourth-hit') + expect(await readFile(join(fourth.root, 'fourth-hit', 'version.txt'), 'utf8')).toBe( + 'original\n' + ) + } finally { + proof.resolve() + obsoleteFetch.resolve() + await first.catch(() => {}) + } +}) + +it('admits with free capacity and reuses an exact full-pool hit while matching cleanup is pending', async () => { + const owner = await fixture() + git(owner.repoPath, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await owner.arm() + const [retired] = listPreparations() + const failed = Promise.withResolvers() + const second = Promise.withResolvers() + const releaseSecond = Promise.withResolvers() + const third = Promise.withResolvers() + const releaseThird = Promise.withResolvers() + const run = gitRunner.gitExecFileAsync + let attempt = 0 + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args.includes('remove') && options.cwd === owner.repoPath) { + attempt += 1 + if (attempt === 1) { + failed.resolve() + throw new Error('transient checkout lock') + } + if (attempt === 2) { + second.resolve() + await releaseSecond.promise + throw new Error('still locked') + } + third.resolve() + await releaseThird.promise + } + return run(args, options) + }) + try { + discardRepoPreparations(retired.repoPathKey) + await failed.promise + await retired.operation.discard() + const free = owner.arm(undefined, {}, 'origin/main') + await second.promise + await free + const other = await fixture() + await other.arm() + expect(preparationCapacityUsed()).toBe(3) + releaseSecond.resolve() + await retired.operation.discard() + const exact = owner.arm(undefined, {}, 'origin/main') + await third.promise + await exact + const timing = createWorktreeCreateTimingRecorder() + await owner.create('retry-isolated', 'origin/main', {}, undefined, timing) + expect(timing.finish().preparedCheckout?.status).toBe('hit') + expect(await readFile(join(owner.root, 'retry-isolated', 'version.txt'), 'utf8')).toBe( + 'original\n' + ) + } finally { + releaseSecond.resolve() + releaseThird.resolve() + } +}) + +it.each(['removed', 'canceled'])( + 'does not publish an admission invalidated while %s', + async (kind) => { + const owners = await Promise.all([fixture(), fixture(), fixture()]) + for (const owner of owners) { + await owner.arm() + } + const fourth = await fixture() + const removing = Promise.withResolvers() + const proof = Promise.withResolvers() + const run = gitRunner.gitExecFileAsync + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { + if (args.includes('remove') && options.cwd === owners[0].repoPath) { + removing.resolve() + return run(args, { + ...options, + observeChildTermination: (terminated, writes) => + options.observeChildTermination?.( + writes ? Promise.all([terminated, proof.promise]).then(() => {}) : terminated, + writes + ) + }) + } + return run(args, options) + }) + const controller = new AbortController() + const pending = fourth.arm(undefined, { signal: controller.signal }) + try { + await removing.promise + if (kind === 'removed') { + discardRepoPreparations(preparationPathKey(fourth.repoPath)) + } else { + controller.abort() + } + await pending + await fourth.create('foreground-during-cleanup') + expect( + await readFile(join(fourth.root, 'foreground-during-cleanup', 'version.txt'), 'utf8') + ).toBe('original\n') + proof.resolve() + await owners[0].arm() + expect(listPreparations().some((entry) => entry.repoPath === fourth.repoPath)).toBe(false) + } finally { + proof.resolve() + controller.abort() + await pending.catch(() => {}) + } + } +) + +it('bounds distinct capacity waiters while allowing three requests to recover', async () => { + const owners = await Promise.all([fixture(), fixture(), fixture()]) + for (const owner of owners) { + await owner.arm() + } + const request = await fixture() + const proof = Promise.withResolvers() + const removing = Promise.withResolvers() + const run = gitRunner.gitExecFileAsync + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { + if (args.includes('remove')) { + removing.resolve() + return run(args, { + ...options, + observeChildTermination: (terminated, writes) => + options.observeChildTermination?.( + writes ? Promise.all([terminated, proof.promise]).then(() => {}) : terminated, + writes + ) + }) + } + return run(args, options) + }) + const roots = Array.from({ length: 30 }, (_, index) => join(request.root, `request-${index}`)) + const pending = roots.map((workspaceRoot) => + startPreparation({ + repoPath: request.repoPath, + workspaceRoot, + baseBranch: 'main', + canonicalBase: 'refs/heads/main', + options: {} + }) + ) + try { + await removing.promise + await Promise.all(pending.slice(3)) + expect(preparationCapacityUsed()).toBe(3) + expect(roots.slice(3).some((root) => existsSync(root))).toBe(false) + proof.resolve() + await Promise.all(pending) + expect(preparationCapacityUsed()).toBe(3) + expect( + listPreparations() + .map((entry) => entry.workspaceRoot) + .sort() + ).toEqual(roots.slice(0, 3).sort()) + expect(roots.slice(3).some((root) => existsSync(root))).toBe(false) + } finally { + proof.resolve() + await Promise.allSettled(pending) + } +}) + +it('declines after a competing request takes the freed slot without evicting another victim', async () => { + const owners = await Promise.all([fixture(), fixture(), fixture()]) + for (const owner of owners) { + await owner.arm() + } + const entries = listPreparations() + const fourth = await fixture() + const competitor = await fixture() + const validating = Promise.withResolvers() + const release = Promise.withResolvers() + let checks = 0 + const gate = wslGate.blockedWslDistroForPath + vi.spyOn(wslGate, 'blockedWslDistroForPath').mockImplementation(async (path, distro, options) => { + if (path === fourth.repoPath && ++checks === 2) { + validating.resolve() + await release.promise + } + return gate(path, distro, options) + }) + const pending = fourth.arm() + try { + await validating.promise + await competitor.arm() + release.resolve() + await pending + expect(preparationCapacityUsed()).toBe(3) + expect(entries.slice(1).every((entry) => existsSync(entry.preparedPath))).toBe(true) + expect(listPreparations().some((entry) => entry.repoPath === fourth.repoPath)).toBe(false) + await fourth.create('competing-fallback') + expect(await readFile(join(fourth.root, 'competing-fallback', 'version.txt'), 'utf8')).toBe( + 'original\n' + ) + } finally { + release.resolve() + await pending.catch(() => {}) + } +}) + +it.each([750, 7500])( + 'avoids cleanup reconciliation of %i unrelated registrations when no add was issued', + async (width) => { + const owner = await fixture() + await owner.arm() + const [primer] = listPreparations() + discardRepoPreparations(primer.repoPathKey) + await primer.operation.discard() + const adminRoot = join(owner.repoPath, '.git', 'worktrees') + const head = git(owner.repoPath, 'rev-parse', 'HEAD') + for (let index = 0; index < width; index += 1) { + const admin = join(adminRoot, `unrelated-${index}`) + await mkdir(admin, { recursive: true }) + await writeFile(join(admin, 'gitdir'), `${join(owner.root, `unrelated-${index}`, '.git')}\n`) + await writeFile(join(admin, 'commondir'), '../..\n') + await writeFile(join(admin, 'HEAD'), `${head}\n`) + } + const blockedRoot = join(owner.root, 'read-only-root') + rootMkdirFailure.path = toHostFilesystemPath(join(blockedRoot, '.orca-preparing')) + const read = gitAdmin.readGitAdminFile + let unrelatedReads = 0 + vi.spyOn(gitAdmin, 'readGitAdminFile').mockImplementation((path, signal) => { + if (path.startsWith(join(adminRoot, 'unrelated-')) && path.endsWith('gitdir')) { + unrelatedReads += 1 + } + return read(path, signal) + }) + const invalidations = vi.spyOn(gitReadCache, 'runWithGitReadCacheInvalidation') + const lookups = vi.spyOn(gitRunner, 'gitExecFileAsync') + const staleScan = vi.spyOn(staleCleanup, 'startStalePreparationCleanup').mockResolvedValue() + for (let request = 0; request < 3; request += 1) { + await expect( + startPreparation({ + repoPath: owner.repoPath, + workspaceRoot: blockedRoot, + baseBranch: 'main', + canonicalBase: 'refs/heads/main', + options: {} + }) + ).rejects.toMatchObject({ code: 'EACCES' }) + await vi.waitFor(() => expect(preparationCapacityUsed()).toBe(0)) + } + expect(unrelatedReads).toBe(0) + expect(invalidations).not.toHaveBeenCalled() + expect(lookups).not.toHaveBeenCalled() + lookups.mockRestore() + staleScan.mockRestore() + const run = gitRunner.gitExecFileAsync + let issuedOperation: typeof primer.operation | undefined + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + const result = await run(args, options) + if (args.includes('add') && args.includes('--no-checkout')) { + issuedOperation = listPreparations()[0].operation + await rm(args.at(-2)!, { recursive: true, force: true }) + throw new Error('issued add lost its public result') + } + return result + }) + await expect(owner.arm()).rejects.toThrow('issued add lost its public result') + expect(issuedOperation).toBeDefined() + await issuedOperation!.discard() + expect(preparationCapacityUsed()).toBe(0) + expect(unrelatedReads).toBe(width) + } +) diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-lifetime.test-fixture.ts b/src/main/workspaces/creation/preparation/worktree-preparation-lifetime.test-fixture.ts new file mode 100644 index 00000000000..4b3d9e22ade --- /dev/null +++ b/src/main/workspaces/creation/preparation/worktree-preparation-lifetime.test-fixture.ts @@ -0,0 +1,95 @@ +import { execFileSync } from 'node:child_process' +import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { RuntimeStore } from '../../../runtime/construction/runtime-store-contract' +import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' +import { createRuntimeLocalGitWorktree } from '../../../runtime/workspaces/creation/runtime-local-git-worktree-create' +import { createWorktreeCreateTimingRecorder } from '../worktree-create-timing' +import { startPreparation } from './worktree-create-preparation-pool' + +const roots: string[] = [] +export function git(cwd: string, ...args: string[]): string { + return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: 'pipe' }).trim() +} + +export async function fixture() { + const root = await realpath(await mkdtemp(join(tmpdir(), 'orca-preparation-lifetime-'))) + roots.push(root) + const repoPath = join(root, 'repo') + execFileSync('git', ['init', '--quiet', repoPath]) + git(repoPath, 'symbolic-ref', 'HEAD', 'refs/heads/main') + git(repoPath, 'config', 'user.email', 'test@example.com') + git(repoPath, 'config', 'user.name', 'Test User') + git(repoPath, 'config', 'core.autocrlf', 'false') + await writeFile(join(repoPath, 'version.txt'), 'original\n') + git(repoPath, 'add', '.') + git(repoPath, 'commit', '--quiet', '-m', 'initial') + const repo = { + id: 'lifetime-repo', + path: repoPath, + displayName: 'Repo', + addedAt: 0, + badgeColor: '' + } + const arm = ( + beforeMaterialization?: Promise, + options: AddWorktreeOptions = {}, + baseBranch = 'main' + ) => + startPreparation({ + repoPath, + workspaceRoot: root, + baseBranch, + canonicalBase: baseBranch === 'origin/main' ? 'refs/remotes/origin/main' : 'refs/heads/main', + options, + beforeMaterialization + }) + const create = async ( + branch: string, + baseBranch = 'main', + options: AddWorktreeOptions = {}, + waiting?: () => void, + timing = createWorktreeCreateTimingRecorder() + ) => { + const time = timing.time.bind(timing) + timing.time = (phase, operation) => { + if (phase === 'prepared_checkout_wait') { + waiting?.() + } + return time(phase, operation) + } + const rearm = { fire: () => {} } + try { + return await createRuntimeLocalGitWorktree({ + request: { repoSelector: repo.id, name: branch }, + repo, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: no metadata/push/name-retirement operation is requested at this Git-only host boundary. + store: {} as RuntimeStore, + settings: { + workspaceDir: root, + nestWorkspaces: false, + refreshLocalBaseRefOnWorktreeCreate: false + }, + base: { baseBranch, remoteTrackingBase: null, deferredRefresh: null }, + workspaceRoot: root, + branchName: branch, + worktreePath: join(root, branch), + checkoutExistingBranch: false, + localWorktreeGitOptions: options, + // Foreground freshness already completed; the obsolete speculative barrier is independent. + baseRefRefresh: { finish: async () => {} }, + rearm, + timing + }) + } finally { + timing.finish() + rearm.fire() + } + } + return { root, repoPath, arm, create } +} + +export async function removeLifetimeFixtures(): Promise { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +} diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-maintenance-real-git.test.ts b/src/main/workspaces/creation/preparation/worktree-preparation-maintenance-real-git.test.ts new file mode 100644 index 00000000000..8b873d66d16 --- /dev/null +++ b/src/main/workspaces/creation/preparation/worktree-preparation-maintenance-real-git.test.ts @@ -0,0 +1,203 @@ +import type * as FilePromises from 'node:fs/promises' +import { existsSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import * as gitRunner from '../../../git/command-runner/git-exec-file' +import { toHostFilesystemPath } from '../../../filesystem/host-tree-removal' +import { preparationCapacityUsed } from './worktree-preparation-discard-retry' +import { _resetWorktreeCreatePreparationsForTests } from './worktree-create-preparation' +import { discardRepoPreparations, listPreparations } from './worktree-create-preparation-pool' +import { fixture, git, removeLifetimeFixtures } from './worktree-preparation-lifetime.test-fixture' +import { + _resetLocalRepoRefMaintenanceForTests, + createLocalRepoRefMaintenanceTarget, + getLocalRepoRefMaintenance +} from '../../../git/refs/maintenance/local-repo-ref-maintenance' + +const identityRead = vi.hoisted( + (): { path?: string; started?: () => void; resume?: Promise } => ({}) +) +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + realpath: async (...args: Parameters) => { + if (String(args[0]) === identityRead.path) { + identityRead.path = undefined + identityRead.started?.() + await identityRead.resume + } + return actual.realpath(...args) + } + } +}) + +afterEach(async () => { + vi.useRealTimers() + vi.restoreAllMocks() + identityRead.path = undefined + identityRead.started = undefined + identityRead.resume = undefined + await _resetWorktreeCreatePreparationsForTests() + _resetLocalRepoRefMaintenanceForTests() + await removeLifetimeFixtures() +}) + +async function attemptMaintenance(repoPath: string): Promise { + const maintenance = getLocalRepoRefMaintenance() + maintenance.arm(createLocalRepoRefMaintenanceTarget({ key: repoPath, repoPath })) + await vi.advanceTimersByTimeAsync(1000) + await maintenance.whenAttemptSettled() +} + +function enableMaintenance(): void { + _resetLocalRepoRefMaintenanceForTests({ + isBusy: () => false, + quietPeriodMs: 1000, + looseRefThreshold: 1 + }) +} + +it('retires a parked identity-read lease, then removes only through its fresh native-settlement wake', async () => { + const { repoPath, arm, create } = await fixture() + const other = await fixture() + await arm() + const [entry] = listPreparations() + const lock = git(entry.preparedPath, 'rev-parse', '--git-path', 'locked') + const readStarted = Promise.withResolvers() + const readReleased = Promise.withResolvers() + identityRead.path = dirname(toHostFilesystemPath(lock)) + identityRead.started = readStarted.resolve + identityRead.resume = readReleased.promise + const run = gitRunner.gitExecFileAsync + const removalPermissions: boolean[] = [] + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { + if (args.includes('remove')) { + removalPermissions.push(options.canStart?.() !== false) + } + return run(args, options) + }) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + enableMaintenance() + discardRepoPreparations(entry.repoPathKey) + await readStarted.promise + const disposal = entry.operation.discard() + try { + await vi.advanceTimersByTimeAsync(30_000) + await disposal + expect(preparationCapacityUsed()).toBe(1) + expect(existsSync(entry.preparedPath)).toBe(true) + await attemptMaintenance(other.repoPath) + expect(existsSync(join(other.repoPath, '.git', 'packed-refs'))).toBe(true) + await arm() + await arm() + expect(removalPermissions).toEqual([]) + readReleased.resolve() + await vi.waitFor(() => { + expect(existsSync(entry.preparedPath)).toBe(false) + expect(preparationCapacityUsed()).toBe(1) + }) + expect(removalPermissions).toEqual([true]) + expect(git(repoPath, 'worktree', 'list', '--porcelain')).not.toContain(entry.lockReason) + await create('after-read-lease') + expect(git(repoPath, 'show', 'after-read-lease:version.txt')).toBe('original') + } finally { + readReleased.resolve() + } +}) + +it('keeps original pause acquisition as its wake and never releases the successor lease', async () => { + const { arm } = await fixture() + const other = await fixture() + await arm() + const [entry] = listPreparations() + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + enableMaintenance() + const maintenance = getLocalRepoRefMaintenance() + const acquireLease = maintenance.pause.bind(maintenance) + const acquiring = Promise.withResolvers() + const acquired = Promise.withResolvers() + const successor = Promise.withResolvers() + const successorReady = Promise.withResolvers() + const releases: string[] = [] + vi.spyOn(maintenance, 'pause') + .mockImplementationOnce(async (reason) => { + const release = await acquireLease(reason) + acquired.resolve() + await acquiring.promise + return () => { + releases.push('old') + release() + } + }) + .mockImplementationOnce(async (reason) => { + const release = await acquireLease(reason) + successorReady.resolve() + await successor.promise + return release + }) + discardRepoPreparations(entry.repoPathKey) + await acquired.promise + const disposal = entry.operation.discard() + try { + await vi.advanceTimersByTimeAsync(30_000) + await disposal + expect(preparationCapacityUsed()).toBe(1) + expect(maintenance.pause).toHaveBeenCalledTimes(1) + expect(releases).toEqual([]) + acquiring.resolve() + await successorReady.promise + expect(releases).toEqual(['old']) + await attemptMaintenance(other.repoPath) + expect(existsSync(join(other.repoPath, '.git', 'packed-refs'))).toBe(false) + successor.resolve() + await vi.waitFor(() => { + expect(existsSync(entry.preparedPath)).toBe(false) + expect(preparationCapacityUsed()).toBe(0) + }) + await attemptMaintenance(other.repoPath) + expect(existsSync(join(other.repoPath, '.git', 'packed-refs'))).toBe(true) + } finally { + acquiring.resolve() + successor.resolve() + } +}) + +it('holds cleanup maintenance through a rejected writer until its actual termination receipt', async () => { + const { arm } = await fixture() + const other = await fixture() + await arm() + const [entry] = listPreparations() + const issued = Promise.withResolvers() + const terminated = Promise.withResolvers() + const run = gitRunner.gitExecFileAsync + let first = true + vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => { + if (args.includes('remove') && first) { + first = false + options.observeChildTermination?.(terminated.promise, true) + issued.resolve() + throw new Error('cleanup rejected before native termination') + } + return run(args, options) + }) + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + enableMaintenance() + discardRepoPreparations(entry.repoPathKey) + await issued.promise + try { + await vi.advanceTimersByTimeAsync(30_000) + await entry.operation.discard() + await attemptMaintenance(other.repoPath) + expect(existsSync(join(other.repoPath, '.git', 'packed-refs'))).toBe(false) + terminated.resolve() + await vi.waitFor(() => { + expect(existsSync(entry.preparedPath)).toBe(false) + expect(preparationCapacityUsed()).toBe(0) + }) + await attemptMaintenance(other.repoPath) + expect(existsSync(join(other.repoPath, '.git', 'packed-refs'))).toBe(true) + } finally { + terminated.resolve() + } +}) diff --git a/src/main/workspaces/creation/preparation/worktree-preparation-tip-refresh.test.ts b/src/main/workspaces/creation/preparation/worktree-preparation-tip-refresh.test.ts index c4ba7537a4e..ee20bbbd568 100644 --- a/src/main/workspaces/creation/preparation/worktree-preparation-tip-refresh.test.ts +++ b/src/main/workspaces/creation/preparation/worktree-preparation-tip-refresh.test.ts @@ -76,7 +76,8 @@ describe('prepared checkout tip refresh', () => { repo.path, entry.preparedPath, expect.anything(), - entry.lockReason + entry.lockReason, + null ) expect(listPreparations()).toEqual([]) } finally { @@ -111,7 +112,8 @@ describe('prepared checkout tip refresh', () => { repo.path, entry.preparedPath, expect.anything(), - entry.lockReason + entry.lockReason, + null ) }) diff --git a/src/renderer/src/app-shell/AppNotificationCards.tsx b/src/renderer/src/app-shell/AppNotificationCards.tsx index 3db3a25dfea..ea36809b65e 100644 --- a/src/renderer/src/app-shell/AppNotificationCards.tsx +++ b/src/renderer/src/app-shell/AppNotificationCards.tsx @@ -4,7 +4,6 @@ import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' import { CodexSharedSettingsNoticeCard } from '../components/CodexSharedSettingsNoticeCard' import { NotificationCardStack } from '../components/NotificationCardStack' import { StarNagCard } from '../components/StarNagCard' -import { SpeechModelUpdateCard } from '../components/dictation/SpeechModelUpdateCard' import { OverlayBoundary } from './app-root-surface-boundaries' const ChatUiHereCornerCard = lazy(() => @@ -60,9 +59,6 @@ export function AppNotificationCards({ - - - ) } diff --git a/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts b/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts index aeea8615dd1..566ec19a254 100644 --- a/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts +++ b/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts @@ -19,7 +19,7 @@ vi.mock('../components/tab-bar/terminal-tab-rename-request', () => ({ requestTerminalTabRename: mocks.requestTerminalTabRename })) -vi.mock('@/lib/floating-workspace-terminal-actions', () => ({ +vi.mock('@/components/floating-terminal/floating-workspace-terminal-actions', () => ({ isFloatingWorkspacePanelFocused: () => false })) diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index 064e4bc6865..f880e57a27b 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -1,6 +1,6 @@ import { canShowRightSidebarForView, canToggleRightSidebar } from '@/lib/right-sidebar-visibility' import { runBuiltInOrReplacement } from '@/lib/plugin-command-replacements' -import { isFloatingWorkspacePanelFocused } from '@/lib/floating-workspace-terminal-actions' +import { isFloatingWorkspacePanelFocused } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { hasVisibleOverlay } from '@/lib/visible-overlay' import { requestScrollToCurrentWorkspaceRevealAndRename } from '@/lib/scroll-to-current-workspace-status' import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord' diff --git a/src/renderer/src/lib/app-font-family.ts b/src/renderer/src/app-shell/appearance/app-font-family.ts similarity index 92% rename from src/renderer/src/lib/app-font-family.ts rename to src/renderer/src/app-shell/appearance/app-font-family.ts index 956f478e0c6..5444ea55e30 100644 --- a/src/renderer/src/lib/app-font-family.ts +++ b/src/renderer/src/app-shell/appearance/app-font-family.ts @@ -1,4 +1,4 @@ -import { DEFAULT_APP_FONT_FAMILY } from '../../../shared/constants' +import { DEFAULT_APP_FONT_FAMILY } from '../../../../shared/constants' const APP_FONT_FALLBACKS = [ DEFAULT_APP_FONT_FAMILY, diff --git a/src/renderer/src/lib/chat-selection-mix.ts b/src/renderer/src/app-shell/appearance/chat-selection-mix.ts similarity index 97% rename from src/renderer/src/lib/chat-selection-mix.ts rename to src/renderer/src/app-shell/appearance/chat-selection-mix.ts index 4e194f7f925..ac0ac4b7a05 100644 --- a/src/renderer/src/lib/chat-selection-mix.ts +++ b/src/renderer/src/app-shell/appearance/chat-selection-mix.ts @@ -1,6 +1,6 @@ import { MIN_TEXT_CONTRAST } from './plugin-theme-contrast-rules' import { browserColorProbe, paintedThemeColors, type ColorProbe } from './plugin-theme-tokens' -import { contrastRatio, mix, type Rgba } from '../../../shared/color/rgba-contrast' +import { contrastRatio, mix, type Rgba } from '../../../../shared/color/rgba-contrast' export const CHAT_SELECTION_MIX_TOKEN = '--chat-selection-mix' // Keep in sync with --chat-selection-mix in main.css: about as deep as the system highlight. diff --git a/src/renderer/src/lib/document-theme.ts b/src/renderer/src/app-shell/appearance/document-theme.ts similarity index 98% rename from src/renderer/src/lib/document-theme.ts rename to src/renderer/src/app-shell/appearance/document-theme.ts index bc776926310..f5d0fe509d6 100644 --- a/src/renderer/src/lib/document-theme.ts +++ b/src/renderer/src/app-shell/appearance/document-theme.ts @@ -1,8 +1,8 @@ -import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' import { PLUGIN_APP_THEME_TOKENS, type PluginThemeRegistration -} from '../../../shared/plugins/artifacts/plugin-theme-artifact' +} from '../../../../shared/plugins/artifacts/plugin-theme-artifact' import { browserColorProbe, HOST_PILL_OUTLINE_MIX_TOKEN, diff --git a/src/renderer/src/lib/left-sidebar-appearance.ts b/src/renderer/src/app-shell/appearance/left-sidebar-appearance.ts similarity index 92% rename from src/renderer/src/lib/left-sidebar-appearance.ts rename to src/renderer/src/app-shell/appearance/left-sidebar-appearance.ts index 169dd101973..ebb0dd37e7e 100644 --- a/src/renderer/src/lib/left-sidebar-appearance.ts +++ b/src/renderer/src/app-shell/appearance/left-sidebar-appearance.ts @@ -1,12 +1,12 @@ import type { CSSProperties } from 'react' -import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' import { normalizeLeftSidebarTintColor, normalizeLeftSidebarTintOpacity -} from '../../../shared/left-sidebar-appearance' -import { pluginAppThemeCssFallback } from '../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' +} from '../../../../shared/left-sidebar-appearance' +import { pluginAppThemeCssFallback } from '../../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' import { hostPillOutlineMixOver, type ColorProbe } from './plugin-theme-tokens' -import { mix, type Rgba } from '../../../shared/color/rgba-contrast' +import { mix, type Rgba } from '../../../../shared/color/rgba-contrast' type LeftSidebarAppearanceSettings = Pick< GlobalSettings, diff --git a/src/renderer/src/lib/monospace-font-family.ts b/src/renderer/src/app-shell/appearance/monospace-font-family.ts similarity index 92% rename from src/renderer/src/lib/monospace-font-family.ts rename to src/renderer/src/app-shell/appearance/monospace-font-family.ts index 2c10df0700d..325e2463c2a 100644 --- a/src/renderer/src/lib/monospace-font-family.ts +++ b/src/renderer/src/app-shell/appearance/monospace-font-family.ts @@ -1,4 +1,4 @@ -import { isPluginFontFamilyName } from '../../../shared/plugins/contributions/plugin-font-contribution' +import { isPluginFontFamilyName } from '../../../../shared/plugins/contributions/plugin-font-contribution' export const BUNDLED_SYMBOLS_FONT_FAMILY = 'Orca Nerd Font Symbols' diff --git a/src/renderer/src/lib/plugin-theme-contrast-rules.ts b/src/renderer/src/app-shell/appearance/plugin-theme-contrast-rules.ts similarity index 100% rename from src/renderer/src/lib/plugin-theme-contrast-rules.ts rename to src/renderer/src/app-shell/appearance/plugin-theme-contrast-rules.ts diff --git a/src/renderer/src/lib/plugin-theme-tokens.ts b/src/renderer/src/app-shell/appearance/plugin-theme-tokens.ts similarity index 98% rename from src/renderer/src/lib/plugin-theme-tokens.ts rename to src/renderer/src/app-shell/appearance/plugin-theme-tokens.ts index 2844bea1da7..8e496c3053d 100644 --- a/src/renderer/src/lib/plugin-theme-tokens.ts +++ b/src/renderer/src/app-shell/appearance/plugin-theme-tokens.ts @@ -1,7 +1,7 @@ import { pluginAppThemeCssFallback, type PluginThemeCssFallbackRule -} from '../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' +} from '../../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' import { BORDERS, CONTRAST_RULES, @@ -11,7 +11,7 @@ import { type ContrastRule } from './plugin-theme-contrast-rules' -import { contrastRatio, mix, over, type Rgba } from '../../../shared/color/rgba-contrast' +import { contrastRatio, mix, over, type Rgba } from '../../../../shared/color/rgba-contrast' /** sRGB channels 0-255 and alpha 0-1, or null when the value is not a CSS color. */ export type ColorProbe = (value: string) => Rgba | null diff --git a/src/renderer/src/app-shell/appearance/terminal-app-theme.test.ts b/src/renderer/src/app-shell/appearance/terminal-app-theme.test.ts new file mode 100644 index 00000000000..0f45a9e902c --- /dev/null +++ b/src/renderer/src/app-shell/appearance/terminal-app-theme.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultSettings } from '../../../../shared/constants' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { ColorProbe } from './plugin-theme-tokens' +import { contrastRatio, over } from '../../../../shared/color/rgba-contrast' +import { synthesizeTerminalAppTheme } from './terminal-app-theme' + +// Parses #rrggbb and rgb(r g b), which is all the synthesized theme and its inputs use. +const probe: ColorProbe = (value) => { + const hex = /^#([0-9a-f]{6})$/i.exec(value.trim())?.[1] + if (hex) { + const channel = (offset: number): number => Number.parseInt(hex.slice(offset, offset + 2), 16) + return [channel(0), channel(2), channel(4), 1] + } + const rgb = /^rgb\((\d+) (\d+) (\d+)\)$/.exec(value.trim()) + return rgb ? [Number(rgb[1]), Number(rgb[2]), Number(rgb[3]), 1] : null +} + +function settingsWith(overrides: Partial): GlobalSettings { + return { ...getDefaultSettings('/tmp'), theme: 'dark', ...overrides } +} + +describe('synthesizeTerminalAppTheme', () => { + it('keeps the host pill label legible on its accent fill in light and dark', () => { + for (const [terminalThemeDark, tint] of [ + ['GitHub Light', 1], + ['Nord', 0.8] + ] as const) { + const tokens = synthesizeTerminalAppTheme( + settingsWith({ terminalThemeDark }), + true, + probe + )?.tokens + const color = (token: string) => probe(tokens?.[token] ?? '') ?? [0, 0, 0, 1] + const [r, g, b] = color('--accent') + const pill = over([r, g, b, tint], color('--sidebar')) + expect(contrastRatio(color('--muted-foreground'), pill)).toBeGreaterThanOrEqual(4.5) + } + }) +}) diff --git a/src/renderer/src/lib/terminal-app-theme.ts b/src/renderer/src/app-shell/appearance/terminal-app-theme.ts similarity index 90% rename from src/renderer/src/lib/terminal-app-theme.ts rename to src/renderer/src/app-shell/appearance/terminal-app-theme.ts index 1ab89a15bdb..32dc7c0e44a 100644 --- a/src/renderer/src/lib/terminal-app-theme.ts +++ b/src/renderer/src/app-shell/appearance/terminal-app-theme.ts @@ -1,17 +1,17 @@ import type { ITheme } from '@xterm/xterm' -import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' import { completePluginAppThemeTokens, type PluginThemeTokenColorRule -} from '../../../shared/plugins/artifacts/plugin-theme-artifact' -import { pluginAppThemeCssFallback } from '../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' -import { MATCH_TERMINAL_APP_THEME } from '../../../shared/plugin-theme-settings' +} from '../../../../shared/plugins/artifacts/plugin-theme-artifact' +import { pluginAppThemeCssFallback } from '../../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' +import { MATCH_TERMINAL_APP_THEME } from '../../../../shared/plugin-theme-settings' import { resolveTerminalPalette, type TerminalPaletteSettings as TerminalAppThemeSettings -} from '../../../shared/terminal-themes/terminal-theme-selection' +} from '../../../../shared/terminal-themes/terminal-theme-selection' import type { AppThemePaint } from './document-theme' -import { hashThemeContent } from './plugin-monaco-theme' +import { hashThemeContent } from '../../lib/editor/appearance/plugin-monaco-theme' import type { ColorProbe } from './plugin-theme-tokens' import { contrastRatio, @@ -19,13 +19,13 @@ import { readableOn, rgbaToHex, type Rgba -} from '../../../shared/color/rgba-contrast' -import { getSystemPrefersDark } from './terminal-theme' +} from '../../../../shared/color/rgba-contrast' +import { getSystemPrefersDark } from '../../lib/terminal-theme' import { isTerminalBackgroundLight, resolveOpaqueTerminalBackground -} from '../../../shared/terminal-themes/terminal-title-contrast' -import { terminalPaletteRgba } from '../../../shared/terminal-themes/terminal-palette-rgba' +} from '../../../../shared/terminal-themes/terminal-title-contrast' +import { terminalPaletteRgba } from '../../../../shared/terminal-themes/terminal-palette-rgba' export type TerminalAppTheme = AppThemePaint & { id: typeof MATCH_TERMINAL_APP_THEME diff --git a/src/renderer/src/lib/theme-background-video.ts b/src/renderer/src/app-shell/appearance/theme-background-video.ts similarity index 94% rename from src/renderer/src/lib/theme-background-video.ts rename to src/renderer/src/app-shell/appearance/theme-background-video.ts index 48f2cfdca6e..a363f37c735 100644 --- a/src/renderer/src/lib/theme-background-video.ts +++ b/src/renderer/src/app-shell/appearance/theme-background-video.ts @@ -1,5 +1,5 @@ -import type { PluginThemeBackground } from '../../../shared/plugins/artifacts/plugin-theme-background' -import { PLUGIN_THEME_VIDEO_RULE } from '../../../shared/plugins/media/plugin-theme-video-rules' +import type { PluginThemeBackground } from '../../../../shared/plugins/artifacts/plugin-theme-background' +import { PLUGIN_THEME_VIDEO_RULE } from '../../../../shared/plugins/media/plugin-theme-video-rules' const LAYER_CLASS = 'theme-background-video' const OVERLAY_ATTRIBUTES = ['data-modal-overlay-open', 'data-onboarding-overlay-open'] diff --git a/src/renderer/src/lib/theme-background.ts b/src/renderer/src/app-shell/appearance/theme-background.ts similarity index 95% rename from src/renderer/src/lib/theme-background.ts rename to src/renderer/src/app-shell/appearance/theme-background.ts index 5d67bcdfa29..4214b66d343 100644 --- a/src/renderer/src/lib/theme-background.ts +++ b/src/renderer/src/app-shell/appearance/theme-background.ts @@ -1,4 +1,4 @@ -import type { PluginThemeBackground } from '../../../shared/plugins/artifacts/plugin-theme-background' +import type { PluginThemeBackground } from '../../../../shared/plugins/artifacts/plugin-theme-background' import { useThemeBackgroundStore } from '@/store/appearance/theme-background' import { syncWindowMaterialWithThemeBackground } from './window-material-runtime' diff --git a/src/renderer/src/lib/window-backdrop.ts b/src/renderer/src/app-shell/appearance/window-backdrop.ts similarity index 100% rename from src/renderer/src/lib/window-backdrop.ts rename to src/renderer/src/app-shell/appearance/window-backdrop.ts diff --git a/src/renderer/src/lib/window-material-runtime.ts b/src/renderer/src/app-shell/appearance/window-material-runtime.ts similarity index 95% rename from src/renderer/src/lib/window-material-runtime.ts rename to src/renderer/src/app-shell/appearance/window-material-runtime.ts index 1164e74c200..c21e63fe549 100644 --- a/src/renderer/src/lib/window-material-runtime.ts +++ b/src/renderer/src/app-shell/appearance/window-material-runtime.ts @@ -1,5 +1,5 @@ -import type { WindowMaterial, WindowMaterialHost } from '../../../shared/window-material' -import { getRendererAppPlatform } from './renderer-app-platform' +import type { WindowMaterial, WindowMaterialHost } from '../../../../shared/window-material' +import { getRendererAppPlatform } from '../../lib/renderer-app-platform' let material: WindowMaterial | undefined diff --git a/src/renderer/src/app-shell/use-app-chrome-layout.ts b/src/renderer/src/app-shell/use-app-chrome-layout.ts index f362353e239..74fc1ac1652 100644 --- a/src/renderer/src/app-shell/use-app-chrome-layout.ts +++ b/src/renderer/src/app-shell/use-app-chrome-layout.ts @@ -2,7 +2,7 @@ import { useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from import { useShallow } from 'zustand/react/shallow' import { SYNC_FIT_PANES_EVENT } from '@/constants/terminal' import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' -import { resolveLeftSidebarStyleVariables } from '@/lib/left-sidebar-appearance' +import { resolveLeftSidebarStyleVariables } from '@/app-shell/appearance/left-sidebar-appearance' import { resolveLeftTitlebarChromeLayout } from '@/lib/titlebar-left-chrome' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' import { useAppStore } from '../store' diff --git a/src/renderer/src/app-shell/use-document-appearance.ts b/src/renderer/src/app-shell/use-document-appearance.ts index 53863ec5cfc..a8b0ff240cf 100644 --- a/src/renderer/src/app-shell/use-document-appearance.ts +++ b/src/renderer/src/app-shell/use-document-appearance.ts @@ -1,13 +1,13 @@ import { useEffect, useMemo, useRef } from 'react' import { useShallow } from 'zustand/react/shallow' -import { buildAppFontFamily } from '@/lib/app-font-family' +import { buildAppFontFamily } from '@/app-shell/appearance/app-font-family' import { applyCodeFontSmoothing } from '@/lib/editor/appearance/code-font-smoothing' import { applyMarkdownCodeFontFamily } from '@/lib/editor/appearance/markdown-code-font' import { useSplitDividerSetting } from '@/hooks/use-split-divider-setting' import { rebuildAllTerminalWebglRenderers } from '@/lib/pane-manager/pane-manager-registry' -import { applyDocumentTheme, applyPluginAppTheme } from '../lib/document-theme' -import { applyThemeBackground } from '../lib/theme-background' -import { syncThemeBackgroundVideo } from '../lib/theme-background-video' +import { applyDocumentTheme, applyPluginAppTheme } from './appearance/document-theme' +import { applyThemeBackground } from './appearance/theme-background' +import { syncThemeBackgroundVideo } from './appearance/theme-background-video' import { usePrefersReducedMotion } from '../hooks/usePrefersReducedMotion' import { useWindowActive } from '../hooks/use-window-active' import { tolerantPluginThemeBackgroundRegistration } from '../../../shared/plugins/artifacts/plugin-theme-background' @@ -16,13 +16,13 @@ import { paintCodeEditorColors, resolveCodeEditorTheme } from '../lib/editor/appearance/code-editor-theme' -import { browserColorProbe } from '../lib/plugin-theme-tokens' +import { browserColorProbe } from './appearance/plugin-theme-tokens' import { TINTED_HOST_PILL_OUTLINE_MIX_TOKEN, tintedSidebarHostPillOutlineMix -} from '../lib/left-sidebar-appearance' +} from './appearance/left-sidebar-appearance' import { useCodeEditorThemeStore } from '../store/appearance/code-editor-theme' -import { synthesizeTerminalAppTheme, type TerminalAppTheme } from '../lib/terminal-app-theme' +import { synthesizeTerminalAppTheme, type TerminalAppTheme } from './appearance/terminal-app-theme' import { MATCH_TERMINAL_APP_THEME } from '../../../shared/plugin-theme-settings' import { usePluginAppThemeSync, diff --git a/src/renderer/src/app-shell/use-floating-workspace-panel.ts b/src/renderer/src/app-shell/use-floating-workspace-panel.ts index 5287c6b836d..de720292670 100644 --- a/src/renderer/src/app-shell/use-floating-workspace-panel.ts +++ b/src/renderer/src/app-shell/use-floating-workspace-panel.ts @@ -9,8 +9,8 @@ import { import { TOGGLE_FLOATING_TERMINAL_EVENT, requestFloatingTerminalOpenMaximized -} from '@/lib/floating-terminal' -import { createFloatingWorkspaceTourInteractionSnapshot } from '@/lib/floating-workspace-tour-interaction-snapshot' +} from '@/components/floating-terminal/floating-terminal' +import { createFloatingWorkspaceTourInteractionSnapshot } from '@/components/floating-terminal/floating-workspace-tour-interaction-snapshot' import { persistFloatingTerminalPanelOpen } from '../components/floating-terminal/floating-terminal-panel-view-state' import { useAppStore } from '../store' import { selectFloatingVisibleTabCount } from '../store/workspaces/floating/floating-workspace-panel-selector' diff --git a/src/renderer/src/app-shell/use-global-keybindings.ts b/src/renderer/src/app-shell/use-global-keybindings.ts index ec2c0578ece..4bada833e8d 100644 --- a/src/renderer/src/app-shell/use-global-keybindings.ts +++ b/src/renderer/src/app-shell/use-global-keybindings.ts @@ -10,7 +10,7 @@ import { findPluginCommandForKeybinding, globalShortcutTargetYields } from '@/lib/plugin-command-keybindings' -import { shouldMinimizeFloatingWorkspacePanelOnCloseShortcut } from '@/lib/floating-workspace-terminal-actions' +import { shouldMinimizeFloatingWorkspacePanelOnCloseShortcut } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification' import { folderRelativePathToIncludeGlob, diff --git a/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts b/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts new file mode 100644 index 00000000000..9c42d0049e4 --- /dev/null +++ b/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts @@ -0,0 +1,58 @@ +import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder' + +/** Why a finished agent turn did not mark its workspace unread. */ +export type AgentFinishDropCause = + | 'fresh-active-hook-status' + | 'superseded-snapshot' + | 'muted-workspace' + | 'coordinator-only-news' + | 'no-live-session' + | 'unknown-surface' + | 'superseded-surface' + | 'viewed' + | 'pane-pruned-before-quiet-window' + | 'held-revision-expired' + | 'pane-not-live' + | 'hook-lane-disabled' + | 'turn-end-not-counted' + | 'restored-unconfirmed' + | 'host-replay-skipped' + +/** Every path that drops a finish was silent, so a missing unread could not be traced (#40340). */ +export function recordAgentFinishDropped( + cause: AgentFinishDropCause, + subject: { workspaceId?: string; paneKey?: string | null } +): void { + recordRendererCrashBreadcrumb('agent_finish_dropped', { + cause, + ...(subject.workspaceId ? { workspaceId: subject.workspaceId } : {}), + ...(subject.paneKey ? { paneKey: subject.paneKey } : {}) + }) +} + +/** A finish waiting out its quiet window is lost when its pane's coordinator is pruned. */ +export function recordPrunedPendingFinish( + workspaceId: string, + paneKey: string, + coordinator: { hasPendingHookDoneCompletion: () => boolean } +): void { + if (coordinator.hasPendingHookDoneCompletion()) { + recordAgentFinishDropped('pane-pruned-before-quiet-window', { workspaceId, paneKey }) + } +} + +/** The hook lane ignores updates for a pane it does not consider live; only a finish matters here. */ +export function recordFinishOnPaneNotLive( + workspaceId: string, + paneKey: string, + state: string +): void { + if (state === 'done') { + recordAgentFinishDropped('pane-not-live', { workspaceId, paneKey }) + } +} + +/** Completion notifications are off for this pane (setting, or waiting for a fresh working state). */ +export function recordHookLaneDisabled(workspaceId: string, paneKey: string): void { + recordAgentFinishDropped('hook-lane-disabled', { workspaceId, paneKey }) +} diff --git a/src/renderer/src/attention/notification-subject-owner.ts b/src/renderer/src/attention/notification-subject-owner.ts index a29bba53e5f..774306f30a7 100644 --- a/src/renderer/src/attention/notification-subject-owner.ts +++ b/src/renderer/src/attention/notification-subject-owner.ts @@ -10,7 +10,7 @@ import { getPtyExecutionHost } from '../../../shared/terminal/pty/lifecycle/term import type { Tab } from '../../../shared/tab-types' import type { AppState } from '@/store/types' import type { PtyTransport } from '@/components/terminal-pane/pty-transport/pty-transport-types' -import { resolveTerminalTabPtyOwnership } from '@/lib/terminal-tab-for-pty-id' +import { resolveTerminalTabPtyOwnership } from '@/lib/workspace/tabs/terminal-tab-for-pty-id' import { resolveExactWorktreeRoute, routeForOwner diff --git a/src/renderer/src/component-fixtures/component-fixture-explorer.tsx b/src/renderer/src/component-fixtures/component-fixture-explorer.tsx index 866e5099854..623b0bde628 100644 --- a/src/renderer/src/component-fixtures/component-fixture-explorer.tsx +++ b/src/renderer/src/component-fixtures/component-fixture-explorer.tsx @@ -2,7 +2,7 @@ import '../assets/main.css' import ReactDOM from 'react-dom/client' import { getDefaultSettings } from '../../../shared/constants' -import { applyDocumentTheme } from '../lib/document-theme' +import { applyDocumentTheme } from '../app-shell/appearance/document-theme' import { installBodyOverlayAttributes } from '../lib/body-overlay-attributes' import { useAppStore } from '../store/index' import { installWebPreloadApi } from '../web/web-preload-api' diff --git a/src/renderer/src/components/LinearItemDrawer.tsx b/src/renderer/src/components/LinearItemDrawer.tsx index a1c8fba8db4..30fecf6f88a 100644 --- a/src/renderer/src/components/LinearItemDrawer.tsx +++ b/src/renderer/src/components/LinearItemDrawer.tsx @@ -1,5 +1,6 @@ import { getLinearSourceScope } from '@/store/slices/linear/linear-slice-scope' -import { observeLinearIssueRead } from '@/store/slices/linear/linear-issue-publication' +import '@/store/slices/linear/linear-issue-read' +import { observeLinearIssueRead } from '@/store/slices/linear/linear-issue-read-lifecycle' import { useLinearIssuePublication } from '@/hooks/useLinearIssuePublication' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 514a3b90408..3a898de67f3 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -5,7 +5,7 @@ import { useAppStore } from '@/store' import { cn } from '@/lib/utils' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { getScreenSubmitModifierLabel } from '@/lib/screen-submit-shortcut' -import { resolveProjectCloneUrlPrefill } from '@/lib/project-clone-url-prefill' +import { resolveProjectCloneUrlPrefill } from '@/lib/workspace/creation/project-clone-url-prefill' import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour' import { AddRemoteHostDialog, diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index 1c0169e1b1b..c0a27c4122c 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -3,13 +3,13 @@ import { toast } from 'sonner' import { formatWorkspaceCreateError, getWorkspaceCreateErrorToastMessage -} from '@/lib/workspace-create-error-format' +} from '@/lib/workspace/creation/workspace-create-error-format' import type { AgentPickerDraft, AgentPickerEntry } from '../../../shared/agent-launch/picker/agent-launch-picker' import { DirectWorkItemSetupDialog } from './new-workspace/DirectWorkItemSetupDialog' -import { agentChoicePending } from '@/lib/host-chat-program' +import { agentChoicePending } from '@/lib/agent-session/launch/inventory/host-chat-program' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store/index' @@ -32,14 +32,14 @@ import { quickWorkspacePickerInputs, pickQuickWorkspaceAgent, resolveQuickWorkspaceAgentSelection -} from '@/lib/quick-workspace-agent-selection' -import { useAgentsOfferedForLaunch } from '@/lib/host-chat-program-acquisition' -import { shouldAllowComposerEnterSubmitTarget } from '@/lib/new-workspace-enter-guard' +} from '@/lib/workspace/creation/quick-workspace-agent-selection' +import { useAgentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { shouldAllowComposerEnterSubmitTarget } from '@/lib/workspace/creation/new-workspace-enter-guard' import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { getWorkspaceComposerInitialFocusTarget } from '@/lib/workspace-composer-initial-focus' +import { getWorkspaceComposerInitialFocusTarget } from '@/lib/workspace/creation/workspace-composer-initial-focus' import '@/components/sidebar/workspace-creation/folder/folder-workspace-source-repos' import { getFolderWorkspacePrimaryActionLabel } from '@/components/sidebar/workspace-creation/folder/folder-workspace-source-selection' import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows' diff --git a/src/renderer/src/components/activity/activity-thread-actions.ts b/src/renderer/src/components/activity/activity-thread-actions.ts index 6c7995f5994..8d10e1c978f 100644 --- a/src/renderer/src/components/activity/activity-thread-actions.ts +++ b/src/renderer/src/components/activity/activity-thread-actions.ts @@ -1,5 +1,5 @@ import { activateTabAndFocusPane } from '@/lib/workspace/tabs/activate-tab-and-focus-pane' -import { revealFloatingWorkspacePanel } from '@/lib/floating-workspace-panel-reveal' +import { revealFloatingWorkspacePanel } from '@/components/floating-terminal/floating-workspace-panel-reveal' import { activateStructuredAgentSessionTab } from '@/lib/agent-session/structured-agent-session-tab-activation' import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' import { jumpToWorktreeFromSidebar } from '@/lib/workspace/activation/worktree-jump-navigation' diff --git a/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx b/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx index 73eae33015f..8af089829b8 100644 --- a/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx +++ b/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx @@ -1,5 +1,5 @@ import { useAgentPickerDraftScope } from '../agent/AgentLaunchSetupButton' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' +import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' import { worktreeLaunchWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { useEffect, useRef, useState } from 'react' import { Loader2, MessageSquarePlus } from 'lucide-react' diff --git a/src/renderer/src/components/agent/AgentSettingsDialog.tsx b/src/renderer/src/components/agent/AgentSettingsDialog.tsx index 4a709c6ac0a..415ba2ff320 100644 --- a/src/renderer/src/components/agent/AgentSettingsDialog.tsx +++ b/src/renderer/src/components/agent/AgentSettingsDialog.tsx @@ -14,7 +14,7 @@ import { useTranslate } from '@/i18n/use-translate' import { isWindowsTerminalCapabilityHost, useLocalWindowsTerminalCapabilities -} from '@/lib/windows-terminal-capabilities' +} from '@/runtime/hosts/capabilities/windows-terminal-capabilities' import { isWebClientLocation } from '@/lib/web-client-location' import { useWindowsTerminalCapabilityOwnerKey } from '@/hooks/useWindowsTerminalCapabilityOwnerKey' import { resolveSettingsHostScope } from '@/components/settings/host-scope/settings-host-scope' diff --git a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx index b47f494f994..fea92e20a4f 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx @@ -17,7 +17,7 @@ import { composeActiveTerminalTheme } from '@/components/terminal-pane/appearanc import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { AgentIcon } from '@/components/agent/icons/AgentIcon' -import { buildFontFamily } from '@/lib/monospace-font-family' +import { buildFontFamily } from '@/app-shell/appearance/monospace-font-family' import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' import { cn } from '@/lib/utils' diff --git a/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx index 55e3087582b..45e34130a12 100644 --- a/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx @@ -2,7 +2,7 @@ import type { AutomationAuthorityRef } from '../../../../../shared/automations/o import React from 'react' import { useAppStore } from '@/store/index' import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' +import { useChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { automationChatSupport, automationDraftSurface, diff --git a/src/renderer/src/components/automations/authoring/automation-orca-save.ts b/src/renderer/src/components/automations/authoring/automation-orca-save.ts index eb6de9e658b..e2dd43ee641 100644 --- a/src/renderer/src/components/automations/authoring/automation-orca-save.ts +++ b/src/renderer/src/components/automations/authoring/automation-orca-save.ts @@ -17,7 +17,7 @@ import type { AutomationUpdateInput } from '../../../../../shared/automations/automation-definition' import { getRepoExecutionHostId } from '../../../../../shared/execution-host' -import { ensureHooksApproved } from '@/lib/ensure-hooks-confirmed' +import { ensureHooksApproved } from '@/runtime/repo-hooks/ensure-hooks-confirmed' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' import { listAutomationsForTarget } from '../hosts/automation-host-client' diff --git a/src/renderer/src/components/automations/authoring/automation-setup-review.ts b/src/renderer/src/components/automations/authoring/automation-setup-review.ts index f93f37175cb..280510157b4 100644 --- a/src/renderer/src/components/automations/authoring/automation-setup-review.ts +++ b/src/renderer/src/components/automations/authoring/automation-setup-review.ts @@ -5,7 +5,7 @@ import { confirmCreatedWorktreeSetupContent, ensureHooksApproved, type HookTrustApproval -} from '@/lib/ensure-hooks-confirmed' +} from '@/runtime/repo-hooks/ensure-hooks-confirmed' import type { AutomationSaveContext } from './automation-save-context' import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationUsageSummary } from '../../../../../shared/automations/history/automation-usage-summary' diff --git a/src/renderer/src/components/automations/automations-page-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index 309adc4fed9..cab3577d27c 100644 --- a/src/renderer/src/components/automations/automations-page-test-harness.tsx +++ b/src/renderer/src/components/automations/automations-page-test-harness.tsx @@ -113,7 +113,7 @@ vi.mock('@/runtime/repo-hooks/runtime-hooks-client', () => ({ checkRuntimeHooks: vi.fn(async () => ({ hooks: null, ok: true })) })) -vi.mock('@/lib/ensure-hooks-confirmed', () => ({ +vi.mock('@/runtime/repo-hooks/ensure-hooks-confirmed', () => ({ ensureHooksConfirmed: vi.fn(async () => 'inherit'), ensureHooksApproved: vi.fn(async () => ({ decision: 'run' })) })) diff --git a/src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts b/src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts index dbb45ed5d28..8453526a281 100644 --- a/src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts +++ b/src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts @@ -1,11 +1,7 @@ import { describe, expect, it } from 'vitest' import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' -import { - externalAutomationProbeOwners, - externalAutomationScopeGateFromError, - parseExternalAutomationScopeCode -} from './external-automation-scope-gating' +import { externalAutomationProbeOwners } from './external-automation-scope-gating' function entry(overrides: Partial = {}): AutomationHostCatalogEntry { return { @@ -41,10 +37,3 @@ describe('external automation scope gating', () => { ]) }) }) - -describe('engine scope errors', () => { - it('leaves unrelated failures alone so they are not relabelled as scope limits', () => { - expect(externalAutomationScopeGateFromError(new Error('socket hang up'))).toBeNull() - expect(parseExternalAutomationScopeCode(null)).toBeNull() - }) -}) diff --git a/src/renderer/src/components/automations/hosts/automation-host-cache.test.ts b/src/renderer/src/components/automations/hosts/automation-host-cache.test.ts index 5ad2c8280b5..604c343c601 100644 --- a/src/renderer/src/components/automations/hosts/automation-host-cache.test.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache.test.ts @@ -38,14 +38,6 @@ function createCache(overrides: Parameters[0] } describe('automation host cache commit fence', () => { - it('discards a response whose entry was invalidated while it was in flight', () => { - const cache = createCache() - const fence = cache.beginRequest(DESKTOP_SELF) - cache.invalidate(DESKTOP_SELF) - expect(cache.commit(fence, { rows: [row('a')] })).toBe(false) - expect(cache.get(DESKTOP_SELF)?.data).toEqual([]) - }) - it('discards a response whose authority catalog generation advanced', () => { let generation = 7 const cache = createCache({ catalogGeneration: () => generation }) diff --git a/src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts b/src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts index 7c3a41555bf..d0cfa3336b8 100644 --- a/src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts @@ -101,19 +101,6 @@ const ALL_HOSTS: AutomationHostFilterResolution = { } describe('automation host list rows', () => { - it('reports nothing answered until a host has actually committed', () => { - const rows = resolveAutomationHostListRows({ - catalog: catalogOf([DESKTOP_SELF]), - resolution: ALL_HOSTS, - entry: () => cached([], null) - }) - - // Why this matters: the caller keeps its own list while this is false, so a - // never-answered host must not read as an empty one. - expect(rows.answered).toBe(false) - expect(rows.automations).toEqual([]) - }) - it('keeps the owned copy when the orphan scope returns the same record', () => { const owned = row('a-1', DESKTOP_SELF.owner) const rows = resolveAutomationHostListRows({ diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-overlay-shortcut-target.ts b/src/renderer/src/components/browser-pane/describe-page/browser-overlay-shortcut-target.ts index 2f545cd8b3f..463f68b4f15 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-overlay-shortcut-target.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-overlay-shortcut-target.ts @@ -1,4 +1,4 @@ -import { isEventTargetInsideFloatingWorkspacePanel } from '@/lib/floating-workspace-terminal-actions' +import { isEventTargetInsideFloatingWorkspacePanel } from '@/components/floating-terminal/floating-workspace-terminal-actions' import type { BrowserChromeShortcutScope } from './browser-page-types' export function browserOverlayOwnsShortcutTarget( diff --git a/src/renderer/src/components/cmd-j/palette-extra-results.ts b/src/renderer/src/components/cmd-j/palette-extra-results.ts new file mode 100644 index 00000000000..974e1da88fe --- /dev/null +++ b/src/renderer/src/components/cmd-j/palette-extra-results.ts @@ -0,0 +1,81 @@ +import type React from 'react' +import type { Translate } from '@/i18n/use-translate' +import type { Worktree } from '../../../../shared/worktree/types' +import type { MatchRange } from '../../../../shared/palette-match/normalized-text' +import type { PaletteResultQualityClass } from '../../../../shared/palette-match/match-quality' +import { + buildPaletteDocument, + type PaletteDocumentRank +} from '../../../../shared/palette-match/palette-document' +import { matchPaletteDocument } from '../../../../shared/palette-match/match-document' +import { preparePaletteQuery } from '../../../../shared/palette-match/palette-query' + +/** One row a non-workspace source contributes to Cmd+J. */ +export type PaletteExtraResult = { + id: string + title: string + titleRanges: readonly MatchRange[] + /** null in the empty query, where rows are listed without a match. */ + rank: PaletteDocumentRank | null + qualityClass: PaletteResultQualityClass | null + lastActiveAt: number | null + /** Source-defined order: empty-query order, and the typed tie-break after rank and activity. */ + order: number + dimmed?: boolean + leading?: React.ReactNode + line?: React.ReactNode + trailing?: React.ReactNode + onSelect: () => void +} + +/** One section a source contributes, with its rows for the current query. */ +export type PaletteExtraSource = { + id: string + sectionLabel: (t: Translate) => string + emptyQueryCap: number + /** Typed queries: where the section sits when it does not lead the list. */ + typedPlacement: 'before-workspaces' | 'after-workspaces' + /** Lead the list when its best match equals the best workspace or tab match, not only when it beats it. */ + leadsOnTie: boolean + /** Typed: matching rows only. Empty query: every row, unranked. */ + results: readonly PaletteExtraResult[] + /** Workspaces the source represents itself; their tabs stay in Open Tabs and recents. */ + hidesWorkspace?: (worktree: Worktree) => boolean +} + +export type PaletteExtraMatch = { + rank: PaletteDocumentRank + qualityClass: PaletteResultQualityClass + rangesByField: ReadonlyMap +} + +/** Ranks a source's row with the same engine as workspaces, so qualities compare across sections. */ +export function matchPaletteExtraFields( + id: string, + fields: readonly { id: string; text: string; role: 'primary' | 'secondary' }[], + query: string +): PaletteExtraMatch | null { + const prepared = preparePaletteQuery(query) + if (prepared.state !== 'ready') { + return null + } + const match = matchPaletteDocument({ + document: buildPaletteDocument({ + id, + visibleFields: fields.map((field) => ({ + id: field.id, + profile: field.role === 'primary' ? 'structured-label' : 'prose', + text: field.text, + role: field.role, + destinationEligible: field.role === 'primary' + })), + evidence: [] + }), + tokens: prepared.tokens, + normalizedQuery: prepared.normalized, + tokenCountBeforeDeduplication: prepared.tokenCountBeforeDeduplication + }) + return match + ? { rank: match.rank, qualityClass: match.qualityClass, rangesByField: match.rangesByField } + : null +} diff --git a/src/renderer/src/components/cmd-j/palette-extra-sources.ts b/src/renderer/src/components/cmd-j/palette-extra-sources.ts new file mode 100644 index 00000000000..48066d300a7 --- /dev/null +++ b/src/renderer/src/components/cmd-j/palette-extra-sources.ts @@ -0,0 +1,11 @@ +import type { PaletteExtraSource } from './palette-extra-results' + +const NO_SOURCES: readonly PaletteExtraSource[] = [] + +/** Each source registers here with its own hook; return a memoized list. */ +export function usePaletteExtraSources(_args: { + query: string + visible: boolean +}): readonly PaletteExtraSource[] { + return NO_SOURCES +} diff --git a/src/renderer/src/components/cmd-j/task-search-activation.ts b/src/renderer/src/components/cmd-j/task-search-activation.ts index 2b7989e3d56..5bf7d033b93 100644 --- a/src/renderer/src/components/cmd-j/task-search-activation.ts +++ b/src/renderer/src/components/cmd-j/task-search-activation.ts @@ -5,12 +5,13 @@ import { getProvenWorkspaceReferenceIdentity, parseWorkspaceReferenceUrl } from '../../../../shared/workspace-attachments/workspace-reference-identity' -import { getLinearIssueWorkspaceName } from '../../../../shared/workspace-name' import { + getLinearIssueWorkspaceName, getLinkedWorkItemWorkspaceName, - getLinkedWorkItemSuggestedName, - type LinkedWorkItemSummary -} from '@/lib/new-workspace' + getLinkedWorkItemSuggestedName +} from '../../../../shared/workspace-name' +import '@/lib/workspace/creation/new-workspace' +import type { LinkedWorkItemSummary } from '@/lib/workspace/creation/new-workspace' import { buildLinearIssueLinkedWorkItem } from '@/lib/work-items/linear/linear-linked-work-item' import type { Worktree } from '../../../../shared/worktree/types' import { diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts index 0ecc2675302..a0ed19dbc07 100644 --- a/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts @@ -11,7 +11,7 @@ import { resolveTerminalScrollOnUserInput } from '@/lib/pane-manager/pane-terminal-options' import { buildLocalConptyTerminalOptions } from '@/lib/pane-manager/windows-pty-compatibility' -import { buildFontFamily } from '@/lib/monospace-font-family' +import { buildFontFamily } from '@/app-shell/appearance/monospace-font-family' import { pluginFontFamilyWhenLoaded } from '@/store/plugins/appearance/plugin-fonts' import { resolveTerminalMinimumContrastRatio } from '../../../../shared/terminal-themes/terminal-contrast-correction' diff --git a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts b/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts index b3f8308d39c..a6f29976a82 100644 --- a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts +++ b/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts @@ -1,6 +1,6 @@ import type { AppState } from '@/store/types' -import { holdChatProgramFacts } from '@/lib/host-chat-program-acquisition' -import { resolveChatProgramContext } from '@/lib/host-chat-program' +import { holdChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' +import { resolveChatProgramContext } from '@/lib/agent-session/launch/inventory/host-chat-program' import { selectAgentLaunchRouteView, worktreeLaunchWorkspace diff --git a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts index 76eaa73c76e..7e6e7dab48b 100644 --- a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts +++ b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts @@ -17,7 +17,7 @@ import { worktreeLaunchWorkspace, type AgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' +import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' export type DashboardLaunchDetectionState = Pick< diff --git a/src/renderer/src/components/dashboard/reveal-dashboard-agent.ts b/src/renderer/src/components/dashboard/reveal-dashboard-agent.ts index 66096361479..fbd66384f8a 100644 --- a/src/renderer/src/components/dashboard/reveal-dashboard-agent.ts +++ b/src/renderer/src/components/dashboard/reveal-dashboard-agent.ts @@ -1,4 +1,4 @@ -import { revealTerminalPane } from '@/lib/reveal-terminal-pane' +import { revealTerminalPane } from '@/lib/workspace/activation/reveal-terminal-pane' import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' import { activateStructuredAgentSessionTab } from '@/lib/agent-session/structured-agent-session-tab-activation' import { diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts index 522f0341ff9..01f3cb3711d 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -6,7 +6,7 @@ import { subscribeStructuredChatTabNames, getStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' -import { subscribeChatProgramFacts } from '@/lib/host-chat-program' +import { subscribeChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program' import { type AgentLaunchRouteView, agentLaunchRouteInputsChanged, diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts index f7335bb8503..a47736c057a 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts @@ -5,7 +5,7 @@ import { useAppStore } from '@/store' import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' import type { DashboardSnapshot } from '../../../../shared/dashboard-snapshot' import { buildDashboardSnapshot } from './build-dashboard-snapshot' -import { useChatProgramFactsVersion } from '@/lib/host-chat-program-acquisition' +import { useChatProgramFactsVersion } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { createWorktreeAgentRowsCache } from './worktree-agent-rows-cache' import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { diff --git a/src/renderer/src/components/dictation/DictationController.tsx b/src/renderer/src/components/dictation/DictationController.tsx index e664085388d..b10035c6acd 100644 --- a/src/renderer/src/components/dictation/DictationController.tsx +++ b/src/renderer/src/components/dictation/DictationController.tsx @@ -32,6 +32,7 @@ import { publishDictationMeter } from './dictation-meter-store' import { useDictationSilenceStop } from './use-dictation-silence-stop' import { stopAfterSilenceSeconds } from '../../../../shared/dictation-silence-stop' import { useDictationSpeechEvents } from './use-dictation-speech-events' +import { useDictationSpeechModelSetup } from './use-dictation-speech-model-setup' import { NO_DICTATION_LIVE_TEXT } from '@/store/slices/dictation/dictation' import { canStartDictation, @@ -74,6 +75,9 @@ export function DictationController() { const [failure, setFailure] = useState(null) // A new recording gets a fresh pill (timer and all); a retry keeps the one it failed in. const [recordingKey, setRecordingKey] = useState(0) + const isIdle = useCallback(() => sessionRef.current.phase === 'idle', []) + const { setupTarget, closeSetup, hasPendingStart, invalidatePendingStart, readyToRecord } = + useDictationSpeechModelSetup(settings?.voice, isIdle, setPillAnchor) const queuedSend = useDictationQueuedSend(sessionRef, keptRef) const { clear: clearQueuedSend, release: releaseQueuedSend } = queuedSend @@ -158,6 +162,7 @@ export function DictationController() { // Words that already landed stay; the engine drops the rest instead of transcribing it. const cancelDictation = useCallback(() => { + invalidatePendingStart() if (sessionRef.current.phase === 'error') { dispatch({ type: 'ended' }) return @@ -169,9 +174,10 @@ export function DictationController() { stopCapture() void window.api.speech.cancelDictation(previous.sessionId).catch(() => undefined) drainStoppedSession(previous.sessionId) - }, [dispatch, stopCapture, drainStoppedSession]) + }, [dispatch, stopCapture, drainStoppedSession, invalidatePendingStart]) const stopDictation = useCallback(async () => { + invalidatePendingStart() const previous = sessionRef.current const next = dispatch({ type: 'stop' }) if (next === previous) { @@ -183,7 +189,7 @@ export function DictationController() { return } await finishDictationSession(next) - }, [dispatch, finishCapture, finishDictationSession]) + }, [dispatch, finishCapture, finishDictationSession, invalidatePendingStart]) const startDictation = useCallback(async () => { if (!canStartDictation(sessionRef.current.phase)) { @@ -201,6 +207,10 @@ export function DictationController() { return } + if (!(await readyToRecord(settings.voice)) || !canStartDictation(sessionRef.current.phase)) { + return + } + const { run, sessionId } = dispatch({ type: 'start' }) if (sessionId === null) { return @@ -315,7 +325,8 @@ export function DictationController() { finishDictationSession, drainStoppedSession, recordFeatureInteraction, - showFailure + showFailure, + readyToRecord ]) // Sends the failed session's recording through the speech host again, into the same place. @@ -346,12 +357,17 @@ export function DictationController() { }, [settings, dispatch, finishDictationSession, showFailure]) const toggleDictation = useCallback(() => { + // A second press while the model check runs takes the first one back. + if (hasPendingStart()) { + invalidatePendingStart() + return + } if (isDictationUnderway(sessionRef.current.phase)) { void stopDictation() } else { void startDictation() } - }, [startDictation, stopDictation]) + }, [startDictation, stopDictation, hasPendingStart, invalidatePendingStart]) useDictationControls(settings?.voice, dictationState, { start: () => void startDictation(), @@ -362,7 +378,9 @@ export function DictationController() { enterQueues: (event) => queuedSend.queueTerminalEnter(event.target), // The error pill leaves Esc to Settings and dialogs; only its ✕ discards the recording. escCancels: () => - isDictationUnderway(sessionRef.current.phase) || sessionRef.current.phase === 'stopping' + hasPendingStart() || + isDictationUnderway(sessionRef.current.phase) || + sessionRef.current.phase === 'stopping' }) const { isHolding } = useHoldDictationGesture({ @@ -414,6 +432,8 @@ export function DictationController() { anchor={pillAnchor} failure={failure} queued={queuedSend.queuedKind} + setup={setupTarget} + onSetupClose={closeSetup} /> ) } diff --git a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx index ca8b05f0971..294c70cb1f8 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx @@ -3,16 +3,20 @@ import { defineFixture } from '../../component-fixtures/component-fixture' import { DictationIndicator } from './DictationIndicator' import { publishDictationMeter, resetDictationMeter } from './dictation-meter-store' import type { DictationFailureKind } from './dictation-toasts' +import type { SpeechModelUpdateTarget } from './speech-model-update-target' +import type { SpeechModelManifest, SpeechModelState } from '../../../../shared/speech-types' import type { DictationQueuedSendKind } from './use-dictation-queued-send' function PaneWithPill({ captureLive = true, failure = null, - queued = null + queued = null, + setup = null }: { captureLive?: boolean failure?: DictationFailureKind | null queued?: DictationQueuedSendKind | null + setup?: SpeechModelUpdateTarget | null }) { const [pane, setPane] = useState(null) const anchor = useMemo( @@ -27,6 +31,8 @@ function PaneWithPill({ anchor={anchor} failure={failure} queued={queued} + setup={setup} + onSetupClose={() => {}} /> ) : null} @@ -138,3 +144,82 @@ export const queuedTerminalEnter = defineFixture({ setup: resetDictationMeter, render: () => }) + +function speechModel(id: string, label: string): SpeechModelManifest { + return { + id, + label, + type: 'transducer', + provider: 'local', + language: 'en', + languages: ['en'], + sampleRate: 16000, + streaming: false, + sizeBytes: 740_000_000 + } +} + +const parakeet = speechModel('parakeet', 'Parakeet') +const updateTarget: SpeechModelUpdateTarget = { model: parakeet } +const retiredTarget: SpeechModelUpdateTarget = { + model: parakeet, + retired: speechModel('zipformer', 'Zipformer') +} + +function mockSpeechDownloads(downloadModel: () => Promise = () => new Promise(() => {})) { + Object.assign(window.api.speech, { + onDownloadProgress: () => () => {}, + getModelStates: async () => [], + downloadModel + }) +} + +function withParakeet(state: Omit) { + return { modelStates: [{ id: 'parakeet', ...state }] } +} + +export const setupNotice = defineFixture({ + width: 520, + store: withParakeet({ status: 'not-downloaded', needsUpdate: true }), + setup: () => mockSpeechDownloads(), + render: () => +}) + +export const setupRetiredNotice = defineFixture({ + width: 520, + store: withParakeet({ status: 'not-downloaded' }), + setup: () => mockSpeechDownloads(), + render: () => +}) + +export const setupDownloading = defineFixture({ + width: 520, + store: withParakeet({ status: 'downloading', progress: 0.42 }), + setup: () => mockSpeechDownloads(), + render: () => +}) + +export const setupDone = defineFixture({ + width: 520, + store: withParakeet({ status: 'ready' }), + setup: () => mockSpeechDownloads(), + render: () => +}) + +export const setupDoneRetired = defineFixture({ + width: 520, + store: withParakeet({ status: 'ready' }), + setup: () => mockSpeechDownloads(), + render: () => +}) + +export const setupFailed = defineFixture({ + width: 520, + store: withParakeet({ status: 'not-downloaded', needsUpdate: true }), + setup: () => mockSpeechDownloads(() => Promise.reject(new Error('network'))), + render: () => , + interact: async (frame) => { + frame.querySelector('[data-testid="dictation-setup-pill"] button')?.click() + await new Promise((resolve) => setTimeout(resolve, 50)) + } +}) diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index 83e1eaada07..43b0969d090 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -4,7 +4,6 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useShortcutKeyDetails } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' -import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/focus-keeping-press' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' @@ -12,12 +11,15 @@ import { ArrowUp, Check, CornerDownLeft, Loader2 } from 'lucide-react' import { isDictationPillShown } from '../../../../shared/dictation-session-machine' import { dictationSeparators } from '../../../../shared/dictation-transcript-spacing' import { CLOUD_DICTATION_MAX_SECONDS } from '../../../../shared/rpc-contract/speech-params' -import type { SpeechModelManifest } from '../../../../shared/speech-types' import { dispatchDictationControl } from './dictation-control-events' import { DictationGrapes } from './DictationGrapes' import { useDictationMeter } from './dictation-meter-store' -import { useDictationPillBox, type DictationPillAnchor } from './dictation-pill-anchor' +import type { DictationPillAnchor } from './dictation-pill-anchor' import { DictationPillCloseButton, DictationPillFailure } from './DictationPillFailure' +import { DictationPillShell } from './DictationPillShell' +import { DictationSetupPill } from './DictationSetupPill' +import { loadSpeechCatalog } from './speech-model-update-check' +import type { SpeechModelUpdateTarget } from './speech-model-update-target' import type { DictationFailureKind } from './dictation-toasts' import type { DictationQueuedSendKind } from './use-dictation-queued-send' @@ -36,9 +38,24 @@ type DictationIndicatorProps = { queued: DictationQueuedSendKind | null } -export function DictationIndicator(props: DictationIndicatorProps) { +type DictationSetupProps = { + /** Set while the pill offers the download the selected model needs instead of recording. */ + setup: SpeechModelUpdateTarget | null + onSetupClose: () => void +} + +export function DictationIndicator({ + setup, + onSetupClose, + ...props +}: DictationIndicatorProps & DictationSetupProps) { const dictationState = useAppStore((state) => state.dictationState) - return isDictationPillShown(dictationState) ? : null + if (isDictationPillShown(dictationState)) { + return + } + return setup ? ( + + ) : null } function formatElapsed(seconds: number): string { @@ -66,21 +83,13 @@ function useElapsedSeconds(running: boolean): number { return seconds } -// The catalog never changes while the app runs; the paired web client has none and its host caps itself. -let catalogRequest: Promise | null = null - +// The paired web client has no catalog; its host caps itself. function useIsCloudModel(): boolean { const modelId = useAppStore((state) => state.settings?.voice?.sttModel) const [cloud, setCloud] = useState(false) useEffect(() => { let current = true - if (!catalogRequest) { - catalogRequest = Promise.resolve() - // The paired web client's fallback resolves with nothing rather than a list. - .then(async () => (await window.api.speech.getCatalog()) ?? []) - .catch(() => []) - } - void catalogRequest.then((catalog) => { + void loadSpeechCatalog().then((catalog) => { if (current) { setCloud(catalog.some((model) => model.id === modelId && model.provider !== 'local')) } @@ -141,17 +150,12 @@ function DictationPendingDots() { ) } -// Presses on the pill keep focus where the words are going. -const keepFocus = (event: React.MouseEvent): void => event.preventDefault() -const keepFocusProps = { [KEEPS_FOCUS_ATTRIBUTE]: '', onMouseDown: keepFocus } - function DictationPill({ captureLive, anchor, failure, queued }: DictationIndicatorProps) { const t = useTranslate() const dictationState = useAppStore((state) => state.dictationState) const liveText = useAppStore((state) => state.liveText) const isHoldMode = useAppStore((state) => state.settings?.voice?.dictationMode === 'hold') const shortcut = useShortcutKeyDetails('voice.dictation') - const box = useDictationPillBox(anchor) const cloudModel = useIsCloudModel() const finishing = dictationState === 'stopping' @@ -185,17 +189,10 @@ function DictationPill({ captureLive, anchor, failure, queued }: DictationIndica const finishLabel = t('auto.components.dictation.DictationIndicator.finish', 'Finish') return ( -

+ ) } diff --git a/src/renderer/src/components/dictation/DictationPillFailure.tsx b/src/renderer/src/components/dictation/DictationPillFailure.tsx index a1448b51608..28cb44bc074 100644 --- a/src/renderer/src/components/dictation/DictationPillFailure.tsx +++ b/src/renderer/src/components/dictation/DictationPillFailure.tsx @@ -5,18 +5,20 @@ import { CircleAlert, X } from 'lucide-react' import { dispatchDictationControl } from './dictation-control-events' import { openVoiceSettings, type DictationFailureKind } from './dictation-toasts' +const cancelDictation = (): void => dispatchDictationControl('cancel') + /** The pill's ✕: cancels a dictation, or discards a failed one's recording. */ -export function DictationPillCloseButton({ label }: { label: string }) { +export function DictationPillCloseButton({ + label, + onClick = cancelDictation +}: { + label: string + onClick?: () => void +}) { return ( - diff --git a/src/renderer/src/components/dictation/DictationPillShell.tsx b/src/renderer/src/components/dictation/DictationPillShell.tsx new file mode 100644 index 00000000000..dbfea6fc954 --- /dev/null +++ b/src/renderer/src/components/dictation/DictationPillShell.tsx @@ -0,0 +1,38 @@ +import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/focus-keeping-press' +import { cn } from '@/lib/utils' +import { useDictationPillBox, type DictationPillAnchor } from './dictation-pill-anchor' + +// Presses on the pill keep focus where the words are going. +const keepFocus = (event: React.MouseEvent): void => event.preventDefault() +const keepFocusProps = { [KEEPS_FOCUS_ATTRIBUTE]: '', onMouseDown: keepFocus } + +/** The pill's floating container: over the anchor pane, or at the window's bottom centre without one. */ +export function DictationPillShell({ + anchor, + testId, + className, + children +}: { + anchor: DictationPillAnchor | null + testId: string + className?: string + children: React.ReactNode +}) { + const box = useDictationPillBox(anchor) + return ( +
+ {children} +
+ ) +} diff --git a/src/renderer/src/components/dictation/DictationSetupPill.tsx b/src/renderer/src/components/dictation/DictationSetupPill.tsx new file mode 100644 index 00000000000..101e8b6fd39 --- /dev/null +++ b/src/renderer/src/components/dictation/DictationSetupPill.tsx @@ -0,0 +1,177 @@ +import { useEffect } from 'react' +import { Check, CircleAlert, Download, Mic } from 'lucide-react' +import { Trans } from 'react-i18next' +import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' +import { Button } from '@/components/ui/button' +import { Progress } from '@/components/ui/progress' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useShortcutKeyDetails } from '@/hooks/useShortcutLabel' +import { i18n } from '@/i18n/i18n' +import { useTranslate } from '@/i18n/use-translate' +import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' +import { isPlainEscapeKeyEvent } from '../terminal-pane/input/keyboard/agent-interrupt-key-event' +import type { DictationPillAnchor } from './dictation-pill-anchor' +import { DictationPillCloseButton } from './DictationPillFailure' +import { DictationPillShell } from './DictationPillShell' +import type { SpeechModelUpdateTarget } from './speech-model-update-target' +import { useSpeechModelUpdateDownload } from './use-speech-model-update-download' + +const DONE_AUTO_HIDE_MS = 4000 + +/** Esc closes the pill, except mid-download so it can still reach the terminal or agent underneath. */ +function useEscCloses(active: boolean, onClose: () => void): void { + useEffect(() => { + if (!active) { + return + } + const handleKeyDown = (event: KeyboardEvent): void => { + if (!isImeOwnedKeyboardEvent(event) && isPlainEscapeKeyEvent(event)) { + event.preventDefault() + event.stopImmediatePropagation() + onClose() + } + } + addAppKeyListener('keydown', handleKeyDown, { first: true }) + return () => removeAppKeyListener('keydown', handleKeyDown) + }, [active, onClose]) +} + +/** Shown instead of recording when the selected model needs a download for the current speech engine. */ +export function DictationSetupPill({ + target, + anchor, + onClose +}: { + target: SpeechModelUpdateTarget + anchor: DictationPillAnchor | null + onClose: () => void +}) { + const t = useTranslate() + const shortcut = useShortcutKeyDetails('voice.dictation') + const download = useSpeechModelUpdateDownload(target, onClose) + const { phase, percent } = download + const retired = Boolean(target.retired) + + useEscCloses(phase !== 'downloading', onClose) + + useEffect(() => { + if (phase !== 'done' || retired) { + return + } + const timer = window.setTimeout(onClose, DONE_AUTO_HIDE_MS) + return () => window.clearTimeout(timer) + }, [phase, retired, onClose]) + + const dismissLabel = t('speechModelUpdate.pill.dismiss', 'Dismiss') + let icon: React.ReactNode + let message: React.ReactNode + let announced: string + let actions: React.ReactNode = null + let closeLabel = dismissLabel + let close = onClose + + if (phase === 'downloading') { + icon = + announced = t('speechModelUpdate.pill.downloading', 'Setting up dictation') + closeLabel = t('speechModelUpdate.pill.cancelDownload', 'Cancel download') + close = () => { + download.cancel() + onClose() + } + message = ( + + + + {announced} + + + {percent}% + + + + + {t('speechModelUpdate.pill.downloadingTooltip', '{{done}} of {{size}} MB', { + done: download.doneMb, + size: download.totalMb + })} + + + ) + } else if (phase === 'done') { + icon = + announced = t('speechModelUpdate.pill.readyNoShortcut', 'Dictation is ready.') + message = + shortcut.keys.length > 0 ? ( + + ')} + components={{ + kbd: + }} + /> + + ) : ( + {announced} + ) + actions = retired ? ( + + ) : null + } else if (phase === 'failed') { + icon = + announced = t('speechModelUpdate.pill.failed', 'Download stopped. Check your connection.') + message = {announced} + actions = ( + + ) + } else { + icon = + announced = retired + ? t('speechModelUpdate.pill.retiredNotice', 'Dictation moved to a faster speech model') + : t('speechModelUpdate.pill.updateNotice', 'Faster dictation is ready to install') + message = {announced} + actions = ( + + + + + + {t('speechModelUpdate.pill.installTooltip', 'One-time download · {{size}} MB', { + size: download.totalMb + })} + + + ) + } + + return ( + + + {announced} + + {icon} + + {message} + + {actions} + + + ) +} diff --git a/src/renderer/src/components/dictation/SpeechModelUpdateCard.tsx b/src/renderer/src/components/dictation/SpeechModelUpdateCard.tsx deleted file mode 100644 index c7ae7f642a8..00000000000 --- a/src/renderer/src/components/dictation/SpeechModelUpdateCard.tsx +++ /dev/null @@ -1,285 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from 'react' -import { Check, CircleAlert, Download, Mic, X } from 'lucide-react' -import { toast } from 'sonner' -import { useAppStore } from '@/store' -import { useTranslate } from '@/i18n/use-translate' -import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' -import { Card } from '../ui/card' -import { Button } from '../ui/button' -import { Progress } from '../ui/progress' -import { - findSpeechModelUpdateTarget, - type SpeechModelUpdateTarget -} from './speech-model-update-target' - -const DONE_AUTO_HIDE_MS = 4000 - -function useSpeechModelUpdateTarget(): SpeechModelUpdateTarget | null { - // Why no hydration check: the flag defaults to true until the persisted value arrives. - const seen = useAppStore((s) => s.speechModelUpdateNoticeSeen) - const voice = useAppStore((s) => s.settings?.voice) - const [target, setTarget] = useState(null) - - useEffect(() => { - // Why skip paired web clients: the models live on the host, whose own window shows this. - if (seen || !voice || isPairedWebClientWindow()) { - return - } - let cancelled = false - void Promise.all([window.api.speech.getCatalog(), window.api.speech.getModelStates()]) - .then(([catalog, states]) => { - if (cancelled) { - return - } - const store = useAppStore.getState() - store.setModelStates(states) - setTarget(findSpeechModelUpdateTarget(voice, catalog, states)) - // Why mark on the first check, shown or not: the card is for the first launch after the engine change. - store.markSpeechModelUpdateNoticeSeen() - }) - .catch(() => {}) - return () => { - cancelled = true - } - }, [seen, voice]) - - return target -} - -/** One-time card offering the download the transcribe-cpp engine needs for the selected model. */ -export function SpeechModelUpdateCard(): React.JSX.Element | null { - const target = useSpeechModelUpdateTarget() - const [closed, setClosed] = useState(false) - const close = useCallback(() => setClosed(true), []) - if (!target || closed) { - return null - } - return -} - -function SpeechModelUpdateCardBody({ - target: { model, retired }, - onClose -}: { - target: SpeechModelUpdateTarget - onClose: () => void -}): React.JSX.Element { - const t = useTranslate() - const state = useAppStore((s) => s.modelStates.find((m) => m.id === model.id)) - const refreshModelStates = useAppStore((s) => s.refreshModelStates) - const [failedAtMb, setFailedAtMb] = useState(null) - const [deleting, setDeleting] = useState(false) - const lastMbRef = useRef(0) - - // The Settings row starts the same download, so both follow the shared model states. - useEffect( - () => window.api.speech.onDownloadProgress(() => void refreshModelStates()), - [refreshModelStates] - ) - - const totalMb = Math.round((model.sizeBytes ?? 0) / 1_000_000) - const downloading = state?.status === 'downloading' || state?.status === 'extracting' - const percent = Math.round((state?.progress ?? 0) * 100) - const doneMb = Math.round((state?.progress ?? 0) * totalMb) - const phase = downloading - ? 'downloading' - : state?.status === 'ready' - ? 'done' - : failedAtMb !== null - ? 'failed' - : 'notice' - - useEffect(() => { - if (downloading) { - lastMbRef.current = doneMb - } - }, [downloading, doneMb]) - - useEffect(() => { - if (phase !== 'done' || retired) { - return - } - const timer = window.setTimeout(onClose, DONE_AUTO_HIDE_MS) - return () => window.clearTimeout(timer) - }, [phase, retired, onClose]) - - const startDownload = (): void => { - setFailedAtMb(null) - lastMbRef.current = 0 - void window.api.speech - .downloadModel(model.id) - .catch(() => setFailedAtMb(lastMbRef.current)) - .finally(() => void refreshModelStates()) - } - - const deleteRetired = (): void => { - if (!retired) { - return - } - setDeleting(true) - void window.api.speech - .deleteModel(retired.id) - .then(() => { - void refreshModelStates() - onClose() - }) - .catch(() => { - setDeleting(false) - toast.error( - t('speechModelUpdate.deleteFailed', 'Failed to delete {{model}}.', { - model: retired.label - }) - ) - }) - } - - const names = { model: model.label, old: retired?.label ?? '', size: totalMb } - const later = ( - - ) - let icon = - let title: string - let description: string - let actions: React.ReactNode = null - - if (phase === 'downloading') { - icon = - title = retired - ? t('speechModelUpdate.downloadingTitle', 'Downloading {{model}}', names) - : t('speechModelUpdate.updatingTitle', 'Updating {{model}}', names) - description = t( - 'speechModelUpdate.downloadingDescription', - 'You can keep working. Dictation is back when this finishes.' - ) - actions = ( - - ) - } else if (phase === 'done') { - icon = - title = t('speechModelUpdate.doneTitle', 'Dictation is ready') - description = retired - ? t( - 'speechModelUpdate.doneRetiredDescription', - '{{model}} is set up. The old {{old}} files are still on disk.', - names - ) - : t( - 'speechModelUpdate.doneDescription', - '{{model}} is updated. The old files were removed.', - names - ) - actions = retired ? ( - <> - - - - ) : null - } else if (phase === 'failed') { - icon = - title = retired - ? t('speechModelUpdate.downloadFailedTitle', "Couldn't download {{model}}", names) - : t('speechModelUpdate.updateFailedTitle', "Couldn't update {{model}}", names) - description = failedAtMb - ? t( - 'speechModelUpdate.failedAtDescription', - 'The download stopped at {{mb}} MB. Check your connection and try again.', - { mb: failedAtMb } - ) - : t( - 'speechModelUpdate.failedDescription', - 'The download stopped. Check your connection and try again.' - ) - actions = ( - <> - {later} - - - ) - } else { - title = retired - ? t('speechModelUpdate.replacedTitle', 'Your speech model was replaced') - : t('speechModelUpdate.updateTitle', 'Update your speech model') - description = retired - ? t( - 'speechModelUpdate.replacedDescription', - "{{old}} can't run on the new speech engine. {{model}} replaces it ({{size}} MB).", - names - ) - : t( - 'speechModelUpdate.updateDescription', - 'Dictation now runs on a faster engine. {{model}} needs a one-time download ({{size}} MB) before you can dictate again.', - names - ) - actions = ( - <> - {later} - - - ) - } - - return ( - -
-
-
{icon}
-
-

- {title} -

-

{description}

-
- -
- {phase === 'downloading' && ( -
- -
- - {t('speechModelUpdate.progress', '{{done}} of {{total}} MB', { - done: doneMb, - total: totalMb - })} - - {percent}% -
-
- )} - {actions &&
{actions}
} -
-
- ) -} diff --git a/src/renderer/src/components/dictation/dictation-setup-pill.test.tsx b/src/renderer/src/components/dictation/dictation-setup-pill.test.tsx new file mode 100644 index 00000000000..6c2f63ea866 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-setup-pill.test.tsx @@ -0,0 +1,86 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { useAppStore } from '@/store' +import { DictationSetupPill } from './DictationSetupPill' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const cancelDownload = vi.fn(async () => {}) +let root: Root +let container: HTMLDivElement + +beforeEach(() => { + cancelDownload.mockClear() + Object.defineProperty(window, 'api', { + configurable: true, + value: { + speech: { + // Neither the download nor its first progress arrives before the pill is closed. + downloadModel: () => new Promise(() => {}), + cancelDownload, + getModelStates: () => new Promise(() => {}), + onDownloadProgress: () => () => {} + } + } + }) + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + modelStates: [{ id: 'parakeet', status: 'not-downloaded', needsUpdate: true }] + }) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + useAppStore.setState(useAppStore.getInitialState(), true) +}) + +function button(label: string): HTMLButtonElement { + const match = Array.from(document.querySelectorAll('button')).find( + (candidate) => + candidate.textContent?.trim() === label || candidate.getAttribute('aria-label') === label + ) + if (!match) { + throw new Error(`missing ${label} button`) + } + return match +} + +it('cancels a download started from the pill when it is closed before any progress', async () => { + const onClose = vi.fn() + await act(async () => { + root.render( + + + + ) + }) + + await act(async () => button('Install').click()) + await act(async () => button('Cancel download').click()) + + expect(cancelDownload).toHaveBeenCalledWith('parakeet') + expect(onClose).toHaveBeenCalledOnce() +}) diff --git a/src/renderer/src/components/dictation/dictation-speech-model-setup.test.tsx b/src/renderer/src/components/dictation/dictation-speech-model-setup.test.tsx new file mode 100644 index 00000000000..4e8cbacae51 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-speech-model-setup.test.tsx @@ -0,0 +1,190 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { useAppStore } from '@/store' +import { getDefaultSettings, getDefaultVoiceSettings } from '../../../../shared/constants' +import type { SpeechModelManifest, SpeechModelState } from '../../../../shared/speech-types' +import { DictationController } from './DictationController' +import { resetSpeechModelUpdateCheckForTests } from './speech-model-update-check' + +const startCapture = vi.fn(async () => ({})) + +vi.mock('@/hooks/use-audio-capture', () => ({ + useAudioCapture: () => ({ + start: startCapture, + stop: vi.fn(), + finish: vi.fn(async () => {}), + flushBufferedAudio: vi.fn(async () => {}), + discardBufferedAudio: vi.fn(), + getCapturedChunkCount: () => 0, + getLastSpeechAt: () => 0 + }) +})) + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const parakeet: SpeechModelManifest = { + id: 'parakeet', + label: 'Parakeet', + type: 'transducer', + provider: 'local', + language: 'en', + languages: ['en'], + sampleRate: 16000, + streaming: false, + sizeBytes: 740_000_000 +} + +let root: Root +let container: HTMLDivElement +let pressShortcut: () => void +let modelStates: SpeechModelState[] +const getModelStates = vi.fn(async () => modelStates) +const startDictation = vi.fn(async () => {}) + +beforeEach(() => { + resetSpeechModelUpdateCheckForTests() + startCapture.mockClear() + getModelStates.mockClear() + startDictation.mockClear() + const unsubscribe = () => () => {} + Object.defineProperty(window, 'api', { + configurable: true, + value: { + ui: { + onDictationKeyDown: (callback: () => void) => { + pressShortcut = callback + return () => {} + } + }, + speech: { + getCatalog: async () => [parakeet], + getModelStates, + startDictation, + stopDictation: async () => {}, + cancelDictation: async () => {}, + onDownloadProgress: unsubscribe, + onPartialTranscript: unsubscribe, + onFinalTranscript: unsubscribe, + onSpeechPending: unsubscribe, + onStopped: unsubscribe, + onError: unsubscribe + } + } + }) + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + settings: { + ...getDefaultSettings('/home/test'), + voice: { ...getDefaultVoiceSettings(), enabled: true, sttModel: 'parakeet' } + } + }) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + useAppStore.setState(useAppStore.getInitialState(), true) +}) + +async function mountAndPress(): Promise { + await act(async () => { + root.render( + + + + ) + }) + expect(getModelStates).not.toHaveBeenCalled() + await act(async () => pressShortcut()) +} + +describe('dictation shortcut and the speech model update', () => { + it('offers the download in the pill instead of opening the mic', async () => { + modelStates = [{ id: 'parakeet', status: 'not-downloaded', needsUpdate: true }] + await mountAndPress() + + expect(document.querySelector('[data-testid="dictation-setup-pill"]')).not.toBeNull() + expect(startCapture).not.toHaveBeenCalled() + expect(startDictation).not.toHaveBeenCalled() + }) + + it('starts dictating when the selected model is up to date', async () => { + modelStates = [{ id: 'parakeet', status: 'ready' }] + await mountAndPress() + + expect(document.querySelector('[data-testid="dictation-setup-pill"]')).toBeNull() + expect(startCapture).toHaveBeenCalledOnce() + expect(startDictation).toHaveBeenCalledWith('parakeet', {}, expect.any(String)) + }) + + it('drops a press whose model check is still running when the press is taken back', async () => { + modelStates = [{ id: 'parakeet', status: 'ready' }] + let releaseStates = (): void => {} + getModelStates.mockImplementationOnce( + () => new Promise((resolve) => (releaseStates = () => resolve(modelStates))) + ) + await mountAndPress() + // A second toggle cancels instead of launching another check. + await act(async () => pressShortcut()) + await act(async () => releaseStates()) + + expect(getModelStates).toHaveBeenCalledOnce() + expect(startCapture).not.toHaveBeenCalled() + }) + + it('lets Escape cancel a press whose model check is still running', async () => { + modelStates = [{ id: 'parakeet', status: 'ready' }] + let releaseStates = (): void => {} + getModelStates.mockImplementationOnce( + () => new Promise((resolve) => (releaseStates = () => resolve(modelStates))) + ) + await mountAndPress() + await act(async () => { + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + }) + await act(async () => releaseStates()) + + expect(startCapture).not.toHaveBeenCalled() + }) + + it('never opens the mic when voice is turned off while the check runs', async () => { + modelStates = [{ id: 'parakeet', status: 'ready' }] + let releaseStates = (): void => {} + getModelStates.mockImplementationOnce( + () => new Promise((resolve) => (releaseStates = () => resolve(modelStates))) + ) + await mountAndPress() + await act(async () => root.render(null)) + await act(async () => releaseStates()) + + expect(startCapture).not.toHaveBeenCalled() + expect(startDictation).not.toHaveBeenCalled() + }) + + it('keeps the setup pill, not the mic, when pressed mid-download', async () => { + modelStates = [{ id: 'parakeet', status: 'downloading', progress: 0.4 }] + await mountAndPress() + await act(async () => pressShortcut()) + + expect(document.querySelector('[data-testid="dictation-setup-pill"]')).not.toBeNull() + expect(startCapture).not.toHaveBeenCalled() + }) + + it('offers the update again after a download was cancelled', async () => { + modelStates = [{ id: 'parakeet', status: 'not-downloaded', needsUpdate: true }] + await mountAndPress() + // The cancelled download's state lost its needsUpdate. + modelStates = [{ id: 'parakeet', status: 'not-downloaded' }] + await act(async () => pressShortcut()) + + expect(document.querySelector('[data-testid="dictation-setup-pill"]')).not.toBeNull() + expect(startCapture).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/dictation/speech-model-update-check.ts b/src/renderer/src/components/dictation/speech-model-update-check.ts new file mode 100644 index 00000000000..b781c271abd --- /dev/null +++ b/src/renderer/src/components/dictation/speech-model-update-check.ts @@ -0,0 +1,88 @@ +import { useAppStore } from '@/store' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' +import type { SpeechModelManifest, VoiceSettings } from '../../../../shared/speech-types' +import { + findSpeechModelUpdateTarget, + isSpeechModelReady, + type SpeechModelUpdateTarget +} from './speech-model-update-target' + +// The catalog never changes while the app runs. +let catalogRequest: Promise | null = null + +export function loadSpeechCatalog(): Promise { + catalogRequest ??= Promise.resolve() + // The paired web client's fallback resolves with nothing rather than a list. + .then(async () => (await window.api.speech.getCatalog()) ?? []) + .catch(() => { + // Not cached, so the next press asks again. + catalogRequest = null + return [] + }) + return catalogRequest +} + +// Only a model seen ready stays so: legacy or retired files never come back, so later presses skip the check. +const readyModelIds = new Set() +// What the pill offered stays offered until the model is ready, so a cancelled or failed download can resume. +const offeredTargets = new Map() +// A press during a prefetch joins it instead of asking main again. +const inFlightChecks = new Map>() + +type CheckedVoice = Pick + +/** True when no check is needed before recording with this model. */ +export function isSpeechModelKnownReady(voice: CheckedVoice): boolean { + return !voice.enabled || readyModelIds.has(voice.sttModel) || isPairedWebClientWindow() +} + +/** The download the selected model needs before it can dictate, checked before any mic capture. */ +export function checkSpeechModelUpdate( + voice: CheckedVoice +): Promise { + // Why skip paired web clients: the models live on the host, whose own window shows this. + if (isSpeechModelKnownReady(voice)) { + return Promise.resolve(null) + } + const modelId = voice.sttModel + let check = inFlightChecks.get(modelId) + if (!check) { + check = runCheck(voice).finally(() => inFlightChecks.delete(modelId)) + inFlightChecks.set(modelId, check) + } + return check +} + +async function runCheck(voice: CheckedVoice): Promise { + try { + const [catalog, states] = await Promise.all([ + loadSpeechCatalog(), + window.api.speech.getModelStates() + ]) + useAppStore.getState().setModelStates(states) + const selected = states.find((state) => state.id === voice.sttModel) + if (isSpeechModelReady(selected)) { + readyModelIds.add(voice.sttModel) + offeredTargets.delete(voice.sttModel) + return null + } + const target = + findSpeechModelUpdateTarget(voice, catalog, states) ?? + offeredTargets.get(voice.sttModel) ?? + null + if (target) { + offeredTargets.set(voice.sttModel, target) + } + return target + } catch { + // A failed check never blocks dictation; the start path reports a model that can't load. + return null + } +} + +export function resetSpeechModelUpdateCheckForTests(): void { + catalogRequest = null + readyModelIds.clear() + offeredTargets.clear() + inFlightChecks.clear() +} diff --git a/src/renderer/src/components/dictation/speech-model-update-target.ts b/src/renderer/src/components/dictation/speech-model-update-target.ts index 4b948a07b7d..ec9982fa058 100644 --- a/src/renderer/src/components/dictation/speech-model-update-target.ts +++ b/src/renderer/src/components/dictation/speech-model-update-target.ts @@ -33,5 +33,18 @@ export function findSpeechModelUpdateTarget( const retired = catalog.find( (m) => m.replacedBy === model.id && stateOf(m.id)?.status === 'ready' ) - return retired ? { model, retired } : null + if (retired) { + return { model, retired } + } + // A download in flight has no needsUpdate, yet the model still can't dictate; the pill shows its progress. + return isSpeechModelDownloading(selected) ? { model } : null +} + +export function isSpeechModelDownloading(state: SpeechModelState | undefined): boolean { + return state?.status === 'downloading' || state?.status === 'extracting' +} + +/** Only a ready model with no pending update is known to dictate. */ +export function isSpeechModelReady(state: SpeechModelState | undefined): boolean { + return state?.status === 'ready' && !state.needsUpdate } diff --git a/src/renderer/src/components/dictation/use-dictation-speech-model-setup.ts b/src/renderer/src/components/dictation/use-dictation-speech-model-setup.ts new file mode 100644 index 00000000000..cdcf53ec4fc --- /dev/null +++ b/src/renderer/src/components/dictation/use-dictation-speech-model-setup.ts @@ -0,0 +1,88 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { useAppStore } from '@/store' +import type { VoiceSettings } from '../../../../shared/speech-types' +import { captureInsertionTarget } from './dictation-insertion-target' +import { dictationPillAnchorFor, type DictationPillAnchor } from './dictation-pill-anchor' +import { checkSpeechModelUpdate, isSpeechModelKnownReady } from './speech-model-update-check' +import type { SpeechModelUpdateTarget } from './speech-model-update-target' + +type CheckedVoice = Pick + +const PREFETCH_DELAY_MS = 1500 + +/** The pill's offer of the download the selected model needs, made in place of recording. */ +export function useDictationSpeechModelSetup( + voice: CheckedVoice | undefined, + isIdle: () => boolean, + setPillAnchor: (anchor: DictationPillAnchor | null) => void +) { + const [setupTarget, setSetupTarget] = useState(null) + // The press whose model check is still running; a stop, cancel, toggle or teardown drops it. + const pendingStartRef = useRef(null) + const startRequestRef = useRef(0) + + const closeSetup = useCallback(() => { + setSetupTarget(null) + if (isIdle()) { + setPillAnchor(null) + } + }, [isIdle, setPillAnchor]) + + const hasPendingStart = useCallback(() => pendingStartRef.current !== null, []) + + const invalidatePendingStart = useCallback(() => { + startRequestRef.current += 1 + pendingStartRef.current = null + }, []) + + // An unmounted controller (voice turned off) must never open the mic from a check it started. + useEffect(() => invalidatePendingStart, [invalidatePendingStart]) + + // Warms the check off the startup path, so the first press records without waiting on main. + const enabled = voice?.enabled === true + const sttModel = voice?.sttModel + useEffect(() => { + if (!enabled || !sttModel || isSpeechModelKnownReady({ enabled, sttModel })) { + return + } + const timer = window.setTimeout( + () => void checkSpeechModelUpdate({ enabled, sttModel }), + PREFETCH_DELAY_MS + ) + return () => window.clearTimeout(timer) + }, [enabled, sttModel]) + + /** Checked before the mic opens, so a model the engine can't load never records; true to go on. */ + const readyToRecord = useCallback( + async (requested: CheckedVoice): Promise => { + if (isSpeechModelKnownReady(requested)) { + setSetupTarget(null) + return true + } + const request = ++startRequestRef.current + pendingStartRef.current = request + const target = await checkSpeechModelUpdate(requested) + if (request !== startRequestRef.current) { + return false + } + pendingStartRef.current = null + // Settings may have turned voice off or switched models while the check ran. + const current = useAppStore.getState().settings?.voice + if (!current?.enabled || current.sttModel !== requested.sttModel) { + return false + } + if (target) { + if (isIdle()) { + setPillAnchor(dictationPillAnchorFor(captureInsertionTarget())) + setSetupTarget(target) + } + return false + } + setSetupTarget(null) + return true + }, + [isIdle, setPillAnchor] + ) + + return { setupTarget, closeSetup, hasPendingStart, invalidatePendingStart, readyToRecord } +} diff --git a/src/renderer/src/components/dictation/use-speech-model-update-download.ts b/src/renderer/src/components/dictation/use-speech-model-update-download.ts new file mode 100644 index 00000000000..0496c35d6e6 --- /dev/null +++ b/src/renderer/src/components/dictation/use-speech-model-update-download.ts @@ -0,0 +1,102 @@ +import { useEffect, useState } from 'react' +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import type { SpeechModelUpdateTarget } from './speech-model-update-target' + +export type SpeechModelUpdatePhase = 'notice' | 'downloading' | 'done' | 'failed' + +export type SpeechModelUpdateDownload = { + phase: SpeechModelUpdatePhase + percent: number + doneMb: number + totalMb: number + deleting: boolean + start: () => void + cancel: () => void + deleteRetired: () => void +} + +/** Downloads the model the speech engine needs; follows the shared model states, as Settings can start it too. */ +export function useSpeechModelUpdateDownload( + { model, retired }: SpeechModelUpdateTarget, + onClose: () => void +): SpeechModelUpdateDownload { + const t = useTranslate() + const state = useAppStore((s) => s.modelStates.find((m) => m.id === model.id)) + const refreshModelStates = useAppStore((s) => s.refreshModelStates) + const [failed, setFailed] = useState(false) + // Set from the click, so ✕ cancels a download whose first progress hasn't arrived yet. + const [inFlight, setInFlight] = useState(false) + const [deleting, setDeleting] = useState(false) + + useEffect( + () => window.api.speech.onDownloadProgress(() => void refreshModelStates()), + [refreshModelStates] + ) + + const totalMb = Math.round((model.sizeBytes ?? 0) / 1_000_000) + const progress = state?.progress ?? 0 + const downloading = + state?.status === 'downloading' || + state?.status === 'extracting' || + (inFlight && state?.status !== 'ready') + const phase: SpeechModelUpdatePhase = downloading + ? 'downloading' + : state?.status === 'ready' + ? 'done' + : failed + ? 'failed' + : 'notice' + + const start = (): void => { + setFailed(false) + setInFlight(true) + void window.api.speech + .downloadModel(model.id) + .catch(() => setFailed(true)) + .finally(() => { + setInFlight(false) + void refreshModelStates() + }) + } + + const cancel = (): void => { + void window.api.speech + .cancelDownload(model.id) + .catch(() => undefined) + .finally(() => void refreshModelStates()) + } + + const deleteRetired = (): void => { + if (!retired) { + return + } + setDeleting(true) + void window.api.speech + .deleteModel(retired.id) + .then(() => { + void refreshModelStates() + onClose() + }) + .catch(() => { + setDeleting(false) + toast.error( + t('speechModelUpdate.pill.deleteFailed', 'Failed to delete {{model}}.', { + model: retired.label + }) + ) + }) + } + + return { + phase, + percent: Math.round(progress * 100), + doneMb: Math.round(progress * totalMb), + totalMb, + deleting, + start, + cancel, + deleteRetired + } +} diff --git a/src/renderer/src/components/editor/editor-dropped-file-open.ts b/src/renderer/src/components/editor/editor-dropped-file-open.ts index 3710cedf3ec..34803145b62 100644 --- a/src/renderer/src/components/editor/editor-dropped-file-open.ts +++ b/src/renderer/src/components/editor/editor-dropped-file-open.ts @@ -19,7 +19,7 @@ import { captureWorktreeSshMutationExpectation } from '@/lib/ssh-mutation-expect import { statUserOpenedPath } from '@/lib/user-opened-local-path' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { DROP_STAGING_RELATIVE_DIR } from '../../../../shared/drop-staging-ignore' -import { openDocumentInFloatingWorkspace } from '@/lib/open-document-in-floating-workspace' +import { openDocumentInFloatingWorkspace } from '@/components/floating-terminal/open-document-in-floating-workspace' import { requireRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import { parseExecutionHostId } from '../../../../shared/execution-host' import { diff --git a/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx b/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx index 82744bf09e0..f2c9d0f0cb1 100644 --- a/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx +++ b/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx @@ -1,6 +1,7 @@ import type { ITheme } from '@xterm/xterm' import { cn } from '@/lib/utils' -import { getBuiltinTheme } from '@/lib/terminal-theme' +import '@/lib/terminal-theme' +import { getTheme } from '@/lib/terminal-themes-data' import { DEFAULT_TERMINAL_THEME_DARK, DEFAULT_TERMINAL_THEME_LIGHT @@ -32,8 +33,8 @@ const ANSI_PALETTE_KEYS = [ // Why: the default terminal themes already carry ANSI palettes tuned for Orca's dark and light surfaces. const ANSI_PALETTES = { - dark: ANSI_PALETTE_KEYS.map((key) => getBuiltinTheme(DEFAULT_TERMINAL_THEME_DARK)?.[key]), - light: ANSI_PALETTE_KEYS.map((key) => getBuiltinTheme(DEFAULT_TERMINAL_THEME_LIGHT)?.[key]) + dark: ANSI_PALETTE_KEYS.map((key) => getTheme(DEFAULT_TERMINAL_THEME_DARK)?.[key]), + light: ANSI_PALETTE_KEYS.map((key) => getTheme(DEFAULT_TERMINAL_THEME_LIGHT)?.[key]) } function valueToText(value: unknown): string { diff --git a/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx b/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx index 6612ba225c7..d4917f2b16f 100644 --- a/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx +++ b/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx @@ -28,7 +28,7 @@ import { DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu' -import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' import '@/lib/agent-session/messaging/terminal/active-agent-note-send' import { activeAgentNotesSendFailureMessage, diff --git a/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.ts b/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.ts index f55af428a3b..fa1695dfba3 100644 --- a/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.ts +++ b/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.ts @@ -1,7 +1,7 @@ import { useEffect, type RefObject } from 'react' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { isEditableTarget } from '@/lib/text-input/focus/editable-target' -import { isEventTargetInsideFloatingWorkspacePanel } from '@/lib/floating-workspace-terminal-actions' +import { isEventTargetInsideFloatingWorkspacePanel } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { keybindingMatchesAction, type KeybindingOverrides } from '../../../../shared/keybindings' import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router' diff --git a/src/renderer/src/components/editor/viewer-zoom-request.ts b/src/renderer/src/components/editor/viewer-zoom-request.ts index c60278534a0..f3aae0d4262 100644 --- a/src/renderer/src/components/editor/viewer-zoom-request.ts +++ b/src/renderer/src/components/editor/viewer-zoom-request.ts @@ -1,4 +1,4 @@ -import { isEventTargetInsideFloatingWorkspacePanel } from '@/lib/floating-workspace-terminal-actions' +import { isEventTargetInsideFloatingWorkspacePanel } from '@/components/floating-terminal/floating-workspace-terminal-actions' export type ViewerZoomDirection = 'in' | 'out' | 'reset' diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx index 32d7b8bb2f7..717b6f99ec8 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx @@ -4,7 +4,7 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { AgentIcon } from '@/components/agent/icons/AgentIcon' -import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' import { launchAgentInNewTab } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/floating-terminal/floating-terminal-focus-reporting.ts b/src/renderer/src/components/floating-terminal/floating-terminal-focus-reporting.ts index c9ab460e00a..896a5d58962 100644 --- a/src/renderer/src/components/floating-terminal/floating-terminal-focus-reporting.ts +++ b/src/renderer/src/components/floating-terminal/floating-terminal-focus-reporting.ts @@ -1,7 +1,7 @@ import { isEventTargetInsideFloatingWorkspacePanel, isFloatingWorkspaceTerminalInputTarget -} from '@/lib/floating-workspace-terminal-actions' +} from '@/components/floating-terminal/floating-workspace-terminal-actions' let lastReportedFloatingFocus: { panelFocused: boolean; terminalFocused: boolean } | null = null let lastReportedFloatingFocusFn: unknown = null diff --git a/src/renderer/src/components/floating-terminal/floating-terminal-panel-types.ts b/src/renderer/src/components/floating-terminal/floating-terminal-panel-types.ts index a065c2013ae..f681d30e67b 100644 --- a/src/renderer/src/components/floating-terminal/floating-terminal-panel-types.ts +++ b/src/renderer/src/components/floating-terminal/floating-terminal-panel-types.ts @@ -1,4 +1,4 @@ -import type { FloatingWorkspacePanelOwnedAction } from '@/lib/floating-workspace-shortcut-policy' +import type { FloatingWorkspacePanelOwnedAction } from '@/components/floating-terminal/floating-workspace-shortcut-policy' import type { KeybindingActionId, PhysicalModifierToken } from '../../../../shared/keybindings' import type { TerminalAgentTabShortcut } from '@/components/terminal-agent-tab-shortcut' diff --git a/src/renderer/src/lib/floating-terminal.ts b/src/renderer/src/components/floating-terminal/floating-terminal.ts similarity index 100% rename from src/renderer/src/lib/floating-terminal.ts rename to src/renderer/src/components/floating-terminal/floating-terminal.ts diff --git a/src/renderer/src/components/floating-terminal/floating-workspace-availability.ts b/src/renderer/src/components/floating-terminal/floating-workspace-availability.ts new file mode 100644 index 00000000000..c797d2a0f24 --- /dev/null +++ b/src/renderer/src/components/floating-terminal/floating-workspace-availability.ts @@ -0,0 +1,13 @@ +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import { isWebClientLocation } from '../../lib/web-client-location' + +/** The floating workspace's terminals and notes live on this computer; a browser tab has none. */ +export function floatingWorkspaceUnavailableReason(t: Translate = translate): string | null { + return isWebClientLocation() + ? t( + 'auto.lib.floating.workspace.availability.web', + 'The floating workspace runs on your own computer, so it is only available in the Orca desktop app.' + ) + : null +} diff --git a/src/renderer/src/lib/floating-workspace-focus-reclaim.ts b/src/renderer/src/components/floating-terminal/floating-workspace-focus-reclaim.ts similarity index 100% rename from src/renderer/src/lib/floating-workspace-focus-reclaim.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-focus-reclaim.ts diff --git a/src/renderer/src/lib/floating-workspace-guest-bridge.ts b/src/renderer/src/components/floating-terminal/floating-workspace-guest-bridge.ts similarity index 100% rename from src/renderer/src/lib/floating-workspace-guest-bridge.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-guest-bridge.ts diff --git a/src/renderer/src/lib/floating-workspace-panel-reveal.ts b/src/renderer/src/components/floating-terminal/floating-workspace-panel-reveal.ts similarity index 78% rename from src/renderer/src/lib/floating-workspace-panel-reveal.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-panel-reveal.ts index db8ffe69826..446feb50d70 100644 --- a/src/renderer/src/lib/floating-workspace-panel-reveal.ts +++ b/src/renderer/src/components/floating-terminal/floating-workspace-panel-reveal.ts @@ -1,6 +1,8 @@ import type { AppState } from '@/store/types' import { selectFloatingWorkspacePanelVisible } from '@/store/workspaces/floating/floating-workspace-panel-selector' +import { toast } from 'sonner' import { TOGGLE_FLOATING_TERMINAL_EVENT } from './floating-terminal' +import { floatingWorkspaceUnavailableReason } from './floating-workspace-availability' function toggleFloatingWorkspacePanel(): void { window.dispatchEvent(new Event(TOGGLE_FLOATING_TERMINAL_EVENT)) @@ -9,18 +11,24 @@ function toggleFloatingWorkspacePanel(): void { // Enable before toggling: floating tabs outlive feature disable and would otherwise reveal silently into nothing. // Why enable first: floating tabs outlive a feature disable, and the panel ignores the toggle // while disabled, so a live floating agent row would otherwise be a silent no-op. +/** Returns false when the floating workspace cannot be shown here (the user is told why). */ export function revealFloatingWorkspacePanel( state: Pick -): void { +): boolean { // Why: host reveals can beat settings hydration; enabling then would overwrite a saved `false`. if (!state.settings) { - return + return true + } + const unavailable = floatingWorkspaceUnavailableReason() + if (unavailable) { + toast.info(unavailable) + return false } if (state.settings.floatingTerminalEnabled === true) { if (!selectFloatingWorkspacePanelVisible(state)) { toggleFloatingWorkspacePanel() } - return + return true } // Enabling shows a panel that was left open; only a closed one still needs the toggle. const wasOpen = state.floatingWorkspacePanelOpen @@ -30,4 +38,5 @@ export function revealFloatingWorkspacePanel( requestAnimationFrame(toggleFloatingWorkspacePanel) } }) + return true } diff --git a/src/renderer/src/lib/floating-workspace-shortcut-policy.ts b/src/renderer/src/components/floating-terminal/floating-workspace-shortcut-policy.ts similarity index 99% rename from src/renderer/src/lib/floating-workspace-shortcut-policy.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-shortcut-policy.ts index 392d413377b..028141fdf78 100644 --- a/src/renderer/src/lib/floating-workspace-shortcut-policy.ts +++ b/src/renderer/src/components/floating-terminal/floating-workspace-shortcut-policy.ts @@ -5,7 +5,7 @@ import { type KeybindingMatchOptions, type KeybindingOverrides, type PhysicalModifierToken -} from '../../../shared/keybindings' +} from '../../../../shared/keybindings' // Allow synthetic double-tap inputs without key/modifier fields, but still require their event target. type FloatingWorkspaceShortcutEvent = Partial< diff --git a/src/renderer/src/lib/floating-workspace-tab-creation.ts b/src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts similarity index 83% rename from src/renderer/src/lib/floating-workspace-tab-creation.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts index bebb8e4093c..37009a22a4e 100644 --- a/src/renderer/src/lib/floating-workspace-tab-creation.ts +++ b/src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts @@ -1,12 +1,12 @@ -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import { createUntitledMarkdownFileWithTemplateSelection } from './editor/file-operations/create-untitled-markdown' -import { getConnectionId } from './workspace/ownership/connection-context' -import { detectLanguage } from '../../../shared/editor-language/editor-language-detect' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { createUntitledMarkdownFileWithTemplateSelection } from '../../lib/editor/file-operations/create-untitled-markdown' +import { getConnectionId } from '../../lib/workspace/ownership/connection-context' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import type { AppState } from '@/store/types' -import { focusTerminalTabSurface } from './focus-terminal-tab-surface' -import { createNonSecureContextUuid as createBrowserUuid } from '../../../shared/non-secure-context-uuid' +import { focusTerminalTabSurface } from '../terminal-pane/input/focus/focus-terminal-tab-surface' +import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/non-secure-context-uuid' import { translate } from '@/i18n/i18n' -import { assertClientCreationActionAvailable } from './client-creation-action-policy' +import { assertClientCreationActionAvailable } from '../../lib/client-creation-action-policy' type FloatingWorkspaceTerminalStore = Pick diff --git a/src/renderer/src/lib/floating-workspace-terminal-actions.ts b/src/renderer/src/components/floating-terminal/floating-workspace-terminal-actions.ts similarity index 88% rename from src/renderer/src/lib/floating-workspace-terminal-actions.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-terminal-actions.ts index d4440181270..91a1d5f29d5 100644 --- a/src/renderer/src/lib/floating-workspace-terminal-actions.ts +++ b/src/renderer/src/components/floating-terminal/floating-workspace-terminal-actions.ts @@ -1,6 +1,6 @@ -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type { BrowserWorkspace } from '../../../shared/browser-workspace-types' -import type { TabGroup } from '../../../shared/tab-types' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' +import type { TabGroup } from '../../../../shared/tab-types' import { getGroupVisibleTabOrder } from '@/components/tab-bar/group-tab-order' import { getNextTabAcrossAllTypes, @@ -13,24 +13,14 @@ import { import type { AppState } from '@/store/types' import { selectEmptyFloatingWorkspacePanelVisible, - selectFloatingVisibleTabCount, type EmptyFloatingWorkspacePanelState } from '@/store/workspaces/floating/floating-workspace-panel-selector' -import { resolveBrowserWorkspaceOwner } from './browser/workspace/browser-workspace-source-resolution' +import { resolveBrowserWorkspaceOwner } from '../../lib/browser/workspace/browser-workspace-source-resolution' import { TOGGLE_FLOATING_TERMINAL_EVENT } from './floating-terminal' -import { focusTerminalTabSurface } from './focus-terminal-tab-surface' -import { keybindingMatchesAction, type KeybindingOverrides } from '../../../shared/keybindings' -export { - createFloatingWorkspaceBrowserTab, - createFloatingWorkspaceMarkdownTab, - createFloatingWorkspaceTerminalTab -} from './floating-workspace-tab-creation' -export { - isFloatingWorkspacePanelShortcut, - isFloatingWorkspacePanelShortcutTarget, - matchFloatingWorkspacePanelChord, - matchFloatingWorkspacePanelShortcut -} from './floating-workspace-shortcut-policy' +import { focusTerminalTabSurface } from '../terminal-pane/input/focus/focus-terminal-tab-surface' +import { keybindingMatchesAction, type KeybindingOverrides } from '../../../../shared/keybindings' +import './floating-workspace-tab-creation' +import './floating-workspace-shortcut-policy' type FloatingWorkspaceTabSwitchMode = 'same-type' | 'all-types' | 'terminal' @@ -97,13 +87,6 @@ function getFloatingWorkspaceVisibleTabs( ) } -/** Recount when async close resolves; concurrent creates/no-op closes can invalidate render-time empty-panel predictions. */ -export function countVisibleFloatingWorkspaceItems( - store: Parameters[0] -): number { - return selectFloatingVisibleTabCount(store) -} - function getFloatingWorkspaceActiveEntry( visibleTabs: readonly TypeCyclableTab[], group: TabGroup diff --git a/src/renderer/src/lib/floating-workspace-tour-interaction-snapshot.ts b/src/renderer/src/components/floating-terminal/floating-workspace-tour-interaction-snapshot.ts similarity index 94% rename from src/renderer/src/lib/floating-workspace-tour-interaction-snapshot.ts rename to src/renderer/src/components/floating-terminal/floating-workspace-tour-interaction-snapshot.ts index d2b826b9aea..6493452846f 100644 --- a/src/renderer/src/lib/floating-workspace-tour-interaction-snapshot.ts +++ b/src/renderer/src/components/floating-terminal/floating-workspace-tour-interaction-snapshot.ts @@ -1,7 +1,7 @@ import { hasFeatureInteraction, type FeatureInteractionState -} from '../../../shared/feature-interactions' +} from '../../../../shared/feature-interactions' export type FloatingWorkspaceTourInteractionSnapshot = { wasPreviouslyInteracted?: boolean diff --git a/src/renderer/src/lib/open-document-in-floating-workspace.ts b/src/renderer/src/components/floating-terminal/open-document-in-floating-workspace.ts similarity index 76% rename from src/renderer/src/lib/open-document-in-floating-workspace.ts rename to src/renderer/src/components/floating-terminal/open-document-in-floating-workspace.ts index e9437c94774..c560585609b 100644 --- a/src/renderer/src/lib/open-document-in-floating-workspace.ts +++ b/src/renderer/src/components/floating-terminal/open-document-in-floating-workspace.ts @@ -1,7 +1,7 @@ -import type { FileDocument } from '../../../shared/file-listing/file-document' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' +import type { FileDocument } from '../../../../shared/file-listing/file-document' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import type { EditorFilesSlice } from '@/store/slices/editor/types/editor-files-slice' -import { detectLanguage } from '../../../shared/editor-language/editor-language-detect' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' /** Open picker/shell-resolved absolute local files in the floating workspace; focused runtime routing would read the wrong machine. */ export function openDocumentInFloatingWorkspace( diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts index faa1c0de455..08c2f74b06f 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts @@ -4,9 +4,9 @@ import { resolveGroupTabFromVisibleId } from '@/components/tab-group/tab-group-v import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { createUntitledMarkdownFileWithTemplateSelection } from '@/lib/editor/file-operations/create-untitled-markdown' import { ensureClientCreationActionAllowed } from '@/lib/client-creation-action-error' -import { openDocumentInFloatingWorkspace } from '@/lib/open-document-in-floating-workspace' +import { openDocumentInFloatingWorkspace } from '@/components/floating-terminal/open-document-in-floating-workspace' import { extractIpcErrorMessage } from '@/lib/ipc-error' -import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/non-secure-context-uuid' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts index eee2d5b02b4..a9a4198a4f3 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts @@ -1,8 +1,8 @@ import { useEffect } from 'react' -import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' import { isFocusKeepingPress } from '@/lib/focus-keeping-press' -import { clearFloatingPanelReclaimIntent } from '@/lib/floating-workspace-focus-reclaim' -import { isFloatingWorkspaceTerminalInputTarget } from '@/lib/floating-workspace-terminal-actions' +import { clearFloatingPanelReclaimIntent } from '@/components/floating-terminal/floating-workspace-focus-reclaim' +import { isFloatingWorkspaceTerminalInputTarget } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { reportFloatingFocus } from './floating-terminal-focus-reporting' import type { FloatingWorkspaceChromeModel } from './use-floating-workspace-chrome-model' import type { FloatingTerminalPanelLocalState } from './use-floating-terminal-panel-local-state' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-global-shortcut-listeners.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-global-shortcut-listeners.ts index 25317fe22d4..b0e64cb3200 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-global-shortcut-listeners.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-global-shortcut-listeners.ts @@ -3,7 +3,7 @@ import { isEventTargetInsideFloatingWorkspacePanel, isFloatingWorkspaceTerminalInputTarget, switchFloatingWorkspaceTab -} from '@/lib/floating-workspace-terminal-actions' +} from '@/components/floating-terminal/floating-workspace-terminal-actions' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { useAppStore } from '@/store' import { diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-guest-bridge.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-guest-bridge.ts index 4b2bbb24b66..0fb3480ca57 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-guest-bridge.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-guest-bridge.ts @@ -4,7 +4,7 @@ import { FLOATING_WORKSPACE_GUEST_SELECT_INDEX_EVENT, type FloatingWorkspaceGuestCloseDetail, type FloatingWorkspaceGuestSelectIndexDetail -} from '@/lib/floating-workspace-guest-bridge' +} from '@/components/floating-terminal/floating-workspace-guest-bridge' import type { FloatingTerminalPanelShortcuts } from './use-floating-terminal-panel-shortcuts' type FloatingTerminalGuestBridgeInput = Pick< diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-initial-focus-effects.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-initial-focus-effects.ts index 9ac3490fc30..c055650618e 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-initial-focus-effects.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-initial-focus-effects.ts @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' import { reportFloatingFocus } from './floating-terminal-focus-reporting' import type { FloatingWorkspaceChromeModel } from './use-floating-workspace-chrome-model' import type { FloatingTerminalPanelLocalState } from './use-floating-terminal-panel-local-state' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-focus-reclaim.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-focus-reclaim.ts index 4680223b512..dc7ab8f347c 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-focus-reclaim.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-focus-reclaim.ts @@ -4,7 +4,7 @@ import { consumeFloatingPanelReclaimIntent, isFloatingPanelReclaimIntentArmed, subscribeFloatingPanelReclaimIntent -} from '@/lib/floating-workspace-focus-reclaim' +} from '@/components/floating-terminal/floating-workspace-focus-reclaim' import { reportFloatingFocus } from './floating-terminal-focus-reporting' import type { FloatingWorkspaceChromeModel } from './use-floating-workspace-chrome-model' import type { FloatingTerminalPanelLocalState } from './use-floating-terminal-panel-local-state' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-maximize.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-maximize.ts index 4349b3ced50..3fc9defd746 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-maximize.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-maximize.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect } from 'react' -import { consumeFloatingTerminalOpenMaximizedIntent } from '@/lib/floating-terminal' +import { consumeFloatingTerminalOpenMaximizedIntent } from '@/components/floating-terminal/floating-terminal' import { getMaximizedFloatingTerminalBounds, resolveFloatingTerminalPanelBounds, diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts index 96a4685fc45..f4d6ce4e291 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts @@ -4,8 +4,8 @@ import { ensureClientCreationActionAllowed } from '@/lib/client-creation-action- import { matchFloatingWorkspacePanelOwnedAction, matchFloatingWorkspacePanelShortcut -} from '@/lib/floating-workspace-shortcut-policy' -import { isFloatingWorkspaceTerminalInputTarget } from '@/lib/floating-workspace-terminal-actions' +} from '@/components/floating-terminal/floating-workspace-shortcut-policy' +import { isFloatingWorkspaceTerminalInputTarget } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { requestTerminalTabRename } from '@/components/tab-bar/terminal-tab-rename-request' import { resolveTerminalAgentTabShortcut } from '@/components/terminal-agent-tab-shortcut' diff --git a/src/renderer/src/components/linear-issue-project-selector.tsx b/src/renderer/src/components/linear-issue-project-selector.tsx index 5067124df84..45dd7c3e76e 100644 --- a/src/renderer/src/components/linear-issue-project-selector.tsx +++ b/src/renderer/src/components/linear-issue-project-selector.tsx @@ -1,5 +1,6 @@ import { getLinearSourceScope } from '@/store/slices/linear/linear-slice-scope' -import { confirmLinearIssueWrite } from '@/store/slices/linear/linear-issue-publication' +import '@/store/slices/linear/linear-issue-read' +import { confirmLinearIssueWrite } from '@/store/slices/linear/linear-issue-write-publication' import { taskProviderErrorMessage, taskProviderErrorText diff --git a/src/renderer/src/components/linear-issue-sub-issues.tsx b/src/renderer/src/components/linear-issue-sub-issues.tsx index 94c6fefe105..b299ea84974 100644 --- a/src/renderer/src/components/linear-issue-sub-issues.tsx +++ b/src/renderer/src/components/linear-issue-sub-issues.tsx @@ -1,4 +1,5 @@ -import { observeLinearIssueRead } from '@/store/slices/linear/linear-issue-publication' +import '@/store/slices/linear/linear-issue-read' +import { observeLinearIssueRead } from '@/store/slices/linear/linear-issue-read-lifecycle' import { taskProviderErrorMessage, taskProviderErrorText diff --git a/src/renderer/src/components/linear-issue-workspace-detail-state.ts b/src/renderer/src/components/linear-issue-workspace-detail-state.ts index b63e4d3335d..609d049f4ee 100644 --- a/src/renderer/src/components/linear-issue-workspace-detail-state.ts +++ b/src/renderer/src/components/linear-issue-workspace-detail-state.ts @@ -1,6 +1,7 @@ import { useAppStore } from '@/store' import { getLinearSourceScope } from '@/store/slices/linear/linear-slice-scope' -import { observeLinearIssueRead } from '@/store/slices/linear/linear-issue-publication' +import '@/store/slices/linear/linear-issue-read' +import { observeLinearIssueRead } from '@/store/slices/linear/linear-issue-read-lifecycle' import { useLinearIssuePublication } from '@/hooks/useLinearIssuePublication' import { translate } from '@/i18n/i18n' import { taskProviderErrorText } from '@/lib/work-items/task-provider-error-copy' diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx index c4fc8c4b958..53a0ebbc0a0 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx @@ -223,7 +223,7 @@ export function NativeChatMessageList({ subagentChoices, forkOffer, line: { - draws: tailRow === 'activity', + tailRow, thinking: turnStatuses.active?.thinking === true, stopping, activityText: turnActivity?.text diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts index 87f861438a3..c891f6e147e 100644 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts +++ b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts @@ -5,13 +5,13 @@ import type { GlobalSettings } from '../../../../../shared/global-settings-types import { resolveNativeChatAppearanceSettings } from '../../../../../shared/native-chat/native-chat-appearance-settings' import { resolveConfiguredTerminalColors } from '../../../../../shared/terminal-themes/terminal-theme-selection' import { MATCH_TERMINAL_APP_THEME } from '../../../../../shared/plugin-theme-settings' -import { buildFontFamily } from '@/lib/monospace-font-family' -import { buildAppFontFamily } from '@/lib/app-font-family' +import { buildFontFamily } from '@/app-shell/appearance/monospace-font-family' +import { buildAppFontFamily } from '@/app-shell/appearance/app-font-family' import { resolveEditorFontStack } from '@/lib/editor/appearance/editor-typography' import { getSystemPrefersDark } from '@/lib/terminal-theme' import { isTerminalBackgroundLight } from '../../../../../shared/terminal-themes/terminal-title-contrast' import { useSystemPrefersDark } from '../../../hooks/theme/use-system-prefers-dark' -import { terminalChatSelectionMix } from '@/lib/chat-selection-mix' +import { terminalChatSelectionMix } from '@/app-shell/appearance/chat-selection-mix' export const NATIVE_CHAT_APPEARANCE_ROOT_CLASS = 'native-chat-appearance bg-chat-canvas' // Bottom padding clears 20px control overhang; rail padding also covers its 34px overlay on macOS without scrollbar gutters. diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.test.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.test.ts new file mode 100644 index 00000000000..e29ddca593e --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.test.ts @@ -0,0 +1,239 @@ +import { describe, expect, it } from 'vitest' + +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { NativeChatTurnStatus } from '../../../../../../shared/native-chat/transcript/native-chat-turn-status' +import type { NativeChatResolvedPrompt } from '../../../../../../shared/native-chat/native-chat-resolution-receipt' +import type { NativeChatTurnDiff } from '../../../../../../shared/native-chat/tools/native-chat-turn-diffs' +import { nativeChatSubagentSections } from '../../subagents/native-chat-subagent-sections' +import { + buildNativeChatTranscriptSlots, + type NativeChatMessageSlot +} from './native-chat-transcript-slots' + +const SETTLED: NativeChatTurnStatus = { startedAt: 1, thinking: false, workedSeconds: 4 } +const DIFF: NativeChatTurnDiff = { files: [], added: 1, removed: 0, truncated: false } + +function text( + id: string, + body: string, + role: NativeChatMessage['role'] = 'assistant' +): NativeChatMessage { + return { id, role, blocks: [{ type: 'text', text: body }], timestamp: 1, source: 'transcript' } +} + +function workerUpdate(id: string): NativeChatMessage { + return { + ...text(id, 'Update from worker', 'user'), + from: { kind: 'agent', senders: [], orchestration: null } + } +} + +function toolRun(id: string): NativeChatMessage { + return { + id, + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'shell', input: { command: 'ls' }, state: 'completed' }], + timestamp: 1, + source: 'transcript' + } +} + +type Overrides = Partial[0]> + +function build(messages: NativeChatMessage[], overrides: Overrides = {}): NativeChatMessageSlot[] { + let turn: string | undefined + const turnKeys = messages.map((message) => { + // A worker's update lands inside the turn it reached, as the host attributes it. + if (message.role === 'user' && !message.from) { + turn = message.id + } + return turn + }) + return buildNativeChatTranscriptSlots({ + messages, + turnKeys, + liveTurnKey: undefined, + receipts: new Map(), + turnStatuses: { active: null, completedByTurn: {} }, + turnDiffs: new Map(), + expandedTurnKeys: new Set(), + isWorking: false, + lifecycleWorking: false, + ...overrides + }).filter((slot): slot is NativeChatMessageSlot => slot.kind === 'message') +} + +function answer(messages: NativeChatMessage[], overrides: Overrides = {}): NativeChatMessageSlot { + const slot = build(messages, overrides).find((candidate) => candidate.message.id === 'answer') + if (!slot) { + throw new Error('Missing the answer row') + } + return slot +} + +const PROMPT = text('u', 'go', 'user') +const ANSWER = text('answer', 'done') +/** One line of text: the row's minimum while its controls hang, 20px more with them in flow. */ +const HANGING_PX = 24 +const IN_FLOW_PX = 44 + +describe('response actions hang', () => { + it("hangs above the person's own bubble and at the end of the transcript", () => { + const followed = answer([PROMPT, ANSWER, text('u2', 'next', 'user')]) + expect(followed.actionsHang).toBe(true) + expect(followed.estimatedHeight).toBe(HANGING_PX) + expect(answer([PROMPT, ANSWER]).actionsHang).toBe(true) + }) + + it('keeps its own height above anything left-side in the next row', () => { + for (const next of [ + workerUpdate('w'), + text('n', 'notice', 'system'), + toolRun('tool'), + text('thought', 'thinking', 'reasoning') + ]) { + const slot = answer([PROMPT, ANSWER, next], { expandedTurnKeys: new Set(['u']) }) + expect([next.id, slot.actionsHang]).toEqual([next.id, undefined]) + expect([next.id, slot.estimatedHeight]).toEqual([next.id, IN_FLOW_PX]) + } + }) + + it('keeps its own height above a turn bar drawn above the next bubble', () => { + const messages = [PROMPT, ANSWER, text('u2', 'next', 'user')] + // The next turn's opener is not loaded, so its bar draws above the row that stands in for it. + const barAbove = build(messages, { + turnKeys: ['u', 'u', 'unloaded'], + turnStatuses: { active: null, completedByTurn: { unloaded: SETTLED } } + }) + expect(barAbove.map((slot) => [slot.message.id, slot.statusAbove, slot.actionsHang])).toEqual([ + ['u', false, undefined], + ['answer', false, undefined], + ['u2', true, undefined] + ]) + }) + + it('keeps its own height above what its own row draws after the message', () => { + const next = text('u2', 'next', 'user') + const withDiff = answer([PROMPT, ANSWER, next], { turnDiffs: new Map([['u', DIFF]]) }) + expect(withDiff.turnDiff).toBe(DIFF) + expect(withDiff.actionsHang).toBeUndefined() + + const pullRequests = [ + { + provider: 'github' as const, + url: 'https://github.com/acme/app/pull/1', + slug: { owner: 'acme', repo: 'app' }, + number: 1 + } + ] + const withPullRequests = answer([PROMPT, ANSWER, next], { + openedPullRequests: new Map([['u', pullRequests]]) + }) + expect(withPullRequests.openedPullRequests).toBe(pullRequests) + expect(withPullRequests.actionsHang).toBeUndefined() + + // Even as the last slot: the rollup is what sits under the controls. + expect(answer([PROMPT, ANSWER], { turnDiffs: new Map([['u', DIFF]]) }).actionsHang).toBe( + undefined + ) + }) + + it('keeps its own height above a status row drawn below the message', () => { + // A turn keyed by the answer itself draws its bar under that row, as it does under a prompt. + const below = answer([ANSWER, text('u2', 'next', 'user')], { + turnKeys: ['answer', 'u2'], + turnStatuses: { active: null, completedByTurn: { answer: SETTLED } } + }) + expect(below.status).toBe(SETTLED) + expect(below.statusAbove).toBe(false) + expect(below.drawsMessage).toBe(true) + expect(below.actionsHang).toBeUndefined() + // Drawn above the row instead, the bar leaves nothing under the controls. + const above = answer([ANSWER, text('u2', 'next', 'user')], { + turnKeys: ['unloaded', 'u2'], + turnStatuses: { active: null, completedByTurn: { unloaded: SETTLED } } + }) + expect(above.statusAbove).toBe(true) + expect(above.actionsHang).toBe(true) + }) + + it('charges the estimate only on a row that holds controls', () => { + // A working turn's frontier offers no controls, so nothing is added though a card follows. + const working = answer([PROMPT, ANSWER, workerUpdate('w')], { + liveTurnKey: 'u', + isWorking: true + }) + expect(working.actionsHang).toBeUndefined() + expect(working.estimatedHeight).toBe(HANGING_PX) + // The turn's actions belong to its last words, so an earlier response holds none. + const earlier = build([PROMPT, text('first', 'looking'), toolRun('tool'), ANSWER], { + expandedTurnKeys: new Set(['u']) + }).find((slot) => slot.message.id === 'first') + expect(earlier?.endsResponse).toBe(false) + expect(earlier?.estimatedHeight).toBe(HANGING_PX) + // Spacing scales the controls with the rest of the row's chrome. + expect( + answer([PROMPT, ANSWER, workerUpdate('w')], { + typography: { lineHeightPx: 22, charsPerLine: 96, spacingScale: 1.5 } + }).estimatedHeight + ).toBe(54) + }) + + it('keeps its own height at the end while a row draws under the transcript', () => { + expect(answer([PROMPT, ANSWER], { tailRowBelow: true }).actionsHang).toBeUndefined() + // Only the last slot sits above that row. + expect( + answer([PROMPT, ANSWER, text('u2', 'next', 'user')], { tailRowBelow: true }).actionsHang + ).toBe(true) + }) + + it('looks past a failed send, which draws after the transcript and its tail row', () => { + const failed: NativeChatMessage = { ...text('failed', 'retry me', 'user'), unsent: true } + expect(answer([PROMPT, ANSWER, failed]).actionsHang).toBe(true) + expect(answer([PROMPT, ANSWER, failed], { tailRowBelow: true }).actionsHang).toBeUndefined() + expect(answer([PROMPT, ANSWER, failed, workerUpdate('w')]).actionsHang).toBeUndefined() + }) + + it('leaves rows that never hold response controls alone', () => { + const slots = build([PROMPT, ANSWER, text('n', 'notice', 'system'), workerUpdate('w')]) + expect(slots.map((slot) => [slot.message.id, slot.actionsHang])).toEqual([ + ['u', undefined], + ['answer', undefined], + ['n', undefined], + ['w', undefined] + ]) + }) + + it('leaves a subagent section as it was, and counts its head as left-side', () => { + const roster: NativeChatMessage = { + id: 'roster', + role: 'system', + blocks: [ + { + type: 'subagent-group', + groupId: 'root', + agents: [{ id: 'worker', label: 'worker', state: 'completed' }] + } + ], + timestamp: 1, + source: 'transcript' + } + const child = text('child', 'reading') + const conversation = [PROMPT, ANSWER, roster, text('u2', 'next', 'user')] + const input: Overrides = { + subagentSections: nativeChatSubagentSections( + conversation, + new Map([['worker', [{ message: child, turnKey: undefined }]]]) + ), + subagentChoices: { sections: new Map([['worker', true]]), rosters: new Map() } + } + const slots = build(conversation, input) + const inSection = slots.find((slot) => slot.message.id === 'child') + expect(inSection?.depth).toBe(1) + expect(inSection?.actionsHang).toBeUndefined() + // A section's rows already keep their controls in flow: one line of text and the controls, + // charged once by the section itself. + expect(inSection?.estimatedHeight).toBe(22 + 20) + expect(slots.find((slot) => slot.message.id === 'answer')?.actionsHang).toBeUndefined() + }) +}) diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts new file mode 100644 index 00000000000..86477296a54 --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts @@ -0,0 +1,98 @@ +// Response controls sit on the left. They may hang into the gap below only when nothing else on the +// left starts there; otherwise they would touch the next item, so they keep their own height. + +import { + type NativeChatRowTypography, + nativeChatRowContentMetrics, + nativeChatRowHeightWithControlsInFlow +} from '../../viewport/virtualization/native-chat-row-height-estimate' +import type { + NativeChatMessageSlot, + NativeChatTranscriptSlot +} from './native-chat-transcript-slots' + +/** The person's own right-aligned bubble, with nothing of the row drawn on the left above it. */ +function slotOpensWithPersonBubble(slot: NativeChatTranscriptSlot): boolean { + return ( + slot.kind === 'message' && + slot.depth === 0 && + slot.drawsMessage && + slot.receipt === undefined && + slot.statusAbove !== true && + slot.message.role === 'user' && + // Agent-authored input draws a left-aligned sender card instead of a bubble. + slot.message.from === undefined && + !slot.message.blocks.some((block) => block.type === 'text' && block.providerFrame) + ) +} + +/** The list moves an unjournaled, unsent message below the transcript and its tail row. */ +function slotDrawsAfterTranscript(slot: NativeChatTranscriptSlot): boolean { + return ( + slot.kind === 'message' && + slot.message.unsent === true && + slot.message.journalPosition === undefined + ) +} + +/** Whether the row draws something after its message: a turn bar, a diff rollup or a PR card. */ +function slotDrawsAfterMessage(slot: NativeChatMessageSlot): boolean { + return ( + (slot.status !== undefined && slot.statusAbove !== true) || + slot.turnDiff !== undefined || + slot.openedPullRequests !== undefined + ) +} + +/** Whether the row draws response controls, as far as its estimate can tell without its words. */ +function slotHoldsControls( + slot: NativeChatMessageSlot, + typography: NativeChatRowTypography | undefined +): boolean { + if (slot.receipt !== undefined || slot.activeTurnIsWorking) { + return false + } + // Outside a turn every worded response holds its own, unless the agent's next step follows. + return ( + slot.endsResponse ?? + (slot.continuesTurn !== true && + nativeChatRowContentMetrics(slot.message, typography).textLines > 0) + ) +} + +/** Set `actionsHang` on the conversation's own agent rows, and charge the estimate of a row whose + * controls stay in flow. Runs after `endsResponse` and `continuesTurn` are known. */ +export function markNativeChatResponseActionsHang( + drawn: readonly NativeChatTranscriptSlot[], + /** A left-side row draws under the last slot (the live activity line, the awaiting-input row). */ + tailRowBelow: boolean, + typography?: NativeChatRowTypography +): void { + // Newest first, carrying what draws next: a send that never reached the journal draws after the + // transcript, so it is not what follows the row before it. + let following: NativeChatTranscriptSlot | undefined + for (let index = drawn.length - 1; index >= 0; index -= 1) { + const slot = drawn[index]! + const next = following + if (!slotDrawsAfterTranscript(slot)) { + following = slot + } + // A subagent's section keeps its controls inside its border, so they never hang there. + if ( + slot.kind !== 'message' || + slot.depth !== 0 || + !slot.drawsMessage || + slot.message.role !== 'assistant' + ) { + continue + } + if ( + !slotDrawsAfterMessage(slot) && + (next === undefined ? !tailRowBelow : slotOpensWithPersonBubble(next)) + ) { + slot.actionsHang = true + } else if (slotHoldsControls(slot, typography)) { + slot.estimatedHeight = nativeChatRowHeightWithControlsInFlow(slot.estimatedHeight, typography) + } + } +} diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts index 44419f356b2..47e6b69266b 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts @@ -35,4 +35,6 @@ export type NativeChatTranscriptSlotsInput = { subagentChoices?: NativeChatSubagentChoices /** The open reasoning block the live activity line discloses: its row takes no slot meanwhile. */ liveReasoningId?: string | null + /** A left-side row draws under the last slot: the live activity line or the awaiting-input row. */ + tailRowBelow?: boolean } diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts index c6291a4bd6e..860d226a374 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts @@ -131,6 +131,22 @@ describe('transcript slots', () => { expect(working.find((slot) => slot.message.id === 'a')?.activeTurnIsWorking).toBe(true) }) + it('marks only the newest reply for always-visible actions, including while it is working', () => { + const messages = [ + text('u1', 'first', 'user'), + text('a1', 'first reply'), + text('u2', 'second', 'user'), + text('a2', 'second reply') + ] + for (const overrides of [{}, { liveTurnKey: 'u2', isWorking: true }]) { + const replies = build(messages, overrides).filter((slot) => slot.endsResponse) + expect(replies.map((slot) => [slot.message.id, slot.latestResponse === true])).toEqual([ + ['a1', false], + ['a2', true] + ]) + } + }) + it("keeps a turn's actions on its text, or on its image while folding hides the text", () => { const image: NativeChatMessage = { id: 'a-image', diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts index 382e173d68e..7072134dc54 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts @@ -40,6 +40,7 @@ import { nativeChatSlotOffersFork, type NativeChatSideChatForkPoint } from '../../messages/actions/native-chat-side-chat-fork-point' +import { markNativeChatResponseActionsHang } from './native-chat-response-actions-hang' import type { Translate } from '../../../../i18n/use-translate' export type NativeChatTranscriptSlot = @@ -73,6 +74,13 @@ export type NativeChatMessageSlot = { * the last drawn response with words, else the last with images. Absent outside a turn and in * subagent sections. */ endsResponse?: boolean + /** This response is the newest one in the conversation. */ + latestResponse?: boolean + /** Response controls under this row may hang into the gap below it: the row draws nothing after + * its message, and what follows is the person's own right-aligned bubble or nothing. Absent when + * something left-side follows (an agent's card, a notice, a task or subagent row, the turn's bar, + * diff rollup or PR card), where the controls keep their own height, and in subagent sections. */ + actionsHang?: boolean turnDiff: NativeChatTurnDiff | undefined /** Pull requests this row's turn opened, drawn after it. */ openedPullRequests?: readonly NativeChatOpenedPullRequest[] @@ -116,6 +124,7 @@ export function buildNativeChatTranscript( subagentSections: sections = NO_NATIVE_CHAT_SUBAGENT_SECTIONS, subagentChoices: choices = NO_NATIVE_CHAT_SUBAGENT_CHOICES, liveReasoningId = null, + tailRowBelow = false, forkOffer } = input // Share row rendering facts with fold selection so answer detection agrees with visible prose. @@ -257,6 +266,19 @@ export function buildNativeChatTranscript( slot.endsResponse = true } } + const latestResponse = drawn.findLast( + (slot) => + slot.kind === 'message' && + slot.depth === 0 && + slot.drawsMessage && + !slot.receipt && + slot.message.role === 'assistant' && + (slot.endsResponse === true || + (slot.endsResponse === undefined && nativeChatAgentRowWords(slot.message, t).length > 0)) + ) + if (latestResponse?.kind === 'message') { + latestResponse.latestResponse = true + } for (let index = 0; index < drawn.length - 1; index += 1) { const slot = drawn[index]! const next = drawn[index + 1]! @@ -275,6 +297,7 @@ export function buildNativeChatTranscript( slot.continuesTurn = true } } + markNativeChatResponseActionsHang(drawn, tailRowBelow, typography) return { slots: drawn, forkPoint: forkOffer diff --git a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts index 8b3b56250f7..4f4d3b63536 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts @@ -15,8 +15,14 @@ import type { NativeChatTranscriptSlotsInput } from './native-chat-transcript-in export function useNativeChatTranscriptSlots({ line, ...input -}: Omit & { - line: { draws: boolean; thinking: boolean; stopping?: boolean; activityText?: string | null } +}: Omit & { + line: { + /** The row drawn under the transcript, if any. */ + tailRow: 'awaiting-input' | 'activity' | null + thinking: boolean + stopping?: boolean + activityText?: string | null + } }): { slots: NativeChatTranscriptSlot[] forkPoint: NativeChatSideChatForkPoint | null @@ -39,7 +45,8 @@ export function useNativeChatTranscriptSlots({ subagentChoices, forkOffer } = input - const { draws, thinking, stopping = false, activityText } = line + const { tailRow, thinking, stopping = false, activityText } = line + const draws = tailRow === 'activity' const liveLine = useMemo( () => nativeChatLiveLine({ @@ -70,6 +77,8 @@ export function useNativeChatTranscriptSlots({ ] ) const liveReasoningId = liveLine?.reasoning?.message.id ?? null + // A boolean, so the line's changing words never rebuild the slots. + const tailRowBelow = liveLine !== null || tailRow === 'awaiting-input' const { slots, forkPoint } = useMemo( () => buildNativeChatTranscript({ @@ -88,6 +97,7 @@ export function useNativeChatTranscriptSlots({ subagentSections, subagentChoices, liveReasoningId, + tailRowBelow, forkOffer }), [ @@ -102,6 +112,7 @@ export function useNativeChatTranscriptSlots({ receipts, subagentChoices, subagentSections, + tailRowBelow, turnDiffs, turnKeys, turnStatuses, diff --git a/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.hooks.test.tsx b/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.hooks.test.tsx index 6f8cc11def4..27eec57c35e 100644 --- a/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.hooks.test.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.hooks.test.tsx @@ -91,7 +91,7 @@ const EMPTY_RECEIPTS = new Map() const NO_STATUSES = { active: null, completedByTurn: {} } const EMPTY_DIFFS = new Map() const EMPTY_KEYS = new Set() -const LINE = { draws: false, thinking: false } +const LINE = { tailRow: null, thinking: false } /** Every eligibility decision, in any search, asks this set; count those asks. */ class CountedSet extends Set { diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx index 9af89d8fddb..19b85488e34 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx @@ -52,6 +52,8 @@ export function NativeChatAssistantMessageRow({ trailingRun, continuesTurn = false, endsResponse, + latestResponse = true, + actionsHang = false, inSubagentSection = false, runtimeContext, fork @@ -122,8 +124,12 @@ export function NativeChatAssistantMessageRow({ } className={cn( 'mt-1 w-fit select-none', - // They hang into the gap below; a section keeps them inside its border instead. - !inSubagentSection && '-mb-5' + !latestResponse && + fork?.pendingItemId !== message.id && + 'transition-opacity can-hover:pointer-events-none can-hover:opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100', + // They hang into the gap below only when nothing left-side starts there. Never in a + // section, which keeps them inside its border. + actionsHang && '-mb-5' )} /> ) : null} diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx index 11c9bbda907..0ee81443a4a 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx @@ -59,6 +59,9 @@ export type MessageRowProps = { continuesTurn?: boolean /** In a turn: whether this row holds the response's actions (its last words, else its last images). */ endsResponse?: boolean + latestResponse?: boolean + /** Response controls may hang into the gap below; otherwise they keep their own height. */ + actionsHang?: boolean /** Align this message's top to the top of the scroll viewport. */ onScrollMessageToTop: (el: HTMLElement) => void deliveryNotice?: NativeChatDeliveryNotice diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.fixture.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.fixture.tsx new file mode 100644 index 00000000000..f2c4f9c04bc --- /dev/null +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.fixture.tsx @@ -0,0 +1,69 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { NativeChatMessageList } from '../../NativeChatMessageList' +import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import { orchestrationMailFixture } from '../../../../../../shared/agent-session/orchestration-mail.test-fixture' + +const STARTED_AT = 1_800_000_000_000 +let sent = 0 +function at(): number { + sent += 1 + return STARTED_AT + sent * 60_000 +} +function text(id: string, role: NativeChatMessage['role'], body: string): NativeChatMessage { + return { id, role, source: 'transcript', timestamp: at(), blocks: [{ type: 'text', text: body }] } +} + +// What follows a response's copy / fork / scroll-up row: a worker's card, the person's own bubble, +// and the turn's changed-files rollup. +const messages: NativeChatMessage[] = [ + text('ask', 'user', 'Have a worker review the parser.'), + text('dispatched', 'assistant', 'A review worker is on it. I will report when it answers.'), + { + ...orchestrationMailFixture({ body: 'The parser review found nothing blocking.' }), + timestamp: at() + }, + text('reported', 'assistant', 'The worker found nothing blocking.'), + text('follow-up', 'user', 'Good. Update the greeting too.'), + { + id: 'edit', + role: 'assistant', + source: 'transcript', + timestamp: at(), + blocks: [ + { + type: 'tool-call', + name: 'Edit', + state: 'completed', + input: { + file_path: '/Users/alice/orca/workspaces/orca/feature-x/src/components/greeting.ts', + old_string: 'return "Hello"', + new_string: 'return `Hello, ${name}`' + } + }, + { type: 'tool-result', output: 'The file was updated successfully.' } + ] + }, + text('answer', 'assistant', 'The greeting now includes the name.') +] + +const session: NativeChatLiveSession = { + messages, + agent: 'claude', + sessionId: 'fixture', + status: 'ready', + readPhase: 'ready', + hasMore: false, + loadingEarlier: false, + olderHistoryGeneration: 0, + loadEarlier: async () => 'applied' +} + +export const responseActionsGap = defineFixture({ + width: 560, + render: () => ( +
+ +
+ ) +}) diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx index 3bfadce54b5..2494bcbd1bc 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx @@ -48,12 +48,15 @@ export type NativeChatTranscriptRowContext = { export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ slot, context, - newRowsMarker + newRowsMarker, + newRowsMarkerBelow = false }: { slot: NativeChatTranscriptSlot context: NativeChatTranscriptRowContext /** The "New" marker, when it draws in this row. */ newRowsMarker?: NativeChatNewRowsMarkerState + /** The "New" marker opens the next row: left-side, so this row's actions keep their own height. */ + newRowsMarkerBelow?: boolean }): React.JSX.Element { // Offered only on the conversation's own turn-opening prompts (`nativeChatRowOffersRewind`). const rewind = useContext(NativeChatRewindContext) @@ -105,7 +108,8 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ ) : null return ( // The negative margin shortens the measured row, which is what moves the next one up. - // A row whose actions hang into the gap keeps it whole, so they never cover the next row. + // A row that holds its response's actions keeps the gap whole: they stay in flow above the + // agent's next step (`actionsHang` is unset there), which then sits a full gap below them.
({ toast: { error: vi.fn() } })) vi.mock('@/runtime/hosted-terminals/creation/web-runtime-terminal-creation', () => ({ createWebRuntimeSessionTerminal: createRemote })) -vi.mock('@/lib/focus-terminal-tab-surface', () => ({ focusTerminalTabSurface: vi.fn() })) +vi.mock('@/components/terminal-pane/input/focus/focus-terminal-tab-surface', () => ({ + focusTerminalTabSurface: vi.fn() +})) vi.mock('@/components/tab-bar/request-active-terminal-pane-split', () => ({ requestActiveTerminalPaneSplit: requestSplit })) diff --git a/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts b/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts index 9d71d93bf52..352c3e4a35b 100644 --- a/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts +++ b/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts @@ -19,7 +19,7 @@ import { isNativeChatTranscriptLocalReadable } from '../../../../../../shared/na import { matchesNativeChatToggleShortcut } from './native-chat-shortcut' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' -import { resolveKeyboardWorkspaceId } from '@/lib/floating-workspace-terminal-actions' +import { resolveKeyboardWorkspaceId } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { isNativeChatTabWideFallbackSafe, resolveNativeChatActiveLayoutLeafId diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx deleted file mode 100644 index b90a1ddb8af..00000000000 --- a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx +++ /dev/null @@ -1,92 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { NativeChatNewRowsMarker } from './NativeChatNewRowsMarker' -import type { NativeChatNewRowsMarkerState as Marker } from './native-chat-new-rows-marker' -import { overrideLayoutProperty } from '../virtualization/native-chat-windowing-test-harness' - -afterEach(cleanup) - -function marker(overrides: Partial = {}): Marker { - return { - key: 'answer', - place: 'above-row', - arriving: true, - onArrived: vi.fn(), - onDismiss: vi.fn(), - ...overrides - } -} - -const VIEWPORT_PX = 600 -const ROW_TOP_PX = 1_000 - -let restoreLayout: (() => void)[] = [] - -/** Place the view bottom aboveMarkerPx short of a marker positioned intoRowPx within its row. */ -function pane( - value: Marker, - { intoRowPx = 0, aboveMarkerPx = 0 }: { intoRowPx?: number; aboveMarkerPx?: number } = {} -) { - const isRow = (element: HTMLElement): boolean => element.hasAttribute('data-index') - const isMarker = (element: HTMLElement): boolean => element.getAttribute('role') === 'separator' - const layout = (name: string, get: (this: HTMLElement) => unknown) => - overrideLayoutProperty(name, { get }) - restoreLayout = [ - layout('clientHeight', () => VIEWPORT_PX), - layout('scrollTop', () => ROW_TOP_PX + intoRowPx - VIEWPORT_PX - aboveMarkerPx), - layout('offsetTop', function () { - return isRow(this) ? ROW_TOP_PX : isMarker(this) ? intoRowPx : 0 - }), - layout('offsetParent', function () { - return isRow(this) || isMarker(this) ? this.parentElement : null - }) - ] - const onReveal = vi.fn() - const view = render( -
-
- -
-
-
- -
-
-