diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 83de7cc109d..9deba707d11 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -124,7 +124,7 @@ "id": "terminal-lifecycle.closed-tab-create-admission", "title": "A shipped runtime refuses stale create identities after a durable tab close", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "sqlite-runtime-rpc-provider-contract", "surfaces": [ @@ -134,60 +134,31 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local-daemon", "paired-runtime", "ssh", "wsl", "mobile-relay"], - "coveredPlatforms": ["linux"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Real SQLite Store, renderer close entry, cold reload and registered terminal.create handler with a synthetic PTY controller on macOS. The workspace resolver supplies a fixture scope; no physical paired client or PTY is launched. Unseen identities and missing-PTY recovery retain spawn behavior. Other provider/platform execution is an explicit gap. Audit1345: focused Linux unit execution now validates this primary selector on source head de234fc7b4a73eda58dd0084bc9e064b5d1191e0. Historical platform statements above describe earlier receipts. Removed fixture/matrix/call-count alarms are intentional losses with no equivalent replacement; no live SSH, physical-provider, p95 or cross-platform claim. Audit1366 deletes terminal-topology-commit.test.ts: five trace span attribute/kind/outcome/logging checks, including the narrow privacy-regex and rethrow alarm, are intentionally lost. Adjacent durable close/RPC tests are unchanged; no equivalent trace coverage is claimed. The mixed prior receipt is historical and cannot validate this reduced selector. Fresh validation remains required. Audit1372: current Linux unit selection passed on source head 9b07e8f1bea37bba70c78df2f9a238ea31d1be7e. Exact selectors and execution command are recorded in the new receipt. Intentional test losses remain in knownGaps; no replacement, live provider, native input, rendered E2E, performance threshold or soak coverage is claimed.", + "coverageNotes": "Audit1904 leaves this gate without any current active execution receipt. No current covered platform/provider or active selector/assertion claim remains; original valid source mappings are archived dormant, not asserted removed. Historical prior account (preserved verbatim): Real SQLite Store, renderer close entry, cold reload and registered terminal.create handler with a synthetic PTY controller on macOS. The workspace resolver supplies a fixture scope; no physical paired client or PTY is launched. Unseen identities and missing-PTY recovery retain spawn behavior. Other provider/platform execution is an explicit gap. Audit1345: focused Linux unit execution now validates this primary selector on source head de234fc7b4a73eda58dd0084bc9e064b5d1191e0. Historical platform statements above describe earlier receipts. Removed fixture/matrix/call-count alarms are intentional losses with no equivalent replacement; no live SSH, physical-provider, p95 or cross-platform claim. Audit1366 deletes terminal-topology-commit.test.ts: five trace span attribute/kind/outcome/logging checks, including the narrow privacy-regex and rethrow alarm, are intentionally lost. Adjacent durable close/RPC tests are unchanged; no equivalent trace coverage is claimed. The mixed prior receipt is historical and cannot validate this reduced selector. Fresh validation remains required. Audit1372: current Linux unit selection passed on source head 9b07e8f1bea37bba70c78df2f9a238ea31d1be7e. Exact selectors and execution command are recorded in the new receipt. Intentional test losses remain in knownGaps; no replacement, live provider, native input, rendered E2E, performance threshold or soak coverage is claimed.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/21341#issuecomment-5770157948"], "invariant": "An unexpired durable tab-close record in any owning host partition must refuse a stale create of that tab in the same workspace before the PTY controller spawns. Unseen ids, panes with no tab-close record, expired records and split creation retain existing behavior; shipped layout ownership stays off.", - "oracle": "Invoke the renderer close entry through a real SQLite Store, freeze and reopen the database, then invoke the registered paired terminal.create handler with the original tab/leaf hints and no command. Both local and runtime-spill close records must return tab_not_found with zero controller spawns and zero inventory reads, and no restored layout. Fresh identities, existing panes without a close record and expired records must still spawn.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts" - ], - "testFiles": [ - "src/main/runtime/terminal-create-closed-tab-durability.test.ts", - "src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts", - "src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts", - "src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", - "src/main/runtime/runtime-pane-admission.test.ts", - "src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts", - "src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts", - "src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts", - "src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts", - "src/main/runtime/terminal-close-observed-exit.test.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/terminal-create-closed-tab-durability.test.ts", - "assertions": ["refuses a stale id closed in %s before spawning, including after restart"] - } - ], - "evidenceRuns": [ - { - "date": "2026-11-04", - "runner": "local", - "platform": "linux", - "command": "pnpm --config.verifyDepsBeforeRun=false test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts --maxWorkers=2", - "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts", - "result": "passed", - "durationSeconds": 19.75, - "summary": "Test Files 10 passed (10); Tests 92 passed (92). Source head 9b07e8f1bea37bba70c78df2f9a238ea31d1be7e. Current retained unit selection only. No removed-case replacement, live provider, native input, rendered Electron E2E, performance threshold or soak claim. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display. currentCommand retains the same selectors; execution adds a worker limit and disables dependency preflight." - } - ], + "oracle": "Audit1904 retires the changed-selector receipt. The reduced source set has no current validated oracle; prior source requirements are historical until fresh execution. Historical prior account (preserved verbatim): Invoke the renderer close entry through a real SQLite Store, freeze and reopen the database, then invoke the registered paired terminal.create handler with the original tab/leaf hints and no command. Both local and runtime-spill close records must return tab_not_found with zero controller spawns and zero inventory reads, and no restored layout. Fresh identities, existing panes without a close record and expired records must still spawn.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 45, - "scope": "deterministic SQLite and runtime/provider contracts" + "scope": "Historical budget only: the original selector lost its sole active receipt and the reduced source set has no new measurement. Historical prior account (preserved verbatim): deterministic SQLite and runtime/provider contracts" }, "flakeHistory": { "status": "not-started", - "evidence": "One focused 11-file pass on macOS; CI soak not collected." + "evidence": "Audit1904 has no current soak evidence for the reduced selector. Historical prior account (preserved verbatim): One focused 11-file pass on macOS; CI soak not collected." }, "redGreenEvidence": { - "status": "complete", - "evidence": "On unmodified production code both actual close/cold-reload/RPC stale-id cases resolve successfully after spawning a replacement PTY; the unseen-id control passes. Admission guard makes both cases reject before the controller is invoked." + "status": "missing", + "evidence": "Audit1904 has no current red/green execution of the reduced selector. Historical prior account (preserved verbatim): On unmodified production code both actual close/cold-reload/RPC stale-id cases resolve successfully after spawning a replacement PTY; the unseen-id control passes. Admission guard makes both cases reject before the controller is invoked." }, "performanceBudget": { "required": true, - "evidence": "One constant-time tombstone lookup per existing host partition inside the already serialized explicit pane-admission mutation. No terminal inventory, filesystem scan, network call, subprocess, timer, retry or polling is introduced. Negative RPC controls assert zero spawn and zero inventory reads." + "evidence": "Historical policy/budget account only: no fresh performance or work-count validation of the reduced selector. Historical prior account (preserved verbatim): One constant-time tombstone lookup per existing host partition inside the already serialized explicit pane-admission mutation. No terminal inventory, filesystem scan, network call, subprocess, timer, retry or polling is introduced. Negative RPC controls assert zero spawn and zero inventory reads." }, "promotionCriteria": [ "Collect 100 CI passes or 14 days without unexplained flakes.", @@ -202,7 +173,9 @@ "Test-value audit1330-refresh679 removes low-value registrations. Historical receipts below predate the changed selected sources or imported spec drivers and are not evidence for the surviving tests; no replacement-equivalence claim.", "Historical receipt before audit1330-refresh679 test removal; complete original record preserved verbatim: {\n \"date\": \"2026-10-22\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-topology-commit.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 23.76,\n \"summary\": \"100 tests pass across 11 files, including cold SQLite close-record replay, fresh/unknown/expired controls, split replay, close write failure, idempotency and close lifecycle controls.\"\n }", "Audit1366 deletes terminal-topology-commit.test.ts: five trace span attribute/kind/outcome/logging checks, including the narrow privacy-regex and rethrow alarm, are intentionally lost. Adjacent durable close/RPC tests are unchanged; no equivalent trace coverage is claimed. The mixed prior receipt is historical and cannot validate this reduced selector. Fresh validation remains required.", - "Historical receipt retired by audit1366 at 25cd81665e1b8eaf75d7715d37999ca1583e1228; original record unchanged, not current validation:\n{\n \"date\": \"2026-11-04\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"result\": \"passed\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-topology-commit.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/runtime/terminal-close-observed-exit.test.ts src/main/runtime/terminal-create-closed-tab-durability.test.ts --maxWorkers=2\",\n \"currentCommand\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-topology-commit.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts\",\n \"durationSeconds\": 24.64,\n \"summary\": \"Test Files 11 passed (11); Tests 97 passed (97). Focused Linux unit execution; no p95, physical-provider or cross-platform claim. Source head de234fc7b4a73eda58dd0084bc9e064b5d1191e0.\"\n }" + "Historical receipt retired by audit1366 at 25cd81665e1b8eaf75d7715d37999ca1583e1228; original record unchanged, not current validation:\n{\n \"date\": \"2026-11-04\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"result\": \"passed\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-topology-commit.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/runtime/terminal-close-observed-exit.test.ts src/main/runtime/terminal-create-closed-tab-durability.test.ts --maxWorkers=2\",\n \"currentCommand\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-topology-commit.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts\",\n \"durationSeconds\": 24.64,\n \"summary\": \"Test Files 11 passed (11); Tests 97 passed (97). Focused Linux unit execution; no p95, physical-provider or cross-platform claim. Source head de234fc7b4a73eda58dd0084bc9e064b5d1191e0.\"\n }", + "Audit1904 retires the sole active2026-11-04 Linux92tests/10files19.75s closed-tab receipt because it selects deleted terminal-pane-admission-taken-ids-switch-off. There is no fresh reduced-selector pass. Protection becomes none; active commands/testFiles/assertionRefs are cleared to satisfy the schema, with their complete original raw arrays preserved below as dormant historical source mappings. Clearing a valid mapping is not deletion of its surviving tests: source27 terminal-close-write-failure-switch-off and unrelated close/RPC assertions remain valid source bodies but have no active gate execution receipt. Lost source35 alarms: \"writes a client tab's second pane under the tab's id\"; 'writes a create under the id of a tab the user closed, on both pane write paths'. No equivalent replacement, fresh provider/platform, red/green, soak or budget evidence is claimed.", + "Audit1904 historical closed-tab receipt and dormant selector/assertion inventory; not active execution or assertions for the reduced sources. Complete original raw subtrees follow verbatim.\nreceipt:\n{\n \"date\": \"2026-11-04\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"command\": \"pnpm --config.verifyDepsBeforeRun=false test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/orca-runtime-terminal-close-records.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts --maxWorkers=2\",\n \"currentCommand\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 19.75,\n \"summary\": \"Test Files 10 passed (10); Tests 92 passed (92). Source head 9b07e8f1bea37bba70c78df2f9a238ea31d1be7e. Current retained unit selection only. No removed-case replacement, live provider, native input, rendered Electron E2E, performance threshold or soak claim. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display. currentCommand retains the same selectors; execution adds a worker limit and disables dependency preflight.\"\n }\ncommands:\n[\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-create-closed-tab-durability.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts src/main/runtime/runtime-pane-admission.test.ts src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts src/main/runtime/terminal-close-observed-exit.test.ts\"\n ]\ntestFiles:\n[\n \"src/main/runtime/terminal-create-closed-tab-durability.test.ts\",\n \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-replay-after-close.test.ts\",\n \"src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts\",\n \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"src/main/runtime/runtime-pane-admission.test.ts\",\n \"src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts\",\n \"src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts\",\n \"src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts\",\n \"src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts\",\n \"src/main/runtime/terminal-close-observed-exit.test.ts\"\n ]\nassertionRefs:\n[\n {\n \"file\": \"src/main/runtime/terminal-create-closed-tab-durability.test.ts\",\n \"assertions\": [\"refuses a stale id closed in %s before spawning, including after restart\"]\n }\n ]" ], "demotionRule": "Keep experimental or demote if stale replay can spawn, unrelated/fresh panes are refused, the guard adds terminal inventory calls, a close loses durability, or focused ordering tests flake without an explained harness or product defect." }, @@ -750,10 +723,10 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit1897 narrows current profile-state unit scope. Retained selected tests cover production SQLite fencing/rollback, competing revision admission, export and recovery byte preservation, worker publication and gated cross-runtime/native Windows outcomes. These are source-review observations, not a fresh integrated gate pass. Commands, testFiles and assertionRefs remain valid and unchanged. The sole unchanged 2026-10-05 macOS hidden-Electron E2E receipt remains scoped to its exact command; no new unit, other-platform, physical-provider, soak or budget measurement is claimed. Historical prior account (preserved verbatim): Audits1891/1893 reduce optional unit selectors and imported persistence specs. Fresh integrated execution remains required; the unchanged 2026-10-05 hidden-Electron E2E receipt applies only to its own command. No equivalent replacement, physical-provider, cross-platform, soak or measured-budget validation is claimed. Audit1893 removes42 authored definitions/71 static rows from imported persistence specs; two maintenance compatibility assertionRefs still map to exact retained registrations. Retained SQL/worker acknowledgement, ciphertext, cancellation, competing-writer, shutdown and partial-mutation refusal callbacks remain, but reduced wrapper selectors await fresh integrated execution. Detailed intentional losses are recorded in knownGaps. Historical scope before these audits: 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: Audits1340 and1348 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): Real temporary profile databases and production Store/CLI recovery paths on macOS; mocked updater feed admission for macOS/Linux/Windows. PTY execution and remote wire payloads are unchanged. Profile persistence executes on its owning runtime. Native installers and physical remote hosts are untested. Audit1340: src/main/orca-profiles/profile-session-owner-transfer.test.ts removed. Ambiguous markdown owner override suppression. src/main/persistence/profile-state/profile-state-writer-capacity-errors.test.ts reduced. Capacity code and permission/busy distinction across synthetic nested errors. No equivalent replacement coverage is claimed. Audit1348: src/main/persistence/loading-store/pty-incarnation-renderer-save.test.ts reduced. Merging another pane incarnation from a partially populated renderer map. No equivalent replacement coverage is claimed. 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. Audit1366 deletes pty-binding-fast-lane.test.ts (five handcrafted predicate/diagnostic inventories) and removes two no-change/switch-off registrations from reused-terminal-id-unbind.test.ts. Those predicate-only and default-branch alarms are intentionally lost; remaining incarnation unbinding behavior is retained. Directory-selected prior unit receipts include these changed sources and are historical, not validation of the reduced set. The separate unchanged E2E receipt remains scoped to its own command. Fresh unit validation remains required. Audit1371 removes the captureSource boolean invalidation replay from durable-settings-write.spec.ts. Actual SQLite acknowledgement, rollback, concurrent edit and optional-key restoration callbacks remain unchanged. Catalog-invalidation-only alarm is intentionally lost; no equivalent report-publication coverage is claimed. Directory-selected old unit receipts are historical; fresh validation remains required. Audit1383: src/main/persistence/profile-state/profile-state-startup-recovery-dialog.test.ts removed. Lose Japanese copy, copy/quit/ambiguity button payloads, selection index/confirmation and missing date formatting alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/main/persistence/loading-store/workspace-session-terminal-binding-replay.test.ts reduced. Lose implementation-specific prior-tab read work bound; no behavior assertion lost beyond computed bulk replay. 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. Audit1401: src/main/persistence/loading-store/store-prune-gate-signals.test.ts removed. Loses gate signals for release/removal and parked state for additive writes. 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/persistence/loading-store/legacy-opencode-go-api-key-migration.test.ts reduced. Loses settings-field removal/no-decrypt parking, plaintext sealing/degraded parking, malformed-field rejection and repeated-run idempotency alarms. Kept failure recovery does not establish those exact paths. 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.", + "coverageNotes": "Audit1904 narrows the directory-selected profile-state unit sources and removes only the selected-profile recovery unknown/escaping-ID assertion. The inactive-profile SQLite downgrade assertion and all valid selectors remain. The unchanged2026-10-05 macOS E2E receipt remains scoped to its exact command; no current unit receipt validates reduced sources and no equivalent replacement, native/platform/provider, soak or measured-budget claim is added. Historical prior account (preserved verbatim): Audit1897 narrows current profile-state unit scope. Retained selected tests cover production SQLite fencing/rollback, competing revision admission, export and recovery byte preservation, worker publication and gated cross-runtime/native Windows outcomes. These are source-review observations, not a fresh integrated gate pass. Commands, testFiles and assertionRefs remain valid and unchanged. The sole unchanged 2026-10-05 macOS hidden-Electron E2E receipt remains scoped to its exact command; no new unit, other-platform, physical-provider, soak or budget measurement is claimed. Historical prior account (preserved verbatim): Audits1891/1893 reduce optional unit selectors and imported persistence specs. Fresh integrated execution remains required; the unchanged 2026-10-05 hidden-Electron E2E receipt applies only to its own command. No equivalent replacement, physical-provider, cross-platform, soak or measured-budget validation is claimed. Audit1893 removes42 authored definitions/71 static rows from imported persistence specs; two maintenance compatibility assertionRefs still map to exact retained registrations. Retained SQL/worker acknowledgement, ciphertext, cancellation, competing-writer, shutdown and partial-mutation refusal callbacks remain, but reduced wrapper selectors await fresh integrated execution. Detailed intentional losses are recorded in knownGaps. Historical scope before these audits: 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: Audits1340 and1348 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): Real temporary profile databases and production Store/CLI recovery paths on macOS; mocked updater feed admission for macOS/Linux/Windows. PTY execution and remote wire payloads are unchanged. Profile persistence executes on its owning runtime. Native installers and physical remote hosts are untested. Audit1340: src/main/orca-profiles/profile-session-owner-transfer.test.ts removed. Ambiguous markdown owner override suppression. src/main/persistence/profile-state/profile-state-writer-capacity-errors.test.ts reduced. Capacity code and permission/busy distinction across synthetic nested errors. No equivalent replacement coverage is claimed. Audit1348: src/main/persistence/loading-store/pty-incarnation-renderer-save.test.ts reduced. Merging another pane incarnation from a partially populated renderer map. No equivalent replacement coverage is claimed. 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. Audit1366 deletes pty-binding-fast-lane.test.ts (five handcrafted predicate/diagnostic inventories) and removes two no-change/switch-off registrations from reused-terminal-id-unbind.test.ts. Those predicate-only and default-branch alarms are intentionally lost; remaining incarnation unbinding behavior is retained. Directory-selected prior unit receipts include these changed sources and are historical, not validation of the reduced set. The separate unchanged E2E receipt remains scoped to its own command. Fresh unit validation remains required. Audit1371 removes the captureSource boolean invalidation replay from durable-settings-write.spec.ts. Actual SQLite acknowledgement, rollback, concurrent edit and optional-key restoration callbacks remain unchanged. Catalog-invalidation-only alarm is intentionally lost; no equivalent report-publication coverage is claimed. Directory-selected old unit receipts are historical; fresh validation remains required. Audit1383: src/main/persistence/profile-state/profile-state-startup-recovery-dialog.test.ts removed. Lose Japanese copy, copy/quit/ambiguity button payloads, selection index/confirmation and missing date formatting alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/main/persistence/loading-store/workspace-session-terminal-binding-replay.test.ts reduced. Lose implementation-specific prior-tab read work bound; no behavior assertion lost beyond computed bulk replay. 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. Audit1401: src/main/persistence/loading-store/store-prune-gate-signals.test.ts removed. Loses gate signals for release/removal and parked state for additive writes. 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/persistence/loading-store/legacy-opencode-go-api-key-migration.test.ts reduced. Loses settings-field removal/no-decrypt parking, plaintext sealing/degraded parking, malformed-field rejection and repeated-run idempotency alarms. Kept failure recovery does not establish those exact paths. 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.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/23262"], "invariant": "Ordinary lifecycle operations durably checkpoint SQLite without rewriting legacy JSON; missing SQLite cannot revive stale JSON; explicit recovery preserves artifacts and selects the named profile without changing active-profile state; the updater refuses JSON-era releases before admitting their feed.", - "oracle": "Audit1897 narrows current profile-state unit scope. Retained selected tests cover production SQLite fencing/rollback, competing revision admission, export and recovery byte preservation, worker publication and gated cross-runtime/native Windows outcomes. These are source-review observations, not a fresh integrated gate pass. Commands, testFiles and assertionRefs remain valid and unchanged. The sole unchanged 2026-10-05 macOS hidden-Electron E2E receipt remains scoped to its exact command; no new unit, other-platform, physical-provider, soak or budget measurement is claimed. Historical prior account (preserved verbatim): Audits1891/1893 reduce optional unit selectors and imported persistence specs. Fresh integrated execution remains required; the unchanged 2026-10-05 hidden-Electron E2E receipt applies only to its own command. No equivalent replacement, physical-provider, cross-platform, soak or measured-budget validation is claimed. Audit1893 removes42 authored definitions/71 static rows from imported persistence specs; two maintenance compatibility assertionRefs still map to exact retained registrations. Retained SQL/worker acknowledgement, ciphertext, cancellation, competing-writer, shutdown and partial-mutation refusal callbacks remain, but reduced wrapper selectors await fresh integrated execution. Detailed intentional losses are recorded in knownGaps. Historical scope before these audits: 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: 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): Assert unchanged JSON through final flush and maintenance, failure propagation before quit, missing-database refusal after marker publication, archived SQLite and latest committed JSON from inactive-profile conversion, unchanged active database/index/HTTP marker, and zero feed/check calls for incompatible pinned/local builds.", + "oracle": "Audit1904 narrows the directory-selected profile-state unit sources and removes only the selected-profile recovery unknown/escaping-ID assertion. The inactive-profile SQLite downgrade assertion and all valid selectors remain. The unchanged2026-10-05 macOS E2E receipt remains scoped to its exact command; no current unit receipt validates reduced sources and no equivalent replacement, native/platform/provider, soak or measured-budget claim is added. Historical prior account (preserved verbatim): Audit1897 narrows current profile-state unit scope. Retained selected tests cover production SQLite fencing/rollback, competing revision admission, export and recovery byte preservation, worker publication and gated cross-runtime/native Windows outcomes. These are source-review observations, not a fresh integrated gate pass. Commands, testFiles and assertionRefs remain valid and unchanged. The sole unchanged 2026-10-05 macOS hidden-Electron E2E receipt remains scoped to its exact command; no new unit, other-platform, physical-provider, soak or budget measurement is claimed. Historical prior account (preserved verbatim): Audits1891/1893 reduce optional unit selectors and imported persistence specs. Fresh integrated execution remains required; the unchanged 2026-10-05 hidden-Electron E2E receipt applies only to its own command. No equivalent replacement, physical-provider, cross-platform, soak or measured-budget validation is claimed. Audit1893 removes42 authored definitions/71 static rows from imported persistence specs; two maintenance compatibility assertionRefs still map to exact retained registrations. Retained SQL/worker acknowledgement, ciphertext, cancellation, competing-writer, shutdown and partial-mutation refusal callbacks remain, but reduced wrapper selectors await fresh integrated execution. Detailed intentional losses are recorded in knownGaps. Historical scope before these audits: 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: 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): Assert unchanged JSON through final flush and maintenance, failure propagation before quit, missing-database refusal after marker publication, archived SQLite and latest committed JSON from inactive-profile conversion, unchanged active database/index/HTTP marker, and zero feed/check calls for incompatible pinned/local builds.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/persistence/profile-state src/main/persistence/loading-store src/main/orca-profiles src/main/startup/profile-state-recovery-preflight.test.ts src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts src/main/updater/updater.build-channel-selection.test.ts src/cli/handlers/profile-state.test.ts src/cli/handlers/profile-state-recovery-admission.test.ts src/cli/specs/profile-state.test.ts src/cli/runtime/profile-state-recovery-launch.test.ts src/shared/profile-state-recovery-command.test.ts src/shared/profile-state-build-compatibility.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/persistence/loading-store/profile-state-update-quit.test.ts src/main/persistence/loading-store/profile-state-maintenance-contracts.test.ts src/main/persistence/profile-state/profile-state-authority-marker.test.ts src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts src/main/persistence/profile-state/profile-state-current-sqlite-command.test.ts src/main/persistence/loading-store/profile-state-checkpoints.test.ts", @@ -779,8 +752,7 @@ { "file": "src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts", "assertions": [ - "downgrades an inactive profile from its latest SQLite state without changing the active profile", - "refuses unknown and escaping IDs without falling back to the active profile" + "downgrades an inactive profile from its latest SQLite state without changing the active profile" ] } ], @@ -834,7 +806,9 @@ "Audit1858 removes ordinary accepted JSON-era target examples from src/shared/profile-state-build-compatibility.test.ts. The JSON-era acceptance alarm is intentionally lost without equivalent replacement coverage. This helper remains in an optional broad unit selector with no active execution receipt; its focused survivor run does not validate the broad selector, physical downgrade/install behavior or other platforms/providers. The separate unchanged 2026-10-05 E2E receipt and historical records remain scoped to their own commands.", "Audit1891 removes checkpoint timer/write-count and selective-write/private-mode inventories, ordinary nested/getter-field persistence and export round trips, and the best-effort/strict final-getter example. Retained checkpoint callbacks cover actual stale-authority refusal, a queued-writer mutation reaching the final durable checkpoint, and frozen-profile durability; retained update/quit callback covers an injected final-commit failure preserving prior durable state without JSON publication. These optional reduced unit selectors have no new integrated execution result. Directory-selected prior unit receipts remain historical; the separate unchanged 2026-10-05 E2E receipt, all original knownGaps, commands, testFiles, assertionRefs and platform/provider/accounting fields retain their original scope. No equivalent replacement coverage is claimed.", "Audit1893 re-reviews imported persistence specs at current frozen bytes and intentionally removes42 authored definitions/71 static rows without equivalent replacement coverage: observer/domain-list inventories, matching-bind work and host/mode matrix, ordinary/memory-only rollback projections, branch-heavy created-surface title cases, synthetic restart retirement, mocked backup signal matrix, and4-phase x2-host queued-retirement/finalization matrix. Actual retained SQL/worker acknowledgement, ciphertext, cancellation, competing-writer, shutdown and partial-mutation refusal callbacks remain unchanged. Four durable-writes imports/describe calls for deleted specs are removed separately; the maintenance wrapper and its two active compatibility assertionRefs remain unchanged. Valid optional commands/testFiles remain, but reduced selectors await fresh integrated execution. The sole unchanged2026-10-05 macOS hidden-Electron E2E receipt and platform scope are preserved and do not execute these imported unit specs. Historical broad/reduced-unit receipts remain historical and verbatim. Focused wrapper execution cannot validate broad optional selectors, PTY delivery, physical SSH/mobile/WSL or other platforms.", - "Audit1897 intentionally removes219 authored definitions/322 static rows across48 selected sources, including23 whole suites. The profile-state selector loses fixture/canonical equality and soak inventories, historical compatibility-acceptance metadata matrices, setup/default/bootstrap/migration inventories, backup-name/rotation branch inventories, raw-SQL child crash scripts that reimplement writes, private domain readers/equality/serialization, fragment-forgery matrices and parsed-snapshot plumbing. Removed command/error-message and injected access inventories are not replacement-validated. Retained independent SQL fencing, trigger rollback, production crash export/recovery and durable byte outcomes do not establish the lost alarms. Static totals use the macOS copy-boundary superset; no new native, WSL/SSH/mobile, rendered UI or cross-platform run is supplied. Exact accepted per-definition losses are recorded in sealed1897 reviews; all current selectors/assertionRefs and the unchanged2026-10-05 macOS E2E raw receipt remain. No equivalent replacement or fresh unit gate evidence is claimed." + "Audit1897 intentionally removes219 authored definitions/322 static rows across48 selected sources, including23 whole suites. The profile-state selector loses fixture/canonical equality and soak inventories, historical compatibility-acceptance metadata matrices, setup/default/bootstrap/migration inventories, backup-name/rotation branch inventories, raw-SQL child crash scripts that reimplement writes, private domain readers/equality/serialization, fragment-forgery matrices and parsed-snapshot plumbing. Removed command/error-message and injected access inventories are not replacement-validated. Retained independent SQL fencing, trigger rollback, production crash export/recovery and durable byte outcomes do not establish the lost alarms. Static totals use the macOS copy-boundary superset; no new native, WSL/SSH/mobile, rendered UI or cross-platform run is supplied. Exact accepted per-definition losses are recorded in sealed1897 reviews; all current selectors/assertionRefs and the unchanged2026-10-05 macOS E2E raw receipt remain. No equivalent replacement or fresh unit gate evidence is claimed.", + "Audit1904 intentionally loses these direct profile-state source alarms: 'refuses rather than replaces something else at the backup path'; 'does nothing for an empty batch'; 'shares one process with absolute arguments and the per-file timeout budget'; 'bounds a shared process when many large artifacts are retained'; 'isolates %s/accepted=%s through corruption and WAL reopen'; 'bundles one process-host source graph into the isolated recovery fixture'; 'refuses readiness when a required worker artifact is absent'; 'refuses unknown and escaping IDs without falling back to the active profile'; 'rejects reused input before Store context installation (secret=%s)'; 'reads established storage once with retained JSON=%s'; 'consumes a parsed startup snapshot once, including an empty revision'; 'rejects initial state without its authority or alongside migration input'; 'keeps any other failed commit indeterminate even after SQLite rolled back'; 'joins an aborted writer without reporting a close request that was never sent'; 'keeps the SQLite failure behind a database open error across the writer boundary'; 'carries a real SQLite error code from a failed open'; 'keeps a cause-less open error cause-less'; 'refuses a versioned export with revision %s for an admitted revision of one'; 'refuses a revision jump at an unchanged-state fence'; 'refuses an initialization acknowledgement for a different revision'; 'leaves startup failure reporting to the startup caller'; 'does not report saving stopped after a recoverable request failure or clean close'; 'retries the first failure at once, then backs off up to a minute'; 'forgets the backoff once a reopen succeeds'; 'lets one attempt through a backoff for a final flush'; 'drops a pending bypass once a reopen succeeds'; 'permanently retires bootstrap authority and refuses subsequent calls'; 'aborts an active request without treating the pending write as rolled back'; 'resolves flat and shared-chunk entry layouts'. Retained production SQLite recovery, durable bytes, fencing and worker callbacks do not establish those exact lost alarms. Sources and accepted reasons are in sealed1904 reviews; no equivalent replacement or fresh integrated unit gate run is claimed.", + "Audit1904 historical selected-profile assertion inventory; only unknown/escaping-ID refusal is removed from the active ref. The retained inactive-profile downgrade assertion remains valid. Complete original raw assertion object follows verbatim:\n{\n \"file\": \"src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts\",\n \"assertions\": [\n \"downgrades an inactive profile from its latest SQLite state without changing the active profile\",\n \"refuses unknown and escaping IDs without falling back to the active profile\"\n ]\n }" ], "promotionCriteria": [ "Collect cross-platform CI and crash-boundary soak evidence without weakening authority or durable-save assertions." @@ -6708,16 +6682,16 @@ "providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "remote-runtime"], - "coverageNotes": "Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer contracts hold CWD resolution behind an explicit promise, require the new pane to be created synchronously, and prove that close cancels the pending connection. A module-level stable-pane-key handoff preserves the exact CWD promise and bounded pre-connect input across whole-tab remounts, including a tab rehome between worktree buckets; stale owners are fenced, concrete PTY bind and definitive spawn failure clear the record, and explicit pane close discards it. Detach contracts reject cwd-pending and cwd-resolved deferred splits before PTY bind without mutation, carry resolved cwd for other unbound panes, and preserve persisted or live PTY handoff. Local IPC transport contracts exercise the real bounded pre-connect buffer and one live input FIFO across seeded and newly typed ordinary, acknowledged, and immediate writes, concurrent flushes, in-flight teardown, late spawn success or failure, attach failure, failed spawn, same-id reuse, stale-spawn retirement ownership, destroy, and mutable recovery metadata. The handoff registry is capped at 64 records for 15 seconds and shares the existing 1,024-entry/conservative UTF-16 input ceilings. A mocked direct-SSH authority-rotation contract proves a rejected stale spawn releases its deferred-CWD fence. The schema-v2 headful Electron benchmark records exact revision identity and attributes CWD request/settlement, PTY spawn request/result, bind, fixture unlock request/IPC write, fixture readiness, input, and first echo across 3 warmups and 20 measured cold-CWD cycles, requiring a distinct child PTY and observed child pty:exit before the next cycle. Remote-runtime coverage proves delegation remains host-owned; its host-delegated split path does not consume the local pre-connect input options, so remote-runtime input-remount replay and physical local-daemon, SSH, WSL, Linux, Windows, and folder-workspace latency journeys remain gaps. The test-value audit retires the benchmark artifact and report unit suites. Their direct JSON write/readback, unwritable-path, path-redaction/string-bound, synthetic phase-attribution, revision/percentile and missing-unlock-event alarms are lost. The real benchmark and its capture/report/writer helpers remain; they do not provide equivalent isolated helper validation. Historical executed commands, counts and results remain historical. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer contracts hold CWD resolution behind an explicit promise, require the new pane to be created synchronously, and prove that close cancels the pending connection. A module-level stable-pane-key handoff preserves the exact CWD promise and bounded pre-connect input across whole-tab remounts, including a tab rehome between worktree buckets; stale owners are fenced, concrete PTY bind and definitive spawn failure clear the record, and explicit pane close discards it. Detach contracts reject cwd-pending and cwd-resolved deferred splits before PTY bind without mutation, carry resolved cwd for other unbound panes, and preserve persisted or live PTY handoff. Local IPC transport contracts exercise the real bounded pre-connect buffer and one live input FIFO across seeded and newly typed ordinary, acknowledged, and immediate writes, concurrent flushes, in-flight teardown, late spawn success or failure, attach failure, failed spawn, same-id reuse, stale-spawn retirement ownership, destroy, and mutable recovery metadata. The handoff registry is capped at 64 records for 15 seconds and shares the existing 1,024-entry/conservative UTF-16 input ceilings. A mocked direct-SSH authority-rotation contract proves a rejected stale spawn releases its deferred-CWD fence. The schema-v2 headful Electron benchmark records exact revision identity and attributes CWD request/settlement, PTY spawn request/result, bind, fixture unlock request/IPC write, fixture readiness, input, and first echo across 3 warmups and 20 measured cold-CWD cycles, requiring a distinct child PTY and observed child pty:exit before the next cycle. Remote-runtime coverage proves delegation remains host-owned; its host-delegated split path does not consume the local pre-connect input options, so remote-runtime input-remount replay and physical local-daemon, SSH, WSL, Linux, Windows, and folder-workspace latency journeys remain gaps. The test-value audit retires the benchmark artifact and report unit suites. Their direct JSON write/readback, unwritable-path, path-redaction/string-bound, synthetic phase-attribution, revision/percentile and missing-unlock-event alarms are lost. The real benchmark and its capture/report/writer helpers remain; they do not provide equivalent isolated helper validation. Historical executed commands, counts and results remain historical. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. No equivalent replacement coverage is claimed.", "motivatingLinks": ["https://github.com/stablyai/orca/commit/572ed1a8882"], "invariant": "A terminal split creates and activates its renderer pane before an inherited-CWD lookup settles, starts its PTY only after the resolved directory is available, and cannot be externally detached while that deferred spawn remains unbound. A whole-tab remount or worktree rehome preserves the same stable pane's CWD promise and admitted local pre-connect bytes in order until a successor binds or the intent is definitively abandoned; stale owners cannot append or clear the successor's record. Other unbound panes preserve resolved cwd as startupCwd when detached. Bounded pre-connect input and later live local input share byte order, and teardown settles acknowledged writes without creating or rebinding a stale PTY. A disconnected or detached pending connect cannot bind its late fresh spawn, report its late failure through current callbacks, or ID-retire a newer same-ID owner; rejecting a stale direct-SSH spawn also releases the matching deferred-CWD fence. Natural exit cannot deliver queued work into a reused PTY id. Bound and remote-runtime splits remain owned by their execution host.", - "oracle": "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): Hold CWD resolution behind a controllable promise, invoke the production split path, and require manager.splitPane plus split telemetry before resolving it. Before PTY bind, require both cwd-pending and cwd-resolved deferred detach attempts to return null without layout, pane, tab, ownership, or focus mutation; separately require resolved cwd on an allowed unbound detach and unchanged persisted/live PTY adoption. Exercise the stable-pane handoff registry through repeated remounts and a worktree rehome, requiring the identical CWD promise, ordered ordinary/acknowledged/immediate seed replay, stale-owner fencing, 64-record/15-second bounds, and discard on bind, failure, or explicit close. Rotate a mocked direct-SSH authority while its delayed spawn is in flight, reject and disconnect the stale PTY claim, then require exactly one deferred-CWD cleanup when the delayed connect settles. At the local IPC PTY boundary, require zero connect calls while pending, the resolved CWD in spawn and local recovery metadata, one shared FIFO across seeded/new pre-connect and live ordinary/acknowledged/immediate input, prompt predecessor acknowledged-promise settlement on teardown, retirement of an unowned late fresh spawn, preservation of a newer same-ID owner, and zero stale delivery after failure, close, destroy, detach, natural exit, or same-id reuse. Capture callback exceptions must not change admission results. In visible Electron, press the real split shortcut for 3 warmup cycles, then after a cold inherited-CWD interval for each of 20 measured cycles, require an exact clean revision identity, complete focus/CWD/spawn/bind/fixture/input/echo attribution, distinct child PTYs, pane count, and child exits for every cycle; a timed-out, missing-event, or cleanup-aborted run must publish no headline latency and fail.", + "oracle": "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): 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): Hold CWD resolution behind a controllable promise, invoke the production split path, and require manager.splitPane plus split telemetry before resolving it. Before PTY bind, require both cwd-pending and cwd-resolved deferred detach attempts to return null without layout, pane, tab, ownership, or focus mutation; separately require resolved cwd on an allowed unbound detach and unchanged persisted/live PTY adoption. Exercise the stable-pane handoff registry through repeated remounts and a worktree rehome, requiring the identical CWD promise, ordered ordinary/acknowledged/immediate seed replay, stale-owner fencing, 64-record/15-second bounds, and discard on bind, failure, or explicit close. Rotate a mocked direct-SSH authority while its delayed spawn is in flight, reject and disconnect the stale PTY claim, then require exactly one deferred-CWD cleanup when the delayed connect settles. At the local IPC PTY boundary, require zero connect calls while pending, the resolved CWD in spawn and local recovery metadata, one shared FIFO across seeded/new pre-connect and live ordinary/acknowledged/immediate input, prompt predecessor acknowledged-promise settlement on teardown, retirement of an unowned late fresh spawn, preservation of a newer same-ID owner, and zero stale delivery after failure, close, destroy, detach, natural exit, or same-id reuse. Capture callback exceptions must not change admission results. In visible Electron, press the real split shortcut for 3 warmup cycles, then after a cold inherited-CWD interval for each of 20 measured cycles, require an exact clean revision identity, complete focus/CWD/spawn/bind/fixture/input/echo attribution, distinct child PTYs, pane count, and child exits for every cycle; a timed-out, missing-event, or cleanup-aborted run must publish no headline latency and fail.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts tests/e2e/terminal-split-activation-latency-main-probe.ts tests/e2e/terminal-split-activation-latency-phases.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts tests/e2e/terminal-split-activation-latency-main-probe.ts tests/e2e/terminal-split-activation-latency-phases.ts --reporter=dot", // Historical evidence maps to the surviving command below. - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts --reporter=dot", // Historical evidence maps to the surviving command below. - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts --reporter=dot", // Historical schema-v1 evidence records only; their labels do not verify the checkout or harness. "ORCA_TERMINAL_SPLIT_LATENCY_BENCH=1 ORCA_TERMINAL_SPLIT_LATENCY_LABEL=baseline-df14d1a2983d8339e788d0e521f1c4affd9c6d5f-headful-run1 ORCA_TERMINAL_SPLIT_LATENCY_OUTPUT=/private/tmp/orca-terminal-split-activation-baseline-df14d1a2983d8339e788d0e521f1c4affd9c6d5f-headful-run1.json pnpm exec playwright test tests/e2e/terminal-split-activation-latency.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", "ORCA_TERMINAL_SPLIT_LATENCY_BENCH=1 ORCA_TERMINAL_SPLIT_LATENCY_LABEL=candidate-d453ffcdb704764daced1b2917fddee7224389f0-headful-run2 ORCA_TERMINAL_SPLIT_LATENCY_OUTPUT=/private/tmp/orca-terminal-split-activation-candidate-d453ffcdb704764daced1b2917fddee7224389f0-headful-run2.json pnpm exec playwright test tests/e2e/terminal-split-activation-latency.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", @@ -6731,8 +6705,6 @@ "src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts", "src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts", "src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts", - "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts", - "src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts", "src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts", @@ -6758,15 +6730,6 @@ "keeps a newer deferred lookup when an older cleanup callback arrives" ] }, - { - "file": "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts", - "assertions": [ - "rejects a deferred split while inherited CWD is pending without mutation", - "continues rejecting after CWD resolves until PTY bind", - "carries resolved CWD as startupCwd for an allowed unbound detach", - "preserves persisted and live remote PTY detach handoff" - ] - }, { "file": "src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts", "assertions": [ @@ -6915,7 +6878,9 @@ "Audit1342 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-31\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/lib/pane-manager/pane-split-close.test.ts src/renderer/src/components/terminal-pane/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/deferred-split-pane-handoff.test.ts tests/e2e/terminal-split-activation-latency-artifact.unit.test.ts --reporter=dot\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/deferred-split-pane-handoff.test.ts --reporter=dot\",\n \"durationSeconds\": 44.43,\n \"summary\": \"Nine focused files and 96 tests passed. Vitest reported 37.78 seconds and measured wall time was 44.43 seconds; the run adds stable-pane CWD/input handoff, repeated-remount stale-owner fencing, bounded 64-record/15-second retention, seeded-input caps, ordered ordinary/acknowledged/immediate replay, predecessor acknowledged-promise settlement, capture-callback failure containment, and benchmark-artifact write-failure coverage to the existing split, detach, CWD, and local transport contracts.\"\n }", "Audit1342 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-31\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/lib/pane-manager/pane-split-close.test.ts src/renderer/src/components/terminal-pane/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/deferred-split-pane-handoff.test.ts tests/e2e/terminal-split-activation-latency-artifact.unit.test.ts tests/e2e/terminal-split-activation-latency-main-probe.ts tests/e2e/terminal-split-activation-latency-phases.ts tests/e2e/terminal-split-activation-latency-report.unit.test.ts --reporter=dot\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-pane-split-with-inherited-cwd.test.ts src/renderer/src/components/terminal-pane/resolve-split-cwd.test.ts src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport-input-write.test.ts src/renderer/src/components/terminal-pane/deferred-split-pane-handoff.test.ts tests/e2e/terminal-split-activation-latency-main-probe.ts tests/e2e/terminal-split-activation-latency-phases.ts --reporter=dot\",\n \"durationSeconds\": 4.14,\n \"summary\": \"The updated twelve-path focused command passed 99 tests (10 runnable test files plus 2 benchmark support modules), including schema-v2 main-process phase attribution, report revision identity, fixture IPC-write validation, stable-pane handoff, ordered pre-connect/live input, cleanup, detach, failure, and same-ID ownership contracts.\"\n }", "Audit1342 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\",\"remote-runtime\"]}. Remaining provider scope applies only to unchanged-source receipts.", - "Audit1342 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts\",\n \"assertions\": [\n \"starts no PTY connection before inherited CWD resolves\",\n \"applies the resolved directory to transport options\",\n \"disposing the split before resolution cancels the pending spawn\",\n \"invokes deferred-CWD cleanup exactly once after an authority-rotated direct-SSH spawn is disconnected and its delayed connect settles\"\n ]\n }\n]" + "Audit1342 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts\",\n \"assertions\": [\n \"starts no PTY connection before inherited CWD resolves\",\n \"applies the resolved directory to transport options\",\n \"disposing the split before resolution cancels the pending spawn\",\n \"invokes deferred-CWD cleanup exactly once after an authority-rotated direct-SSH spawn is disconnected and its delayed connect settles\"\n ]\n }\n]", + "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Exact lost direct alarms: 'moves chat mode only with its owning leaf %s'; 'creates a new terminal tab with the detached leaf layout and PTY id'; 'preserves the moved PTY shell override when the source uses %s'; 'syncs PTY ownership when the primary source pane is detached'; 'names the new tab as the client that already drew it did'; 'reports a refused move as a toast only for %s'; 'moves the detached tab into the requested group slot'; 'uses the live transport PTY id when the snapshot has not persisted it yet'; 'rejects a deferred split while inherited cwd is pending'; 'rejects a pending cwd even when the deferred marker is absent'; 'still rejects a deferred split after cwd resolves but before PTY bind'; 'carries resolved cwd when detaching an unbound non-deferred pane'; 'finds a same-worktree tab strip under overlay elements'; 'resolves the insertion slot from the hovered tab side'; 'ignores strips from another worktree'.", + "Audit1903 historical retired assertion inventory; these are not current validated assertions. Complete original raw assertion objects follow verbatim:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts\",\n \"assertions\": [\n \"rejects a deferred split while inherited CWD is pending without mutation\",\n \"continues rejecting after CWD resolves until PTY bind\",\n \"carries resolved CWD as startupCwd for an allowed unbound detach\",\n \"preserves persisted and live remote PTY detach handoff\"\n ]\n }" ], "demotionRule": "Keep experimental or demote if pane activation waits on CWD, a deferred split can detach before PTY bind, a remount or rehome loses its stable CWD/input handoff, stale owners mutate a successor record, detached cwd is lost, input reorders or remains pending after cleanup, a closed pane can spawn, stale retirement kills a newer same-ID owner, remote-runtime delegation creates a competing local pane, or the focused suite flakes without an identified product or harness cause." }, @@ -6994,7 +6959,7 @@ "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4327", "https://github.com/stablyai/orca/pull/14590", @@ -7003,7 +6968,7 @@ "https://github.com/stablyai/orca/issues/14524" ], "invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close commits durable tab retirement before PTY stop can publish graph loss, does not acknowledge before that retirement, and treats the later exit retirement as idempotent. Workspace-wide CLI close applies that same durable contract to every terminal in exactly one worktree, including pinned and persisted-only surfaces, without touching sibling-worktree PTYs or resume records. A persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.", - "oracle": "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: 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: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", + "oracle": "Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 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: 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: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts", @@ -7218,7 +7183,8 @@ "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.", "Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Historical removed assertion inventory: []", "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. Historical removed assertion inventory: [{\"file\":\"src/main/runtime/orca-runtime.test.ts\",\"assertions\":[\"workspace-wide close force-retires pinned and unpinned tabs, clears resume/incarnation state, awaits both target PTYs, preserves the sibling worktree, and reports an unconfirmed stop as unverifiable\"]}]", - "Audit1863 removes the standalone local pane-to-PTY equality example. Its direct local-PTY authority alarm is intentionally lost; retained canonical runtime-handle tests do not replace it or prove physical pane/session retirement. Existing E2E and continuity receipts remain scoped to their original commands and counts." + "Audit1863 removes the standalone local pane-to-PTY equality example. Its direct local-PTY authority alarm is intentionally lost; retained canonical runtime-handle tests do not replace it or prove physical pane/session retirement. Existing E2E and continuity receipts remain scoped to their original commands and counts.", + "Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Lost direct alarms: 'remaps legacy SSH lease leaf ids by PTY when the layout is already normalized'; 'promotes an empty tab layout to a durable UUID root when persisting the first PTY binding'." ], "demotionRule": "Keep experimental or demote to protection none if exact PTY disappearance flakes, a sibling/detached pane is retired, late hooks can recreate closed authority, or a renderer graph sync retires a host-created tab that no explicit close retired." }, @@ -10331,7 +10297,7 @@ "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", + "coverageNotes": "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -10346,14 +10312,14 @@ "https://github.com/stablyai/orca/issues/12902" ], "invariant": "SSH, WSL, and remote-runtime restore paths must treat provider listing failures and unknown liveness as unknown, not dead, while still avoiding duplicate spawn and clearing expired relay leases exactly once. Direct SSH disconnect, reconnect, and wake must keep PTY bindings and relay identity, and target snapshot hydration/reconnect cannot reset sibling SSH, local, WSL, or runtime-owned state. Every restored remote terminal must preserve its provider PTY identity, including the authoritative incarnation returned by a successful session-ID reattach. After a recoverable partition the same authenticated runtime must reattach the same PTY, reject detached input, apply the latest viewport, and report healthy only after authoritative replay. A successful one-shot reachability probe may replace a pre-ready shared-control socket, but waiting RPCs must continue onto the replacement under their original deadline without duplicate host delivery or retained request bytes. Automatic PTY recovery stops after one bounded minute without a fatal terminal error; a manual reconnect starts a newly fenced epoch against the same PTY, and closed panes retain no recovery UI state. Successful current-transport recovery must clear every stale error surfaced for that pane without clearing or displaying a sibling pane's error; a later genuine failure must remain visible. Each transport retains at most eight suppressed messages, each pane retains at most eight distinct messages, and the rendered surface retains at most 24 lines and 4,000 characters. One capability-gated terminal-create mutation must produce at most one host PTY across an unknown response outcome, remain manually retryable after cutoff, and never let a stale completion replace a newer pane lifecycle. Reconnect must alternate exact activation with authoritative inventory so neither a stale activation response nor an activation failure can strand or retire a pane, and activating a parked surface whose persisted binding was already retired must respawn it rather than report a changed owner after signalling its exit.", - "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: 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): 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): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples.", + "oracle": "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): 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: 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): 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): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/layout/split/pane-split-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/mounting/pane-transport-unmount.test.ts src/renderer/src/components/terminal-pane/titles/restored-pane-titles.test.ts src/renderer/src/components/terminal-pane/mounting/queued-initial-cwd.test.ts src/renderer/src/components/terminal-pane/viewport/pane-visibility-identity.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/layout/split/pane-split-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/mounting/pane-transport-unmount.test.ts src/renderer/src/components/terminal-pane/titles/restored-pane-titles.test.ts src/renderer/src/components/terminal-pane/mounting/queued-initial-cwd.test.ts src/renderer/src/components/terminal-pane/viewport/pane-visibility-identity.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/TerminalRemoteRuntimeReconnectBanner.test.tsx src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal/terminal-create-idempotency.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/runtime/hosts/platform-probe/public-ssh-state.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "pnpm run build:web-from-renderer", @@ -10364,7 +10330,6 @@ "src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts", "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", "src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts", - "src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts", "src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts", "src/renderer/src/components/terminal-pane/layout/split/pane-split-startup.test.ts", "src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts", @@ -10396,8 +10361,6 @@ "src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts", "src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts", "src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts", - "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts", - "src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts", "src/main/ipc/ssh/ssh.test.ts", "src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts", "src/main/runtime/hosts/platform-probe/public-ssh-state.test.ts", @@ -10499,12 +10462,6 @@ "in-flight mutation coordination is bounded and releases capacity after settlement" ] }, - { - "file": "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts", - "assertions": [ - "a detached null-PTY leaf remains marked for pending activation before ownership transfer" - ] - }, { "file": "src/main/ssh/connection/ssh-connection-manager.test.ts", "assertions": [ @@ -10658,7 +10615,9 @@ "Module-layout cleanup splits the former terminals-hydration suite into workspace-terminal-reconnect-hydration and workspace-navigation-history-hydration. The reconnect case retains daemon wake-hint/session-readiness outcomes; its store-publication count assertion is intentionally retired. The navigation case retains hydration-seeded visit/Back behavior. Historical receipts remain verbatim and do not validate these changed test owners.", "Audit1862 reduces remote-runtime-client-error-classification.test.ts by removing recoverable-code, authentication/protocol-negative and client-code blacklist inventories. Those direct classification alarms are lost; no equivalent replacement or actual retry behavior is claimed. Retained structured-code precedence and unstructured legacy normalization cases do not execute a remote connection. Socket-generation and socket-liveness sources in this selector are unchanged. Existing active receipts use unrelated selectors and remain unchanged; focused survivor execution does not validate the broad reconnect selector or physical platform/provider coverage.", "Audit1879 removes the standalone ASCII serving-detail length-cap example from ssh-retained-payload-admission.test.ts. That direct cap alarm is intentionally lost without equivalent replacement coverage. The three retained authority assertion references, commands and testFiles remain unchanged. Focused survivor execution is not new execution evidence for the broad SSH reattach gate or actual remote/platform behavior; existing receipts retain their original commands, results and counts.", - "Audit1880 removes the entire mounted-terminal-scrollback.test.ts suite. Its direct fake-terminal scrollback option-assignment and repeated-value write-budget alarm is intentionally lost; no actual xterm output-retention or equivalent replacement coverage is claimed. Only its exact tokens in current commands and its testFiles entry are removed. Existing unrelated dated receipts, their raw objects and platform/provider accounting remain unchanged; they do not validate the reduced command selector." + "Audit1880 removes the entire mounted-terminal-scrollback.test.ts suite. Its direct fake-terminal scrollback option-assignment and repeated-value write-budget alarm is intentionally lost; no actual xterm output-retention or equivalent replacement coverage is claimed. Only its exact tokens in current commands and its testFiles entry are removed. Existing unrelated dated receipts, their raw objects and platform/provider accounting remain unchanged; they do not validate the reduced command selector.", + "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Exact lost direct alarms: 'detaches a rolled-back split surface without closing its PTY'; \"closes a tab through its last pane with the requester's reason, never an implied user close\"; 'uses non-destructive tab close semantics for the last rolled-back pane'; 'ignores a delayed rollback after the pane PTY identity changed'; 'retires a mounted rollback pane without detaching it as a movable surface'; 'retires mounted authority and binding while preserving the process and sleeping fence'; 'suppresses the pane PTY exit before intentional close teardown destroys the transport'; 'does not suppress natural PTY exits that already cleared the transport id'; 'moves chat mode only with its owning leaf %s'; 'creates a new terminal tab with the detached leaf layout and PTY id'; 'preserves the moved PTY shell override when the source uses %s'; 'syncs PTY ownership when the primary source pane is detached'; 'names the new tab as the client that already drew it did'; 'reports a refused move as a toast only for %s'; 'moves the detached tab into the requested group slot'; 'uses the live transport PTY id when the snapshot has not persisted it yet'; 'rejects a deferred split while inherited cwd is pending'; 'rejects a pending cwd even when the deferred marker is absent'; 'still rejects a deferred split after cwd resolves but before PTY bind'; 'carries resolved cwd when detaching an unbound non-deferred pane'; 'finds a same-worktree tab strip under overlay elements'; 'resolves the insertion slot from the hovered tab side'; 'ignores strips from another worktree'.", + "Audit1903 historical retired assertion inventory; these are not current validated assertions. Complete original raw assertion objects follow verbatim:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts\",\n \"assertions\": [\n \"a detached null-PTY leaf remains marked for pending activation before ownership transfer\"\n ]\n }" ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, @@ -15168,22 +15127,21 @@ "providers": ["local"], "coveredPlatforms": ["macos"], "coveredProviders": ["local"], - "coverageNotes": "A forced pre-spawn barrier makes one visible Quick Command cross a recovery remount before its successor PTY binds. Lifecycle contracts retain lower-layer ownership; the Electron sentinel adds the rendered affordance, real PTY, exact-once terminal marker, staged identity file, and unrelated sibling canary. The test-value audit removed the store examples for retaining an undelivered queued startup command across remount, distinct queued ownership, sibling-bind preservation, unspawned close, and sibling queue isolation. The remaining store cases exercise recovery admission/settlement and non-replay after consumption; neither covers an undelivered command. The store suite is retired from this gate. Retained lifecycle and historical Electron evidence do not establish equivalent replacement coverage; historical commands and results remain historical. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", + "coverageNotes": "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): A forced pre-spawn barrier makes one visible Quick Command cross a recovery remount before its successor PTY binds. Lifecycle contracts retain lower-layer ownership; the Electron sentinel adds the rendered affordance, real PTY, exact-once terminal marker, staged identity file, and unrelated sibling canary. The test-value audit removed the store examples for retaining an undelivered queued startup command across remount, distinct queued ownership, sibling-bind preservation, unspawned close, and sibling queue isolation. The remaining store cases exercise recovery admission/settlement and non-replay after consumption; neither covers an undelivered command. The store suite is retired from this gate. Retained lifecycle and historical Electron evidence do not establish equivalent replacement coverage; historical commands and results remain historical. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4876", "https://github.com/stablyai/orca/pull/15630" ], "invariant": "A Quick Command selected for a new terminal remains owned by that tab through a recovery remount, executes exactly once only after the successor PTY binds, and never reaches an unrelated terminal.", - "oracle": "Arm the E2E-only pre-spawn barrier, click the visible Quick Command, force one recovery generation while the original spawn is blocked, and release it. Require one exact semantic xterm marker, an independently written pane/tab identity file matching the bound live PTY, queue consumption only after bind, and a live interactive sibling canary.", + "oracle": "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Arm the E2E-only pre-spawn barrier, click the visible Quick Command, force one recovery generation while the original spawn is blocked, and release it. Require one exact semantic xterm marker, an independently written pane/tab identity file matching the bound live PTY, queue consumption only after bind, and a live interactive sibling canary.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-owner-hydration-backend-retention.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-queued-startup-consume.test.ts src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/layout/split/pane-split-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/mounting/pane-transport-unmount.test.ts src/renderer/src/components/terminal-pane/titles/restored-pane-titles.test.ts src/renderer/src/components/terminal-pane/mounting/queued-initial-cwd.test.ts src/renderer/src/components/terminal-pane/viewport/pane-visibility-identity.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-owner-hydration-backend-retention.test.ts src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-queued-startup-consume.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/layout/split/pane-split-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/mounting/pane-transport-unmount.test.ts src/renderer/src/components/terminal-pane/titles/restored-pane-titles.test.ts src/renderer/src/components/terminal-pane/mounting/queued-initial-cwd.test.ts src/renderer/src/components/terminal-pane/viewport/pane-visibility-identity.test.ts --reporter=dot", "pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-owner-hydration-backend-retention.test.ts", "src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-queued-startup-consume.test.ts", - "src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts", "src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts", "src/renderer/src/components/terminal-pane/layout/split/pane-split-startup.test.ts", "src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts", @@ -15248,7 +15206,8 @@ "Windows, Linux, SSH, WSL, and paired-runtime topologies are not covered because they were not causal to STA-4876.", "The sentinel remains advisory while the repository-wide E2E signal is red.", "The test-value audit removed the store examples for retaining an undelivered queued startup command across remount, distinct queued ownership, sibling-bind preservation, unspawned close, and sibling queue isolation. The remaining store cases exercise recovery admission/settlement and non-replay after consumption; neither covers an undelivered command. The store suite is retired from this gate. Retained lifecycle and historical Electron evidence do not establish equivalent replacement coverage; historical commands and results remain historical.", - "Audit1880 removes the entire mounted-terminal-scrollback.test.ts suite. Its direct fake-terminal scrollback option-assignment and repeated-value write-budget alarm is intentionally lost; no actual xterm output-retention or equivalent replacement coverage is claimed. Only its exact tokens in current commands and its testFiles entry are removed. Existing unrelated dated receipts, their raw objects and platform/provider accounting remain unchanged; they do not validate the reduced command selector." + "Audit1880 removes the entire mounted-terminal-scrollback.test.ts suite. Its direct fake-terminal scrollback option-assignment and repeated-value write-budget alarm is intentionally lost; no actual xterm output-retention or equivalent replacement coverage is claimed. Only its exact tokens in current commands and its testFiles entry are removed. Existing unrelated dated receipts, their raw objects and platform/provider accounting remain unchanged; they do not validate the reduced command selector.", + "Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Exact lost direct alarms: 'detaches a rolled-back split surface without closing its PTY'; \"closes a tab through its last pane with the requester's reason, never an implied user close\"; 'uses non-destructive tab close semantics for the last rolled-back pane'; 'ignores a delayed rollback after the pane PTY identity changed'; 'retires a mounted rollback pane without detaching it as a movable surface'; 'retires mounted authority and binding while preserving the process and sleeping fence'; 'suppresses the pane PTY exit before intentional close teardown destroys the transport'; 'does not suppress natural PTY exits that already cleared the transport id'." ], "demotionRule": "Demote if the barrier can be bypassed nondeterministically, either independent oracle is removed, the sibling canary is no longer isolated, or one unexplained flake occurs." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 07808e80134..e3471d4aafc 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -2962,7 +2962,6 @@ "src/main/persistence/profile-state/profile-state-recovery-batch.test.ts": 180, "src/main/persistence/profile-state/profile-state-recovery-copy.test.ts": 133, "src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts": 11125, - "src/main/persistence/profile-state/profile-state-recovery-crash-process.test.ts": 275, "src/main/persistence/profile-state/profile-state-runtime-preflight.test.ts": 723, "src/main/persistence/profile-state/profile-state-section-repair.test.ts": 5877, "src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts": 1860, @@ -2976,9 +2975,7 @@ "src/main/persistence/profile-state/profile-state-write-transaction.test.ts": 94, "src/main/persistence/profile-state/profile-state-writer-capacity-errors.test.ts": 84, "src/main/persistence/profile-state/profile-state-writer-close.test.ts": 108, - "src/main/persistence/profile-state/profile-state-writer-open-error-cause.test.ts": 79, "src/main/persistence/profile-state/profile-state-writer-protocol-faults.test.ts": 747, - "src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts": 57, "src/main/persistence/profile-state/profile-state-writer-sleep.test.ts": 803, "src/main/persistence/profile-state/profile-state-writer-worker.test.ts": 1458, "src/main/persistence/restoring-sessions/pane-alias-normalization.test.ts": 847, @@ -3011,15 +3008,12 @@ "src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts": 1853, "src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts": 2079, "src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts": 1795, - "src/main/persistence/terminal-topology/persistence-terminal-option-key-migration.test.ts": 1937, "src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts": 2870, "src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts": 2027, - "src/main/persistence/terminal-topology/terminal-close-write-failure.test.ts": 58, "src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts": 1808, "src/main/persistence/terminal-topology/terminal-layout-apply.test.ts": 2005, "src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts": 1773, "src/main/persistence/terminal-topology/terminal-layout-create.test.ts": 2107, - "src/main/persistence/terminal-topology/terminal-layout-default-tabs-applied.test.ts": 1749, "src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts": 1753, "src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts": 1977, "src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts": 2198, @@ -3027,13 +3021,11 @@ "src/main/persistence/terminal-topology/terminal-leaf-move.test.ts": 2197, "src/main/persistence/terminal-topology/terminal-owner-invariants.test.ts": 285, "src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts": 1796, - "src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts": 381, "src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts": 1766, "src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts": 1941, "src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts": 2114, "src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts": 1872, "src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts": 1626, - "src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts": 673, "src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts": 544, "src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts": 619, "src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts": 2374, @@ -3054,9 +3046,7 @@ "src/main/persistence/tracking-repos/persistence-worktree-meta-host-target-twins.test.ts": 2062, "src/main/persistence/tracking-repos/persistence-worktree-name-retirement.test.ts": 2905, "src/main/persistence/tracking-repos/persistence-worktree-visibility.test.ts": 1935, - "src/main/persistence/tracking-repos/probeable-local-worktree-metadata-candidates.test.ts": 541, "src/main/persistence/tracking-repos/project-group-session-batch.test.ts": 496, - "src/main/persistence/tracking-repos/project-host-compatibility.test.ts": 75, "src/main/persistence/tracking-repos/repo-update-host-guard.test.ts": 478, "src/main/persistence/tracking-repos/worktree-identity-migration-field-coverage.test.ts": 505, "src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts": 372, @@ -5819,7 +5809,6 @@ "src/renderer/src/components/native-chat/session/options/controls/NativeChatModelCombobox.test.tsx": 692, "src/renderer/src/components/native-chat/NativeChatNewRowsMarker.test.tsx": 3019, "src/renderer/src/components/native-chat/usage/NativeChatNoticeRow.test.tsx": 3399, - "src/renderer/src/components/native-chat/markdown/NativeChatPacedMarkdown.mermaid.test.tsx": 2702, "src/renderer/src/components/native-chat/NativeChatPaneHeader.test.tsx": 2736, "src/renderer/src/components/native-chat/NativeChatPromptEditor.paragraph-selection.test.tsx": 652, "src/renderer/src/components/native-chat/NativeChatPromptEditor.test.tsx": 1110, @@ -5830,7 +5819,6 @@ "src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageRows.test.tsx": 2691, "src/renderer/src/components/native-chat/prompts/NativeChatResolutionReceipt.test.tsx": 912, "src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx": 4025, - "src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.images.test.tsx": 3477, "src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx": 7151, "src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx": 3594, "src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx": 4368, @@ -5859,7 +5847,6 @@ "src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.test.tsx": 3183, "src/renderer/src/components/native-chat/NativeChatUserMessageFold.test.tsx": 3156, "src/renderer/src/components/native-chat/NativeChatView.test.tsx": 5672, - "src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.test.tsx": 643, "src/renderer/src/components/native-chat/session/attention/StructuredAgentSessionAttentionBridge.lifecycle.test.tsx": 2167, "src/renderer/src/components/native-chat/session/attention/StructuredAgentSessionAttentionBridge.test.tsx": 2855, "src/renderer/src/components/native-chat/StructuredAgentSessionPaneOverlayLayer.test.tsx": 620, @@ -5892,7 +5879,6 @@ "src/renderer/src/components/native-chat/native-chat-element-file-drop.test.tsx": 2057, "src/renderer/src/components/native-chat/native-chat-external-attachments-destination.test.tsx": 951, "src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937, - "src/renderer/src/components/native-chat/links/actions/native-chat-file-link.test.ts": 336, "src/renderer/src/components/native-chat/native-chat-header-ownership.test.tsx": 2796, "src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts": 895, "src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts": 49, @@ -5936,7 +5922,6 @@ "src/renderer/src/components/native-chat/native-chat-turn-diffs.test.ts": 340, "src/renderer/src/components/native-chat/native-chat-unkerned-run-decorations.test.ts": 594, "src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.test.tsx": 2351, - "src/renderer/src/components/native-chat/media/visuals/native-chat-visual-read-client.test.ts": 163, "src/renderer/src/components/native-chat/native-chat-working-status-shared-clock.test.tsx": 412, "src/renderer/src/components/native-chat/session/options/catalog/omp-model-switch-capability.test.ts": 211, "src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts": 131, @@ -5969,7 +5954,6 @@ "src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.test.tsx": 2131, "src/renderer/src/components/native-chat/prompts/use-native-chat-interactive-prompt-card.test.ts": 1962, "src/renderer/src/components/native-chat/use-native-chat-launch-draft-adoption.test.tsx": 319, - "src/renderer/src/components/native-chat/links/actions/use-native-chat-link-actions.test.tsx": 2225, "src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-pending.test.ts": 2063, "src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-visibility.test.ts": 2047, "src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-wsl-wake.test.ts": 1800, @@ -6473,8 +6457,6 @@ "src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1953, "src/renderer/src/components/task-page/task-page-work-item-pagination.test.ts": 63, "src/renderer/src/components/task-page/use-task-page-source-display.test.tsx": 5228, - "src/renderer/src/components/terminal-pane/layout/close/CloseTerminalDialog.test.tsx": 484, - "src/renderer/src/components/terminal-pane/layout/close/PinnedTabCloseDialog.test.tsx": 2221, "src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx": 2303, "src/renderer/src/components/terminal-pane/session-fork/TerminalAgentSessionForkDialog.test.tsx": 266, "src/renderer/src/components/terminal-pane/mounting/TerminalOverlaySlot.emptied-reaction.test.tsx": 430, @@ -6504,7 +6486,6 @@ "src/renderer/src/components/terminal-pane/account-restart/detached/claude-detached-pane-restart.test.ts": 1938, "src/renderer/src/components/terminal-pane/provider-notices/claude-diff-panel/claude-diff-panel-notice-banner.test.tsx": 1986, "src/renderer/src/components/terminal-pane/notifications/claude-side-question-completion.test.ts": 2305, - "src/renderer/src/components/terminal-pane/layout/close/closed-terminal-leaf-notice-layout-owner.test.ts": 1032, "src/renderer/src/components/terminal-pane/provider-notices/codex-backfill/codex-backfill-error-detector.test.ts": 26, "src/renderer/src/components/terminal-pane/account-restart/detached/codex-detached-pane-restart.test.ts": 2270, "src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-shared-server-banner.test.tsx": 2766, @@ -6516,8 +6497,6 @@ "src/renderer/src/components/terminal-pane/viewport/desktop-fit-fallback.test.ts": 92, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/direct-ssh-hidden-output-restore-unavailable-banner.test.ts": 1975, "src/renderer/src/components/terminal-pane/links/http/edge-wrapped-terminal-http-links.test.ts": 529, - "src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout-render-stability.test.ts": 2069, - "src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout.test.ts": 102, "src/renderer/src/components/terminal-pane/links/floating-file-link-selection.test.ts": 2282, "src/renderer/src/components/terminal-pane/links/http/framed-overlay-terminal-http-links.test.ts": 508, "src/shared/git-bash-console-capacity.test.ts": 56, @@ -6529,7 +6508,6 @@ "src/renderer/src/components/terminal-pane/input/keyboard-handlers-ime-enter-keyup.test.tsx": 2120, "src/renderer/src/components/terminal-pane/input/keyboard-handlers-ime.test.tsx": 2239, "src/renderer/src/components/terminal-pane/pty-connection/startup/launch-parity-window-tab.test.ts": 17426, - "src/renderer/src/components/terminal-pane/layout/close/layout-owner-pane-close.test.ts": 2445, "src/renderer/src/components/terminal-pane/layout-serialization.test.ts": 109, "src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-transport.test.ts": 358, "src/renderer/src/components/terminal-pane/parking/retention/manual-terminal-worktree-park-eligibility.test.ts": 302, @@ -6713,7 +6691,6 @@ "src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-history-seam.test.ts": 2093, "src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts": 371, "src/renderer/src/components/terminal-pane/links/http/repro-8832-url-next-line.test.ts": 592, - "src/renderer/src/components/terminal-pane/layout/close/request-active-terminal-pane-close.test.ts": 187, "src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts": 56, "src/renderer/src/components/terminal-pane/snapshots/restored-snapshot-coverage.test.ts": 44, "src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts": 577, @@ -6763,8 +6740,6 @@ "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts": 980, "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts": 498, "src/renderer/src/components/terminal-pane/emulation/terminal-inline-image-da1.test.ts": 127, - "src/renderer/src/components/terminal-pane/input/terminal-input-host-platform.test.ts": 1681, - "src/renderer/src/components/terminal-pane/input/terminal-input-quarantine.test.ts": 62, "src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit-coexistence.test.ts": 621, "src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit-device-trace.test.ts": 415, "src/renderer/src/components/terminal-pane/input/ime/terminal-ios-hangul-preedit.test.ts": 818, @@ -6800,7 +6775,6 @@ "src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx": 1748, "src/renderer/src/components/terminal-pane/layout/reconciliation/terminal-pane-frame-reconciliation.test.ts": 903, "src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts": 4534, - "src/renderer/src/components/terminal-pane/layout/ownership/terminal-pane-layout-owner-commands.test.ts": 182, "src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-bootstrap.test.ts": 1723, "src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-events-layout-owner.test.ts": 986, "src/renderer/src/components/terminal-pane/render-health/recovery/terminal-pane-recovery-host-rebind-cap.test.ts": 826, @@ -6809,11 +6783,8 @@ "src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts": 2015, "src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-with-inherited-cwd.test.ts": 1834, "src/renderer/src/components/terminal-pane/pty-transport/recovery/terminal-pane-surface-ownership.test.ts": 426, - "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-commit.test.ts": 2141, - "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-frame-drawn.test.ts": 1889, "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts": 2090, "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts": 2147, - "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts": 1893, "src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-flip-telemetry.test.ts": 123, "src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-worktree-driver-loop.test.tsx": 735, "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-pane-candidates.test.ts": 252, @@ -6841,7 +6812,6 @@ "src/renderer/src/components/terminal-pane/snapshots/terminal-snapshot-replay-paint.test.ts": 499, "src/renderer/src/components/terminal-pane/titles/terminal-title-evidence.test.ts": 184, "src/renderer/src/components/terminal-pane/links/http/terminal-url-link-click.test.ts": 2057, - "src/renderer/src/components/terminal-pane/input/terminal-user-input-signal.test.ts": 57, "src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts": 1669, "src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts": 48, "src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.test.ts": 1878, diff --git a/src/main/persistence/profile-state/profile-state-pre-migration-backup.test.ts b/src/main/persistence/profile-state/profile-state-pre-migration-backup.test.ts index 8f2ce95caf7..eccfe39da24 100644 --- a/src/main/persistence/profile-state/profile-state-pre-migration-backup.test.ts +++ b/src/main/persistence/profile-state/profile-state-pre-migration-backup.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs' +import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -103,18 +103,6 @@ describe('the backup taken before the first boot-time rewrite of saved data', () expect(readGeneration(backupPath)).toBe(1) }) - it('refuses rather than replaces something else at the backup path', async () => { - const { databasePath, backupPath } = fixture() - mkdirSync(backupPath) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const runBackup = vi.fn(writeProfileStateBackup) - - await expect( - ensureProfileStatePreMigrationBackup(databasePath, PROFILE, runBackup) - ).resolves.toBe('failed') - expect(runBackup).not.toHaveBeenCalled() - }) - it('is not one of the hourly backups, so rotation never prunes it', async () => { const { databasePath, backupPath, write } = fixture() await ensureProfileStatePreMigrationBackup(databasePath, PROFILE, writeProfileStateBackup) diff --git a/src/main/persistence/profile-state/profile-state-recovery-batch.test.ts b/src/main/persistence/profile-state/profile-state-recovery-batch.test.ts index 7a192915968..fe48e2c409f 100644 --- a/src/main/persistence/profile-state/profile-state-recovery-batch.test.ts +++ b/src/main/persistence/profile-state/profile-state-recovery-batch.test.ts @@ -15,7 +15,7 @@ import { } from 'node:fs' import type * as FileSystem from 'node:fs' import { tmpdir } from 'node:os' -import { basename, dirname, isAbsolute, join } from 'node:path' +import { basename, dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import * as processes from '@orca/process-host' import { copyProfileStateRecoveryFiles } from './profile-state-recovery-copy' @@ -109,38 +109,7 @@ describe('batched profile recovery copies', () => { expectNoTemporary(directory) }) - it('does nothing for an empty batch', () => { - const run = vi.spyOn(processes, 'runProcessSync') - copyProfileStateRecoveryFiles([]) - expect(run).not.toHaveBeenCalled() - }) - describe.skipIf(process.platform !== 'darwin')('Darwin batch boundaries', () => { - it('shares one process with absolute arguments and the per-file timeout budget', () => { - const { directory, files } = fixture() - const run = vi.spyOn(processes, 'runProcessSync') - copyProfileStateRecoveryFiles(files) - expect(run).toHaveBeenCalledOnce() - const spec = run.mock.calls[0]?.[0] - expect(spec?.args?.slice(1).every(isAbsolute)).toBe(true) - expect(spec?.args).toHaveLength(4) - expect(spec?.timeoutMs).toBe(60_000) - expectIndependent(files) - expectNoTemporary(directory) - }) - - it('bounds a shared process when many large artifacts are retained', () => { - const { directory, files } = fixture( - Array.from({ length: 17 }, (_, index) => `backup-${index}.db`) - ) - const run = vi.spyOn(processes, 'runProcessSync') - copyProfileStateRecoveryFiles(files) - expect(run).toHaveBeenCalledTimes(2) - expect(run.mock.calls.every(([spec]) => (spec.args?.length ?? 0) <= 18)).toBe(true) - expectIndependent(files) - expectNoTemporary(directory) - }) - it.each([ ['same.db', 'same.db'], ['CASE.db', 'case.db'], diff --git a/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts b/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts index b556acce830..0acc49d27ea 100644 --- a/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts +++ b/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts @@ -461,35 +461,6 @@ describe('SQLite recovery process death', () => { ) }) -describe('seeded recovery fixture copies', () => { - it.each([ - ['json', false], - ['json', true], - ['sqlite', true] - ] as const)( - 'isolates %s/accepted=%s through corruption and WAL reopen', - async (kind, accepted) => { - const first = await fixture(kind, accepted) - const second = await fixture(kind, accepted) - const seed = seededFixtures.get(`${kind}/${accepted}`) - if (!seed) { - throw new Error('Seed fixture was not retained') - } - expect(new Set([first.root, second.root, seed.root]).size).toBe(3) - for (const [suffix, bytes] of seed.originalFamily) { - expect(readFileSync(`${first.databasePath}${suffix}`).equals(bytes)).toBe(true) - writeFileSync(`${first.databasePath}${suffix}`, 'corrupted-copy') - expect(readFileSync(`${second.databasePath}${suffix}`).equals(bytes)).toBe(true) - expect(readFileSync(`${seed.databasePath}${suffix}`).equals(bytes)).toBe(true) - } - const third = await fixture(kind, accepted) - expect(readSqlite(third.databasePath)).toEqual(oldState) - expect(readFileSync(seed.backupPath).equals(seed.backupBytes)).toBe(true) - expect(readFileSync(seed.exportPath, 'utf8')).toBe(selectedJson) - } - ) -}) - it.each(['first-export', 'authority-marker'] as const)( 'keeps current-JSON rollback safe through %s removal', async (boundary) => { diff --git a/src/main/persistence/profile-state/profile-state-recovery-crash-process.test.ts b/src/main/persistence/profile-state/profile-state-recovery-crash-process.test.ts deleted file mode 100644 index 93ecec15a29..00000000000 --- a/src/main/persistence/profile-state/profile-state-recovery-crash-process.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import { buildRecoveryCrashProcess } from './profile-state-recovery-crash-process' - -it('bundles one process-host source graph into the isolated recovery fixture', () => { - const root = mkdtempSync(join(tmpdir(), 'orca-recovery-bundle-')) - try { - const { metafile } = buildRecoveryCrashProcess(root) - const packageInputs = Object.keys(metafile.inputs).filter((file) => - file.includes('/process-host/') - ) - expect(packageInputs).toContain('src/packages/process-host/src/run-process.ts') - expect(packageInputs.every((file) => file.startsWith('src/packages/process-host/src/'))).toBe( - true - ) - const packageExternals = Object.values(metafile.outputs) - .flatMap((output) => output.imports) - .filter((entry) => entry.external && entry.path.startsWith('@orca/process-host')) - expect(packageExternals).toEqual([]) - } finally { - rmSync(root, { recursive: true, force: true }) - } -}) diff --git a/src/main/persistence/profile-state/profile-state-runtime-preflight.test.ts b/src/main/persistence/profile-state/profile-state-runtime-preflight.test.ts index 34a4b02c0a4..fbc5f736b92 100644 --- a/src/main/persistence/profile-state/profile-state-runtime-preflight.test.ts +++ b/src/main/persistence/profile-state/profile-state-runtime-preflight.test.ts @@ -35,15 +35,6 @@ describe('profile runtime preflight', () => { expect(result.sqliteVersion).toMatch(/^\d+\.\d+\.\d+$/) }) - it('refuses readiness when a required worker artifact is absent', async () => { - await expect( - preflightProfileStateRuntime({ - workerPath: join(directory, 'missing.js'), - backupWorkerPath - }) - ).rejects.toThrow('Profile state writer') - }) - it('does not trust a backup success reply without a valid database', async () => { const corruptBackup = join(directory, 'corrupt-backup.cjs') writeFileSync( diff --git a/src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts b/src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts index ed6e3609f4a..e5c699c2353 100644 --- a/src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts +++ b/src/main/persistence/profile-state/profile-state-selected-profile-recovery.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { acquireProfileStateMaintenance } from './profile-state-access' import { migrateProfileStateToSqlite } from './profile-state-migration' -import { getProfileStateExports, rollbackProfileState } from './profile-state-recovery-command' +import { rollbackProfileState } from './profile-state-recovery-command' import { bootstrapProfileStateAuthority } from './profile-state-authority-bootstrap' const roots: string[] = [] @@ -67,13 +67,4 @@ describe('explicit profile recovery selection', () => { expect(reopened.migrated).toBe(true) reopened.authority?.close() }) - - it('refuses unknown and escaping IDs without falling back to the active profile', () => { - const f = fixture() - const before = readFileSync(f.active.databaseFile) - for (const id of ['missing', '../active']) { - expect(() => getProfileStateExports(f.root, id)).toThrow('Could not resolve') - } - expect(readFileSync(f.active.databaseFile).equals(before)).toBe(true) - }) }) diff --git a/src/main/persistence/profile-state/profile-state-startup-secrets.test.ts b/src/main/persistence/profile-state/profile-state-startup-secrets.test.ts index deaebc70d17..e8c6c221c35 100644 --- a/src/main/persistence/profile-state/profile-state-startup-secrets.test.ts +++ b/src/main/persistence/profile-state/profile-state-startup-secrets.test.ts @@ -9,7 +9,7 @@ import { _resetSecretStoreForTests } from '../../../shared/secret-store' import { Store } from '../loading-store/store' -import * as storeDomains from '../loading-store/store-domain-composition' + import { ProfileStateSqliteAuthority } from './profile-state-sqlite-authority' let keyState: 'available' | 'unavailable' | 'decrypt-fails' = 'available' @@ -80,38 +80,6 @@ const secrets = { } const sealed = (value: string) => Buffer.from(`encrypted:${value}`, 'utf8').toString('base64') -it.each([false, true])( - 'rejects reused input before Store context installation (secret=%s)', - (hasSecret) => { - const directory = mkdtempSync(join(tmpdir(), 'orca-consumed-startup-')) - directories.push(directory) - const authority = new ProfileStateSqliteAuthority(join(directory, 'profile-state.db'), 'once') - if (hasSecret) { - authority.writeSerializedState( - Buffer.from( - JSON.stringify({ - settings: { opencodeSessionCookie: sealed(secrets.cookie) } - }) - ) - ) - } - const options = { - dataFile: join(directory, 'orca-data.json'), - profileStateAuthority: authority, - initialAuthorityState: authority.readInitialState() - } - const store = new Store(options) - stores.push(store) - if (hasSecret) { - expect(store.getSettings().opencodeSessionCookie).toBe(secrets.cookie) - } - const install = vi.spyOn(storeDomains, 'installStoreDomainContexts') - - expect(() => new Store(options)).toThrow('already been consumed') - expect(install).not.toHaveBeenCalled() - } -) - describe.each(['serialized', 'parsed'] as const)( '%s startup secret retention', (representation) => { diff --git a/src/main/persistence/profile-state/profile-state-startup-snapshot.test.ts b/src/main/persistence/profile-state/profile-state-startup-snapshot.test.ts index 84401b47d28..ccfef4d39d5 100644 --- a/src/main/persistence/profile-state/profile-state-startup-snapshot.test.ts +++ b/src/main/persistence/profile-state/profile-state-startup-snapshot.test.ts @@ -6,7 +6,7 @@ import type { ProfileStateAuthority } from '../loading-store/profile-state-autho import { Store } from '../loading-store/store' import { bootstrapProfileStateAuthority } from './profile-state-authority-bootstrap' import * as profileStateDatabase from './profile-state-database' -import * as profileStateDocumentReader from './profile-state-document-reader' + import { hashProfileStateJson, importProfileStateJson } from './profile-state-documents' import { ProfileStateSqliteAuthority } from './profile-state-sqlite-authority' import { createProfileStateStore } from './profile-state-store-factory' @@ -114,28 +114,6 @@ describe('profile state startup snapshot handoff', () => { }) }) - it.each([false, true])('reads established storage once with retained JSON=%s', (keepJson) => { - const paths = createEstablishedProfile(keepJson) - const open = vi.spyOn(profileStateDatabase, 'openProfileStateDatabaseReadOnly') - const documentRead = vi.spyOn(profileStateDocumentReader, 'readProfileStateDocuments') - const initialRead = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'readInitialState') - const serializedRead = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'readSerializedState') - const acceptedRead = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'readAcceptedState') - - const result = createProfileStateStore({ ...paths }) - stores.push(result.store) - - expect(open).toHaveBeenCalledTimes(1) - expect(documentRead).toHaveBeenCalledTimes(1) - expect(initialRead).toHaveBeenCalledTimes(keepJson ? 0 : 1) - expect(serializedRead).not.toHaveBeenCalled() - expect(acceptedRead).toHaveBeenCalledTimes(keepJson ? 1 : 0) - expect(result.store.getSettings().theme).toBe('dark') - expect(JSON.parse(result.store.prepareProfileStateExport().json)).toMatchObject({ - futureDomain: { keep: true } - }) - }) - it('uses the validated empty snapshot without rereading SQLite or consulting JSON', () => { const paths = createPaths() const opened = profileStateDatabase.openProfileStateDatabase( @@ -167,20 +145,6 @@ describe('profile state startup snapshot handoff', () => { expect(bootstrapped.authority.readSerializedState()).toContain('"dark"') }) - it('consumes a parsed startup snapshot once, including an empty revision', () => { - const paths = createPaths() - const opened = profileStateDatabase.openProfileStateDatabase( - paths.databaseFile, - paths.profileId - ) - opened.db.close() - const authority = new ProfileStateSqliteAuthority(paths.databaseFile, paths.profileId) - authorities.push(authority) - const initial = authority.readInitialState() - expect(initial.takeParsedState?.()).toBeUndefined() - expect(() => initial.takeParsedState?.()).toThrow('already been consumed') - }) - it.each([false, true])( 'fences a writer between bootstrap and Store construction with retained JSON=%s', (keepJson) => { @@ -284,26 +248,4 @@ describe('profile state startup snapshot handoff', () => { expect(again.getSettings().opencodeSessionCookie).toBe('startup-secret') expect(again.getSettings().theme).toBe('light') }) - - it('rejects initial state without its authority or alongside migration input', () => { - const paths = createPaths() - const authority = new ProfileStateSqliteAuthority(paths.databaseFile, paths.profileId) - const otherAuthority = new ProfileStateSqliteAuthority(paths.databaseFile, paths.profileId) - const initialAuthorityState = { authority, serializedState: '{}' } - - expect(() => new Store({ dataFile: paths.dataFile, initialAuthorityState })).toThrow( - 'must belong to its profile-state authority' - ) - expect( - () => new Store({ profileStateAuthority: otherAuthority, initialAuthorityState }) - ).toThrow('must belong to its profile-state authority') - expect( - () => - new Store({ - profileStateAuthority: authority, - initialAuthorityState, - serializedState: '{}' - }) - ).toThrow('cannot use both a profile-state authority and serialized state') - }) }) diff --git a/src/main/persistence/profile-state/profile-state-write-transaction.test.ts b/src/main/persistence/profile-state/profile-state-write-transaction.test.ts index 9525cd78810..a8bdc62128a 100644 --- a/src/main/persistence/profile-state/profile-state-write-transaction.test.ts +++ b/src/main/persistence/profile-state/profile-state-write-transaction.test.ts @@ -68,25 +68,6 @@ describe('profile state write transaction ownership', () => { } }) - it('keeps any other failed commit indeterminate even after SQLite rolled back', () => { - const db = new Database(':memory:') - db.exec('CREATE TABLE writes (id INTEGER)') - // Failed fsync can leave an already-written commit frame. - const ioerr = Object.assign(new Error('disk I/O error'), { - code: 'ERR_SQLITE_ERROR', - errcode: 1034 - }) - const restore = failCommitAfterAutoRollback(db, ioerr) - try { - expect(() => - withProfileStateWriteTransaction(db, () => db.exec('INSERT INTO writes VALUES (1)')) - ).toThrow(ProfileStateIndeterminateWriteError) - } finally { - restore() - db.close() - } - }) - it('rolls back a failed deferred commit and leaves the connection usable', () => { const db = new Database(':memory:') try { diff --git a/src/main/persistence/profile-state/profile-state-writer-close.test.ts b/src/main/persistence/profile-state/profile-state-writer-close.test.ts index b50d039df0b..d6826b8a9ce 100644 --- a/src/main/persistence/profile-state/profile-state-writer-close.test.ts +++ b/src/main/persistence/profile-state/profile-state-writer-close.test.ts @@ -106,17 +106,3 @@ it('keeps an unacknowledged close pending, then holds abort until the terminated expect(onFailure).toHaveBeenCalledOnce() expect(vi.getTimerCount()).toBe(0) }) - -it('joins an aborted writer without reporting a close request that was never sent', async () => { - const { client, worker } = await createClient() - const aborting = client.abort() - const closing = client.close() - await waitForPoll() - vi.advanceTimersByTime(WARNING_MS * 10) - expect(await isSettled(closing)).toBe(false) - expect(diagnostics.slow).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - worker.emit('exit', 1) - await aborting - await closing -}) diff --git a/src/main/persistence/profile-state/profile-state-writer-open-error-cause.test.ts b/src/main/persistence/profile-state/profile-state-writer-open-error-cause.test.ts deleted file mode 100644 index 9a695f88ada..00000000000 --- a/src/main/persistence/profile-state/profile-state-writer-open-error-cause.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { expect, it } from 'vitest' -import Database from '../../sqlite/sync-database' -import { - decodeProfileStateWriterError, - encodeProfileStateWriterError -} from './profile-state-writer-errors' -import { ProfileStateDatabaseOpenError } from './profile-state-database-errors' - -function acrossWorker(error: unknown): Error { - return decodeProfileStateWriterError( - JSON.parse(JSON.stringify(encodeProfileStateWriterError(error))) - ) -} - -// Regression #27333: missing causes concealed the failing SQLite call. -it('keeps the SQLite failure behind a database open error across the writer boundary', () => { - const sqliteFailure = Object.assign(new Error('database is locked'), { - code: 'ERR_SQLITE_ERROR', - errcode: 261 - }) - const decoded = acrossWorker( - new ProfileStateDatabaseOpenError( - 'unreadable', - 'Unable to initialize profile state database', - sqliteFailure - ) - ) - - expect(decoded).toBeInstanceOf(ProfileStateDatabaseOpenError) - expect(decoded.cause).toBeInstanceOf(Error) - expect(decoded.cause).toMatchObject({ - code: 'ERR_SQLITE_ERROR', - errcode: 261, - message: 'database is locked' - }) -}) - -it('carries a real SQLite error code from a failed open', () => { - const db = new Database(':memory:') - let failure: unknown - try { - db.exec('SELECT * FROM missing_table') - } catch (error) { - failure = error - } finally { - db.close() - } - const decoded = acrossWorker( - new ProfileStateDatabaseOpenError('unreadable', 'open failed', failure) - ) - - expect(decoded.cause).toMatchObject({ - code: 'ERR_SQLITE_ERROR', - errcode: 1, - message: expect.stringContaining('missing_table') - }) -}) - -it('keeps a cause-less open error cause-less', () => { - const decoded = acrossWorker(new ProfileStateDatabaseOpenError('unreadable', 'gone')) - expect(decoded).toBeInstanceOf(ProfileStateDatabaseOpenError) - expect(decoded.cause).toBeUndefined() -}) diff --git a/src/main/persistence/profile-state/profile-state-writer-protocol-faults.test.ts b/src/main/persistence/profile-state/profile-state-writer-protocol-faults.test.ts index 25a717d0899..6eb5144da74 100644 --- a/src/main/persistence/profile-state/profile-state-writer-protocol-faults.test.ts +++ b/src/main/persistence/profile-state/profile-state-writer-protocol-faults.test.ts @@ -57,37 +57,6 @@ describe('writer protocol refuses uncertain acknowledgements', () => { }) }) - it.each(['undefined', 'null', '0', '2'])( - 'refuses a versioned export with revision %s for an admitted revision of one', - async (exportedRevision) => { - const client = clientFor(`parentPort.postMessage({ - id: request.id, ok: true, revision: 1, exportedRevision: ${exportedRevision} - })`) - await client.ready - await expect(client.writeLatestJsonExport('unused.json')).rejects.toMatchObject({ - code: 'profile-state-writer-protocol', - outcome: 'indeterminate' - }) - } - ) - - it('refuses a revision jump at an unchanged-state fence', async () => { - const client = clientFor('parentPort.postMessage({ id: request.id, ok: true, revision: 2 })') - await client.ready - await expect(client.assertCurrentRevision()).rejects.toMatchObject({ - code: 'profile-state-writer-protocol', - outcome: 'indeterminate' - }) - }) - - it('refuses an initialization acknowledgement for a different revision', async () => { - const client = clientFor('', '{ id: 0, ok: true, revision: 2 }') - await expect(client.ready).rejects.toMatchObject({ - code: 'profile-state-writer-protocol', - outcome: 'known-failure' - }) - }) - it('reports an idle writer exit even without a subsequent save', async () => { const notify = vi.fn() const client = clientFor('', undefined, notify, 'setTimeout(() => process.exit(1), 50)') @@ -99,34 +68,4 @@ describe('writer protocol refuses uncertain acknowledgements', () => { await client.close() expect(notify).toHaveBeenCalledOnce() }) - - it('leaves startup failure reporting to the startup caller', async () => { - const notify = vi.fn() - const client = clientFor('', '{ id: 0, ok: true, revision: 2 }', notify) - await expect(client.ready).rejects.toThrow() - await client.close() - expect(notify).not.toHaveBeenCalled() - }) - - it('does not report saving stopped after a recoverable request failure or clean close', async () => { - const notify = vi.fn() - const client = clientFor( - ` - if (request.command === 'close') { - parentPort.postMessage({ id: request.id, ok: true, revision: 1 }) - parentPort.close() - } else { - parentPort.postMessage({ id: request.id, ok: false, - error: { code: 'SQLITE_BUSY', message: 'busy', outcome: 'known-failure' } }) - } - `, - undefined, - notify - ) - await client.ready - await expect(client.assertCurrentRevision()).rejects.toThrow('busy') - expect(() => client.assertWritable()).not.toThrow() - await client.close() - expect(notify).not.toHaveBeenCalled() - }) }) diff --git a/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts b/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts deleted file mode 100644 index 9f4705abed2..00000000000 --- a/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ProfileStateWriterReopenPolicy } from './profile-state-writer-reopen-policy' - -const spawnFailure = Object.assign(new Error('spawn failed'), { - code: 'profile-state-writer-unavailable' -}) - -describe('ProfileStateWriterReopenPolicy', () => { - beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - afterEach(() => vi.restoreAllMocks()) - - it('retries the first failure at once, then backs off up to a minute', () => { - let now = 0 - const policy = new ProfileStateWriterReopenPolicy(() => now) - expect(policy.recordFailure(spawnFailure)).toEqual({ retryInMs: 0 }) - expect(() => policy.admit()).not.toThrow() - expect(policy.recordFailure(spawnFailure)).toEqual({ retryInMs: 1_000 }) - expect(() => policy.admit()).toThrow('spawn failed') - now = 1_000 - expect(() => policy.admit()).not.toThrow() - for (let failure = 0; failure < 10; failure += 1) { - policy.recordFailure(spawnFailure) - } - now += 59_999 - expect(() => policy.admit()).toThrow('spawn failed') - now += 1 - expect(() => policy.admit()).not.toThrow() - }) - - it('forgets the backoff once a reopen succeeds', () => { - let now = 0 - const policy = new ProfileStateWriterReopenPolicy(() => now) - policy.recordFailure(spawnFailure) - policy.recordFailure(spawnFailure) - policy.recordSuccess() - expect(() => policy.admit()).not.toThrow() - expect(policy.recordFailure(spawnFailure)).toEqual({ retryInMs: 0 }) - expect(() => policy.admit()).not.toThrow() - }) - - it('lets one attempt through a backoff for a final flush', () => { - const policy = new ProfileStateWriterReopenPolicy(() => 0) - policy.recordFailure(spawnFailure) - policy.recordFailure(spawnFailure) - policy.bypassBackoffOnce() - expect(() => policy.admit()).not.toThrow() - expect(() => policy.admit()).toThrow('spawn failed') - }) - - it('drops a pending bypass once a reopen succeeds', () => { - let now = 0 - const policy = new ProfileStateWriterReopenPolicy(() => now) - policy.recordFailure(spawnFailure) - policy.bypassBackoffOnce() - policy.recordSuccess() - policy.recordFailure(spawnFailure) - policy.recordFailure(spawnFailure) - expect(() => policy.admit()).toThrow('spawn failed') - now = 1_000 - expect(() => policy.admit()).not.toThrow() - }) -}) diff --git a/src/main/persistence/profile-state/profile-state-writer-worker.test.ts b/src/main/persistence/profile-state/profile-state-writer-worker.test.ts index 494427a014a..265e90fb320 100644 --- a/src/main/persistence/profile-state/profile-state-writer-worker.test.ts +++ b/src/main/persistence/profile-state/profile-state-writer-worker.test.ts @@ -9,8 +9,7 @@ import { openProfileStateDatabase } from './profile-state-database' import { readProfileStateSnapshot } from './profile-state-documents' import { ProfileStateWriteWorkerClient, - profileStateWriterFailureOutcome, - resolveProfileStateWriterWorkerPath + profileStateWriterFailureOutcome } from './profile-state-writer-worker-client' let bundleRoot: string @@ -139,27 +138,6 @@ describe('persistent profile state write worker', () => { expect(existsSync(join(f.root, 'missing.db'))).toBe(false) }) - it('permanently retires bootstrap authority and refuses subsequent calls', () => { - const f = fixture() - for (const call of [ - () => f.authority.readInitialState(), - () => f.authority.readAcceptedState('{}'), - () => f.authority.readSerializedState(), - () => f.authority.writeSerializedDomains([]), - () => f.authority.writeCompleteSerializedDomains([]), - () => f.authority.writeSerializedAutomationRuns([], []), - () => f.authority.writeSerializedState(Buffer.from('{}')), - () => f.authority.writeJsonExport(join(f.root, 'export.json')), - () => f.authority.scheduleBackup(), - () => f.authority.assertCurrentRevision(), - () => f.authority.initializeFromRevision(1), - () => f.authority.retireForWorker(), - () => f.authority.close() - ]) { - expect(call).toThrow(/retired/) - } - }) - it('preserves known validation failures and rejects a peer at the no-op fence', async () => { const f = fixture() const client = clientFor(f.initialization) @@ -349,28 +327,4 @@ describe('persistent profile state write worker', () => { await client.close() expect(readState(f.path, f.profileId)).toEqual({ settings: { theme: 'dark' } }) }) - - it('aborts an active request without treating the pending write as rolled back', async () => { - const f = fixture() - const hung = script( - f.root, - ` - const { parentPort } = require('node:worker_threads') - parentPort.postMessage({ id: 0, ok: true, revision: 1 }) - parentPort.on('message', () => {}) - ` - ) - const client = clientFor(f.initialization, hung) - await client.ready - const write = client.writeSerializedDomains([{ domain: 'settings', payload: '{}' }]) - const failed = expect(write).rejects.toMatchObject({ outcome: 'indeterminate' }) - await client.abort() - await failed - await client.close() - }) - - it('resolves flat and shared-chunk entry layouts', () => { - expect(resolveProfileStateWriterWorkerPath(bundleRoot)).toBe(workerPath) - expect(resolveProfileStateWriterWorkerPath(join(bundleRoot, 'chunks'))).toBe(workerPath) - }) }) diff --git a/src/main/persistence/scheduling-automations/automation-managed-host-boundary.test.ts b/src/main/persistence/scheduling-automations/automation-managed-host-boundary.test.ts deleted file mode 100644 index 226ca6db029..00000000000 --- a/src/main/persistence/scheduling-automations/automation-managed-host-boundary.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AutomationCreateInput } from '../../../shared/automations-types' -import { getDefaultPersistedState } from '../../../shared/constants' -import { createAutomation } from './automation-definition-operations' - -// Desktop rows on a managed SSH host never run; the desktop store refuses new ones for any caller. -describe('desktop automation create on a managed SSH host', () => { - it('refuses the write and keeps the store unchanged', () => { - const state = getDefaultPersistedState('/home/me') - state.sshTargets = [ - { - id: 'box', - label: 'Build box', - host: 'box', - port: 22, - username: 'me', - generation: 3, - orcadFence: { environmentId: 'env-1' } - } - ] - state.repos = [ - { - id: 'repo-1', - path: '/srv/repo', - displayName: 'Repo', - badgeColor: '#000', - addedAt: 1, - connectionId: 'box' - } - ] - const input: AutomationCreateInput = { - name: 'Nightly', - prompt: 'Run checks', - agentId: 'claude', - projectId: 'repo-1', - workspaceMode: 'new_per_run', - rrule: 'FREQ=DAILY', - dtstart: 1, - timezone: 'UTC' - } - const operations = { - state, - storageAuthority: 'desktop' as const, - flush: () => undefined, - recordCreated: () => undefined - } - - expect(() => createAutomation(operations, input)).toThrow() - expect(state.automations ?? []).toEqual([]) - }) -}) diff --git a/src/main/persistence/terminal-topology/pane-last-grid.test.ts b/src/main/persistence/terminal-topology/pane-last-grid.test.ts index c33f4aa1b8b..ade8d50f6ea 100644 --- a/src/main/persistence/terminal-topology/pane-last-grid.test.ts +++ b/src/main/persistence/terminal-topology/pane-last-grid.test.ts @@ -89,38 +89,6 @@ describe("a pane's last grid (layout-owner build)", () => { expect(layouts[movedTo!]?.lastGridsByLeafId).toEqual({ [LEAF_B]: { cols: 91, rows: 33 } }) }) - it("writes only the pane's own tab record", async () => { - const { store } = await storeWithSplit() - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-other' }) - const before = store.getWorkspaceSession() - await apply(store, { - ...on, - type: 'setPaneGrid', - tabId: 'tab-1', - leafId: LEAF_B, - grid: { cols: 91, rows: 33 } - }) - const after = store.getWorkspaceSession() - - expect(after.terminalLayoutsByTabId['tab-other']).toBe( - before.terminalLayoutsByTabId['tab-other'] - ) - expect(after.unifiedTabs).toBe(before.unifiedTabs) - expect(after.tabsByWorktree).toBe(before.tabsByWorktree) - }) - - it('is refused for a pane the tab does not hold', async () => { - const { store } = await storeWithSplit() - const result = await store.applyLayoutCommand({ - ...on, - type: 'setPaneGrid', - tabId: 'tab-1', - leafId: '33333333-3333-4333-8333-333333333333', - grid: { cols: 80, rows: 24 } - }) - expect(result).toMatchObject({ ok: false }) - }) - it("keeps a grid resized just before quit, written by the quit's flush", async () => { const { store, directory } = await storeWithSplit() await store.persistPtyBinding({ diff --git a/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts b/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts index 59aa4b1af93..8b3d420c0b6 100644 --- a/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts +++ b/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts @@ -2,9 +2,7 @@ import { closeTestStores, createStore, registerWorkspaceRepos, - testState, - workspaceRepos, - writeDataFile + testState } from '../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' @@ -65,58 +63,6 @@ describe('Store', () => { await closeTestStores() rmSync(testState.dir, { recursive: true, force: true }) }) - it('remaps legacy SSH lease leaf ids by PTY when the layout is already normalized', async () => { - writeDataFile({ - schemaVersion: 1, - repos: workspaceRepos('wt1'), - worktreeMeta: {}, - settings: {}, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: { - activeRepoId: 'r1', - activeWorktreeId: 'wt1', - activeTabId: 'tab1', - tabsByWorktree: { - wt1: [ - { - id: 'tab1', - worktreeId: 'wt1', - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1, - ptyId: 'remote-pty' - } - ] - }, - terminalLayoutsByTabId: { - tab1: { - root: { type: 'leaf', leafId: TEST_LEAF_1 }, - activeLeafId: TEST_LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [TEST_LEAF_1]: 'remote-pty' } - } - } - }, - sshRemotePtyLeases: [ - { - targetId: 'ssh-1', - ptyId: 'remote-pty', - worktreeId: 'wt1', - tabId: 'tab1', - leafId: 'pane:1', - state: 'detached', - createdAt: 1, - updatedAt: 1 - } - ] - }) - - const store = await createStore() - expect(store.getSshRemotePtyLeases('ssh-1')[0].leafId).toBe(TEST_LEAF_1) - }) it('normalizes stale legacy session writes to prior UUID leaves before preserving bindings', async () => { const store = await createStore() @@ -183,52 +129,6 @@ describe('Store', () => { expect(session.tabsByWorktree.wt1[0].ptyId).toBe('remote-pty') }) - it('promotes an empty tab layout to a durable UUID root when persisting the first PTY binding', async () => { - const store = await createStore() - store.setWorkspaceSession({ - activeRepoId: 'r1', - activeWorktreeId: 'wt1', - activeTabId: 'tab1', - tabsByWorktree: { - wt1: [ - { - id: 'tab1', - worktreeId: 'wt1', - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1, - ptyId: null - } - ] - }, - terminalLayoutsByTabId: { - tab1: { - root: null, - activeLeafId: null, - expandedLeafId: null - } - } - }) - - await store.persistPtyBinding({ - worktreeId: 'wt1', - tabId: 'tab1', - leafId: TEST_LEAF_1, - ptyId: 'daemon-pty' - }) - - const session = store.getWorkspaceSession() - expect(session.tabsByWorktree.wt1[0].ptyId).toBe('daemon-pty') - expect(session.terminalLayoutsByTabId.tab1).toEqual({ - root: { type: 'leaf', leafId: TEST_LEAF_1 }, - activeLeafId: TEST_LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [TEST_LEAF_1]: 'daemon-pty' } - }) - }) - it('admits a fresh host spawn after retirement while rejecting an older renderer topology', async () => { const store = await createStore() store.setWorkspaceSession({ diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts b/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts index 320abc07536..d80eddd87fa 100644 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts +++ b/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts @@ -110,15 +110,4 @@ describe("pinning existing hosts' orca CLI control switch on upgrade", () => { expect(reopened.getSshTarget(added.id)?.allowRemoteCliControl).toBe(true) expect(isRemoteCliControlAllowed(reopened.getSshTarget(added.id))).toBe(true) }) - - it('does not re-run after a downgrade wrote an absent switch alongside the marker', async () => { - // Older builds preserve unknown migration markers when saving settings. - writeProfile([host('added-by-older-build')], { - sshRemoteCliControlExistingHostsMigrated: true - }) - - const store = await createStore() - - expect(store.getSshTarget('added-by-older-build')).not.toHaveProperty('allowRemoteCliControl') - }) }) diff --git a/src/main/persistence/terminal-topology/persistence-terminal-option-key-migration.test.ts b/src/main/persistence/terminal-topology/persistence-terminal-option-key-migration.test.ts deleted file mode 100644 index 6d23634a682..00000000000 --- a/src/main/persistence/terminal-topology/persistence-terminal-option-key-migration.test.ts +++ /dev/null @@ -1,327 +0,0 @@ -import { - closeTestStores, - testState, - createStore, - withPlatform, - writeDataFile, - readDataFile -} from '../persistence-test-harness' -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { rmSync, mkdtempSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import type { PersistedState } from '../../../shared/persisted-state-types' - -const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ - loadUserSshConfigMock: vi.fn(), - sshConfigHostsToTargetsMock: vi.fn() -})) - -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: loadUserSshConfigMock, - sshConfigHostsToTargets: sshConfigHostsToTargetsMock -})) -const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({ - trackMock: vi.fn(), - getCohortAtEmitMock: vi.fn() -})) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.dir - }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => { - const decoded = ciphertext.toString('utf-8') - if (!decoded.startsWith('encrypted:')) { - throw new Error('invalid ciphertext') - } - return decoded.slice('encrypted:'.length) - } - } -})) - -vi.mock('../../telemetry/client', () => ({ - track: trackMock -})) - -vi.mock('../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: getCohortAtEmitMock -})) - -describe('Store', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - trackMock.mockReset() - getCohortAtEmitMock.mockReset() - getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) - }) - - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('migrates legacy "true" terminalMacOptionAsAlt to "auto" on first load', async () => { - // The old true default cannot reveal user intent; migrate it once to auto for non-US layouts. - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalMacOptionAsAlt: 'true' }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalMacOptionAsAlt).toBe('auto') - expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true) - }) - - it('migrates inherited right-click paste to each platform default once', async () => { - for (const [platform, expected] of [ - ['win32', true], - ['darwin', false], - ['linux', false] - ] as const) { - await withPlatform(platform, async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalRightClickToPaste: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalRightClickToPaste).toBe(expected) - expect(store.getSettings().terminalRightClickToPasteDefaultedForPlatform).toBe(true) - }) - } - }) - - it('preserves an explicit Windows right-click paste opt-out during migration', async () => { - await withPlatform('win32', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalRightClickToPaste: false }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalRightClickToPaste).toBe(false) - expect(store.getSettings().terminalRightClickToPasteDefaultedForPlatform).toBe(true) - }) - }) - - it('preserves right-click paste choices after the platform migration', async () => { - await withPlatform('darwin', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { - terminalRightClickToPaste: true, - terminalRightClickToPasteDefaultedForPlatform: true - }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalRightClickToPaste).toBe(true) - }) - }) - - it('migrates inherited terminal bar cursor defaults to block on first load', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalCursorStyle: 'bar' }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalCursorStyle).toBe('block') - expect(store.getSettings().terminalCursorStyleDefaultedToBlock).toBe(true) - }) - - it('preserves terminal cursor choices after the block-default migration', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalCursorStyle: 'bar', terminalCursorStyleDefaultedToBlock: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalCursorStyle).toBe('bar') - expect(store.getSettings().terminalCursorStyleDefaultedToBlock).toBe(true) - }) - - it('replaces an invalid persisted terminal cursor choice after migration', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalCursorStyle: 'beam', terminalCursorStyleDefaultedToBlock: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalCursorStyle).toBe('block') - store.flush() - expect((readDataFile() as PersistedState).settings.terminalCursorStyle).toBe('block') - }) - - it('preserves explicit "false" terminalMacOptionAsAlt through migration', async () => { - // Legacy false differed from the default and therefore proves an explicit choice. - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalMacOptionAsAlt: 'false' }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalMacOptionAsAlt).toBe('false') - expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true) - }) - - it.each(['left', 'right'] as const)( - 'preserves explicit "%s" terminalMacOptionAsAlt through migration', - async (side) => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalMacOptionAsAlt: side }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalMacOptionAsAlt).toBe(side) - expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true) - } - ) - - it('respects already-migrated settings with explicit "true"', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { terminalMacOptionAsAlt: 'true', terminalMacOptionAsAltMigrated: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalMacOptionAsAlt).toBe('true') - expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true) - }) - - it('fresh install defaults terminalMacOptionAsAlt to "auto" and marks migrated', async () => { - const store = await createStore() - expect(store.getSettings().terminalMacOptionAsAlt).toBe('auto') - // No migration ran on a new profile; a later legacy true value must still migrate. - expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(false) - }) - - it('missing terminalMacOptionAsAlt in persisted file defaults to "auto" and flags migrated', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - const store = await createStore() - expect(store.getSettings().terminalMacOptionAsAlt).toBe('auto') - expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true) - }) - - it('migrates the legacy experimentalSidekick setting to experimentalPet', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { experimentalSidekick: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - - expect(store.getSettings().experimentalPet).toBe(true) - }) - - it('migrates the legacy experimental compact worktree cards setting', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { experimentalCompactWorktreeCards: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - - expect(store.getSettings().compactWorktreeCards).toBe(true) - expect(store.getSettings().experimentalCompactWorktreeCards).toBeUndefined() - }) - - it('defaults legacy experimentalActivity profiles off once', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { experimentalActivity: true }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - - expect(store.getSettings().experimentalActivity).toBe(false) - expect(store.getSettings().experimentalActivityDefaultedOffForAllUsers).toBe(true) - }) - - it('preserves experimentalActivity after the default-off migration has run', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: { - experimentalActivity: true, - experimentalActivityDefaultedOffForAllUsers: true - }, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - - expect(store.getSettings().experimentalActivity).toBe(true) - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts b/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts index 35bf1edc939..55a0218ed39 100644 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts +++ b/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts @@ -65,17 +65,3 @@ it('still refuses and rolls back a rename whose profile write fails', async () = .tabsByWorktree[pane.worktreeId]?.find((row) => row.id === pane.tabId) expect(tab?.customTitle ?? null).toBeNull() }) - -it('refuses a close once profile writes are frozen, and changes nothing', async () => { - const { store, liveTabIds } = await openWithTab() - await store.freezeWritesAsync() - - await expect( - store.applyLayoutCommand({ - type: 'closeTabs', - workspace: pane.worktreeId, - tabIds: [pane.tabId] - }) - ).rejects.toThrow('finalized') - expect(liveTabIds()).toContain(pane.tabId) -}) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure.test.ts b/src/main/persistence/terminal-topology/terminal-close-write-failure.test.ts deleted file mode 100644 index 5dfaaff8cf9..00000000000 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' -import { keptOnWriteFailure } from './terminal-close-write-failure' - -function durableRun(write: () => void) { - return async (mutate: () => DurableProfileStateMutation): Promise => { - const mutation = mutate() - try { - write() - } catch (error) { - mutation.rollback?.() - throw error - } - return mutation.value - } -} - -describe('a terminal close whose profile write fails', () => { - it('stays closed, answers as applied, and is written again later', async () => { - let tabs = ['tab-1', 'tab-2'] - const writeLater = vi.fn() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const reply = await keptOnWriteFailure( - durableRun(() => { - throw new Error('ENOSPC') - }), - () => { - const before = tabs - tabs = tabs.filter((tab) => tab !== 'tab-2') - return { value: { ok: true as const }, rollback: () => (tabs = before) } - }, - writeLater - ) - expect(reply).toEqual({ ok: true }) - expect(tabs).toEqual(['tab-1']) - expect(writeLater).toHaveBeenCalledTimes(1) - warn.mockRestore() - }) - - it('refuses a close the profile froze before it changed anything', async () => { - const writeLater = vi.fn() - const mutate = vi.fn() - await expect( - keptOnWriteFailure( - async () => { - throw new Error('Cannot mutate finalized profile persistence') - }, - mutate, - writeLater - ) - ).rejects.toThrow('finalized') - expect(mutate).not.toHaveBeenCalled() - expect(writeLater).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts b/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts index 13718ef5cda..133cb702ab2 100644 --- a/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts +++ b/src/main/persistence/terminal-topology/terminal-late-bind-layout-rules.test.ts @@ -11,7 +11,7 @@ import { FIXTURE_GIT_WORKTREE_ID, openTopologyStore } from './terminal-topology-profile-fixture' -import { WindowSession, withoutLeaf } from './terminal-topology-window-session-fixture' +import { WindowSession } from './terminal-topology-window-session-fixture' import { checkWorkspaceLayoutRules } from '../../../shared/workspace-layout/workspace-layout-rules' // Retire this rollback coverage with switch-off code. @@ -96,37 +96,4 @@ describe('a terminal spawn that lands after its pane changed', () => { expect(store.getWorkspaceSession().tabsByWorktree[WT] ?? []).toEqual([]) await store.freezeWritesAsync() }) - - // Known switch-off gap: late spawn grafts a moved pane back; the renderer blocks in-flight drags. - it.fails('keeps a dragged-out pane in its new tab when its spawn lands late', async () => { - const { store, window } = await openWithSplit() - await expect( - store.moveTerminalLeafToNewTab({ - worktreeId: WT, - sourceTabId: 'tab-a', - targetTabId: 'tab-b', - leafId: TEST_LEAF_2, - ptyId: 'pty-2' - }) - ).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' }) - const source = window.session.terminalLayoutsByTabId['tab-a']! - window.setLayout('tab-a', withoutLeaf(source.root!, TEST_LEAF_2)!, { [TEST_LEAF_1]: 'pty-1' }) - window.addTab(WT, 'tab-b', TEST_LEAF_2) - window.bind('tab-b', TEST_LEAF_2, 'pty-2') - store.setWorkspaceSession(window.snapshot()) - expect(violations(store)).toEqual([]) - - // Commit the spawn that began against the old source tab. - await store.persistPtyBinding({ - worktreeId: WT, - tabId: 'tab-a', - leafId: TEST_LEAF_2, - ptyId: 'pty-2b' - }) - try { - expect(violations(store)).toEqual([]) - } finally { - await store.freezeWritesAsync() - } - }) }) diff --git a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts index dc68ab7c110..b64d12311b9 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts @@ -9,7 +9,6 @@ import type { Store } from '../loading-store/store' import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, - FIXTURE_FOLDER_WORKTREE_ID, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore @@ -102,41 +101,6 @@ describe('Store.applyLayoutCommand (layout.apply)', () => { expect(revision(store)).toBeGreaterThan(revisionBefore) }) - it('prunes the partition’s expired close records when it records one, as today', async () => { - const { store } = await storeWithOneTab() - store.setWorkspaceSession({ - ...store.getWorkspaceSession(), - closedTerminalTabTombstonesByTabId: { - 'tab-old': { worktreeId: 'repo-other::/x', closedAt: 1, reason: 'user' } - } - }) - - await store.applyLayoutCommand({ - type: 'closeTabs', - workspace: WORKTREE, - tabIds: [TAB], - force: true, - recordClose: 'cleanup' - }) - - expect( - Object.keys(store.getWorkspaceSession().closedTerminalTabTombstonesByTabId ?? {}) - ).toEqual([TAB]) - }) - - it('writes a folder workspace’s split', async () => { - const { store } = await storeWithOneTab(undefined, FIXTURE_FOLDER_WORKTREE_ID) - - const reply = await store.applyLayoutCommand({ - ...split, - workspace: FIXTURE_FOLDER_WORKTREE_ID - }) - - expect(reply.ok).toBe(true) - const root = store.getWorkspaceSession().terminalLayoutsByTabId[TAB]?.root - expect(leafIds(root)).toEqual([LEAF, reply.ok ? reply.result.leafId : undefined]) - }) - it('keeps records the split did not touch exactly as stored', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-layout-apply-')) directories.push(directory) @@ -160,16 +124,6 @@ describe('Store.applyLayoutCommand (layout.apply)', () => { expect(written.unifiedTabs).toEqual(stored.unifiedTabs) }) - it('refuses a pane main does not hold and writes nothing', async () => { - const { store } = await storeWithOneTab() - const before = store.getWorkspaceSession() - - const reply = await store.applyLayoutCommand({ ...split, leafId: 'missing-leaf' }) - - expect(reply).toEqual({ ok: false, code: 'pane_not_found' }) - expect(store.getWorkspaceSession()).toEqual(before) - }) - it('writes an SSH workspace’s split into that host’s partition only', async () => { const { store } = await storeWithOneTab('ssh:target-1') const local = store.getWorkspaceSession() diff --git a/src/main/persistence/terminal-topology/terminal-layout-create.test.ts b/src/main/persistence/terminal-topology/terminal-layout-create.test.ts index fb2525c828c..3f5835f0fb1 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-create.test.ts +++ b/src/main/persistence/terminal-topology/terminal-layout-create.test.ts @@ -102,38 +102,6 @@ describe('Store.applyLayoutCommand: a window’s terminal tab create', () => { expect(leafIds(root)).toEqual([NEW_LEAF, reply.ok ? reply.result.leafId : undefined]) }) - it('treats the same create again as done, and writes nothing', async () => { - const { store } = await openStore(withOneTab) - await store.applyLayoutCommand(create) - const before = store.getWorkspaceSession() - - const reply = await store.applyLayoutCommand({ ...create, groupId: 'another-group' }) - - expect(reply).toEqual({ - ok: true, - result: { tabId: NEW_TAB, leafId: NEW_LEAF, paneKey: `${NEW_TAB}:${NEW_LEAF}` } - }) - expect(store.getWorkspaceSession()).toBe(before) - }) - - it('refuses an id another tab holds, in this workspace or another, and writes nothing', async () => { - const { store } = await openStore((window) => { - withOneTab(window) - window.addTab(FIXTURE_FOLDER_WORKTREE_ID, 'folder-tab', NEW_LEAF) - }) - const before = store.getWorkspaceSession() - - expect(await store.applyLayoutCommand({ ...create, tabId: TAB })).toEqual({ - ok: false, - code: 'tab_exists' - }) - expect(await store.applyLayoutCommand({ ...create, tabId: 'folder-tab' })).toEqual({ - ok: false, - code: 'tab_exists' - }) - expect(store.getWorkspaceSession()).toBe(before) - }) - it('keeps records the create did not touch exactly as stored', async () => { const { store } = await openStore((window) => { withOneTab(window) @@ -153,24 +121,6 @@ describe('Store.applyLayoutCommand: a window’s terminal tab create', () => { expect(written.unifiedTabs?.[WORKTREE]?.[0]).toEqual(stored.unifiedTabs?.[WORKTREE]?.[0]) }) - it('makes a workspace’s first tab on activation only while main’s copy holds no tab', async () => { - const { store } = await openStore(withOneTab) - const before = store.getWorkspaceSession() - const initial = { ...create, groupId: undefined, initial: 'activation' as const } - - expect(await store.applyLayoutCommand(initial)).toEqual({ ok: true, result: {} }) - expect(store.getWorkspaceSession()).toBe(before) - - const empty = await store.applyLayoutCommand({ - ...initial, - workspace: FIXTURE_FOLDER_WORKTREE_ID - }) - expect(empty.ok && empty.result.tabId).toBe(NEW_TAB) - expect( - store.getWorkspaceSession().tabsByWorktree[FIXTURE_FOLDER_WORKTREE_ID]?.map((tab) => tab.id) - ).toEqual([NEW_TAB]) - }) - it('writes an SSH workspace’s tab into that host’s partition only', async () => { const { store } = await openStore(withOneTab, 'ssh:target-1') const local = store.getWorkspaceSession() @@ -211,17 +161,4 @@ describe('Store.applyLayoutCommand: a workspace’s default tabs', () => { ]) expect(session.defaultTerminalTabsAppliedByWorktreeId?.[FIXTURE_FOLDER_WORKTREE_ID]).toBe(true) }) - - it('refuses the whole command when another tab holds one of its ids, and writes nothing', async () => { - const { store } = await openStore(withOneTab) - const before = store.getWorkspaceSession() - - const reply = await store.applyLayoutCommand({ - ...defaults, - tabs: [defaults.tabs[0]!, { ...defaults.tabs[1]!, tabId: TAB }] - }) - - expect(reply).toEqual({ ok: false, code: 'tab_exists' }) - expect(store.getWorkspaceSession()).toBe(before) - }) }) diff --git a/src/main/persistence/terminal-topology/terminal-layout-default-tabs-applied.test.ts b/src/main/persistence/terminal-topology/terminal-layout-default-tabs-applied.test.ts deleted file mode 100644 index 7fa2708af82..00000000000 --- a/src/main/persistence/terminal-topology/terminal-layout-default-tabs-applied.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - emptyTerminalSessionProfile, - FIXTURE_FOLDER_WORKTREE_ID, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from './terminal-topology-profile-fixture' - -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const directories: string[] = [] - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -async function emptyStore() { - const directory = mkdtempSync(join(tmpdir(), 'orca-layout-default-tabs-')) - directories.push(directory) - return { store: await openTopologyStore(directory, emptyTerminalSessionProfile()), directory } -} - -describe('Store.applyLayoutCommand setDefaultTabsApplied (layout.apply)', () => { - it.each([ - ['a git worktree', FIXTURE_GIT_WORKTREE_ID], - ['a folder workspace', FIXTURE_FOLDER_WORKTREE_ID] - ])('records %s’s mark durably without making it a workspace', async (_kind, workspace) => { - const { store, directory } = await emptyStore() - - const reply = await store.applyLayoutCommand({ type: 'setDefaultTabsApplied', workspace }) - - expect(reply).toEqual({ ok: true, result: {} }) - const session = (await reopenTopologyStore(store, directory)).getWorkspaceSession() - expect(session.defaultTerminalTabsAppliedByWorktreeId).toEqual({ [workspace]: true }) - expect(session.tabsByWorktree[workspace]).toBeUndefined() - expect(session.unifiedTabs?.[workspace]).toBeUndefined() - expect(session.tabGroups?.[workspace]).toBeUndefined() - }) - - it('a repeat changes nothing', async () => { - const { store, directory } = await emptyStore() - const workspace = FIXTURE_GIT_WORKTREE_ID - await store.applyLayoutCommand({ type: 'setDefaultTabsApplied', workspace }) - const reopened = await reopenTopologyStore(store, directory) - const before = reopened.getWorkspaceSession() - - const reply = await reopened.applyLayoutCommand({ type: 'setDefaultTabsApplied', workspace }) - - expect(reply).toEqual({ ok: true, result: {} }) - expect(reopened.getWorkspaceSession()).toEqual(before) - const session = (await reopenTopologyStore(reopened, directory)).getWorkspaceSession() - expect(session.defaultTerminalTabsAppliedByWorktreeId).toEqual({ [workspace]: true }) - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts b/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts index bdbacb168ed..3e7c628392b 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts +++ b/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts @@ -2,10 +2,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { toSshExecutionHostId } from '../../../shared/execution-host' -import { _resetTracerForTests, setActiveSink } from '../../observability/tracer' +import { _resetTracerForTests } from '../../observability/tracer' import { makeRepo } from '../persistence-test-harness' -import { makeTerminalTab } from '../persistence-session-fixtures' -import { planTerminalLeafMove } from './terminal-leaf-move' + import { closeMoveTestStores, FROM, @@ -119,133 +118,6 @@ describe('moving a pane to a new tab', () => { expect.objectContaining({ ptyId: 'pty-agent', tabId: TARGET, leafId: MOVED }) ]) }) - - it('reports a leaf main never held instead of inventing one', async () => { - const store = openStore(newDataFile()) - await expect( - store.moveTerminalLeafToNewTab({ ...moveRequest, ptyId: 'pty-agent' }) - ).resolves.toEqual({ status: 'not_held' }) - expect(store.getWorkspaceSession().tabsByWorktree[WT]).toBeUndefined() - }) - - it('refuses a move that names another terminal or an existing tab', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - await expect( - store.moveTerminalLeafToNewTab({ ...moveRequest, ptyId: 'pty-other' }) - ).resolves.toEqual({ status: 'refused', reason: 'pty_mismatch' }) - await expect( - store.moveTerminalLeafToNewTab({ ...moveRequest, targetTabId: SOURCE, ptyId: 'pty-agent' }) - ).resolves.toEqual({ status: 'refused', reason: 'target_tab_exists' }) - expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED)).toEqual([SOURCE]) - }) - - it('moves a leaf that a stray layout of a removed tab still names', () => { - const planned = planTerminalLeafMove( - [ - { - hostId: 'local', - session: { - activeRepoId: 'repo-1', - activeWorktreeId: WT, - activeTabId: SOURCE, - tabsByWorktree: { [WT]: [makeTerminalTab({ id: SOURCE, worktreeId: WT })] }, - terminalLayoutsByTabId: { - [SOURCE]: { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEFT }, - second: { type: 'leaf', leafId: MOVED } - }, - activeLeafId: LEFT, - expandedLeafId: null - }, - 'tab-removed': { - root: { type: 'leaf', leafId: MOVED }, - activeLeafId: MOVED, - expandedLeafId: null - } - } - } - } - ], - { ...moveRequest, ptyId: 'pty-agent' } - ) - expect(planned.result).toEqual({ status: 'moved', ptyId: 'pty-agent' }) - }) - - it('records a persistence.terminal-topology span without pane keys or PTY ids', async () => { - const records: { - name: string - attributes: Record - traceId: string - spanId: string - parentSpanId?: string - startTimeUnixNano: string - endTimeUnixNano: string - durationMs: number - }[] = [] - setActiveSink({ - push: (record) => { - records.push(JSON.parse(JSON.stringify(record))) - }, - flush: () => {}, - close: () => {} - }) - try { - const store = openStore(newDataFile()) - await seedSplitSource(store) - records.length = 0 - const request = { ...moveRequest, ptyId: 'pty-agent' } - await store.moveTerminalLeafToNewTab(request) - await store.moveTerminalLeafToNewTab(request) - await store.moveTerminalLeafToNewTab({ ...request, targetTabId: 'tab-other' }) - - const spans = records.filter((record) => record.name === 'persistence.terminal-topology') - expect(spans.map((span) => span.attributes)).toEqual([ - { kind: 'persistence', 'topology.kind': 'move_leaf', 'topology.outcome': 'committed' }, - { - kind: 'persistence', - 'topology.kind': 'move_leaf', - 'topology.outcome': 'refused', - 'topology.refusal': 'target_tab_exists' - }, - { - kind: 'persistence', - 'topology.kind': 'move_leaf', - 'topology.outcome': 'refused', - 'topology.refusal': 'leaf_in_other_tab' - } - ]) - const transportFields = new Set([ - 'traceId', - 'spanId', - 'parentSpanId', - 'startTimeUnixNano', - 'endTimeUnixNano', - 'durationMs' - ]) - for (const span of spans) { - expect(span.traceId).toMatch(/^[a-f0-9]{32}$/) - expect(span.spanId).toMatch(/^[a-f0-9]{16}$/) - if (span.parentSpanId !== undefined) { - expect(span.parentSpanId).toMatch(/^[a-f0-9]{16}$/) - } - expect(span.startTimeUnixNano).toMatch(/^\d+$/) - expect(span.endTimeUnixNano).toMatch(/^\d+$/) - expect(Number.isFinite(span.durationMs)).toBe(true) - expect(span.durationMs).toBeGreaterThanOrEqual(0) - } - // Random IDs and clocks can coincidentally contain the leaf's numeric prefix. - const payloads = spans.map((span) => - Object.fromEntries(Object.entries(span).filter(([key]) => !transportFields.has(key))) - ) - expect(JSON.stringify(payloads)).not.toMatch(/pty-|tab-source|tab-target|2222/) - } finally { - _resetTracerForTests() - } - }) }) // Relay reattach can duplicate SSH panes into local; all holders must move or future binds refuse. @@ -337,34 +209,6 @@ describe('moving an SSH pane held by both partitions', () => { expect(store.getWorkspaceSession(hostId).terminalPtyIncarnationsByPaneKey?.[TO]).toBe('inc-2') expect(store.getWorkspaceSession().terminalPtyIncarnationsByPaneKey?.[TO]).toBeUndefined() }) - - it('refuses a move while another tab already holds the leaf', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - const session = store.getWorkspaceSession() - store.setWorkspaceSession({ - ...session, - tabsByWorktree: { - ...session.tabsByWorktree, - [WT]: [ - ...(session.tabsByWorktree[WT] ?? []), - { ...(session.tabsByWorktree[WT] ?? [])[0]!, id: 'tab-earlier-move' } - ] - }, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - 'tab-earlier-move': { - root: { type: 'leaf', leafId: MOVED }, - activeLeafId: MOVED, - expandedLeafId: null - } - } - }) - - await expect( - store.moveTerminalLeafToNewTab({ ...moveRequest, ptyId: 'pty-agent' }) - ).resolves.toEqual({ status: 'refused', reason: 'leaf_in_other_tab' }) - }) }) // STA-9259: move, reattach, stale renderer save and restart must retain one leaf/PTY owner. diff --git a/src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts b/src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts deleted file mode 100644 index 1eea995b396..00000000000 --- a/src/main/persistence/terminal-topology/terminal-pane-admission-taken-ids-switch-off.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Switch-off builds permit paired hosts to add panes and do not enforce main-owned close records. -import { describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { admitPaneToSession, applyCommandToSession } from './terminal-pane-admission' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) - -const WORKTREE = 'repo-1::/workspace' -const TAB = 'tab-1' - -describe('a runtime pane in the shipped build', () => { - it("writes a client tab's second pane under the tab's id", () => { - const first = admitPaneToSession('local', getDefaultWorkspaceSession(), { - type: 'createTerminalTab', - workspace: WORKTREE, - tabId: TAB, - leafId: '11111111-1111-4111-8111-111111111111' - }) - expect(first.value).toBe('admitted') - const second = admitPaneToSession('local', first.session!, { - type: 'createTerminalTab', - workspace: WORKTREE, - tabId: TAB, - leafId: '22222222-2222-4222-8222-222222222222' - }) - expect(second.value).toBe('admitted') - }) - - it('writes a create under the id of a tab the user closed, on both pane write paths', () => { - const create = { - type: 'createTerminalTab', - workspace: WORKTREE, - tabId: TAB, - leafId: '11111111-1111-4111-8111-111111111111' - } as const - const opened = applyCommandToSession('local', getDefaultWorkspaceSession(), create) - const closed = applyCommandToSession('local', opened.session!, { - type: 'closeTabs', - workspace: WORKTREE, - tabIds: [TAB], - recordClose: 'user' - }) - expect(closed.value.ok).toBe(true) - const afterClose = closed.session! - expect(afterClose.closedTerminalTabTombstonesByTabId?.[TAB]).toBeDefined() - - expect(applyCommandToSession('local', afterClose, create).value.ok).toBe(true) - expect(admitPaneToSession('local', afterClose, create).value).toBe('admitted') - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts b/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts index 6d97610548b..1155756d26f 100644 --- a/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts +++ b/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts @@ -169,94 +169,6 @@ describe('a window drag-out through layout.apply', () => { ).toBe(true) expect(tabsHoldingLeaf(store.getWorkspaceSession(), LEFT)).toEqual([SOURCE]) }) - - it('starts an unbound pane’s new tab in the folder the window sent', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - const seeded = store.getWorkspaceSession() - store.setWorkspaceSession({ - ...seeded, - terminalLayoutsByTabId: { - [SOURCE]: { - ...seeded.terminalLayoutsByTabId[SOURCE]!, - ptyIdsByLeafId: { [LEFT]: 'pty-left' } - } - } - }) - - await expect(detach(store, null, ['local'], '/wt/app')).resolves.toMatchObject({ - ok: true, - result: { tabId: TARGET, ptyId: null } - }) - - const target = store.getWorkspaceSession().tabsByWorktree[WT]?.find((tab) => tab.id === TARGET) - expect(target?.startupCwd).toBe('/wt/app') - }) - - it('refuses a terminal no copy names, and a leaf another tab holds', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - // Main-owned binding outranks the renderer's claimed PTY. - const claimed = openStore(newDataFile()) - await seedSplitSource(claimed) - await expect(detach(claimed, 'pty-other')).resolves.toEqual({ - ok: true, - result: { tabId: TARGET, ptyId: 'pty-agent' } - }) - } else { - await expect(detach(store, 'pty-other')).resolves.toEqual({ ok: false, code: 'pty_mismatch' }) - } - const session = store.getWorkspaceSession() - store.setWorkspaceSession({ - ...session, - tabsByWorktree: { - ...session.tabsByWorktree, - [WT]: [ - ...(session.tabsByWorktree[WT] ?? []), - { ...(session.tabsByWorktree[WT] ?? [])[0]!, id: 'tab-earlier-move' } - ] - }, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - 'tab-earlier-move': { - root: { type: 'leaf', leafId: MOVED }, - activeLeafId: MOVED, - expandedLeafId: null - } - } - }) - await expect(detach(store, 'pty-agent')).resolves.toEqual({ - ok: false, - code: 'pane_in_other_tab' - }) - expect(tabsHoldingLeaf(store.getWorkspaceSession(), MOVED)).toContain(SOURCE) - }) - - it('takes the one bound terminal when the window has none', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - await expect(detach(store, null)).resolves.toEqual({ - ok: true, - result: { tabId: TARGET, ptyId: 'pty-agent' } - }) - }) - - it('moves the remote session id with the moved terminal', async () => { - const store = openStore(newDataFile()) - await seedSplitSource(store) - store.setWorkspaceSession({ - ...store.getWorkspaceSession(), - remoteSessionIdsByTabId: { [SOURCE]: 'pty-agent' } - }) - - await detach(store, 'pty-agent') - - expect(store.getWorkspaceSession().remoteSessionIdsByTabId).toEqual({ - [SOURCE]: 'pty-left', - [TARGET]: 'pty-agent' - }) - }) }) describe('a window drag-out of an SSH pane held by both partitions', () => { diff --git a/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts b/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts index a643e7418fa..fb6c00f9ea1 100644 --- a/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts +++ b/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts @@ -111,23 +111,6 @@ describe('main shows a live terminal no pane shows, at startup with no window', }) }) - it('a bind by main’s pass raises the pane’s binding generation by exactly one', async () => { - const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) - const before = store.getPtyBindingGeneration('local', LEAF) ?? 0 - - await placeOn(store, [livePty('pty-agent', { tabId: TAB, paneKey: `${TAB}:${LEAF}` })]) - - expect(store.getPtyBindingGeneration('local', LEAF)).toBe(before + 1) - await store.applyLayoutCommand({ - type: 'renameTab', - workspace: WORKTREE, - tabId: TAB, - kind: 'custom', - title: 'x' - }) - expect(store.getPtyBindingGeneration('local', LEAF)).toBe(before + 1) - }) - it('shows a terminal no pane ever named in a new tab bound to it, kept across a restart', async () => { const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) @@ -145,83 +128,4 @@ describe('main shows a live terminal no pane shows, at startup with no window', ) expect((await placeOn(relaunched, [livePty('pty-cli')])).placed).toEqual([]) }) - - it('leaves a terminal whose spawn is still binding its pane to that spawn', async () => { - const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) - - const placement = await placeOn(store, [livePty('pty-starting')], { - isStillBinding: () => true - }) - - expect(placement).toMatchObject({ placed: [], declined: [] }) - expect(terminalTabs(store)).toHaveLength(1) - }) - - it('leaves alone a terminal a pane shows, one being killed, and a remote one', async () => { - const store = await openStore((window) => { - window.addTab(WORKTREE, TAB, LEAF) - window.bind(TAB, LEAF, 'pty-bound') - }) - const remote: LivePty = { ...livePty('ssh:host@@pty-remote'), connectionId: 'host' } - - const placement = await placeOn(store, [livePty('pty-bound'), livePty('pty-closing'), remote], { - refreshInventory: async () => ({ - exitingPtyIds: new Set(['pty-closing']), - workspaceIds: new Set([WORKTREE]) - }) - }) - - expect(placement).toMatchObject({ placed: [], declined: [] }) - expect(terminalTabs(store).map((tab) => tab.id)).toEqual([TAB]) - }) - - it('places nothing in a workspace this host does not know (removed outside the app)', async () => { - const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) - const stray: LivePty = { ...livePty('pty-stray'), worktreeId: 'repo-local::/fixture/removed' } - - const placement = await placeOn(store, [stray]) - - expect(placement).toMatchObject({ placed: [], declined: [] }) - expect(Object.keys(store.getWorkspaceSession().tabsByWorktree)).toEqual([WORKTREE]) - }) - - it('a terminal main cannot place is declined, and the rest are still placed', async () => { - const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const apply: LiveTerminalPlacementPorts['apply'] = (command) => - command.adopt?.ptyId === 'pty-bad' - ? Promise.reject(new Error('record unreadable')) - : store.applyLayoutCommand(command) - - const placement = await placeOn(store, [livePty('pty-bad'), livePty('pty-good')], { apply }) - - expect(placement).toMatchObject({ placed: ['pty-good'], declined: ['pty-bad'] }) - expect(warn).toHaveBeenCalledOnce() - expect(String(warn.mock.calls[0])).toContain('record unreadable') - warn.mockRestore() - }) - - it('places nothing, and does not fail, when the census itself fails', async () => { - const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const placement = await placeOn(store, [livePty('pty-cli')], { - refreshInventory: () => Promise.reject(new Error('terminal service down')) - }) - - expect(placement).toMatchObject({ placed: [], declined: [] }) - expect(terminalTabs(store)).toHaveLength(1) - warn.mockRestore() - }) - - it('places nothing when the host census could not answer', async () => { - const store = await openStore((window) => window.addTab(WORKTREE, TAB, LEAF)) - - const placement = await placeOn(store, [livePty('pty-cli')], { - refreshInventory: async () => null - }) - - expect(placement).toMatchObject({ placed: [], declined: [] }) - expect(terminalTabs(store)).toHaveLength(1) - }) }) diff --git a/src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts b/src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts deleted file mode 100644 index 0f5a85a80c6..00000000000 --- a/src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -// Opt in: ORCA_LOCAL_METADATA_PRUNE_BENCH=1 pnpm test src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts -import { performance } from 'node:perf_hooks' -import { describe, expect, it, vi } from 'vitest' -import { getDefaultPersistedState } from '../../../shared/constants' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { Repo } from '../../../shared/repo-types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { removeWorkspaceSessionOwner } from '../restoring-sessions/session-owner-removal' -import { - pruneUnreferencedWorktreeIdentityMeta, - removeWorktreeMetadataForHost -} from '../loading-store/worktree-identity-metadata' -import { - captureNativeLocalWorktreeMetadataScanExpectation, - pruneSessionlessMissingLocalWorktreeMetadataForRepo -} from './missing-local-worktree-metadata-pruning' - -const describeBench = process.env.ORCA_LOCAL_METADATA_PRUNE_BENCH ? describe : describe.skip -const ROW_COUNT = 2_709 -const REPO: Repo = { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0 -} - -function makeMeta(index: number): WorktreeMeta { - return { - instanceId: `instance-${index}`, - hostId: 'local', - displayName: `stale-${index}`, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: index, - lastActivityAt: 0 - } -} - -function makeState(): { state: PersistedState; staleIds: string[] } { - const state = getDefaultPersistedState('/home/test') - state.repos = [REPO] - state.worktreeMetaByIdentity = {} - state.worktreeIdentityAliases = {} - const staleIds = Array.from( - { length: ROW_COUNT }, - (_, index) => `${REPO.id}::/workspace/stale-${index}` - ) - for (const [index, worktreeId] of staleIds.entries()) { - const meta = makeMeta(index) - const identityKey = `identity-${index}` - state.worktreeMeta[worktreeId] = meta - state.worktreeMetaByIdentity[identityKey] = meta - state.worktreeIdentityAliases[`local|${worktreeId}`] = [identityKey] - } - return { state, staleIds } -} - -describeBench('authoritative local metadata batch pruning', () => { - it('measures the reported 2,709-row sequential and batch shapes', () => { - const legacy = makeState() - const batch = makeState() - const cloneSpy = vi.spyOn(globalThis, 'structuredClone') - const legacyStartedAt = performance.now() - for (const worktreeId of legacy.staleIds) { - removeWorktreeMetadataForHost(legacy.state, worktreeId, undefined) - delete legacy.state.worktreeMeta[worktreeId] - legacy.state.workspaceSession = removeWorkspaceSessionOwner( - legacy.state.workspaceSession, - worktreeId - )! - } - pruneUnreferencedWorktreeIdentityMeta(legacy.state) - const legacyMs = performance.now() - legacyStartedAt - const legacySessionClones = cloneSpy.mock.calls.length - cloneSpy.mockClear() - - const batchStartedAt = performance.now() - const scan = captureNativeLocalWorktreeMetadataScanExpectation(batch.state, REPO) - const removed = pruneSessionlessMissingLocalWorktreeMetadataForRepo( - batch.state, - scan, - scan.metadata - ) - const batchMs = performance.now() - batchStartedAt - const batchSessionClones = cloneSpy.mock.calls.length - cloneSpy.mockRestore() - - expect(removed).toHaveLength(ROW_COUNT) - expect(Object.keys(legacy.state.worktreeMeta)).toHaveLength(0) - expect(Object.keys(batch.state.worktreeMeta)).toHaveLength(0) - expect(legacySessionClones).toBe(ROW_COUNT) - expect(batchSessionClones).toBe(0) - - console.log( - `[bench] rows=${ROW_COUNT} metadata+session=${legacyMs.toFixed(2)}ms -> ${batchMs.toFixed(2)}ms; ` + - `gitScans=${ROW_COUNT} -> 1; sessionClones=${legacySessionClones} -> ${batchSessionClones}; ` + - `minimumSaveSchedules=${ROW_COUNT * 2} -> 1` - ) - }) -}) diff --git a/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts b/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts index 85c883fe666..8fb19067b63 100644 --- a/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts +++ b/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts @@ -72,19 +72,6 @@ describe('local worktree metadata scan expectations', () => { expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeUndefined() }) - it('removes equal legacy and canonical projections after a persistence round trip', () => { - const state = makeState() - const meta = makeMeta() - state.worktreeMeta[WORKTREE_ID] = structuredClone(meta) - state.worktreeMetaByIdentity = { [IDENTITY_KEY]: structuredClone(meta) } - state.worktreeIdentityAliases = { [LOCAL_ALIAS]: [IDENTITY_KEY] } - - expect(pruneCaptured(state)).toEqual([WORKTREE_ID]) - expect(state.worktreeMeta[WORKTREE_ID]).toBeUndefined() - expect(state.worktreeIdentityAliases[LOCAL_ALIAS]).toBeUndefined() - expect(state.worktreeMetaByIdentity[IDENTITY_KEY]).toBeUndefined() - }) - it('does not sweep an unrelated unaliased canonical row during pruning', () => { const { state, meta } = makeCanonicalOnlyState() const unrelated = makeMeta(`${REPO_ID}::/workspace/unrelated`) @@ -96,31 +83,6 @@ describe('local worktree metadata scan expectations', () => { expect(meta).not.toBe(unrelated) }) - it('allocates expectations only for the scanned repository', () => { - const state = makeState() - const otherRepo = makeRepo('repo-2') - const otherId = `${otherRepo.id}::/workspace/other` - const canonicalId = `${REPO_ID}::/workspace/canonical` - const canonicalKey = 'canonical-key' - state.repos.push(otherRepo) - state.worktreeMeta[WORKTREE_ID] = makeMeta() - state.worktreeMeta[otherId] = makeMeta(otherId) - state.worktreeMetaByIdentity = { - [canonicalKey]: makeMeta(canonicalId), - 'other-key': makeMeta(otherId) - } - state.worktreeIdentityAliases = { - [`local|${canonicalId}`]: [canonicalKey], - [`local|${otherId}`]: ['other-key'] - } - - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - - expect(scan.metadata.map(({ worktreeId }) => worktreeId).sort()).toEqual( - [WORKTREE_ID, canonicalId].sort() - ) - }) - it('preserves metadata when an alias array is replaced with identical contents', () => { const { state } = makeCanonicalOnlyState() const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) @@ -132,54 +94,6 @@ describe('local worktree metadata scan expectations', () => { expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeDefined() }) - it('preserves metadata when the captured alias array is mutated in place', () => { - const { state } = makeCanonicalOnlyState() - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - state.worktreeIdentityAliases![LOCAL_ALIAS]!.push('new-identity') - state.worktreeMetaByIdentity!['new-identity'] = makeMeta() - - expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual( - [] - ) - }) - - it.each([ - [ - 'replaced', - (state: PersistedState) => { - state.worktreeMetaByIdentity![IDENTITY_KEY] = { - ...state.worktreeMetaByIdentity![IDENTITY_KEY]! - } - } - ], - [ - 'host-mutated', - (state: PersistedState) => { - state.worktreeMetaByIdentity![IDENTITY_KEY]!.hostId = 'ssh:builder' - } - ], - [ - 'instance-mutated', - (state: PersistedState) => { - state.worktreeMetaByIdentity![IDENTITY_KEY]!.instanceId = 'new-instance' - } - ], - [ - 'content-mutated', - (state: PersistedState) => { - state.worktreeMetaByIdentity![IDENTITY_KEY]!.comment = 'new comment' - } - ] - ] as const)('preserves metadata when a canonical row is %s', (_label, mutate) => { - const { state } = makeCanonicalOnlyState() - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - mutate(state) - - expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual( - [] - ) - }) - it.each([ [ 'added', @@ -214,29 +128,4 @@ describe('local worktree metadata scan expectations', () => { ) expect(state.worktreeMeta[WORKTREE_ID]).toBeDefined() }) - - it.each([WORKTREE_ID, `bogus|${WORKTREE_ID}`, `ssh:builder|${WORKTREE_ID}`])( - 'preserves metadata with an unqualified or foreign alias: %s', - (alias) => { - const state = makeState() - state.worktreeMeta[WORKTREE_ID] = makeMeta() - state.worktreeMetaByIdentity = { [IDENTITY_KEY]: state.worktreeMeta[WORKTREE_ID]! } - state.worktreeIdentityAliases = { [alias]: [IDENTITY_KEY] } - - expect(pruneCaptured(state)).toEqual([]) - expect(state.worktreeMeta[WORKTREE_ID]).toBeDefined() - } - ) - - it('preserves an unqualified alias whose worktree path contains a pipe', () => { - const state = makeState() - const pipedId = `${REPO_ID}::/workspace/a|b` - state.worktreeMeta[pipedId] = makeMeta(pipedId) - state.worktreeMetaByIdentity = { [IDENTITY_KEY]: state.worktreeMeta[pipedId]! } - state.worktreeIdentityAliases = { [pipedId]: [IDENTITY_KEY] } - - expect(pruneCaptured(state)).toEqual([]) - expect(state.worktreeMeta[pipedId]).toBeDefined() - expect(state.worktreeIdentityAliases[pipedId]).toEqual([IDENTITY_KEY]) - }) }) diff --git a/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts b/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts index d43433bc0a2..afbfb7b8d3a 100644 --- a/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts +++ b/src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts @@ -116,26 +116,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => { expect(state.workspaceSessionsByHostId?.['runtime:mirror']).toEqual(hostSessionSnapshot) }) - it('fails closed when metadata is mutated or replaced after the scan starts', () => { - const inPlaceState = makeState() - const inPlaceId = `${REPO_ID}::/workspace/in-place` - inPlaceState.worktreeMeta[inPlaceId] = makeMeta(inPlaceId) - const inPlaceScan = capture(inPlaceState) - inPlaceState.worktreeMeta[inPlaceId]!.instanceId = 'replacement-instance' - - expect(pruneCaptured(inPlaceState, inPlaceScan, [inPlaceId])).toEqual([]) - - const replacedState = makeState() - const replacedId = `${REPO_ID}::/workspace/replaced` - const original = makeMeta(replacedId) - replacedState.worktreeMeta[replacedId] = original - const replacedScan = capture(replacedState) - replacedState.worktreeMeta[replacedId] = { ...original } - - expect(pruneCaptured(replacedState, replacedScan, [replacedId])).toEqual([]) - expect(replacedState.worktreeMeta[replacedId]).not.toBe(original) - }) - it('fails closed when an identical repo row is removed and re-added during the scan', () => { const state = makeState() const worktreeId = `${REPO_ID}::/workspace/re-added-repo` @@ -149,145 +129,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => { expect(state.worktreeMeta[worktreeId]).toBeDefined() }) - it('uses the effective Git kind when the raw legacy repo omitted kind', () => { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/legacy-git-kind` - const rawRepo = state.repos[0]! - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - const scan = capture(state, { ...rawRepo, kind: 'git' }) - - expect(rawRepo.kind).toBeUndefined() - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([worktreeId]) - }) - - it.each([ - 'tabsByWorktree', - 'browserTabsByWorktree', - 'openFilesByWorktree', - 'activeFileIdByWorktree', - 'activeBrowserTabIdByWorktree', - 'clientHostedBrowserPagesByWorktree', - 'activeTabTypeByWorktree', - 'activeTabIdByWorktree', - 'unifiedTabs', - 'tabGroups', - 'tabGroupLayouts', - 'activeGroupIdByWorktree', - 'lastVisitedAtByWorktreeId', - 'defaultTerminalTabsAppliedByWorktreeId' - ] as const)('preserves an owner named by workspaceSession.%s', (field) => { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/${field}` - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - const scan = capture(state) - const ownerKey = field === 'lastVisitedAtByWorktreeId' ? `local|${worktreeId}` : worktreeId - ;(state.workspaceSession as unknown as Record)[field] = { - [ownerKey]: [] - } - - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([]) - expect(state.worktreeMeta[worktreeId]).toBeDefined() - }) - - it('preserves scalar, nested, remote-partition, mobile, and relay recovery owners', () => { - const ownerMutations: ((state: PersistedState, worktreeId: string) => void)[] = [ - (state, worktreeId) => { - state.workspaceSession.activeWorktreeId = worktreeId - }, - (state, worktreeId) => { - state.workspaceSession.activeWorkspaceKey = worktreeWorkspaceKey(worktreeId) - }, - (state, worktreeId) => { - state.workspaceSession.activeWorktreeIdsOnShutdown = [worktreeId] - }, - (state, worktreeId) => { - state.ui.lastActiveWorktreeId = worktreeId - }, - (state, worktreeId) => { - state.workspaceSession.sleepingAgentSessionsByPaneKey = { - pane: { worktreeId } as never - } - }, - (state, worktreeId) => { - state.workspaceSession.terminalSurfaceTombstonesByPaneKey = { - pane: { worktreeId } as never - } - }, - (state, worktreeId) => { - state.workspaceSession.closedTerminalTabTombstonesByTabId = { - tab: { worktreeId, closedAt: 1 } - } - }, - (state, worktreeId) => { - state.workspaceSession.clientHostedBrowserCloseIntentsByEnvironment = { - runtime: [{ worktreeId, browserPageId: 'page', closedAt: 1 }] - } - }, - (state, worktreeId) => { - state.workspaceSession.browserPagesByWorkspace = { - browser: [{ worktreeId } as never] - } - }, - (state, worktreeId) => { - state.workspaceSessionsByHostId = { - 'ssh:builder': { - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { [worktreeId]: 1 } - } - } - }, - (state, worktreeId) => { - state.mobileClientTabSelectionsByDeviceId = { - phone: { [worktreeId]: {} as never } - } - }, - (state, worktreeId) => { - state.sshRemotePtyLeases = [ - { - targetId: 'builder', - ptyId: 'pty', - worktreeId, - state: 'detached', - createdAt: 1, - updatedAt: 1 - } - ] - }, - (state, worktreeId) => { - state.migrationUnsupportedPtyEntries = [ - { - ptyId: 'pty', - worktreeId, - reason: 'legacy-numeric-pane-key', - source: 'local', - updatedAt: 1 - } - ] - }, - (state, worktreeId) => { - state.automations = [ - { - enabled: true, - workspaceMode: 'existing', - workspaceId: worktreeId - } as never - ] - }, - (state, worktreeId) => { - state.automationRuns = [{ status: 'dispatching', workspaceId: worktreeId } as never] - } - ] - - for (const [index, mutate] of ownerMutations.entries()) { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/owner-${index}` - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - const scan = capture(state) - mutate(state, worktreeId) - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([]) - } - }) - // Route-retired tombstones must not pin metadata forever (#17775). it('does not let route-retired SSH leases pin a metadata row', () => { const state = makeState() @@ -324,85 +165,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => { expect(Object.keys(state.worktreeMeta).sort()).toEqual([...liveIds].sort()) }) - // Plain expiry proves only route loss; recoverable panes retain ownership. - it('keeps a metadata row pinned by an unmarked expired lease', () => { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/orphaned` - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - const scan = capture(state) - state.sshRemotePtyLeases = [ - { - targetId: 'builder', - ptyId: 'pty', - worktreeId, - state: 'expired', - createdAt: 1, - updatedAt: 1 - } - ] - - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([]) - }) - - it('preserves canonically equivalent session and top-level owners', () => { - const candidateId = `${REPO_ID}::/workspace/Café`.normalize('NFC') - const ownerId = candidateId.normalize('NFD') - const ownerMutations: ((state: PersistedState) => void)[] = [ - (state) => { - state.workspaceSession.activeWorktreeId = ownerId - }, - (state) => { - state.ui.lastActiveWorktreeId = ownerId - } - ] - - for (const mutate of ownerMutations) { - const state = makeState() - state.worktreeMeta[candidateId] = makeMeta(candidateId) - const scan = capture(state) - mutate(state) - - expect(pruneCaptured(state, scan, [candidateId])).toEqual([]) - expect(state.worktreeMeta[candidateId]).toBeDefined() - } - }) - - it('removes a row on a later pass after its persisted owner is cleared', () => { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/two-phase` - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - state.workspaceSession.lastVisitedAtByWorktreeId = { [worktreeId]: 1 } - const scan = capture(state) - - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([]) - delete state.workspaceSession.lastVisitedAtByWorktreeId![worktreeId] - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([worktreeId]) - }) - - it('treats dotfile visibility and cleanup dismissals as non-owning preferences', () => { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/non-owning-preferences` - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - const showDotfilesByWorktree = { [worktreeId]: true } - const workspaceCleanup = { - dismissals: { - [worktreeId]: { - worktreeId, - dismissedAt: 1, - fingerprint: 'fingerprint', - classifierVersion: 1 - } - } - } - state.ui.showDotfilesByWorktree = showDotfilesByWorktree - state.ui.workspaceCleanup = workspaceCleanup - const scan = capture(state) - - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([worktreeId]) - expect(state.ui.showDotfilesByWorktree).toBe(showDotfilesByWorktree) - expect(state.ui.workspaceCleanup).toBe(workspaceCleanup) - }) - it('preserves foreign aliases, ambiguous local aliases, and divergent projections', () => { const foreignState = makeState() const foreignId = `${REPO_ID}::/workspace/foreign-alias` @@ -438,34 +200,6 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => { expect(pruneCaptured(divergentState, divergentScan, [divergentId])).toEqual([]) }) - it('fails closed for repo replacement, host collisions, remote, runtime, and folder repos', () => { - const mutations: ((state: PersistedState) => void)[] = [ - (state) => { - state.repos[0] = makeRepo({ path: '/workspace/replacement' }) - }, - (state) => { - state.repos.push(makeRepo({ connectionId: 'builder', executionHostId: 'ssh:builder' })) - }, - (state) => { - state.repos[0] = makeRepo({ connectionId: 'builder', executionHostId: 'ssh:builder' }) - }, - (state) => { - state.repos[0] = makeRepo({ executionHostId: 'runtime:environment' }) - }, - (state) => { - state.repos[0] = makeRepo({ kind: 'folder' }) - } - ] - for (const mutate of mutations) { - const state = makeState() - const worktreeId = `${REPO_ID}::/workspace/stale` - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - const scan = capture(state) - mutate(state) - expect(pruneCaptured(state, scan, [worktreeId])).toEqual([]) - } - }) - it('fails closed when project runtime routing changes away and back during the scan', () => { const state = makeState() const worktreeId = `${REPO_ID}::/workspace/project-routing-race` @@ -509,26 +243,4 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => { expect(pruneCaptured(state, scan, [worktreeId])).toEqual([]) expect(state.worktreeMeta[worktreeId]).toBeDefined() }) - - it('rejects malformed, folder-instance, WSL, and non-native Windows candidate paths', () => { - const state = makeState() - const foreignWindowsId = `${REPO_ID}::C:\\workspace\\stale` - const ids = [ - `${REPO_ID}::relative/path`, - `${REPO_ID}::`, - `wrong::/workspace/stale`, - `${REPO_ID}::/workspace/folder::workspace:11111111-1111-4111-8111-111111111111`, - `${REPO_ID}::\\\\wsl.localhost\\Ubuntu\\home\\gone`, - `${REPO_ID}::/home/user/wsl-legacy`, - foreignWindowsId - ] - for (const worktreeId of ids) { - state.worktreeMeta[worktreeId] = makeMeta(worktreeId) - } - const scan = capture(state) - - expect(pruneCaptured(state, scan, ids.slice(0, -2))).toEqual([]) - expect(pruneCaptured(state, scan, [ids.at(-2)!], 'win32')).toEqual([]) - expect(pruneCaptured(state, scan, [foreignWindowsId], 'linux')).toEqual([]) - }) }) diff --git a/src/main/persistence/tracking-repos/persistence-agent-workspace-trust-migration.test.ts b/src/main/persistence/tracking-repos/persistence-agent-workspace-trust-migration.test.ts deleted file mode 100644 index 4becbae7a48..00000000000 --- a/src/main/persistence/tracking-repos/persistence-agent-workspace-trust-migration.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - closeTestStores, - testState, - createStore, - writeDataFile, - makeRepo -} from '../persistence-test-harness' -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { rmSync, mkdtempSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import type { Repo } from '../../../shared/repo-types' - -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: vi.fn(), - sshConfigHostsToTargets: vi.fn() -})) -vi.mock('electron', () => ({ - app: { getPath: () => testState.dir }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) - } -})) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: () => ({ nth_repo_added: 2 }) -})) - -function writeProfile(repos: Repo[], settings: Record = {}): void { - writeDataFile({ - schemaVersion: 1, - repos, - worktreeMeta: {}, - settings, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) -} - -describe('keeping agent pre-trust for repos saved before per-repo decisions', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - }) - - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('pins existing repos to pre-trust and keeps explicit answers', async () => { - writeProfile([ - makeRepo({ id: 'existing', path: '/repos/existing' }), - makeRepo({ id: 'asks', path: '/repos/asks', agentWorkspaceTrust: 'agent-asks' }) - ]) - - const store = await createStore() - - expect(store.getRepo('existing')?.agentWorkspaceTrust).toBe('pre-trust') - expect(store.getRepo('asks')?.agentWorkspaceTrust).toBe('agent-asks') - expect(store.getSettings().agentWorkspaceTrustExistingReposMigrated).toBe(true) - }) - - it('leaves repos undecided when the user had turned folder trust off', async () => { - writeProfile([makeRepo({ id: 'existing', path: '/repos/existing' })], { - agentWorkspaceTrustEnabled: false - }) - - const store = await createStore() - - expect(store.getRepo('existing')).not.toHaveProperty('agentWorkspaceTrust') - expect(store.getSettings().agentWorkspaceTrustEnabled).toBe(false) - }) - - it('runs once, so repos added after the upgrade stay undecided', async () => { - writeProfile([makeRepo({ id: 'added-later', path: '/repos/added-later' })], { - agentWorkspaceTrustExistingReposMigrated: true - }) - - const store = await createStore() - - expect(store.getRepo('added-later')).not.toHaveProperty('agentWorkspaceTrust') - }) -}) diff --git a/src/main/persistence/tracking-repos/persistence-folder-scan-project-groups.test.ts b/src/main/persistence/tracking-repos/persistence-folder-scan-project-groups.test.ts index f8ef9a691f9..d5ca41c75a5 100644 --- a/src/main/persistence/tracking-repos/persistence-folder-scan-project-groups.test.ts +++ b/src/main/persistence/tracking-repos/persistence-folder-scan-project-groups.test.ts @@ -10,10 +10,8 @@ import { testState, writeDataFile } from '../persistence-test-harness' -import { getDefaultPersistedState } from '../../../shared/constants' -import { createProjectGroup } from '../../../shared/project-groups' + import { normalizeRuntimePathSeparators } from '../../../shared/cross-platform-path' -import { LoadedStateAdaptationOperations } from '../loading-store/loaded-state-adaptation' vi.mock('electron', () => ({ app: { @@ -44,34 +42,6 @@ describe('Flat folder-scan project groups adaptation', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it('leaves unchanged group membership and manual order clean on load', () => { - const state = getDefaultPersistedState(testState.dir) - const parentPath = join(testState.dir, 'projects') - const group = createProjectGroup({ - name: 'Projects', - parentPath, - createdFrom: 'folder-scan', - tabOrder: 0 - }) - state.projectGroups = [group] - state.repos = ['alpha', 'beta'].map((name, index) => - makeRepo({ - id: name, - path: join(parentPath, name), - projectGroupId: group.id, - projectGroupOrder: 1 - index - }) - ) - const operations = new LoadedStateAdaptationOperations({ state, loadNeedsSave: false }) - - expect(operations.adaptFlatFolderScanProjectGroups()).toBe(false) - expect(state.projectGroups).toEqual([group]) - expect(state.repos.map((repo) => [repo.projectGroupId, repo.projectGroupOrder])).toEqual([ - [group.id, 1], - [group.id, 0] - ]) - }) - it.each([false, true])( 'preserves saved order through a Store restart (folder repo: %s)', async (includeFolder) => { diff --git a/src/main/persistence/tracking-repos/persistence-workspace-status-workflow.test.ts b/src/main/persistence/tracking-repos/persistence-workspace-status-workflow.test.ts index 0272bffc21d..ad9799f7b6e 100644 --- a/src/main/persistence/tracking-repos/persistence-workspace-status-workflow.test.ts +++ b/src/main/persistence/tracking-repos/persistence-workspace-status-workflow.test.ts @@ -11,13 +11,6 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import type { PersistedState } from '../../../shared/persisted-state-types' -import { - REORDERED_DEFAULT_WORKSPACE_STATUSES, - REORDERED_DONE_DEFAULT_WORKSPACE_STATUSES, - LEGACY_DEFAULT_WORKSPACE_STATUSES, - WORKFLOW_DEFAULT_WORKSPACE_STATUSES -} from './persistence-workspace-status-fixtures' - const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() @@ -69,85 +62,6 @@ describe('Store', () => { await closeTestStores() rmSync(testState.dir, { recursive: true, force: true }) }) - it('preserves persisted smart sort value', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { sortBy: 'smart' }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().sortBy).toBe('smart') - }) - - it('migrates legacy recent sort to smart on first load', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { sortBy: 'recent' }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().sortBy).toBe('smart') - expect(store.getUI()._sortBySmartMigrated).toBe(true) - }) - - it('preserves new recent sort after migration flag is set', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { sortBy: 'recent', _sortBySmartMigrated: true }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().sortBy).toBe('recent') - }) - - it('uses recent as the default sort for a fresh install (no persisted sortBy)', async () => { - // Gate migration on the raw stored sort, or normalization would misclassify fresh profiles. - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().sortBy).toBe('recent') - }) - - it('defaults workspace board task status sync off and normalizes persisted values', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { syncTaskStatusFromWorkspaceBoard: 'yes' }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().syncTaskStatusFromWorkspaceBoard).toBe(false) - - store.updateUI({ syncTaskStatusFromWorkspaceBoard: true }) - expect(store.getUI().syncTaskStatusFromWorkspaceBoard).toBe(true) - }) it('preserves workflows above 20 statuses across load, write, and restart', async () => { const imported = Array.from({ length: 21 }, (_, index) => ({ @@ -188,147 +102,4 @@ describe('Store', () => { authored.map((status) => status.id) ) }) - - it('repairs the known-bad reordered default workspace statuses once on load', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { workspaceStatuses: REORDERED_DEFAULT_WORKSPACE_STATUSES }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - const ui = store.getUI() - expect(ui.workspaceStatuses?.map((status) => status.id)).toEqual([ - 'todo', - 'in-progress', - 'in-review', - 'completed' - ]) - expect(ui.workspaceStatuses?.at(-1)?.label).toBe('Done') - expect(ui._workspaceStatusesDefaultOrderMigrated).toBe(true) - expect(ui._workspaceStatusesDefaultWorkflowMigrated).toBe(true) - - store.flush() - const persisted = readDataFile() as PersistedState - expect(persisted.ui._workspaceStatusesDefaultOrderMigrated).toBe(true) - expect(persisted.ui._workspaceStatusesReorderedDefaultRepaired).toBe(true) - expect(persisted.ui._workspaceStatusesDefaultWorkflowMigrated).toBe(true) - expect(persisted.ui._workspaceStatusesDefaultVisualsMigrated).toBe(true) - expect(persisted.ui.workspaceStatuses?.map((status) => status.id)).toEqual([ - 'todo', - 'in-progress', - 'in-review', - 'completed' - ]) - expect(persisted.ui.workspaceStatuses?.at(-1)?.label).toBe('Done') - }) - - it('repairs the known-bad reordered default statuses after old migration flags are set', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { - workspaceStatuses: REORDERED_DONE_DEFAULT_WORKSPACE_STATUSES, - _workspaceStatusesDefaultOrderMigrated: true, - _workspaceStatusesDefaultWorkflowMigrated: true, - _workspaceStatusesDefaultVisualsMigrated: true - }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().workspaceStatuses?.map((status) => status.id)).toEqual([ - 'todo', - 'in-progress', - 'in-review', - 'completed' - ]) - expect(store.getUI().workspaceStatuses?.at(-1)?.label).toBe('Done') - expect(store.getUI()._workspaceStatusesReorderedDefaultRepaired).toBe(true) - }) - - it('migrates legacy default workspace status visuals and workflow once on load', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { - workspaceStatuses: LEGACY_DEFAULT_WORKSPACE_STATUSES, - _workspaceStatusesDefaultOrderMigrated: true - }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().workspaceStatuses).toEqual(WORKFLOW_DEFAULT_WORKSPACE_STATUSES) - expect(store.getUI()._workspaceStatusesDefaultWorkflowMigrated).toBe(true) - expect(store.getUI()._workspaceStatusesDefaultVisualsMigrated).toBe(true) - - store.flush() - const persisted = readDataFile() as { - ui?: { - _workspaceStatusesDefaultWorkflowMigrated?: boolean - _workspaceStatusesDefaultVisualsMigrated?: boolean - } - } - expect(persisted.ui?._workspaceStatusesDefaultWorkflowMigrated).toBe(true) - expect(persisted.ui?._workspaceStatusesDefaultVisualsMigrated).toBe(true) - }) - - it('preserves legacy-looking workspace status visuals after the load migration', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { - workspaceStatuses: LEGACY_DEFAULT_WORKSPACE_STATUSES, - _workspaceStatusesDefaultOrderMigrated: true, - _workspaceStatusesDefaultWorkflowMigrated: true, - _workspaceStatusesDefaultVisualsMigrated: true - }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - const inProgress = store - .getUI() - .workspaceStatuses?.find((status) => status.id === 'in-progress') - expect(inProgress).toMatchObject({ color: 'blue', icon: 'circle-dot' }) - }) - - it('preserves intentionally reordered default workspace statuses after the load migration', async () => { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings: {}, - ui: { - workspaceStatuses: REORDERED_DEFAULT_WORKSPACE_STATUSES, - _workspaceStatusesDefaultOrderMigrated: true, - _workspaceStatusesReorderedDefaultRepaired: true, - _workspaceStatusesDefaultWorkflowMigrated: true - }, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {} - }) - - const store = await createStore() - expect(store.getUI().workspaceStatuses?.map((status) => status.id)).toEqual([ - 'completed', - 'in-review', - 'in-progress', - 'todo' - ]) - }) }) diff --git a/src/main/persistence/tracking-repos/persistence-worktree-deletion-fencing.test.ts b/src/main/persistence/tracking-repos/persistence-worktree-deletion-fencing.test.ts index d6ba531c3c1..55005f699f3 100644 --- a/src/main/persistence/tracking-repos/persistence-worktree-deletion-fencing.test.ts +++ b/src/main/persistence/tracking-repos/persistence-worktree-deletion-fencing.test.ts @@ -123,39 +123,6 @@ describe('Store', () => { }) }) - it('advances host topology when a live spawn adds a split leaf after retirement', async () => { - const store = await createStore() - store.setWorkspaceSession({ - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - wt1: [makeTerminalTab({ id: 'tab1', worktreeId: 'wt1', ptyId: 'pty-1' })] - }, - terminalLayoutsByTabId: { - tab1: { - root: { type: 'leaf', leafId: TEST_LEAF_1 }, - activeLeafId: TEST_LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [TEST_LEAF_1]: 'pty-1' } - } - }, - terminalTopologyRevisionByRepoId: { wt1: 1 } - }) - - await store.persistPtyBinding({ - worktreeId: 'wt1', - tabId: 'tab1', - leafId: TEST_LEAF_2, - ptyId: 'pty-2' - }) - - const session = store.getWorkspaceSession() - expect(session.terminalTopologyRevisionByRepoId?.wt1).toBe(2) - expect(session.terminalLayoutsByTabId.tab1.ptyIdsByLeafId).toEqual({ - [TEST_LEAF_1]: 'pty-1', - [TEST_LEAF_2]: 'pty-2' - }) - }) - it('keeps worktree deletion authoritative against stale writes and later same-path reuse', async () => { const store = await createStore() store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt1', hostId: 'local' }), { @@ -224,35 +191,6 @@ describe('Store', () => { expect(store.getWorkspaceSession().tabsByWorktree[worktreeId]).toEqual([]) }) - it('advances deletion authority when only a legacy retirement fence existed', async () => { - const store = await createStore() - const worktreeId = 'repo::/legacy-tombstone' - store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId: 'local' }), { - displayName: 'Legacy worktree' - }) - store.setWorkspaceSession({ - ...getDefaultWorkspaceSession(), - terminalSurfaceTombstonesByPaneKey: { - 'old-tab:old-leaf': { - worktreeId, - parentTabId: 'old-tab', - leafId: 'old-leaf', - ptyId: 'old-pty', - incarnationId: 'old-incarnation', - retiredAt: 1 - } - } - }) - const revisionBeforeDelete = - store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.repo ?? 0 - - removeWorktreeMetaRow(store, worktreeId, undefined) - - expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.repo).toBe( - revisionBeforeDelete + 1 - ) - }) - it('enforces one repo epoch across siblings and admits a fresh sibling spawn', async () => { const store = await createStore() const worktreeA = 'repo::/worktree-a' @@ -290,28 +228,6 @@ describe('Store', () => { expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.repo).toBe(2) }) - it('keeps one deletion watermark for many historical worktrees in the same repo', async () => { - const store = await createStore() - - for (let index = 0; index < 25; index += 1) { - const worktreeId = `repo::/worktree-${index}` - store.setWorktreeMeta(hostWorktreeTarget({ id: worktreeId, hostId: 'local' }), { - displayName: `Worktree ${index}` - }) - await store.persistPtyBinding({ - worktreeId, - tabId: `tab-${index}`, - leafId: TEST_LEAF_1, - ptyId: `pty-${index}` - }) - removeWorktreeMetaRow(store, worktreeId, undefined) - } - - const session = store.getWorkspaceSession() - expect(Object.keys(session.terminalTopologyRevisionByRepoId ?? {})).toEqual(['repo']) - expect(session.tabsByWorktree).toEqual({}) - }) - it('does not remove colliding worktree ids from other execution-host partitions', async () => { const store = await createStore() const worktreeId = 'repo::/same-path' diff --git a/src/main/persistence/tracking-repos/persistence-worktree-lineage-and-backups.test.ts b/src/main/persistence/tracking-repos/persistence-worktree-lineage-and-backups.test.ts index 725f26b630e..b6236d1b5ab 100644 --- a/src/main/persistence/tracking-repos/persistence-worktree-lineage-and-backups.test.ts +++ b/src/main/persistence/tracking-repos/persistence-worktree-lineage-and-backups.test.ts @@ -7,7 +7,6 @@ import { writeDataFile, readDataFile, makeRepo, - makeWorktreeLineage, makeWorkspaceLineage } from '../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' @@ -20,8 +19,6 @@ import { restoreProfileStateJsonExport } from '../profile-state/legacy-json/prof import { acquireProfileStateMaintenance } from '../profile-state/profile-state-access' import type { Repo } from '../../../shared/repo-types' import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../shared/workspace-scope' -import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' -import { removeWorktreeMetaRow } from '../host-qualified-worktree-meta' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), @@ -75,81 +72,6 @@ describe('Store', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it('getAllWorktreeMeta returns all entries', async () => { - const store = await createStore() - store.setWorktreeMeta(hostWorktreeTarget({ id: 'a', hostId: 'local' }), { displayName: 'A' }) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'b', hostId: 'local' }), { displayName: 'B' }) - const all = store.getAllWorktreeMeta() - expect(Object.keys(all)).toHaveLength(2) - expect(all['a'].displayName).toBe('A') - expect(all['b'].displayName).toBe('B') - }) - - it('removeWorktreeMeta deletes a single entry', async () => { - const store = await createStore() - store.setWorktreeMeta(hostWorktreeTarget({ id: 'a', hostId: 'local' }), { displayName: 'A' }) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'b', hostId: 'local' }), { displayName: 'B' }) - removeWorktreeMetaRow(store, 'a', undefined) - expect(store.getWorktreeMeta('a')).toBeUndefined() - expect(store.getWorktreeMeta('b')).toBeDefined() - }) - - it('stores and removes worktree lineage independently from metadata', async () => { - const store = await createStore() - const lineage = makeWorktreeLineage() - - store.setWorktreeMeta(hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }), { - displayName: 'child' - }) - store.setWorktreeLineage( - hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }), - lineage - ) - - expect(store.getWorktreeLineage(lineage.worktreeId)).toEqual(lineage) - expect(store.getAllWorktreeLineage()).toEqual({ [lineage.worktreeId]: lineage }) - - store.removeWorktreeLineage(hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' })) - - expect(store.getWorktreeLineage(lineage.worktreeId)).toBeUndefined() - expect(store.getWorktreeMeta(lineage.worktreeId)).toBeDefined() - }) - - it('removeWorktreeMeta deletes that worktree lineage entry', async () => { - const store = await createStore() - const lineage = makeWorktreeLineage() - - store.setWorktreeMeta(hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }), { - displayName: 'child' - }) - store.setWorktreeLineage( - hostWorktreeTarget({ id: lineage.worktreeId, hostId: 'local' }), - lineage - ) - - removeWorktreeMetaRow(store, lineage.worktreeId, undefined) - - expect(store.getWorktreeMeta(lineage.worktreeId)).toBeUndefined() - expect(store.getWorktreeLineage(lineage.worktreeId)).toBeUndefined() - }) - - it('stores workspace lineage and removes it with the child worktree metadata', async () => { - const store = await createStore() - const lineage = makeWorkspaceLineage() - - store.setWorktreeMeta(hostWorktreeTarget({ id: 'r1::/path/child', hostId: 'local' }), { - displayName: 'child' - }) - store.setWorkspaceLineage(lineage) - - expect(store.getWorkspaceLineage(lineage.childWorkspaceKey)).toEqual(lineage) - expect(store.getAllWorkspaceLineage()).toEqual({ [lineage.childWorkspaceKey]: lineage }) - - removeWorktreeMetaRow(store, 'r1::/path/child', undefined) - - expect(store.getWorkspaceLineage(lineage.childWorkspaceKey)).toBeUndefined() - }) - it('removeFolderWorkspace deletes child workspace lineage for that folder parent', async () => { const store = await createStore() const group = store.createProjectGroup({ @@ -179,29 +101,6 @@ describe('Store', () => { }) describe('mobileClientTabSelectionsByDeviceId', () => { - it('persists device tab selections across reloads and drops malformed payloads', async () => { - const store = await createStore() - // Register the owner so orphan cleanup cannot erase the fixture on reload. - store.addRepo(makeRepo({ id: 'repo-1', path: '/repo-1' })) - store.setMobileClientTabSelections({ - 'device-a': { - 'repo-1::/tmp/wt': { activeTabId: 'tab-1', activeGroupId: 'g1', activeTabIdByGroupId: {} } - } - }) - store.flush() - - const reloaded = await createStore() - expect(reloaded.getMobileClientTabSelections()['device-a']?.['repo-1::/tmp/wt']).toEqual({ - activeTabId: 'tab-1', - activeGroupId: 'g1', - activeTabIdByGroupId: {} - }) - - writeDataFile({ mobileClientTabSelectionsByDeviceId: { 'device-a': 'corrupt' } }) - const corrupted = await createStore() - expect(corrupted.getMobileClientTabSelections()).toEqual({}) - }) - it('prunes selections for a removed repo worktree', async () => { const store = await createStore() store.addRepo(makeRepo()) diff --git a/src/main/persistence/tracking-repos/persistence-worktree-visibility.test.ts b/src/main/persistence/tracking-repos/persistence-worktree-visibility.test.ts index 925ecfa9828..8a30d13211e 100644 --- a/src/main/persistence/tracking-repos/persistence-worktree-visibility.test.ts +++ b/src/main/persistence/tracking-repos/persistence-worktree-visibility.test.ts @@ -9,8 +9,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import type { GlobalSettings } from '../../../shared/global-settings-types' -import type { ExternalWorktreeVisibility } from '../../../shared/repo-types' + import { getDefaultPersistedState } from '../../../shared/constants' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ @@ -64,21 +63,6 @@ describe('Store', () => { await closeTestStores() rmSync(testState.dir, { recursive: true, force: true }) }) - it('updateRepo stamps legacy external-worktree visibility before changing old repos', async () => { - const store = await createStore() - store.addRepo( - makeRepo({ - addedAt: Date.UTC(2026, 4, 24), - externalWorktreeVisibility: undefined, - externalWorktreeVisibilityLegacy: undefined - }) - ) - - const updated = store.updateRepo({ id: 'r1' }, { externalWorktreeVisibility: 'hide' }) - - expect(updated!.externalWorktreeVisibility).toBe('hide') - expect(updated!.externalWorktreeVisibilityLegacy).toBe(true) - }) it('migrates implicit legacy visibility to an explicit override before defaulting global hide', async () => { const persisted = getDefaultPersistedState(testState.dir) @@ -117,287 +101,4 @@ describe('Store', () => { }) expect(reloaded.getRepo('inherited')?.externalWorktreeVisibility).toBeUndefined() }) - - it('merges visibility-default patches so future source defaults survive older controls', async () => { - const store = await createStore() - store.updateSettings({ - worktreeVisibilityDefaults: { - external: 'show', - futureSource: 'hide' - } as GlobalSettings['worktreeVisibilityDefaults'] - }) - - store.updateSettings({ worktreeVisibilityDefaults: { external: 'hide' } }) - - expect(store.getSettings().worktreeVisibilityDefaults).toEqual({ - external: 'hide', - futureSource: 'hide' - }) - }) - - it('normalizes and persists global worktree source defaults', async () => { - const store = await createStore() - - store.updateSettings({ - worktreeVisibilityDefaults: { - external: 'show', - customSources: [ - { id: 'team', rootPath: ' /srv/team-worktrees ' }, - { id: 'invalid', rootPath: '../relative' } - ], - sourcePreferences: { - builtIn: { claude: 'show', gsd: 'hide' }, - custom: { team: 'show' } - } - } - }) - - expect(store.getSettings().worktreeVisibilityDefaults).toEqual({ - external: 'show', - customSources: [{ id: 'team', rootPath: '/srv/team-worktrees' }], - sourcePreferences: { - builtIn: { claude: 'show', gsd: 'hide' }, - custom: { team: 'show' } - } - }) - store.flush() - const reloaded = await createStore() - expect(reloaded.getSettings().worktreeVisibilityDefaults).toEqual( - store.getSettings().worktreeVisibilityDefaults - ) - }) - - it('persists agent worktree visibility independently from external visibility', async () => { - const store = await createStore() - store.addRepo(makeRepo({ externalWorktreeVisibility: 'hide' })) - - const updated = store.updateRepo({ id: 'r1' }, { agentWorktreeVisibility: 'show' }) - - expect(updated).toMatchObject({ - externalWorktreeVisibility: 'hide', - agentWorktreeVisibility: 'show', - worktreeVisibilitySourcePreferences: { - builtIn: { claude: 'show', gsd: 'show' } - } - }) - - store.flush() - const reloaded = await createStore() - expect(reloaded.getRepo('r1')).toMatchObject({ - externalWorktreeVisibility: 'hide', - agentWorktreeVisibility: 'show', - worktreeVisibilitySourcePreferences: { - builtIn: { claude: 'show', gsd: 'show' } - } - }) - }) - - it('persists bounded custom worktree sources separately from their preferences', async () => { - const store = await createStore() - store.addRepo(makeRepo()) - - const updated = store.updateRepo( - { id: 'r1' }, - { - customWorktreeVisibilitySources: [ - { id: 'team', rootPath: ' /srv/team-worktrees ' }, - { id: 'invalid', rootPath: '../relative' } - ], - worktreeVisibilitySourcePreferences: { - builtIn: { claude: 'show', gsd: 'hide' }, - custom: { team: 'show' } - } - } - ) - - expect(updated).toMatchObject({ - customWorktreeVisibilitySources: [{ id: 'team', rootPath: '/srv/team-worktrees' }], - worktreeVisibilitySourcePreferences: { - builtIn: { claude: 'show', gsd: 'hide' }, - custom: { team: 'show' } - } - }) - - store.flush() - const reloaded = await createStore() - expect(reloaded.getRepo('r1')?.customWorktreeVisibilitySources).toEqual([ - { id: 'team', rootPath: '/srv/team-worktrees' } - ]) - }) - - it('clears an explicit external-worktree override without stamping an inherited default', async () => { - const store = await createStore() - store.addRepo( - makeRepo({ - externalWorktreeVisibility: 'show', - externalWorktreeVisibilityLegacy: true - }) - ) - - const updated = store.updateRepo({ id: 'r1' }, { externalWorktreeVisibility: null }) - - expect(updated?.externalWorktreeVisibility).toBeUndefined() - expect(updated?.externalWorktreeVisibilityLegacy).toBe(false) - store.flush() - const reloaded = await createStore() - expect(reloaded.getRepo('r1')?.externalWorktreeVisibility).toBeUndefined() - expect(reloaded.getRepo('r1')?.externalWorktreeVisibilityLegacy).toBe(false) - }) - - it('sanitizes raw custom worktree visibility sources on the read path', async () => { - const persisted = getDefaultPersistedState(testState.dir) - persisted.repos = [ - makeRepo({ - id: 'r1', - customWorktreeVisibilitySources: [ - { id: 'team', rootPath: ' /srv/team-worktrees ' }, - { id: 'invalid', rootPath: '../relative' } - ], - worktreeVisibilitySourcePreferences: { - builtIn: { claude: 'show', gsd: 'show' }, - custom: { team: 'show', missing: 'bogus' as unknown as ExternalWorktreeVisibility } - } - }) - ] - writeDataFile(persisted) - - const store = await createStore() - expect(store.getRepo('r1')).toMatchObject({ - customWorktreeVisibilitySources: [{ id: 'team', rootPath: '/srv/team-worktrees' }], - worktreeVisibilitySourcePreferences: { - builtIn: { claude: 'show', gsd: 'show' }, - custom: { team: 'show' } - } - }) - }) - - it('updateRepo clears source-control AI overrides independently from other clearable fields', async () => { - const store = await createStore() - store.addRepo( - makeRepo({ - issueSourcePreference: 'origin', - sourceControlAi: { - instructionsByOperation: { commitMessage: 'Repo style' }, - prCreationDefaults: { draft: true } - } - }) - ) - - store.updateRepo( - { id: 'r1' }, - { - issueSourcePreference: undefined, - sourceControlAi: undefined - } - ) - - expect(store.getRepo('r1')!.issueSourcePreference).toBeUndefined() - expect(store.getRepo('r1')!.sourceControlAi).toBeUndefined() - - store.flush() - const reloaded = await createStore() - expect(reloaded.getRepo('r1')!.issueSourcePreference).toBeUndefined() - expect(reloaded.getRepo('r1')!.sourceControlAi).toBeUndefined() - }) - - it('updateRepo treats source-control AI null as a transport clear sentinel', async () => { - const store = await createStore() - store.addRepo( - makeRepo({ - sourceControlAi: { - enabled: true, - customAgentCommand: 'repo-agent {prompt}' - } - }) - ) - - store.updateRepo( - { id: 'r1' }, - { - sourceControlAi: null - } - ) - - expect(store.getRepo('r1')!.sourceControlAi).toBeUndefined() - - store.flush() - const reloaded = await createStore() - expect(reloaded.getRepo('r1')!.sourceControlAi).toBeUndefined() - }) - - it('updateRepo normalizes source-control AI overrides before storing', async () => { - const store = await createStore() - store.addRepo(makeRepo()) - - const updated = store.updateRepo( - { id: 'r1' }, - { - sourceControlAi: { - instructionsByOperation: { - commitMessage: 'Repo style', - pullRequest: 42, - unknown: 'ignored' - }, - prCreationDefaults: { - draft: true, - useTemplate: null, - openAfterCreate: 'yes' - }, - modelOverridesByOperation: { - commitMessage: { - selectedModelByAgent: { codex: 'gpt-5.4', claude: false }, - selectedThinkingByModel: { 'gpt-5.4': 'high', bad: true } - }, - unknown: { - selectedModelByAgent: { codex: 'ignored' } - } - } - } as never - } - ) - - expect(updated!.sourceControlAi).toEqual({ - instructionsByOperation: { - commitMessage: 'Repo style' - }, - actionOverrides: { - commitMessage: { - commandInputTemplate: '{basePrompt}\n\nRepo style' - } - }, - prCreationDefaults: { - draft: true, - useTemplate: null - }, - modelOverridesByOperation: { - commitMessage: { - selectedModelByAgent: { codex: 'gpt-5.4' }, - selectedThinkingByModel: { 'gpt-5.4': 'high' } - } - } - }) - }) - - it('updateRepo ignores malformed source-control AI overrides without clearing existing overrides', async () => { - const store = await createStore() - store.addRepo( - makeRepo({ - sourceControlAi: { - instructionsByOperation: { commitMessage: 'Keep me' } - } - }) - ) - - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: feeds the sanitizer a value its type forbids, on purpose. - const updated = store.updateRepo({ id: 'r1' }, { sourceControlAi: 'bad' as never }) - - expect(updated!.sourceControlAi).toEqual({ - instructionsByOperation: { commitMessage: 'Keep me' }, - actionOverrides: { - commitMessage: { - commandInputTemplate: '{basePrompt}\n\nKeep me' - } - } - }) - }) }) diff --git a/src/main/persistence/tracking-repos/probeable-local-worktree-metadata-candidates.test.ts b/src/main/persistence/tracking-repos/probeable-local-worktree-metadata-candidates.test.ts deleted file mode 100644 index 635e4992f52..00000000000 --- a/src/main/persistence/tracking-repos/probeable-local-worktree-metadata-candidates.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultPersistedState } from '../../../shared/constants' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { Repo } from '../../../shared/repo-types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { - captureNativeLocalWorktreeMetadataScanExpectation, - pruneSessionlessMissingLocalWorktreeMetadataForRepo, - selectProbeableLocalWorktreeMetadataCandidates -} from './missing-local-worktree-metadata-pruning' - -const REPO_ID = 'repo-1' - -function makeRepo(): Repo { - return { - id: REPO_ID, - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0 - } -} - -function makeMeta(worktreeId: string, overrides: Partial = {}): WorktreeMeta { - return { - instanceId: `instance-${worktreeId}`, - hostId: 'local', - displayName: worktreeId, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - ...overrides - } -} - -function makeState(): PersistedState { - const state = getDefaultPersistedState('/home/test') - state.repos = [makeRepo()] - return state -} - -function probeableIds(state: PersistedState): string[] { - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - return selectProbeableLocalWorktreeMetadataCandidates(state, scan, 'linux').map( - ({ worktreeId }) => worktreeId - ) -} - -describe('selectProbeableLocalWorktreeMetadataCandidates', () => { - it('keeps an ordinary sessionless local row', () => { - const state = makeState() - const id = `${REPO_ID}::/workspace/gone` - state.worktreeMeta[id] = makeMeta(id) - - expect(probeableIds(state)).toEqual([id]) - }) - - it('drops a row a persisted session still pins', () => { - const state = makeState() - const pinned = `${REPO_ID}::/workspace/pinned` - const free = `${REPO_ID}::/workspace/free` - state.worktreeMeta[pinned] = makeMeta(pinned) - state.worktreeMeta[free] = makeMeta(free) - state.ui.lastActiveWorktreeId = pinned - - expect(probeableIds(state)).toEqual([free]) - }) - - it('drops a row whose locator is also known on a remote host', () => { - const state = makeState() - const shared = `${REPO_ID}::/workspace/shared` - const free = `${REPO_ID}::/workspace/free` - state.worktreeMeta[shared] = makeMeta(shared) - state.worktreeMeta[free] = makeMeta(free) - state.worktreeIdentityAliases = { [`ssh:box|${shared}`]: ['identity-1'] } - - expect(probeableIds(state)).toEqual([free]) - }) - - it('drops a row pinned to another execution host', () => { - const state = makeState() - const remote = `${REPO_ID}::/workspace/remote` - state.worktreeMeta[remote] = makeMeta(remote, { hostId: 'ssh:box' }) - - expect(probeableIds(state)).toEqual([]) - }) - - it('never widens what the authoritative prune would remove', () => { - const state = makeState() - const ids = [ - `${REPO_ID}::/workspace/free`, - `${REPO_ID}::/workspace/pinned`, - `${REPO_ID}::/workspace/remote` - ] - state.worktreeMeta[ids[0]] = makeMeta(ids[0]) - state.worktreeMeta[ids[1]] = makeMeta(ids[1]) - state.worktreeMeta[ids[2]] = makeMeta(ids[2], { hostId: 'ssh:box' }) - state.ui.lastActiveWorktreeId = ids[1] - - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - const selected = selectProbeableLocalWorktreeMetadataCandidates(state, scan, 'linux') - // Prefiltering must preserve the authoritative deletion verdict. - const removed = pruneSessionlessMissingLocalWorktreeMetadataForRepo( - state, - scan, - scan.metadata, - 'linux' - ) - - expect(selected.map(({ worktreeId }) => worktreeId)).toEqual(removed) - }) -}) diff --git a/src/main/persistence/tracking-repos/project-host-compatibility.test.ts b/src/main/persistence/tracking-repos/project-host-compatibility.test.ts deleted file mode 100644 index fc3fd7ba8bb..00000000000 --- a/src/main/persistence/tracking-repos/project-host-compatibility.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ProjectHostSetup } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' -import { mergeProjectHostSetupCompatibilityState } from './project-host-compatibility' - -const PROJECT_ID = 'github:acme/orca' - -function repo(overrides: Partial & Pick): Repo { - return { - path: `/src/${overrides.id}`, - displayName: 'orca', - addedAt: 1, - upstream: { owner: 'acme', repo: 'orca' }, - ...overrides - } as Repo -} - -function pendingSetup(overrides: Partial = {}): ProjectHostSetup { - return { - id: `${PROJECT_ID}::ssh:devbox`, - projectId: PROJECT_ID, - hostId: 'ssh:devbox', - repoId: '', - path: '', - displayName: 'orca', - setupState: 'not-set-up', - setupMethod: 'pending', - createdAt: 1, - updatedAt: 1, - ...overrides - } as ProjectHostSetup -} - -describe('mergeProjectHostSetupCompatibilityState', () => { - it('keeps a placeholder for a host with no repo yet', () => { - const merged = mergeProjectHostSetupCompatibilityState( - { projects: [], projectHostSetups: [pendingSetup()] }, - [repo({ id: 'local-repo' })] - ) - - expect(merged.projectHostSetups.map((setup) => setup.hostId)).toEqual(['local', 'ssh:devbox']) - }) - - // Ready repo projections must displace same-project/host placeholders or they shadow setup state. - it('drops a placeholder once a repo covers the same project and host', () => { - const merged = mergeProjectHostSetupCompatibilityState( - { projects: [], projectHostSetups: [pendingSetup()] }, - [repo({ id: 'local-repo' }), repo({ id: 'devbox-repo', executionHostId: 'ssh:devbox' })] - ) - - expect(merged.projectHostSetups).toHaveLength(2) - expect(merged.projectHostSetups.every((setup) => setup.setupState === 'ready')).toBe(true) - expect(merged.projectHostSetups.map((setup) => setup.id)).toEqual(['local-repo', 'devbox-repo']) - }) - - it('keeps the placeholder when the repo covers a different host', () => { - const merged = mergeProjectHostSetupCompatibilityState( - { projects: [], projectHostSetups: [pendingSetup({ hostId: 'ssh:other' })] }, - [repo({ id: 'devbox-repo', executionHostId: 'ssh:devbox' })] - ) - - expect(merged.projectHostSetups.map((setup) => setup.hostId)).toEqual([ - 'ssh:devbox', - 'ssh:other' - ]) - }) -}) diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-write.test.ts b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-write.test.ts index 5ad8ee3934f..b4c69d45ce3 100644 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-write.test.ts +++ b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-write.test.ts @@ -55,35 +55,4 @@ describe('chat appearance write queue', () => { fontSize: 15 }) }) - - it('consumes chat size actions without changing saved size while terminal matching is active', async () => { - const updateSettings = vi.fn(async (updates: Partial) => { - mock.state.settings = { ...mock.state.settings!, ...updates } - }) - mock.state.updateSettings = updateSettings - mock.state.settings = { - ...getDefaultSettings('/tmp'), - nativeChatAppearance: { - fontSize: 18, - codeFontSize: 16, - contrast: 125, - matchTerminalInterface: true - } - } - await writeNativeChatFontSize('increase') - await writeNativeChatFontSize('decrease') - await writeNativeChatFontSize('reset') - expect(updateSettings).not.toHaveBeenCalled() - expect(mock.state.settings.nativeChatAppearance?.fontSize).toBe(18) - mock.state.settings = { - ...mock.state.settings, - nativeChatAppearance: { - ...mock.state.settings.nativeChatAppearance, - matchTerminalInterface: false - } - } - await writeNativeChatFontSize('increase') - expect(updateSettings).toHaveBeenCalledTimes(1) - expect(mock.state.settings.nativeChatAppearance?.fontSize).toBe(19) - }) }) diff --git a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts index 07cc26a7062..fe785068cb5 100644 --- a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts +++ b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts @@ -3,9 +3,8 @@ import type { ParsedTerminalFileLink } from '../../../../../../shared/terminal/l import type * as FileLinkTargetModule from '@/components/terminal-pane/links/files/terminal-file-link-target' import type { FileLinkPathExistence } from '@/components/terminal-pane/links/files/terminal-file-link-target' import type * as FilePathMappingModule from '@/components/terminal-pane/host-files/terminal-file-path-mapping' -import { RECENT_PATH_ANSWERS_MAX } from '../../../../../../shared/recent-path-answers' + import { createNativeChatFileLinkExistence } from './native-chat-file-link-existence' -import { UNVERIFIABLE_RETRY_DELAYS_MS } from '../../../../../../shared/native-chat/native-chat-file-link-existence' const connection = vi.hoisted(() => ({ resolved: true, @@ -91,43 +90,6 @@ describe('createNativeChatFileLinkExistence', () => { connection.currentOwnerResolved = true }) - it('links a path the turn created once the turn ends, without re-rendering first', async () => { - let created = false - const { asked, pathExists } = hostWith(() => created) - const existence = createNativeChatFileLinkExistence(host, pathExists) - const { watcher, onChange } = watching(existence) - watcher.getSnapshot().check(link('src/new.ts')) - await settle() - - created = true - existence.recheck() - expect(onChange).not.toHaveBeenCalled() - await settle() - - expect(asked).toEqual(['/repo/src/new.ts', '/repo/src/new.ts']) - expect(onChange).toHaveBeenCalledOnce() - expect(watcher.getSnapshot().check(link('src/new.ts'))).toBe(true) - }) - - it('removes the underline of a confirmed path deleted during the turn', async () => { - let deleted = false - const { pathExists } = hostWith(() => !deleted) - const existence = createNativeChatFileLinkExistence(host, pathExists) - const { watcher, onChange } = watching(existence) - watcher.getSnapshot().check(link('src/old.ts')) - await settle() - expect(watcher.getSnapshot().check(link('src/old.ts'))).toBe(true) - - deleted = true - existence.recheck() - // Why: the old answer keeps showing until the host replies, so nothing flickers. - expect(watcher.getSnapshot().check(link('src/old.ts'))).toBe(true) - await settle() - - expect(onChange).toHaveBeenCalledTimes(2) - expect(watcher.getSnapshot().check(link('src/old.ts'))).toBe(false) - }) - it('shows an answer that landed between a message rendering and subscribing', async () => { const { pathExists } = hostWith(() => true) const existence = createNativeChatFileLinkExistence(host, pathExists) @@ -145,48 +107,6 @@ describe('createNativeChatFileLinkExistence', () => { expect(pathExists).toHaveBeenCalledOnce() }) - it('asks again on subscribe when the host failed before the message subscribed', async () => { - vi.useFakeTimers() - let reachable = false - const { pathExists } = hostWith(() => (reachable ? true : new Error('SSH connection closed'))) - const existence = createNativeChatFileLinkExistence(host, pathExists) - const late = existence.watch() - late.getSnapshot().check(link('src/App.tsx')) - await settle() - // Why: nothing showed the path yet, so no retry was armed for it. - expect(vi.getTimerCount()).toBe(0) - - reachable = true - const onChange = vi.fn() - late.subscribe(onChange) - await settle() - - expect(pathExists).toHaveBeenCalledTimes(2) - expect(onChange).toHaveBeenCalledOnce() - expect(late.getSnapshot().check(link('src/App.tsx'))).toBe(true) - }) - - it('keeps every answer a shown message needs, past the unobserved cache limit', async () => { - const { pathExists } = hostWith(() => true) - const existence = createNativeChatFileLinkExistence(host, pathExists) - const { watcher } = watching(existence) - const names = Array.from( - { length: RECENT_PATH_ANSWERS_MAX + 100 }, - (_, index) => `file-${index}.md` - ) - const render = (): boolean[] => names.map((name) => watcher.getSnapshot().check(link(name))) - - render() - await settle() - expect(render().every(Boolean)).toBe(true) - await settle() - expect(pathExists).toHaveBeenCalledTimes(names.length) - - existence.recheck() - await settle() - expect(pathExists).toHaveBeenCalledTimes(names.length * 2) - }) - it('keeps a reply to an older question from overwriting a newer answer', async () => { const replies: ((exists: boolean) => void)[] = [] const pathExists = vi.fn( @@ -207,43 +127,4 @@ describe('createNativeChatFileLinkExistence', () => { expect(watcher.getSnapshot().check(link('src/new.ts'))).toBe(true) }) - - it('links a path once a host that could not answer comes back, without a remount', async () => { - vi.useFakeTimers() - let reachable = false - const { pathExists } = hostWith(() => (reachable ? true : new Error('SSH connection closed'))) - const { watcher, onChange } = watching(createNativeChatFileLinkExistence(host, pathExists)) - - watcher.getSnapshot().check(link('src/App.tsx')) - await settle() - // Why: re-renders while the host is down must not ask again; the retry owns that. - watcher.getSnapshot().check(link('src/App.tsx')) - await settle() - expect(pathExists).toHaveBeenCalledOnce() - expect(onChange).not.toHaveBeenCalled() - - reachable = true - await vi.advanceTimersByTimeAsync(UNVERIFIABLE_RETRY_DELAYS_MS[0]) - - expect(pathExists).toHaveBeenCalledTimes(2) - expect(onChange).toHaveBeenCalledOnce() - expect(watcher.getSnapshot().check(link('src/App.tsx'))).toBe(true) - }) - - it('keeps the shown answer when the host cannot answer a recheck', async () => { - let reachable = true - const { pathExists } = hostWith(() => (reachable ? true : new Error('SSH connection closed'))) - const existence = createNativeChatFileLinkExistence(host, pathExists) - const { watcher, onChange } = watching(existence) - watcher.getSnapshot().check(link('src/App.tsx')) - await settle() - onChange.mockClear() - - reachable = false - existence.recheck() - await settle() - - expect(onChange).not.toHaveBeenCalled() - expect(watcher.getSnapshot().check(link('src/App.tsx'))).toBe(true) - }) }) diff --git a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link.test.ts b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link.test.ts deleted file mode 100644 index f986ad78eb5..00000000000 --- a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { createNativeChatFileHref } from '../../../../../../shared/native-chat/native-chat-href-routing' -import { resolveNativeChatFileLink } from './native-chat-file-link' -import type { NativeChatFileLinkContext } from './native-chat-file-link-context' - -const context: NativeChatFileLinkContext = { - worktreeId: 'wt-1', - worktreePath: '/repo/worktree', - runtimeEnvironmentId: null -} - -describe('resolveNativeChatFileLink', () => { - it.each([ - ['/repo/report:12', '/repo/report:12'], - ['/repo/report:0', '/repo/report:0'], - ['/repo/report:12:4', '/repo/report:12:4'], - ['/repo/ leading ', '/repo/ leading '], - [' leading ', '/repo/worktree/ leading '], - ['notes%23?#.md', '/repo/worktree/notes%23?#.md'], - ['https:notes.md', '/repo/worktree/https:notes.md'], - ['file:notes.md', '/repo/worktree/file:notes.md'], - ['../sibling/readme.md', '/repo/sibling/readme.md'] - ])('resolves literal tool path %j without parsing a reply location', (path, absolutePath) => { - expect(resolveNativeChatFileLink(createNativeChatFileHref(path, 'literal'), context)).toEqual({ - absolutePath, - line: null, - column: null - }) - }) - - it('reads URL-style /D:/ targets as the drive only in a Windows workspace', () => { - const windowsContext = { ...context, worktreePath: 'D:/repo' } - for (const href of ['/D:/Temp/report.txt', createNativeChatFileHref('/D:/Temp/report.txt')]) { - expect(resolveNativeChatFileLink(href, windowsContext)?.absolutePath).toBe( - 'D:/Temp/report.txt' - ) - } - expect( - resolveNativeChatFileLink( - createNativeChatFileHref('/D:/Temp/report.txt', 'literal'), - windowsContext - )?.absolutePath - ).toBe('D:/Temp/report.txt') - expect( - resolveNativeChatFileLink('//server/share/report.txt', windowsContext)?.absolutePath - ).toBe('//server/share/report.txt') - expect(resolveNativeChatFileLink('/D:/Temp/report.txt', context)?.absolutePath).toBe( - '/D:/Temp/report.txt' - ) - }) -}) diff --git a/src/renderer/src/components/native-chat/links/actions/use-native-chat-link-actions.test.tsx b/src/renderer/src/components/native-chat/links/actions/use-native-chat-link-actions.test.tsx deleted file mode 100644 index 39516674de9..00000000000 --- a/src/renderer/src/components/native-chat/links/actions/use-native-chat-link-actions.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -// @vitest-environment happy-dom -import type { ReactNode } from 'react' -import { useRef } from 'react' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { LinkActionPopover } from '@/components/link-actions/LinkActionPopover' -import CommentMarkdown from '@/components/sidebar/CommentMarkdown' -import { useNativeChatLinkActions } from './use-native-chat-link-actions' -import type * as HttpLinkRoutingModule from '@/lib/browser/navigation/http-link-routing' - -const mocks = vi.hoisted(() => ({ - openHttpLink: vi.fn(), - openFileLink: vi.fn(), - settings: { openLinksInApp: true, terminalLinkActionPopoverEnabled: true } as { - openLinksInApp?: boolean - terminalLinkActionPopoverEnabled?: boolean - } -})) - -vi.mock('@/lib/browser/navigation/http-link-routing', async (importOriginal) => ({ - ...(await importOriginal()), - openHttpLink: mocks.openHttpLink -})) - -vi.mock('./native-chat-http-link-source-owner', () => ({ - resolveNativeChatHttpLinkSourceOwner: () => ({ kind: 'local' }), - canNativeChatOpenOwnedBrowser: () => false -})) - -vi.mock('./use-native-chat-file-link-click', () => ({ - useNativeChatFileLinkClick: (context: unknown) => (context ? mocks.openFileLink : undefined) -})) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: Record) => unknown) => - selector({ openSettingsPage: vi.fn(), openSettingsTarget: vi.fn() }), - { getState: () => ({ settings: mocks.settings }) } - ) -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => children, - TooltipTrigger: ({ children }: { children: ReactNode }) => children, - TooltipContent: ({ children }: { children: ReactNode }) => {children} -})) - -vi.mock('@/components/ui/popover', () => ({ - Popover: ({ children, open }: { children: ReactNode; open: boolean }) => - open ?
{children}
: null, - PopoverAnchor: () => null, - PopoverContent: ({ children }: { children: ReactNode }) =>
{children}
-})) - -const context = { worktreeId: 'wt-1', worktreePath: '/repo', runtimeEnvironmentId: null } - -function Transcript({ - markdown, - sessionId = 'session-1', - isVisible = true, - linkContext = context -}: { - markdown: string - sessionId?: string - isVisible?: boolean - linkContext?: typeof context | null -}): React.JSX.Element { - const rootRef = useRef(null) - const { onLinkClick, linkActionRequest, closeLinkActions } = useNativeChatLinkActions( - linkContext, - rootRef, - { sessionId, isVisible } - ) - return ( -
- - -
- ) -} - -afterEach(() => { - cleanup() - vi.clearAllMocks() - mocks.settings = { openLinksInApp: true, terminalLinkActionPopoverEnabled: true } -}) - -describe('native chat transcript links', () => { - it('keeps mailto links on the anchor default', async () => { - const { container } = render() - const anchorDefault = vi.fn((event: Event) => { - expect(event.defaultPrevented).toBe(false) - event.preventDefault() - }) - container.addEventListener('click', anchorDefault) - fireEvent.click(await screen.findByRole('link', { name: 'email' })) - expect(anchorDefault).toHaveBeenCalledOnce() - expect(mocks.openHttpLink).not.toHaveBeenCalled() - expect(mocks.openFileLink).not.toHaveBeenCalled() - expect(screen.queryByText('System Browser')).toBeNull() - }) - - it('restores focus to the clicked transcript link', async () => { - render() - const anchor = await screen.findByRole('link', { name: 'link' }) - fireEvent.click(anchor) - fireEvent.click(screen.getByText('System Browser')) - expect(document.activeElement).toBe(anchor) - }) -}) diff --git a/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts b/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts index 432de95ccaf..a6c2ff5284f 100644 --- a/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts +++ b/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts @@ -2,39 +2,6 @@ import { describe, expect, it } from 'vitest' import { createHoverPreviewCache } from './native-chat-hover-preview-cache' describe('createHoverPreviewCache', () => { - it('drops the oldest answers once their total size passes the budget', async () => { - const cache = createHoverPreviewCache({ - freshMs: 60_000, - maxEntries: 100, - budget: { maxBytes: 10, sizeOf: (value) => value.length } - }) - await cache.load('a', async () => 'aaaa') - await cache.load('b', async () => 'bbbb') - await cache.load('c', async () => 'cccc') - - expect(cache.read('a')).toBeNull() - expect(cache.read('b')).toBe('bbbb') - expect(cache.read('c')).toBe('cccc') - }) - - it('stays within the budget when an older request finishes last', async () => { - const cache = createHoverPreviewCache({ - freshMs: 60_000, - maxEntries: 100, - budget: { maxBytes: 10, sizeOf: (value) => value.length } - }) - let finishSlow: (value: string) => void = () => {} - const slow = cache.load('slow', () => new Promise((resolve) => (finishSlow = resolve))) - await cache.load('b', async () => 'bbbb') - await cache.load('c', async () => 'cccc') - finishSlow('ssss') - await slow - - expect(cache.read('slow')).toBe('ssss') - expect(cache.read('b')).toBeNull() - expect(cache.read('c')).toBe('cccc') - }) - it('keeps the last answer through a reread that fails, and rereads past one started earlier', async () => { const cache = createHoverPreviewCache({ freshMs: 60_000, maxEntries: 100 }) await cache.load('pr', async () => 'closed') @@ -55,20 +22,4 @@ describe('createHoverPreviewCache', () => { await cache.load('pr', async () => null) expect(cache.read('pr')).toBe('open') }) - - it('keeps counting an answer against the budget while it is reread', async () => { - const cache = createHoverPreviewCache({ - freshMs: 60_000, - maxEntries: 100, - budget: { maxBytes: 10, sizeOf: (value) => value.length } - }) - await cache.load('a', async () => 'aaaaaa') - cache.expire('a') - let failA: (value: null) => void = () => {} - const reread = cache.load('a', () => new Promise((resolve) => (failA = resolve))) - await cache.load('b', async () => 'bbbbbb') - failA(null) - await reread - expect([cache.read('a'), cache.read('b')]).toEqual([null, 'bbbbbb']) - }) }) diff --git a/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.mermaid.test.tsx b/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.mermaid.test.tsx index 059a85be62f..0dbc318df34 100644 --- a/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.mermaid.test.tsx +++ b/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.mermaid.test.tsx @@ -36,9 +36,6 @@ import { NativeChatMarkdown } from './NativeChatMarkdown' import { NativeChatCodeBlock } from './code/NativeChatCodeBlock' import { TooltipProvider } from '@/components/ui/tooltip' -const partial = 'flowchart TD\n A["Sync with main ' -const complete = `${partial}once"]` - function reply(source: string, streaming: boolean): React.JSX.Element { return ( @@ -104,35 +101,4 @@ describe('native chat Mermaid fences', () => { expect(container.querySelector('svg')).toHaveTextContent('Finished') expect(container.querySelector('[data-code-language="mermaid"]')).toBeNull() }) - - it('keeps the source mounted until a pending diagram fails', async () => { - const pending = holdNextRender() - const view = render(reply(partial, true)) - const source = view.container.querySelector('pre') - view.rerender(reply(partial, false)) - await waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(1)) - expect(view.container.querySelector('pre')).toBe(source) - expect(screen.queryByText(/Diagram error:/)).toBeNull() - await act(async () => pending.reject(new Error('Invalid mermaid syntax'))) - expect(screen.getByText(/Diagram error: Invalid mermaid syntax/)).toBeInTheDocument() - expect(view.container.querySelector('pre')?.textContent).toBe(partial.trimEnd()) - }) - - it('waits for the updated diagram when a previously rendered fence grows again', async () => { - const view = render(reply(complete, false)) - await waitFor(() => - expect(view.container.querySelector('.mermaid-block svg')).toBeInTheDocument() - ) - const next = `${complete}\n B["Next step"]` - view.rerender(reply(next, true)) - const source = view.container.querySelector('pre') - expect(source).toHaveTextContent('Next step') - const pending = holdNextRender() - view.rerender(reply(next, false)) - await waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(2)) - expect(view.container.querySelector('pre')).toBe(source) - expect(view.container.querySelector('.mermaid-block svg')).toBeNull() - await act(async () => pending.resolve({ svg: 'Next step' })) - expect(view.container.querySelector('.mermaid-block svg')).toHaveTextContent('Next step') - }) }) diff --git a/src/renderer/src/components/native-chat/markdown/NativeChatPacedMarkdown.mermaid.test.tsx b/src/renderer/src/components/native-chat/markdown/NativeChatPacedMarkdown.mermaid.test.tsx deleted file mode 100644 index b705462f6e9..00000000000 --- a/src/renderer/src/components/native-chat/markdown/NativeChatPacedMarkdown.mermaid.test.tsx +++ /dev/null @@ -1,77 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { NativeChatPacedMarkdown } from './NativeChatPacedMarkdown' -import { NativeChatReplyRevealsContext } from './native-chat-reply-reveals' -import type { NativeChatReplyReveals } from '../../../../../shared/native-chat/transcript/native-chat-reply-reveals' -import { NATIVE_CHAT_TEXT_REVEAL_DELAY_MS } from '../../../../../shared/native-chat/transcript/native-chat-text-reveal' - -const reveals: NativeChatReplyReveals = { begun: new Set(['reply']), drawn: new Map() } - -const mermaid = vi.hoisted(() => ({ rendered: vi.fn() })) -vi.mock('@/components/sidebar/CommentMermaidBlock', () => ({ - default: ({ - content: code, - pendingContent, - renderEnabled - }: { - content: string - pendingContent?: React.ReactNode - renderEnabled?: boolean - }) => { - if (renderEnabled === false) { - return <>{pendingContent} - } - mermaid.rendered(code) - return
{code}
- } -})) -vi.mock('@/hooks/usePrefersReducedMotion', () => ({ usePrefersReducedMotion: () => false })) -vi.mock('../media/visuals/native-chat-visual-markdown-extension', () => ({ - useNativeChatVisualMarkdownExtension: () => undefined -})) - -afterEach(() => { - cleanup() - vi.useRealTimers() - mermaid.rendered.mockClear() - reveals.drawn.clear() -}) - -it('keeps surrounding paragraphs, links, and code mounted when Mermaid switches to a diagram', () => { - vi.useFakeTimers({ - toFake: [ - 'setTimeout', - 'clearTimeout', - 'requestAnimationFrame', - 'cancelAnimationFrame', - 'performance' - ] - }) - const content = - 'Read [this](https://example.com).\n\n```ts\nconst value = 1\n```\n\n```mermaid\ngraph TD\nA --> B\n```' - const reply = (streaming: boolean) => ( - - - - ) - const view = render(reply(true)) - act(() => vi.advanceTimersByTime(NATIVE_CHAT_TEXT_REVEAL_DELAY_MS + 16)) - const paragraph = view.container.querySelector('p') - const code = view.container.querySelector('pre') - const link = view.getByRole('link') - expect(paragraph).not.toBeNull() - expect(code).not.toBeNull() - expect(mermaid.rendered).not.toHaveBeenCalled() - view.rerender(reply(false)) - expect(view.getByTestId('diagram')).toBeTruthy() - expect(view.container.querySelector('p')).toBe(paragraph) - expect(view.container.querySelector('pre')).toBe(code) - expect(view.getByRole('link')).toBe(link) - expect(view.container.querySelector('[data-block-fade]')).toBeNull() -}) diff --git a/src/renderer/src/components/native-chat/markdown/code/NativeChatCodeBlock.test.tsx b/src/renderer/src/components/native-chat/markdown/code/NativeChatCodeBlock.test.tsx index 47f798df570..d12a20ba097 100644 --- a/src/renderer/src/components/native-chat/markdown/code/NativeChatCodeBlock.test.tsx +++ b/src/renderer/src/components/native-chat/markdown/code/NativeChatCodeBlock.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { cleanup, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { NativeChatCodeBlock } from './NativeChatCodeBlock' @@ -37,29 +37,4 @@ describe('NativeChatCodeBlock', () => { expect(screen.getByText('lastLine')).toBeInTheDocument() expect(second.container.querySelector('pre')?.textContent).toBe(code) }) - - it('colors and wraps fenced code, copies its text, and confirms success', async () => { - const writeClipboardText = vi.fn().mockResolvedValue(undefined) - Object.assign(window, { api: { ui: { writeClipboardText } } }) - const code = 'const answer = 42\nconsole.log(answer)\n' - const { container } = render( - - {code} - - ) - const pre = container.querySelector('pre') - expect(screen.getByText('TypeScript')).toBeInTheDocument() - await waitFor(() => expect(pre?.querySelector('span[style*="--syntax-dark"]')).not.toBeNull(), { - timeout: 10_000 - }) - - fireEvent.click(screen.getByRole('button', { name: 'Wrap lines' })) - - expect(pre).toHaveClass('whitespace-pre-wrap') - expect(pre?.querySelector('span[style*="--syntax-dark"]')).not.toBeNull() - expect(pre?.textContent).toBe(code) - fireEvent.click(screen.getByRole('button', { name: 'Copy code' })) - await waitFor(() => expect(writeClipboardText).toHaveBeenCalledWith(code)) - expect(await screen.findByRole('button', { name: 'Copied' })).toBeInTheDocument() - }) }) diff --git a/src/renderer/src/components/native-chat/markdown/code/NativeChatMarkdown.code-wrap.test.tsx b/src/renderer/src/components/native-chat/markdown/code/NativeChatMarkdown.code-wrap.test.tsx index c0732923467..f0104e331ca 100644 --- a/src/renderer/src/components/native-chat/markdown/code/NativeChatMarkdown.code-wrap.test.tsx +++ b/src/renderer/src/components/native-chat/markdown/code/NativeChatMarkdown.code-wrap.test.tsx @@ -21,7 +21,7 @@ import { NativeChatDisclosureContext, useNativeChatDisclosures } from '../../native-chat-disclosure-store' -import { NativeChatNoticeRow } from '../../NativeChatNoticeRow' + import { NativeChatReasoningRow } from '../../NativeChatReasoningRow' vi.mock('@/lib/syntax-highlighting/oniguruma', async () => ({ @@ -86,45 +86,6 @@ describe('native chat code block line wrap', () => { expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true') }) - it('keeps each block of a row to its own wrap', () => { - const content = '```ts\nconst first = 1\n```\n\n```ts\nconst second = 2\n```' - render() - - fireEvent.click(screen.getAllByRole('button', { name: 'Wrap lines' })[1]) - - expect(screen.getAllByRole('button', { name: /^(Wrap lines|Disable line wrap)$/ })).toEqual([ - screen.getByRole('button', { name: 'Wrap lines' }), - screen.getByRole('button', { name: 'Disable line wrap' }) - ]) - }) - - // Streaming escape fixes can shift a fence’s source offset when the finished block is reparsed. - it.each([ - [ - 'the reply finishes', - '1. Undo with git reset HEAD~1:\n ```sh\n git status\n ```\n', - (content: string) => ({ content, growing: false }) - ], - [ - 'another block follows a list item', - '- >5 users need x~y:\n ```sh\n scale up\n ```\n', - (content: string) => ({ content: `${content}\nDone.`, growing: true }) - ], - [ - 'the reply merges into one block', - 'Undo with git reset HEAD~1 first.\n\n```sh\ngit status\n```\n\nThen press ', - (content: string) => ({ content: `${content}Enter`, growing: true }) - ] - ])('stays on when %s after streaming escaped text before it', (_name, content, next) => { - const view = render() - fireEvent.click(wrapToggle()) - expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true') - - view.rerender() - - expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true') - }) - it('keeps a reasoning block and the reply of one message apart', () => { const fence = '```ts\nconst first = 1\n```' function Row(): React.JSX.Element { @@ -153,31 +114,4 @@ describe('native chat code block line wrap', () => { expect(reasoningWrap).toHaveAttribute('aria-pressed', 'false') expect(replyWrap).toHaveAttribute('aria-pressed', 'true') }) - - it("keeps a plan card's wrap when its row remounts", () => { - function Row({ mounted }: { mounted: boolean }): React.JSX.Element { - const disclosures = useNativeChatDisclosures() - return ( - - {mounted ? ( - - ) : null} - - ) - } - const view = render() - fireEvent.click(wrapToggle()) - - view.rerender() - view.rerender() - - expect(wrapToggle()).toHaveAttribute('aria-pressed', 'true') - }) }) diff --git a/src/renderer/src/components/native-chat/markdown/use-native-chat-paced-text.remount.test.tsx b/src/renderer/src/components/native-chat/markdown/use-native-chat-paced-text.remount.test.tsx index 1cd4ca44373..d54882bccf1 100644 --- a/src/renderer/src/components/native-chat/markdown/use-native-chat-paced-text.remount.test.tsx +++ b/src/renderer/src/components/native-chat/markdown/use-native-chat-paced-text.remount.test.tsx @@ -4,7 +4,7 @@ import type { ReactNode } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { NativeChatReplyRevealsContext } from './native-chat-reply-reveals' import type { NativeChatReplyReveals } from '../../../../../shared/native-chat/transcript/native-chat-reply-reveals' -import { NATIVE_CHAT_TEXT_REVEAL_DELAY_MS as D } from '../../../../../shared/native-chat/transcript/native-chat-text-reveal' + import { useNativeChatPacedText } from './use-native-chat-paced-text' const motion = vi.hoisted(() => ({ reduced: false })) @@ -64,34 +64,4 @@ describe('fixed latency text reveal', () => { advance(50) expect(returned.result.current.text).toHaveLength(2000) }) - - it('shows text received while unmounted immediately rather than resetting its deadline', () => { - const wrapper = within() - const row = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(100), true), { - wrapper - }) - advance(50) - row.unmount() - advance(D) - const returned = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(2000), true), { - wrapper - }) - expect(returned.result.current.text).toHaveLength(4000) - }) - - it('shows reduced-motion text immediately without fading or replay on remount', () => { - motion.reduced = true - const wrapper = within() - const row = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(1000), true), { - wrapper - }) - expect(row.result.current.text).toHaveLength(2000) - expect(row.result.current.fading).toBe(false) - row.unmount() - motion.reduced = false - const returned = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(1000), true), { - wrapper - }) - expect(returned.result.current.text).toHaveLength(2000) - }) }) diff --git a/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.image-preview.test.tsx b/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.image-preview.test.tsx index ec7afa4cdc7..fda39c86fe8 100644 --- a/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.image-preview.test.tsx +++ b/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.image-preview.test.tsx @@ -2,17 +2,14 @@ import '@testing-library/jest-dom/vitest' import { useRef, type ComponentProps } from 'react' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' -import userEvent from '@testing-library/user-event' + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { LinkActionPopover } from '@/components/link-actions/LinkActionPopover' import { TooltipProvider } from '@/components/ui/tooltip' import '@/components/editor/document-images/useLocalImageSrc' -import { - invalidateLocalImageCache as invalidateLocalImageSrcCacheForTests, - resetLocalImageCacheState as resetLocalImageSrcStateForTests -} from '@/components/editor/document-images/local-image-src-cache' +import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '@/components/editor/document-images/local-image-src-cache' import { useAppStore } from '@/store' -import * as imageCache from '@/components/editor/document-images/local-image-src-cache' + import { NativeChatMarkdown } from '../../markdown/NativeChatMarkdown' import { NativeChatMarkdownImageOwnerContext, @@ -28,8 +25,6 @@ import { import type * as TerminalFileOpenRouting from '@/components/terminal-pane/links/files/terminal-file-open-routing' import type * as HttpLinkRouting from '@/lib/browser/navigation/http-link-routing' -import * as imageCachePinning from '@/components/editor/document-images/local-image-cache-pinning' -import { ImageVisibilityObserver } from './native-chat-image-visibility-observer.test-fixture' import { NativeChatLinkClickContext } from '../../links/actions/native-chat-link-click-context' const mocks = vi.hoisted(() => ({ @@ -236,176 +231,6 @@ describe('native chat Markdown image preview', () => { } }) - it('loads only visible nearby images and keeps their bytes when they leave the viewport', async () => { - vi.stubGlobal('IntersectionObserver', ImageVisibilityObserver) - const { rerender } = render() - const trigger = screen.getByRole('button', { name: 'View image: Chart' }) - act(() => ImageVisibilityObserver.current.emit(trigger, true)) - expect(mocks.readRuntimeFilePreview).not.toHaveBeenCalled() - rerender() - expect(await screen.findByRole('img')).toHaveAttribute('src', 'blob:image-1') - vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 640, 360)) - act(() => ImageVisibilityObserver.current.emit(trigger, false)) - expect(screen.queryByRole('img')).toBeNull() - expect(trigger).toHaveStyle({ width: '640px', aspectRatio: '640 / 360' }) - act(() => ImageVisibilityObserver.current.emit(trigger, true)) - const returned = await screen.findByRole('img') - expect(returned).toHaveAttribute('src', 'blob:image-1') - fireEvent.load(returned) - expect(trigger.style.width).toBe('') - rerender() - expect(screen.queryByRole('img')).toBeNull() - expect(trigger).toHaveStyle({ width: '640px', aspectRatio: '640 / 360' }) - rerender() - expect(await screen.findByRole('img')).toHaveAttribute('src', 'blob:image-1') - expect(mocks.readRuntimeFilePreview).toHaveBeenCalledOnce() - expect(URL.revokeObjectURL).not.toHaveBeenCalled() - }) - - it('retries a cache-byte-budget rejection on open after another image releases its lease', async () => { - vi.stubGlobal('IntersectionObserver', ImageVisibilityObserver) - imageCachePinning.pinLocalImageCacheKey('reserved') - expect(imageCache.cacheLocalImageBlob('reserved', 'blob:reserved', 2 ** 27 - 2)).toBe(true) - const content = [0, 1, 2].map((i) => `![Chart ${i}](chart-${i}.png)`).join('\n\n') - const { container } = render() - const triggers = screen.getAllByRole('button') - expect(mocks.readRuntimeFilePreview).not.toHaveBeenCalled() - await act(async () => { - for (const trigger of triggers) { - ImageVisibilityObserver.current.emit(trigger, true) - } - }) - expect(container.querySelectorAll('img')).toHaveLength(2) - expect(mocks.readRuntimeFilePreview).toHaveBeenCalledTimes(3) - act(() => ImageVisibilityObserver.current.emit(triggers[0]!, false)) - fireEvent.click(triggers[2]!) - const dialog = screen.getByRole('dialog', { name: 'Chart 2' }) - expect(await within(dialog).findByRole('img')).toHaveAttribute('src', 'blob:image-4') - expect(mocks.readRuntimeFilePreview).toHaveBeenCalledTimes(4) - fireEvent.click(within(dialog).getByRole('button', { name: 'Close' })) - act(() => { - for (const trigger of triggers) { - ImageVisibilityObserver.current.emit(trigger, false) - } - }) - expect(container.querySelectorAll('img')).toHaveLength(0) - imageCache.unpinLocalImageCache('reserved') - }) - - it('closes stale previews when session metadata resolves or the session changes', () => { - const { rerender } = render() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - expect(screen.getByRole('dialog')).toBeInTheDocument() - rerender() - expect(screen.queryByRole('dialog')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - rerender() - expect(screen.queryByRole('dialog')).toBeNull() - }) - - it('keeps a streamed image dialog mounted when later prose arrives', async () => { - const content = '![Chart](data:image/png;base64,AA==)\n\n' - const { rerender } = render() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - const dialog = screen.getByRole('dialog', { name: 'Chart' }) - rerender() - expect(screen.getByRole('dialog', { name: 'Chart' })).toBe(dialog) - }) - - it('retains a closable unavailable preview after image decoding fails', async () => { - render() - await screen.findByRole('img', { name: 'Chart' }) - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - const dialog = screen.getByRole('dialog') - fireEvent.error(within(dialog).getByRole('img')) - expect(within(dialog).getByRole('status')).toHaveTextContent('Preview unavailable') - expect(within(dialog).getByRole('button', { name: 'File actions' })).toBeInTheDocument() - fireEvent.click(within(dialog).getByRole('button', { name: 'Close' })) - expect(screen.queryByRole('dialog')).toBeNull() - }) - - it('recovers from a failed thumbnail when refreshed image bytes become available', async () => { - render() - fireEvent.error(await screen.findByRole('img', { name: 'Chart' })) - expect(screen.queryByRole('img', { name: 'Chart' })).toBeNull() - act(() => invalidateLocalImageSrcCacheForTests()) - expect(await screen.findByRole('img', { name: 'Chart' })).toHaveAttribute('src', 'blob:image-2') - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - expect(within(screen.getByRole('dialog')).getByRole('img')).toHaveAttribute( - 'src', - 'blob:image-2' - ) - }) - - it('dismisses the nested file menu before the dialog and runs an action after preview closes', async () => { - const user = userEvent.setup() - render( - <> - - - - ) - await user.click(screen.getByRole('button', { name: 'View image: Chart' })) - const trigger = screen.getByRole('button', { name: 'File actions' }) - await user.click(trigger) - expect(screen.getByRole('menuitem', { name: 'Open file' })).toBeInTheDocument() - await user.keyboard('{Escape}') - expect(screen.queryByRole('menu')).toBeNull() - expect(screen.getByRole('dialog', { name: 'Chart' })).toBeInTheDocument() - expect(trigger).toHaveFocus() - await user.click(trigger) - mocks.openDetectedFilePath.mockImplementationOnce(() => { - expect(screen.queryByRole('dialog')).toBeNull() - screen.getByRole('textbox', { name: 'Opened editor' }).focus() - }) - await user.click(screen.getByRole('menuitem', { name: 'Open file' })) - expect(mocks.openDetectedFilePath).toHaveBeenCalledExactlyOnceWith( - '/repo/worktree/screenshots/chart.png', - null, - null, - expect.objectContaining({ worktreeId: 'wt-1', sourceTabId: 'tab-1' }) - ) - expect(screen.queryByRole('menu')).toBeNull() - await waitFor(() => - expect(screen.getByRole('textbox', { name: 'Opened editor' })).toHaveFocus() - ) - }) - - it('opens while a remote read is pending and clears image bytes and actions on owner loss', async () => { - const pendingRead = Promise.withResolvers<{ - content: string - isBinary: boolean - mimeType: string - }>() - mocks.readRuntimeFilePreview.mockReturnValueOnce(pendingRead.promise) - const owner: ImageOwner = { - ...localOwner, - runtimeContext: { - ...localOwner.runtimeContext, - target: { kind: 'environment', environmentId: 'remote-a' } - }, - fileLinkContext: { ...localOwner.fileLinkContext, runtimeEnvironmentId: 'remote-a' } - } - const { rerender } = render() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - expect(screen.getByRole('dialog', { name: 'Chart' })).toBeInTheDocument() - expect(mocks.readRuntimeFilePreview).toHaveBeenCalledWith( - expect.objectContaining({ target: { kind: 'environment', environmentId: 'remote-a' } }), - '/repo/worktree/screenshots/chart.png', - { kind: 'chat-image' } - ) - rerender() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' }), { ctrlKey: true }) - expect(mocks.openDetectedFilePath).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - expect(screen.queryByRole('button', { name: 'File actions' })).toBeNull() - await act(async () => - pendingRead.resolve({ content: 'AA==', isBinary: true, mimeType: 'image/png' }) - ) - expect(within(screen.getByRole('dialog')).queryByRole('img')).toBeNull() - expect(mocks.readRuntimeFilePreview).toHaveBeenCalledOnce() - }) - it('closes the preview when the owning chat becomes hidden', () => { const { rerender } = render() fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) diff --git a/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.session-images.test.tsx b/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.session-images.test.tsx index cb8cc75d604..6c029c3e4e8 100644 --- a/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.session-images.test.tsx +++ b/src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.session-images.test.tsx @@ -1,8 +1,8 @@ import type * as RuntimeRpcCallModule from '@/runtime/rpc/calls/runtime-rpc-call' // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' -import userEvent from '@testing-library/user-event' +import { act, cleanup, render, screen, waitFor } from '@testing-library/react' + import type { ComponentProps } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -134,79 +134,6 @@ describe('session image source resolution', () => { ) }) - it.each(['matched', 'missing'] as const)( - 'retains an already loaded workspace image during expansion until refresh settles %s', - async (settlement) => { - const originalPath = '/repo/worktree/images/chart.png' - const nextPath = '/session/images/chart.png' - let complete!: (value: { exists: boolean; absolutePath: string | null }) => void - mocks.callRuntimeRpc - .mockResolvedValueOnce({ exists: true, absolutePath: originalPath }) - .mockReturnValueOnce( - new Promise((resolve) => { - complete = resolve - }) - ) - render() - const thumbnail = await screen.findByRole('img', { name: 'Chart' }) - const originalSrc = thumbnail.getAttribute('src') - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - await waitFor(() => expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(2)) - const dialog = screen.getByRole('dialog') - expect(thumbnail).toHaveAttribute('src', originalSrc) - expect(within(dialog).getByRole('img')).toHaveAttribute('src', originalSrc) - expect(within(dialog).queryByText('Preview unavailable')).not.toBeInTheDocument() - const user = userEvent.setup() - await user.click(screen.getByRole('button', { name: 'File actions' })) - await user.click(screen.getByRole('menuitem', { name: 'Open file' })) - expect(mocks.openDetectedFilePath).toHaveBeenLastCalledWith( - originalPath, - null, - null, - expect.anything() - ) - await act(async () => - complete({ - exists: settlement === 'matched', - absolutePath: settlement === 'matched' ? nextPath : null - }) - ) - if (settlement === 'matched') { - await waitFor(() => - expect(screen.getByRole('img', { name: 'Chart' })).toHaveAttribute('src', 'blob:image-2') - ) - expect(mocks.readRuntimeFilePreview).toHaveBeenLastCalledWith(expect.anything(), nextPath, { - kind: 'chat-image' - }) - } else { - await waitFor(() => - expect(screen.queryByRole('img', { name: 'Chart' })).not.toBeInTheDocument() - ) - } - } - ) - - it('retries a missing live session image on expand without reading a workspace decoy', async () => { - mocks.callRuntimeRpc - .mockResolvedValueOnce({ exists: false, absolutePath: null }) - .mockResolvedValue({ exists: true, absolutePath: '/session/images/chart.png' }) - render( - - ) - await waitFor(() => expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1)) - expect(mocks.readRuntimeFilePreview).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: 'View image: Chart' })) - await within(screen.getByRole('dialog')).findByRole('img') - expect(mocks.readRuntimeFilePreview).toHaveBeenCalledExactlyOnceWith( - expect.anything(), - '/session/images/chart.png', - { kind: 'chat-image' } - ) - }) - it('discards a session lookup after its owner changes', async () => { let complete!: (value: unknown) => void mocks.callRuntimeRpc diff --git a/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx b/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx index a7978be09ef..432ef9b35ab 100644 --- a/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx +++ b/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx @@ -3,7 +3,7 @@ import '@testing-library/jest-dom/vitest' import { isValidElement, type ComponentProps } from 'react' import type { NativeChatCrewFrame } from '../../../orchestration-crew/NativeChatCrewPanel' -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as ImageBlobPng from '@/lib/image-blob-png' import { NativeChatImageAttachmentPreview } from '../../NativeChatImageAttachmentPreview' @@ -74,9 +74,6 @@ vi.mock('sonner', () => ({ toast: { success: mocks.success, error: mocks.error } const { NativeChatResolvedView } = await import('../../NativeChatResolvedView') const { useAppStore } = await import('../../../../store/index') -const { installNativeChatMessageListTestViewport } = - await import('../../native-chat-message-list-test-viewport') -const { TooltipProvider } = await import('@/components/ui/tooltip') function RetainedBridgeChat({ visible = true }: { visible?: boolean }) { return ( @@ -124,74 +121,6 @@ afterEach(() => { }) describe('NativeChatResolvedView image menu ownership', () => { - it('refuses image capture from a portaled preview while its retained owner is hidden', async () => { - mocks.fetch.mockResolvedValue({ ok: true, blob: async () => new Blob(['original image']) }) - const view = render() - fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: original.png' })) - const preview = screen.getByRole('dialog') - expect(screen.getByTestId('retained-owner').contains(preview)).toBe(false) - - view.rerender() - fireEvent.contextMenu(within(preview).getByRole('img')) - - expect(mocks.fetch).not.toHaveBeenCalled() - view.rerender() - expect(screen.queryByRole('menu')).toBeNull() - expect(mocks.writeClipboardImage).not.toHaveBeenCalled() - }) - - it('closes the image preview on the first Close click while its copy menu is open', async () => { - mocks.fetch.mockResolvedValue({ ok: true, blob: async () => new Blob(['original image']) }) - render() - fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: original.png' })) - const preview = screen.getByRole('dialog', { name: 'original.png' }) - fireEvent.contextMenu(within(preview).getByRole('img')) - await screen.findByRole('menuitem', { name: 'Copy image' }) - const close = within(preview).getByRole('button', { name: 'Close' }) - - fireEvent.pointerDown(close, { button: 0 }) - fireEvent.pointerUp(close, { button: 0 }) - fireEvent.click(close) - - await waitFor(() => expect(preview).not.toBeInTheDocument()) - expect(mocks.writeClipboardImage).not.toHaveBeenCalled() - }) - - it.each(['thumbnail', 'preview'])( - 'copies the original image from the %s through the visible bridge chat menu', - async (surface) => { - mocks.fetch.mockResolvedValue({ ok: true, blob: async () => new Blob(['original image']) }) - render() - - if (surface === 'preview') { - fireEvent.click(screen.getByRole('button', { name: 'Image #1: View image: original.png' })) - } - const preview = - surface === 'preview' ? screen.getByRole('dialog', { name: 'original.png' }) : null - const image = preview - ? within(preview).getByRole('img') - : screen.getByRole('img', { name: 'original.png' }) - fireEvent.contextMenu(image) - const copy = await screen.findByRole('menuitem', { name: 'Copy image' }) - fireEvent.pointerDown(copy, { button: 0, pointerType: 'mouse' }) - fireEvent.pointerUp(copy, { button: 0, pointerType: 'mouse' }) - fireEvent.click(copy) - - await waitFor(() => - expect(mocks.writeClipboardImage).toHaveBeenCalledWith( - `data:image/png;base64,${Buffer.from('original image').toString('base64')}` - ) - ) - expect(mocks.fetch).toHaveBeenCalledWith('blob:original') - expect(mocks.success).toHaveBeenCalledWith('Image copied') - expect(mocks.error).not.toHaveBeenCalled() - if (preview) { - expect(preview).toBeInTheDocument() - expect(preview).toHaveAttribute('data-state', 'open') - } - } - ) - it('removes the portaled menu and captured image when the retained bridge owner hides', async () => { const capturedImage = Promise.withResolvers() mocks.fetch.mockResolvedValue({ ok: true, blob: () => capturedImage.promise }) @@ -229,54 +158,3 @@ describe('NativeChatResolvedView image menu ownership', () => { expect(mocks.error).not.toHaveBeenCalled() }) }) - -function chatMessage(id: string, role: 'user' | 'assistant', text: string): NativeChatMessage { - return { id, role, blocks: [{ type: 'text', text }], timestamp: 1, source: 'transcript' } -} - -const REPLY = [ - 'Run the build:', - '', - '```sh', - 'pnpm build', - '```', - '', - '::orca-visual{file="chart.html"}' -].join('\n') - -describe('NativeChatResolvedView right-click targets', () => { - let restoreViewport = (): void => {} - beforeEach(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterEach(() => restoreViewport()) - - it('copies a reply and its code block with the text their hover buttons copy', async () => { - mocks.session.messages = [ - chatMessage('ask', 'user', 'Fix the build'), - chatMessage('reply', 'assistant', REPLY) - ] - render( - - - - ) - - fireEvent.contextMenu(screen.getByText('Run the build:')) - fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy message' })) - expect(mocks.writeClipboardText).toHaveBeenLastCalledWith( - 'Run the build:\n\n```sh\npnpm build\n```' - ) - - fireEvent.click(screen.getByRole('button', { name: 'Copy code' })) - const hoverCopy = mocks.writeClipboardText.mock.lastCall - fireEvent.contextMenu(screen.getByText('pnpm build')) - fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy code' })) - expect(mocks.writeClipboardText.mock.lastCall).toEqual(hoverCopy) - expect(hoverCopy).toEqual(['pnpm build\n']) - - fireEvent.contextMenu(screen.getByText('Fix the build')) - fireEvent.click(await screen.findByRole('menuitem', { name: 'Copy message' })) - expect(mocks.writeClipboardText).toHaveBeenLastCalledWith('Fix the build') - }) -}) diff --git a/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.images.test.tsx b/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.images.test.tsx deleted file mode 100644 index a58e9cd63be..00000000000 --- a/src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.images.test.tsx +++ /dev/null @@ -1,93 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { cleanup, screen, waitFor } from '@testing-library/react' -import { render } from '../../native-chat-tooltip-test-harness' -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' -import '@/components/editor/document-images/useLocalImageSrc' -import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '@/components/editor/document-images/local-image-src-cache' -import { useAppStore } from '@/store' -import { nativeChatFanoutFixture } from '../../native-chat-workspace-test-fixtures' -import { installNativeChatMessageListTestViewport } from '../../native-chat-message-list-test-viewport' - -const session: NativeChatLiveSession = { - messages: [ - { - id: 'user-image', - role: 'user', - blocks: [{ type: 'image-ref', path: '/repo/0/orca-paste-shot.png' }], - timestamp: 1, - source: 'transcript' - } - ], - status: 'ready', - sessionId: 'session-image', - agent: 'claude', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' -} - -vi.mock('../../session/terminal/read/use-native-chat-retained-session', () => ({ - useNativeChatRetainedSession: () => session -})) -vi.mock('../../NativeChatComposer', () => ({ NativeChatComposer: () => null })) - -const { NativeChatResolvedView } = await import('../../NativeChatResolvedView') -const original = useAppStore.getState() -const readFile = vi.fn() -let restoreViewport = (): void => {} - -beforeEach(() => { - restoreViewport = installNativeChatMessageListTestViewport() - resetLocalImageSrcStateForTests() - vi.stubGlobal('IntersectionObserver', undefined) - vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:terminal-image') - vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined) - readFile.mockResolvedValue({ content: 'AA==', isBinary: true, mimeType: 'image/png' }) - vi.stubGlobal('api', { ...window.api, fs: { ...window.api?.fs, readFile } }) - useAppStore.setState({ - ...useAppStore.getInitialState(), - ...nativeChatFanoutFixture(0, 1, 1), - activeWorktreeId: null, - activeWorkspaceExecutionHostId: null, - runtimeEnvironmentCatalogHydrated: true - }) -}) - -afterEach(() => { - cleanup() - restoreViewport() - resetLocalImageSrcStateForTests() - useAppStore.setState(original, true) - vi.unstubAllGlobals() - vi.restoreAllMocks() - readFile.mockReset() -}) - -it('previews a terminal transcript image from the terminal tab’s workspace owner', async () => { - render( - - ) - const preview = await screen.findByRole('button', { name: 'View image: Pasted image' }) - await waitFor(() => - expect(preview.querySelector('img')?.getAttribute('src')).toBe('blob:terminal-image') - ) - expect(readFile).toHaveBeenCalledExactlyOnceWith({ - filePath: '/repo/0/orca-paste-shot.png', - connectionId: undefined, - access: { kind: 'chat-image' } - }) -}) diff --git a/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx b/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx index a63f176ee2c..22e336eff9e 100644 --- a/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx +++ b/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx @@ -4,11 +4,8 @@ import { act, createElement } from 'react' import { createRoot } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' -import { - invalidateLocalImageCache as invalidateLocalImageSrcCacheForTests, - resetLocalImageCacheState as resetLocalImageSrcStateForTests -} from '@/components/editor/document-images/local-image-src-cache' + +import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '@/components/editor/document-images/local-image-src-cache' import { useAppStore } from '@/store' import { NativeChatImageAttachments } from './NativeChatImageAttachments' import { useNativeChatImageRuntimeContext } from './native-chat-image-runtime-context' @@ -34,15 +31,6 @@ vi.mock('@/lib/connection-context', () => ({ globalThis.IS_REACT_ACT_ENVIRONMENT = true -function runtimeContext(worktreeId: string): RuntimeFileOperationArgs { - return { - target: { kind: 'local' as const }, - worktreeId, - worktreePath: `/repo/${worktreeId}`, - expectedExecutionHostId: 'local' - } -} - async function flushPromises(): Promise { await Promise.resolve() await Promise.resolve() @@ -147,81 +135,4 @@ describe('NativeChatImageAttachments', () => { useAppStore.setState(original, true) } }) - - it('preserves same-image errors but retries when the runtime owner changes', async () => { - const container = document.createElement('div') - const root = createRoot(container) - const blocks = [{ type: 'image-ref' as const, path: '/repo/image.png' }] - const ownerOne = runtimeContext('wt-1') - - await act(async () => { - root.render( - createElement(NativeChatImageAttachments, { - blocks, - runtimeContext: ownerOne - }) - ) - await flushPromises() - }) - const firstOwnerSrc = container.querySelector('img')?.getAttribute('src') - expect(firstOwnerSrc).toBe('blob:owner-1') - - await act(async () => { - container.querySelector('img')?.dispatchEvent(new Event('error')) - }) - expect(container.querySelector('img')).toBeNull() - - await act(async () => { - root.render( - createElement(NativeChatImageAttachments, { - blocks, - runtimeContext: ownerOne - }) - ) - await flushPromises() - }) - expect(container.querySelector('img')).toBeNull() - - await act(async () => { - root.render( - createElement(NativeChatImageAttachments, { - blocks, - runtimeContext: runtimeContext('wt-2') - }) - ) - await flushPromises() - }) - expect(container.querySelector('img')?.getAttribute('src')).not.toBe(firstOwnerSrc) - expect(window.api.fs.readFile).toHaveBeenCalledTimes(2) - - root.unmount() - }) - - it('retries a failed thumbnail after the image cache refreshes', async () => { - const container = document.createElement('div') - const root = createRoot(container) - const props = { - blocks: [{ type: 'image-ref' as const, path: '/repo/image.png' }], - runtimeContext: runtimeContext('wt-1') - } - - await act(async () => { - root.render(createElement(NativeChatImageAttachments, props)) - await flushPromises() - }) - expect(container.querySelector('img')?.getAttribute('src')).toBe('blob:owner-1') - - await act(async () => { - container.querySelector('img')?.dispatchEvent(new Event('error')) - }) - expect(container.querySelector('img')).toBeNull() - - await act(async () => { - invalidateLocalImageSrcCacheForTests() - await flushPromises() - }) - - expect(container.querySelector('img')?.getAttribute('src')).toBe('blob:owner-2') - root.unmount() - }) }) diff --git a/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachments.test.tsx b/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachments.test.tsx index bb0e9ef4bfe..6b7c3ef1f95 100644 --- a/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachments.test.tsx +++ b/src/renderer/src/components/native-chat/media/text/NativeChatTextAttachments.test.tsx @@ -10,7 +10,7 @@ import { NativeChatTextAttachmentScope, NativeChatTextAttachmentOpener } from './NativeChatTextAttachments' -import { NativeChatTextAttachmentPreview } from './NativeChatTextAttachmentPreview' + import { AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities' import { NativeChatMarkdownImageOwnerContext } from '../images/native-chat-markdown-image-owner' import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' @@ -90,16 +90,6 @@ afterEach(async () => { const waitUntilEnabled = (name: string) => waitFor(() => expect(screen.getByRole('button', { name }).hasAttribute('disabled')).toBe(false)) -it('shows the old-host limitation and refreshes capability on Retry without affecting the message', async () => { - capable = false - render( {}} />) - await screen.findByText(/This host cannot open text attachments yet/) - expect(mocks.rpc.mock.calls.every((call) => call[1] === 'status.get')).toBe(true) - capable = true - fireEvent.click(screen.getByRole('button', { name: 'Retry' })) - await waitUntilEnabled('Copy contents') -}) - it('keeps focused stateful composer descendants mounted when owner context changes', async () => { mocks.context = { target: { kind: 'local' }, worktreeId: 'w', worktreePath: '/repo' } function Child() { diff --git a/src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.test.tsx b/src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.test.tsx deleted file mode 100644 index d28954366e3..00000000000 --- a/src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.test.tsx +++ /dev/null @@ -1,211 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { act, cleanup, render } from '@testing-library/react' -import { useRef } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX, - NATIVE_CHAT_VISUAL_OPEN_LINK_TYPE, - NATIVE_CHAT_VISUAL_PING_TYPE, - NATIVE_CHAT_VISUAL_PONG_TIMEOUT_MS, - NATIVE_CHAT_VISUAL_PONG_TYPE, - NATIVE_CHAT_VISUAL_THEME_TYPE -} from '../../../../../../shared/native-chat/native-chat-visual-shell' - -const openHttpLink = vi.fn() -vi.mock('@/lib/browser/navigation/http-link-routing', () => ({ - openHttpLink: (...args: unknown[]) => openHttpLink(...args) -})) - -import { NativeChatVisualFrame } from './NativeChatVisualFrame' -import type { ReaderGesture } from '../../native-chat-autoscroll' - -const visual = { revision: 'r1', html: '

chart

', path: '/v' } - -function Harness(props: { - onRetired?: () => void - onReaderGesture?: (gesture: ReaderGesture) => void -}) { - const scope = useRef(null) - return ( -
- {})} - onReaderGesture={props.onReaderGesture} - /> -
- ) -} - -function frameOf(container: HTMLElement): HTMLIFrameElement { - const frame = container.querySelector('iframe') - if (!frame) { - throw new Error('no frame') - } - return frame -} - -function channelOf(frame: HTMLIFrameElement): string { - return frame.name.slice(NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX.length) -} - -function post(data: unknown, source: MessageEventSource | null): void { - act(() => { - window.dispatchEvent(new MessageEvent('message', { data, source })) - }) -} - -function load(frame: HTMLIFrameElement): void { - act(() => { - frame.dispatchEvent(new Event('load')) - }) -} - -function answer(frame: HTMLIFrameElement, id: number): void { - post({ type: NATIVE_CHAT_VISUAL_PONG_TYPE, channel: channelOf(frame), id }, frame.contentWindow) -} - -/** Records what the host posts into the frame, so only the test answers its pings. */ -function captureFramePosts(frame: HTMLIFrameElement): ReturnType { - const contentWindow = frame.contentWindow - if (!contentWindow) { - throw new Error('no content window') - } - const posted = vi.fn() - vi.spyOn(contentWindow, 'postMessage').mockImplementation(posted) - return posted -} - -/** Renders the frame and lets its own first load land, then hands the clock to the test. */ -async function renderLoaded(onRetired: () => void) { - const view = render() - const frame = frameOf(view.container) - const posted = captureFramePosts(frame) - await vi.waitFor(() => { - expect(posted).toHaveBeenCalledWith( - expect.objectContaining({ type: NATIVE_CHAT_VISUAL_THEME_TYPE }), - '*' - ) - }) - vi.useFakeTimers() - return { ...view, frame, posted } -} - -function waitOutTheAnswer(): void { - act(() => { - vi.advanceTimersByTime(NATIVE_CHAT_VISUAL_PONG_TIMEOUT_MS) - }) -} - -function setUserActivation(isActive: boolean): void { - Object.defineProperty(navigator, 'userActivation', { - configurable: true, - value: { isActive, hasBeenActive: isActive } - }) -} - -beforeEach(() => { - openHttpLink.mockReset() -}) - -afterEach(() => { - vi.useRealTimers() - cleanup() - document.documentElement.classList.remove('dark') -}) - -describe('NativeChatVisualFrame', () => { - it('runs the visual in a scripts-only sandbox, named for host registration, with its CSP first', () => { - const { container } = render() - const frame = frameOf(container) - expect(frame.getAttribute('sandbox')).toBe('allow-scripts') - expect(frame.name.startsWith(NATIVE_CHAT_VISUAL_FRAME_NAME_PREFIX)).toBe(true) - const srcdoc = frame.getAttribute('srcdoc') ?? '' - expect(srcdoc.indexOf('Content-Security-Policy')).toBeLessThan(srcdoc.indexOf('

chart

')) - expect(channelOf(frame)).toMatch(/^[0-9a-f]{32}$/) - }) - - it('opens a link only while the frame has focus and the user has just acted', () => { - const { container } = render() - const frame = frameOf(container) - const channel = channelOf(frame) - const link = { type: NATIVE_CHAT_VISUAL_OPEN_LINK_TYPE, channel, url: 'https://example.com/' } - - setUserActivation(true) - post(link, frame.contentWindow) - expect(openHttpLink).not.toHaveBeenCalled() - - frame.tabIndex = 0 - frame.focus() - setUserActivation(false) - post(link, frame.contentWindow) - expect(openHttpLink).not.toHaveBeenCalled() - - setUserActivation(true) - post(link, window) - post({ ...link, url: 'javascript:alert(1)' }, frame.contentWindow) - expect(openHttpLink).not.toHaveBeenCalled() - - post(link, frame.contentWindow) - expect(openHttpLink).toHaveBeenCalledWith('https://example.com/', { forceSystemBrowser: true }) - // A burst of requests opens at most one page. - post(link, frame.contentWindow) - expect(openHttpLink).toHaveBeenCalledTimes(1) - }) - - it('keeps the visual through a later load it answers, as for an in-page link in WebKit', async () => { - const onRetired = vi.fn() - const { frame, posted } = await renderLoaded(onRetired) - const ping = expect.objectContaining({ type: NATIVE_CHAT_VISUAL_PING_TYPE }) - expect(posted).not.toHaveBeenCalledWith(ping, '*') - load(frame) - expect(posted).toHaveBeenCalledWith( - { type: NATIVE_CHAT_VISUAL_PING_TYPE, channel: channelOf(frame), id: 2 }, - '*' - ) - answer(frame, 2) - waitOutTheAnswer() - expect(onRetired).not.toHaveBeenCalled() - }) - - it('retires itself when a later load goes unanswered: the frame went blank or left', async () => { - const onRetired = vi.fn() - const { frame } = await renderLoaded(onRetired) - load(frame) - act(() => { - vi.advanceTimersByTime(NATIVE_CHAT_VISUAL_PONG_TIMEOUT_MS - 1) - }) - expect(onRetired).not.toHaveBeenCalled() - act(() => { - vi.advanceTimersByTime(1) - }) - expect(onRetired).toHaveBeenCalledTimes(1) - }) - - it('ignores answers from another window, another channel, or an earlier load', async () => { - const onRetired = vi.fn() - const { frame } = await renderLoaded(onRetired) - load(frame) - load(frame) - answer(frame, 2) - const pong = { type: NATIVE_CHAT_VISUAL_PONG_TYPE, id: 3 } - post({ ...pong, channel: channelOf(frame) }, window) - post({ ...pong, channel: 'other' }, frame.contentWindow) - waitOutTheAnswer() - expect(onRetired).toHaveBeenCalledTimes(1) - }) - - it('owes no answer once it unmounts', async () => { - const onRetired = vi.fn() - const { frame, unmount } = await renderLoaded(onRetired) - load(frame) - unmount() - waitOutTheAnswer() - expect(onRetired).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.test.tsx b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.test.tsx index dff6c592453..cbe7be38f76 100644 --- a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.test.tsx +++ b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-markdown-syntax.test.tsx @@ -61,31 +61,6 @@ function mountedFiles(markup: string): string[] { const LINE = '::orca-visual{file="usage.html" title="Usage by day"}' describe('remarkNativeChatVisuals', () => { - it('splits a paragraph that runs straight into and out of the directive', () => { - const markup = render(`Here it is:\n${LINE}\nThat is the trend.`) - expect(mountedFiles(markup)).toEqual(['usage.html']) - expect(markup).toContain('Here it is:') - expect(markup).toContain('That is the trend.') - }) - - it.each([ - ['fenced code', `\`\`\`\n${LINE}\n\`\`\``], - ['tilde fenced code', `~~~md\n${LINE}\n~~~`], - ['indented code', `Intro\n\n ${LINE}`], - ['inline code', `Use \`${LINE}\` to show a chart.`], - ['a block quote', `> ${LINE}`], - ['a list item', `- ${LINE}`], - ['an ordered list item', `1. ${LINE}`], - ['mid-sentence', `See ${LINE} here`], - ['a malformed directive', '::orca-visual{file="../usage.html"}'], - ['an unclosed directive', '::orca-visual{file="usage.html"'], - ['trailing prose on the line', `${LINE} done`] - ])('leaves it as text inside %s', (_name, content) => { - const markup = render(content) - expect(mountedFiles(markup)).toEqual([]) - expect(markup).toContain('::orca-visual') - }) - it('does not mount a raw HTML placeholder forged without the nonce', () => { const markup = render( '
x
\n\nafter' @@ -93,19 +68,6 @@ describe('remarkNativeChatVisuals', () => { expect(mountedFiles(markup)).toEqual([]) }) - it('caps how many visuals one reply mounts and shows the rest as text', () => { - const lines = Array.from( - { length: 10 }, - (_, index) => `::orca-visual{file="chart-${index}.html"}` - ) - const markup = render(lines.join('\n\n')) - expect(mountedFiles(markup)).toEqual( - Array.from({ length: 8 }, (_, index) => `chart-${index}.html`) - ) - expect(markup).toContain('chart-8.html') - expect(markup).toContain('chart-9.html') - }) - it('keeps reference links defined after the directive working', () => { const markup = render(`See [the docs][d].\n\n${LINE}\n\n[d]: https://example.com/docs`) expect(mountedFiles(markup)).toEqual(['usage.html']) diff --git a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-read-client.test.ts b/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-read-client.test.ts deleted file mode 100644 index 017e858cf34..00000000000 --- a/src/renderer/src/components/native-chat/media/visuals/native-chat-visual-read-client.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const callRuntimeRpc = vi.fn() -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: (...args: unknown[]) => callRuntimeRpc(...args) -})) - -import { - clearNativeChatVisualCacheForTests, - peekCachedNativeChatVisual, - readNativeChatVisual -} from './native-chat-visual-read-client' - -const local = { target: { kind: 'local' as const }, sessionId: 'session-alpha', file: 'a.html' } -const remote = { - target: { kind: 'environment' as const, environmentId: 'env-1' }, - sessionId: 'session-alpha', - file: 'a.html' -} - -beforeEach(() => { - clearNativeChatVisualCacheForTests() - callRuntimeRpc.mockReset() -}) - -afterEach(() => { - clearNativeChatVisualCacheForTests() -}) - -describe('readNativeChatVisual', () => { - it('revalidates with the held revision and keeps the cached bytes when unchanged', async () => { - callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r1', html: '

', path: '/v' }) - await readNativeChatVisual(local) - callRuntimeRpc.mockResolvedValueOnce({ - ok: true, - revision: 'r1', - sizeBytes: 3, - unchanged: true - }) - expect(await readNativeChatVisual(local)).toEqual({ - ok: true, - document: { revision: 'r1', html: '

', path: '/v' } - }) - expect(callRuntimeRpc.mock.calls[1][2]).toEqual({ - sessionId: 'session-alpha', - file: 'a.html', - knownRevision: 'r1' - }) - }) - - it('keeps one runtime from answering for another', async () => { - callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r1', html: '

', path: '/v' }) - await readNativeChatVisual(local) - expect(peekCachedNativeChatVisual(remote)).toBeNull() - }) - - it('passes host refusals through, degrades an unknown one, and forgets a refused file', async () => { - callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r1', html: '

', path: '/v' }) - await readNativeChatVisual(local) - callRuntimeRpc.mockResolvedValueOnce({ ok: false, error: 'not_found' }) - expect(await readNativeChatVisual(local)).toEqual({ ok: false, reason: 'not_found' }) - expect(peekCachedNativeChatVisual(local)).toBeNull() - callRuntimeRpc.mockResolvedValueOnce({ ok: true, revision: 'r2', html: '

', path: '/v' }) - await readNativeChatVisual(local) - callRuntimeRpc.mockResolvedValueOnce({ ok: false, error: 'too_large' }) - expect(await readNativeChatVisual(local)).toEqual({ ok: false, reason: 'too_large' }) - // A rewrite the host now refuses must not keep showing the old bytes on the next mount. - expect(peekCachedNativeChatVisual(local)).toBeNull() - callRuntimeRpc.mockResolvedValueOnce({ ok: false, error: 'some_future_reason' }) - expect(await readNativeChatVisual(local)).toEqual({ ok: false, reason: 'unavailable' }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/input/terminal-input-host-platform.test.ts b/src/renderer/src/components/terminal-pane/input/terminal-input-host-platform.test.ts deleted file mode 100644 index bbcc06d58a9..00000000000 --- a/src/renderer/src/components/terminal-pane/input/terminal-input-host-platform.test.ts +++ /dev/null @@ -1,346 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' -import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' -import type { AppState } from '@/store/types' -import { resolveTerminalInputHostPlatform } from './terminal-input-host-platform' - -function state(overrides: Partial = {}): AppState { - return { - repos: [], - worktreesByRepo: {}, - detectedWorktreesByRepo: {}, - folderWorkspaces: [], - projectGroups: [], - settings: { activeRuntimeEnvironmentId: null }, - sshConnectionStates: new Map(), - sshStateByEnvironment: new Map(), - runtimeStatusByEnvironmentId: new Map(), - restoredRuntimeHostIdByWorkspaceSessionKey: {}, - ...overrides - } as AppState -} - -/** A Windows host that answered once and whose latest probe came back unverifiable. */ -function unverifiableWindowsHost(): RuntimeEnvironmentStatus { - const answered: RuntimeStatus = { - runtimeId: 'rt-win', - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - hostPlatform: 'win32' - } - return { - status: null, - checkedAt: 2, - snapshot: { - environmentId: 'windows-box', - pairingRevision: 1, - sequence: 2, - checkedAt: 2, - status: answered, - verification: 'unavailable', - transport: 'ready' - } - } -} - -describe('resolveTerminalInputHostPlatform', () => { - it('uses a paired runtime host platform instead of the macOS client', () => { - const worktreeId = 'repo::C:\\repo' - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - repos: [ - { - id: 'repo', - path: 'C:\\repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - executionHostId: 'runtime:windows-box' - } - ], - runtimeStatusByEnvironmentId: new Map([ - [ - 'windows-box', - { - status: { hostPlatform: 'win32' } - } as AppState['runtimeStatusByEnvironmentId'] extends Map ? T : never - ] - ]) - }), - worktreeId, - transport: null - }) - ).toBe('win32') - }) - - it('uses the active remote runtime PTY owner after worktree ownership changes', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - repos: [ - { - id: 'repo', - path: 'C:\\repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - executionHostId: 'runtime:linux-box' - } - ], - runtimeStatusByEnvironmentId: new Map([ - ['windows-box', { status: { hostPlatform: 'win32' } } as never], - ['linux-box', { status: { hostPlatform: 'linux' } } as never] - ]) - }), - worktreeId: 'repo::C:\\repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'remote:windows-box@@terminal-1' - } - }) - ).toBe('win32') - }) - - it('uses the nested SSH host platform instead of the outer HUB platform', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - runtimeStatusByEnvironmentId: new Map([ - ['hub', { status: { hostPlatform: 'linux' } } as never] - ]), - sshStateByEnvironment: new Map([ - [ - 'hub', - { - connectionStates: new Map([['ssh-windows', { remotePlatform: 'win32' } as never]]) - } as never - ] - ]) - }), - worktreeId: 'repo::C:\\repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'remote:hub@@terminal-1', - getRuntimeEnvironmentId: () => 'hub', - getExecutionHostId: () => 'ssh:ssh-windows' - } - }) - ).toBe('win32') - }) - - it('uses captured runtime ownership for a legacy remote PTY id', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - runtimeStatusByEnvironmentId: new Map([ - ['windows-box', { status: { hostPlatform: 'win32' } } as never] - ]) - }), - worktreeId: 'repo::/repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'remote:terminal-1', - getRuntimeEnvironmentId: () => 'windows-box' - } - }) - ).toBe('win32') - }) - - it('keeps a live local PTY on the client after worktree ownership changes', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - repos: [ - { - id: 'repo', - path: '/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - executionHostId: 'runtime:windows-box' - } - ], - runtimeStatusByEnvironmentId: new Map([ - ['windows-box', { status: { hostPlatform: 'win32' } } as never] - ]) - }), - worktreeId: 'repo::/repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'local-pty-1', - getLocalSessionMetadata: () => ({ cwd: '/repo' }) - } - }) - ).toBe('darwin') - }) - - it('normalizes a live WSL session to a Linux terminal host', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'win32', - state: state(), - worktreeId: 'repo::C:\\repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'local-pty-1', - getLocalSessionMetadata: () => ({ - shellOverride: ' "C:\\Windows\\System32\\wsl.exe" -d Ubuntu-24.04' - }) - } - }) - ).toBe('linux') - }) - - it('keeps a live native Windows session after the worktree switches to WSL', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'win32', - state: state({ - repos: [ - { - id: 'repo', - path: 'C:\\repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - executionHostId: 'runtime:linux-box' - } - ], - runtimeStatusByEnvironmentId: new Map([ - ['linux-box', { status: { hostPlatform: 'linux' } } as never] - ]) - }), - worktreeId: 'repo::C:\\repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'windows-pty-1', - getLocalSessionMetadata: () => ({ cwd: 'C:\\repo', shellOverride: 'pwsh.exe' }) - } - }) - ).toBe('win32') - }) - - it('uses SSH remote platform metadata', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - sshConnectionStates: new Map([['ssh-win', { remotePlatform: 'win32' } as never]]) - }), - worktreeId: 'repo::C:\\repo', - transport: { getConnectionId: () => 'ssh-win' } - }) - ).toBe('win32') - }) - - it('uses conservative POSIX input when SSH platform metadata is unavailable', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ sshConnectionStates: new Map([['ssh-unknown', {} as never]]) }), - worktreeId: 'repo::/repo', - transport: { getConnectionId: () => 'ssh-unknown' } - }) - ).toBe('linux') - }) - - it('prefers the PTY-owner platform over stale nested SSH state', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ sshStateByEnvironment: new Map() }), - worktreeId: 'repo::/repo', - transport: { - getConnectionId: () => null, - getRuntimeEnvironmentId: () => 'hub', - getExecutionHostId: () => 'ssh:ssh-win', - getRemotePlatform: () => 'win32' - } - }) - ).toBe('win32') - }) - - it('falls back to the client when runtime platform metadata is unavailable', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state(), - worktreeId: 'repo::/repo', - transport: { - getConnectionId: () => null, - getPtyId: () => 'remote:windows-box@@terminal-1', - getRuntimeEnvironmentId: () => 'windows-box' - } - }) - ).toBe('darwin') - }) - - it('uses the SSH execution host when the transport has no connection id', () => { - const worktreeId = 'repo::C:\\repo' - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - repos: [ - { - id: 'repo', - path: 'C:\\repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - executionHostId: 'ssh:ssh-win' - } - ], - sshConnectionStates: new Map([['ssh-win', { remotePlatform: 'win32' } as never]]) - }), - worktreeId, - transport: { getConnectionId: () => null } - }) - ).toBe('win32') - }) - - // Unanswered probes cannot substitute client platform: Mac-driven Windows hosts must retain host input/path conventions. - it('keeps the Windows host platform while its probe is unverifiable', () => { - const worktreeId = 'repo::C:\\repo' - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state({ - repos: [ - { - id: 'repo', - path: 'C:\\repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - executionHostId: 'runtime:windows-box' - } - ], - runtimeStatusByEnvironmentId: new Map([['windows-box', unverifiableWindowsHost()]]) - }), - worktreeId, - transport: null - }) - ).toBe('win32') - }) - - it('keeps the client platform for local terminals', () => { - expect( - resolveTerminalInputHostPlatform({ - clientPlatform: 'darwin', - state: state(), - worktreeId: 'repo::/repo', - transport: null - }) - ).toBe('darwin') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/input/terminal-input-quarantine.test.ts b/src/renderer/src/components/terminal-pane/input/terminal-input-quarantine.test.ts deleted file mode 100644 index 6d804e1c4d6..00000000000 --- a/src/renderer/src/components/terminal-pane/input/terminal-input-quarantine.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, beforeEach, vi } from 'vitest' - -const { notifyTerminalInputNotSent } = vi.hoisted(() => ({ notifyTerminalInputNotSent: vi.fn() })) -vi.mock('./terminal-input-not-sent-notice', () => ({ notifyTerminalInputNotSent })) -import { - _resetTerminalInputQuarantineForTests, - armTerminalInputQuarantine, - isTerminalInputQuarantined, - shouldDropQuarantinedTerminalInput -} from './terminal-input-quarantine' - -const TAB = 'tab-1' -// Re-attach measured at ~1.1s in STA-2373 live QA; the tail lands just after. -const REATTACH_MS = 1_100 - -beforeEach(() => { - _resetTerminalInputQuarantineForTests() - notifyTerminalInputNotSent.mockReset() -}) - -describe('terminal input quarantine', () => { - it('drops the surviving tail of an interrupted line and its Enter', () => { - armTerminalInputQuarantine(TAB, 0) - // The tail of `echo hi; rm -rf x` after the head was eaten by recovery. - let at = REATTACH_MS - for (const char of 'cho hi; rm -rf x') { - expect(shouldDropQuarantinedTerminalInput(TAB, char, at)).toBe(true) - at += 30 - } - // The user's own Enter would have submitted the mangled line. - expect(shouldDropQuarantinedTerminalInput(TAB, '\r', at)).toBe(true) - expect(isTerminalInputQuarantined(TAB)).toBe(false) - }) - - it('releases on an idle gap once a quarantined byte has been seen', () => { - armTerminalInputQuarantine(TAB, 0) - // Burst tail, no Enter — the user was still mid-line when the endpoint died. - expect(shouldDropQuarantinedTerminalInput(TAB, 'c', REATTACH_MS)).toBe(true) - expect(shouldDropQuarantinedTerminalInput(TAB, 'h', REATTACH_MS + 40)).toBe(true) - // Then they notice, pause, and type a real command. - expect(shouldDropQuarantinedTerminalInput(TAB, 'l', REATTACH_MS + 40 + 700)).toBe(false) - expect(isTerminalInputQuarantined(TAB)).toBe(false) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/input/terminal-user-input-signal.test.ts b/src/renderer/src/components/terminal-pane/input/terminal-user-input-signal.test.ts deleted file mode 100644 index f7a88d0092b..00000000000 --- a/src/renderer/src/components/terminal-pane/input/terminal-user-input-signal.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { Terminal } from '@xterm/xterm' -import { - subscribeToTerminalInputData, - subscribeToTerminalUserInput -} from './terminal-user-input-signal' - -type CoreServiceAccess = { - _core: { - coreService: { - triggerDataEvent: (data: string, wasUserInput?: boolean) => void - } - } -} - -// Use vendored xterm so private input-signal API drift fails here instead of silently disabling activity tracking. -describe('subscribeToTerminalUserInput', () => { - it('fires for real user input and not for parser auto-replies', () => { - const terminal = new Terminal({ allowProposedApi: true }) - const listener = vi.fn() - const subscription = subscribeToTerminalUserInput(terminal, listener) - expect(subscription).not.toBeNull() - - const coreService = (terminal as unknown as CoreServiceAccess)._core.coreService - // Keyboard/IME/paste/mouse paths mark their data as user input. - coreService.triggerDataEvent('a', true) - expect(listener).toHaveBeenCalledTimes(1) - - // Parser replies still reach onData but must not count as user input. - const onData = vi.fn() - terminal.onData(onData) - coreService.triggerDataEvent('\x1b[O', false) - coreService.triggerDataEvent('\x1b[?1;2c') - expect(listener).toHaveBeenCalledTimes(1) - expect(onData).toHaveBeenCalledTimes(2) - - subscription?.dispose() - coreService.triggerDataEvent('b', true) - expect(listener).toHaveBeenCalledTimes(1) - terminal.dispose() - }) - - it('returns null when the core signal is unavailable', () => { - const listener = vi.fn() - expect(subscribeToTerminalUserInput({} as never, listener)).toBeNull() - expect( - subscribeToTerminalUserInput({ _core: { coreService: {} } } as never, listener) - ).toBeNull() - expect( - subscribeToTerminalUserInput( - { - _core: { - coreService: { - onUserInput: () => { - throw new Error('unavailable') - } - } - } - } as never, - listener - ) - ).toBeNull() - // A subscription without usable disposal is unavailable; preserve callers’ onData fallback. - expect( - subscribeToTerminalUserInput( - { _core: { coreService: { onUserInput: () => undefined } } } as never, - listener - ) - ).toBeNull() - expect( - subscribeToTerminalUserInput( - { _core: { coreService: { onUserInput: () => ({}) } } } as never, - listener - ) - ).toBeNull() - expect(listener).not.toHaveBeenCalled() - }) -}) - -describe('subscribeToTerminalInputData', () => { - it('classifies real xterm events independently and disposes both subscriptions', () => { - const terminal = new Terminal({ allowProposedApi: true }) - const core = (terminal as unknown as CoreServiceAccess)._core.coreService - const listener = vi.fn() - const subscription = subscribeToTerminalInputData(terminal, listener) - core.triggerDataEvent('keyboard', true) - core.triggerDataEvent('\x1b[?1;2c') - core.triggerDataEvent('\x1b[200~paste\x1b[201~', true) - core.triggerDataEvent('\x1b[O', false) - expect(listener.mock.calls).toEqual([ - ['keyboard', true], - ['\x1b[?1;2c', false], - ['\x1b[200~paste\x1b[201~', true], - ['\x1b[O', false] - ]) - subscription.dispose() - core.triggerDataEvent('after-dispose', true) - expect(listener).toHaveBeenCalledTimes(4) - terminal.dispose() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/close/CloseTerminalDialog.test.tsx b/src/renderer/src/components/terminal-pane/layout/close/CloseTerminalDialog.test.tsx deleted file mode 100644 index e6dafd44026..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/close/CloseTerminalDialog.test.tsx +++ /dev/null @@ -1,113 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import CloseTerminalDialog from './CloseTerminalDialog' - -vi.mock('@/i18n/i18n', () => ({ - translate: vi.fn((_key: string, fallback: string) => fallback) -})) - -const mountedRoots: Root[] = [] - -async function renderDialog(props: { - copyKind?: 'command' | 'agent' - onConfirm: (dontAskAgain: boolean) => void - onCancel?: () => void -}): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - mountedRoots.push(root) - - await act(async () => { - root.render( - - ) - }) -} - -function clickButton(label: string): void { - const button = [...document.body.querySelectorAll('button')].find( - (candidate) => candidate.textContent === label - ) - if (!button) { - throw new Error(`Button not found: ${label}`) - } - button.click() -} - -afterEach(async () => { - await act(async () => { - for (const root of mountedRoots.splice(0)) { - root.unmount() - } - }) - document.body.innerHTML = '' -}) - -describe('CloseTerminalDialog', () => { - it('renders running command copy and confirms without skipping by default', async () => { - const onConfirm = vi.fn() - - await renderDialog({ copyKind: 'command', onConfirm }) - - await act(async () => { - clickButton('Stop and Close') - }) - - expect(onConfirm).toHaveBeenCalledWith(false) - }) - - it('renders agent copy and passes the skip preference when checked', async () => { - const onConfirm = vi.fn() - - await renderDialog({ copyKind: 'agent', onConfirm }) - - const checkbox = document.body.querySelector('[role="checkbox"]') - expect(checkbox).not.toBeNull() - - await act(async () => { - checkbox?.click() - }) - await act(async () => { - clickButton('Stop Agent') - }) - - expect(onConfirm).toHaveBeenCalledWith(true) - }) - - it('resets the skip preference when the dialog closes and reopens', async () => { - const onConfirm = vi.fn() - const onCancel = vi.fn() - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - mountedRoots.push(root) - const render = async (open: boolean): Promise => { - await act(async () => { - root.render() - }) - } - - await render(true) - const checkbox = document.body.querySelector('[role="checkbox"]') - await act(async () => { - checkbox?.click() - }) - expect(checkbox?.getAttribute('aria-checked')).toBe('true') - - await render(false) - await render(true) - - expect(document.body.querySelector('[role="checkbox"]')?.getAttribute('aria-checked')).toBe( - 'false' - ) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/close/PinnedTabCloseDialog.test.tsx b/src/renderer/src/components/terminal-pane/layout/close/PinnedTabCloseDialog.test.tsx deleted file mode 100644 index 8fe713998fc..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/close/PinnedTabCloseDialog.test.tsx +++ /dev/null @@ -1,142 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import type { AppState } from '@/store/types' -import PinnedTabCloseDialog from './PinnedTabCloseDialog' - -const initialState = useAppStore.getInitialState() -const mountedRoots: Root[] = [] - -async function renderDialog({ - tabLabel = 'Docs', - onConfirm, - onCancel, - updateSettings -}: { - tabLabel?: string - onConfirm: () => void - onCancel?: () => void - updateSettings: AppState['updateSettings'] -}): Promise { - useAppStore.setState({ - settings: { confirmClosePinnedTab: true } as AppState['settings'], - updateSettings - }) - useAppStore.getState().requestPinnedTabCloseConfirm({ - tabLabel, - onConfirm, - ...(onCancel ? { onCancel } : {}) - }) - - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - mountedRoots.push(root) - - await act(async () => { - root.render() - }) -} - -function getButton(label: string): HTMLButtonElement { - const button = [...document.body.querySelectorAll('button')].find( - (candidate) => candidate.textContent === label - ) - if (!button) { - throw new Error(`Button not found: ${label}`) - } - return button -} - -function getCheckbox(): HTMLButtonElement { - const checkbox = document.body.querySelector('[role="checkbox"]') - if (!checkbox) { - throw new Error('Checkbox not found') - } - return checkbox -} - -beforeEach(() => { - useAppStore.setState(initialState, true) -}) -afterEach(async () => { - await act(async () => { - for (const root of mountedRoots.splice(0)) { - root.unmount() - } - }) - document.body.innerHTML = '' - useAppStore.setState(initialState, true) -}) - -describe('PinnedTabCloseDialog', () => { - it('confirms without changing the preference by default', async () => { - const onConfirm = vi.fn() - const updateSettings = vi.fn().mockResolvedValue(undefined) - - await renderDialog({ onConfirm, updateSettings }) - - await act(async () => { - getButton('Close').click() - }) - - expect(updateSettings).not.toHaveBeenCalled() - expect(onConfirm).toHaveBeenCalledTimes(1) - }) - - it('turns off future pinned-tab confirmations when checked and confirmed', async () => { - const onConfirm = vi.fn() - const updateSettings = vi.fn().mockResolvedValue(undefined) - - await renderDialog({ onConfirm, updateSettings }) - - await act(async () => { - getCheckbox().click() - }) - await act(async () => { - getButton('Close').click() - }) - - expect(updateSettings).toHaveBeenCalledWith({ confirmClosePinnedTab: false }) - expect(onConfirm).toHaveBeenCalledTimes(1) - }) - - it('does not persist the checkbox on cancel and resets it for the next request', async () => { - const firstOnConfirm = vi.fn() - const secondOnConfirm = vi.fn() - const onCancel = vi.fn() - const updateSettings = vi.fn().mockResolvedValue(undefined) - - await renderDialog({ onConfirm: firstOnConfirm, onCancel, updateSettings }) - - await act(async () => { - getCheckbox().click() - }) - await act(async () => { - getButton('Cancel').click() - }) - - expect(onCancel).toHaveBeenCalledTimes(1) - expect(firstOnConfirm).not.toHaveBeenCalled() - expect(updateSettings).not.toHaveBeenCalled() - - await act(async () => { - useAppStore.getState().requestPinnedTabCloseConfirm({ - tabLabel: 'Console', - onConfirm: secondOnConfirm - }) - }) - - expect(getCheckbox().getAttribute('aria-checked')).toBe('false') - - await act(async () => { - getButton('Close').click() - }) - - expect(updateSettings).not.toHaveBeenCalled() - expect(secondOnConfirm).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx b/src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx index 009abe5c0c3..2deb7ccab43 100644 --- a/src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx +++ b/src/renderer/src/components/terminal-pane/layout/close/RunningTerminalCloseDialog.test.tsx @@ -83,40 +83,6 @@ afterEach(async () => { }) describe('RunningTerminalCloseDialog', () => { - it('names the tab so a background close is not ambiguous', async () => { - const onConfirm = vi.fn() - const updateSettings = vi.fn().mockResolvedValue(undefined) - - await renderDialog({ onConfirm }, updateSettings) - - expect(document.body.textContent).toContain('Stop running command?') - expect(document.body.textContent).toContain('dev server') - - await act(async () => { - getButton('Stop and Close').click() - }) - - expect(updateSettings).not.toHaveBeenCalled() - expect(onConfirm).toHaveBeenCalledTimes(1) - }) - - it('uses truthful chat copy and the shared opt-out without terminal sleep advice', async () => { - const updateSettings = vi.fn().mockResolvedValue(undefined) - const onConfirm = vi.fn() - await renderDialog({ onConfirm, copyKind: 'chat-agent' }, updateSettings) - - await act(async () => { - getCheckbox().click() - }) - await act(async () => { - getButton('Stop Agent').click() - }) - expect(updateSettings).toHaveBeenCalledWith({ - skipCloseTerminalWithRunningProcessConfirm: true - }) - expect(onConfirm).toHaveBeenCalledTimes(1) - }) - it('waits for a visible pinned confirmation instead of stacking a second modal', async () => { const updateSettings = vi.fn().mockResolvedValue(undefined) useAppStore.setState({ @@ -134,38 +100,6 @@ describe('RunningTerminalCloseDialog', () => { expect(document.body.textContent).toContain('Stop running command?') }) - it('does not carry the opt-out tick over to the next queued tab', async () => { - const updateSettings = vi.fn().mockResolvedValue(undefined) - const nextOnConfirm = vi.fn() - - await renderDialog({ onConfirm: vi.fn(), onCancel: vi.fn() }, updateSettings) - await act(async () => { - useRunningTerminalCloseConfirmStore.getState().requestRunningTerminalCloseConfirm({ - terminalTabId: 'tab-2', - tabLabel: 'build watcher', - copyKind: 'command', - onConfirm: nextOnConfirm - }) - }) - - await act(async () => { - getCheckbox().click() - }) - await act(async () => { - getButton('Cancel').click() - }) - - expect(document.body.textContent).toContain('build watcher') - - advancePastGuard() - await act(async () => { - getButton('Stop and Close').click() - }) - - expect(updateSettings).not.toHaveBeenCalled() - expect(nextOnConfirm).toHaveBeenCalledTimes(1) - }) - it('drops a queued prompt once the user opts out of asking again', async () => { const updateSettings = vi.fn().mockResolvedValue(undefined) const onConfirm = vi.fn() @@ -195,36 +129,4 @@ describe('RunningTerminalCloseDialog', () => { expect(nextOnConfirm).toHaveBeenCalledTimes(1) expect(document.body.textContent).not.toContain('build watcher') }) - - it('cancels without closing and shows the next queued tab', async () => { - const onConfirm = vi.fn() - const onCancel = vi.fn() - const nextOnConfirm = vi.fn() - const updateSettings = vi.fn().mockResolvedValue(undefined) - - await renderDialog({ onConfirm, onCancel }, updateSettings) - await act(async () => { - useRunningTerminalCloseConfirmStore.getState().requestRunningTerminalCloseConfirm({ - terminalTabId: 'tab-2', - tabLabel: 'build watcher', - copyKind: 'command', - onConfirm: nextOnConfirm - }) - }) - - await act(async () => { - getButton('Cancel').click() - }) - - expect(onCancel).toHaveBeenCalledTimes(1) - expect(onConfirm).not.toHaveBeenCalled() - expect(document.body.textContent).toContain('build watcher') - - advancePastGuard() - await act(async () => { - getButton('Stop and Close').click() - }) - - expect(nextOnConfirm).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/renderer/src/components/terminal-pane/layout/close/closed-terminal-leaf-notice-layout-owner.test.ts b/src/renderer/src/components/terminal-pane/layout/close/closed-terminal-leaf-notice-layout-owner.test.ts deleted file mode 100644 index 9fabab343bb..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/close/closed-terminal-leaf-notice-layout-owner.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { CLOSE_TERMINAL_PANE_EVENT } from '@/constants/terminal' - -vi.mock('../../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } })) - -import { applyClosedTerminalLeafNotice } from './closed-terminal-leaf-notice' -import { - _resetTerminalPaneSplitRequestRoutingForTests, - hasTerminalPaneSplitMountLease, - takeQueuedTerminalPaneSplitRequests -} from '../split/terminal-pane-split-request-routing' - -afterEach(() => { - _resetTerminalPaneSplitRequestRoutingForTests() - vi.unstubAllGlobals() -}) - -describe('a pane main closed before its tab mounted, in a layout-owner build', () => { - // Main-owned splits mount from frames; once main removes the leaf, no window-side deferred mount may remain. - it('leaves nothing waiting to mount it, and drops it from a mounted tab as before', () => { - const target = new EventTarget() - vi.stubGlobal('window', target) - const closed = vi.fn() - target.addEventListener(CLOSE_TERMINAL_PANE_EVENT, (event) => { - if (event instanceof CustomEvent) { - closed(event.detail) - } - }) - - applyClosedTerminalLeafNotice('tab-1', '22222222-2222-4222-8222-222222222222', 'requested') - - expect(takeQueuedTerminalPaneSplitRequests('tab-1', 'wt-1')).toEqual([]) - expect(hasTerminalPaneSplitMountLease('tab-1')).toBe(false) - expect(closed).toHaveBeenCalledWith({ - tabId: 'tab-1', - leafId: '22222222-2222-4222-8222-222222222222', - lastPaneCloseReason: 'requested' - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/close/layout-owner-pane-close.test.ts b/src/renderer/src/components/terminal-pane/layout/close/layout-owner-pane-close.test.ts deleted file mode 100644 index 03b58aef2b4..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/close/layout-owner-pane-close.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import { preparePendingSplitClose } from './pending-split-close-test-fixture' -import type { sendLayoutCommandToOwner } from '@/runtime/layout-owner-command' -import { LOCAL_LAYOUT_APPLY_ORIGIN } from '@/runtime/server-layout-apply-routes' - -const mocks = vi.hoisted(() => ({ - layoutOwnerIsMain: false, - commitTerminalSurfaceClose: vi.fn(), - sendLayoutCommandToOwner: vi.fn(), - noteAgentLaunchPaneClosedByUser: vi.fn() -})) - -vi.mock('../../../../../../shared/layout-owner-switch', () => ({ - get ORCA_LAYOUT_OWNER_IS_MAIN() { - return mocks.layoutOwnerIsMain - } -})) -vi.mock('@/runtime/layout-owner-command', () => ({ - sendLayoutCommandToOwner: mocks.sendLayoutCommandToOwner -})) -vi.mock('@/lib/agent-session/launch/pane/agent-launch-pane-closes', () => ({ - noteAgentLaunchPaneClosedByUser: mocks.noteAgentLaunchPaneClosedByUser -})) -vi.mock('@/store/terminals/terminal-surface-close-intent', () => ({ - commitTerminalSurfaceClose: mocks.commitTerminalSurfaceClose -})) - -const LEAF = '11111111-1111-4111-8111-111111111111' - -beforeEach(() => { - mocks.layoutOwnerIsMain = false - mocks.commitTerminalSurfaceClose.mockReset() - mocks.sendLayoutCommandToOwner.mockReset() - mocks.noteAgentLaunchPaneClosedByUser.mockReset() - mocks.sendLayoutCommandToOwner.mockReturnValue(true) -}) - -it('a window-owned build closes the pane at once and reports it to main', async () => { - const p = await preparePendingSplitClose() - - p.actions.executeClosePane(1, 'user') - - expect(mocks.sendLayoutCommandToOwner).not.toHaveBeenCalled() - expect(mocks.commitTerminalSurfaceClose).toHaveBeenCalledWith('workspace', { - kind: 'pane', - tabId: 'tab-parent', - leafId: LEAF - }) - expect(p.transports.has(1)).toBe(false) -}) - -it('a layout-owner build removes the pane only once main’s frame drops it', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - const intents = await import('@/runtime/layout-owner-pane-intents') - ;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1) - - p.actions.executeClosePane(1, 'user') - - expect(mocks.sendLayoutCommandToOwner).toHaveBeenCalledWith( - 'workspace', - { type: 'closePane', tabId: 'tab-parent', leafId: LEAF }, - { - apply: expect.any(Function), - asToday: expect.any(Function), - refused: expect.any(Function) - } - ) - mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].apply({}, LOCAL_LAYOUT_APPLY_ORIGIN) - expect(p.transports.has(1)).toBe(true) - - // The frame without the pane finds the window's close and runs it. - expect(intents.takePaneCloseIntent('tab-parent', LEAF)).toBe('user') - p.actions.closePaneLocally(1, LEAF, 'user') - - expect(p.transports.has(1)).toBe(false) - expect(mocks.commitTerminalSurfaceClose).not.toHaveBeenCalled() -}) - -it('a layout-owner build closes the pane itself when main closed it and no frame is coming', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - ;(await import('@/runtime/layout-frame-position')).endLayoutFramePositions() - - p.actions.executeClosePane(1, 'user') - mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].apply({}, LOCAL_LAYOUT_APPLY_ORIGIN) - - expect(p.transports.has(1)).toBe(false) - expect(mocks.commitTerminalSurfaceClose).not.toHaveBeenCalled() -}) - -it('a layout-owner build closes the pane itself when main holds no such pane, so no frame drops it', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - ;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1) - - p.actions.executeClosePane(1, 'user') - mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].apply( - { alreadyClosed: true }, - LOCAL_LAYOUT_APPLY_ORIGIN - ) - - const intents = await import('@/runtime/layout-owner-pane-intents') - expect(intents.takePaneCloseIntent('tab-parent', LEAF)).toBeNull() - expect(p.transports.has(1)).toBe(false) - expect(mocks.commitTerminalSurfaceClose).not.toHaveBeenCalled() -}) - -it('a layout-owner build closes as today, forgetting its close, when main lacks the pane', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - - p.actions.executeClosePane(1, 'user') - mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].asToday() - - const intents = await import('@/runtime/layout-owner-pane-intents') - expect(intents.takePaneCloseIntent('tab-parent', LEAF)).toBeNull() - expect(mocks.commitTerminalSurfaceClose).toHaveBeenCalledOnce() - expect(p.transports.has(1)).toBe(false) -}) - -it('a layout-owner build closes the tab when main refuses a second close as the last pane', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - p.actions.executeClosePane(1, 'user') - p.actions.executeClosePane(2, 'user') - const [first, second] = mocks.sendLayoutCommandToOwner.mock.calls.map(([, , on]) => on) - - // Main took pane 1; its frame is still on the way when main refuses pane 2 as its last. - ;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1) - first?.apply({}, LOCAL_LAYOUT_APPLY_ORIGIN) - second?.refused?.('last_pane') - - expect(p.controller.onCloseTab).toHaveBeenCalledOnce() -}) - -it("a layout-owner build closes the tab with the pane close's own reason, never an implied user close", async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - p.actions.executeClosePane(1, 'cleanup') - p.actions.executeClosePane(2, 'cleanup') - const [first, second] = mocks.sendLayoutCommandToOwner.mock.calls.map(([, , on]) => on) - - ;(await import('@/runtime/layout-frame-position')).noteLayoutFramePosition(1) - first?.apply({}, LOCAL_LAYOUT_APPLY_ORIGIN) - second?.refused?.('last_pane') - - expect(p.controller.onCloseTab).toHaveBeenCalledWith('cleanup') -}) - -it('a layout-owner build leaves an unmounted tab alone when main refuses its last pane', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - p.actions.executeClosePane(1, 'user') - p.controller.managerRef.current = null - - mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].refused?.('last_pane') - - expect(p.controller.onCloseTab).not.toHaveBeenCalled() -}) - -it('a layout-owner build closes as today when main calls it the last pane but the window has more', async () => { - mocks.layoutOwnerIsMain = true - const p = await preparePendingSplitClose() - p.actions.executeClosePane(1, 'user') - - mocks.sendLayoutCommandToOwner.mock.calls[0]?.[2].refused?.('last_pane') - - expect(p.controller.onCloseTab).not.toHaveBeenCalled() - expect(mocks.commitTerminalSurfaceClose).toHaveBeenCalledOnce() - expect(p.transports.has(1)).toBe(false) -}) - -it.each([ - ['user', true], - ['cleanup', false] -] as const)( - 'a %s close of a starting launch pane stops its launch only when the user closed it', - async (reason, stopsLaunch) => { - const p = await preparePendingSplitClose() - const { useAppStore } = await import('../../../../store/index') - const [tab] = useAppStore.getState().tabsByWorktree.workspace ?? [] - Object.assign(tab!, { agentLaunchPane: { leafId: LEAF } }) - - p.actions.executeClosePane(1, reason) - - expect(mocks.noteAgentLaunchPaneClosedByUser).toHaveBeenCalledTimes(stopsLaunch ? 1 : 0) - } -) diff --git a/src/renderer/src/components/terminal-pane/layout/close/pending-pane-close-confirmation.test.ts b/src/renderer/src/components/terminal-pane/layout/close/pending-pane-close-confirmation.test.ts index e916aedfc35..af3563f9cca 100644 --- a/src/renderer/src/components/terminal-pane/layout/close/pending-pane-close-confirmation.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/close/pending-pane-close-confirmation.test.ts @@ -44,131 +44,6 @@ async function prepare(remote = false, requestedPtyId?: string) { return { ...p, paired, actions, probePtyRunningWork, verdict, reply, closed, settle } } -it.each([false, true])('requires confirmation for pending live work, paired=%s', async (remote) => { - const p = await prepare(remote) - p.actions.handleRequestClosePane(1) - expect(p.probePtyRunningWork).toHaveBeenCalledWith( - [remote ? 'remote:env-1@@term_original' : 'pty-restored'], - expect.any(Object) - ) - expect(p.closed()).toBe(false) - p.verdict('live') - await flushPtySideEffects() - expect(p.controller.setPendingCloseConfirmation).toHaveBeenCalledWith( - expect.objectContaining({ paneId: 1 }) - ) - expect(p.closed()).toBe(false) - p.actions.handleConfirmClose(false) - await p.settle() - expect(p.closed()).toBe(true) -}) - -it.each([false, true])('Cancel preserves pending work, paired=%s', async (remote) => { - const p = await prepare(remote) - p.actions.handleRequestClosePane(1) - p.verdict('live') - await flushPtySideEffects() - p.actions.handleCancelClose() - p.actions.handleConfirmClose(false) - await p.settle() - expect(p.closed()).toBe(false) -}) - -it.each(['unverifiable', 'rejected', 'timeout'] as const)( - 'requires confirmation when a pending owner probe is %s', - async (mode) => { - vi.useFakeTimers() - const p = await prepare() - p.actions.handleRequestClosePane(1) - if (mode === 'rejected') { - p.reply.reject(new Error('owner unavailable')) - } else if (mode === 'unverifiable') { - p.verdict(mode) - } else { - await vi.advanceTimersByTimeAsync(101) - } - await Promise.resolve() - await Promise.resolve() - expect(p.controller.setPendingCloseConfirmation).toHaveBeenCalled() - expect(p.closed()).toBe(false) - p.actions.handleCancelClose() - p.verdict('exited') - vi.useRealTimers() - await p.settle() - expect(p.closed()).toBe(false) - } -) - -it('uses the direct SSH identity in the running-work probe', async () => { - const id = 'ssh:ssh-1@@pty-restored' - const p = await prepare(false, id) - p.state.worktreesByRepo = { repo: [{ id: 'workspace', repoId: 'repo', hostId: 'ssh:ssh-1' }] } - p.actions.handleRequestClosePane(1) - p.verdict('live') - await flushPtySideEffects() - expect(p.probePtyRunningWork).toHaveBeenCalledWith([id], expect.any(Object)) - expect(p.closed()).toBe(false) - p.actions.handleConfirmClose(false) - await p.settle() - expect(p.closed()).toBe(true) - expect(window.api.pty.kill).toHaveBeenCalledWith(id) -}) - -it.each(['rejected', 'timeout'] as const)( - 'honors the skip-confirmation setting when a pending probe is %s', - async (mode) => { - vi.useFakeTimers() - const p = await prepare() - Object.assign(p.state, { settings: { skipCloseTerminalWithRunningProcessConfirm: true } }) - p.actions.handleRequestClosePane(1) - if (mode === 'rejected') { - p.reply.reject(new Error('owner unavailable')) - } else { - await vi.advanceTimersByTimeAsync(101) - } - await Promise.resolve() - await Promise.resolve() - expect(p.controller.setPendingCloseConfirmation).not.toHaveBeenCalled() - expect(p.closed()).toBe(true) - p.verdict('exited') - vi.useRealTimers() - await p.settle() - } -) - -it.each(['exited', 'skip-setting'] as const)('keeps allowed pending close for %s', async (mode) => { - const p = await prepare() - if (mode === 'skip-setting') { - Object.assign(p.state, { settings: { skipCloseTerminalWithRunningProcessConfirm: true } }) - } - p.actions.handleRequestClosePane(1) - p.verdict(mode === 'exited' ? 'exited' : 'live') - await flushPtySideEffects() - expect(p.controller.setPendingCloseConfirmation).not.toHaveBeenCalled() - await p.settle() - expect(p.closed()).toBe(true) -}) - -it.each(['probe', 'dialog'] as const)( - 'accepts the same pending attach finishing during %s', - async (phase) => { - const p = await prepare() - p.actions.handleRequestClosePane(1) - if (phase === 'dialog') { - p.verdict('live') - await flushPtySideEffects() - } - p.spawn.resolve({ id: 'pty-restored', isReattach: true }) - await p.connecting - p.verdict('live') - await flushPtySideEffects() - expect(p.closed()).toBe(false) - p.actions.handleConfirmClose(false) - await flushPtySideEffects() - expect(p.closed()).toBe(true) - } -) - it.each(['tab', 'generation', 'leaf', 'transport', 'manager', 'whole-tab', 'binding'] as const)( 'does not apply a pending confirmation to a replacement %s', async (replacement) => { diff --git a/src/renderer/src/components/terminal-pane/layout/close/pending-runtime-pane-close.test.ts b/src/renderer/src/components/terminal-pane/layout/close/pending-runtime-pane-close.test.ts index 00ff3fa823a..c0a4e9447e6 100644 --- a/src/renderer/src/components/terminal-pane/layout/close/pending-runtime-pane-close.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/close/pending-runtime-pane-close.test.ts @@ -1,40 +1,7 @@ -import { expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { preparePendingRuntimeClose } from './pending-runtime-pane-close-test-fixture' import { makeCloseTestTab } from './pending-split-close-test-fixture' -it('closes the captured scoped handle while actual remote attach is still unbound', async () => { - const p = await preparePendingRuntimeClose() - expect(p.runtimeCall).toHaveBeenCalledWith( - expect.objectContaining({ method: 'terminal.resolvePane' }) - ) - expect(p.remote.getPtyId()).toBeNull() - p.actions.executeClosePane(1, 'user') - expect(p.runtimeCall).toHaveBeenCalledWith(expect.objectContaining({ method: 'status.get' })) - p.acceptCompatibility() - await p.settle() - expect(p.runtimeCall).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'terminal.close', - params: { terminal: 'term_original' }, - expectedEnvironmentPairingRevision: 1 - }) - ) - expect(window.api.pty.kill).not.toHaveBeenCalled() -}) - -it('normal remount keeps the captured remote handle', async () => { - const p = await preparePendingRuntimeClose() - p.remote.detach?.() - p.acceptCompatibility() - await p.settle() - expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).not.toContain( - 'terminal.close' - ) - expect(p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId?.[p.leafId]).toBe( - 'remote:env-1@@term_original' - ) -}) - it.each(['same-leaf', 'other-tab', 'bound-transport', 'worktree-owner', 'pairing'] as const)( 'rechecks %s ownership after compatibility settles', async (owner) => { @@ -68,49 +35,6 @@ it.each(['same-leaf', 'other-tab', 'bound-transport', 'worktree-owner', 'pairing } ) -it('protects a sibling legacy alias before issuing a compatibility request', async () => { - const p = await preparePendingRuntimeClose() - p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId = { - [p.leafId]: 'remote:env-1@@term_original', - [p.siblingLeafId]: 'remote:term_original' - } - p.actions.executeClosePane(1, 'user') - p.acceptCompatibility() - await p.settle() - expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).toEqual([ - 'terminal.resolvePane' - ]) -}) - -it.each(['ssh:host@@native-hint', 'remote:term_original', 'remote:env-2@@term_original'])( - 'refuses to infer close authority from %s', - async (id) => { - const p = await preparePendingRuntimeClose(id) - p.actions.executeClosePane(1, 'user') - p.acceptCompatibility() - await p.settle() - expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).not.toContain( - 'terminal.close' - ) - expect(window.api.pty.kill).not.toHaveBeenCalled() - } -) - -it('does not bypass a failed compatibility check', async () => { - const p = await preparePendingRuntimeClose() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - p.actions.executeClosePane(1, 'user') - p.compatibility.reject(new Error('incompatible runtime')) - await p.settle() - expect(p.runtimeCall.mock.calls.map(([request]) => request.method)).not.toContain( - 'terminal.close' - ) - expect(warn).toHaveBeenCalledWith( - '[terminal-retirement] provider teardown failed', - expect.objectContaining({ runtimeFailures: 1 }) - ) -}) - it('never turns a late different resolved handle into close authority', async () => { const p = await preparePendingRuntimeClose() p.actions.executeClosePane(1, 'user') diff --git a/src/renderer/src/components/terminal-pane/layout/close/pending-split-close.test.ts b/src/renderer/src/components/terminal-pane/layout/close/pending-split-close.test.ts index f09b8d46d64..d0383699739 100644 --- a/src/renderer/src/components/terminal-pane/layout/close/pending-split-close.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/close/pending-split-close.test.ts @@ -1,7 +1,6 @@ import { expect, it, vi } from 'vitest' import { makeCloseTestTab, preparePendingSplitClose } from './pending-split-close-test-fixture' -import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' -import { flushPtySideEffects } from '../../pty-transport/ipc/pty-transport-test-harness' + import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' const replyFor = (kind: 'reattach' | 'cold-restore-new' | 'ordinary-fresh') => ({ @@ -10,75 +9,6 @@ const replyFor = (kind: 'reattach' | 'cold-restore-new' | 'ordinary-fresh') => ( ...(kind === 'cold-restore-new' ? { coldRestore: { scrollback: 'saved', cwd: '/tmp' } } : {}) }) -it.each(['reattach', 'cold-restore-new', 'ordinary-fresh'] as const)( - 'explicit split close retires a pending %s before and after its reply', - async (kind) => { - const p = await preparePendingSplitClose() - expect(p.transport.getPtyId()).toBeNull() - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - expect(p.transports.has(1)).toBe(false) - expect(p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId?.[p.leafId]).toBeUndefined() - expect(window.api.pty.kill).toHaveBeenCalledExactlyOnceWith('pty-restored') - p.spawn.resolve(replyFor(kind)) - await p.connecting - expect(window.api.pty.kill).toHaveBeenCalledTimes(2) - expect(p.transport.getPtyId()).toBeNull() - } -) - -it.each(['reattach', 'cold-restore-new'] as const)( - 'ordinary remount preserves pending %s for adoption', - async (kind) => { - const p = await preparePendingSplitClose() - p.transport.detach?.({ preserveExitObserver: false }) - p.spawn.resolve(replyFor(kind)) - await p.connecting - expect(window.api.pty.kill).not.toHaveBeenCalled() - expect(p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId?.[p.leafId]).toBe('pty-restored') - const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport') - vi.mocked(window.api.pty.spawn).mockResolvedValueOnce({ id: 'pty-restored', isReattach: true }) - const replacement = createIpcPtyTransport({}) - await replacement.connect({ url: '', sessionId: 'pty-restored', callbacks: {} }) - expect(replacement.getPtyId()).toBe('pty-restored') - replacement.detach?.({ preserveExitObserver: false }) - } -) - -it.each(['layout', 'transport'] as const)( - 'protects a sibling owner recorded only in %s', - async (owner) => { - const p = await preparePendingSplitClose() - const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport') - const survivor = createIpcPtyTransport({}) - if (owner === 'transport') { - survivor.attach({ existingPtyId: 'pty-restored', callbacks: {} }) - p.transports.set(2, survivor) - } else { - p.state.terminalLayoutsByTabId[p.tabId].ptyIdsByLeafId = { - [p.leafId]: 'pty-restored', - [p.siblingLeafId]: 'pty-restored' - } - } - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.resolve(replyFor('reattach')) - await p.connecting - expect(window.api.pty.kill).not.toHaveBeenCalled() - survivor.detach?.({ preserveExitObserver: false }) - } -) - -it('protects a different tab owner present before explicit close', async () => { - const p = await preparePendingSplitClose() - p.state.tabsByWorktree.workspace.push(makeCloseTestTab('survivor', 'pty-restored')) - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.resolve(replyFor('cold-restore-new')) - await p.connecting - expect(window.api.pty.kill).not.toHaveBeenCalled() -}) - it.each(['same-leaf', 'different-tab', 'new-transport-map'] as const)( 'protects a %s replacement that adopts after explicit close', async (owner) => { @@ -102,108 +32,6 @@ it.each(['same-leaf', 'different-tab', 'new-transport-map'] as const)( } ) -it('retains explicit close intent across repeated generic destroy calls', async () => { - const p = await preparePendingSplitClose() - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.transport.destroy?.() - p.transport.destroy?.() - p.spawn.resolve(replyFor('cold-restore-new')) - await p.connecting - expect(window.api.pty.kill).toHaveBeenCalledTimes(2) -}) - -it('preserves a different returned reattach identity', async () => { - const p = await preparePendingSplitClose() - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.resolve({ id: 'different-existing-session', isReattach: true }) - await p.connecting - expect(window.api.pty.kill).toHaveBeenCalledExactlyOnceWith('pty-restored') -}) - -it('retries an eager provider failure when the same-ID reply arrives', async () => { - const p = await preparePendingSplitClose() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.mocked(window.api.pty.kill).mockRejectedValueOnce( - new Error('provider temporarily unavailable') - ) - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - await flushPtySideEffects() - expect(warn).toHaveBeenCalledWith( - '[terminal-retirement] provider teardown failed', - expect.any(Object) - ) - p.spawn.resolve(replyFor('reattach')) - await p.connecting - expect(window.api.pty.kill).toHaveBeenCalledTimes(2) -}) - -it('does not invent a late session after a rejected spawn', async () => { - const p = await preparePendingSplitClose() - vi.spyOn(console, 'error').mockImplementation(() => {}) - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.reject(new Error('spawn rejected')) - await p.connecting - expect(window.api.pty.kill).toHaveBeenCalledExactlyOnceWith('pty-restored') -}) - -it('routes direct SSH retirement through the existing IPC identity', async () => { - const id = 'ssh:ssh-1@@pty-restored' - const p = await preparePendingSplitClose(id) - p.state.worktreesByRepo = { repo: [{ id: 'workspace', repoId: 'repo', hostId: 'ssh:ssh-1' }] } - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.resolve({ id, isReattach: true }) - await p.connecting - expect(window.api.pty.kill).toHaveBeenNthCalledWith(1, id) - expect(window.api.pty.kill).toHaveBeenNthCalledWith(2, id) -}) - -it.each(['runtime-handle', 'runtime-legacy', 'unresolved-owner', 'runtime-native-hint'] as const)( - 'never falls through to local kill for %s', - async (kind) => { - const id = - kind === 'runtime-handle' - ? 'remote:env-1@@pty-restored' - : kind === 'runtime-legacy' - ? 'remote:pty-restored' - : 'pty-restored' - const p = await preparePendingSplitClose(id) - if (kind === 'unresolved-owner') { - p.state.worktreesByRepo = {} - } else if (kind === 'runtime-native-hint') { - p.state.worktreesByRepo = { - repo: [ - { - id: 'workspace', - repoId: 'repo', - hostId: 'ssh:ssh-1', - runtimeOwnerEnvironmentId: 'env-1' - } - ] - } - } - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.resolve({ id, isReattach: true }) - await p.connecting - expect(window.api.pty.kill).not.toHaveBeenCalled() - } -) - -it('retires a local folder-workspace split without a git worktree row', async () => { - const p = await preparePendingSplitClose('pty-restored', folderWorkspaceKey('folder-1')) - p.state.worktreesByRepo = {} - p.actions.executeClosePane(1, 'user') - await p.mainAnswered() - p.spawn.resolve(replyFor('reattach')) - await p.connecting - expect(window.api.pty.kill).toHaveBeenCalledTimes(2) -}) - it('commits the explicit split close in main by its leaf without waiting for its write', async () => { const p = await preparePendingSplitClose() // Main's durable write never settles here: the pane must still leave and be killed at once. diff --git a/src/renderer/src/components/terminal-pane/layout/close/request-active-terminal-pane-close.test.ts b/src/renderer/src/components/terminal-pane/layout/close/request-active-terminal-pane-close.test.ts deleted file mode 100644 index c0360e1e3be..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/close/request-active-terminal-pane-close.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - onActiveTerminalPaneCloseRequest, - requestActiveTerminalPaneClose -} from './request-active-terminal-pane-close' - -describe('active terminal pane close request', () => { - const unsubscribes: (() => void)[] = [] - afterEach(() => { - unsubscribes.splice(0).forEach((unsubscribe) => unsubscribe()) - }) - - it('reaches only the pane mounted for the named tab', () => { - const closeA = vi.fn() - const closeB = vi.fn() - unsubscribes.push(onActiveTerminalPaneCloseRequest('tab-a', closeA)) - unsubscribes.push(onActiveTerminalPaneCloseRequest('tab-b', closeB)) - - requestActiveTerminalPaneClose('tab-a') - - expect(closeA).toHaveBeenCalledOnce() - expect(closeB).not.toHaveBeenCalled() - }) - - it('stops reaching a pane once it unsubscribes', () => { - const close = vi.fn() - onActiveTerminalPaneCloseRequest('tab-a', close)() - - requestActiveTerminalPaneClose('tab-a') - - expect(close).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts b/src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts deleted file mode 100644 index 43aa4ecd5d9..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/close/terminal-pane-close-request.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - applyTerminalPaneCloseRequest, - retireMountedTerminalPaneSurface, - suppressIntentionalPaneCloseExit -} from './terminal-pane-lifecycle-close' - -describe('applyTerminalPaneCloseRequest', () => { - it('detaches a rolled-back split surface without closing its PTY', () => { - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getNumericIdForLeaf: vi.fn(() => 2), - closePane: vi.fn(), - detachPaneForExternalMove: vi.fn(() => true), - retirePanePreservingPty: vi.fn(() => true) - } - const closeTab = vi.fn() - const closeTabPreservingPty = vi.fn() - - expect( - applyTerminalPaneCloseRequest({ - detail: { - lastPaneCloseReason: 'cleanup', - tabId: 'legacy-worker', - leafId: '11111111-1111-4111-8111-111111111111', - preservePty: true - }, - manager, - closeTab, - closeTabPreservingPty - }) - ).toBe('pane') - expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(2) - expect(manager.closePane).not.toHaveBeenCalled() - expect(closeTab).not.toHaveBeenCalled() - expect(closeTabPreservingPty).not.toHaveBeenCalled() - }) - - it("closes a tab through its last pane with the requester's reason, never an implied user close", () => { - // A withdrawn launch pane closing the tab must not reach a paired host as the user's close (#37245). - const closeTab = vi.fn() - const manager = { - getPanes: vi.fn(() => [{ id: 1 }]), - getNumericIdForLeaf: vi.fn(() => 1), - closePane: vi.fn(), - detachPaneForExternalMove: vi.fn(() => true), - retirePanePreservingPty: vi.fn(() => true) - } - - applyTerminalPaneCloseRequest({ - detail: { - lastPaneCloseReason: 'cleanup', - tabId: 'launch-tab', - leafId: '11111111-1111-4111-8111-111111111111' - }, - manager, - closeTab, - closeTabPreservingPty: vi.fn() - }) - - expect(closeTab).toHaveBeenCalledWith('cleanup') - }) - - it('uses non-destructive tab close semantics for the last rolled-back pane', () => { - const closeTab = vi.fn() - const closeTabPreservingPty = vi.fn() - - expect( - applyTerminalPaneCloseRequest({ - detail: { - lastPaneCloseReason: 'cleanup', - tabId: 'legacy-worker', - paneRuntimeId: 1, - preservePty: true - }, - manager: { - getPanes: vi.fn(() => [{ id: 1 }]), - getNumericIdForLeaf: vi.fn(() => 1), - closePane: vi.fn(), - detachPaneForExternalMove: vi.fn(() => true), - retirePanePreservingPty: vi.fn(() => true) - }, - closeTab, - closeTabPreservingPty - }) - ).toBe('tab') - expect(closeTabPreservingPty).toHaveBeenCalledOnce() - expect(closeTab).not.toHaveBeenCalled() - }) - - it('ignores a delayed rollback after the pane PTY identity changed', () => { - const manager = { - getPanes: vi.fn(() => [{ id: 1 }]), - getNumericIdForLeaf: vi.fn(() => 1), - closePane: vi.fn(), - detachPaneForExternalMove: vi.fn(() => true), - retirePanePreservingPty: vi.fn(() => true) - } - const closeTab = vi.fn() - const closeTabPreservingPty = vi.fn() - - expect( - applyTerminalPaneCloseRequest({ - detail: { - lastPaneCloseReason: 'cleanup', - tabId: 'legacy-worker', - leafId: '11111111-1111-4111-8111-111111111111', - preservePty: true, - expectedPtyId: 'pty-legacy' - }, - manager, - closeTab, - closeTabPreservingPty, - getPtyIdForLeaf: () => 'pty-replacement' - }) - ).toBe('ignored') - expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled() - expect(closeTabPreservingPty).not.toHaveBeenCalled() - }) - - it('retires a mounted rollback pane without detaching it as a movable surface', () => { - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getNumericIdForLeaf: vi.fn(() => 2), - closePane: vi.fn(), - detachPaneForExternalMove: vi.fn(() => true), - retirePanePreservingPty: vi.fn(() => true) - } - - expect( - applyTerminalPaneCloseRequest({ - detail: { - lastPaneCloseReason: 'cleanup', - tabId: 'legacy-worker', - leafId: '11111111-1111-4111-8111-111111111111', - preservePty: true, - retireSurface: true, - expectedPtyId: 'pty-legacy' - }, - manager, - closeTab: vi.fn(), - closeTabPreservingPty: vi.fn(), - getPtyIdForLeaf: () => 'pty-legacy' - }) - ).toBe('pane') - expect(manager.retirePanePreservingPty).toHaveBeenCalledWith(2) - expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled() - expect(manager.closePane).not.toHaveBeenCalled() - }) - - it('retires mounted authority and binding while preserving the process and sleeping fence', () => { - const retireAgentPaneAuthority = vi.fn() - const syncPanePtyLayoutBinding = vi.fn() - const clearExitedPanePtyLayoutBindingForLeaf = vi.fn() - const clearTabPtyId = vi.fn() - const transport = { detach: vi.fn(), destroy: vi.fn() } - - retireMountedTerminalPaneSurface({ - paneKey: 'legacy-worker:11111111-1111-4111-8111-111111111111', - leafId: '11111111-1111-4111-8111-111111111111', - paneId: 2, - tabId: 'legacy-worker', - ptyId: 'pty-legacy', - retireAgentPaneAuthority, - syncPanePtyLayoutBinding, - clearExitedPanePtyLayoutBindingForLeaf, - clearTabPtyId, - transport - }) - - expect(retireAgentPaneAuthority).toHaveBeenCalledWith( - 'legacy-worker:11111111-1111-4111-8111-111111111111', - { preserveSleepingAgentSession: true } - ) - expect(clearExitedPanePtyLayoutBindingForLeaf).toHaveBeenCalledWith( - '11111111-1111-4111-8111-111111111111', - 'pty-legacy' - ) - expect(syncPanePtyLayoutBinding).not.toHaveBeenCalled() - expect(clearTabPtyId).toHaveBeenCalledWith('legacy-worker', 'pty-legacy') - expect(transport.detach).toHaveBeenCalledOnce() - expect(transport.destroy).not.toHaveBeenCalled() - }) -}) - -describe('suppressIntentionalPaneCloseExit', () => { - it('suppresses the pane PTY exit before intentional close teardown destroys the transport', () => { - const suppressPtyExit = vi.fn() - const transport = { - getPtyId: vi.fn(() => 'pty-pane-2') - } - - expect(suppressIntentionalPaneCloseExit(transport, suppressPtyExit)).toBe('pty-pane-2') - expect(suppressPtyExit).toHaveBeenCalledWith('pty-pane-2') - }) - - it('does not suppress natural PTY exits that already cleared the transport id', () => { - const suppressPtyExit = vi.fn() - const transport = { - getPtyId: vi.fn(() => null) - } - - expect(suppressIntentionalPaneCloseExit(transport, suppressPtyExit)).toBeNull() - expect(suppressPtyExit).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-move-request-routing.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-move-request-routing.test.ts index 44fbcd13088..cee1015a236 100644 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-move-request-routing.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-move-request-routing.test.ts @@ -85,43 +85,6 @@ describe('a pane move a client asked this window for', () => { vi.useRealTimers() }) - it('moves the named pane into the tab the client drew, where the client dropped it', async () => { - const detachPaneToNewTab = vi.fn(() => moved('pty-2')) - unmount = mountTab(detachPaneToNewTab) - - await expect( - moveTerminalPaneToNewTabForClient({ ...request, targetGroupId: 'group-2', index: 0 }) - ).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' }) - expect(detachPaneToNewTab).toHaveBeenCalledWith(2, { - groupId: 'group-2', - index: 0, - targetTabId: 'client-tab' - }) - }) - - it('puts the tab beside its source when this window has no such drop group', async () => { - const detachPaneToNewTab = vi.fn(() => moved('pty-2')) - unmount = mountTab(detachPaneToNewTab) - - await moveTerminalPaneToNewTabForClient({ ...request, targetGroupId: 'gone', index: 3 }) - expect(detachPaneToNewTab).toHaveBeenCalledWith(2, { - groupId: 'group-1', - targetTabId: 'client-tab' - }) - }) - - it('mounts a parked source tab, then moves its pane', async () => { - const detachPaneToNewTab = vi.fn(() => moved('pty-2')) - const answer = moveTerminalPaneToNewTabForClient(request) - expect(requestBackgroundTerminalWorktreeMount).toHaveBeenCalledWith({ - worktreeId: 'wt-1', - tabIds: ['tab-1'] - }) - unmount = mountTab(detachPaneToNewTab) - - await expect(answer).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' }) - }) - it('keeps a parked source tab mounted until a move slower than the mount lease settles', async () => { const detached = Promise.withResolvers>>() const answer = moveTerminalPaneToNewTabForClient(request) @@ -133,12 +96,4 @@ describe('a pane move a client asked this window for', () => { await expect(answer).resolves.toEqual({ status: 'moved', ptyId: 'pty-2' }) expect(hasTerminalPaneSplitMountLease('tab-1', 'wt-1')).toBe(false) }) - - it('refuses when the source tab does not mount, so the client puts the pane back', async () => { - const answer = moveTerminalPaneToNewTabForClient(request) - await vi.runAllTimersAsync() - - await expect(answer).resolves.toEqual({ status: 'refused', reason: 'pane_unavailable' }) - expect(hasTerminalPaneSplitMountLease('tab-1', 'wt-1')).toBe(false) - }) }) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-commit.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-commit.test.ts deleted file mode 100644 index 00ea1d2d3c7..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-commit.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - TerminalLeafMoveRequest, - TerminalLeafMoveResult -} from '../../../../../../shared/workspace-layout/terminal-leaf-move' -import { detachTerminalPaneToTab } from './terminal-pane-tab-detach' -import { - createStore, - LEAF_1, - LEAF_2, - SOURCE_TAB_ID, - splitLayout, - TARGET_GROUP_ID, - unboundSplitLayout, - WORKTREE_ID -} from './terminal-pane-tab-detach-fixture' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' - -// Window-side IPC coverage; main-command/frame equivalents live in terminal-pane-tab-detach-main-commit.test.ts. -const itSwitchOff = it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN) - -const toastErrorMock = vi.hoisted(() => vi.fn()) -vi.mock('sonner', () => ({ toast: { error: toastErrorMock } })) -const closeTerminalSurface = vi.fn(async () => {}) -beforeEach(() => { - toastErrorMock.mockClear() - closeTerminalSurface.mockClear() - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) - -/** Answers each call with the next result; an Error throws. */ -function mainAnswering(results: (TerminalLeafMoveResult | Error)[]) { - return vi.fn((_request: TerminalLeafMoveRequest): Promise => { - const next = results.shift() ?? { status: 'not_held' } - return next instanceof Error ? Promise.reject(next) : Promise.resolve(next) - }) -} - -function managerWithPanes(paneIds: () => number[] = () => [1, 2]) { - return { - getPanes: vi.fn(() => paneIds().map((id) => ({ id }))), - getLeafId: vi.fn((paneId: number): string | null => (paneId === 2 ? LEAF_2 : LEAF_1)), - detachPaneForExternalMove: vi.fn(() => true) - } -} - -type CommitMove = (request: TerminalLeafMoveRequest) => Promise - -function detach( - overrides: Partial[0]> & { - commitMove?: CommitMove - store?: ReturnType - } -) { - const { commitMove = mainAnswering([]), store = createStore(), ...rest } = overrides - vi.stubGlobal('window', { - api: { pty: { moveLeafToNewTab: commitMove }, session: { closeTerminalSurface } } - }) - return detachTerminalPaneToTab({ - getStore: () => store, - manager: managerWithPanes(), - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID, - ...rest - }) -} - -const moved: TerminalLeafMoveResult = { status: 'moved', ptyId: 'remote:env-1@@terminal-1' } - -describe('detachTerminalPaneToTab rolls a committed move forward', () => { - it('refuses, silently, a pane whose PTY spawn is still in flight', async () => { - const commitMove = mainAnswering([{ status: 'moved', ptyId: null }]) - const store = createStore(unboundSplitLayout()) - - await expect(detach({ commitMove, store, sourceConnectPending: true })).resolves.toBeNull() - - expect(commitMove).not.toHaveBeenCalled() - expect(store.createTab).not.toHaveBeenCalled() - expect(toastErrorMock).not.toHaveBeenCalled() - }) - - it('shows the failure toast and keeps the pane when main refuses or the commit throws', async () => { - for (const results of [ - [{ status: 'refused', reason: 'pty_mismatch' } as const], - [new Error('write failed')] - ]) { - toastErrorMock.mockClear() - const store = createStore() - const manager = managerWithPanes() - - await expect( - detach({ commitMove: mainAnswering(results), store, manager }) - ).resolves.toBeNull() - - expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled() - expect(store.createTab).not.toHaveBeenCalled() - expect(toastErrorMock).toHaveBeenCalledOnce() - } - }) - - itSwitchOff( - 'closes main’s new tab, without a toast, when the user closed the pane meanwhile', - async () => { - let paneIds = [1, 2] - const manager = managerWithPanes(() => paneIds) - const commitMove = vi.fn( - async (_request: TerminalLeafMoveRequest): Promise => { - paneIds = [1] - manager.getLeafId.mockImplementation((paneId) => (paneId === 1 ? LEAF_1 : null)) - return moved - } - ) - const store = createStore() - - await expect(detach({ commitMove, manager, store })).resolves.toBeNull() - - const targetTabId = commitMove.mock.calls[0]?.[0]?.targetTabId - expect(closeTerminalSurface).toHaveBeenCalledWith({ - worktreeId: WORKTREE_ID, - target: { kind: 'tab', tabId: targetTabId }, - reason: 'cleanup' - }) - expect(store.createTab).not.toHaveBeenCalled() - expect(toastErrorMock).not.toHaveBeenCalled() - } - ) - - itSwitchOff('closes main’s new tab when the user closed the source tab meanwhile', async () => { - const store = createStore() - const commitMove = vi.fn( - async (_request: TerminalLeafMoveRequest): Promise => { - // A tab close drops its row and its layout. - store.tabsByWorktree[WORKTREE_ID] = [] - delete store.terminalLayoutsByTabId[SOURCE_TAB_ID] - return moved - } - ) - - await expect(detach({ commitMove, store })).resolves.toBeNull() - - expect(closeTerminalSurface).toHaveBeenCalledOnce() - expect(store.createTab).not.toHaveBeenCalled() - }) - - itSwitchOff('finds the pane by its leaf when its pane id changed meanwhile', async () => { - const manager = managerWithPanes(() => [1, 7]) - manager.getLeafId.mockImplementation((paneId) => (paneId === 1 ? LEAF_1 : LEAF_2)) - const commitMove = vi.fn( - async (_request: TerminalLeafMoveRequest): Promise => { - manager.getLeafId.mockImplementation((paneId) => - paneId === 1 ? LEAF_1 : paneId === 7 ? LEAF_2 : null - ) - return moved - } - ) - - await expect(detach({ commitMove, manager })).resolves.toMatchObject({ leafId: LEAF_2 }) - - expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(7) - }) - - itSwitchOff( - 'closes main’s new tab when the pane manager refuses to detach the pane', - async () => { - const manager = managerWithPanes() - manager.detachPaneForExternalMove.mockReturnValue(false) - const commitMove = mainAnswering([moved]) - const store = createStore() - - await expect(detach({ commitMove, manager, store })).resolves.toBeNull() - - expect(closeTerminalSurface).toHaveBeenCalledWith({ - worktreeId: WORKTREE_ID, - target: { kind: 'tab', tabId: commitMove.mock.calls[0]?.[0]?.targetTabId }, - reason: 'cleanup' - }) - expect(store.createTab).not.toHaveBeenCalled() - expect(store.setTabLayout).not.toHaveBeenCalled() - } - ) - - itSwitchOff( - 'moves the last pane, after a sibling closed meanwhile, without killing its PTY', - async () => { - const store = createStore() - let paneIds = [1, 2] - const manager = managerWithPanes(() => paneIds) - const commitMove = vi.fn(async (_request: TerminalLeafMoveRequest) => { - // Closing a pane persists the layout synchronously (onLayoutChanged), as the real close does. - paneIds = [2] - store.terminalLayoutsByTabId[SOURCE_TAB_ID] = { - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'pty-right' } - } - return { status: 'moved', ptyId: 'pty-right' } satisfies TerminalLeafMoveResult - }) - - await expect(detach({ commitMove, manager, store })).resolves.toMatchObject({ - leafId: LEAF_2, - ptyId: 'pty-right' - }) - - expect(closeTerminalSurface).not.toHaveBeenCalled() - expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled() - expect(store.createTab).toHaveBeenCalledOnce() - expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith( - expect.objectContaining({ detachedLeafId: LEAF_2, detachedPtyId: 'pty-right' }) - ) - expect(store.closeTab).toHaveBeenCalledWith( - SOURCE_TAB_ID, - expect.objectContaining({ localPtyTeardownOwnedExternally: true }) - ) - } - ) - - itSwitchOff( - 'commits the move in main before the target tab exists, using the same tab id', - async () => { - const store = createStore() - let release!: () => void - const commitMove = vi.fn( - (_request: TerminalLeafMoveRequest) => - new Promise((resolve) => { - release = () => resolve(moved) - }) - ) - - const detaching = detach({ commitMove, store }) - await vi.waitFor(() => expect(commitMove).toHaveBeenCalledOnce()) - expect(store.createTab).not.toHaveBeenCalled() - release() - await detaching - - const request = commitMove.mock.calls[0]?.[0] - expect(request).toEqual({ - worktreeId: WORKTREE_ID, - sourceTabId: SOURCE_TAB_ID, - targetTabId: expect.any(String), - leafId: LEAF_2, - ptyId: expect.any(String) - }) - expect(store.createTab).toHaveBeenCalledWith( - WORKTREE_ID, - TARGET_GROUP_ID, - 'powershell.exe', - expect.objectContaining({ id: request?.targetTabId, initialLeafId: LEAF_2 }) - ) - } - ) - - itSwitchOff('ignores a repeat drop of a pane whose move is still committing', async () => { - const store = createStore() - let release!: () => void - const commitMove = vi.fn( - (_request: TerminalLeafMoveRequest) => - new Promise((resolve) => { - release = () => resolve(moved) - }) - ) - - const first = detach({ commitMove, store }) - await vi.waitFor(() => expect(commitMove).toHaveBeenCalledOnce()) - await expect(detach({ commitMove, store })).resolves.toBeNull() - release() - - await expect(first).resolves.toMatchObject({ leafId: LEAF_2 }) - expect(commitMove).toHaveBeenCalledOnce() - expect(toastErrorMock).not.toHaveBeenCalled() - }) - - itSwitchOff('binds the moved tab’s layout to the live PTY, not the saved one', async () => { - const store = createStore(splitLayout()) - const saved = store.terminalLayoutsByTabId[SOURCE_TAB_ID]?.ptyIdsByLeafId?.[LEAF_2] - expect(saved).toBeTruthy() - - const result = await detach({ livePtyId: 'pty-respawned', store }) - - expect(result?.ptyId).toBe('pty-respawned') - expect(store.terminalLayoutsByTabId['tab-detached']?.ptyIdsByLeafId?.[LEAF_2]).toBe( - 'pty-respawned' - ) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-frame-drawn.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-frame-drawn.test.ts deleted file mode 100644 index 94a653c2f35..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-frame-drawn.test.ts +++ /dev/null @@ -1,303 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as AgentStatusModule from '../../../../../../shared/agent-status/title/agent-title-status' -import type { sendLayoutCommandToOwner } from '@/runtime/layout-owner-command' -import { createTestStore, seedStore } from '../../../../store/testing/app-store-test-fixture' -import { makeWorktree } from '../../../../store/slices/worktrees/worktree.test-fixture' -import { createStoreCascadesMockApi } from '../../../../store/testing/app-store-cascade-api.test-fixture' -import { detachTerminalPaneToTab } from './terminal-pane-tab-detach' -import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session' -import { buildLayoutFrameSlices } from '../../../../store/workspace-layout/frames/workspace-layout-frame-slices' -import { buildLayoutFrameStorePatch } from '../../../../store/workspace-layout/frames/workspace-layout-frame-store-patch' -import { applyLayoutCommand } from '../../../../../../shared/workspace-layout/workspace-layout-commands' -import { testContext } from '../../../../../../shared/workspace-layout/workspace-layout-command.test-fixture' -import { loadWorkspaceLayoutWithoutReport } from '../../../../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../../../../shared/workspace-layout/workspace-layout-minted-ids' -import { publishWorkspaceLayout } from '../../../../../../shared/workspace-layout/workspace-layout-published' -import { LEAF_1, LEAF_2, splitLayout } from './terminal-pane-tab-detach-fixture' -import { LOCAL_LAYOUT_APPLY_ORIGIN } from '@/runtime/server-layout-apply-routes' - -const mocks = vi.hoisted(() => ({ - send: vi.fn(), - callRuntimeRpc: vi.fn(async (..._args: unknown[]) => ({ ok: true, result: {} })) -})) -vi.mock('../../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('@/runtime/layout-owner-command', () => ({ sendLayoutCommandToOwner: mocks.send })) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: mocks.callRuntimeRpc -})) -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: vi.fn(), - unregisterPtyDataHandlers: vi.fn(() => []) -})) -vi.mock( - '../../../../../../shared/agent-status/title/agent-title-status', - async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } - } -) - -createStoreCascadesMockApi() - -const WT = 'repo1::/path/wt' -const SOURCE = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' -const MOVED = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' -const GROUP = 'group-1' - -function row(id: string, ptyId: string, createdAt: number) { - return { - id, - ptyId, - worktreeId: WT, - title: 'Terminal 1', - defaultTitle: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt - } -} - -function entry(id: string, createdAt: number) { - return { - id, - entityId: id, - groupId: GROUP, - worktreeId: WT, - contentType: 'terminal' as const, - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt - } -} - -/** The source tab split in two, and main's frame already showing the tab the pane moved into. */ -function storeWithFrameDrawnMove() { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt' })] }, - tabsByWorktree: { [WT]: [row(SOURCE, 'pty-left', 1), row(MOVED, 'pty-right', 2)] }, - unifiedTabsByWorktree: { [WT]: [entry(SOURCE, 1), entry(MOVED, 2)] }, - groupsByWorktree: { - [WT]: [ - { - id: GROUP, - worktreeId: WT, - activeTabId: SOURCE, - tabOrder: [SOURCE, MOVED], - recentTabIds: [SOURCE] - } - ] - }, - activeGroupIdByWorktree: { [WT]: GROUP }, - terminalLayoutsByTabId: { - [SOURCE]: { - ...splitLayout(), - ptyIdsByLeafId: { [LEAF_1]: 'pty-left', [LEAF_2]: 'pty-right' } - }, - [MOVED]: { - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'pty-right' } - } - } - }) - return store -} - -/** The source tab alone, split in two, its second pane showing chat. */ -function storeWithChatSplit() { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt' })] }, - tabsByWorktree: { [WT]: [row(SOURCE, 'pty-left', 1)] }, - unifiedTabsByWorktree: { [WT]: [{ ...entry(SOURCE, 1), viewMode: 'chat' }] }, - groupsByWorktree: { - [WT]: [ - { id: GROUP, worktreeId: WT, activeTabId: SOURCE, tabOrder: [SOURCE], recentTabIds: [] } - ] - }, - activeGroupIdByWorktree: { [WT]: GROUP }, - terminalLayoutsByTabId: { - [SOURCE]: { - ...splitLayout(), - chatLeafId: LEAF_2, - ptyIdsByLeafId: { [LEAF_1]: 'pty-left', [LEAF_2]: 'pty-right' } - } - } - }) - return store -} - -/** The source tab split in two, its second pane not yet bound to a terminal. */ -function storeWithUnboundSplit() { - const store = storeWithChatSplit() - const layout = store.getState().terminalLayoutsByTabId[SOURCE]! - store.setState({ - unifiedTabsByWorktree: { [WT]: [entry(SOURCE, 1)] }, - terminalLayoutsByTabId: { - [SOURCE]: { ...layout, chatLeafId: undefined, ptyIdsByLeafId: { [LEAF_1]: 'pty-left' } } - } - }) - return store -} - -type MoveCommand = Parameters[1] & { type: 'movePaneToNewTab' } - -/** Main applies the window's drag-out to its copy and the frame with the result is drawn. */ -function drawMainMove( - store: ReturnType, - windowDetach: MoveCommand['windowDetach'] = { ptyId: 'pty-right' } -): void { - const state = store.getState() - const loaded = loadWorkspaceLayoutWithoutReport( - 'local', - buildWorkspaceSessionPayload(state), - nameBasedLoadContext() - ) - const applied = applyLayoutCommand( - loaded.layout, - { - type: 'movePaneToNewTab', - workspace: WT, - tabId: SOURCE, - leafId: LEAF_2, - groupId: GROUP, - windowDetach: { ...windowDetach, tabId: MOVED } - }, - testContext() - ) - if (!applied.ok) { - throw new Error(`main refused the move: ${applied.code}`) - } - const slices = buildLayoutFrameSlices({ - layouts: { [WT]: publishWorkspaceLayout(applied.model.workspaces[WT]!, 'local') }, - facts: loaded.facts, - view: loaded.desktopView - }) - store.setState(buildLayoutFrameStorePatch(state, slices, [WT])) -} - -beforeEach(() => { - mocks.send.mockReset() - mocks.callRuntimeRpc.mockClear() - vi.stubGlobal('window', { api: { pty: { moveLeafToNewTab: vi.fn() } } }) -}) - -describe('a drag-out whose new tab main’s frame drew first', () => { - it('shows the pane in the tab the frame drew instead of making a second one', async () => { - const store = storeWithFrameDrawnMove() - mocks.send.mockImplementation((_worktreeId, _command, handlers) => { - handlers.apply({ tabId: MOVED, ptyId: 'pty-right' }, LOCAL_LAYOUT_APPLY_ORIGIN) - return true - }) - - const moved = await detachTerminalPaneToTab({ - getStore: () => store.getState(), - manager: { - getPanes: () => [{ id: 1 }, { id: 2 }], - getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1), - detachPaneForExternalMove: () => true - }, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 2, - sourceTabId: SOURCE, - targetGroupId: GROUP, - worktreeId: WT - }) - - expect(moved).toMatchObject({ leafId: LEAF_2, ptyId: 'pty-right', tab: { id: MOVED } }) - const state = store.getState() - expect(state.tabsByWorktree[WT]!.map((tab) => tab.id)).toEqual([SOURCE, MOVED]) - expect(state.terminalLayoutsByTabId[SOURCE]!.root).toEqual({ type: 'leaf', leafId: LEAF_1 }) - expect(state.terminalLayoutsByTabId[MOVED]!.root).toEqual({ type: 'leaf', leafId: LEAF_2 }) - expect(state.activeTabIdByWorktree[WT]).toBe(MOVED) - }) - - it('leaves the tab where main’s frame placed it, asked for an index', async () => { - const store = storeWithFrameDrawnMove() - mocks.send.mockImplementation((_worktreeId, _command, handlers) => { - handlers.apply({ tabId: MOVED, ptyId: 'pty-right' }, LOCAL_LAYOUT_APPLY_ORIGIN) - return true - }) - - await detachTerminalPaneToTab({ - getStore: () => store.getState(), - manager: { - getPanes: () => [{ id: 1 }, { id: 2 }], - getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1), - detachPaneForExternalMove: () => true - }, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 2, - sourceTabId: SOURCE, - targetGroupId: GROUP, - targetIndex: 0, - worktreeId: WT - }) - - expect(store.getState().groupsByWorktree[WT]![0]!.tabOrder).toEqual([SOURCE, MOVED]) - }) - - it('opens a dragged-out chat pane’s tab in chat view, as a window-owned build does', async () => { - const store = storeWithChatSplit() - mocks.send.mockImplementation((_worktreeId, _command, handlers) => { - drawMainMove(store) - handlers.apply({ tabId: MOVED, ptyId: 'pty-right' }, LOCAL_LAYOUT_APPLY_ORIGIN) - return true - }) - - await detachTerminalPaneToTab({ - getStore: () => store.getState(), - manager: { - getPanes: () => [{ id: 1 }, { id: 2 }], - getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1), - detachPaneForExternalMove: () => true - }, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 2, - sourceTabId: SOURCE, - targetGroupId: GROUP, - worktreeId: WT - }) - - const moved = store.getState().unifiedTabsByWorktree[WT]!.find((tab) => tab.entityId === MOVED) - expect(moved?.viewMode).toBe('chat') - expect(store.getState().terminalLayoutsByTabId[MOVED]?.chatLeafId).toBe(LEAF_2) - }) - - it('starts an unbound pane’s new tab in the pane’s folder, as a window-owned build does', async () => { - const store = storeWithUnboundSplit() - mocks.send.mockImplementation((_worktreeId, command, handlers) => { - drawMainMove(store, command.type === 'movePaneToNewTab' ? command.windowDetach : undefined) - handlers.apply({ tabId: MOVED, ptyId: null }, LOCAL_LAYOUT_APPLY_ORIGIN) - return true - }) - - await detachTerminalPaneToTab({ - getStore: () => store.getState(), - manager: { - getPanes: () => [{ id: 1 }, { id: 2 }], - getLeafId: (paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1), - detachPaneForExternalMove: () => true - }, - persistLayoutSnapshot: vi.fn(), - sourcePaneCwd: { cwd: '/path/wt/packages/app', confirmed: false }, - sourcePaneId: 2, - sourceTabId: SOURCE, - targetGroupId: GROUP, - worktreeId: WT - }) - - const moved = store.getState().tabsByWorktree[WT]!.find((tab) => tab.id === MOVED) - expect(moved).toMatchObject({ startupCwd: '/path/wt/packages/app' }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts index e7fb847affd..4b7f36f5590 100644 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts @@ -7,11 +7,9 @@ import { createStoreCascadesMockApi } from '../../../../store/testing/app-store- import { LEAF_1, LEAF_2, splitLayout } from './terminal-pane-tab-detach-fixture' import { detachFrom, - GROUP, mainMovedTabId, openMainFrames, seedDetachStore, - sentMove, SOURCE, twoPaneManager, WT, @@ -124,20 +122,6 @@ describe('detachTerminalPaneToTab rolls main’s committed move forward (layout- expectOnlyMainTabs(store) }) - it('finds the pane by its leaf when its pane id changed meanwhile', async () => { - const store = await seeded() - const manager = twoPaneManager() - const move = await moveHeldByMain(() => detachFrom(store, { manager })) - manager.getPanes.mockImplementation(() => [{ id: 1 }, { id: 7 }]) - manager.getLeafId.mockImplementation((paneId) => - paneId === 1 ? LEAF_1 : paneId === 7 ? LEAF_2 : null - ) - - await expect(move.answer()).resolves.toMatchObject({ leafId: LEAF_2 }) - - expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(7) - }) - it('moves the last pane, after a sibling closed meanwhile, without killing its PTY', async () => { const store = await seeded({ ...splitLayout(), @@ -173,53 +157,4 @@ describe('detachTerminalPaneToTab rolls main’s committed move forward (layout- expect(api.pty.kill).not.toHaveBeenCalledWith('pty-right', expect.anything()) expect(api.pty.kill).not.toHaveBeenCalledWith('pty-right') }) - - it('commits the move in main before the target tab exists, then shows main’s tab', async () => { - const store = await seeded() - const tabsBefore = store.getState().tabsByWorktree[WT]?.map((tab) => tab.id) - const move = await moveHeldByMain(() => detachFrom(store)) - - expect(sentMove()).toEqual({ - type: 'movePaneToNewTab', - workspace: WT, - tabId: SOURCE, - leafId: LEAF_2, - groupId: GROUP, - windowDetach: { ptyId: 'remote:env-1@@terminal-1' } - }) - expect(store.getState().tabsByWorktree[WT]?.map((tab) => tab.id)).toEqual(tabsBefore) - - const result = await move.answer() - const movedId = mainMovedTabId() - expect(result?.tab.id).toBe(movedId) - expect(store.getState().terminalLayoutsByTabId[movedId]?.root).toEqual({ - type: 'leaf', - leafId: LEAF_2 - }) - }) - - it('ignores a repeat drop of a pane whose move is still committing', async () => { - const store = await seeded() - const move = await moveHeldByMain(() => detachFrom(store)) - - await expect(detachFrom(store)).resolves.toBeNull() - - await expect(move.answer()).resolves.toMatchObject({ leafId: LEAF_2 }) - expect(main.sentOfType('movePaneToNewTab')).toHaveLength(1) - expect(toast.error).not.toHaveBeenCalled() - }) - - it('binds the moved tab’s layout to the live PTY, not the saved one', async () => { - const store = await seeded() - const saved = store.getState().terminalLayoutsByTabId[SOURCE]?.ptyIdsByLeafId?.[LEAF_2] - expect(saved).toBeTruthy() - - const result = await detachFrom(store, { livePtyId: 'pty-respawned' }) - - expect(sentMove().windowDetach).toEqual({ ptyId: 'pty-respawned' }) - expect(result?.ptyId).toBe('pty-respawned') - expect(store.getState().terminalLayoutsByTabId[mainMovedTabId()]?.ptyIdsByLeafId).toEqual({ - [LEAF_2]: 'pty-respawned' - }) - }) }) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts index 410e94cfde7..7b1677b64f2 100644 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts @@ -3,14 +3,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as AgentStatusModule from '../../../../../../shared/agent-status/title/agent-title-status' import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session' import { createStoreCascadesMockApi } from '../../../../store/testing/app-store-cascade-api.test-fixture' -import { LEAF_1, LEAF_2, splitLayout, unboundSplitLayout } from './terminal-pane-tab-detach-fixture' +import { LEAF_1, LEAF_2, splitLayout } from './terminal-pane-tab-detach-fixture' import { detachFrom, GROUP, mainMovedTabId, openMainFrames, - OTHER_1, - OTHER_2, seedDetachStore, sentMove, SOURCE, @@ -66,23 +64,6 @@ function movedRow(store: DetachStore) { } describe('detachTerminalPaneToTab, main moving the pane (layout-owner build)', () => { - it.each([LEAF_1, LEAF_2])('moves chat mode only with its owning leaf %s', async (chatLeafId) => { - const store = await seeded({ ...splitLayout(), chatLeafId }) - - await detachFrom(store) - - const movedId = mainMovedTabId() - const state = store.getState() - const movedTab = state.unifiedTabsByWorktree[WT]?.find((tab) => tab.entityId === movedId) - expect(movedTab?.viewMode ?? 'terminal').toBe(chatLeafId === LEAF_2 ? 'chat' : 'terminal') - expect(state.terminalLayoutsByTabId[movedId]?.chatLeafId).toBe( - chatLeafId === LEAF_2 ? LEAF_2 : undefined - ) - expect(state.terminalLayoutsByTabId[SOURCE]?.chatLeafId).toBe( - chatLeafId === LEAF_1 ? LEAF_1 : undefined - ) - }) - it('shows main’s new terminal tab holding the moved pane and its terminal', async () => { const store = await seeded(splitLayout(), { shellOverride: 'powershell.exe', sshRepo: true }) const manager = twoPaneManager() @@ -131,92 +112,4 @@ describe('detachTerminalPaneToTab, main moving the pane (layout-owner build)', ( expect(state.activeTabTypeByWorktree[WT]).toBe('terminal') expect(persistLayoutSnapshot).toHaveBeenCalled() }) - - it.each(['powershell.exe', 'wsl.exe'])( - 'preserves the moved PTY shell override when the source uses %s', - async (shellOverride) => { - const store = await seeded(splitLayout(), { shellOverride }) - - await detachFrom(store, { sourcePaneId: 1 }) - - expect(sentMove()).toMatchObject({ leafId: LEAF_1, windowDetach: { ptyId: 'pty-left' } }) - expect(movedRow(store)).toMatchObject({ shellOverride }) - expect(store.getState().ptyIdsByTabId[mainMovedTabId()]).toEqual(['pty-left']) - } - ) - - it('syncs PTY ownership when the primary source pane is detached', async () => { - const store = await seeded(splitLayout()) - - const result = await detachFrom(store, { sourcePaneId: 1 }) - - const movedId = mainMovedTabId() - expect(result?.ptyId).toBe('pty-left') - const state = store.getState() - expect(state.terminalLayoutsByTabId[SOURCE]).toMatchObject({ - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' }, - titlesByLeafId: { [LEAF_2]: 'remote shell' } - }) - expect(state.terminalLayoutsByTabId[movedId]?.root).toEqual({ type: 'leaf', leafId: LEAF_1 }) - expect(state.ptyIdsByTabId[SOURCE]).toEqual(['remote:env-1@@terminal-1']) - expect(state.ptyIdsByTabId[movedId]).toEqual(['pty-left']) - }) - - it('moves the detached tab into the requested group slot', async () => { - const store = await seeded(splitLayout()) - - await detachFrom(store, { targetIndex: 1 }) - - expect(sentMove()).toMatchObject({ groupId: GROUP, index: 1 }) - expect(store.getState().groupsByWorktree[WT]?.[0]?.tabOrder).toEqual([ - OTHER_1, - mainMovedTabId(), - OTHER_2, - SOURCE - ]) - }) - - it('uses the live transport PTY id when the snapshot has not persisted it yet', async () => { - const store = await seeded(unboundSplitLayout()) - - await detachFrom(store, { - livePtyId: 'remote:env-2@@terminal-9', - sourcePaneCwd: { - cwd: '/remote/repo', - confirmed: false, - deferredSplitSpawn: true, - pendingCwd: Promise.resolve('/remote/repo/packages/app') - } - }) - - expect(sentMove().windowDetach).toMatchObject({ ptyId: 'remote:env-2@@terminal-9' }) - expect(store.getState().terminalLayoutsByTabId[mainMovedTabId()]).toMatchObject({ - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - ptyIdsByLeafId: { [LEAF_2]: 'remote:env-2@@terminal-9' } - }) - }) - - it('carries resolved cwd when detaching an unbound non-deferred pane', async () => { - const store = await seeded(unboundSplitLayout(), { shellOverride: 'powershell.exe' }) - - const result = await detachFrom(store, { - sourcePaneCwd: { cwd: '/remote/repo/packages/app', confirmed: false } - }) - - expect(sentMove().windowDetach).toEqual({ - ptyId: null, - startupCwd: '/remote/repo/packages/app' - }) - expect(result?.ptyId).toBeNull() - expect(movedRow(store)).toMatchObject({ - ptyId: null, - shellOverride: 'powershell.exe', - startupCwd: '/remote/repo/packages/app', - pendingActivationSpawn: true - }) - expect(store.getState().activeTabIdByWorktree[WT]).toBe(mainMovedTabId()) - }) }) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts deleted file mode 100644 index 545d9f9fa09..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach.test.ts +++ /dev/null @@ -1,417 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { detachTerminalPaneToTab } from './terminal-pane-tab-detach' -import { - createStore, - EXISTING_TAB_1, - EXISTING_TAB_2, - LEAF_1, - LEAF_2, - SOURCE_TAB_ID, - splitLayout, - TARGET_GROUP_ID, - unboundSplitLayout, - WORKTREE_ID -} from './terminal-pane-tab-detach-fixture' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' - -// Window-created tab coverage; main-command/frame equivalents live in terminal-pane-tab-detach-main-move.test.ts. -const itSwitchOff = it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN) - -const toastErrorMock = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ toast: { error: toastErrorMock } })) - -beforeEach(() => { - toastErrorMock.mockClear() - // No local main holds these sessions, so each move stays in the renderer. - vi.stubGlobal('window', { - api: { pty: { moveLeafToNewTab: () => Promise.resolve({ status: 'not_held' }) } } - }) -}) - -type SourcePaneCwd = NonNullable[0]['sourcePaneCwd']> - -async function expectDeferredSplitDetachRejected(sourcePaneCwd: SourcePaneCwd): Promise { - const store = createStore(unboundSplitLayout()) - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn(() => LEAF_2), - detachPaneForExternalMove: vi.fn(() => true) - } - const persistLayoutSnapshot = vi.fn() - - const result = await detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot, - sourcePaneCwd, - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - - expect(result).toBeNull() - expect(persistLayoutSnapshot).not.toHaveBeenCalled() - expect(manager.detachPaneForExternalMove).not.toHaveBeenCalled() - expect(store.createTab).not.toHaveBeenCalled() - expect(store.setTabLayout).not.toHaveBeenCalled() - expect(store.syncPaneDetachPtyOwnership).not.toHaveBeenCalled() - expect(store.setActiveTab).not.toHaveBeenCalled() - expect(store.setActiveTabType).not.toHaveBeenCalled() -} - -describe('detachTerminalPaneToTab', () => { - itSwitchOff.each([LEAF_1, LEAF_2])( - 'moves chat mode only with its owning leaf %s', - async (chatLeafId) => { - const store = createStore({ ...splitLayout(), chatLeafId }) - await detachTerminalPaneToTab({ - getStore: () => store, - manager: { - getPanes: () => [{ id: 1 }, { id: 2 }], - getLeafId: () => LEAF_2, - detachPaneForExternalMove: () => true - }, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - const options = vi.mocked(store.createTab).mock.calls[0]?.[3] - expect(options?.viewMode ?? 'terminal').toBe(chatLeafId === LEAF_2 ? 'chat' : 'terminal') - expect(store.terminalLayoutsByTabId['tab-detached']?.chatLeafId).toBe( - chatLeafId === LEAF_2 ? LEAF_2 : undefined - ) - expect(store.terminalLayoutsByTabId[SOURCE_TAB_ID]?.chatLeafId).toBe( - chatLeafId === LEAF_1 ? LEAF_1 : undefined - ) - } - ) - - itSwitchOff('creates a new terminal tab with the detached leaf layout and PTY id', async () => { - const store = createStore() - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn((paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1)), - detachPaneForExternalMove: vi.fn(() => true) - } - const persistLayoutSnapshot = vi.fn() - - const result = await detachTerminalPaneToTab({ - manager, - getStore: () => store, - persistLayoutSnapshot, - sourcePaneCwd: { - cwd: '/remote/repo', - confirmed: false, - deferredSplitSpawn: true, - pendingCwd: Promise.resolve('/remote/repo/packages/app') - }, - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - - expect(result?.ptyId).toBe('remote:env-1@@terminal-1') - expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(2) - expect(store.createTab).toHaveBeenCalledWith(WORKTREE_ID, TARGET_GROUP_ID, 'powershell.exe', { - id: expect.any(String), - activate: true, - initialPtyId: 'remote:env-1@@terminal-1', - initialLeafId: LEAF_2, - recordInteraction: true - }) - expect(store.setTabLayout).toHaveBeenCalledWith(SOURCE_TAB_ID, { - root: { type: 'leaf', leafId: LEAF_1 }, - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_1]: 'pty-left' } - }) - expect(store.setTabLayout).toHaveBeenCalledWith('tab-detached', { - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' }, - buffersByLeafId: { [LEAF_2]: 'remote-buffer' }, - titlesByLeafId: { [LEAF_2]: 'remote shell' } - }) - expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith({ - detachedLeafId: LEAF_2, - detachedPtyId: 'remote:env-1@@terminal-1', - sourceLayout: { - root: { type: 'leaf', leafId: LEAF_1 }, - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_1]: 'pty-left' } - }, - sourceTabId: SOURCE_TAB_ID, - targetTabId: 'tab-detached' - }) - expect(store.setActiveTab).toHaveBeenCalledWith('tab-detached') - expect(store.setActiveTabType).toHaveBeenCalledWith('terminal', WORKTREE_ID) - expect(persistLayoutSnapshot).toHaveBeenCalled() - }) - - itSwitchOff.each(['powershell.exe', 'wsl.exe'])( - 'preserves the moved PTY shell override when the source uses %s', - async (shellOverride) => { - const store = createStore(splitLayout(), [EXISTING_TAB_1], shellOverride) - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn(() => LEAF_1), - detachPaneForExternalMove: vi.fn(() => true) - } - - await detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 1, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - - expect(store.createTab).toHaveBeenCalledWith( - WORKTREE_ID, - TARGET_GROUP_ID, - shellOverride, - expect.objectContaining({ initialPtyId: 'pty-left' }) - ) - } - ) - - itSwitchOff('syncs PTY ownership when the primary source pane is detached', async () => { - const store = createStore() - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn((paneId: number) => (paneId === 1 ? LEAF_1 : LEAF_2)), - detachPaneForExternalMove: vi.fn(() => true) - } - - const result = await detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 1, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - - expect(result?.ptyId).toBe('pty-left') - expect(store.setTabLayout).toHaveBeenCalledWith(SOURCE_TAB_ID, { - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' }, - buffersByLeafId: { [LEAF_2]: 'remote-buffer' }, - titlesByLeafId: { [LEAF_2]: 'remote shell' } - }) - expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith({ - detachedLeafId: LEAF_1, - detachedPtyId: 'pty-left', - sourceLayout: { - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'remote:env-1@@terminal-1' }, - buffersByLeafId: { [LEAF_2]: 'remote-buffer' }, - titlesByLeafId: { [LEAF_2]: 'remote shell' } - }, - sourceTabId: SOURCE_TAB_ID, - targetTabId: 'tab-detached' - }) - }) - - itSwitchOff('names the new tab as the client that already drew it did', async () => { - const moveLeafToNewTab = vi.fn(() => Promise.resolve({ status: 'moved', ptyId: 'pty-left' })) - vi.stubGlobal('window', { api: { pty: { moveLeafToNewTab } } }) - const store = createStore() - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn((paneId: number) => (paneId === 1 ? LEAF_1 : LEAF_2)), - detachPaneForExternalMove: vi.fn(() => true) - } - - await detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 1, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - targetTabId: 'client-drawn-tab', - worktreeId: WORKTREE_ID - }) - - expect(moveLeafToNewTab).toHaveBeenCalledWith( - expect.objectContaining({ targetTabId: 'client-drawn-tab', leafId: LEAF_1 }) - ) - expect(store.createTab).toHaveBeenCalledWith( - WORKTREE_ID, - TARGET_GROUP_ID, - 'powershell.exe', - expect.objectContaining({ id: 'client-drawn-tab' }) - ) - }) - - itSwitchOff.each([ - ["this window's own drag", undefined, 1], - ["another client's move", 'client-drawn-tab', 0] - ])('reports a refused move as a toast only for %s', async (_label, targetTabId, toasts) => { - const moveLeafToNewTab = vi.fn(() => - Promise.resolve({ status: 'refused', reason: 'target_tab_exists' }) - ) - vi.stubGlobal('window', { api: { pty: { moveLeafToNewTab } } }) - const store = createStore() - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn((paneId: number) => (paneId === 1 ? LEAF_1 : LEAF_2)), - detachPaneForExternalMove: vi.fn(() => true) - } - - await expect( - detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 1, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - ...(targetTabId ? { targetTabId } : {}), - worktreeId: WORKTREE_ID - }) - ).resolves.toBeNull() - expect(toastErrorMock).toHaveBeenCalledTimes(toasts) - }) - - itSwitchOff('moves the detached tab into the requested group slot', async () => { - const store = createStore(splitLayout(), [EXISTING_TAB_1, EXISTING_TAB_2]) - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn((paneId: number) => (paneId === 2 ? LEAF_2 : LEAF_1)), - detachPaneForExternalMove: vi.fn(() => true) - } - - await detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - targetIndex: 1, - worktreeId: WORKTREE_ID - }) - - expect(store.reorderUnifiedTabs).toHaveBeenCalledWith( - TARGET_GROUP_ID, - [EXISTING_TAB_1, 'tab-detached', EXISTING_TAB_2], - { recordInteraction: false, layoutOwnerHandled: false } - ) - }) - - itSwitchOff( - 'uses the live transport PTY id when the snapshot has not persisted it yet', - async () => { - const store = createStore({ - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_2 } - }, - activeLeafId: LEAF_2, - expandedLeafId: null - }) - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn(() => LEAF_2), - detachPaneForExternalMove: vi.fn(() => true) - } - - await detachTerminalPaneToTab({ - livePtyId: 'remote:env-2@@terminal-9', - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneCwd: { - cwd: '/remote/repo', - confirmed: false, - deferredSplitSpawn: true, - pendingCwd: Promise.resolve('/remote/repo/packages/app') - }, - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - - expect(store.setTabLayout).toHaveBeenCalledWith('tab-detached', { - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'remote:env-2@@terminal-9' } - }) - } - ) - - it('rejects a deferred split while inherited cwd is pending', async () => { - await expectDeferredSplitDetachRejected({ - cwd: '/remote/repo', - deferredSplitSpawn: true, - pendingCwd: new Promise(() => {}) - }) - }) - - it('rejects a pending cwd even when the deferred marker is absent', async () => { - await expectDeferredSplitDetachRejected({ - cwd: '/remote/repo', - pendingCwd: new Promise(() => {}) - }) - }) - - it('still rejects a deferred split after cwd resolves but before PTY bind', async () => { - await expectDeferredSplitDetachRejected({ - cwd: '/remote/repo/packages/app', - confirmed: false, - deferredSplitSpawn: true - }) - }) - - itSwitchOff('carries resolved cwd when detaching an unbound non-deferred pane', async () => { - const store = createStore(unboundSplitLayout()) - const manager = { - getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), - getLeafId: vi.fn(() => LEAF_2), - detachPaneForExternalMove: vi.fn(() => true) - } - - const result = await detachTerminalPaneToTab({ - getStore: () => store, - manager, - persistLayoutSnapshot: vi.fn(), - sourcePaneCwd: { - cwd: '/remote/repo/packages/app', - confirmed: false - }, - sourcePaneId: 2, - sourceTabId: SOURCE_TAB_ID, - targetGroupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID - }) - - expect(result?.ptyId).toBeNull() - expect(store.createTab).toHaveBeenCalledWith(WORKTREE_ID, TARGET_GROUP_ID, 'powershell.exe', { - id: expect.any(String), - activate: true, - pendingActivationSpawn: true, - recordInteraction: true, - startupCwd: '/remote/repo/packages/app' - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts b/src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts deleted file mode 100644 index 24626e35a53..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/detach/terminal-tab-strip-drop-target-geometry.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '@/store/types' -import { resolveTerminalTabStripDropTarget } from './terminal-tab-strip-drop-target' -import { - EXISTING_TAB_1, - EXISTING_TAB_2, - TARGET_GROUP_ID, - WORKTREE_ID -} from './terminal-pane-tab-detach-fixture' - -const toastErrorMock = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ toast: { error: toastErrorMock } })) - -beforeEach(() => { - toastErrorMock.mockClear() - // No local main holds these sessions, so each move stays in the renderer. - vi.stubGlobal('window', { - api: { pty: { moveLeafToNewTab: () => Promise.resolve({ status: 'not_held' }) } } - }) -}) - -function rect(args: { left: number; top: number; width: number; height: number }): DOMRect { - return { - left: args.left, - top: args.top, - right: args.left + args.width, - bottom: args.top + args.height, - width: args.width, - height: args.height - } as DOMRect -} - -describe('resolveTerminalTabStripDropTarget', () => { - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('finds a same-worktree tab strip under overlay elements', () => { - const stripRect = rect({ left: 0, top: 0, width: 300, height: 32 }) - const strip = { - dataset: { tabGroupStripId: TARGET_GROUP_ID, worktreeId: WORKTREE_ID }, - getBoundingClientRect: () => stripRect, - querySelectorAll: () => [] - } - const overlay = { closest: () => null } - const child = { closest: () => strip } - vi.stubGlobal('document', { - elementsFromPoint: vi.fn(() => [overlay, child]), - elementFromPoint: vi.fn() - }) - - expect( - resolveTerminalTabStripDropTarget({ - clientX: 10, - clientY: 10, - groupsByWorktree: { - [WORKTREE_ID]: [{ id: TARGET_GROUP_ID } as AppState['groupsByWorktree'][string][number]] - }, - worktreeId: WORKTREE_ID - }) - ).toEqual({ - id: TARGET_GROUP_ID, - groupId: TARGET_GROUP_ID, - worktreeId: WORKTREE_ID, - rect: stripRect - }) - }) - - it('resolves the insertion slot from the hovered tab side', () => { - const stripRect = rect({ left: 0, top: 0, width: 300, height: 32 }) - const firstTabRect = rect({ left: 0, top: 0, width: 80, height: 32 }) - const secondTabRect = rect({ left: 80, top: 0, width: 80, height: 32 }) - const firstTab = { - dataset: { tabId: EXISTING_TAB_1 }, - getBoundingClientRect: () => firstTabRect - } - const secondTab = { - dataset: { tabId: EXISTING_TAB_2 }, - getBoundingClientRect: () => secondTabRect - } - const strip = { - dataset: { tabGroupStripId: TARGET_GROUP_ID, worktreeId: WORKTREE_ID }, - getBoundingClientRect: () => stripRect, - querySelectorAll: () => [firstTab, secondTab] - } - vi.stubGlobal('document', { - elementsFromPoint: vi.fn(() => [{ closest: () => firstTab }, { closest: () => strip }]), - elementFromPoint: vi.fn() - }) - - expect( - resolveTerminalTabStripDropTarget({ - clientX: 60, - clientY: 10, - groupsByWorktree: { - [WORKTREE_ID]: [ - { - id: TARGET_GROUP_ID, - activeTabId: EXISTING_TAB_1, - tabOrder: [EXISTING_TAB_1, EXISTING_TAB_2], - worktreeId: WORKTREE_ID - } as AppState['groupsByWorktree'][string][number] - ] - }, - worktreeId: WORKTREE_ID - }) - ).toMatchObject({ - groupId: TARGET_GROUP_ID, - insertionIndex: 1, - overlayKind: 'insertion', - rect: rect({ left: 80, top: 0, width: 2, height: 32 }) - }) - }) - - it('ignores strips from another worktree', () => { - const strip = { - dataset: { tabGroupStripId: TARGET_GROUP_ID, worktreeId: 'other-worktree' }, - getBoundingClientRect: () => - ({ left: 0, top: 0, right: 300, bottom: 32, width: 300, height: 32 }) as DOMRect - } - vi.stubGlobal('document', { - elementsFromPoint: vi.fn(() => [{ closest: () => strip }]), - elementFromPoint: vi.fn() - }) - - expect( - resolveTerminalTabStripDropTarget({ - clientX: 10, - clientY: 10, - groupsByWorktree: { - [WORKTREE_ID]: [{ id: TARGET_GROUP_ID } as AppState['groupsByWorktree'][string][number]] - }, - worktreeId: WORKTREE_ID - }) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout-render-stability.test.ts b/src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout-render-stability.test.ts deleted file mode 100644 index 3ccda5b0751..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout-render-stability.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PaneManager } from '@/lib/pane-manager/pane-manager' -import type { PtyTransport } from '../../pty-transport/pty-transport-types' -import { useExpandCollapseActions } from './expanded-pane-layout' -import { useTerminalKeyboardShortcuts } from '../../input/keyboard/terminal-keyboard-hook' - -type ExpandCollapseHookState = Parameters[0] -type KeyboardHandlersDeps = Parameters[0] - -// Match TerminalPane’s stable fields inside a newly allocated dependency wrapper each render. -function createStableFields(): Omit { - return { - expandedPaneIdRef: { current: null }, - expandedStyleSnapshotRef: { current: new Map() }, - containerRef: { current: null }, - managerRef: { current: null }, - setExpandedPaneId: vi.fn(), - setTabPaneExpanded: vi.fn(), - pendingPaneSizeRefreshFrameIdsRef: { current: [] }, - persistLayoutSnapshot: vi.fn() - } -} - -afterEach(() => { - cleanup() - vi.restoreAllMocks() -}) - -describe('useExpandCollapseActions render stability', () => { - it('keeps all five action identities across rerenders that rebuild the state object', () => { - const fields = createStableFields() - const hook = renderHook(() => useExpandCollapseActions({ ...fields, tabId: 'tab-1' })) - const first = hook.result.current - - hook.rerender() - hook.rerender() - - const actionNames = Object.keys(first) as (keyof typeof first)[] - expect(actionNames).toHaveLength(5) - for (const name of actionNames) { - expect(Object.is(hook.result.current[name], first[name])).toBe(true) - } - }) - - it('remints actions when tabId changes', () => { - const fields = createStableFields() - const hook = renderHook(({ tabId }) => useExpandCollapseActions({ ...fields, tabId }), { - initialProps: { tabId: 'tab-1' } - }) - const first = hook.result.current - - hook.rerender({ tabId: 'tab-2' }) - - expect(Object.is(hook.result.current.setExpandedPane, first.setExpandedPane)).toBe(false) - }) -}) - -describe('terminal keyboard effect registration stability', () => { - it('registers window listeners once across rerenders with TerminalPane-shaped wiring', () => { - const scope = document.createElement('div') - document.body.append(scope) - const pane = { - id: 1, - leafId: '00000000-0000-4000-8000-000000000001', - terminal: { element: scope, focus: vi.fn(), getSelection: vi.fn(() => '') } - } - const manager = { - getActivePane: () => pane, - getPanes: () => [pane] - } as unknown as PaneManager - const transport = { getPtyId: () => 'pty-1', sendInput: vi.fn(() => true) } - const fields = createStableFields() - const stableDeps = { - tabId: 'tab-1', - worktreeId: 'worktree-1', - isActive: true, - keyboardScopeRef: { current: scope }, - managerRef: { current: manager }, - paneTransportsRef: { - current: new Map([[pane.id, transport as unknown as PtyTransport]]) - }, - panePtyBindingsRef: { current: new Map() }, - paneCwdRef: { current: new Map() }, - fallbackCwd: '', - expandedPaneIdRef: { current: null }, - setSearchOpen: vi.fn(), - focusSearchInput: vi.fn(), - onSearchSelectedText: vi.fn(), - onRequestClosePane: vi.fn(), - onClearPaneScrollback: vi.fn(), - onSetTitle: vi.fn(), - onClearPaneTitle: vi.fn(), - searchOpenRef: { current: false }, - searchStateRef: { current: { query: '', caseSensitive: false, regex: false } }, - macOptionAsAltRef: { current: 'false' as const } - } - - const addSpy = vi.spyOn(window, 'addEventListener') - const countBeforeinputAdds = (): number => - addSpy.mock.calls.filter(([type]) => type === 'beforeinput').length - - const hook = renderHook(() => { - // Same wiring shape as TerminalPane: both dep objects are rebuilt every render. - const actions = useExpandCollapseActions({ ...fields, tabId: stableDeps.tabId }) - useTerminalKeyboardShortcuts({ - ...stableDeps, - setExpandedPane: actions.setExpandedPane, - restoreExpandedLayout: actions.restoreExpandedLayout, - refreshPaneSizes: actions.refreshPaneSizes, - persistLayoutSnapshot: fields.persistLayoutSnapshot, - toggleExpandPane: actions.toggleExpandPane - } as KeyboardHandlersDeps) - }) - expect(countBeforeinputAdds()).toBe(1) - - for (let render = 0; render < 10; render++) { - hook.rerender() - } - - expect(countBeforeinputAdds()).toBe(1) - hook.unmount() - scope.remove() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout.test.ts b/src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout.test.ts deleted file mode 100644 index 8cdcc3f06f0..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/expand/expanded-pane-layout.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - cancelPendingPaneSizeRefreshFrames, - createExpandCollapseActions -} from './expanded-pane-layout' - -type ExpandCollapseStateForTest = Parameters[0] - -function ref(current: T): React.MutableRefObject { - return { current } -} - -function createState( - overrides: Partial = {} -): ExpandCollapseStateForTest { - return { - expandedPaneIdRef: ref(null), - expandedStyleSnapshotRef: ref(new Map()), - containerRef: ref(null), - managerRef: ref(null), - pendingPaneSizeRefreshFrameIdsRef: ref([]), - setExpandedPaneId: vi.fn(), - setTabPaneExpanded: vi.fn(), - tabId: 'tab-1', - persistLayoutSnapshot: vi.fn(), - ...overrides - } -} - -describe('createExpandCollapseActions', () => { - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('cancels pending pane-size refresh frames', () => { - const cancelAnimationFrame = vi.fn() - vi.stubGlobal( - 'requestAnimationFrame', - vi.fn(() => 42) - ) - vi.stubGlobal('cancelAnimationFrame', cancelAnimationFrame) - const state = createState() - - createExpandCollapseActions(state).refreshPaneSizes(true) - - expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([42]) - - cancelPendingPaneSizeRefreshFrames(state) - - expect(cancelAnimationFrame).toHaveBeenCalledWith(42) - expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([]) - }) - - it('forgets completed pane-size refresh frames', () => { - const callbacks: FrameRequestCallback[] = [] - vi.stubGlobal( - 'requestAnimationFrame', - vi.fn((next: FrameRequestCallback) => { - callbacks.push(next) - return 7 - }) - ) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - const state = createState({ - managerRef: ref({ - getPanes: () => [], - getActivePane: () => null - } as never) - }) - - createExpandCollapseActions(state).refreshPaneSizes(false) - - expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([7]) - - const callback = callbacks[0] - if (!callback) { - throw new Error('expected pane-size refresh frame to be scheduled') - } - callback(16) - - expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([]) - }) - - it('does not retain synchronously completed pane-size refresh frames', () => { - vi.stubGlobal( - 'requestAnimationFrame', - vi.fn((callback: FrameRequestCallback) => { - callback(16) - return 9 - }) - ) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - const state = createState() - - createExpandCollapseActions(state).refreshPaneSizes(false) - - expect(state.pendingPaneSizeRefreshFrameIdsRef.current).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/ownership/terminal-pane-layout-owner-commands.test.ts b/src/renderer/src/components/terminal-pane/layout/ownership/terminal-pane-layout-owner-commands.test.ts deleted file mode 100644 index 3118d3b0ce0..00000000000 --- a/src/renderer/src/components/terminal-pane/layout/ownership/terminal-pane-layout-owner-commands.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { PaneManager } from '@/lib/pane-manager/pane-manager' -import { equalizeTerminalPanes } from './terminal-pane-layout-owner-commands' -import { - _resetLayoutFramePositionForTests, - beginLayoutFramePositions, - endLayoutFramePositions -} from '@/runtime/layout-frame-position' -import { provideServerLayoutApplyRoutes } from '@/runtime/server-layout-apply-routes' - -const mocks = vi.hoisted( - (): { - callRuntimeRpc: ReturnType - ownerEnvironmentId: string | null - layoutOwnerIsMain: boolean - } => ({ - callRuntimeRpc: vi.fn(), - ownerEnvironmentId: null, - layoutOwnerIsMain: false - }) -) - -vi.mock('../../../../../../shared/layout-owner-switch', () => ({ - get ORCA_LAYOUT_OWNER_IS_MAIN() { - return mocks.layoutOwnerIsMain - } -})) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: mocks.callRuntimeRpc -})) -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } })) -vi.mock('@/lib/resolve-owner', () => ({ - runtimeEnvironmentIdUnlessTwin: () => mocks.ownerEnvironmentId -})) - -describe('equalizeTerminalPanes', () => { - beforeEach(() => { - mocks.callRuntimeRpc.mockReset() - mocks.ownerEnvironmentId = null - mocks.layoutOwnerIsMain = false - _resetLayoutFramePositionForTests() - }) - - function manager() { - const equalizePaneSizes = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: equalize calls only equalizePaneSizes. - return { equalizePaneSizes } as unknown as PaneManager & { - equalizePaneSizes: typeof equalizePaneSizes - } - } - - it('a layout-owner build equalizes itself when no frame is coming', async () => { - mocks.layoutOwnerIsMain = true - beginLayoutFramePositions() - endLayoutFramePositions() - mocks.callRuntimeRpc.mockResolvedValue({ ok: true, result: {} }) - const current = manager() - const then = vi.fn() - - equalizeTerminalPanes( - { worktreeId: 'worktree-1', tabId: 'tab-1', getManager: () => current }, - then - ) - - await vi.waitFor(() => expect(then).toHaveBeenCalledWith(current)) - expect(current.equalizePaneSizes).toHaveBeenCalledOnce() - }) - - it('leaves a paired server’s panes to that server’s frames, whatever this window’s stream does', async () => { - mocks.layoutOwnerIsMain = true - mocks.ownerEnvironmentId = 'env-1' - // This window's own stream is down; the server's frames draw the workspace. - const stop = provideServerLayoutApplyRoutes('env-1', () => ({ - environmentId: 'env-1', - serverTabId: () => 'server-tab-1', - desktopTabId: (id) => id, - redraw: vi.fn() - })) - mocks.callRuntimeRpc.mockResolvedValue({ ok: true, result: {} }) - const current = manager() - const then = vi.fn() - try { - equalizeTerminalPanes( - { worktreeId: 'worktree-1', tabId: 'tab-1', getManager: () => current }, - then - ) - - expect(mocks.callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-1' }, - 'layout.apply', - { command: { type: 'equalizePanes', tabId: 'server-tab-1', workspace: 'worktree-1' } } - ) - await vi.waitFor(() => expect(then).toHaveBeenCalledWith(current)) - expect(current.equalizePaneSizes).not.toHaveBeenCalled() - } finally { - stop() - } - }) -}) diff --git a/src/renderer/src/components/terminal-pane/layout/persistence/remote-pane-layout-push.test.ts b/src/renderer/src/components/terminal-pane/layout/persistence/remote-pane-layout-push.test.ts index 6cefdf9a2e0..c3b84d3c48c 100644 --- a/src/renderer/src/components/terminal-pane/layout/persistence/remote-pane-layout-push.test.ts +++ b/src/renderer/src/components/terminal-pane/layout/persistence/remote-pane-layout-push.test.ts @@ -12,8 +12,6 @@ const { notePendingPaneTitleRename } = await import('@/runtime/pending-pane-titl const { toRemoteRuntimePtyId } = await import('../../../../../../shared/remote-runtime/remote-runtime-pty-id') -const PERSISTS = 100 - function deferred(): { promise: Promise; resolve: (value: T) => void } { let resolve = (_value: T): void => undefined const promise = new Promise((complete) => { @@ -44,124 +42,6 @@ describe('createRemotePaneLayoutPusher', () => { updateWebRuntimePaneLayout.mockReset().mockResolvedValue(true) }) - it('pushes once across 100 persists of an unchanged layout', () => { - const pusher = createRemotePaneLayoutPusher() - for (let i = 0; i < PERSISTS; i += 1) { - // Fresh object each time: persistLayoutSnapshot re-serializes on every call. - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - } - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(1) - }) - - it('sends the same payload the un-deduped path sent', () => { - const pusher = createRemotePaneLayoutPusher() - const layout = makeLayout() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout }) - expect(updateWebRuntimePaneLayout).toHaveBeenCalledWith({ - worktreeId: 'wt-1', - tabId: 'tab-1', - root: layout.root, - expandedLeafId: layout.expandedLeafId, - chatLeafId: null, - titlesByLeafId: layout.titlesByLeafId - }) - }) - - it('omits titlesByLeafId when the layout carries no titles', () => { - const pusher = createRemotePaneLayoutPusher() - pusher.push({ - worktreeId: 'wt-1', - tabId: 'tab-1', - layout: makeLayout({ titlesByLeafId: undefined }) - }) - expect(updateWebRuntimePaneLayout.mock.calls[0][0]).not.toHaveProperty('titlesByLeafId') - }) - - it('publishes owner changes and an explicit clear without a geometry change', () => { - const pusher = createRemotePaneLayoutPusher() - for (const chatLeafId of ['leaf-a', 'leaf-b', undefined]) { - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout({ chatLeafId }) }) - } - expect(updateWebRuntimePaneLayout.mock.calls.map(([args]) => args.chatLeafId)).toEqual([ - 'leaf-a', - 'leaf-b', - null - ]) - }) - - it('pushes again for every host-visible change', () => { - const pusher = createRemotePaneLayoutPusher() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - pusher.push({ - worktreeId: 'wt-1', - tabId: 'tab-1', - layout: makeLayout({ expandedLeafId: 'leaf-a' }) - }) - pusher.push({ - worktreeId: 'wt-1', - tabId: 'tab-1', - layout: makeLayout({ - expandedLeafId: 'leaf-a', - titlesByLeafId: { 'leaf-a': 'test' } - }) - }) - pusher.push({ - worktreeId: 'wt-1', - tabId: 'tab-1', - layout: makeLayout({ - expandedLeafId: 'leaf-a', - titlesByLeafId: { 'leaf-a': 'test' }, - root: { - type: 'split', - direction: 'vertical', - ratio: 0.7, - first: { type: 'leaf', leafId: 'leaf-a' }, - second: { type: 'leaf', leafId: 'leaf-b' } - } - }) - }) - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(4) - }) - - it('pushes again when a remote pane swaps its pty', () => { - // ptyIdsByLeafId is not in the payload, but a swap means a different host session. - const pusher = createRemotePaneLayoutPusher() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - pusher.push({ - worktreeId: 'wt-1', - tabId: 'tab-1', - layout: makeLayout({ ptyIdsByLeafId: { 'leaf-a': 'remote:pty-c', 'leaf-b': 'remote:pty-b' } }) - }) - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2) - }) - - it('does not carry a cached layout across tabs', () => { - const pusher = createRemotePaneLayoutPusher() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-2', layout: makeLayout() }) - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(3) - }) - - it('does not carry a cached layout across worktrees', () => { - const pusher = createRemotePaneLayoutPusher() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - pusher.push({ worktreeId: 'wt-2', tabId: 'tab-1', layout: makeLayout() }) - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2) - }) - - it('retries an unchanged layout after a failed push', async () => { - updateWebRuntimePaneLayout.mockResolvedValueOnce(false) - const pusher = createRemotePaneLayoutPusher() - const input = { worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() } - - pusher.push(input) - await Promise.resolve() - pusher.push(input) - - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2) - }) - it('does not let a stale failure invalidate a newer in-flight layout', async () => { const first = deferred() const second = deferred() @@ -180,17 +60,6 @@ describe('createRemotePaneLayoutPusher', () => { second.resolve(true) }) - it('re-pushes after a remount re-establishes host geometry', () => { - const pusher = createRemotePaneLayoutPusher() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout: makeLayout() }) - createRemotePaneLayoutPusher().push({ - worktreeId: 'wt-1', - tabId: 'tab-1', - layout: makeLayout() - }) - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2) - }) - it('names a renamed pane in its push, and again in the retry after that push fails', async () => { const remote = { 'leaf-a': toRemoteRuntimePtyId('pty-a', 'env-1') } notePendingPaneTitleRename({ @@ -215,23 +84,4 @@ describe('createRemotePaneLayoutPusher', () => { expect(sent[1]).toMatchObject({ renamedLeafIds: ['leaf-a'] }) expect(sent[2]).not.toHaveProperty('renamedLeafIds') }) - - it('sends a rename back to the title the last push carried', () => { - const remote = { 'leaf-b': toRemoteRuntimePtyId('pty-b', 'env-1') } - const pusher = createRemotePaneLayoutPusher() - const layout = makeLayout() - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout }) - // The host renamed leaf-b meanwhile; the user names it back to what the last push held. - notePendingPaneTitleRename({ - leafId: 'leaf-b', - title: null, - layout: makeLayout({ ptyIdsByLeafId: remote, titlesByLeafId: { 'leaf-b': 'host' } }) - }) - pusher.push({ worktreeId: 'wt-1', tabId: 'tab-1', layout }) - - expect(updateWebRuntimePaneLayout).toHaveBeenCalledTimes(2) - expect(updateWebRuntimePaneLayout.mock.calls[1]?.[0]).toMatchObject({ - renamedLeafIds: ['leaf-b'] - }) - }) })