diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index b24708c7f0f..4e44c0abe11 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -1078,9 +1078,6 @@ 7 test-no-wall-clock:src/renderer/src/store/slices/linear-source-context-cache-scope.test.ts 1 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-agent-status-retention.test.ts 2 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-exact-runtime-stop.test.ts -7 test-no-wall-clock:src/renderer/src/store/slices/tabs-unread-and-focus.test.ts -1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-view-layout.test.ts -1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts 2 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-agent-stop-preflight.test.ts 4 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-local-evidence-invariants.test.ts 2 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-removal-preflight.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 2a716b51187..da0fcf7eb77 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -3282,7 +3282,7 @@ "providers": ["local", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "ssh", "remote-runtime"], - "coverageNotes": "Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them.", + "coverageNotes": "Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4965", "https://github.com/stablyai/orca/pull/15371" @@ -3294,11 +3294,11 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/lib/open-mobile-emulator-tab.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/shared/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/lib/open-mobile-emulator-tab.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session-schema.test.ts", "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], @@ -3315,8 +3315,6 @@ "src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts", "src/renderer/src/lib/open-mobile-emulator-tab.test.ts", "src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts", - "src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts", - "src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts", "src/shared/workspace-session-schema.test.ts", "tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts" ], @@ -3341,12 +3339,6 @@ "host filtering and scoped open-tab search cannot hide a same-id sibling from the legacy ownership ambiguity set" ] }, - { - "file": "src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts", - "assertions": [ - "active local tab creation stamps local ownership instead of leaving a same-id row ambiguous" - ] - }, { "file": "src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts", "assertions": [ @@ -3387,8 +3379,8 @@ "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts", "result": "failed", "durationSeconds": 1.8, - "summary": "The first review-round oracle failed 4/40: browser and simulator dropped the SSH worktree's paired-runtime-owned tab, generic workspace rows attributed the remote tab to local, and active local tab creation left ownership unstamped.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts" + "summary": "The first review-round oracle failed 4/40: browser and simulator dropped the SSH worktree's paired-runtime-owned tab, generic workspace rows attributed the remote tab to local, and active local tab creation left ownership unstamped. Historical command and result are preserved after the test-value audit removed the tab-store assertions this run included. currentCommand is only an administrative link to the remaining gate command; the historical run has not validated that command or equivalent coverage.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts" }, { "date": "2026-08-20", @@ -3407,8 +3399,8 @@ "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", "result": "passed", "durationSeconds": 2.3, - "summary": "6 test files passed, 104 tests passed on the STA-4965 candidate.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts" + "summary": "6 test files passed, 104 tests passed on the STA-4965 candidate. Historical command and result are preserved after the test-value audit removed the tab-store assertions this run included. currentCommand is only an administrative link to the remaining gate command; the historical run has not validated that command or equivalent coverage.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/shared/workspace-session-schema.test.ts" }, { "date": "2026-08-20", @@ -3447,8 +3439,8 @@ "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/palette-repo-resolution.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/workspace-tab-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", "result": "passed", "durationSeconds": 10.5, - "summary": "The review-hardened candidate passed 189/189 focused contracts, including direct browser-result host fallback, SSH plus paired-runtime current-row aliases, explicit-owner fail-closed behavior, generic workspace rows, simulator reuse, local creation stamping, activation, and same-id distinct-runtime mirror preservation. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts" + "summary": "The review-hardened candidate passed 189/189 focused contracts, including direct browser-result host fallback, SSH plus paired-runtime current-row aliases, explicit-owner fail-closed behavior, generic workspace rows, simulator reuse, local creation stamping, activation, and same-id distinct-runtime mirror preservation. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage. Historical command and result are preserved after the test-value audit removed the tab-store assertions this run included. currentCommand is only an administrative link to the remaining gate command; the historical run has not validated that command or equivalent coverage.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session-schema.test.ts" }, { "date": "2026-08-20", @@ -3465,10 +3457,10 @@ "runner": "local", "platform": "macos", "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/palette-repo-resolution.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/workspace-tab-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts src/shared/workspace-session-schema.test.ts", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/components/tab-bar/use-open-tab-search.test.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser-palette-page-entries.test.ts src/renderer/src/lib/browser-palette-search.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session-schema.test.ts", "result": "passed", "durationSeconds": 24.3, - "summary": "The OpenCode-review-hardened candidate passed 225/225 focused contracts, including unfiltered ownership ambiguity under host filters and scoped open-tab search, review-cache ownership, rendered palette repo metadata, folder workspaces, inactive local simulator creation, paired SSH/runtime display metadata, and explicit-owner fail-closed resolution. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage." + "summary": "The OpenCode-review-hardened candidate passed 225/225 focused contracts, including unfiltered ownership ambiguity under host filters and scoped open-tab search, review-cache ownership, rendered palette repo metadata, folder workspaces, inactive local simulator creation, paired SSH/runtime display metadata, and explicit-owner fail-closed resolution. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage. Historical command and result are preserved after the test-value audit removed the tab-store assertions this run included. currentCommand is only an administrative link to the remaining gate command; the historical run has not validated that command or equivalent coverage." }, { "date": "2026-08-20", @@ -3568,7 +3560,8 @@ "Mixed-version behavior is covered by optional-field parsing and fail-closed legacy ambiguity, not a live old-client/new-host matrix.", "The test-value audit removed the palette repository resolver examples and manual emulator local-provider routing assertion. Their historical alarms are no longer provided by these suites; the retained emulator cases cover narrower coordination boundaries. No equivalent coverage is claimed.", "The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical.", - "The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them." + "The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them.", + "The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical." ], "demotionRule": "Cannot promote if a same-id sibling tab duplicates, disappears, activates another host, or if ambiguous unstamped ownership is guessed." }, @@ -5908,7 +5901,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged.", + "coverageNotes": "A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-5557/remote-html-preview-render-workspace-files-locally-over-the-file", "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", @@ -5919,7 +5912,7 @@ "https://github.com/stablyai/orca/pull/13876" ], "invariant": "Opening one HTML preview from a paired client renders the workspace document in exactly one client-local browser tab, located by that document and served over the orca-preview scheme. The client gains exactly that one browser workspace and it is the document one — blank where a URL page carries a URL, named by the document, with the chip naming the file — while the host gains no browser page at all, neither in its own page registry nor in the tab snapshot its clients publish into. The preview occupies its own split without taking focus from the source editor; an explicit click activates it, and closing it removes only the preview. Following a document from a file link is the other half of that switch and does move the reader to it, tab group included, whether the preview is new or already open, because opening a file is a request to look at it. A document tab quit with the client comes back as the same row on a grant the relaunched client mints afresh. A preview is named by the browser page it is open in, not by a namespace of its own, and the page registry has two halves: a workspace-document guest is registered in its own map and is absent from the browsing one entirely. That absence is the fence. Page, session and profile management, agent tab enumeration and command targeting, download routing and certificate attribution all read the browsing map directly, in more places than a per-channel guard could be remembered in, so none of them can name a document page and none of them carries a guard. Browser tools the reader drives (element grab, hover describe, selection capture, the annotation viewport bridge) are the one operation that legitimately spans the halves, and they go through the single authority that reads both, keyed by the page and its hosting renderer. The halves are disjoint in both directions: browsing registration refuses a page the document half already holds, and minting a grant refuses a page the browsing half already holds, so one id can never name a surface in both. The headless backend acts on that refusal by destroying the window it had already opened rather than leaving a policy-less page behind an id nothing can drive, keeping nothing under that id for its own shutdown to hand back. Registration refuses on the same terms when the guest it was asked about is already gone. The exit door is guarded in both its halves: a preview withdraws by revoking its grant and never through the unregister channel, so a page the document half holds arriving there is refused before either the registration teardown or the grab-state disposal beside it, which would otherwise drop the intent an in-flight preview grab compares by identity and leave that grab answering ok without ever arming its guest. A bridge request whose guest does not resolve is refused without tearing down the page it named, so a misaddressed request cannot cancel a healthy page's in-flight downloads and grabs. The annotation viewport bridge resolves its guest when its serialized op actually runs rather than when the request arrived, so a cross-process navigation while it waited cannot leave the bridge installed in a retired guest while the reader looks at a new one. State main keys by a preview's page is disposed when that page's grant is revoked, which is the only signal a preview's surface is gone. A tool asking for a page whose guest has not attached yet waits for that registration and arms when it arrives, rather than answering not-ready at the reader; that wait resolves only the request already naming this page, never the worktree-wide or any-tab waits the CLI and agents use to ask for a browser tab to drive. Handing the previewed document to the reader's own machine routes on the owners its grant was minted against — the file's own connection owner and the worktree's own runtime owner, neither read from the tab's stored fields. Only a document proven to live on this machine reaches the client OS; one with a resolved remote owner is downloaded first; and one whose owner cannot be resolved at all, workspace root included, is refused with a message naming that, because the download route would otherwise read the same absolute path on the client and hand back a same-named local file under the remote document's name. A runtime-owned path that falls outside its worktree root is refused by that route itself and surfaces as a failure toast rather than a download. Nothing the document does writes a file to this machine either: the preview partition denies downloads outright instead of routing them through the browser download flow, which has no page to attribute a preview's bytes to and would otherwise reserve a name in this desktop's Downloads folder and write them there unprompted. That refusal is visible to the reader and invisible to the document: the preview's shell carries a fixed sentence saying downloads are off, published at most once per preview per interval so a document asking in a loop cannot fill Orca's chrome, while the page itself gets back exactly what it got before, which is nothing. The sentence names no file, because the document chooses the name it offers; and a refusal never takes the document away the way an entry document's own failure does, whatever it names. A preview is a browser tab, not an editor tab in a preview mode: it is named the way a browser tab is named — by the document it shows when that document declares a title, and by the file it shows when it does not — while the chip goes on naming the file and the host whatever the document calls itself. A title is refused on the same terms the url is: a document that declares none has Chromium report the grant URL as its title, and that title is stored, mirrored onto the tab and written to disk, so anything carrying the scheme falls back to the file instead. It is created by the preview action as a page located by its document, it carries the workspace-relative path copy the editor's path header owned, and closing it revokes the grant that made the document readable while a URL tab closing beside it revokes nothing. Chrome persisted by builds that made previews editor tabs is dropped on restore rather than coming back naming a surface no restore can produce, and the ordinary editor tab for the same document is left alone. A document tab is held back at the mobile publish boundary — no client holds its grant, and the wire has no tab kind for it — while an ordinary browser tab beside it still publishes. It is held back from the group projection that publishes tab order, recency and group activity as well as from the tab list itself, so no published group names a tab the phone is never sent. A browser page can be located by a workspace document instead of a URL, and the document is the whole of its stored identity. The grant and the orca-preview URL that document is served over are minted when the page mounts and replaced by a hard reload, so neither is ever written to the page's url, mirrored onto its tab, persisted or published: such a page's url is the blank URL from creation through restore, including when a session written elsewhere carries a grant URL in, and what the session carries is the worktree and path a restored page mints afresh against today's owners. Every door onto a page's url holds that line — creation, the title update, and the navigation commit alike — so a report about a document page cannot give it a URL it never had, and the title fallback and the loading affordance follow the url each door actually wrote. The mirror carries the document too, so a tab entry cannot go on naming a document its active page has left. Every guest in the app is policy-attached through one door: a workspace document takes a restricted profile there rather than a separate installer beside it, so the attachment bookkeeping that door owns — what registration refuses, and what teardown frees — covers a preview on the same terms as a browsing page, and a preview takes none of the browsing machinery that door installs. That authority answers from the moment the embedder hands the guest over rather than only after a later navigation: the guest binds to the grant it is already showing, so the tools reach the document the reader opened and not just one they navigated to. A read the host reports as truncated or over-cap is refused rather than served partially, and a document outside the paired worktree is refused with a message naming that boundary instead of a bare read failure. The rendered document reaches nothing off-machine on its own: every served response carries a self-only content security policy, the preview session cancels any request that is not in-document, subframes cannot navigate outside the grant, a guest no document has yet bound to a grant may not navigate at all, the guest gathers no ICE candidates, and an SSH path that canonicalizes outside the grant root is refused before it is read. The one route out is a link the reader presses: a trusted click on an anchor, reported by the preview's own preload from a guest still bound to a live grant, leaves through the configured browser destination and captured source route — and only after the reader confirms the exact destination URL, so a document cannot spend a single stray press exfiltrating what it can read into a link it authored. The preview hands its guest that focus itself whenever it is the surface the reader is in — a browsing page gets it from the chrome around it, and a preview has no chrome to get it from — and it does so only then, so a preview mounted behind a terminal or an editor never takes the keyboard from what the reader is actually in. It offers again when the window itself takes focus back and nothing in the embedder has claimed that focus, because another app coming to the front lands focus on the embedder rather than the guest and the route out would otherwise stay shut until something remounted the pane — while the same window focus also arrives when the reader presses a tab, that being the guest's own blur returning, and taking focus back from there would fight the reader for their own click. Nothing else does. A navigation or popup the document starts by itself is swallowed whatever else is happening, including immediately after a genuine press elsewhere in the document, so a page that can read its grant cannot hand it to a browser tab; a middle click opens nothing; and a fragment link is answered inside the document. A preview attach carries the preview preload and no renderer-supplied one, and no other attach path can acquire it. A subresource the workspace will not send degrades the document to a notice naming that file, never to a failure panel over a page that rendered. A grant outlives neither the tab that owns it nor the renderer document that minted it, and only the trusted renderer can mint or revoke one. For the browser creations this gate still owns, owner-pinned creation returns the canonical host page identity before navigation readiness; delayed navigation cannot turn a created page into an unidentifiable failure or a duplicate retry. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback.", - "oracle": "In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Hydrate a session carrying preview chrome from a build that made previews editor tabs and require it dropped while the ordinary editor tab for the same document survives. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. Drive that notice directly for a guest bound to a live grant, for repeated attempts inside and outside its interval, for two previews at once, and for a contents no preview is bound to; require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle.", + "oracle": "In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. Drive that notice directly for a guest bound to a live grant, for repeated attempts inside and outside its interval, for two previews at once, and for a contents no preview is bound to; require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-browser.test.ts src/main/runtime/rpc/methods/browser.test.ts src/renderer/src/runtime/web-session-tabs-sync-focus-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync-browser-tabs.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/doc-preview-grant-registry.test.ts src/main/browser/doc-preview-file-reader.test.ts src/main/browser/doc-preview-protocol.test.ts src/main/browser/doc-preview-guest-policy.test.ts src/main/browser/doc-preview-failure-notice.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/lib/doc-preview-grants.test.ts src/main/window/main-window-webview-security.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts src/renderer/src/components/terminal-pane/terminal-file-link-actions.test.ts", @@ -5928,14 +5921,13 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-manager-guest-policy-profile.test.ts src/main/window/main-window-webview-security.test.ts src/main/browser/doc-preview-guest-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/shared/doc-preview-scheme.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/preload/doc-preview-link-interception.test.ts src/main/browser/doc-preview-guest-policy.test.ts src/main/window/main-window-webview-security.test.ts src/main/ipc/doc-preview-grant-ipc.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/browser-preview-tool-authorization.test.ts src/main/browser/doc-preview-guest-policy.test.ts src/main/ipc/browser.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/browser-preview-tool-authorization.test.ts src/main/browser/browser-manager-annotation-bridge.test.ts src/main/browser/browser-manager-guest-lifecycle.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/editor/EditorPanelShell.header.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/browser-preview-tool-authorization.test.ts src/main/browser/browser-manager-annotation-bridge.test.ts src/main/browser/browser-manager-guest-lifecycle.test.ts src/main/browser/offscreen-browser-backend-lifecycle.test.ts src/main/browser/doc-preview-guest-policy.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/editor/EditorPanelShell.header.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/doc-preview-grant-ipc.test.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/store/slices/tabs-hydration.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/doc-preview-grant-ipc.test.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/browser-preview-tool-authorization.test.ts src/main/ipc/browser-tab-registration-wait.test.ts src/main/ipc/doc-preview-grant-ipc.test.ts src/main/browser/browser-manager-guest-lifecycle.test.ts src/main/browser/browser-manager-guest-policy-profile.test.ts src/main/browser/browser-manager-annotation-bridge.test.ts src/main/browser/offscreen-browser-backend-lifecycle.test.ts src/main/browser/doc-preview-guest-policy.test.ts src/shared/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph-conversion-publish.test.ts src/renderer/src/lib/workspace-doc-address-input.test.ts src/shared/workspace-doc-history.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx src/renderer/src/components/browser-pane/assemble-chrome/browser-address-bar-suggestions.test.ts", "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list", @@ -5980,7 +5972,6 @@ "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", "src/renderer/src/components/terminal-pane/terminal-file-link-actions.test.ts", "src/main/ipc/doc-preview-grant-ipc.test.ts", - "src/renderer/src/store/slices/tabs-hydration.test.ts", "src/renderer/src/components/link-actions/LinkActionPopover.test.tsx", "src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts", "src/renderer/src/store/slices/browser-page-conversion.test.ts", @@ -6136,12 +6127,6 @@ "a document navigation report leaves its URL blank, its title standing and nothing loading; its session excludes preview URLs" ] }, - { - "file": "src/renderer/src/store/slices/tabs-hydration.test.ts", - "assertions": [ - "chrome for a preview tab written before previews were browser tabs is dropped, and the ordinary editor tab for the same document is kept" - ] - }, { "file": "src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts", "assertions": [ @@ -6374,8 +6359,8 @@ "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/doc-preview-grant-ipc.test.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/store/slices/tabs-hydration.test.ts", "result": "passed", "durationSeconds": 7.12, - "summary": "44/44 across all four files after PR #19130 moved the terminal popover suite to the shared LinkActionPopover path; all eight popover cases remain. This replaces the 2026-08-27 command that named the removed test path. Historical evidence from that run (4.77 seconds; mutation checks were not repeated in this rerun): 40/40 on the candidate that removes the editor preview species and moves its two boundary duties onto the browser tab. The publish filter moved with the tab: it used to exclude an editor file by mode, and now excludes a browser workspace by whether it is located by a document — asserted at both the group projection and the tab loop, because a mutant that filters only one of them still publishes. Migration is the other half: sessions written by builds that made previews editor tabs carry chrome whose entity id encodes the document, and whose document was never persisted, so it has always come back naming a surface no restore produces; that chrome is now dropped. Each mutant as the sole delta: filtering neither place publishes the document tab to mobile, filtering only the projection still publishes it, and removing the migration leaves the stale strip entry. Presence preconditions in the same runs: an ordinary browser tab beside the document tab does publish, and the ordinary editor tab for the very same document survives hydration.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/doc-preview-grant-ipc.test.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/store/slices/tabs-hydration.test.ts" + "summary": "44/44 across all four files after PR #19130 moved the terminal popover suite to the shared LinkActionPopover path; all eight popover cases remain. This replaces the 2026-08-27 command that named the removed test path. Historical evidence from that run (4.77 seconds; mutation checks were not repeated in this rerun): 40/40 on the candidate that removes the editor preview species and moves its two boundary duties onto the browser tab. The publish filter moved with the tab: it used to exclude an editor file by mode, and now excludes a browser workspace by whether it is located by a document — asserted at both the group projection and the tab loop, because a mutant that filters only one of them still publishes. Migration is the other half: sessions written by builds that made previews editor tabs carry chrome whose entity id encodes the document, and whose document was never persisted, so it has always come back naming a surface no restore produces; that chrome is now dropped. Each mutant as the sole delta: filtering neither place publishes the document tab to mobile, filtering only the projection still publishes it, and removing the migration leaves the stale strip entry. Presence preconditions in the same runs: an ordinary browser tab beside the document tab does publish, and the ordinary editor tab for the very same document survives hydration. Historical command and result are preserved after the test-value audit removed the tab-store assertions this run included. currentCommand is only an administrative link to the remaining gate command; the historical run has not validated that command or equivalent coverage.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/doc-preview-grant-ipc.test.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts" }, { "date": "2026-08-27", @@ -6619,7 +6604,8 @@ "WebRTC is fenced by the IP-handling policy rather than by removing the API; the guest can still construct a peer connection, and the journey measures that it gathers nothing.", "The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical.", "The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent.", - "The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged." + "The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged.", + "The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite." ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -8561,13 +8547,13 @@ "providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon"], - "coverageNotes": "Provider-independent unit tests cover persisted replay, state-boundary authority transfer, remote-runtime mirroring, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage.", + "coverageNotes": "Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/11757", "https://github.com/stablyai/orca/pull/11726" ], "invariant": "Within one terminal tab, each PTY has at most one layout leaf, pane manager surface, and xterm renderer owner. Restore and remote mirroring must normalize duplicate ownership before replay while retaining active-leaf focus, scrollback, pane authority, agent metadata, and distinct sibling PTYs.", - "oracle": "Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Unit contracts require the same one-owner result through persisted replay, store hydration, remote mirroring, rootless and repeated-leaf layouts, and deeply nested input.", + "oracle": "Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Component contracts cover persisted replay, rootless and repeated-leaf layouts, metadata repair, and deeply nested input. Retained store contracts cover live/future authority transfer onto a retained leaf and preservation of a prior detach destination.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", @@ -8594,8 +8580,8 @@ { "file": "src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts", "assertions": [ - "normalizes duplicate PTY surfaces at the renderer state boundary", - "moves hydrated pane authority onto the retained PTY leaf" + "moves live and future pane authority onto the retained PTY leaf", + "does not steal authority from a pane that was already detached to another tab" ] }, { @@ -8642,7 +8628,8 @@ "The gate deterministically seeds the historical persisted-state shape; it does not depend on reproducing the unknown UI sequence that originally wrote duplicate ownership.", "The visual old-release evidence and the structural current-version oracle are separate runs because the current test harness did not exist in Orca 1.4.161.", "The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage.", - "The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage." + "The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage.", + "The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage." ], "demotionRule": "Keep experimental or demote if ownership cardinality flakes, duplicate replay reaches a second renderer, active metadata or authority moves to the wrong leaf, deep normalization regresses, or a supported provider bypasses normalization." }, @@ -9043,7 +9030,7 @@ "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "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, persisted-empty restart suppression, same-incarnation handle continuity, 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. That claim now covers BOTH shapes, including the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId - each asserted by its own test. 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.", + "coverageNotes": "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. That claim now covers BOTH shapes, including the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId - each asserted by its own test. 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 retained 100-tab case measures one scan of each ownership store only. 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.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4327", "https://github.com/stablyai/orca/pull/14590", @@ -9056,7 +9043,6 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts", "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/ipc/pty/pty-management.test.ts src/main/persistence/persistence-initial-load.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-pane-authority.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/slices/terminal-tab-retirement.test.ts src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/pty-descendant-termination.test.ts src/main/daemon/session.test.ts src/main/daemon/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/worktree-teardown.test.ts", "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", @@ -9068,7 +9054,6 @@ "testFiles": [ "src/main/runtime/orca-runtime-terminal-close-continuity.test.ts", "src/main/runtime/orca-runtime.test.ts", - "src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts", "src/main/agent-hooks/server-pane-authority.test.ts", "src/main/ipc/agent-hooks.test.ts", "src/main/ipc/agent-pane-authority-ownership.test.ts", @@ -9117,12 +9102,6 @@ "a durability-acknowledged whole-tab close leaves zero terminal tabs and provider sessions after restart" ] }, - { - "file": "src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts", - "assertions": [ - "git worktree and folder workspace hydration preserve an explicit empty terminal row" - ] - }, { "file": "tests/e2e/completed-worker-retirement-resume.unit.test.ts", "assertions": [ @@ -9289,7 +9268,9 @@ "recordTerminalSurfaceRetirement advances the INCOMING session's terminal topology revision, so a tombstoned close whose write carries a revision at or below the store's own is rebased away instead of persisting. Pre-existing for every repo already past revision 0 and unchanged by the host-admitted membership fix, which only makes more repos reach that state sooner; the authoritative close path (stageTerminalSurfaceRetirements) computes from the store's session and is unaffected. Known, unaddressed, and deliberately out of scope here: the safe correction is per-tab rather than per-worktree rebase arbitration, because raising the incoming revision wholesale would re-open the host-tab loss whenever a close coincides with a host create.", "The SSH relay reattach binding (src/main/ssh/ssh-relay-session.ts persistPtyBinding) is NOT flagged host-admitted, so a lease rebind that has to mint a missing tab raises no fence. It rebinds an existing lease rather than admitting a new surface, so it is believed not to need one, but that was not established either way. Known, unaddressed, and deliberately out of scope here.", "The host-created retention journey is macOS-local; the reported incident was on a physical Windows host, which we did not run against.", - "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 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 retained 100-tab case measures one scan of each ownership store only. 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." ], "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." }, @@ -13260,7 +13241,7 @@ "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "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.", + "coverageNotes": "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.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -13275,7 +13256,7 @@ "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": "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.", + "oracle": "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/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/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", @@ -13443,10 +13424,7 @@ }, { "file": "src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", - "assertions": [ - "repeated handle rotations retain exactly one live PTY identity and update the tab fallback atomically", - "snapshot-first replacement still migrates stale PTY-indexed state" - ] + "assertions": ["publishes pane and tab replacement identities in one store commit"] }, { "file": "src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts", @@ -13539,11 +13517,7 @@ }, { "file": "src/renderer/src/store/slices/terminals-hydration.test.ts", - "assertions": [ - "target-scoped hydration and reconnect preserve sibling SSH and runtime tabs, PTY indexes, runtime ownership, and active selection", - "authoritative target-tab deletion prunes only that tab's retry, live-binding, and retry-history ledgers", - "a snapshot PTY from another SSH host is rejected from the target scope" - ] + "assertions": ["batches restored terminal reconnect wake hints into one store update"] }, { "file": "src/renderer/src/store/slices/repos-ssh-host-reconciliation.test.ts", @@ -13663,7 +13637,9 @@ "Terminal-create recovery depends on providers authoritatively listing live terminal handles and worktree ownership; older runtimes do not advertise the capability and are never retried after an unknown outcome.", "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 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 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." ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, @@ -19526,7 +19502,7 @@ "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. Store and 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.", + "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.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4876", "https://github.com/stablyai/orca/pull/15630" @@ -19534,21 +19510,16 @@ "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.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-queued-startup-consume.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-queued-startup-consume.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.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-queued-startup-consume.test.ts", "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts", - "src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts", "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts" ], "assertionRefs": [ - { - "file": "src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts", - "assertions": ["recovery remount retains the exact queued startup command"] - }, { "file": "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts", "assertions": [ @@ -19600,7 +19571,8 @@ ], "knownGaps": [ "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 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." ], "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-shard-timings.json b/config/scripts/ci-shard-timings.json index 611334053c0..d9f9d94c6c9 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -11392,46 +11392,30 @@ "src/renderer/src/store/slices/tabs-model-reconciliation.test.ts": 1800, "src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts": 2140, "src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts": 1652, - "src/renderer/src/store/slices/tabs-session-hydration.test.ts": 1772, "src/renderer/src/store/slices/tabs-split-create.test.ts": 1733, "src/renderer/src/store/slices/tabs-unread-and-focus.test.ts": 1801, "src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts": 1988, - "src/renderer/src/store/slices/tabs/layout-owner-shared-path-gates.test.ts": 1707, "src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts": 1866, - "src/renderer/src/store/slices/tabs/tab-selection-contract.test.ts": 270, - "src/renderer/src/store/slices/tabs/tabs-layout-owner-groups-order.test.ts": 1731, - "src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts": 1901, "src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703, - "src/renderer/src/store/slices/tabs/tabs-root-group.test.ts": 1796, "src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts": 1726, "src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts": 1734, - "src/renderer/src/store/slices/terminal-orphan-helpers.test.ts": 308, "src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts": 1627, "src/renderer/src/store/slices/terminal-pane-detach-agent-retention.test.ts": 2846, "src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts": 1751, "src/renderer/src/store/slices/terminal-quick-command-hosts.test.ts": 1759, - "src/renderer/src/store/slices/terminal-tab-id-hydration.test.ts": 1738, "src/renderer/src/store/slices/terminal-tab-owner-index.test.ts": 50, "src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts": 1791, "src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts": 1955, "src/renderer/src/store/slices/terminal-tab-retirement.test.ts": 338, "src/renderer/src/store/slices/terminal-tab-title-batch.test.ts": 1749, - "src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts": 1673, "src/renderer/src/store/slices/terminals-hydration-canonical-pty-overlap.test.ts": 1946, "src/renderer/src/store/slices/terminals-hydration-canonical-rows.test.ts": 1680, "src/renderer/src/store/slices/terminals-hydration.test.ts": 1768, - "src/renderer/src/store/slices/ui-acknowledge-agents-clock-skew.test.ts": 631, "src/renderer/src/store/slices/ui-agent-send-target.test.ts": 760, - "src/renderer/src/store/slices/ui-contextual-tours.test.ts": 659, "src/renderer/src/store/slices/ui-feature-interactions.test.ts": 648, "src/renderer/src/store/slices/ui-host-filter-sync.test.ts": 597, "src/renderer/src/store/slices/ui-host-workspace-statuses.test.ts": 1695, - "src/renderer/src/store/slices/ui-hydration-view-layout.test.ts": 659, - "src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts": 659, - "src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts": 723, "src/renderer/src/store/slices/ui-modal-slot-dismissal.test.ts": 662, - "src/renderer/src/store/slices/ui-notice-dismissals.test.ts": 544, - "src/renderer/src/store/slices/ui-page-navigation.test.ts": 629, "src/renderer/src/store/slices/ui/ui-slice-surface-actions.test.ts": 1760, "src/renderer/src/store/slices/workspace-activation-preparation.test.ts": 1932, "src/renderer/src/store/slices/workspace-attention/workspace-unread-characterization.test.ts": 1974, diff --git a/src/renderer/src/store/slices/tabs-close-dangling-group.test.ts b/src/renderer/src/store/slices/tabs-close-dangling-group.test.ts index 59d63c9cb0b..9b35dec4fca 100644 --- a/src/renderer/src/store/slices/tabs-close-dangling-group.test.ts +++ b/src/renderer/src/store/slices/tabs-close-dangling-group.test.ts @@ -44,14 +44,4 @@ describe('closeUnifiedTab with a missing group record (#11308)', () => { expect(result).toEqual({ closedTabId: closing.id, wasLastTab: false, worktreeId: WT }) expect(store.getState().unifiedTabsByWorktree[WT]?.map((tab) => tab.id)).toEqual([kept.id]) }) - - it('reports the last tab when the worktree has no other tab', async () => { - const only = store.getState().createUnifiedTab(WT, 'editor', { id: 'editor-only' }) - main = await drawTabsFromMain(store) - store.setState({ groupsByWorktree: { [WT]: [] } }) - - expect(store.getState().closeUnifiedTab(only.id)?.wasLastTab).toBe(true) - await main.settle() - expect(store.getState().unifiedTabsByWorktree[WT] ?? []).toEqual([]) - }) }) diff --git a/src/renderer/src/store/slices/tabs-hydration-group-validation.test.ts b/src/renderer/src/store/slices/tabs-hydration-group-validation.test.ts index 08799d10af5..95d2d3b40d9 100644 --- a/src/renderer/src/store/slices/tabs-hydration-group-validation.test.ts +++ b/src/renderer/src/store/slices/tabs-hydration-group-validation.test.ts @@ -12,91 +12,6 @@ function makeBaseSession(): WorkspaceSessionState { } } -describe('buildHydratedTabState group validation', () => { - it('filters out invalid worktree IDs', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - unifiedTabs: { - w1: [ - { - id: 't1', - entityId: 't1', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'terminal', - label: 'Term', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ], - w_gone: [ - { - id: 't2', - entityId: 't2', - groupId: 'g2', - worktreeId: 'w_gone', - contentType: 'terminal', - label: 'Gone', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - tabGroups: { - w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }], - w_gone: [{ id: 'g2', worktreeId: 'w_gone', activeTabId: 't2', tabOrder: ['t2'] }] - } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - - expect(result.unifiedTabsByWorktree.w1).toHaveLength(1) - expect(result.unifiedTabsByWorktree.w_gone).toBeUndefined() - }) - - it('validates group references against hydrated tabs', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - unifiedTabs: { - w1: [ - { - id: 't1', - entityId: 't1', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'terminal', - label: 'Term', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - tabGroups: { - w1: [ - { - id: 'g1', - worktreeId: 'w1', - activeTabId: 'deleted-tab', - tabOrder: ['deleted-tab', 't1'] - } - ] - } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - const group = result.groupsByWorktree.w1[0] - - expect(group.activeTabId).toBeNull() - expect(group.tabOrder).toEqual(['t1']) - }) -}) - describe('buildHydratedTabState referential repair', () => { const tab = (id: string, groupId: string, sortOrder: number) => ({ id, @@ -143,73 +58,6 @@ describe('buildHydratedTabState referential repair', () => { ]) }) - it('adopts tabs stranded by one dropped group into a surviving group', () => { - const result = buildHydratedTabState( - { - ...makeBaseSession(), - unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g2', 1)] }, - tabGroups: { w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }] } - }, - new Set(['w1']) - ) - - expect(result.groupsByWorktree.w1.map((group) => group.id)).toEqual(['g1']) - expect(result.groupsByWorktree.w1[0].tabOrder).toEqual(['t1', 't2']) - expect(result.unifiedTabsByWorktree.w1.map((t) => t.groupId)).toEqual(['g1', 'g1']) - }) - - it('repairs a tab groupId when a surviving group already owns the tab', () => { - const result = buildHydratedTabState( - { - ...makeBaseSession(), - unifiedTabs: { w1: [tab('t1', 'g-dropped', 0)] }, - tabGroups: { w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }] } - }, - new Set(['w1']) - ) - - expect(result.groupsByWorktree.w1[0].tabOrder).toEqual(['t1']) - expect(result.unifiedTabsByWorktree.w1[0].groupId).toBe('g1') - }) - - it('spans every surviving group when the persisted layout is gone', () => { - // Salvaged layouts must span every surviving group or tabs in omitted groups remain silently hidden. - const result = buildHydratedTabState( - { - ...makeBaseSession(), - unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g2', 1)] }, - tabGroups: { - w1: [ - { id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }, - { id: 'g2', worktreeId: 'w1', activeTabId: 't2', tabOrder: ['t2'] } - ] - } - }, - new Set(['w1']) - ) - - expect(leafGroupIds(result.layoutByWorktree.w1)).toEqual(['g1', 'g2']) - }) - - it('adds surviving groups omitted by a partial persisted layout', () => { - const result = buildHydratedTabState( - { - ...makeBaseSession(), - unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g2', 1)] }, - tabGroups: { - w1: [ - { id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }, - { id: 'g2', worktreeId: 'w1', activeTabId: 't2', tabOrder: ['t2'] } - ] - }, - tabGroupLayouts: { w1: { type: 'leaf', groupId: 'g1' } } - }, - new Set(['w1']) - ) - - expect(leafGroupIds(result.layoutByWorktree.w1)).toEqual(['g1', 'g2']) - }) - it('collapses a persisted layout that repeats one group across leaves', () => { const result = buildHydratedTabState( { diff --git a/src/renderer/src/store/slices/tabs-hydration.test.ts b/src/renderer/src/store/slices/tabs-hydration.test.ts index a5a86d57175..732485029c2 100644 --- a/src/renderer/src/store/slices/tabs-hydration.test.ts +++ b/src/renderer/src/store/slices/tabs-hydration.test.ts @@ -15,273 +15,6 @@ function makeBaseSession(): WorkspaceSessionState { } describe('buildHydratedTabState – unified format', () => { - it('hydrates tabs and groups from unified format', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - unifiedTabs: { - w1: [ - { - id: 't1', - entityId: 't1', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'terminal', - label: 'Term', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'f1', - entityId: 'f1', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'editor', - label: 'File', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - tabGroups: { - w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1', 'f1'] }] - } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - expect(result.unifiedTabsByWorktree.w1).toHaveLength(2) - expect(result.groupsByWorktree.w1).toHaveLength(1) - expect(result.activeGroupIdByWorktree.w1).toBe('g1') - }) - - // Legacy previews persisted editor chrome without documents; drop unrestorable preview tabs while retaining normal editors. - it('drops the chrome of a preview tab from before previews were browser tabs', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - openFilesByWorktree: { - w1: [ - { - filePath: '/repo/docs/report.html', - relativePath: 'docs/report.html', - worktreeId: 'w1', - language: 'html' - } - ] - }, - unifiedTabs: { - w1: [ - { - id: 'preview-1', - entityId: 'html-preview::w1::/repo/docs/report.html', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'editor', - label: 'docs/report.html (preview)', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'editor-1', - entityId: '/repo/docs/report.html', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'editor', - label: 'report.html', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - tabGroups: { - w1: [ - { - id: 'g1', - worktreeId: 'w1', - activeTabId: 'preview-1', - tabOrder: ['preview-1', 'editor-1'] - } - ] - } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - - // Same-document normal editor must survive; dropping all editor chrome would pass an empty-strip check. - expect(result.unifiedTabsByWorktree.w1?.map((tab) => tab.id)).toEqual(['editor-1']) - }) - - it('collapses groups and layout when transient tabs are dropped during hydration', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - openFilesByWorktree: { - w1: [ - { - filePath: '/editor.ts', - relativePath: 'editor.ts', - worktreeId: 'w1', - language: 'typescript' - } - ] - }, - unifiedTabs: { - w1: [ - { - id: 'diff-1', - entityId: '/diff.ts', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'diff', - label: 'diff.ts', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'editor-1', - entityId: '/editor.ts', - groupId: 'g2', - worktreeId: 'w1', - contentType: 'editor', - label: 'editor.ts', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - tabGroups: { - w1: [ - { id: 'g1', worktreeId: 'w1', activeTabId: 'diff-1', tabOrder: ['diff-1'] }, - { id: 'g2', worktreeId: 'w1', activeTabId: 'editor-1', tabOrder: ['editor-1'] } - ] - }, - tabGroupLayouts: { - w1: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: 'g1' }, - second: { type: 'leaf', groupId: 'g2' }, - ratio: 0.5 - } - }, - activeGroupIdByWorktree: { w1: 'g1' } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - - expect(result.unifiedTabsByWorktree.w1).toEqual([ - expect.objectContaining({ id: 'editor-1', groupId: 'g2', contentType: 'editor' }) - ]) - expect(result.groupsByWorktree.w1).toEqual([ - { - id: 'g2', - worktreeId: 'w1', - activeTabId: 'editor-1', - tabOrder: ['editor-1'], - recentTabIds: ['editor-1'] - } - ]) - expect(result.activeGroupIdByWorktree.w1).toBe('g2') - expect(result.layoutByWorktree.w1).toEqual({ type: 'leaf', groupId: 'g2' }) - }) - - it('keeps restored simulator tabs while pruning unrelated empty split groups', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - unifiedTabs: { - w1: [ - { - id: 'terminal-1', - entityId: 'terminal-1', - groupId: 'g1', - worktreeId: 'w1', - contentType: 'terminal', - label: 'Terminal', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'simulator-1', - entityId: 'simulator-1', - groupId: 'g2', - worktreeId: 'w1', - contentType: 'simulator', - label: 'iPhone 17 Pro', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - tabGroups: { - w1: [ - { id: 'g1', worktreeId: 'w1', activeTabId: 'terminal-1', tabOrder: ['terminal-1'] }, - { id: 'g2', worktreeId: 'w1', activeTabId: 'simulator-1', tabOrder: ['simulator-1'] }, - { id: 'g3', worktreeId: 'w1', activeTabId: null, tabOrder: [] } - ] - }, - tabGroupLayouts: { - w1: { - type: 'split', - direction: 'horizontal', - first: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: 'g1' }, - second: { type: 'leaf', groupId: 'g2' }, - ratio: 0.5 - }, - second: { type: 'leaf', groupId: 'g3' }, - ratio: 0.5 - } - }, - activeGroupIdByWorktree: { w1: 'g2' } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - - expect(result.unifiedTabsByWorktree.w1).toEqual([ - expect.objectContaining({ id: 'terminal-1', contentType: 'terminal', groupId: 'g1' }), - expect.objectContaining({ id: 'simulator-1', contentType: 'simulator', groupId: 'g2' }) - ]) - expect(result.groupsByWorktree.w1).toEqual([ - { - id: 'g1', - worktreeId: 'w1', - activeTabId: 'terminal-1', - tabOrder: ['terminal-1'], - recentTabIds: ['terminal-1'] - }, - { - id: 'g2', - worktreeId: 'w1', - activeTabId: 'simulator-1', - tabOrder: ['simulator-1'], - recentTabIds: ['simulator-1'] - } - ]) - expect(result.activeGroupIdByWorktree.w1).toBe('g2') - expect(result.layoutByWorktree.w1).toEqual({ - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: 'g1' }, - second: { type: 'leaf', groupId: 'g2' }, - ratio: 0.5 - }) - }) - it('collapses tab records that a corrupt session persisted under one id', () => { // Editor migration could re-stamp a sibling’s tab ID; duplicate React keys strand ghost rows. const duplicateId = 'editor:wt%3A%3Alungfish:env-a:FINAL-REPORT.md' diff --git a/src/renderer/src/store/slices/tabs-label-and-pin-state.test.ts b/src/renderer/src/store/slices/tabs-label-and-pin-state.test.ts index 3c5c536a3e0..eb23150a21c 100644 --- a/src/renderer/src/store/slices/tabs-label-and-pin-state.test.ts +++ b/src/renderer/src/store/slices/tabs-label-and-pin-state.test.ts @@ -45,18 +45,6 @@ vi.mock('@/runtime/runtime-layout-client', async (importOriginal) => store = createTestStore() }) - describe('tab property setters', () => { - it('setTabLabel preserves tab map references when the label is unchanged', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().setTabLabel(tab.id, 'zsh') - const before = store.getState().unifiedTabsByWorktree - - store.getState().setTabLabel(tab.id, 'zsh') - - expect(store.getState().unifiedTabsByWorktree).toBe(before) - }) - }) - describe('pinTab / unpinTab', () => { it('pins a tab and promotes preview to permanent', async () => { store.setState({ @@ -102,124 +90,6 @@ vi.mock('@/runtime/runtime-layout-client', async (importOriginal) => main.close() } }) - - it('moves pinned tabs before unpinned siblings', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().pinTab(t3.id) - store.getState().pinTab(t2.id) - - expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([t3.id, t2.id, t1.id]) - expect(store.getState().unifiedTabsByWorktree[WT].map((tab) => tab.sortOrder)).toEqual([ - 2, 1, 0 - ]) - }) - - it('keeps remaining pinned tabs before a tab that was unpinned', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().pinTab(t2.id) - store.getState().pinTab(t3.id) - - store.getState().unpinTab(t2.id) - - expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([t3.id, t2.id, t1.id]) - }) - - it('syncs isPinned to the TerminalTab in tabsByWorktree (reconcile echo guard)', async () => { - // Sync legacy isPinned too or reconciliation unpins the tab during host-snapshot echo. - const tab = store.getState().createUnifiedTab(WT, 'terminal') - store.setState((state) => ({ - tabsByWorktree: { - ...state.tabsByWorktree, - [WT]: [ - { - id: tab.id, - ptyId: null, - worktreeId: WT, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - } - })) - - // A layout-owner build draws the color from main's frame. - const main = await drawTabsFromMain(store) - try { - const interaction = vi.fn() - store.setState({ recordFeatureInteraction: interaction }) - store.getState().pinTab(tab.id, { recordInteraction: false }) - expect(store.getState().tabsByWorktree[WT][0].isPinned).toBe(true) - store.getState().unpinTab(tab.id, { recordInteraction: false }) - expect(store.getState().tabsByWorktree[WT][0].isPinned).toBe(false) - store.getState().setTabColor(tab.entityId, '#ff0000', { recordInteraction: false }) - await main.settle() - expect(store.getState().tabsByWorktree[WT][0].color).toBe('#ff0000') - expect(interaction).not.toHaveBeenCalled() - store.getState().pinTab(tab.id) - store.getState().unpinTab(tab.id) - store.getState().setTabColor(tab.entityId, null) - await main.settle() - expect(interaction).toHaveBeenCalledTimes(3) - } finally { - main.close() - } - }) - }) - }) -} - -{ - createTabsSliceMockApi() - const mockWindow = globalThis.window - - const WT = 'repo1::/tmp/feature' - - describe('createEmptySplitGroup', () => { - beforeEach(() => { - globalThis.window = mockWindow - }) - - let store: ReturnType - - beforeEach(() => { - store = createTestStore() - }) - - it('activates the new group by default so terminal splits land in the empty pane', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal') - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - - const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right') - - expect(targetGroupId).toBeTruthy() - expect(store.getState().activeGroupIdByWorktree[WT]).toBe(targetGroupId) - expect( - store.getState().groupsByWorktree[WT].find((group) => group.id === sourceGroupId) - ).toEqual(expect.objectContaining({ tabOrder: [tab.id] })) - }) - - it('keeps the source group focused when activate is false', () => { - store.getState().createUnifiedTab(WT, 'editor', { id: 'file-a.ts', label: 'file-a.ts' }) - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - - const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right', { - activate: false - }) - - expect(targetGroupId).toBeTruthy() - expect(store.getState().activeGroupIdByWorktree[WT]).toBe(sourceGroupId) - expect(store.getState().groupsByWorktree[WT].map((group) => group.id)).toEqual([ - sourceGroupId, - targetGroupId - ]) }) }) } diff --git a/src/renderer/src/store/slices/tabs-model-reconciliation.test.ts b/src/renderer/src/store/slices/tabs-model-reconciliation.test.ts index ca70a5a2663..c0e3944aa89 100644 --- a/src/renderer/src/store/slices/tabs-model-reconciliation.test.ts +++ b/src/renderer/src/store/slices/tabs-model-reconciliation.test.ts @@ -25,535 +25,6 @@ describe('TabsSlice', () => { }) describe('reconcileWorktreeTabModel', () => { - it('drops unified tabs whose backing content no longer exists', () => { - const groupId = 'g-1' - store.setState({ - unifiedTabsByWorktree: { - [WT]: [ - { - id: 'stale-terminal', - entityId: 'stale-terminal', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - groupsByWorktree: { - [WT]: [ - { - id: groupId, - worktreeId: WT, - activeTabId: 'stale-terminal', - tabOrder: ['stale-terminal'] - } - ] - }, - activeGroupIdByWorktree: { [WT]: groupId }, - tabsByWorktree: { [WT]: [] } - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - - expect(result.renderableTabCount).toBe(0) - expect(result.activeRenderableTabId).toBeNull() - expect(store.getState().unifiedTabsByWorktree[WT]).toEqual([]) - expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([]) - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBeNull() - }) - - // Reconnect-map-only liveness must prevent orphan sweep from deleting terminals before rebind (#9911). - it('keeps a reconnecting terminal whose live session survives only in a reconnect map', () => { - store.setState({ - tabsByWorktree: { - [WT]: [ - { - id: 'reconnecting-terminal', - ptyId: null, - worktreeId: WT, - title: 'claude', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'reconnecting-terminal': [] }, - pendingReconnectPtyIdByTabId: { 'reconnecting-terminal': 'session-live' }, - unifiedTabsByWorktree: { [WT]: [] }, - groupsByWorktree: {}, - activeGroupIdByWorktree: {} - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const state = store.getState() - - expect(state.tabsByWorktree[WT].map((tab) => tab.id)).toContain('reconnecting-terminal') - expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.entityId)).toContain( - 'reconnecting-terminal' - ) - expect(result.renderableTabCount).toBe(1) - }) - - it('restores a marker-only terminal when the host loss omitted its unified row', () => { - store.setState({ - tabsByWorktree: { - [WT]: [ - { - id: 'host-lost-terminal', - ptyId: null, - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'host-lost-terminal': [] }, - unverifiedPtyLossTabIds: { 'host-lost-terminal': true }, - unifiedTabsByWorktree: { [WT]: [] }, - groupsByWorktree: {}, - activeGroupIdByWorktree: {} - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const state = store.getState() - - expect(result.renderableTabCount).toBe(1) - expect(state.unifiedTabsByWorktree[WT]?.map((tab) => tab.entityId)).toContain( - 'host-lost-terminal' - ) - }) - - // Mirrored layouts could append a second leaf for one group and repeat tab strips; collapse duplicates. - it('collapses a layout that repeats one group across leaves', () => { - const groupId = 'g-1' - store.setState({ - unifiedTabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - entityId: 'terminal-1', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - tabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - ptyId: 'pty-1', - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'terminal-1': ['pty-1'] }, - groupsByWorktree: { - [WT]: [ - { id: groupId, worktreeId: WT, activeTabId: 'terminal-1', tabOrder: ['terminal-1'] } - ] - }, - activeGroupIdByWorktree: { [WT]: groupId }, - layoutByWorktree: { - [WT]: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId }, - second: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId }, - second: { type: 'leaf', groupId } - } - } - } - }) - - store.getState().reconcileWorktreeTabModel(WT) - - expect(store.getState().layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId }) - }) - - it('keeps simulator tabs because they reconnect their own backing stream', () => { - const terminalGroupId = 'g-terminal' - const simulatorGroupId = 'g-simulator' - store.setState({ - unifiedTabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - entityId: 'terminal-1', - groupId: terminalGroupId, - worktreeId: WT, - contentType: 'terminal', - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'simulator-1', - entityId: 'simulator-1', - groupId: simulatorGroupId, - worktreeId: WT, - contentType: 'simulator', - label: 'iPhone 17 Pro', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 2 - } - ] - }, - groupsByWorktree: { - [WT]: [ - { - id: terminalGroupId, - worktreeId: WT, - activeTabId: 'terminal-1', - tabOrder: ['terminal-1'] - }, - { - id: simulatorGroupId, - worktreeId: WT, - activeTabId: 'simulator-1', - tabOrder: ['simulator-1'] - } - ] - }, - layoutByWorktree: { - [WT]: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: terminalGroupId }, - second: { type: 'leaf', groupId: simulatorGroupId } - } - }, - activeGroupIdByWorktree: { [WT]: simulatorGroupId }, - tabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - ptyId: 'pty-1', - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'terminal-1': ['pty-1'] } - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const state = store.getState() - - expect(result.renderableTabCount).toBe(2) - expect(result.activeRenderableTabId).toBe('simulator-1') - expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.id)).toEqual([ - 'terminal-1', - 'simulator-1' - ]) - expect(state.groupsByWorktree[WT].map((group) => group.tabOrder)).toEqual([ - ['terminal-1'], - ['simulator-1'] - ]) - expect(state.layoutByWorktree[WT]).toEqual({ - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: terminalGroupId }, - second: { type: 'leaf', groupId: simulatorGroupId } - }) - }) - - it('keeps a structured session activation target during worktree reconciliation', () => { - const groupId = 'g-structured' - store.setState({ - unifiedTabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - entityId: 'terminal-1', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'structured-session-1', - entityId: 'session-1', - groupId, - worktreeId: WT, - contentType: 'agent-session', - label: 'Codex Chat', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2, - agentSessionAgent: 'codex' - } - ] - }, - groupsByWorktree: { - [WT]: [ - { - id: groupId, - worktreeId: WT, - activeTabId: 'structured-session-1', - tabOrder: ['terminal-1', 'structured-session-1'] - } - ] - }, - activeGroupIdByWorktree: { [WT]: groupId }, - tabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - ptyId: 'pty-1', - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'terminal-1': ['pty-1'] } - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const state = store.getState() - - expect(result).toEqual({ - renderableTabCount: 2, - activeRenderableTabId: 'structured-session-1' - }) - expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.id)).toEqual([ - 'terminal-1', - 'structured-session-1' - ]) - expect(state.groupsByWorktree[WT][0]).toMatchObject({ - activeTabId: 'structured-session-1', - tabOrder: ['terminal-1', 'structured-session-1'] - }) - }) - - it('collapses empty split groups when reconciliation drops a stale tab', () => { - const terminalGroupId = 'g-terminal' - const staleGroupId = 'g-stale' - store.setState({ - unifiedTabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - entityId: 'terminal-1', - groupId: terminalGroupId, - worktreeId: WT, - contentType: 'terminal', - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'stale-browser', - entityId: 'missing-browser', - groupId: staleGroupId, - worktreeId: WT, - contentType: 'browser', - label: 'Missing browser', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - groupsByWorktree: { - [WT]: [ - { - id: terminalGroupId, - worktreeId: WT, - activeTabId: 'terminal-1', - tabOrder: ['terminal-1'] - }, - { - id: staleGroupId, - worktreeId: WT, - activeTabId: 'stale-browser', - tabOrder: ['stale-browser'] - } - ] - }, - layoutByWorktree: { - [WT]: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: terminalGroupId }, - second: { type: 'leaf', groupId: staleGroupId } - } - }, - activeGroupIdByWorktree: { [WT]: staleGroupId }, - tabsByWorktree: { - [WT]: [ - { - id: 'terminal-1', - ptyId: 'pty-1', - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'terminal-1': ['pty-1'] }, - browserTabsByWorktree: { [WT]: [] } - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const state = store.getState() - - expect(result.renderableTabCount).toBe(1) - expect(result.activeRenderableTabId).toBe('terminal-1') - expect(state.groupsByWorktree[WT]).toEqual([ - expect.objectContaining({ id: terminalGroupId, tabOrder: ['terminal-1'] }) - ]) - expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: terminalGroupId }) - expect(state.activeGroupIdByWorktree[WT]).toBe(terminalGroupId) - }) - - it('restores live runtime terminal tabs into the unified tab model', () => { - const runtimeTerminalId = 'runtime-terminal-1' - - store.setState({ - tabsByWorktree: { - [WT]: [ - { - id: runtimeTerminalId, - ptyId: 'pty-4', - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { - [runtimeTerminalId]: ['pty-4'] - }, - unifiedTabsByWorktree: { - [WT]: [] - }, - groupsByWorktree: { - [WT]: [] - }, - activeGroupIdByWorktree: {} - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const state = store.getState() - const restoredTab = state.unifiedTabsByWorktree[WT]?.[0] - const restoredGroup = state.groupsByWorktree[WT]?.[0] - - expect(result.renderableTabCount).toBe(1) - expect(result.activeRenderableTabId).toBe(runtimeTerminalId) - expect(restoredTab).toMatchObject({ - id: runtimeTerminalId, - entityId: runtimeTerminalId, - contentType: 'terminal', - label: 'Terminal 1' - }) - expect(restoredGroup).toMatchObject({ - activeTabId: runtimeTerminalId, - tabOrder: [runtimeTerminalId] - }) - expect(state.layoutByWorktree[WT]).toEqual({ - type: 'leaf', - groupId: restoredGroup?.id - }) - }) - - it('promotes legacy terminals to the worktree remembered tab, not always the first one', () => { - // Why (regression): reconcile seeded the group with restoredLegacyTabs[0], dropping the remembered selection so it always reopened Terminal 1. - const firstTerminalId = 'runtime-terminal-1' - const secondTerminalId = 'runtime-terminal-2' - - store.setState({ - tabsByWorktree: { - [WT]: [ - { - id: firstTerminalId, - ptyId: 'pty-1', - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: secondTerminalId, - ptyId: 'pty-2', - worktreeId: WT, - title: 'Terminal 2', - customTitle: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - ptyIdsByTabId: { - [firstTerminalId]: ['pty-1'], - [secondTerminalId]: ['pty-2'] - }, - unifiedTabsByWorktree: { [WT]: [] }, - groupsByWorktree: { [WT]: [] }, - activeGroupIdByWorktree: {}, - activeTabIdByWorktree: { [WT]: secondTerminalId } - }) - - const result = store.getState().reconcileWorktreeTabModel(WT) - const restoredGroup = store.getState().groupsByWorktree[WT]?.[0] - - expect(result.renderableTabCount).toBe(2) - expect(result.activeRenderableTabId).toBe(secondTerminalId) - expect(restoredGroup?.activeTabId).toBe(secondTerminalId) - }) - it('keeps a sole terminal renderable after its PTY exits so a failed direnv does not strand the worktree', () => { // Why (regression): a promoted terminal whose PTY dies must stay renderable, not orphan and bounce to Landing. const tab = store diff --git a/src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts b/src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts index c5142ab28aa..59988931610 100644 --- a/src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts +++ b/src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import type * as AgentStatusModule from '@/lib/agent-status' -import { getDefaultUIState } from '../../../../shared/constants' +import '../../../../shared/constants' import { buildMobileSessionTabSnapshots } from '../../runtime/sync-runtime-graph/mobile-session-snapshots' import { closeMobileSessionTabInStore } from '../../runtime/mobile-session-tab-close' import { createTabsSliceMockApi } from './tabs-slice-test-harness' @@ -10,8 +10,7 @@ import { makeOpenFile, makeTab, makeTabGroup, - makeUnifiedTab, - makeWorktree + makeUnifiedTab } from './store-test-helpers' import { makeBrowserTab } from './store-session-test-harness' import { drawTabsFromMain } from './tabs-drawn-from-main.test-fixture' @@ -63,202 +62,7 @@ describe('TabsSlice', () => { store = createTestStore() }) - describe('createUnifiedTab', () => { - it('creates a terminal tab and auto-creates a group', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal') - - expect(tab.contentType).toBe('terminal') - expect(tab.worktreeId).toBe(WT) - expect(tab.label).toMatch(/^Terminal/) - - const state = store.getState() - expect(state.unifiedTabsByWorktree[WT]).toHaveLength(1) - expect(state.groupsByWorktree[WT]).toHaveLength(1) - expect(state.groupsByWorktree[WT][0].activeTabId).toBe(tab.id) - expect(state.groupsByWorktree[WT][0].tabOrder).toEqual([tab.id]) - }) - - it('creates an editor tab with filePath as id', () => { - const tab = store.getState().createUnifiedTab(WT, 'editor', { - id: '/tmp/feature/src/main.ts', - label: 'main.ts' - }) - - expect(tab.id).toBe('/tmp/feature/src/main.ts') - expect(tab.contentType).toBe('editor') - expect(tab.label).toBe('main.ts') - }) - - it('stamps tabs with the active execution host', () => { - store.setState({ - activeWorktreeId: WT, - activeWorkspaceExecutionHostId: 'runtime:host-b' - }) - - expect(store.getState().createUnifiedTab(WT, 'simulator').executionHostId).toBe( - 'runtime:host-b' - ) - }) - - it('stamps active local tabs when the local host field is null', () => { - store.setState({ activeWorktreeId: WT, activeWorkspaceExecutionHostId: null }) - - expect(store.getState().createUnifiedTab(WT, 'browser').executionHostId).toBe('local') - }) - - it("stamps an SSH worktree's own host when activation passed none", () => { - store.setState({ - repos: [ - { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } - ], - worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', hostId: 'ssh:box' })] }, - activeWorktreeId: WT, - activeWorkspaceExecutionHostId: null - }) - - expect(store.getState().createUnifiedTab(WT, 'browser').executionHostId).toBe('ssh:box') - }) - - it('activates the newly created tab', () => { - const tab1 = store.getState().createUnifiedTab(WT, 'terminal') - const tab2 = store.getState().createUnifiedTab(WT, 'terminal') - - const group = store.getState().groupsByWorktree[WT][0] - expect(group.activeTabId).toBe(tab2.id) - expect(group.tabOrder).toEqual([tab1.id, tab2.id]) - }) - - it('can create a tab without activating it', () => { - const tab1 = store.getState().createUnifiedTab(WT, 'terminal') - const tab2 = store.getState().createUnifiedTab(WT, 'browser', { activate: false }) - - const group = store.getState().groupsByWorktree[WT][0] - expect(group.activeTabId).toBe(tab1.id) - expect(group.tabOrder).toEqual([tab1.id, tab2.id]) - expect(group.recentTabIds).toEqual([tab1.id]) - }) - - it('replaces existing preview tab when creating a new preview', () => { - const preview1 = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts', - isPreview: true - }) - store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-b.ts', - label: 'file-b.ts', - isPreview: true - }) - - const tabs = store.getState().unifiedTabsByWorktree[WT] - expect(tabs).toHaveLength(1) - expect(tabs[0].id).toBe('file-b.ts') - - const group = store.getState().groupsByWorktree[WT][0] - expect(group.tabOrder).toEqual(['file-b.ts']) - expect(group.tabOrder).not.toContain(preview1.id) - }) - - it('replaces editor preview tabs with diff preview tabs', () => { - store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts', - isPreview: true - }) - store.getState().createUnifiedTab(WT, 'diff', { - id: 'diff-file-b.ts', - entityId: 'diff-file-b.ts', - label: 'file-b.ts', - isPreview: true - }) - - expect(store.getState().unifiedTabsByWorktree[WT]).toEqual([ - expect.objectContaining({ - id: 'diff-file-b.ts', - contentType: 'diff', - isPreview: true - }) - ]) - expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual(['diff-file-b.ts']) - }) - - it('reuses the existing group for the worktree', () => { - store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'editor', { id: 'f.ts', label: 'f.ts' }) - - expect(store.getState().groupsByWorktree[WT]).toHaveLength(1) - }) - }) - - describe('terminal tab creation tracking', () => { - it('records normal terminal tab creation without recording activation fallback tabs', () => { - const setMock = vi.mocked(window.api.ui.set) - store.getState().hydratePersistedUI(getDefaultUIState()) - setMock.mockClear() - - store.getState().createTab(WT) - store.getState().createTab(WT, undefined, undefined, { pendingActivationSpawn: true }) - - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ - featureInteractions: { - 'terminal-tabs': expect.objectContaining({ interactionCount: 1 }) - } - }) - }) - }) - describe('closeUnifiedTab', () => { - it('removes the tab and selects right neighbor', () => { - store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().activateTab(t2.id) - - const result = store.getState().closeUnifiedTab(t2.id) - - expect(result).toEqual({ closedTabId: t2.id, wasLastTab: false, worktreeId: WT }) - const state = store.getState() - expect(state.unifiedTabsByWorktree[WT]).toHaveLength(2) - expect(state.groupsByWorktree[WT][0].activeTabId).toBe(t3.id) - }) - - it('selects left neighbor when closing the rightmost tab', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - - const result = store.getState().closeUnifiedTab(t2.id) - - expect(result?.wasLastTab).toBe(false) - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id) - }) - - it('returns wasLastTab: true when closing the only tab', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - - const result = store.getState().closeUnifiedTab(t1.id) - - expect(result?.wasLastTab).toBe(true) - expect(store.getState().unifiedTabsByWorktree[WT]).toHaveLength(0) - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBeNull() - }) - - it('does not change active tab when closing a non-active tab', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().closeUnifiedTab(t1.id) - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t3.id) - }) - - it('returns null for nonexistent tab', () => { - const result = store.getState().closeUnifiedTab('nonexistent') - expect(result).toBeNull() - }) - it('removes a mobile-closed markdown tab from open files so it is not republished', async () => { const groupId = 'editor-group' const file = makeOpenFile({ @@ -312,59 +116,6 @@ describe('TabsSlice', () => { expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs ?? []).toEqual([]) }) - it('removes a mobile-closed regular file tab from open files so fallback closes do not resurrect', async () => { - const groupId = 'editor-group' - const file = makeOpenFile({ - id: '/tmp/feature/src/app.ts', - filePath: '/tmp/feature/src/app.ts', - relativePath: 'src/app.ts', - language: 'typescript', - worktreeId: WT - }) - const tab = makeUnifiedTab({ - id: 'app-unified', - entityId: file.id, - contentType: 'editor', - label: 'app.ts', - worktreeId: WT, - groupId - }) - store.setState({ - openFiles: [file], - unifiedTabsByWorktree: { [WT]: [tab] }, - groupsByWorktree: { - [WT]: [ - makeTabGroup({ - id: groupId, - worktreeId: WT, - activeTabId: tab.id, - tabOrder: [tab.id], - recentTabIds: [tab.id] - }) - ] - }, - activeGroupIdByWorktree: { [WT]: groupId }, - activeFileId: file.id, - activeFileIdByWorktree: { [WT]: file.id }, - activeWorktreeId: WT, - activeTabType: 'editor', - activeTabTypeByWorktree: { [WT]: 'editor' } - }) - - expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs).toMatchObject([ - { id: tab.id, type: 'file', filePath: file.filePath } - ]) - - const main = await drawTabsFromMain(store) - expect(closeMobileSessionTabInStore(store.getState(), WT, tab.id)).toBe(true) - // A layout-owner build closes the tab in main; the file goes after its frame drops the tab. - await main.settle() - main.close() - - expect(store.getState().openFiles).toEqual([]) - expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs ?? []).toEqual([]) - }) - it('closes a mobile fallback file-id tab after the unified wrapper is already gone', () => { const file = makeOpenFile({ id: '/tmp/feature/src/app.ts', @@ -417,263 +168,5 @@ describe('TabsSlice', () => { .sort() ).toEqual([t1.id, t2.id].sort()) }) - - it('falls back to neighbor selection when the MRU stack has no prior tab', () => { - // Build state manually (no prior activations) — mirrors a freshly-hydrated session with only an active tab known. - const groupId = 'mru-fallback-group' - store.setState({ - unifiedTabsByWorktree: { - [WT]: [ - { - id: 'a', - entityId: 'a', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'a', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: 'b', - entityId: 'b', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'b', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - }, - { - id: 'c', - entityId: 'c', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'c', - customLabel: null, - color: null, - sortOrder: 2, - createdAt: 3 - } - ] - }, - groupsByWorktree: { - [WT]: [ - { - id: groupId, - worktreeId: WT, - activeTabId: 'b', - tabOrder: ['a', 'b', 'c'], - recentTabIds: ['b'] - } - ] - }, - activeGroupIdByWorktree: { [WT]: groupId } - }) - - store.getState().closeUnifiedTab('b') - - // MRU only contains 'b' itself, so fallback picks the right neighbor 'c'. - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe('c') - }) - - it('tracks an independent MRU history per tab group', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - const secondGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right') - expect(secondGroupId).toBeTruthy() - - const t2 = store.getState().createUnifiedTab(WT, 'terminal', { - targetGroupId: secondGroupId! - }) - const t3 = store.getState().createUnifiedTab(WT, 'terminal', { - targetGroupId: secondGroupId! - }) - - // Focus the source group without changing the second group’s MRU. - store.getState().activateTab(t1.id) - - // Re-focus the second group via t2, then close it: expect the same-group previous tab (t3), not a source-group neighbor. - store.getState().activateTab(t3.id) - store.getState().activateTab(t2.id) - store.getState().closeUnifiedTab(t2.id) - - const secondGroup = store.getState().groupsByWorktree[WT].find((g) => g.id === secondGroupId) - expect(secondGroup?.activeTabId).toBe(t3.id) - const sourceGroup = store.getState().groupsByWorktree[WT].find((g) => g.id === sourceGroupId) - expect(sourceGroup?.activeTabId).toBe(t1.id) - }) - - it('records generic pane interaction when creating an empty split group', () => { - const setMock = vi.mocked(window.api.ui.set) - store.getState().hydratePersistedUI(getDefaultUIState()) - setMock.mockClear() - store.getState().createUnifiedTab(WT, 'terminal') - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - - store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right') - - expect(store.getState().featureInteractions['terminal-pane-split']).toBeUndefined() - expect(store.getState().featureInteractions['terminal-panes']).toMatchObject({ - interactionCount: 1 - }) - }) - }) - - describe('closeOtherTabs', () => { - it('closes all tabs except the target and pinned tabs', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().pinTab(t1.id) - - const closed = store.getState().closeOtherTabs(t2.id) - - expect(closed).toEqual([t3.id]) - const tabs = store.getState().unifiedTabsByWorktree[WT] - expect(tabs).toHaveLength(2) - expect(tabs.map((t) => t.id)).toContain(t1.id) - expect(tabs.map((t) => t.id)).toContain(t2.id) - }) - - it('activates the target tab', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().closeOtherTabs(t1.id) - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id) - }) - - it('returns empty when nothing to close', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const closed = store.getState().closeOtherTabs(t1.id) - expect(closed).toEqual([]) - }) - }) - - describe('closeTabsToRight', () => { - it('closes unpinned tabs to the right of target', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - const t4 = store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().pinTab(t3.id) - - const closed = store.getState().closeTabsToRight(t1.id) - - expect(closed).toEqual([t2.id, t4.id]) - const tabs = store.getState().unifiedTabsByWorktree[WT] - expect(tabs.map((t) => t.id)).toEqual([t1.id, t3.id]) - }) - - it('activates target if active tab was closed', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().closeTabsToRight(t1.id) - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id) - }) - }) - - describe('closeTabsToLeft', () => { - it('closes unpinned tabs to the left of target', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - const t4 = store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().pinTab(t2.id) - - const closed = store.getState().closeTabsToLeft(t4.id) - - expect(closed).toEqual([t1.id, t3.id]) - const tabs = store.getState().unifiedTabsByWorktree[WT] - expect(tabs.map((t) => t.id)).toEqual([t2.id, t4.id]) - }) - - it('returns empty when target is the leftmost tab', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'terminal') - - const closed = store.getState().closeTabsToLeft(t1.id) - - expect(closed).toEqual([]) - expect(store.getState().unifiedTabsByWorktree[WT]).toHaveLength(2) - }) - - it('activates target if active tab was closed', () => { - store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().activateTab(t2.id) - - store.getState().closeTabsToLeft(t3.id) - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t3.id) - }) - }) - - describe('getActiveTab / getTab', () => { - it('getActiveTab returns the active tab for a worktree', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'editor', { id: 'f.ts', label: 'f.ts' }) - - store.getState().activateTab(t1.id) - - expect(store.getState().getActiveTab(WT)?.id).toBe(t1.id) - }) - - it('getActiveTab returns null for worktree with no tabs', () => { - expect(store.getState().getActiveTab(WT)).toBeNull() - }) - - it('getTab finds a tab by id across worktrees', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal') - expect(store.getState().getTab(tab.id)?.id).toBe(tab.id) - }) - - it('getTab returns null for unknown id', () => { - expect(store.getState().getTab('unknown')).toBeNull() - }) - }) - - describe('cross-content-type neighbor selection', () => { - it('selects an editor tab as neighbor when closing a terminal tab', () => { - const term = store.getState().createUnifiedTab(WT, 'terminal') - const editor = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file.ts', - label: 'file.ts' - }) - - store.getState().activateTab(term.id) - store.getState().closeUnifiedTab(term.id) - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(editor.id) - }) - - it('selects a terminal tab as neighbor when closing an editor tab', async () => { - seedContentRecords(store, { terminalId: 'term-1', fileId: 'file.ts' }) - const term = store.getState().createUnifiedTab(WT, 'terminal', { id: 'term-1' }) - const editor = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file.ts', - label: 'file.ts' - }) - const main = await drawTabsFromMain(store) - - store.getState().closeUnifiedTab(editor.id) - await main.settle() - main.close() - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(term.id) - }) }) }) diff --git a/src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts b/src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts index 502bf1da1bb..1760bfe2f1a 100644 --- a/src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts +++ b/src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts @@ -24,55 +24,7 @@ describe('TabsSlice', () => { store = createTestStore() }) - describe('reorderUnifiedTabs', () => { - it('updates tabOrder on the group and sortOrder on tabs', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - const t2 = store.getState().createUnifiedTab(WT, 'terminal') - const t3 = store.getState().createUnifiedTab(WT, 'terminal') - - const groupId = store.getState().groupsByWorktree[WT][0].id - store.getState().reorderUnifiedTabs(groupId, [t3.id, t1.id, t2.id]) - - const group = store.getState().groupsByWorktree[WT][0] - expect(group.tabOrder).toEqual([t3.id, t1.id, t2.id]) - - const tabs = store.getState().unifiedTabsByWorktree[WT] - const sorted = [...tabs].sort((a, b) => a.sortOrder - b.sortOrder) - expect(sorted.map((t) => t.id)).toEqual([t3.id, t1.id, t2.id]) - }) - }) - describe('setTabGroupSplitRatio', () => { - it('updates the persisted ratio for the targeted split node', () => { - store.setState({ - layoutByWorktree: { - [WT]: { - type: 'split', - direction: 'horizontal', - ratio: 0.5, - first: { type: 'leaf', groupId: 'g-1' }, - second: { - type: 'split', - direction: 'vertical', - ratio: 0.5, - first: { type: 'leaf', groupId: 'g-2' }, - second: { type: 'leaf', groupId: 'g-3' } - } - } - } - }) - - store.getState().setTabGroupSplitRatio(WT, 'second', 0.7) - - const layout = store.getState().layoutByWorktree[WT] - expect(layout.type).toBe('split') - if (layout.type !== 'split' || layout.second.type !== 'split') { - throw new Error('expected nested split layout') - } - expect(layout.ratio).toBe(0.5) - expect(layout.second.ratio).toBe(0.7) - }) - it('keeps state identity when the ratio is unchanged', () => { store.setState({ layoutByWorktree: { @@ -106,87 +58,6 @@ describe('TabsSlice', () => { }) describe('move/copy/merge group operations', () => { - it('moves a unified tab into another group', () => { - const tab = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts' - }) - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right') - expect(targetGroupId).toBeTruthy() - - store.getState().moveUnifiedTabToGroup(tab.id, targetGroupId!) - - const state = store.getState() - const moved = state.unifiedTabsByWorktree[WT].find((item) => item.id === tab.id) - expect(moved?.groupId).toBe(targetGroupId) - expect(state.groupsByWorktree[WT].find((group) => group.id === sourceGroupId)).toBeUndefined() - expect( - state.groupsByWorktree[WT].find((group) => group.id === targetGroupId)?.tabOrder - ).toEqual([tab.id]) - }) - - it('drops a unified tab into another group and collapses an emptied source group', () => { - const tab = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts' - }) - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right') - expect(targetGroupId).toBeTruthy() - - const moved = store.getState().dropUnifiedTab(tab.id, { groupId: targetGroupId! }) - - expect(moved).toBe(true) - const state = store.getState() - expect(state.groupsByWorktree[WT]).toHaveLength(1) - expect(state.groupsByWorktree[WT][0].id).toBe(targetGroupId) - expect(state.groupsByWorktree[WT][0].tabOrder).toEqual([tab.id]) - expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: targetGroupId }) - expect(state.activeGroupIdByWorktree[WT]).toBe(targetGroupId) - }) - - it('drops a unified tab onto a pane edge to create a sibling split', () => { - const first = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts' - }) - const second = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-b.ts', - label: 'file-b.ts' - }) - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - - const moved = store.getState().dropUnifiedTab(second.id, { - groupId: sourceGroupId, - splitDirection: 'right' - }) - - expect(moved).toBe(true) - const state = store.getState() - expect(state.groupsByWorktree[WT]).toHaveLength(2) - - const originGroup = state.groupsByWorktree[WT].find((group) => group.id === sourceGroupId) - expect(originGroup?.tabOrder).toEqual([first.id]) - - const movedTab = state.unifiedTabsByWorktree[WT].find((tab) => tab.id === second.id) - const newGroupId = movedTab?.groupId - expect(newGroupId).toBeTruthy() - expect(newGroupId).not.toBe(sourceGroupId) - expect(state.groupsByWorktree[WT].find((group) => group.id === newGroupId)?.tabOrder).toEqual( - [second.id] - ) - - const layout = state.layoutByWorktree[WT] - expect(layout.type).toBe('split') - if (layout.type !== 'split') { - throw new Error('expected split layout after edge drop') - } - expect(layout.direction).toBe('horizontal') - expect(layout.first).toEqual({ type: 'leaf', groupId: sourceGroupId }) - expect(layout.second).toEqual({ type: 'leaf', groupId: newGroupId }) - }) - it('creates a unified tab directly in a sibling split without publishing a source-group midpoint', () => { const terminal = store.getState().createUnifiedTab(WT, 'terminal', { id: 'terminal-1', @@ -238,101 +109,5 @@ describe('TabsSlice', () => { expect(layout.first).toEqual({ type: 'leaf', groupId: sourceGroupId }) expect(layout.second).toEqual({ type: 'leaf', groupId: simulatorGroupId }) }) - - it('creates a split tab without stealing focus when activation is disabled', () => { - store.getState().createUnifiedTab(WT, 'terminal', { - id: 'terminal-1', - label: 'Terminal 1' - }) - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - store.setState({ activeWorktreeId: WT }) - - const simulator = store.getState().createUnifiedTabInSplit( - WT, - 'simulator', - { - sourceGroupId, - splitDirection: 'right' - }, - { - id: 'simulator-1', - label: 'Mobile Emulator', - activate: false - } - ) - - expect(simulator).not.toBeNull() - const state = store.getState() - expect(state.activeGroupIdByWorktree[WT]).toBe(sourceGroupId) - expect(state.activeTabType).toBe('terminal') - expect( - state.groupsByWorktree[WT].find((group) => group.id === simulator!.groupId)?.recentTabIds - ).toEqual([]) - }) - - it('treats splitting the only tab onto its own pane body as a no-op', () => { - const onlyTab = store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts' - }) - const sourceGroupId = store.getState().groupsByWorktree[WT][0].id - - const moved = store.getState().dropUnifiedTab(onlyTab.id, { - groupId: sourceGroupId, - splitDirection: 'down' - }) - - expect(moved).toBe(false) - const state = store.getState() - expect(state.groupsByWorktree[WT]).toHaveLength(1) - expect(state.groupsByWorktree[WT][0].tabOrder).toEqual([onlyTab.id]) - expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: sourceGroupId }) - }) - - it('treats splitting the only tab onto the adjacent sibling edge as a no-op', () => { - store.getState().createUnifiedTab(WT, 'editor', { - id: 'file-a.ts', - label: 'file-a.ts' - }) - const right = store.getState().createUnifiedTab(WT, 'terminal', { - id: 'terminal-1', - label: 'Terminal 1' - }) - const leftGroupId = store.getState().groupsByWorktree[WT][0].id - - expect( - store.getState().dropUnifiedTab(right.id, { - groupId: leftGroupId, - splitDirection: 'right' - }) - ).toBe(true) - - const rightGroupId = store - .getState() - .unifiedTabsByWorktree[WT].find((tab) => tab.id === right.id)?.groupId - expect(rightGroupId).toBeTruthy() - - const moved = store.getState().dropUnifiedTab(right.id, { - groupId: leftGroupId, - splitDirection: 'right' - }) - - expect(moved).toBe(false) - expect( - store.getState().unifiedTabsByWorktree[WT].find((tab) => tab.id === right.id)?.groupId - ).toBe(rightGroupId) - }) - }) - - describe('tabOrder dedupe', () => { - it('deduplicates drag reorder payloads before persisting group order', () => { - const first = store.getState().createUnifiedTab(WT, 'terminal') - const second = store.getState().createUnifiedTab(WT, 'terminal') - - const groupId = store.getState().groupsByWorktree[WT][0].id - store.getState().reorderUnifiedTabs(groupId, [second.id, first.id, second.id, first.id]) - - expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([second.id, first.id]) - }) }) }) diff --git a/src/renderer/src/store/slices/tabs-session-hydration.test.ts b/src/renderer/src/store/slices/tabs-session-hydration.test.ts deleted file mode 100644 index dd2b5e355f0..00000000000 --- a/src/renderer/src/store/slices/tabs-session-hydration.test.ts +++ /dev/null @@ -1,400 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type { Tab, TabGroup } from '../../../../shared/tab-types' -import type * as AgentStatusModule from '@/lib/agent-status' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' -import { createTabsSliceMockApi } from './tabs-slice-test-harness' -import { createTestStore, makeTabGroup, makeUnifiedTab, makeWorktree } from './store-test-helpers' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -vi.mock('@/lib/agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -createTabsSliceMockApi() - -const WT = 'repo1::/tmp/feature' - -describe('TabsSlice', () => { - let store: ReturnType - - beforeEach(() => { - store = createTestStore() - }) - - describe('hydrateTabsSession', () => { - it('hydrates floating workspace unified tabs without a repo worktree', () => { - store.getState().hydrateTabsSession({ - activeRepoId: null, - activeWorktreeId: FLOATING_TERMINAL_WORKTREE_ID, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: { - [FLOATING_TERMINAL_WORKTREE_ID]: [ - { - id: 'floating-browser-1', - entityId: 'floating-browser-1', - groupId: 'floating-group-1', - worktreeId: FLOATING_TERMINAL_WORKTREE_ID, - contentType: 'browser', - label: 'Browser', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - tabGroups: { - [FLOATING_TERMINAL_WORKTREE_ID]: [ - { - id: 'floating-group-1', - worktreeId: FLOATING_TERMINAL_WORKTREE_ID, - activeTabId: 'floating-browser-1', - tabOrder: ['floating-browser-1'] - } - ] - } - }) - - expect(store.getState().unifiedTabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toHaveLength(1) - }) - - it('hydrates from unified format', () => { - store.setState({ - worktreesByRepo: { - repo1: [ - { - id: WT, - repoId: 'repo1', - path: '/tmp/feature', - head: 'abc', - branch: 'feature', - isBare: false, - isMainWorktree: false, - displayName: 'feature', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - linkedGitLabMR: null, - linkedGitLabIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 - } - ] - } - }) - - const groupId = 'g-1' - const tabs: Tab[] = [ - { - id: 't-1', - entityId: 't-1', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'zsh', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1000 - }, - { - id: '/file.ts', - entityId: '/file.ts', - groupId, - worktreeId: WT, - contentType: 'editor', - label: 'file.ts', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2000 - } - ] - const groups: TabGroup[] = [ - { id: groupId, worktreeId: WT, activeTabId: '/file.ts', tabOrder: ['t-1', '/file.ts'] } - ] - - store.getState().hydrateTabsSession({ - activeRepoId: 'repo1', - activeWorktreeId: WT, - activeTabId: 't-1', - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: { [WT]: tabs }, - tabGroups: { [WT]: groups } - }) - - const state = store.getState() - expect(state.unifiedTabsByWorktree[WT]).toHaveLength(2) - expect(state.groupsByWorktree[WT][0].activeTabId).toBe('/file.ts') - }) - - it('deduplicates persisted tab order during unified hydration', () => { - store.setState({ - worktreesByRepo: { - repo1: [ - { - id: WT, - repoId: 'repo1', - path: '/tmp/feature', - head: 'abc', - branch: 'feature', - isBare: false, - isMainWorktree: false, - displayName: 'feature', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - linkedGitLabMR: null, - linkedGitLabIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 - } - ] - } - }) - - const groupId = 'g-1' - const tabs: Tab[] = [ - { - id: 't-1', - entityId: 't-1', - groupId, - worktreeId: WT, - contentType: 'terminal', - label: 'zsh', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1000 - }, - { - id: '/file.ts', - entityId: '/file.ts', - groupId, - worktreeId: WT, - contentType: 'editor', - label: 'file.ts', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2000 - } - ] - const groups: TabGroup[] = [ - { - id: groupId, - worktreeId: WT, - activeTabId: '/file.ts', - tabOrder: ['t-1', 't-1', '/file.ts', '/file.ts'] - } - ] - - store.getState().hydrateTabsSession({ - activeRepoId: 'repo1', - activeWorktreeId: WT, - activeTabId: 't-1', - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: { [WT]: tabs }, - tabGroups: { [WT]: groups } - }) - - expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual(['t-1', '/file.ts']) - }) - - it('filters out invalid worktree IDs during hydration', () => { - store.setState({ worktreesByRepo: {} }) - - store.getState().hydrateTabsSession({ - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: { - 'nonexistent-wt': [ - { - id: 't-1', - ptyId: null, - worktreeId: 'nonexistent-wt', - title: 'zsh', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1000 - } - ] - }, - terminalLayoutsByTabId: {} - }) - - expect(store.getState().unifiedTabsByWorktree).toEqual({}) - }) - - it('replaces only explicitly scoped worktree tab chrome', () => { - const siblingWorktreeId = 'repo2::/tmp/sibling' - const targetGroup = makeTabGroup({ - id: 'group-target', - worktreeId: WT, - activeTabId: 'target-old', - tabOrder: ['target-old'] - }) - const siblingGroup = makeTabGroup({ - id: 'group-sibling', - worktreeId: siblingWorktreeId, - activeTabId: 'sibling-tab', - tabOrder: ['sibling-tab'] - }) - const siblingTabs = [ - makeUnifiedTab({ - id: 'sibling-tab', - worktreeId: siblingWorktreeId, - groupId: siblingGroup.id - }) - ] - const siblingGroups = [siblingGroup] - store.setState({ - worktreesByRepo: { - repo1: [makeWorktree({ id: WT, repoId: 'repo1' })], - repo2: [makeWorktree({ id: siblingWorktreeId, repoId: 'repo2' })] - }, - unifiedTabsByWorktree: { - [WT]: [makeUnifiedTab({ id: 'target-old', worktreeId: WT, groupId: targetGroup.id })], - [siblingWorktreeId]: siblingTabs - }, - groupsByWorktree: { - [WT]: [targetGroup], - [siblingWorktreeId]: siblingGroups - }, - activeGroupIdByWorktree: { - [WT]: targetGroup.id, - [siblingWorktreeId]: siblingGroup.id - }, - layoutByWorktree: { - [WT]: { type: 'leaf', groupId: targetGroup.id }, - [siblingWorktreeId]: { type: 'leaf', groupId: siblingGroup.id } - } - }) - const targetNew = makeUnifiedTab({ - id: 'target-new', - worktreeId: WT, - groupId: targetGroup.id, - label: 'Remote target' - }) - - store.getState().hydrateTabsSession( - { - activeRepoId: 'repo1', - activeWorktreeId: WT, - activeTabId: targetNew.id, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: { - [WT]: [targetNew], - [siblingWorktreeId]: [ - makeUnifiedTab({ - id: 'sibling-replaced', - worktreeId: siblingWorktreeId, - groupId: siblingGroup.id - }) - ] - }, - tabGroups: { - [WT]: [{ ...targetGroup, activeTabId: targetNew.id, tabOrder: [targetNew.id] }], - [siblingWorktreeId]: [ - { ...siblingGroup, activeTabId: 'sibling-replaced', tabOrder: ['sibling-replaced'] } - ] - } - }, - { replaceWorkspaceKeys: [WT] } - ) - - expect(store.getState().unifiedTabsByWorktree[WT]).toEqual([targetNew]) - expect(store.getState().unifiedTabsByWorktree[siblingWorktreeId]).toBe(siblingTabs) - expect(store.getState().groupsByWorktree[siblingWorktreeId]).toBe(siblingGroups) - }) - - it('deletes omitted target chrome while preserving sibling references', () => { - const siblingWorktreeId = 'repo2::/tmp/sibling' - const targetGroup = makeTabGroup({ - id: 'group-target', - worktreeId: WT, - activeTabId: 'target-tab', - tabOrder: ['target-tab'] - }) - const siblingGroup = makeTabGroup({ - id: 'group-sibling', - worktreeId: siblingWorktreeId, - activeTabId: 'sibling-tab', - tabOrder: ['sibling-tab'] - }) - const siblingTabs = [ - makeUnifiedTab({ - id: 'sibling-tab', - worktreeId: siblingWorktreeId, - groupId: siblingGroup.id - }) - ] - const siblingGroups = [siblingGroup] - const siblingLayout = { type: 'leaf' as const, groupId: siblingGroup.id } - store.setState({ - worktreesByRepo: { - repo1: [makeWorktree({ id: WT, repoId: 'repo1' })], - repo2: [makeWorktree({ id: siblingWorktreeId, repoId: 'repo2' })] - }, - unifiedTabsByWorktree: { - [WT]: [makeUnifiedTab({ id: 'target-tab', worktreeId: WT, groupId: targetGroup.id })], - [siblingWorktreeId]: siblingTabs - }, - groupsByWorktree: { - [WT]: [targetGroup], - [siblingWorktreeId]: siblingGroups - }, - activeGroupIdByWorktree: { - [WT]: targetGroup.id, - [siblingWorktreeId]: siblingGroup.id - }, - layoutByWorktree: { - [WT]: { type: 'leaf', groupId: targetGroup.id }, - [siblingWorktreeId]: siblingLayout - } - }) - - store.getState().hydrateTabsSession( - { - activeRepoId: 'repo1', - activeWorktreeId: WT, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: {}, - tabGroups: {} - }, - { replaceWorkspaceKeys: [WT] } - ) - - const state = store.getState() - expect(state.unifiedTabsByWorktree).not.toHaveProperty(WT) - expect(state.groupsByWorktree).not.toHaveProperty(WT) - expect(state.activeGroupIdByWorktree).not.toHaveProperty(WT) - expect(state.layoutByWorktree).not.toHaveProperty(WT) - expect(state.unifiedTabsByWorktree[siblingWorktreeId]).toBe(siblingTabs) - expect(state.groupsByWorktree[siblingWorktreeId]).toBe(siblingGroups) - expect(state.layoutByWorktree[siblingWorktreeId]).toBe(siblingLayout) - }) - }) -}) diff --git a/src/renderer/src/store/slices/tabs-split-create.test.ts b/src/renderer/src/store/slices/tabs-split-create.test.ts index 9ac9b28f637..383f50b59a2 100644 --- a/src/renderer/src/store/slices/tabs-split-create.test.ts +++ b/src/renderer/src/store/slices/tabs-split-create.test.ts @@ -153,16 +153,4 @@ describe('creating a tab directly into a new split', () => { ).toEqual(layoutProjection(chained.store.getState(), chained.sourceGroupId, chainedGroupId!)) } ) - - it('records the pane interaction the empty split used to record', () => { - const { store, sourceGroupId } = seededStore() - const recordFeatureInteraction = vi.fn() - store.setState({ recordFeatureInteraction }) - - store.getState().createTab(WT, undefined, undefined, { - split: { ...SPLIT, sourceGroupId } - }) - - expect(recordFeatureInteraction).toHaveBeenCalledWith('terminal-panes') - }) }) diff --git a/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts b/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts index 87a62069491..58a76a8ec4d 100644 --- a/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts +++ b/src/renderer/src/store/slices/tabs-unread-and-focus.test.ts @@ -40,15 +40,6 @@ describe('TabsSlice', () => { }) describe('activateTab', () => { - it('sets the active tab on the group', () => { - const t1 = store.getState().createUnifiedTab(WT, 'terminal') - store.getState().createUnifiedTab(WT, 'terminal') - - store.getState().activateTab(t1.id) - - expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id) - }) - it('promotes a preview tab to permanent on activation', async () => { store.setState({ openFiles: [makeOpenFile({ id: 'f.ts', worktreeId: WT, isPreview: true })] }) const preview = store.getState().createUnifiedTab(WT, 'editor', { @@ -106,244 +97,6 @@ describe('TabsSlice', () => { }) }) - // Ghostty "show until interact": BEL always marks unread (even focused/visible tabs); the on-screen read dismisses it. - describe('lastFocusedAt', () => { - it('stamps a newly created tab that activates', () => { - const before = Date.now() - const tab = store.getState().createUnifiedTab(WT, 'terminal') - - const stored = store.getState().unifiedTabsByWorktree[WT].find((t) => t.id === tab.id) - expect(stored?.lastFocusedAt).toBeGreaterThanOrEqual(before) - }) - - it('leaves a background-created tab unstamped', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal', { activate: false }) - - const stored = store.getState().unifiedTabsByWorktree[WT].find((t) => t.id === tab.id) - expect(stored?.lastFocusedAt).toBeUndefined() - }) - - it('stamps a tab created into a new split group', () => { - const source = store.getState().createUnifiedTab(WT, 'terminal') - const before = Date.now() - const split = store.getState().createUnifiedTabInSplit(WT, 'terminal', { - sourceGroupId: source.groupId, - splitDirection: 'right' - }) - - const stored = store.getState().unifiedTabsByWorktree[WT].find((t) => t.id === split?.id) - expect(stored?.lastFocusedAt).toBeGreaterThanOrEqual(before) - }) - }) - - describe('markTerminalBell tab marker', () => { - it('marks the tab even when it is active in a visible split group of the active worktree', () => { - const tabA = store.getState().createUnifiedTab(WT, 'terminal') - const groupAId = store.getState().groupsByWorktree[WT][0].id - - // Split/focus group B so group A’s tab is visible but unfocused. - const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right') - if (!groupBId) { - throw new Error('createEmptySplitGroup returned null') - } - store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId }) - store.getState().focusGroup(WT, groupBId) - store.setState({ activeWorktreeId: WT }) - - // Seed the backing legacy terminal tab so the owner-missing guard doesn't short-circuit. - store.setState({ - tabsByWorktree: { - [WT]: [ - { - id: tabA.entityId, - ptyId: null, - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - }) - - // Visible unfocused tabs still get BEL markers; only pane input dismisses them. - store - .getState() - .markTerminalBell({ worktreeId: WT, tabId: tabA.entityId, paneKey: `${tabA.entityId}:0` }) - - expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBe('terminal-bell') - }) - - it('does mark a tab that is not the active tab of any visible group', () => { - const tabA1 = store.getState().createUnifiedTab(WT, 'terminal') - const tabA2 = store.getState().createUnifiedTab(WT, 'terminal') - const groupAId = store.getState().groupsByWorktree[WT][0].id - store.getState().activateTab(tabA1.id) - - // Create/focus group B to exercise bells with two visible groups. - const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right') - if (!groupBId) { - throw new Error('createEmptySplitGroup returned null') - } - store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId }) - store.getState().focusGroup(WT, groupBId) - store.setState({ activeWorktreeId: WT }) - // Bell marking requires backing legacy terminal rows, as every production terminal has. - store.setState({ - tabsByWorktree: { - [WT]: [ - { - id: tabA2.entityId, - ptyId: null, - worktreeId: WT, - title: 'Terminal 2', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - }) - - store - .getState() - .markTerminalBell({ worktreeId: WT, tabId: tabA2.entityId, paneKey: `${tabA2.entityId}:0` }) - - expect(store.getState().unreadTerminalTabs[tabA2.entityId]).toBe('terminal-bell') - }) - - // Why: under show-until-interact, BEL fires unconditionally even on a non-terminal/offscreen surface — a legitimate unread. - it('still marks the tab when the active surface is not terminal', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal') - // Point active* at this tab but mark a different worktree active (skips the visible-groups check); only activeTabType='editor' remains as a guard. - // Why: seed tabsByWorktree — the tab marker guards against a missing owner tab. - store.setState({ - activeWorktreeId: 'other-wt::/path/x', - activeTabId: tab.entityId, - activeTabType: 'editor', - tabsByWorktree: { - [WT]: [ - { - id: tab.entityId, - ptyId: null, - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - }) - - store - .getState() - .markTerminalBell({ worktreeId: WT, tabId: tab.entityId, paneKey: `${tab.entityId}:0` }) - - expect(store.getState().unreadTerminalTabs[tab.entityId]).toBe('terminal-bell') - }) - - it('is a no-op when the tab is already flagged', () => { - const tab = store.getState().createUnifiedTab(WT, 'terminal') - // Why: seed tabsByWorktree so the owner-missing guard doesn't short-circuit before we reach the "already flagged" branch. - store.setState({ - unreadTerminalTabs: { [tab.entityId]: true as const }, - activeTabId: 'something-else', - activeTabType: 'terminal', - activeWorktreeId: 'other-wt', - tabsByWorktree: { - [WT]: [ - { - id: tab.entityId, - ptyId: null, - worktreeId: WT, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - }) - const before = store.getState().unreadTerminalTabs - - store - .getState() - .markTerminalBell({ worktreeId: WT, tabId: tab.entityId, paneKey: `${tab.entityId}:0` }) - - // Same object reference => no state mutation occurred. - expect(store.getState().unreadTerminalTabs).toBe(before) - }) - - // Why: the bell's tab marker is agent-agnostic — blocking the working→idle dot here would swallow the agent's completion signal. - it('marks unread for an agent tab when it is not focused', () => { - const agentTabId = 'agent-tab-1' - store.setState({ - activeTabId: 'something-else', - activeTabType: 'terminal', - activeWorktreeId: 'other-wt', - tabsByWorktree: { - [WT]: [ - { - id: agentTabId, - ptyId: null, - worktreeId: WT, - title: '* Claude done', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - }) - - store - .getState() - .markTerminalBell({ worktreeId: WT, tabId: agentTabId, paneKey: `${agentTabId}:0` }) - - expect(store.getState().unreadTerminalTabs[agentTabId]).toBe('terminal-bell') - }) - }) - - // The on-screen scan's read of a visible tab. - describe('readOnScreenAttention tab marker', () => { - it('removes the tab from unreadTerminalTabs', () => { - const tabId = 'bell-tab-1' - store.setState({ - unreadTerminalTabs: { [tabId]: true as const, 'other-tab': true as const } - }) - - store - .getState() - .readOnScreenAttention( - { workspaceIds: [WT], targets: [{ worktreeId: WT, tabId }] }, - { screenArrived: false } - ) - - expect(store.getState().unreadTerminalTabs).toEqual({ 'other-tab': true }) - }) - - it('is a reference-preserving no-op when the tab is not flagged', () => { - const initial = { 'other-tab': true as const } - store.setState({ unreadTerminalTabs: initial }) - - store - .getState() - .readOnScreenAttention( - { workspaceIds: [WT], targets: [{ worktreeId: WT, tabId: 'bell-tab-1' }] }, - { screenArrived: false } - ) - - expect(store.getState().unreadTerminalTabs).toBe(initial) - }) - }) - // Already-active group clicks skip activateTab; focusGroup must still expose its tab to the attention scan. describe('focusGroup', () => { it('does not broadcast active-surface writes when the focused group is already current', () => { @@ -419,23 +172,5 @@ describe('TabsSlice', () => { surfaceKind: 'terminal' }) }) - - it('puts the active tab of every side-by-side group on screen', () => { - const tabA = store.getState().createUnifiedTab(WT, 'terminal') - const groupAId = store.getState().groupsByWorktree[WT][0].id - const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right') - if (!groupBId) { - throw new Error('createEmptySplitGroup returned null') - } - const tabB = store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId }) - store.setState({ activeWorktreeId: WT, activeView: 'terminal' }) - - store.getState().focusGroup(WT, groupAId) - - expect(resolveAutoAckTabTargets(store.getState())).toEqual([ - { tabId: tabA.entityId, worktreeId: WT, surfaceKind: 'terminal' }, - { tabId: tabB.entityId, worktreeId: WT, surfaceKind: 'terminal' } - ]) - }) }) }) diff --git a/src/renderer/src/store/slices/tabs/layout-owner-shared-path-gates.test.ts b/src/renderer/src/store/slices/tabs/layout-owner-shared-path-gates.test.ts deleted file mode 100644 index b1299a2d92d..00000000000 --- a/src/renderer/src/store/slices/tabs/layout-owner-shared-path-gates.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { createTabsSliceMockApi } from '../tabs-slice-test-harness' -import { createTestStore, makeTab } from '../store-test-helpers' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -createTabsSliceMockApi() - -const WT = 'repo1::/tmp/feature' - -// Main draws the tab bar from its frames; these shared paths must not write structure of their own. -describe('shared tab paths in a layout-owner build', () => { - let store: ReturnType - - beforeEach(() => { - store = createTestStore() - }) - - it('reconcile counts what would render and leaves the tab bar to main', () => { - const entry = { - id: 'stale-terminal', - entityId: 'stale-terminal', - groupId: 'g-1', - worktreeId: WT, - contentType: 'terminal' as const, - label: 'Terminal 1', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - store.setState({ - unifiedTabsByWorktree: { [WT]: [entry] }, - groupsByWorktree: { - [WT]: [{ id: 'g-1', worktreeId: WT, activeTabId: entry.id, tabOrder: [entry.id] }] - }, - activeGroupIdByWorktree: { [WT]: 'g-1' }, - tabsByWorktree: { [WT]: [] } - }) - const before = store.getState() - - expect(store.getState().reconcileWorktreeTabModel(WT)).toEqual({ - renderableTabCount: 0, - activeRenderableTabId: null - }) - store.getState().reconcileWorktreeTabModels([WT]) - - expect(store.getState().unifiedTabsByWorktree).toBe(before.unifiedTabsByWorktree) - expect(store.getState().groupsByWorktree).toBe(before.groupsByWorktree) - }) - - // A row's ptyId is the window's own field (the frame merge keeps it), so reconnect sets only that. - it('reconnect advertises restored terminals and changes only each row ptyId', async () => { - const rows = { [WT]: [makeTab({ id: 'tab-1', worktreeId: WT, ptyId: null })] } - store.setState({ - tabsByWorktree: rows, - terminalLayoutsByTabId: {}, - pendingReconnectWorktreeIds: [WT], - pendingReconnectTabByWorktree: { [WT]: ['tab-1'] }, - pendingReconnectPtyIdByTabId: { 'tab-1': 'pty-1' } - }) - - await store.getState().reconnectPersistedTerminals() - - expect(store.getState().ptyIdsByTabId['tab-1']).toEqual(['pty-1']) - expect(store.getState().tabsByWorktree).toEqual({ - [WT]: [{ ...rows[WT][0], ptyId: 'pty-1' }] - }) - expect(store.getState().workspaceSessionReady).toBe(true) - }) -}) diff --git a/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts b/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts index 33a7228fb21..0816a87a3e5 100644 --- a/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts +++ b/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts @@ -79,21 +79,6 @@ afterEach(() => { }) describe('closing a structured chat from outside its workspace', () => { - it('stops it on the host stamped on its tab, not on whichever host shares its id', () => { - const store = storeWith(chatTab('runtime:server-1')) - - const layoutOwner = store.getState() - store.getState().closeUnifiedTab('agent-session:chat-1') - - expect(mocks.beginClose).toHaveBeenCalledWith( - expect.objectContaining({ - target: { kind: 'environment', environmentId: 'server-1' }, - sessionId: 'chat-1', - layoutOwner - }) - ) - }) - // Switch on, main's layout holds only chats this machine's host placed, so the stamp is a fact. it('an unstamped chat whose workspace two hosts publish: no host off, main’s host on', async () => { const store = storeWith(chatTab()) diff --git a/src/renderer/src/store/slices/tabs/tab-selection-contract.test.ts b/src/renderer/src/store/slices/tabs/tab-selection-contract.test.ts deleted file mode 100644 index 68781fa5738..00000000000 --- a/src/renderer/src/store/slices/tabs/tab-selection-contract.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Tab, TabContentType } from '../../../../../shared/tab-types' -import { buildHydratedTabState } from '../tabs-hydration' -import { resolveActivatedWorktreeSurface } from '../worktrees/session/active-worktree-surface' -import { deriveActiveSurfaceForWorktree } from './tabs-surface' - -type SelectionState = Parameters[0] - -const workspace = 'repo::/workspace' -function selectedTab(contentType: TabContentType): Tab { - return { - id: 'selected', - entityId: 'selected-entity', - groupId: 'group', - worktreeId: workspace, - contentType, - label: 'Selected', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } -} - -function selectionState(tab: Tab | null): SelectionState { - return { - rightSidebarExplorerViewByWorktree: {}, - activeGroupIdByWorktree: { [workspace]: 'group' }, - groupsByWorktree: { - [workspace]: [ - { - id: 'group', - worktreeId: workspace, - activeTabId: tab?.id ?? null, - tabOrder: tab ? [tab.id] : [] - } - ] - }, - unifiedTabsByWorktree: { [workspace]: tab ? [tab] : [] }, - layoutByWorktree: {}, - activeTabIdByWorktree: { [workspace]: 'remembered-terminal' }, - activeFileIdByWorktree: { [workspace]: 'remembered-file' }, - activeBrowserTabIdByWorktree: { [workspace]: 'remembered-browser' }, - activeTabTypeByWorktree: { [workspace]: 'browser' }, - tabsByWorktree: { - [workspace]: [ - { - id: 'remembered-terminal', - worktreeId: workspace, - ptyId: null, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - browserTabsByWorktree: { - [workspace]: [ - { - id: 'remembered-browser', - worktreeId: workspace, - url: 'about:blank', - title: 'Browser', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } - ] - }, - openFiles: [ - { - id: 'remembered-file', - worktreeId: workspace, - filePath: '/workspace/file', - relativePath: 'file', - language: 'plaintext', - isDirty: false, - mode: 'edit' - } - ] - } -} - -function activate(state: SelectionState) { - const { restoredRightSidebarExplorerView: _view, ...surface } = resolveActivatedWorktreeSurface( - state, - workspace, - undefined, - null - ) - return surface -} - -describe('tab selection and hydration ownership', () => { - it.each([ - ['terminal', 'terminal'], - ['editor', 'editor'], - ['diff', 'editor'], - ['conflict-review', 'editor'], - ['check-details', 'editor'], - ['browser', 'browser'], - ['simulator', 'simulator'], - ['agent-session', 'agent-session'] - ] as const)( - 'projects %s selection while retaining other remembered surfaces', - (kind, visible) => { - const state = selectionState(selectedTab(kind)) - const expected = { - activeTabType: visible, - activeTabId: kind === 'terminal' ? 'selected-entity' : 'remembered-terminal', - activeFileId: visible === 'editor' ? 'selected-entity' : 'remembered-file', - activeBrowserTabId: kind === 'browser' ? 'selected-entity' : 'remembered-browser' - } - expect(deriveActiveSurfaceForWorktree(state, workspace)).toEqual(expected) - expect(activate(state)).toEqual(expected) - } - ) - - it('keeps empty groups authoritative over remembered browser/editor surfaces', () => { - const state = selectionState(null) - expect(activate(state).activeTabType).toBe('terminal') - expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('terminal') - }) - - it('keeps layout-only ownership authoritative during staged hydration', () => { - const state = selectionState(null) - state.groupsByWorktree = {} - state.layoutByWorktree = { [workspace]: { type: 'leaf', groupId: 'pending' } } - expect(activate(state).activeTabType).toBe('terminal') - expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('terminal') - }) - - it('distinguishes workspace restoration from group-focus legacy fallback', () => { - const state = selectionState(null) - state.groupsByWorktree = {} - state.activeTabTypeByWorktree[workspace] = 'terminal' - expect(activate(state).activeTabType).toBe('terminal') - expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('browser') - }) - - it('does not select a preferred tab owned by another group', () => { - const state = selectionState(selectedTab('browser')) - state.unifiedTabsByWorktree[workspace].push({ - ...selectedTab('editor'), - id: 'foreign', - groupId: 'other' - }) - expect(resolveActivatedWorktreeSurface(state, workspace, 'foreign', null).activeTabType).toBe( - 'terminal' - ) - }) - - it('resolves stale active-group IDs to the first group consistently', () => { - const state = selectionState(selectedTab('simulator')) - state.activeGroupIdByWorktree[workspace] = 'removed' - expect(activate(state).activeTabType).toBe('simulator') - expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('simulator') - }) - - it('requires group ownership even for an explicit preferred tab during hydration', () => { - const state = selectionState(selectedTab('simulator')) - state.groupsByWorktree = {} - state.activeTabTypeByWorktree[workspace] = 'terminal' - expect(resolveActivatedWorktreeSurface(state, workspace, 'selected', null).activeTabType).toBe( - 'terminal' - ) - }) - - it('honors a preferred tab in the selected group without mutating selection', () => { - const state = selectionState(selectedTab('browser')) - const preferred = { ...selectedTab('simulator'), id: 'preferred' } - state.unifiedTabsByWorktree[workspace].push(preferred) - state.groupsByWorktree[workspace][0].tabOrder.push(preferred.id) - expect( - resolveActivatedWorktreeSurface(state, workspace, preferred.id, null).activeTabType - ).toBe('simulator') - expect(state.groupsByWorktree[workspace][0].activeTabId).toBe('selected') - }) - - it.each([ - ['terminal', 'terminal', 'remembered-file'], - ['editor', 'editor', 'remembered-file'], - ['browser', 'browser', 'remembered-file'], - // Closed chats/simulators cannot render from remembered type; fall back to browser and clear the remembered file. - ['agent-session', 'browser', null], - ['simulator', 'browser', null] - ] as const)( - 'projects legacy %s memory as %s when unified groups are absent', - (activeTabType, visible, activeFileId) => { - const state = selectionState(null) - state.groupsByWorktree = {} - state.activeTabTypeByWorktree[workspace] = activeTabType - expect(activate(state)).toEqual({ - activeTabType: visible, - activeTabId: 'remembered-terminal', - activeFileId, - activeBrowserTabId: 'remembered-browser' - }) - } - ) - - it('hydrates unified selection without allowing conflicting legacy memories to choose it', () => { - const tab = selectedTab('simulator') - const state = selectionState(tab) - const session = { - activeRepoId: null, - activeWorktreeId: workspace, - activeTabId: 'remembered-terminal', - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: state.unifiedTabsByWorktree, - tabGroups: state.groupsByWorktree, - activeGroupIdByWorktree: state.activeGroupIdByWorktree, - activeTabTypeByWorktree: { [workspace]: 'browser' as const }, - activeTabIdByWorktree: state.activeTabIdByWorktree - } - const before = structuredClone(session) - const hydrated = buildHydratedTabState(session, new Set([workspace])) - expect(activate({ ...state, ...hydrated }).activeTabType).toBe('simulator') - expect(session).toEqual(before) - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-layout-owner-groups-order.test.ts b/src/renderer/src/store/slices/tabs/tabs-layout-owner-groups-order.test.ts deleted file mode 100644 index 5fc71a2c379..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-layout-owner-groups-order.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { recordLayoutApply, sendLayoutApply } from '@/runtime/layout-apply-send' - -import type { Tab } from '../../../../../shared/tab-types' - -import { createTestStore } from '../store-test-helpers' -import { createTabsSliceMockApi } from '../tabs-slice-test-harness' - -const mocks = vi.hoisted(() => { - const held: { - send: ReturnType> - sendFirst: ReturnType> - store: unknown - } = { - send: vi.fn(), - sendFirst: vi.fn(() => true), - store: null - } - return held -}) - -vi.mock('../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('@/runtime/layout-apply-send', () => ({ - recordLayoutApply: mocks.send, - sendLayoutApply: mocks.sendFirst -})) -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/store', () => ({ - get useAppStore() { - return mocks.store - } -})) - -createTabsSliceMockApi() - -const WT = 'repo1::/path/wt1' -const GROUP = 'group-1' - -function tab(id: string, extra: Partial = {}): Tab { - return { - id, - entityId: id, - groupId: GROUP, - worktreeId: WT, - contentType: 'browser', - label: id, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1, - ...extra - } -} - -function seeded(tabs: Tab[]) { - const store = createTestStore() - store.setState({ - unifiedTabsByWorktree: { [WT]: tabs }, - groupsByWorktree: { - [WT]: [{ id: GROUP, worktreeId: WT, activeTabId: null, tabOrder: tabs.map((t) => t.id) }] - }, - activeGroupIdByWorktree: { [WT]: GROUP } - }) - mocks.store = store - return store -} - -const moves = () => - mocks.send.mock.calls.flatMap(([, worktreeId, command]) => - command.type === 'moveTab' ? [{ worktreeId, ...command }] : [] - ) - -beforeEach(() => { - mocks.send.mockReset() - mocks.sendFirst.mockClear() -}) - -describe('tab activation in a layout-owner build', () => { - it('asks main to end a preview, writing no preview flag itself', () => { - const store = seeded([tab('tab-a'), tab('tab-b', { isPreview: true })]) - - store.getState().activateTab('tab-a') - store.getState().activateTab('tab-b') - - const [a, b] = store.getState().unifiedTabsByWorktree[WT]! - expect(a).not.toHaveProperty('isPreview') - // Main's frame ends it (editor-tab-layout-owner.test.ts, "clears a promoted preview"). - expect(b?.isPreview).toBe(true) - expect( - mocks.sendFirst.mock.calls.map(([, worktreeId, command]) => [worktreeId, command]) - ).toEqual([[WT, { type: 'promotePreviewTab', tabId: 'tab-b' }]]) - }) -}) - -describe('tab order in a layout-owner build', () => { - it('records a reversed order as moves main replays to the same order', () => { - const store = seeded([tab('tab-a'), tab('tab-b'), tab('tab-c')]) - - store.getState().reorderUnifiedTabs(GROUP, ['tab-c', 'tab-b', 'tab-a']) - - let order = ['tab-a', 'tab-b', 'tab-c'] - for (const move of moves()) { - order = order.filter((id) => id !== move.tabId) - order.splice(move.index, 0, move.tabId) - // Each step's anchor is the tab its slot follows in the wanted order. - expect(move.afterTabId).toBe(order[move.index - 1] ?? null) - } - expect(order).toEqual(['tab-c', 'tab-b', 'tab-a']) - }) - - it('sends nothing for an order the caller already had main make', () => { - const store = seeded([tab('tab-a'), tab('tab-b')]) - - store.getState().reorderUnifiedTabs(GROUP, ['tab-b', 'tab-a'], { layoutOwnerHandled: true }) - - expect(moves()).toEqual([]) - expect(store.getState().groupsByWorktree[WT]![0]!.tabOrder).toEqual(['tab-b', 'tab-a']) - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts b/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts deleted file mode 100644 index 2d97865ec7c..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createWorktreeTabModelReconciliationBatch, - writeBatchedWorkspaceRecordEntry -} from './tabs-reconciliation-batch' -import { projectWorktreeTabModelReconciliation } from './tabs-reconciliation' -import { createTestStore } from '../store-test-helpers' - -const WORKTREE = 'repo::/tmp/app' - -describe('projectWorktreeTabModelReconciliation identity', () => { - it('keeps every tab-model map when only an orphan runtime terminal changed', () => { - const groupId = 'g-1' - const store = createTestStore() - store.setState({ - unifiedTabsByWorktree: { - [WORKTREE]: [ - { - id: 'sim-1', - entityId: 'sim-1', - groupId, - worktreeId: WORKTREE, - contentType: 'simulator', - label: 'Simulator', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - groupsByWorktree: { - [WORKTREE]: [ - { - id: groupId, - worktreeId: WORKTREE, - activeTabId: 'sim-1', - tabOrder: ['sim-1'] - } - ] - }, - activeGroupIdByWorktree: { [WORKTREE]: groupId }, - layoutByWorktree: { [WORKTREE]: { type: 'leaf', groupId } }, - // Orphan: a runtime terminal with no unified row and no live PTY. - tabsByWorktree: { - [WORKTREE]: [ - { - id: 'orphan', - ptyId: null, - worktreeId: WORKTREE, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { orphan: [] } - }) - const before = store.getState() - - const { patch } = projectWorktreeTabModelReconciliation(before, WORKTREE) - - expect(patch.tabsByWorktree?.[WORKTREE]).toEqual([]) - expect(patch.unifiedTabsByWorktree).toBe(before.unifiedTabsByWorktree) - expect(patch.groupsByWorktree).toBe(before.groupsByWorktree) - expect(patch.activeGroupIdByWorktree).toBe(before.activeGroupIdByWorktree) - expect(patch.layoutByWorktree).toBeUndefined() - }) -}) - -describe('writeBatchedWorkspaceRecordEntry identity', () => { - it('returns the same record when the entry already holds that value', () => { - const groups = [{ id: 'group-1' }] - const current = { [WORKTREE]: groups } - - const next = writeBatchedWorkspaceRecordEntry( - current, - 'groupsByWorktree', - WORKTREE, - groups, - undefined - ) - - // A new reference here rerenders every component selecting the map. - expect(next).toBe(current) - }) - - it('does not claim ownership of a map it never cloned', () => { - const groups = [{ id: 'group-1' }] - const current = { [WORKTREE]: groups } - const batch = createWorktreeTabModelReconciliationBatch({ openFiles: [] }) - - const unchanged = writeBatchedWorkspaceRecordEntry( - current, - 'groupsByWorktree', - WORKTREE, - groups, - batch - ) - expect(unchanged).toBe(current) - expect(batch.ownedStateKeys.has('groupsByWorktree')).toBe(false) - - // A later real change must therefore still copy rather than mutate the caller's map. - const changed = writeBatchedWorkspaceRecordEntry( - current, - 'groupsByWorktree', - WORKTREE, - [{ id: 'group-2' }], - batch - ) - expect(changed).not.toBe(current) - expect(current[WORKTREE]).toBe(groups) - expect(batch.ownedStateKeys.has('groupsByWorktree')).toBe(true) - }) - - it('copies when the value differs', () => { - const current = { [WORKTREE]: 'group-1' } - - const next = writeBatchedWorkspaceRecordEntry( - current, - 'activeGroupIdByWorktree', - WORKTREE, - 'group-2', - undefined - ) - - expect(next).not.toBe(current) - expect(next[WORKTREE]).toBe('group-2') - }) - - it('still stores an absent key, including an undefined value', () => { - const current: Record = { other: 'group-1' } - - const next = writeBatchedWorkspaceRecordEntry( - current, - 'activeGroupIdByWorktree', - WORKTREE, - undefined, - undefined - ) - - // The spread this replaces added the key; dropping it would change Object.keys. - expect(next).not.toBe(current) - expect(WORKTREE in next).toBe(true) - expect(next[WORKTREE]).toBeUndefined() - }) - - it('keeps mutating in place once the batch owns the map', () => { - const batch = createWorktreeTabModelReconciliationBatch({ openFiles: [] }) - batch.ownedStateKeys.add('groupsByWorktree') - const draft: Record = { [WORKTREE]: 'old' } - - const next = writeBatchedWorkspaceRecordEntry(draft, 'groupsByWorktree', WORKTREE, 'new', batch) - - expect(next).toBe(draft) - expect(draft[WORKTREE]).toBe('new') - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts b/src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts index 53256cb0ee5..c2e7a060219 100644 --- a/src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts +++ b/src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts @@ -44,13 +44,7 @@ function splitBesideSource(store: ReturnType, workspaceI return { store, sourceGroupId, emptyGroupId } } -function splitWorkspace(workspaceId: string, source: 'terminal' | 'agent-session' = 'terminal') { - const store = createTestStore() - seedSource(store, workspaceId, source) - return splitBesideSource(store, workspaceId) -} - -/** As splitWorkspace, with main holding the source tab and drawing the store from its frames. */ +/** Main holds the source tab and draws the store from its frames. */ async function drawnSplitWorkspace(workspaceId: string, source: 'terminal' | 'agent-session') { const store = createTestStore() seedSource(store, workspaceId, source) @@ -103,29 +97,4 @@ describe.each(['repo1::/tmp/feature', 'folder:folder-1'])('empty groups in %s', ).toMatchObject({ activeTabId: 'source', tabOrder: ['source'] }) } ) - - it('removes a group emptied by stale-tab cleanup while preserving an already empty group', () => { - const { store, sourceGroupId, emptyGroupId } = splitWorkspace(workspaceId) - const layoutWithEmptyNeighbor = store.getState().layoutByWorktree[workspaceId] - const staleGroupId = store.getState().createEmptySplitGroup(workspaceId, emptyGroupId, 'right') - if (!staleGroupId) { - throw new Error('Expected a stale split group') - } - store.getState().createUnifiedTab(workspaceId, 'browser', { - id: 'stale-browser', - entityId: 'missing-browser', - targetGroupId: staleGroupId - }) - - store.getState().reconcileWorktreeTabModel(workspaceId) - - const state = store.getState() - expect(state.groupsByWorktree[workspaceId].map((group) => group.id)).toEqual([ - sourceGroupId, - emptyGroupId - ]) - expect(state.layoutByWorktree[workspaceId]).toEqual(layoutWithEmptyNeighbor) - expect(state.activeGroupIdByWorktree[workspaceId]).toBe(sourceGroupId) - expect(state.unifiedTabsByWorktree[workspaceId].map((tab) => tab.id)).toEqual(['source']) - }) }) diff --git a/src/renderer/src/store/slices/tabs/tabs-root-group.test.ts b/src/renderer/src/store/slices/tabs/tabs-root-group.test.ts deleted file mode 100644 index 31d26881aef..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-root-group.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' -import { loadWorkspaceLayout } from '../../../../../shared/workspace-layout/workspace-layout-load' -import { nameBasedLoadContext } from '../../../../../shared/workspace-layout/workspace-layout-minted-ids' -import { - addWorkspace, - emptySession, - FOLDER_KEY, - GIT_KEY, - leaf -} from '../../../../../shared/workspace-layout/workspace-layout-session.test-fixture' -import { createTabsSliceMockApi } from '../tabs-slice-test-harness' -import { createTestStore } from '../store-test-helpers' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -createTabsSliceMockApi() - -describe('ensureWorktreeRootGroup', () => { - it.each([GIT_KEY, FOLDER_KEY])('mints the group main mints for %s', (workspaceKey) => { - const stored = addWorkspace(emptySession(), workspaceKey, [ - { id: 'g1', tabs: [{ id: 'tab-a', leaves: [[leaf(1), 'pty-a']] }] } - ]) - stored.unifiedTabs = {} - stored.tabGroups = {} - stored.tabGroupLayouts = {} - const loaded = loadWorkspaceLayout(LOCAL_EXECUTION_HOST_ID, stored, nameBasedLoadContext()) - - const groupId = createTestStore().getState().ensureWorktreeRootGroup(workspaceKey) - - expect(loaded.layout.workspaces[workspaceKey]?.groups.map((group) => group.id)).toEqual([ - groupId - ]) - }) -}) diff --git a/src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts b/src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts index 184eb077fef..a2c83f0f9bf 100644 --- a/src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts +++ b/src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts @@ -69,14 +69,6 @@ describe('recordTerminalInput store writes are coalesced', () => { expect(store.getState().lastTerminalInputAtByPaneKey[PANE]).toBe(1_200) }) - it('writes the very first stamp for a pane synchronously', () => { - const store = createTestStore() - - store.getState().recordTerminalInput(PANE, 1_000) - - expect(store.getState().lastTerminalInputAtByPaneKey[PANE]).toBe(1_000) - }) - it('does not resurrect a pane key a purge deleted', () => { const store = createTestStore() @@ -92,13 +84,4 @@ describe('recordTerminalInput store writes are coalesced', () => { expect(readLastTerminalInputAt(stored, PANE)).toBeUndefined() expect(mergePendingTerminalInputActivity(stored)[PANE]).toBeUndefined() }) - - it('ignores invalid pane keys and timestamps', () => { - const store = createTestStore() - - store.getState().recordTerminalInput('', 1_000) - store.getState().recordTerminalInput(PANE, Number.NaN) - - expect(store.getState().lastTerminalInputAtByPaneKey).toEqual({}) - }) }) diff --git a/src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts b/src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts index 41948d42a5d..b9c32c0c67d 100644 --- a/src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts +++ b/src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts @@ -1,11 +1,11 @@ import { beforeEach, describe, expect, it } from 'vitest' import { makePaneKey } from '../../../../shared/stable-pane-id' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import '../../../../shared/constants' import { resetAgentPaneAuthorityAliasesForTests, resolveAgentPaneAuthorityKey } from './agent-pane-authority' -import { createTestStore, makeTab, makeWorktree, seedStore } from './store-test-helpers' +import { createTestStore } from './store-test-helpers' const LEAF_1 = '11111111-1111-4111-8111-111111111111' const LEAF_2 = '22222222-2222-4222-8222-222222222222' @@ -15,54 +15,6 @@ describe('setTabLayout PTY ownership', () => { resetAgentPaneAuthorityAliasesForTests() }) - it('normalizes duplicate PTY surfaces at the renderer state boundary', () => { - const store = createTestStore() - - store.getState().setTabLayout('tab-1', { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_2 } - }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-agent', - [LEAF_2]: 'pty-agent' - } - }) - - expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({ - root: { type: 'leaf', leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'pty-agent' } - }) - }) - - it('preserves valid live layouts and legacy leaf ids by identity', () => { - const store = createTestStore() - const layout = { - root: { - type: 'split' as const, - direction: 'horizontal' as const, - first: { type: 'leaf' as const, leafId: 'pane:1' }, - second: { type: 'leaf' as const, leafId: 'pane:2' } - }, - activeLeafId: 'pane:2', - expandedLeafId: 'pane:1', - ptyIdsByLeafId: { - 'pane:1': 'pty-local', - 'pane:2': 'remote:env-1@@term_remote' - } - } - - store.getState().setTabLayout('tab-1', layout) - - expect(store.getState().terminalLayoutsByTabId['tab-1']).toBe(layout) - }) - it('moves live and future pane authority onto the retained PTY leaf', () => { const store = createTestStore() const removedPaneKey = makePaneKey('tab-1', LEAF_1) @@ -100,53 +52,6 @@ describe('setTabLayout PTY ownership', () => { expect(store.getState().agentStatusByPaneKey[retainedPaneKey]?.prompt).toBe('after repair') }) - it('moves hydrated pane authority onto the retained PTY leaf', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - const removedPaneKey = makePaneKey('tab-1', LEAF_1) - const retainedPaneKey = makePaneKey('tab-1', LEAF_2) - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - store.getState().setAgentStatus(removedPaneKey, { - state: 'working', - prompt: 'before hydration', - agentType: 'codex' - }) - - store.getState().hydrateWorkspaceSession({ - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: 'tab-1', - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'pty-agent' })] - }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_2 } - }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-agent', - [LEAF_2]: 'pty-agent' - } - } - } - }) - - expect(store.getState().agentStatusByPaneKey[removedPaneKey]).toBeUndefined() - expect(store.getState().agentStatusByPaneKey[retainedPaneKey]?.prompt).toBe('before hydration') - expect(resolveAgentPaneAuthorityKey(removedPaneKey)).toBe(retainedPaneKey) - }) - it('does not steal authority from a pane that was already detached to another tab', () => { const store = createTestStore() const removedPaneKey = makePaneKey('source-tab', LEAF_1) @@ -183,53 +88,4 @@ describe('setTabLayout PTY ownership', () => { expect(resolveAgentPaneAuthorityKey(detachedPaneKey)).toBe(detachedPaneKey) expect(resolveAgentPaneAuthorityKey(retainedPaneKey)).toBe(retainedPaneKey) }) - - it('repairs duplicate legacy leaf ownership without throwing', () => { - const store = createTestStore() - - expect(() => - store.getState().setTabLayout('tab-1', { - root: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: 'pane:1' }, - second: { type: 'leaf', leafId: 'pane:2' } - }, - activeLeafId: 'pane:2', - expandedLeafId: null, - ptyIdsByLeafId: { - 'pane:1': 'pty-agent', - 'pane:2': 'pty-agent' - } - }) - ).not.toThrow() - expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({ - root: { type: 'leaf', leafId: 'pane:2' }, - activeLeafId: 'pane:2', - expandedLeafId: null, - ptyIdsByLeafId: { 'pane:2': 'pty-agent' } - }) - }) - - it('scopes ownership to a tab so detach handoffs can share a PTY across tabs', () => { - const store = createTestStore() - const sourceLayout = { - root: { type: 'leaf' as const, leafId: LEAF_1 }, - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_1]: 'pty-detached' } - } - const targetLayout = { - root: { type: 'leaf' as const, leafId: LEAF_2 }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'pty-detached' } - } - - store.getState().setTabLayout('source-tab', sourceLayout) - store.getState().setTabLayout('target-tab', targetLayout) - - expect(store.getState().terminalLayoutsByTabId['source-tab']).toBe(sourceLayout) - expect(store.getState().terminalLayoutsByTabId['target-tab']).toBe(targetLayout) - }) }) diff --git a/src/renderer/src/store/slices/terminal-orphan-helpers.test.ts b/src/renderer/src/store/slices/terminal-orphan-helpers.test.ts deleted file mode 100644 index cde7d9154b2..00000000000 --- a/src/renderer/src/store/slices/terminal-orphan-helpers.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { TerminalTab } from '../../../../shared/terminal-tab-types' -import { getOrphanTerminalIds } from './terminal-orphan-helpers' -import { buildTerminalTabRetirementPlan } from './terminal-tab-retirement' - -// Reconnect-map sessions count as retirement ownership and must also prevent orphan deletion before rebind (#9911). - -// Use one state fixture to prove retirement and orphan sweep agree on liveness. -type TestState = Parameters[0] & - Parameters[0] - -function makeTab(overrides: Partial & { id: string }): TerminalTab { - return { - ptyId: null, - worktreeId: 'wt-1', - title: 'claude', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 0, - ...overrides - } -} - -function makeState(overrides: Partial = {}): TestState { - return { - worktreesByRepo: { repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'local' }] }, - tabsByWorktree: {}, - unifiedTabsByWorktree: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - lastKnownRelayPtyIdByTabId: {}, - deferredSshSessionIdsByTabId: {}, - pendingReconnectPtyIdByTabId: {}, - unverifiedPtyLossTabIds: {}, - ...overrides - } as TestState -} - -describe('getOrphanTerminalIds reconnect-map liveness', () => { - it('does not orphan a tab whose live session survives in pendingReconnectPtyIdByTabId', () => { - const state = makeState({ - tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1', ptyId: null })] }, - ptyIdsByTabId: { T1: [] }, - unifiedTabsByWorktree: { 'wt-1': [] }, - pendingReconnectPtyIdByTabId: { T1: 'session-live' } - }) - - expect(buildTerminalTabRetirementPlan(state, 'T1').ptyIds).toContain('session-live') - expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1') - }) - - it('does not orphan a tab whose live session survives in lastKnownRelayPtyIdByTabId', () => { - const state = makeState({ - tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1' })] }, - ptyIdsByTabId: { T1: [] }, - unifiedTabsByWorktree: { 'wt-1': [] }, - lastKnownRelayPtyIdByTabId: { T1: 'relay:conn@@pty-live' } - }) - - expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1') - }) - - it('does not orphan a tab whose live session survives in deferredSshSessionIdsByTabId', () => { - const state = makeState({ - tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1' })] }, - ptyIdsByTabId: { T1: [] }, - unifiedTabsByWorktree: { 'wt-1': [] }, - deferredSshSessionIdsByTabId: { T1: 'ssh-session-live' } - }) - - expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1') - }) - - it('still orphans a tab with no live PTY evidence anywhere', () => { - const state = makeState({ - tabsByWorktree: { 'wt-1': [makeTab({ id: 'dead', ptyId: null })] }, - ptyIdsByTabId: { dead: [] }, - unifiedTabsByWorktree: { 'wt-1': [] } - }) - - expect(getOrphanTerminalIds(state, 'wt-1')).toContain('dead') - }) - - it('does not orphan a tab whose PTY loss is unverified', () => { - const state = makeState({ - tabsByWorktree: { 'wt-1': [makeTab({ id: 'host-lost', ptyId: null })] }, - ptyIdsByTabId: { 'host-lost': [] }, - unifiedTabsByWorktree: { 'wt-1': [] }, - unverifiedPtyLossTabIds: { 'host-lost': true } - }) - - expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('host-lost') - }) - - // SSH removal leaves persisted layout bindings behind; these cannot prove liveness or dead relay tabs stay forever. - it('still orphans a tab whose only reference is a stale layout leaf binding', () => { - const state = makeState({ - tabsByWorktree: { 'wt-1': [makeTab({ id: 'stale-layout', ptyId: null })] }, - ptyIdsByTabId: { 'stale-layout': [] }, - unifiedTabsByWorktree: { 'wt-1': [] }, - terminalLayoutsByTabId: { - 'stale-layout': { - root: { type: 'leaf', leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null, - ptyIdsByLeafId: { 'leaf-1': 'dead-relay-pty' } - } - } - }) - - expect(getOrphanTerminalIds(state, 'wt-1')).toContain('stale-layout') - }) -}) diff --git a/src/renderer/src/store/slices/terminal-pane-detach-agent-retention.test.ts b/src/renderer/src/store/slices/terminal-pane-detach-agent-retention.test.ts index 01036290f38..10828675926 100644 --- a/src/renderer/src/store/slices/terminal-pane-detach-agent-retention.test.ts +++ b/src/renderer/src/store/slices/terminal-pane-detach-agent-retention.test.ts @@ -170,25 +170,6 @@ function collect(args: { } describe('detach completed split pane → sidebar retention', () => { - it('recognizes the same run at its transferred authority without a suppressor', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - const state = store.getState() - const result = collect({ currentPaneKey: TARGET_PANE_KEY, currentTabId: TARGET_TAB }) - - expect(state.agentStatusByPaneKey[SOURCE_PANE_KEY]).toBeUndefined() - expect(state.agentStatusByPaneKey[TARGET_PANE_KEY]?.state).toBe('done') - expect(state.retentionSuppressedPaneKeys[SOURCE_PANE_KEY]).toBeUndefined() - expect(result.toRetain).toEqual([]) - expect(result.consumedSuppressedPaneKeys).toEqual([]) - }) - it('recognizes the same run after chained transfers', () => { const store = createDetachStore() store.getState().setAgentStatus(SOURCE_PANE_KEY, { @@ -237,140 +218,6 @@ describe('detach completed split pane → sidebar retention', () => { expect(store.getState().agentStatusByPaneKey[extraPaneKey]?.prompt).toBe('late post') }) - it('still retains the source when a different run occupies the transferred key', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - const result = collect({ - currentPaneKey: TARGET_PANE_KEY, - currentTabId: TARGET_TAB, - currentStartedAt: 900 - }) - - expect(result.toRetain).toHaveLength(1) - expect(result.toRetain[0]?.entry.paneKey).toBe(SOURCE_PANE_KEY) - }) - - it('still retains when a new agent reuses the pty and inherits its terminal handle', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - // Why: terminalHandle is pty-scoped, so a fresh codex run carries the same handle. - const result = collect({ - currentPaneKey: TARGET_PANE_KEY, - currentTabId: TARGET_TAB, - currentStartedAt: 900, - currentAgentType: 'codex', - terminalHandle: 'term_shared' - }) - - expect(result.toRetain).toHaveLength(1) - expect(result.toRetain[0]?.entry.paneKey).toBe(SOURCE_PANE_KEY) - }) - - it('treats differing terminal handles as different runs', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - // Why: identical startedAt/agentType can collide, so a differing handle is the - // only signal that these are separate terminals. - const result = collectRetainedAgentsOnDisappear({ - previousAgents: new Map([ - [ - SOURCE_PANE_KEY, - { - row: makeRow(SOURCE_PANE_KEY, SOURCE_TAB, 100, { terminalHandle: 'term_source' }), - worktreeId: WORKTREE_ID - } - ] - ]), - currentAgents: new Map([ - [ - TARGET_PANE_KEY, - { - row: makeRow(TARGET_PANE_KEY, TARGET_TAB, 100, { terminalHandle: 'term_other' }), - worktreeId: WORKTREE_ID - } - ] - ]), - retainedAgentsByPaneKey: {}, - retentionSuppressedPaneKeys: {}, - recentlyClosedAgentStatusTabIds: {}, - recentlyRetiredAgentStatusPaneKeys: {} - }) - - expect(result.toRetain).toHaveLength(1) - }) - - it('recognizes the same run when resume identity lands only after the move', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - // Provider session arrives in separate IPC; a stamped destination and unstamped source do not prove separate runs. - const result = collect({ - currentPaneKey: TARGET_PANE_KEY, - currentTabId: TARGET_TAB, - currentProviderSession: { key: 'session_id', id: 'session-1' } - }) - - expect(result.toRetain).toEqual([]) - }) - - it('treats mismatched resume identities as different runs', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - const result = collect({ - currentPaneKey: TARGET_PANE_KEY, - currentTabId: TARGET_TAB, - previousProviderSession: { key: 'session_id', id: 'session-1' }, - currentProviderSession: { key: 'session_id', id: 'session-2' } - }) - - expect(result.toRetain).toHaveLength(1) - }) - - it('recognizes a handle-less local pty run at its transferred authority', () => { - const store = createDetachStore() - store.getState().setAgentStatus(SOURCE_PANE_KEY, { - state: 'done', - prompt: 'Fix it', - agentType: 'claude' - }) - - detach(store, SOURCE_TAB, TARGET_TAB) - // Local PTY rows can lack terminalHandle; requiring it would revive moved-row ghosts. - const result = collect({ currentPaneKey: TARGET_PANE_KEY, currentTabId: TARGET_TAB }) - - expect(result.toRetain[0]?.entry.terminalHandle).toBeUndefined() - expect(result.toRetain).toEqual([]) - }) - it('does not resurrect the source when the transferred owner immediately closes', () => { const store = createDetachStore() store.getState().setAgentStatus(SOURCE_PANE_KEY, { @@ -417,13 +264,4 @@ describe('detach completed split pane → sidebar retention', () => { expect(retained[0]?.tab).toBe(destinationTab) expect(retained[0]?.tab.title).toBe('Destination') }) - - it('does not create suppressors for a plain terminal detach', () => { - const store = createDetachStore() - - detach(store, SOURCE_TAB, TARGET_TAB) - - expect(store.getState().retentionSuppressedPaneKeys[SOURCE_PANE_KEY]).toBeUndefined() - expect(store.getState().retentionSuppressedPaneKeys[TARGET_PANE_KEY]).toBeUndefined() - }) }) diff --git a/src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts b/src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts index 853bcbb5654..a1c1e887fb4 100644 --- a/src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts +++ b/src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts @@ -1,52 +1,9 @@ import { describe, expect, it } from 'vitest' import { createTestStore, makeTab, seedStore } from './store-test-helpers' -import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types' +import type { TerminalLayoutSnapshot } from '../../../../shared/terminal-tab-types' { describe('terminal PTY identity replacement', () => { - it('keeps repeated remote handle rotations bounded to the live identity', () => { - const store = createTestStore() - const worktreeId = 'repo1::/path/wt1' - const firstPtyId = 'remote:env-1@@terminal-1' - const secondPtyId = 'remote:env-1@@terminal-2' - const thirdPtyId = 'remote:env-1@@terminal-3' - seedStore(store, { - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: firstPtyId })] - }, - ptyIdsByTabId: { 'tab-1': [firstPtyId] }, - suppressedPtyExitIds: { [firstPtyId]: true } - }) - - store.getState().updateTabPtyId('tab-1', secondPtyId, firstPtyId) - store.getState().updateTabPtyId('tab-1', thirdPtyId, secondPtyId) - - const state = store.getState() - expect(state.ptyIdsByTabId['tab-1']).toEqual([thirdPtyId]) - expect(state.tabsByWorktree[worktreeId][0]?.ptyId).toBe(thirdPtyId) - expect(state.lastKnownRelayPtyIdByTabId['tab-1']).toBe(thirdPtyId) - expect(state.suppressedPtyExitIds).toEqual({ [thirdPtyId]: true }) - }) - - it('migrates stale PTY state when the host snapshot published the replacement first', () => { - const store = createTestStore() - const worktreeId = 'repo1::/path/wt1' - const stalePtyId = 'remote:env-1@@terminal-stale' - const replacementPtyId = 'remote:env-1@@terminal-replacement' - seedStore(store, { - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: replacementPtyId })] - }, - ptyIdsByTabId: { 'tab-1': [replacementPtyId] }, - pendingPaneAccountRestarts: { [stalePtyId]: 'codex' } - }) - - store.getState().updateTabPtyId('tab-1', replacementPtyId, stalePtyId) - - expect(store.getState().ptyIdsByTabId['tab-1']).toEqual([replacementPtyId]) - expect(store.getState().pendingPaneAccountRestarts).toEqual({ [replacementPtyId]: 'codex' }) - }) - it('publishes pane and tab replacement identities in one store commit', () => { const store = createTestStore() const worktreeId = 'repo1::/path/wt1' @@ -126,23 +83,6 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter expect(store.getState().cacheTimerByKey[paneKey]).toBeNull() }) - it('wakes zero subscribers across 1,000 repeats of the same timestamp', () => { - const store = createTestStore() - const paneKey = 'tab-1:leaf-a' - store.getState().setCacheTimerStartedAt(paneKey, 1_700_000_000_000) - - let wakeups = 0 - const unsubscribe = store.subscribe(() => { - wakeups += 1 - }) - for (let i = 0; i < REPEATS; i += 1) { - store.getState().setCacheTimerStartedAt(paneKey, 1_700_000_000_000) - } - unsubscribe() - - expect(wakeups).toBe(0) - }) - it('still publishes when the timestamp actually changes', () => { const store = createTestStore() const paneKey = 'tab-1:leaf-a' @@ -159,33 +99,6 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter expect(wakeups).toBe(2) expect(store.getState().cacheTimerByKey[paneKey]).toBeNull() }) - - it('records the first write for a key even when the value is null', () => { - const store = createTestStore() - const paneKey = 'tab-1:leaf-a' - - let wakeups = 0 - const unsubscribe = store.subscribe(() => { - wakeups += 1 - }) - store.getState().setCacheTimerStartedAt(paneKey, null) - unsubscribe() - - expect(wakeups).toBe(1) - expect(paneKey in store.getState().cacheTimerByKey).toBe(true) - }) - - it('still clears a stale :seed sentinel when the pane value is unchanged', () => { - // Without this carve-out the bailout would strand the sentinel and leave a phantom timer. - const store = createTestStore() - const paneKey = 'tab-1:leaf-a' - store.getState().setCacheTimerStartedAt(paneKey, null) - store.setState((s) => ({ cacheTimerByKey: { ...s.cacheTimerByKey, 'tab-1:seed': 42 } })) - - store.getState().setCacheTimerStartedAt(paneKey, null) - - expect('tab-1:seed' in store.getState().cacheTimerByKey).toBe(false) - }) }) describe('setTabLayout identity bailout', () => { @@ -206,16 +119,6 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter expect(wakeups).toBe(0) }) - it('keeps the stored snapshot reference stable when nothing changed', () => { - const store = createTestStore() - store.getState().setTabLayout('tab-1', makeLayout()) - const first = store.getState().terminalLayoutsByTabId['tab-1'] - - store.getState().setTabLayout('tab-1', makeLayout()) - - expect(store.getState().terminalLayoutsByTabId['tab-1']).toBe(first) - }) - it('publishes when any tracked field changes', () => { const store = createTestStore() store.getState().setTabLayout('tab-1', makeLayout()) @@ -259,173 +162,5 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter expect(wakeups, `expected a publish for ${JSON.stringify(mutation)}`).toBe(1) } }) - - it('does not fire pane-ownership transfers for a bailed-out identical layout', () => { - // Duplicate-PTY normalization transfers ownership; replaying its normalized result must publish nothing. - const store = createTestStore() - const duplicate = makeLayout({ - ptyIdsByLeafId: { 'leaf-a': 'pty-a', 'leaf-b': 'pty-a' } - }) - store.getState().setTabLayout('tab-1', duplicate) - const normalized = store.getState().terminalLayoutsByTabId['tab-1'] - expect(normalized.ptyIdsByLeafId).not.toEqual(duplicate.ptyIdsByLeafId) - - store.setState({ unreadTerminalPanes: { 'tab-1:leaf-a': 'terminal-bell' } }) - const beforeUnread = { ...store.getState().unreadTerminalPanes } - - for (let i = 0; i < REPEATS; i += 1) { - store.getState().setTabLayout('tab-1', { ...normalized }) - } - - expect(store.getState().terminalLayoutsByTabId['tab-1']).toBe(normalized) - expect(store.getState().unreadTerminalPanes).toEqual(beforeUnread) - }) - - it('still deletes the layout on a clearing call, and bails when already absent', () => { - const store = createTestStore() - store.getState().setTabLayout('tab-1', makeLayout()) - - store.getState().setTabLayout('tab-1', null) - expect('tab-1' in store.getState().terminalLayoutsByTabId).toBe(false) - - let wakeups = 0 - const unsubscribe = store.subscribe(() => { - wakeups += 1 - }) - store.getState().setTabLayout('tab-1', null) - unsubscribe() - expect(wakeups).toBe(0) - }) - }) -} - -{ - function terminalTab(id: string, worktreeId: string): TerminalTab { - return { - id, - ptyId: null, - worktreeId, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - } - - describe('pane foreground agent slice', () => { - it('sets, value-bails, and clears entries per pane key', () => { - const store = createTestStore() - store - .getState() - .setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false }) - const first = store.getState().paneForegroundAgentByPaneKey - - store - .getState() - .setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false }) - expect(store.getState().paneForegroundAgentByPaneKey).toBe(first) - - store.getState().setPaneForegroundAgent('tab-1:leaf-1', { - agent: 'aider', - routingRevoked: true, - routingConfirmationPending: true, - shellForeground: false - }) - expect(store.getState().paneForegroundAgentByPaneKey).not.toBe(first) - expect(store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']?.routingRevoked).toBe( - true - ) - expect( - store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']?.routingConfirmationPending - ).toBe(true) - - store.getState().clearPaneForegroundAgent('tab-1:leaf-1') - expect(store.getState().paneForegroundAgentByPaneKey).toEqual({}) - }) - - // Confirmation settle can change only routingConfirmationPending; equality must allow clearing it or CSI-u stays enabled. - it('lands the publish that clears a pending confirmation', () => { - const store = createTestStore() - store.getState().setPaneForegroundAgent('tab-1:leaf-1', { - agent: 'pi', - routingRevoked: true, - routingConfirmationPending: true, - shellForeground: false - }) - - // Exactly the entry the inconclusive-settle path republishes. - store.getState().setPaneForegroundAgent('tab-1:leaf-1', { - agent: 'pi', - routingRevoked: true, - shellForeground: false - }) - - expect(store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']).toEqual({ - agent: 'pi', - routingRevoked: true, - shellForeground: false - }) - }) - - // Same-agent confirmation must still replace launch-only evidence so sidebar recognizes process-backed identity. - it('lands a process read that confirms a launch-record agent', () => { - const store = createTestStore() - store.getState().setPaneForegroundAgent('tab-1:leaf-1', { - agent: 'codex', - agentEvidence: 'launch-record', - shellForeground: false - }) - store.getState().setPaneForegroundAgent('tab-1:leaf-1', { - agent: 'codex', - agentEvidence: 'process-read', - shellForeground: false - }) - - expect(store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']?.agentEvidence).toBe( - 'process-read' - ) - }) - - it('sweeps only the closed tab prefix, not sibling tabs or prefix-share ids', () => { - const store = createTestStore() - store - .getState() - .setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false }) - store - .getState() - .setPaneForegroundAgent('tab-10:leaf-1', { agent: 'codex', shellForeground: false }) - - store.getState().clearPaneForegroundAgentByTabPrefix('tab-1') - - expect(Object.keys(store.getState().paneForegroundAgentByPaneKey)).toEqual(['tab-10:leaf-1']) - }) - - it('sweeps every tab of a worktree on wholesale teardown', () => { - const store = createTestStore() - store.setState({ - tabsByWorktree: { - 'wt-1': [terminalTab('tab-1', 'wt-1'), terminalTab('tab-2', 'wt-1')], - 'wt-2': [terminalTab('tab-3', 'wt-2')] - } - }) - store - .getState() - .setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false }) - store - .getState() - .setPaneForegroundAgent('tab-2:leaf-1', { agent: null, shellForeground: true }) - store - .getState() - .setPaneForegroundAgent('tab-3:leaf-1', { agent: 'codex', shellForeground: false }) - - const before = store.getState().paneForegroundAgentByPaneKey - store.getState().clearPaneForegroundAgentByWorktree('wt-missing') - expect(store.getState().paneForegroundAgentByPaneKey).toBe(before) - - store.getState().clearPaneForegroundAgentByWorktree('wt-1') - - expect(Object.keys(store.getState().paneForegroundAgentByPaneKey)).toEqual(['tab-3:leaf-1']) - }) }) } diff --git a/src/renderer/src/store/slices/terminal-tab-id-hydration.test.ts b/src/renderer/src/store/slices/terminal-tab-id-hydration.test.ts deleted file mode 100644 index 40e7b9c949e..00000000000 --- a/src/renderer/src/store/slices/terminal-tab-id-hydration.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' -import { buildHydratedTabState } from './tabs-hydration' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/runtime/sync-runtime-graph', () => ({ - scheduleRuntimeGraphSync: vi.fn() -})) -vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ - registerEagerPtyBuffer: vi.fn(), - ensurePtyDispatcher: vi.fn() -})) - -const apiProxy = (): unknown => - new Proxy(() => undefined, { - get: (_target, prop) => (prop === 'then' ? undefined : apiProxy()), - apply: () => Promise.resolve(null) - }) - -// @ts-expect-error -- mocked browser preload API -globalThis.window = { api: apiProxy() } - -import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers' - -const BAD_TAB_ID = 'host-tab::11111111-1111-4111-8111-111111111111' -const GOOD_TAB_ID = 'terminal-good' -const WORKTREE_ID = 'repo1::/wt-1' - -function makeBaseSession(): WorkspaceSessionState { - return { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - } -} - -describe('terminal tab id hydration', () => { - it('drops unified terminal tabs whose IDs cannot form pane keys', () => { - const session: WorkspaceSessionState = { - ...makeBaseSession(), - unifiedTabs: { - w1: [ - { - id: BAD_TAB_ID, - entityId: BAD_TAB_ID, - groupId: 'g1', - worktreeId: 'w1', - contentType: 'terminal', - label: 'Bad remote terminal', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: GOOD_TAB_ID, - entityId: GOOD_TAB_ID, - groupId: 'g1', - worktreeId: 'w1', - contentType: 'terminal', - label: 'Good terminal', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - }, - tabGroups: { - w1: [ - { - id: 'g1', - worktreeId: 'w1', - activeTabId: BAD_TAB_ID, - tabOrder: [BAD_TAB_ID, GOOD_TAB_ID] - } - ] - } - } - - const result = buildHydratedTabState(session, new Set(['w1'])) - - expect(result.unifiedTabsByWorktree.w1.map((tab) => tab.id)).toEqual([GOOD_TAB_ID]) - expect(result.groupsByWorktree.w1[0]).toMatchObject({ - activeTabId: null, - tabOrder: [GOOD_TAB_ID] - }) - }) - - it('drops runtime terminal state whose IDs cannot form pane keys', () => { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })] - } - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: WORKTREE_ID, - activeTabId: BAD_TAB_ID, - tabsByWorktree: { - [WORKTREE_ID]: [ - makeTab({ id: BAD_TAB_ID, worktreeId: WORKTREE_ID, ptyId: 'bad-pty', sortOrder: 0 }), - makeTab({ id: GOOD_TAB_ID, worktreeId: WORKTREE_ID, ptyId: 'good-pty', sortOrder: 1 }) - ] - }, - terminalLayoutsByTabId: { - [BAD_TAB_ID]: makeLayout(), - [GOOD_TAB_ID]: makeLayout() - }, - activeTabIdByWorktree: { - [WORKTREE_ID]: BAD_TAB_ID - }, - remoteSessionIdsByTabId: { - [BAD_TAB_ID]: 'bad-remote', - [GOOD_TAB_ID]: 'good-remote' - }, - activeWorktreeIdsOnShutdown: [WORKTREE_ID] - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().tabsByWorktree[WORKTREE_ID].map((tab) => tab.id)).toEqual([GOOD_TAB_ID]) - expect(store.getState().activeTabId).toBeNull() - expect(store.getState().activeTabIdByWorktree[WORKTREE_ID]).toBeUndefined() - expect(store.getState().terminalLayoutsByTabId[BAD_TAB_ID]).toBeUndefined() - expect(store.getState().terminalLayoutsByTabId[GOOD_TAB_ID]).toBeDefined() - expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({ - [GOOD_TAB_ID]: 'good-remote' - }) - }) - - it('does not turn a rejected terminal row into an explicit-empty tombstone', () => { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })] - } - }) - - store.getState().hydrateWorkspaceSession({ - ...makeBaseSession(), - tabsByWorktree: { - [WORKTREE_ID]: [makeTab({ id: BAD_TAB_ID, worktreeId: WORKTREE_ID })] - } - }) - - expect(Object.hasOwn(store.getState().tabsByWorktree, WORKTREE_ID)).toBe(false) - }) -}) diff --git a/src/renderer/src/store/slices/terminal-tab-owner-index.test.ts b/src/renderer/src/store/slices/terminal-tab-owner-index.test.ts index 09ecdf4ccb9..b14687d816c 100644 --- a/src/renderer/src/store/slices/terminal-tab-owner-index.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-owner-index.test.ts @@ -103,31 +103,6 @@ describe('terminal tab owner index', () => { expect(bucketVisits).toBe(0) }) - it('replaces the topology on hydration across every workspace key kind', () => { - const index = createTerminalTabOwnerIndex() - index.getOwners({ stale: [{ id: 'stale-tab' }] }) - - const hydrated = { - 'repo-local::/Users/me/project': [{ id: 'local-tab' }], - 'folder:folder-workspace-id': [{ id: 'folder-tab' }], - 'repo-ssh::/srv/project': [{ id: 'ssh-tab' }], - 'repo-wsl::\\\\wsl.localhost\\Ubuntu\\home\\me\\project': [{ id: 'wsl-tab' }], - 'worktree:repo-runtime::/workspace::workspace:paired-runtime-id': [ - { id: 'paired-runtime-tab' } - ] - } - const owners = index.getOwners(hydrated) - - expect(Object.fromEntries(owners)).toEqual({ - 'local-tab': 'repo-local::/Users/me/project', - 'folder-tab': 'folder:folder-workspace-id', - 'ssh-tab': 'repo-ssh::/srv/project', - 'wsl-tab': 'repo-wsl::\\\\wsl.localhost\\Ubuntu\\home\\me\\project', - 'paired-runtime-tab': 'worktree:repo-runtime::/workspace::workspace:paired-runtime-id' - }) - expect(owners.has('stale-tab')).toBe(false) - }) - it('preserves last-wins object order for duplicate ids when only outer keys reorder', () => { let idReads = 0 const firstBucket = [ diff --git a/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts b/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts index ca99a8956a8..0df514208ff 100644 --- a/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createTestStore, makeWorktree, seedStore } from './store-test-helpers' -import { isTerminalTabPresent } from './terminal-tab-retirement' +import './terminal-tab-retirement' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { createStoreSessionMockApi } from './store-session-test-harness' @@ -26,99 +26,6 @@ function seedWorktreeWithTab(store: ReturnType): string return store.getState().createTab(WORKTREE_ID).id } -describe('remountTerminalTabForRecovery', () => { - it('bumps the tab generation so TerminalPane remounts', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - const before = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === tabId) - - const remounted = store.getState().remountTerminalTabForRecovery(tabId) - - expect(remounted.remounted).toBe(true) - const after = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === tabId) - expect(after?.generation ?? 0).toBe((before?.generation ?? 0) + 1) - // Recovery is not user interaction — the remount's PTY updates must not - // reshuffle Recent, mirroring the activation-time generation bump. - expect(after?.pendingActivationSpawn).toBeTruthy() - }) - - it('gives a remounted pane a distinct queued startup owner', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - const startup = { command: 'echo recover' } - store.getState().queueTabStartupCommand(tabId, startup) - const before = store.getState().pendingStartupByTabId[tabId] - - expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(true) - - const after = store.getState().pendingStartupByTabId[tabId] - expect(after).toEqual(before) - expect(after).not.toBe(before) - }) - - it('leaves sibling tabs untouched', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - const siblingId = store.getState().createTab(WORKTREE_ID).id - - store.getState().remountTerminalTabForRecovery(tabId) - - const sibling = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === siblingId) - expect(sibling?.generation ?? 0).toBe(0) - expect(sibling?.pendingActivationSpawn).toBeFalsy() - }) - - it('returns false when the tab no longer exists', () => { - const store = createTestStore() - seedWorktreeWithTab(store) - - expect(store.getState().remountTerminalTabForRecovery('missing-tab')).toEqual({ - remounted: false, - declinedBy: 'tab-missing' - }) - }) -}) - -// Recovery budget must follow the terminal-row index; temporary unified-index absence previously released the budget on every remount (b5cfc6ca). -describe('isTerminalTabPresent as the recovery existence check', () => { - it('answers true for a tab remountTerminalTabForRecovery can still remount', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - - expect(isTerminalTabPresent(store.getState(), tabId)).toBe(true) - expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(true) - }) - - it('stays true when the tab is missing from the unified tab index', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - store.setState({ unifiedTabsByWorktree: {} }) - - expect(store.getState().getTab(tabId)).toBeNull() - expect(isTerminalTabPresent(store.getState(), tabId)).toBe(true) - }) - - it('answers false once the tab leaves the remount index', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - store.setState({ tabsByWorktree: { [WORKTREE_ID]: [] } }) - - expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false) - expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(false) - }) - - // The budget release still has to fire for a real close, or a closed tab's - // timestamps and pending retry outlive it. - it('answers false after a genuine closeTab', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - - store.getState().closeTab(tabId) - - expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false) - }) -}) - // Recovery ledger follows tab rows across worktree, folder and floating buckets; no repository-only lookup may strand it. describe.each([ ['a repository worktree', WORKTREE_ID], @@ -168,42 +75,10 @@ describe.each([ .remounted ).toBe(true) }) - - it('drops the ledger with the row when the tab closes', () => { - const store = createTestStore() - const tabId = seedBucket(store) - store.getState().remountTerminalTabForRecovery(tabId, AUTOMATIC) - - store.getState().closeTab(tabId) - - expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false) - expect(store.getState().tabsByWorktree[bucketId]?.some((tab) => tab.id === tabId)).toBeFalsy() - }) }) // Pane mount snapshots startup commands once; recovery must retain queued commands until owning-pane spawn or leave quick commands at a bare prompt (STA-4876). describe('queued startup command retention', () => { - it('survives a recovery remount so the next mount can still deliver it', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - store.getState().queueTabStartupCommand(tabId, { command: 'echo hi' }) - - store.getState().remountTerminalTabForRecovery(tabId) - - expect(store.getState().pendingStartupByTabId[tabId]).toEqual({ command: 'echo hi' }) - }) - - // Commands are tab-scoped but binds are pane-scoped; a sibling’s earlier bind must not consume the owner’s remount command. - it('is not spent by a sibling pane binding a pty to the same tab', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - store.getState().queueTabStartupCommand(tabId, { command: 'echo hi' }) - - store.getState().updateTabPtyId(tabId, 'pty-sibling') - - expect(store.getState().pendingStartupByTabId[tabId]).toEqual({ command: 'echo hi' }) - }) - // Only the owning pane spends it, via this action, once its own fresh spawn exists. it('is spent through consumeTabStartupCommand and does not replay afterwards', () => { const store = createTestStore() @@ -216,27 +91,4 @@ describe('queued startup command retention', () => { expect(store.getState().pendingStartupByTabId[tabId]).toBeUndefined() expect(store.getState().consumeTabStartupCommand(tabId)).toBeNull() }) - - // Why: retention is bounded by tab lifetime, so a spawn that never binds cannot leak forever. - it('is dropped when the tab closes without ever spawning', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - store.getState().queueTabStartupCommand(tabId, { command: 'echo hi' }) - - store.getState().closeTab(tabId) - - expect(store.getState().pendingStartupByTabId[tabId]).toBeUndefined() - }) - - it('leaves a sibling tab’s queued command alone', () => { - const store = createTestStore() - const tabId = seedWorktreeWithTab(store) - const siblingId = store.getState().createTab(WORKTREE_ID).id - store.getState().queueTabStartupCommand(tabId, { command: 'echo mine' }) - store.getState().queueTabStartupCommand(siblingId, { command: 'echo theirs' }) - - store.getState().consumeTabStartupCommand(tabId) - - expect(store.getState().pendingStartupByTabId[siblingId]).toEqual({ command: 'echo theirs' }) - }) }) diff --git a/src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts b/src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts index 87baf2bf241..3225dffafcd 100644 --- a/src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts @@ -145,30 +145,6 @@ describe('terminal tab retirement store boundary', () => { expect(mockKill).not.toHaveBeenCalled() }) - it('preserves shared-owner snapshots while closing the source tab', async () => { - const store = createRetirementStore() - const snapshot = { snapshot: 'shared snapshot' } - const coldRestore = { scrollback: 'shared scrollback', cwd: 'C:\\workspace' } - seedStore(store, { - tabsByWorktree: { - 'wt-1': [ - makeTab({ id: 'tab-1', worktreeId: 'wt-1', ptyId: 'pty-shared' }), - makeTab({ id: 'tab-2', worktreeId: 'wt-1', ptyId: 'pty-shared' }) - ] - }, - ptyIdsByTabId: { 'tab-1': ['pty-shared'], 'tab-2': ['pty-shared'] }, - pendingSnapshotByPtyId: { 'pty-shared': snapshot }, - pendingColdRestoreByPtyId: { 'pty-shared': coldRestore } - }) - - store.getState().closeTab('tab-1') - await Promise.resolve() - - expect(mockKill).not.toHaveBeenCalled() - expect(store.getState().pendingSnapshotByPtyId['pty-shared']).toBe(snapshot) - expect(store.getState().pendingColdRestoreByPtyId['pty-shared']).toBe(coldRestore) - }) - it('reconciles natural exit without issuing teardown or revoking resume authority', async () => { const store = createRetirementStore() const record = sleepingRecord('tab-1:leaf-1', 'tab-1') @@ -188,15 +164,6 @@ describe('terminal tab retirement store boundary', () => { expect(store.getState().sleepingAgentSessionsByPaneKey['tab-1:leaf-1']).toBe(record) }) - it('does not recreate PTY indexes for a tab that no longer exists', () => { - const store = createRetirementStore() - - store.getState().updateTabPtyId('closed-tab', 'pty-after-close') - - expect(store.getState().ptyIdsByTabId['closed-tab']).toBeUndefined() - expect(store.getState().lastKnownRelayPtyIdByTabId['closed-tab']).toBeUndefined() - }) - it('retires a unified-only terminal instead of removing only its wrapper', async () => { const store = createRetirementStore() const unified = makeUnifiedTab({ @@ -228,22 +195,6 @@ describe('terminal tab retirement store boundary', () => { expect(store.getState().ptyIdsByTabId['terminal-tab-1']).toBeUndefined() }) - it('lets a paired host own runtime teardown while pruning local state', async () => { - const store = createRetirementStore() - seedStore(store, { - tabsByWorktree: { - 'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', ptyId: 'remote:terminal-1' })] - }, - ptyIdsByTabId: { 'tab-1': ['remote:terminal-1'] } - }) - - store.getState().closeTab('tab-1', { remoteCloseOwnedByHost: true }) - await Promise.resolve() - - expect(mockRuntimeCall).not.toHaveBeenCalled() - expect(store.getState().tabsByWorktree['wt-1']).toEqual([]) - }) - it('retires parked ownership before teardown and sweeps published state before unified close', () => { const store = createRetirementStore() const events: string[] = [] @@ -326,28 +277,4 @@ describe('terminal tab retirement store boundary', () => { ) warn.mockRestore() }) - - it('keeps the tab retired and reports provider rejection without an unhandled promise', async () => { - const store = createRetirementStore() - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - mockKill.mockRejectedValueOnce(new Error('provider unavailable')) - seedStore(store, { - tabsByWorktree: { - 'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', ptyId: 'pty-1' })] - }, - ptyIdsByTabId: { 'tab-1': ['pty-1'] } - }) - - store.getState().closeTab('tab-1') - await vi.waitFor(() => - expect(warn).toHaveBeenCalledWith('[terminal-retirement] provider teardown failed', { - tabId: 'tab-1', - localOrSshFailures: 1, - runtimeFailures: 0 - }) - ) - - expect(store.getState().tabsByWorktree['wt-1']).toEqual([]) - warn.mockRestore() - }) }) diff --git a/src/renderer/src/store/slices/terminal-tab-retirement.test.ts b/src/renderer/src/store/slices/terminal-tab-retirement.test.ts index 0f82c7a9891..5419ef178f4 100644 --- a/src/renderer/src/store/slices/terminal-tab-retirement.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-retirement.test.ts @@ -1,15 +1,11 @@ import { describe, expect, it } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' + import type { TerminalTab } from '../../../../shared/terminal-tab-types' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' -import { brandEphemeralSetupTerminalWorktreeId } from '../../../../shared/ephemeral-setup-terminal-worktree-id' -import { folderWorkspaceKey } from '../../../../shared/workspace-scope' -import { - buildTerminalTabRetirementPlan, - buildTerminalTabRetirementPlans, - isTerminalTabPresent, - removeSleepingAgentSessionsForTab -} from './terminal-tab-retirement' +import '../../../../shared/constants' +import '../../../../shared/ephemeral-setup-terminal-worktree-id' +import '../../../../shared/workspace-scope' +import type { buildTerminalTabRetirementPlan } from './terminal-tab-retirement' +import { buildTerminalTabRetirementPlans } from './terminal-tab-retirement' type RetirementState = Parameters[0] @@ -45,390 +41,7 @@ function makeState(overrides: Partial = {}): RetirementState { } } -function makeSleepingRecord(paneKey: string, tabId?: string): SleepingAgentSessionRecord { - return { - paneKey, - tabId, - worktreeId: 'wt-1', - agent: 'codex', - providerSession: { key: 'session_id', id: paneKey }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1 - } -} - describe('terminal tab retirement planning', () => { - it('collects and deduplicates every ownership source before routing providers', () => { - const state = makeState({ - tabsByWorktree: { - 'wt-1': [makeTab('tab-1', 'wt-1', 'pty-row')] - }, - ptyIdsByTabId: { 'tab-1': ['pty-index', 'pty-row'] }, - terminalLayoutsByTabId: { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { - leaf1: 'pty-layout', - leaf2: 'remote:env-1@@terminal-1' - } - } - }, - lastKnownRelayPtyIdByTabId: { 'tab-1': 'ssh:ssh-1@@relay-pty' }, - deferredSshSessionIdsByTabId: { 'tab-1': 'pty-deferred' }, - pendingReconnectPtyIdByTabId: { 'tab-1': 'pty-pending' } - }) - - expect(buildTerminalTabRetirementPlan(state, 'tab-1')).toEqual({ - tabId: 'tab-1', - worktreeId: 'wt-1', - ptyIds: [ - 'pty-index', - 'pty-row', - 'pty-layout', - 'remote:env-1@@terminal-1', - 'ssh:ssh-1@@relay-pty', - 'pty-deferred', - 'pty-pending' - ], - localOrSshPtyIds: [ - 'pty-index', - 'pty-row', - 'pty-layout', - 'ssh:ssh-1@@relay-pty', - 'pty-deferred', - 'pty-pending' - ], - runtimeTerminals: [ - { - ptyId: 'remote:env-1@@terminal-1', - environmentId: 'env-1', - handle: 'terminal-1' - } - ], - cleanupOnlyPtyIds: [], - sharedPtyIds: [], - unroutablePtyIds: [] - }) - expect(isTerminalTabPresent(state, 'tab-1')).toBe(true) - }) - - it('recognizes a tab after it is rehomed into a new worktree bucket', () => { - const state = makeState({ - tabsByWorktree: { - 'wt-old': [], - 'wt-new': [makeTab('tab-rehomed', 'wt-new', null)] - } - }) - - expect(isTerminalTabPresent(state, 'tab-rehomed')).toBe(true) - }) - - it('does not retire a PTY still referenced by another live surface', () => { - const shared = 'pty-in-transfer' - const state = makeState({ - tabsByWorktree: { - 'wt-1': [makeTab('tab-1', 'wt-1', shared), makeTab('tab-2', 'wt-1', null)] - }, - ptyIdsByTabId: { 'tab-1': [shared], 'tab-2': [shared] }, - terminalLayoutsByTabId: { - 'tab-2': { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { leaf2: shared } - } - } - }) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - expect(plan.sharedPtyIds).toEqual([shared]) - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.runtimeTerminals).toEqual([]) - }) - - it('protects a scoped runtime terminal referenced through its legacy alias', () => { - const scoped = 'remote:env-1@@terminal-1' - const legacy = 'remote:terminal-1' - const state = makeState({ - settings: { activeRuntimeEnvironmentId: 'env-1' }, - worktreesByRepo: { - repo: [ - { id: 'wt-1', repoId: 'repo', hostId: 'runtime:env-1' }, - { id: 'wt-2', repoId: 'repo', hostId: 'runtime:env-1' } - ] - }, - tabsByWorktree: { - 'wt-1': [makeTab('tab-1', 'wt-1', legacy)], - 'wt-2': [makeTab('tab-2', 'wt-2', scoped)] - }, - ptyIdsByTabId: { 'tab-1': [legacy], 'tab-2': [scoped] } - }) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - expect(plan.sharedPtyIds).toEqual([legacy]) - expect(plan.runtimeTerminals).toEqual([]) - }) - - it('deduplicates legacy and scoped aliases owned by the closing tab', () => { - const state = makeState({ - settings: { activeRuntimeEnvironmentId: 'env-1' }, - worktreesByRepo: { repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'runtime:env-1' }] }, - tabsByWorktree: { - 'wt-1': [makeTab('tab-1', 'wt-1', 'remote:terminal-1')] - }, - ptyIdsByTabId: { - 'tab-1': ['remote:terminal-1', 'remote:env-1@@terminal-1'] - } - }) - - expect(buildTerminalTabRetirementPlan(state, 'tab-1').runtimeTerminals).toEqual([ - { - ptyId: 'remote:terminal-1', - environmentId: null, - handle: 'terminal-1' - } - ]) - }) - - describe('legacy runtime ids in a local twin of a server', () => { - const TWIN = 'twin-repo::/w' - const legacy = 'remote:terminal-1' - const twinRows = { - repos: [ - { id: 'twin-repo', executionHostId: 'local' as const }, - { id: 'twin-repo', executionHostId: 'runtime:env-b' as const }, - { id: 'repo', executionHostId: 'local' as const } - ], - worktreesByRepo: { - 'twin-repo': [ - { id: TWIN, repoId: 'twin-repo', hostId: 'local' as const }, - { - id: TWIN, - repoId: 'twin-repo', - hostId: 'runtime:env-b' as const, - runtimeOwnerEnvironmentId: 'env-b' - } - ], - repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'local' as const }] - } - } - - it("does not merge a twin's legacy id with the same id on another host", () => { - const state = makeState({ - ...twinRows, - tabsByWorktree: { - [TWIN]: [makeTab('tab-twin', TWIN, legacy)], - 'wt-1': [makeTab('tab-local', 'wt-1', legacy)] - }, - ptyIdsByTabId: { 'tab-twin': [legacy], 'tab-local': [legacy] } - }) - - expect(buildTerminalTabRetirementPlan(state, 'tab-local').sharedPtyIds).toEqual([]) - expect(buildTerminalTabRetirementPlan(state, 'tab-twin').sharedPtyIds).toEqual([]) - }) - - it("still protects a twin's legacy id held by a second tab of the same twin", () => { - const state = makeState({ - ...twinRows, - tabsByWorktree: { - [TWIN]: [makeTab('tab-a', TWIN, legacy), makeTab('tab-b', TWIN, legacy)] - }, - ptyIdsByTabId: { 'tab-a': [legacy], 'tab-b': [legacy] } - }) - - expect(buildTerminalTabRetirementPlan(state, 'tab-a').sharedPtyIds).toEqual([legacy]) - }) - }) - - it('ignores stale ownership maps and never routes malformed remote ids locally', () => { - const malformedRemote = 'remote:' - const state = makeState({ - tabsByWorktree: { - 'wt-1': [makeTab('tab-1', 'wt-1', malformedRemote)] - }, - ptyIdsByTabId: { - 'tab-1': [malformedRemote, 'pty-live'], - 'stale-tab': ['pty-live'] - } - }) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - expect(plan.unroutablePtyIds).toEqual([malformedRemote]) - expect(plan.localOrSshPtyIds).toEqual(['pty-live']) - expect(plan.sharedPtyIds).toEqual([]) - }) - - it('never kills a HUB-native PTY when duplicate worktree ownership is ambiguous', () => { - const state = makeState({ - worktreesByRepo: { - repo: [ - { id: 'wt-1', repoId: 'repo', hostId: 'ssh:private', runtimeOwnerEnvironmentId: 'hub-a' }, - { id: 'wt-1', repoId: 'repo', hostId: 'ssh:private', runtimeOwnerEnvironmentId: 'hub-b' } - ] - }, - tabsByWorktree: { - 'wt-1': [makeTab('tab-1', 'wt-1', 'ssh:private@@pty-1')] - } - }) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.runtimeTerminals).toEqual([]) - expect(plan.unroutablePtyIds).toEqual(['ssh:private@@pty-1']) - }) - - it('never falls an unknown stale worktree through to local PTY teardown', () => { - const state = makeState({ - worktreesByRepo: {}, - tabsByWorktree: { - 'stale-worktree': [makeTab('tab-1', 'stale-worktree', 'ssh:private@@pty-1')] - } - }) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.unroutablePtyIds).toEqual(['ssh:private@@pty-1']) - }) - - // Ownerless host-agnostic surfaces still own local PTYs; teardown previously dropped them without killing (STA-2639). - describe('host-agnostic terminal surfaces are killed, not dropped', () => { - const localSurfaces: [string, string][] = [ - ['floating terminal', FLOATING_TERMINAL_WORKTREE_ID], - ['ephemeral setup terminal', brandEphemeralSetupTerminalWorktreeId('panel-1')], - ['folder workspace', folderWorkspaceKey('fw-1')] - ] - - for (const [label, worktreeId] of localSurfaces) { - it(`kills a local ${label} PTY while a runtime is focused`, () => { - // Runtime focus changes during catalog hydration; it cannot retarget teardown of local surfaces. - const state = makeState({ - settings: { activeRuntimeEnvironmentId: 'hub-a' }, - runtimeEnvironments: [{ id: 'hub-a' }], - folderWorkspaces: [{ id: 'fw-1', projectGroupId: 'pg-1', connectionId: null }], - projectGroups: [{ id: 'pg-1', connectionId: null, executionHostId: null }], - tabsByWorktree: { [worktreeId]: [makeTab('tab-1', worktreeId, 'pty-1')] } - } as unknown as Partial) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual(['pty-1']) - expect(plan.unroutablePtyIds).toEqual([]) - }) - } - - it('closes a runtime-hosted floating terminal over RPC instead of killing it locally', () => { - const state = makeState({ - settings: { activeRuntimeEnvironmentId: 'hub-a' }, - runtimeEnvironments: [{ id: 'hub-a' }], - tabsByWorktree: { - [FLOATING_TERMINAL_WORKTREE_ID]: [ - makeTab('tab-1', FLOATING_TERMINAL_WORKTREE_ID, 'remote:hub-a@@handle-1') - ] - } - } as unknown as Partial) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.runtimeTerminals).toEqual([ - { ptyId: 'remote:hub-a@@handle-1', environmentId: 'hub-a', handle: 'handle-1' } - ]) - }) - - it('never kills a HUB-owned folder workspace PTY', () => { - const state = makeState({ - folderWorkspaces: [{ id: 'fw-1', projectGroupId: 'pg-1', connectionId: null }], - projectGroups: [{ id: 'pg-1', connectionId: null, executionHostId: 'runtime:hub-a' }], - tabsByWorktree: { - [folderWorkspaceKey('fw-1')]: [makeTab('tab-1', folderWorkspaceKey('fw-1'), 'pty-hub')] - } - } as unknown as Partial) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.unroutablePtyIds).toEqual(['pty-hub']) - }) - - it('never kills a HUB wake hint on a worktree owned only by the focused runtime', () => { - // Ownerless legacy rows may spawn on focused runtime with ssh:-shaped hints; shape alone must not route kill to the wrong host. - const state = makeState({ - repos: [{ id: 'repo1', connectionId: null }], - worktreesByRepo: { repo1: [{ id: 'wt-legacy', repoId: 'repo1' }] }, - settings: { activeRuntimeEnvironmentId: 'legacy-hub' }, - runtimeEnvironments: [{ id: 'legacy-hub' }], - tabsByWorktree: { - 'wt-legacy': [makeTab('tab-1', 'wt-legacy', 'ssh:hub-private@@pty-2')] - } - } as unknown as Partial) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.unroutablePtyIds).toEqual(['ssh:hub-private@@pty-2']) - }) - - it('never kills a PTY whose owning tab row is already gone', () => { - // Why: a vanished row is the ambiguity #9994 guards — nothing proves which host holds the PTY. - const state = makeState({ ptyIdsByTabId: { 'tab-1': ['pty-ghost'] } }) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.unroutablePtyIds).toEqual(['pty-ghost']) - }) - - it('never kills an unknown worktree PTY when every owner catalog is absent', () => { - // Spawn may fall back during catalog hydration; teardown must refuse unknown ownership rather than kill by guess. - const state = makeState({ - worktreesByRepo: undefined, - detectedWorktreesByRepo: undefined, - repos: undefined, - tabsByWorktree: { 'wt-unknown': [makeTab('tab-1', 'wt-unknown', 'pty-1')] } - } as unknown as Partial) - - const plan = buildTerminalTabRetirementPlan(state, 'tab-1') - - expect(plan.localOrSshPtyIds).toEqual([]) - expect(plan.unroutablePtyIds).toEqual(['pty-1']) - }) - }) - - it('deduplicates batch-owned PTYs while protecting owners outside the close set', () => { - const state = makeState({ - tabsByWorktree: { - 'wt-1': [ - makeTab('tab-1', 'wt-1', 'pty-batch'), - makeTab('tab-2', 'wt-1', 'pty-batch'), - makeTab('later-tab', 'wt-1', 'pty-external') - ] - }, - ptyIdsByTabId: { - 'tab-1': ['pty-batch', 'pty-external'], - 'tab-2': ['pty-batch'], - 'later-tab': ['pty-external'] - } - }) - - const plans = buildTerminalTabRetirementPlans(state, ['tab-1', 'tab-2']) - - expect(plans.get('tab-1')).toMatchObject({ - localOrSshPtyIds: ['pty-batch'], - sharedPtyIds: ['pty-external'] - }) - expect(plans.get('tab-2')).toMatchObject({ - localOrSshPtyIds: [], - cleanupOnlyPtyIds: ['pty-batch'], - sharedPtyIds: [] - }) - }) - it('indexes live owners once for a 100-tab batch', () => { const tabs = Array.from({ length: 100 }, (_, index) => makeTab(`tab-${index}`, 'wt-1', `pty-${index}`) @@ -467,19 +80,3 @@ describe('terminal tab retirement planning', () => { expect(unifiedStoreScans).toBe(1) }) }) - -describe('sleeping agent retirement', () => { - it('removes key- and metadata-owned records while preserving siblings by reference', () => { - const sibling = makeSleepingRecord('tab-2:leaf-2', 'tab-2') - const records = { - 'tab-1:leaf-1': makeSleepingRecord('tab-1:leaf-1'), - 'legacy-pane-key': makeSleepingRecord('legacy-pane-key', 'tab-1'), - 'tab-2:leaf-2': sibling - } - - const next = removeSleepingAgentSessionsForTab(records, 'tab-1') - expect(next).toEqual({ 'tab-2:leaf-2': sibling }) - expect(next['tab-2:leaf-2']).toBe(sibling) - expect(removeSleepingAgentSessionsForTab(next, 'missing-tab')).toBe(next) - }) -}) diff --git a/src/renderer/src/store/slices/terminal-tab-title-batch.test.ts b/src/renderer/src/store/slices/terminal-tab-title-batch.test.ts index 0d0370b7313..1bd538b2e52 100644 --- a/src/renderer/src/store/slices/terminal-tab-title-batch.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-title-batch.test.ts @@ -163,142 +163,6 @@ describe('terminal tab title batches', () => { expect(store.getState().tabsByWorktree['wt-299']?.[0]?.title).toBe('Second warm title') }) - it('preserves ordered duplicate updates and last-owner duplicate-id routing', () => { - const store = createTestStore() - seedStore(store, { - tabsByWorktree: { - first: [makeTab({ id: 'duplicate-tab', worktreeId: 'first', title: 'First owner' })], - second: [makeTab({ id: 'duplicate-tab', worktreeId: 'second', title: 'Second owner' })] - } - }) - - store.getState().updateTabTitles([ - { tabId: 'duplicate-tab', title: 'Intermediate' }, - { tabId: 'duplicate-tab', title: 'Final' } - ]) - - expect(store.getState().tabsByWorktree.first?.[0]?.title).toBe('First owner') - expect(store.getState().tabsByWorktree.second?.[0]?.title).toBe('Final') - }) - - it('updates every same-owner backing duplicate but only the first unified row', async () => { - const store = createTestStore() - seedStore(store, { - settings: { ...getDefaultSettings('/tmp'), tabAutoGenerateTitle: true }, - tabsByWorktree: { - owner: [ - makeTab({ id: 'duplicate-tab', worktreeId: 'owner', title: 'First backing' }), - makeTab({ id: 'duplicate-tab', worktreeId: 'owner', title: 'Second backing' }) - ] - }, - unifiedTabsByWorktree: { - owner: [ - makeUnifiedTab({ - id: 'duplicate-tab', - worktreeId: 'owner', - groupId: 'group-1', - label: 'First visible' - }), - makeUnifiedTab({ - id: 'duplicate-tab', - worktreeId: 'owner', - groupId: 'group-2', - label: 'Second visible' - }) - ] - } - }) - - store.getState().updateTabTitles([{ tabId: 'duplicate-tab', title: 'Final live title' }]) - store.getState().setGeneratedTabTitlesFromAgentPrompts([ - { - paneKey: makePaneKey('duplicate-tab', LEAF_ID), - prompt: 'Generated duplicate title for remote startup' - } - ]) - - expect(store.getState().tabsByWorktree.owner?.map((tab) => tab.title)).toEqual([ - 'Final live title', - 'Final live title' - ]) - // The live title is the window's own write in both builds. - expect(store.getState().unifiedTabsByWorktree.owner?.map((tab) => tab.label)).toEqual([ - 'Final live title', - 'Second visible' - ]) - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - // Main derives the generated title from its own agent status and its frame draws it: the - // window sends and writes none. - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(main.commands).toEqual([]) - expect(store.getState().tabsByWorktree.owner?.map((tab) => tab.generatedTitle)).toEqual([ - undefined, - undefined - ]) - expect( - store.getState().unifiedTabsByWorktree.owner?.map((tab) => tab.generatedLabel) - ).toEqual([undefined, undefined]) - return - } - expect(store.getState().tabsByWorktree.owner?.map((tab) => tab.generatedTitle)).toEqual([ - 'Generated duplicate title for remote', - 'Generated duplicate title for remote' - ]) - expect(store.getState().unifiedTabsByWorktree.owner?.map((tab) => tab.generatedLabel)).toEqual([ - 'Generated duplicate title for remote', - undefined - ]) - }) - - it('matches sequential live and generated title semantics in event order', () => { - const sequentialStore = createTestStore() - const batchStore = createTestStore() - const fixture = { - settings: { ...getDefaultSettings('/tmp'), tabAutoGenerateTitle: true }, - tabsByWorktree: { - owner: [makeTab({ id: 'tab-1', worktreeId: 'owner', title: 'Terminal 1' })] - }, - unifiedTabsByWorktree: { - owner: [makeUnifiedTab({ id: 'tab-1', worktreeId: 'owner', groupId: 'group-1' })] - } - } - seedStore(sequentialStore, structuredClone(fixture)) - seedStore(batchStore, structuredClone(fixture)) - const liveUpdates = [ - { tabId: 'tab-1', title: 'Codex' }, - { tabId: 'tab-1', title: '⠋ Codex is thinking' }, - { tabId: 'tab-1', title: '⠙ Codex is thinking' }, - { tabId: 'tab-1', title: '' }, - { tabId: 'tab-1', title: 'Final stable title' } - ] - const generatedUpdates = [ - { paneKey: makePaneKey('tab-1', LEAF_ID), prompt: 'First generated title wins here' }, - { paneKey: makePaneKey('tab-1', LEAF_ID), prompt: 'Ignored later generated title' }, - { - paneKey: makePaneKey('tab-1', LEAF_ID), - prompt: 'Forced replacement generated title', - options: { replaceExistingGeneratedTitle: true } - } - ] - - for (const update of liveUpdates) { - sequentialStore.getState().updateTabTitle(update.tabId, update.title) - } - for (const update of generatedUpdates) { - sequentialStore - .getState() - .setGeneratedTabTitleFromAgentPrompt(update.paneKey, update.prompt, update.options) - } - batchStore.getState().updateTabTitles(liveUpdates) - batchStore.getState().setGeneratedTabTitlesFromAgentPrompts(generatedUpdates) - - expect(batchStore.getState().tabsByWorktree).toEqual(sequentialStore.getState().tabsByWorktree) - expect(batchStore.getState().unifiedTabsByWorktree).toEqual( - sequentialStore.getState().unifiedTabsByWorktree - ) - expect(batchStore.getState().sortEpoch).toBe(sequentialStore.getState().sortEpoch) - }) - it('coalesces generated titles while preserving first-write and replacement semantics', async () => { const store = createTestStore() const fixture = makeScaleState(100) diff --git a/src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts b/src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts deleted file mode 100644 index 27ab55265ae..00000000000 --- a/src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { folderWorkspaceKey } from '../../../../shared/workspace-scope' -import { createTestStore, makeWorktree, seedStore } from './store-test-helpers' -import { shouldAutoCreateInitialTerminal } from '@/components/terminal/initial-terminal' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/runtime/sync-runtime-graph', () => ({ scheduleRuntimeGraphSync: vi.fn() })) -vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ - registerEagerPtyBuffer: vi.fn(), - ensurePtyDispatcher: vi.fn() -})) - -// @ts-expect-error -- hydration does not call the mocked preload surface. -globalThis.window = { api: {} } - -describe('explicit empty terminal hydration', () => { - it('preserves a git worktree terminal tombstone', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - store.getState().hydrateWorkspaceSession({ - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - tabsByWorktree: { [worktreeId]: [] } - }) - - expect(store.getState().tabsByWorktree).toEqual({ [worktreeId]: [] }) - }) - - it('preserves a folder workspace terminal tombstone', () => { - const store = createTestStore() - const workspaceKey = folderWorkspaceKey('folder-1') - - store.getState().hydrateWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - activeWorkspaceKey: workspaceKey, - activeWorktreeId: workspaceKey, - tabsByWorktree: { [workspaceKey]: [] } - }, - { additionalValidWorkspaceKeys: [workspaceKey] } - ) - - expect(store.getState().tabsByWorktree).toEqual({ [workspaceKey]: [] }) - }) -}) - -// Hydrated explicit-empty workspaces must suppress passive terminal creation (#15513); mirror terminal-tab-close-restart-persistence.spec.ts’s decision locally. -describe('hydrated active workspace with a terminal tombstone', () => { - it('reports no auto-create for the restored active worktree', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - store.getState().hydrateWorkspaceSession({ - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - tabsByWorktree: { [worktreeId]: [] } - }) - - const state = store.getState() - expect(state.activeWorktreeId).toBe(worktreeId) - expect(state.tabsByWorktree[worktreeId]).toEqual([]) - const { renderableTabCount } = state.reconcileWorktreeTabModel(worktreeId) - // The exact inputs Terminal.tsx's auto-create effect feeds shouldAutoCreateInitialTerminal. - expect(renderableTabCount).toBe(0) - expect(Object.hasOwn(state.tabsByWorktree, worktreeId)).toBe(true) - expect(shouldAutoCreateInitialTerminal(renderableTabCount, true)).toBe(false) - }) -}) diff --git a/src/renderer/src/store/slices/terminals-hydration-canonical-pty-overlap.test.ts b/src/renderer/src/store/slices/terminals-hydration-canonical-pty-overlap.test.ts index f75029bf156..817bcd708fa 100644 --- a/src/renderer/src/store/slices/terminals-hydration-canonical-pty-overlap.test.ts +++ b/src/renderer/src/store/slices/terminals-hydration-canonical-pty-overlap.test.ts @@ -2,12 +2,12 @@ import './terminal-hydration-store-test-bootstrap' import { describe, expect, it, vi } from 'vitest' import { getOrphanTerminalIds } from './terminal-orphan-helpers' -import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' + import type { Tab } from '../../../../shared/tab-types' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { buildWorkspaceSessionPayload } from '@/lib/workspace-session' +import '@/lib/workspace-session' import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers' vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) @@ -67,20 +67,6 @@ function makeSession(args: { } } -function makeSleepingRecord(paneKey: string, tabId: string): SleepingAgentSessionRecord { - return { - paneKey, - tabId, - worktreeId: WORKTREE_ID, - agent: 'claude', - providerSession: { key: 'session_id', id: `session-${paneKey}` }, - prompt: '', - state: 'waiting', - capturedAt: 1, - updatedAt: 1 - } -} - function hydrate(session: WorkspaceSessionState): ReturnType { const store = createTestStore() seedStore(store, { @@ -94,166 +80,6 @@ function hydrate(session: WorkspaceSessionState): ReturnType { - it('keeps the valid local row when an invalid-id canonical mirror shares its PTY', () => { - const sharedPtyId = 'daemon-session-1' - const mirrorTabId = 'host-tab::11111111-1111-4111-8111-111111111111' - const session = makeSession({ - tabs: [ - makeTab({ id: mirrorTabId, worktreeId: WORKTREE_ID, ptyId: sharedPtyId }), - makeTab({ id: 'local-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId, sortOrder: 1 }) - ], - layouts: { - [mirrorTabId]: { ...makeLayout(), ptyIdsByLeafId: { 'mirror-leaf': sharedPtyId } }, - 'local-tab': { ...makeLayout(), ptyIdsByLeafId: { 'local-leaf': sharedPtyId } } - }, - canonicalEntityIds: [mirrorTabId] - }) - - const state = hydrate(session).getState() - const persisted = buildWorkspaceSessionPayload(state) - - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual(['local-tab']) - expect(state.pendingReconnectPtyIdByTabId['local-tab']).toBe(sharedPtyId) - expect(persisted.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual(['local-tab']) - expect(persisted.terminalLayoutsByTabId[mirrorTabId]).toBeUndefined() - }) - - it('keeps a legacy split tab whose second pane owns an independent PTY', () => { - const sharedPtyId = 'daemon-shared' - const soloPtyId = 'daemon-solo' - const session = makeSession({ - tabs: [ - makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }), - makeTab({ id: 'split-tab', worktreeId: WORKTREE_ID, ptyId: soloPtyId, sortOrder: 1 }) - ], - layouts: { - 'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } }, - 'split-tab': { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: 'leaf-a' }, - second: { type: 'leaf', leafId: 'leaf-b' } - }, - activeLeafId: 'leaf-a', - expandedLeafId: null, - ptyIdsByLeafId: { 'leaf-a': sharedPtyId, 'leaf-b': soloPtyId } - } - }, - canonicalEntityIds: ['canonical-tab'] - }) - - const state = hydrate(session).getState() - const persisted = buildWorkspaceSessionPayload(state) - - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'split-tab' - ]) - expect(state.pendingReconnectPtyIdByTabId['split-tab']).toBe(soloPtyId) - // Why: the split row keeps its own PTY and gives up the one the canonical row owns. - expect(Object.values(state.terminalLayoutsByTabId['split-tab']?.ptyIdsByLeafId ?? {})).toEqual([ - soloPtyId - ]) - expect(persisted.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'split-tab' - ]) - expect( - Object.values(persisted.terminalLayoutsByTabId['split-tab']?.ptyIdsByLeafId ?? {}) - ).toEqual([soloPtyId]) - }) - - it('ignores a canonical row’s stale leaf binding when scoring another row’s live PTY', () => { - const canonicalPtyId = 'daemon-canonical' - const livePtyId = 'daemon-live' - const session = makeSession({ - tabs: [ - makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: canonicalPtyId }), - makeTab({ id: 'live-tab', worktreeId: WORKTREE_ID, ptyId: livePtyId, sortOrder: 1 }) - ], - layouts: { - // 'ghost-leaf' left the tree but its binding was never pruned, so it must not claim livePtyId. - 'canonical-tab': { - root: { type: 'leaf', leafId: 'canonical-leaf' }, - activeLeafId: 'canonical-leaf', - expandedLeafId: null, - ptyIdsByLeafId: { 'canonical-leaf': canonicalPtyId, 'ghost-leaf': livePtyId } - }, - 'live-tab': { ...makeLayout(), ptyIdsByLeafId: { 'live-leaf': livePtyId } } - }, - canonicalEntityIds: ['canonical-tab'] - }) - - const state = hydrate(session).getState() - - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'live-tab' - ]) - expect(state.pendingReconnectPtyIdByTabId['live-tab']).toBe(livePtyId) - }) - - it('strips a retained row’s stale binding to a PTY the canonical row owns', () => { - const sharedPtyId = 'daemon-shared' - const soloPtyId = 'daemon-solo' - const session = makeSession({ - tabs: [ - makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }), - makeTab({ id: 'legacy-tab', worktreeId: WORKTREE_ID, ptyId: soloPtyId, sortOrder: 1 }) - ], - layouts: { - 'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } }, - 'legacy-tab': { - root: { type: 'leaf', leafId: 'leaf-a' }, - activeLeafId: 'leaf-a', - expandedLeafId: null, - ptyIdsByLeafId: { 'leaf-a': soloPtyId, 'ghost-leaf': sharedPtyId } - } - }, - canonicalEntityIds: ['canonical-tab'] - }) - - const state = hydrate(session).getState() - - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'legacy-tab' - ]) - // Why: reconnect publishes every recorded leaf PTY, so a leftover binding would re-duplicate ownership. - expect(Object.values(state.terminalLayoutsByTabId['legacy-tab']?.ptyIdsByLeafId ?? {})).toEqual( - [soloPtyId] - ) - }) - - it('ignores a rootless canonical row’s extra bindings when scoring another row’s live PTY', () => { - const canonicalPtyId = 'daemon-canonical' - const livePtyId = 'daemon-live' - const session = makeSession({ - tabs: [ - makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: canonicalPtyId }), - makeTab({ id: 'live-tab', worktreeId: WORKTREE_ID, ptyId: livePtyId, sortOrder: 1 }) - ], - layouts: { - // Rootless proves ownership only for a sole off-tree pane; a second never-pruned binding proves nothing. - 'canonical-tab': { - ...makeLayout(), - ptyIdsByLeafId: { 'canonical-leaf': canonicalPtyId, 'ghost-leaf': livePtyId } - }, - 'live-tab': { ...makeLayout(), ptyIdsByLeafId: { 'live-leaf': livePtyId } } - }, - canonicalEntityIds: ['canonical-tab'] - }) - - const state = hydrate(session).getState() - - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'live-tab' - ]) - expect(state.pendingReconnectPtyIdByTabId['live-tab']).toBe(livePtyId) - }) - it('advertises a retained row’s own PTY after its tab-level id went to the canonical row', async () => { const sharedPtyId = 'daemon-shared' const soloPtyId = 'daemon-solo' @@ -296,64 +122,4 @@ describe('hydrateWorkspaceSession canonical PTY overlap', () => { // Why: liveness reads ptyIdsByTabId; without this the surviving pane's PTY reads as an orphan until mount. expect(state.ptyIdsByTabId['split-tab']).toEqual([soloPtyId]) }) - - it('drops a sleeping agent record on the leaf whose PTY moved to the canonical row', () => { - const sharedPtyId = 'daemon-shared' - const soloPtyId = 'daemon-solo' - const sharedLeafId = '11111111-1111-4111-8111-111111111111' - const soloLeafId = '22222222-2222-4222-8222-222222222222' - const session = { - ...makeSession({ - tabs: [ - makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }), - makeTab({ id: 'split-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId, sortOrder: 1 }) - ], - layouts: { - 'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } }, - 'split-tab': { - root: { - type: 'split' as const, - direction: 'vertical' as const, - first: { type: 'leaf' as const, leafId: sharedLeafId }, - second: { type: 'leaf' as const, leafId: soloLeafId } - }, - activeLeafId: sharedLeafId, - expandedLeafId: null, - ptyIdsByLeafId: { [sharedLeafId]: sharedPtyId, [soloLeafId]: soloPtyId } - } - }, - canonicalEntityIds: ['canonical-tab'] - }), - sleepingAgentSessionsByPaneKey: { - [`split-tab:${sharedLeafId}`]: makeSleepingRecord(`split-tab:${sharedLeafId}`, 'split-tab'), - [`split-tab:${soloLeafId}`]: makeSleepingRecord(`split-tab:${soloLeafId}`, 'split-tab') - } - } - - const state = hydrate(session).getState() - - expect(Object.keys(state.sleepingAgentSessionsByPaneKey)).toEqual([`split-tab:${soloLeafId}`]) - }) - - it('retains a non-canonical row that owns no PTY at all', () => { - const sharedPtyId = 'daemon-shared' - const session = makeSession({ - tabs: [ - makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }), - makeTab({ id: 'empty-tab', worktreeId: WORKTREE_ID, ptyId: null, sortOrder: 1 }) - ], - layouts: { - 'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } }, - 'empty-tab': makeLayout() - }, - canonicalEntityIds: ['canonical-tab'] - }) - - const state = hydrate(session).getState() - - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'empty-tab' - ]) - }) }) diff --git a/src/renderer/src/store/slices/terminals-hydration-canonical-rows.test.ts b/src/renderer/src/store/slices/terminals-hydration-canonical-rows.test.ts index 1af25d2b3ff..a5167f59bbe 100644 --- a/src/renderer/src/store/slices/terminals-hydration-canonical-rows.test.ts +++ b/src/renderer/src/store/slices/terminals-hydration-canonical-rows.test.ts @@ -1,6 +1,6 @@ import './terminal-hydration-store-test-bootstrap' import { describe, expect, it, vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' + import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { buildWorkspaceSessionPayload } from '@/lib/workspace-session' @@ -121,119 +121,4 @@ describe('hydrateWorkspaceSession canonical terminal rows', () => { expect(state.activeTabId).toBe('canonical-tab') expect(state.activeTabIdByWorktree).toEqual({ [worktreeId]: 'canonical-tab' }) }) - - it('clears sleeping-agent records for subsumed and invalid-id rows only', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - const sharedPtyId = 'daemon-session-1' - const recoveryPtyId = 'daemon-session-2' - const invalidTabId = 'host-tab::11111111-1111-4111-8111-111111111111' - const leafId = '22222222-2222-4222-8222-222222222222' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - const makeSleepingRecord = (tabId: string): SleepingAgentSessionRecord => ({ - paneKey: `${tabId}:${leafId}`, - tabId, - worktreeId, - agent: 'codex', - providerSession: { key: 'session_id', id: `session-${tabId}` }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1 - }) - - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeWorktreeIdsOnShutdown: [worktreeId], - tabsByWorktree: { - [worktreeId]: [ - makeTab({ id: 'canonical-tab', worktreeId, ptyId: sharedPtyId }), - makeTab({ id: 'stale-tab', worktreeId, ptyId: sharedPtyId }), - makeTab({ id: invalidTabId, worktreeId, ptyId: null }), - makeTab({ id: 'recovery-tab', worktreeId, ptyId: recoveryPtyId }) - ] - }, - terminalLayoutsByTabId: { - 'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } }, - 'stale-tab': { ...makeLayout(), ptyIdsByLeafId: { 'stale-leaf': sharedPtyId } }, - 'recovery-tab': { ...makeLayout(), ptyIdsByLeafId: { 'recovery-leaf': recoveryPtyId } } - }, - sleepingAgentSessionsByPaneKey: { - [`stale-tab:${leafId}`]: makeSleepingRecord('stale-tab'), - [`${invalidTabId}:${leafId}`]: makeSleepingRecord(invalidTabId), - [`recovery-tab:${leafId}`]: makeSleepingRecord('recovery-tab') - }, - unifiedTabs: { - [worktreeId]: [ - { - id: 'canonical-unified-tab', - entityId: 'canonical-tab', - groupId: 'group-1', - worktreeId, - contentType: 'terminal', - label: 'Grok', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - tabGroups: { - [worktreeId]: [ - { - id: 'group-1', - worktreeId, - activeTabId: 'canonical-unified-tab', - tabOrder: ['canonical-unified-tab'] - } - ] - } - } - - store.getState().hydrateWorkspaceSession(session) - const state = store.getState() - - expect(state.tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([ - 'canonical-tab', - 'recovery-tab' - ]) - // Why: both dropped classes keep a valid worktreeId, so only the per-tab sweep can evict them. - expect(Object.keys(state.sleepingAgentSessionsByPaneKey)).toEqual([`recovery-tab:${leafId}`]) - }) - - it('drops stale unverified-loss markers when full hydration removes their rows', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - const retainedTab = makeTab({ id: 'retained-tab', worktreeId, ptyId: null }) - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - }, - tabsByWorktree: { [worktreeId]: [retainedTab] }, - unverifiedPtyLossTabIds: { - [retainedTab.id]: true, - 'dropped-tab': true - } - }) - - store.getState().hydrateWorkspaceSession({ - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: retainedTab.id, - tabsByWorktree: { [worktreeId]: [retainedTab] }, - terminalLayoutsByTabId: {} - }) - - expect(store.getState().unverifiedPtyLossTabIds).toEqual({ - [retainedTab.id]: true - }) - }) }) diff --git a/src/renderer/src/store/slices/terminals-hydration.test.ts b/src/renderer/src/store/slices/terminals-hydration.test.ts index 6dcffc66f1a..53af4161d69 100644 --- a/src/renderer/src/store/slices/terminals-hydration.test.ts +++ b/src/renderer/src/store/slices/terminals-hydration.test.ts @@ -91,19 +91,9 @@ const mockApi = { globalThis.window = { api: mockApi } import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' -import { - FLOATING_TERMINAL_WORKTREE_ID, - getDefaultWorkspaceSession -} from '../../../../shared/constants' -import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' -import { - createTestStore, - makeLayout, - makeTab, - makeWorktree, - seedStore, - TEST_REPO -} from './store-test-helpers' +import '../../../../shared/constants' +import '../../../../shared/workspace-scope' +import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers' import { canGoBackWorktreeHistory } from './worktree-nav-history' describe('hydrateWorkspaceSession', () => { @@ -111,294 +101,6 @@ describe('hydrateWorkspaceSession', () => { vi.clearAllMocks() }) - it('preserves ptyIdsByLeafId so reconnect can reattach each split-pane leaf', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: 'tab-1', - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'old-pty' })] - }, - terminalLayoutsByTabId: { - 'tab-1': { - ...makeLayout(), - ptyIdsByLeafId: { 'pane:1': 'daemon-session-1' }, - buffersByLeafId: { 'pane:1': 'buffer' } - } - } - } - - store.getState().hydrateWorkspaceSession(session) - - // Why: ptyIdsByLeafId holds daemon session IDs that survive restart, letting each split-pane leaf reattach to its own session. - expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({ - ...makeLayout(), - ptyIdsByLeafId: { 'pane:1': 'daemon-session-1' }, - buffersByLeafId: { 'pane:1': 'buffer' } - }) - }) - - it('hydrates runtime-owned tabs from host partitions before remote catalogs load', () => { - const store = createTestStore() - const worktreeId = 'remote-repo::/srv/remote-wt' - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - activeRepoId: 'remote-repo', - activeWorktreeId: worktreeId, - activeTabId: 'remote-tab', - activeWorktreeIdsOnShutdown: [worktreeId], - tabsByWorktree: { - [worktreeId]: [ - makeTab({ - id: 'remote-tab', - worktreeId, - ptyId: 'remote-session' - }) - ] - }, - remoteSessionIdsByTabId: { 'remote-tab': 'remote-session' } - } - - store.getState().hydrateWorkspaceSession(session, { - runtimeHostIdByWorkspaceSessionKey: { [worktreeId]: 'runtime:env-1' } - }) - - expect(store.getState().tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([ - 'remote-tab' - ]) - expect(store.getState().activeWorktreeId).toBe(worktreeId) - expect(store.getState().activeRepoId).toBe('remote-repo') - expect(store.getState().pendingReconnectWorktreeIds).toEqual([worktreeId]) - expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({ - 'remote-tab': 'remote-session' - }) - expect(store.getState().repos).toEqual([ - expect.objectContaining({ - id: 'remote-repo', - executionHostId: 'runtime:env-1' - }) - ]) - expect(store.getState().worktreesByRepo['remote-repo']).toEqual([ - expect.objectContaining({ - id: worktreeId, - hostId: 'runtime:env-1' - }) - ]) - }) - - it('strips the synthetic workspace suffix from folder-workspace instance placeholders', () => { - const store = createTestStore() - const workspaceUuid = '123e4567-e89b-12d3-a456-426614174000' - const worktreeId = `folder-repo::/home/user::workspace:${workspaceUuid}` - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - activeRepoId: 'folder-repo', - activeWorktreeId: worktreeId, - activeTabId: 'folder-tab', - activeWorktreeIdsOnShutdown: [worktreeId], - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'folder-tab', worktreeId, ptyId: 'folder-session' })] - } - } - - store.getState().hydrateWorkspaceSession(session, { - runtimeHostIdByWorkspaceSessionKey: { - [worktreeWorkspaceKey(worktreeId)]: 'runtime:env-1' - } - }) - - // Why: id keeps the ::workspace: suffix, but path/displayName must resolve to the real folder so callers don't spawn against a missing cwd. - expect(store.getState().worktreesByRepo['folder-repo']).toEqual([ - expect.objectContaining({ id: worktreeId, path: '/home/user', displayName: 'user' }) - ]) - expect(store.getState().repos).toEqual([ - expect.objectContaining({ id: 'folder-repo', path: '/home/user' }) - ]) - }) - - it('avoids duplicate repo placeholders when a same-id local repo is already loaded', () => { - const store = createTestStore() - const worktreeId = 'same-repo::/srv/remote-wt' - store.setState({ - repos: [ - { - id: 'same-repo', - path: '/Users/me/same-repo', - displayName: 'Same repo', - badgeColor: '#000', - addedAt: 1, - connectionId: null, - executionHostId: 'local' - } - ], - worktreesByRepo: {} - }) - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - activeRepoId: 'same-repo', - activeWorktreeId: worktreeId, - activeTabId: 'remote-tab', - activeWorktreeIdsOnShutdown: [worktreeId], - tabsByWorktree: { - [worktreeId]: [ - makeTab({ - id: 'remote-tab', - worktreeId, - ptyId: 'remote-session' - }) - ] - } - } - - store.getState().hydrateWorkspaceSession(session, { - runtimeHostIdByWorkspaceSessionKey: { - [worktreeWorkspaceKey(worktreeId)]: 'runtime:env-1' - } - }) - - expect(store.getState().repos.map((repo) => `${repo.id}:${repo.executionHostId}`)).toEqual([ - 'same-repo:local' - ]) - expect(store.getState().worktreesByRepo['same-repo']).toEqual([ - expect.objectContaining({ id: worktreeId, hostId: 'runtime:env-1' }) - ]) - expect(store.getState().tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([ - 'remote-tab' - ]) - }) - - it('hydrates runtime folder workspace tabs before remote folder catalogs load', () => { - const store = createTestStore() - const folderKey = folderWorkspaceKey('folder-1') - const session: WorkspaceSessionState = { - ...getDefaultWorkspaceSession(), - activeWorkspaceKey: folderKey, - activeWorktreeId: folderKey, - activeTabId: 'remote-folder-tab', - activeWorktreeIdsOnShutdown: [folderKey], - tabsByWorktree: { - [folderKey]: [ - makeTab({ - id: 'remote-folder-tab', - worktreeId: folderKey, - ptyId: 'remote-folder-session' - }) - ] - }, - remoteSessionIdsByTabId: { 'remote-folder-tab': 'remote-folder-session' } - } - - store.getState().hydrateWorkspaceSession(session, { - additionalValidWorkspaceKeys: [folderKey], - runtimeHostIdByWorkspaceSessionKey: { [folderKey]: 'runtime:env-1' } - }) - - expect(store.getState().tabsByWorktree[folderKey]?.map((tab) => tab.id)).toEqual([ - 'remote-folder-tab' - ]) - expect(store.getState().activeWorktreeId).toBe(folderKey) - expect(store.getState().activeWorkspaceKey).toBe(folderKey) - expect(store.getState().pendingReconnectWorktreeIds).toEqual([folderKey]) - expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({ - 'remote-folder-tab': 'remote-folder-session' - }) - expect(store.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({ - [folderKey]: 'runtime:env-1' - }) - }) - - it('moves restored active focus from a dead split leaf to a pty-backed sibling', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - const liveLeftLeafId = '9ee09218-72a5-4e1c-b075-729e937d4e29' - const liveRightLeafId = 'f5fc66b1-ec43-404b-b7b0-a06f0db34940' - const deadActiveLeafId = 'fbf63fd9-34d6-4387-9109-562f7c02bc4c' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: 'tab-1', - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'old-pty' })] - }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: liveLeftLeafId }, - second: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: liveRightLeafId }, - second: { type: 'leaf', leafId: deadActiveLeafId } - } - }, - activeLeafId: deadActiveLeafId, - expandedLeafId: null, - ptyIdsByLeafId: { - [liveLeftLeafId]: 'daemon-session-left', - [liveRightLeafId]: 'daemon-session-right' - }, - buffersByLeafId: { - [deadActiveLeafId]: 'retained scrollback' - } - } - } - } - - store.getState().hydrateWorkspaceSession(session) - - // Why: restart can preserve scrollback for an exited pane, so focus must land on a live PTY-backed pane, not the dead leaf. - expect(store.getState().terminalLayoutsByTabId['tab-1']?.activeLeafId).toBe(liveLeftLeafId) - }) - - it('hydrates floating terminal tabs even though they are not repo worktrees', () => { - const store = createTestStore() - const session: WorkspaceSessionState = { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: { - [FLOATING_TERMINAL_WORKTREE_ID]: [ - makeTab({ - id: 'floating-tab-1', - worktreeId: FLOATING_TERMINAL_WORKTREE_ID, - ptyId: 'floating-pty-1' - }) - ] - }, - terminalLayoutsByTabId: { - 'floating-tab-1': makeLayout() - }, - activeTabIdByWorktree: { - [FLOATING_TERMINAL_WORKTREE_ID]: 'floating-tab-1' - }, - activeWorktreeIdsOnShutdown: [FLOATING_TERMINAL_WORKTREE_ID] - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().tabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toHaveLength(1) - expect(store.getState().activeTabIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toBe( - 'floating-tab-1' - ) - expect(store.getState().pendingReconnectWorktreeIds).toEqual([FLOATING_TERMINAL_WORKTREE_ID]) - }) - it('batches restored terminal reconnect wake hints into one store update', async () => { const store = createTestStore() const worktreeId = 'repo1::/wt-1' @@ -450,252 +152,6 @@ describe('hydrateWorkspaceSession', () => { ]) }) - it('stashes deferred SSH session ids for worktrees not yet in worktreesByRepo', async () => { - // Cold-start SSH rows may lack worktree metadata; infer repo from composite ID or restored panes report inactive SSH. - const store = createTestStore() - const worktreeId = 'repo1::/home/user/remote-project' - const sshSessionId = 'ssh:ssh-target-1@@pty-7' - seedStore(store, { - repos: [{ ...TEST_REPO, connectionId: 'ssh-target-1' }], - worktreesByRepo: {} - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: 'tab-1', - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: null })] - }, - terminalLayoutsByTabId: {}, - activeWorktreeIdsOnShutdown: [worktreeId], - remoteSessionIdsByTabId: { 'tab-1': sshSessionId } - } - - store.getState().hydrateWorkspaceSession(session) - await store.getState().reconnectPersistedTerminals() - - expect(store.getState().deferredSshSessionIdsByTabId).toMatchObject({ - 'tab-1': sshSessionId - }) - }) - - it('stops deferring a session once its SSH target is known-absent, but keeps deferring present targets', async () => { - // Authoritative target removal makes deferred sessions dead liveness evidence (#9911); skip them or orphan sweep pins dead tabs. Disconnected present targets still defer. - const store = createTestStore() - const goneWt = 'repo-gone::/home/user/remote-gone' - const liveWt = 'repo-live::/home/user/remote-live' - seedStore(store, { - repos: [ - { ...TEST_REPO, id: 'repo-gone', connectionId: 'ssh-target-removed' }, - { ...TEST_REPO, id: 'repo-live', connectionId: 'ssh-target-present' } - ], - worktreesByRepo: {}, - sshTargetsHydrated: true, - sshTargetLabels: new Map([['ssh-target-present', 'Present']]) - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo-live', - activeWorktreeId: liveWt, - activeTabId: 'tab-live', - tabsByWorktree: { - [goneWt]: [makeTab({ id: 'tab-gone', worktreeId: goneWt, ptyId: null })], - [liveWt]: [makeTab({ id: 'tab-live', worktreeId: liveWt, ptyId: null })] - }, - terminalLayoutsByTabId: {}, - activeWorktreeIdsOnShutdown: [goneWt, liveWt], - remoteSessionIdsByTabId: { - 'tab-gone': 'ssh:ssh-target-removed@@pty-7', - 'tab-live': 'ssh:ssh-target-present@@pty-8' - } - } - - store.getState().hydrateWorkspaceSession(session) - await store.getState().reconnectPersistedTerminals() - - expect(store.getState().deferredSshSessionIdsByTabId['tab-gone']).toBeUndefined() - expect(store.getState().pendingReconnectPtyIdByTabId['tab-gone']).toBeUndefined() - expect(store.getState().deferredSshSessionIdsByTabId['tab-live']).toBe( - 'ssh:ssh-target-present@@pty-8' - ) - }) - - it('resets persisted agent titles to the fallback label on hydration', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: 'tab-1', - terminalLayoutsByTabId: {}, - tabsByWorktree: { - [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, title: '* Claude done', ptyId: '207' })] - } - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().tabsByWorktree[worktreeId]).toEqual([ - expect.objectContaining({ - id: 'tab-1', - title: 'Terminal 1', - ptyId: null - }) - ]) - }) - - it('hydrates the default-tab idempotency marker', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: null, - terminalLayoutsByTabId: {}, - tabsByWorktree: {}, - defaultTerminalTabsAppliedByWorktreeId: { [worktreeId]: true } - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().defaultTerminalTabsAppliedByWorktreeId).toEqual({ - [worktreeId]: true - }) - }) - - it('seeds worktree nav history with the restored active worktree', () => { - // Seed restored workspace at history[0] so the first switch enables Back. - const store = createTestStore() - const worktreeId = 'repo1::/wt-1' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })] - } - }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().worktreeNavHistory).toEqual([worktreeId]) - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('restores the active repo main worktree when the session has no active terminal tabs', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-main' - seedStore(store, { - worktreesByRepo: { - repo1: [ - makeWorktree({ - id: worktreeId, - repoId: 'repo1', - path: '/wt-main', - isMainWorktree: true - }) - ] - } - }) - - store.getState().hydrateWorkspaceSession({ - activeRepoId: 'repo1', - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - }) - - expect(store.getState().activeWorktreeId).toBe(worktreeId) - expect(store.getState().activeWorkspaceKey).toBe(`worktree:${worktreeId}`) - expect(store.getState().worktreeNavHistory).toEqual([worktreeId]) - }) - - it('ignores a persisted workspace key that disagrees with the restored active worktree', () => { - const store = createTestStore() - const worktreeId = 'repo1::/wt-current' - const staleFolderKey = folderWorkspaceKey('folder-stale') - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-current' })] - } - }) - - store.getState().hydrateWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: worktreeId, - activeWorkspaceKey: staleFolderKey - }, - { additionalValidWorkspaceKeys: [staleFolderKey] } - ) - - expect(store.getState().activeWorkspaceKey).toBe(worktreeWorkspaceKey(worktreeId)) - }) - - it('leaves nav history empty when no active worktree is restored', () => { - const store = createTestStore() - seedStore(store, { worktreesByRepo: {} }) - - // Seed stale history to prove hydration actively replaces it. - store.setState({ worktreeNavHistory: ['stale-a', 'stale-b'], worktreeNavHistoryIndex: 1 }) - - const session: WorkspaceSessionState = { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().worktreeNavHistory).toEqual([]) - expect(store.getState().worktreeNavHistoryIndex).toBe(-1) - }) - - it('drops invalid restored worktree from nav history seed', () => { - // Seed only validated selection or deleted workspaces occupy history[0] and break Back. - const store = createTestStore() - seedStore(store, { worktreesByRepo: { repo1: [] } }) - - // Seed stale history to prove invalid selection actively clears it. - store.setState({ worktreeNavHistory: ['stale-a', 'stale-b'], worktreeNavHistoryIndex: 1 }) - - const session: WorkspaceSessionState = { - activeRepoId: 'repo1', - activeWorktreeId: 'repo1::/missing', - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - } - - store.getState().hydrateWorkspaceSession(session) - - expect(store.getState().activeWorktreeId).toBeNull() - expect(store.getState().worktreeNavHistory).toEqual([]) - expect(store.getState().worktreeNavHistoryIndex).toBe(-1) - }) - it('records a subsequent visit on top of the hydration seed so Back is enabled after the first click', () => { // Restored history[0] enables Back on the first sidebar click. const store = createTestStore() @@ -726,38 +182,3 @@ describe('hydrateWorkspaceSession', () => { expect(canGoBackWorktreeHistory(store.getState())).toBe(true) }) }) - -describe('hydrationSucceeded flag (issue #1158)', () => { - it('defaults to false so the session writer is gated off at startup', () => { - // Gate persistence until clean hydration so startup errors cannot overwrite saved state with empty snapshots. - const store = createTestStore() - expect(store.getState().hydrationSucceeded).toBe(false) - }) - - it('setHydrationSucceeded toggles the flag both ways', () => { - const store = createTestStore() - store.getState().setHydrationSucceeded(true) - expect(store.getState().hydrationSucceeded).toBe(true) - store.getState().setHydrationSucceeded(false) - expect(store.getState().hydrationSucceeded).toBe(false) - }) - - it('hydrateWorkspaceSession does not flip hydrationSucceeded on its own', () => { - // Why: hydration can populate state then throw downstream, so App.tsx flips the flag only after a clean return. - const store = createTestStore() - const wt = 'repo1::/wt' - seedStore(store, { - worktreesByRepo: { repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/wt' })] } - }) - - store.getState().hydrateWorkspaceSession({ - activeRepoId: 'repo1', - activeWorktreeId: wt, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - }) - - expect(store.getState().hydrationSucceeded).toBe(false) - }) -}) diff --git a/src/renderer/src/store/slices/ui-acknowledge-agents-clock-skew.test.ts b/src/renderer/src/store/slices/ui-acknowledge-agents-clock-skew.test.ts deleted file mode 100644 index bf4a854a52f..00000000000 --- a/src/renderer/src/store/slices/ui-acknowledge-agents-clock-skew.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createUIStore } from './ui-slice-test-harness' -import type { AppState } from '../types' -import type { AgentStatusEntry } from '../../../../shared/agent-status-types' -import type { TerminalTab } from '../../../../shared/terminal-tab-types' -import { makePaneKey } from '../../../../shared/stable-pane-id' - -// Ahead-of-client host clocks kept ackAt below turn timestamps, leaving rows unread and auto-ack looping into React #185. - -const NOW = new Date('2026-06-02T12:00:00Z').getTime() -const SKEW_MS = 90_000 -const LEAF_ID = '11111111-1111-4111-8111-111111111111' -const PANE_KEY = makePaneKey('tab-1', LEAF_ID) - -function makeAgentEntry(overrides: Partial = {}): AgentStatusEntry { - return { - state: 'done', - prompt: 'Review complete', - updatedAt: NOW, - stateStartedAt: NOW, - agentType: 'codex', - paneKey: PANE_KEY, - stateHistory: [], - ...overrides - } -} - -function makeTerminalTab(id: string, worktreeId: string): TerminalTab { - return { - id, - worktreeId, - ptyId: null, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: NOW - } -} - -describe('acknowledgeAgents with a clock-skewed execution host', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(NOW) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('clears unread for a live turn stamped ahead of the local clock in one acknowledge', () => { - const store = createUIStore() - const futureStartedAt = NOW + SKEW_MS - store.setState({ - tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] }, - agentStatusByPaneKey: { - [PANE_KEY]: makeAgentEntry({ stateStartedAt: futureStartedAt, updatedAt: futureStartedAt }) - } - } as Partial) - - store.getState().acknowledgeAgents([PANE_KEY]) - - const ackAt = store.getState().acknowledgedAgentsByPaneKey[PANE_KEY] - expect(ackAt).toBe(futureStartedAt) - expect(ackAt < futureStartedAt).toBe(false) - }) - - it('stops rewriting the ack map once a future-stamped turn is acknowledged', () => { - const store = createUIStore() - const futureStartedAt = NOW + SKEW_MS - store.setState({ - agentStatusByPaneKey: { - [PANE_KEY]: makeAgentEntry({ stateStartedAt: futureStartedAt, updatedAt: futureStartedAt }) - } - } as Partial) - - store.getState().acknowledgeAgents([PANE_KEY]) - const firstMap = store.getState().acknowledgedAgentsByPaneKey - - // Later millisecond, same turn: the retry that used to allocate a new map (and re-render forever). - vi.setSystemTime(NOW + 1_000) - store.getState().acknowledgeAgents([PANE_KEY]) - - expect(store.getState().acknowledgedAgentsByPaneKey).toBe(firstMap) - }) - - it('covers a retained row and a future history event on the same pane', () => { - const store = createUIStore() - const futureHistoryAt = NOW + SKEW_MS - store.setState({ - retainedAgentsByPaneKey: { - [PANE_KEY]: { - entry: makeAgentEntry({ - stateStartedAt: NOW + 1_000, - stateHistory: [{ state: 'blocked', prompt: 'p', startedAt: futureHistoryAt }] - }), - worktreeId: 'wt-1', - tab: makeTerminalTab('tab-1', 'wt-1'), - agentType: 'codex', - startedAt: NOW + 1_000 - } - } - } as Partial) - - store.getState().acknowledgeAgents([PANE_KEY]) - - expect(store.getState().acknowledgedAgentsByPaneKey[PANE_KEY]).toBe(futureHistoryAt) - }) - - it('covers a future-stamped migration-unsupported row, which Activity renders as a blocked event', () => { - const store = createUIStore() - const futureUpdatedAt = NOW + SKEW_MS - store.setState({ - migrationUnsupportedByPtyId: { - 'pty-1': { - ptyId: 'pty-1', - paneKey: PANE_KEY, - reason: 'legacy-numeric-pane-key', - source: 'ssh', - updatedAt: futureUpdatedAt - } - } - } as Partial) - - store.getState().acknowledgeAgents([PANE_KEY]) - - expect(store.getState().acknowledgedAgentsByPaneKey[PANE_KEY]).toBe(futureUpdatedAt) - }) -}) diff --git a/src/renderer/src/store/slices/ui-agent-send-target.test.ts b/src/renderer/src/store/slices/ui-agent-send-target.test.ts index dd36d16813b..039486fa42a 100644 --- a/src/renderer/src/store/slices/ui-agent-send-target.test.ts +++ b/src/renderer/src/store/slices/ui-agent-send-target.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import { makePaneKey } from '../../../../shared/stable-pane-id' -import { structuredAgentSessionPaneKey } from '../../../../shared/agent-session/view/structured-agent-session-projection' +import '../../../../shared/agent-session/view/structured-agent-session-projection' import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' import type { AppState } from '../types' import { createUIStore } from './ui-slice-test-harness' @@ -189,50 +189,6 @@ describe('createUISlice agent send target mode', () => { } as Partial) } - it('opens target mode with derived eligible and disabled pane keys', () => { - const store = createAgentSendStore() - seedAgentSendState(store) - - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'diff-notes', - prompt: 'Review this', - label: 'All unsent notes', - launchSource: 'notes_send' - }) - - expect(store.getState().agentSendPopoverTargetMode).toMatchObject({ - id: 'send-1', - eligiblePaneKeys: [readyPaneKey, workingPaneKey], - disabledPaneKeys: {}, - status: 'open' - }) - expect(store.getState().pendingRevealWorktree).toMatchObject({ - worktreeId, - behavior: 'auto', - highlight: true - }) - }) - - it('switches out of the activity view because send targets render on workspace cards', () => { - const store = createAgentSendStore() - seedAgentSendState(store) - store.getState().setSidebarBody('agents') - - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'diff-notes', - prompt: 'Review this', - label: 'All unsent notes', - launchSource: 'notes_send' - }) - - expect(store.getState().sidebarBody).toBe('workspaces') - expect(store.getState().pendingRevealWorktree).toMatchObject({ worktreeId }) - }) - it('disables sidebar target rows that need permission', async () => { const store = createAgentSendStore() seedAgentSendState(store) @@ -270,51 +226,6 @@ describe('createUISlice agent send target mode', () => { expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled() }) - it('does not reveal the sidebar when the current workspace has no eligible targets', () => { - const store = createAgentSendStore() - seedAgentSendState(store) - store.setState({ - terminalLayoutsByTabId: { - [tabId]: { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: readyLeafId }, - second: { type: 'leaf', leafId: workingLeafId } - }, - activeLeafId: readyLeafId, - expandedLeafId: null, - ptyIdsByLeafId: { - [readyLeafId]: 'pty-ready', - [workingLeafId]: 'pty-working' - } - } - }, - ptyIdsByTabId: { - [tabId]: [] - } - }) - - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'browser-annotations', - prompt: 'Review this', - label: 'Browser annotations', - launchSource: 'notes_send' - }) - - expect(store.getState().agentSendPopoverTargetMode).toMatchObject({ - id: 'send-1', - eligiblePaneKeys: [], - disabledPaneKeys: { - [readyPaneKey]: 'Terminal is no longer available', - [workingPaneKey]: 'Terminal is no longer available' - } - }) - expect(store.getState().pendingRevealWorktree).toBeNull() - }) - it('sends to the live leaf PTY, runs delivery callback, tracks followup, and closes', async () => { const store = createAgentSendStore() const onPromptDelivered = vi.fn() @@ -352,120 +263,6 @@ describe('createUISlice agent send target mode', () => { expect(store.getState().agentSendPopoverTargetMode).toBeNull() }) - const chatTabId = 'structured-agent-session-claude_1' - const chatPaneKey = structuredAgentSessionPaneKey(chatTabId, 'claude_1') - - function seedChatState( - store: StoreApi, - agentStatusByPaneKey: AppState['agentStatusByPaneKey'] - ): void { - store.setState({ - agentStatusByPaneKey, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - ptyIdsByTabId: {}, - unifiedTabsByWorktree: { - [worktreeId]: [ - { - id: chatTabId, - entityId: 'claude_1', - groupId: 'group-1', - worktreeId, - contentType: 'agent-session', - agentSessionAgent: 'claude', - label: 'Claude Chat', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - }) - } - - it('does not reveal the sidebar for a chat before its first turn, which has no row there', () => { - const store = createAgentSendStore() - seedChatState(store, {}) - - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'diff-notes', - prompt: 'Review this', - label: 'All unsent notes', - launchSource: 'notes_send' - }) - - expect(store.getState().agentSendPopoverTargetMode?.eligiblePaneKeys).toEqual([]) - expect(store.getState().pendingRevealWorktree).toBeNull() - }) - - it('sends to a structured chat by its session, not a terminal', async () => { - const store = createAgentSendStore() - const onPromptDelivered = vi.fn() - const now = Date.now() - seedChatState(store, { - [chatPaneKey]: { - state: 'done', - prompt: 'previous', - updatedAt: now, - stateStartedAt: now, - agentType: 'claude', - paneKey: chatPaneKey, - stateHistory: [] - } - }) - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'diff-notes', - prompt: 'Review this', - label: 'All unsent notes', - launchSource: 'notes_send', - onPromptDelivered - }) - expect(store.getState().agentSendPopoverTargetMode?.eligiblePaneKeys).toEqual([chatPaneKey]) - - await expect(store.getState().sendPromptToSidebarAgentTarget(chatPaneKey)).resolves.toBe(true) - - expect(mocks.sendStructuredAgentSessionMessage).toHaveBeenCalledWith({ - sessionId: 'claude_1', - target: { kind: 'local' }, - text: 'Review this', - callerKeepsText: true - }) - expect(mocks.relaunchFailedStructuredAgentSessionWithMessage).toHaveBeenCalledWith( - worktreeId, - 'claude_1', - 'Review this', - { callerKeepsText: true } - ) - expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled() - expect(onPromptDelivered).toHaveBeenCalledTimes(1) - expect(mocks.toastSuccess).toHaveBeenCalledWith('Sent to Claude') - }) - - it('sends nothing to a sidebar agent when every note is already on its way', async () => { - const store = createAgentSendStore() - const onPromptHandedOff = vi.fn() - seedAgentSendState(store) - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'diff-notes', - prompt: '', - label: 'All unsent notes', - launchSource: 'notes_send', - onPromptHandedOff - }) - - await expect(store.getState().sendPromptToSidebarAgentTarget(readyPaneKey)).resolves.toBe(false) - - expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled() - expect(onPromptHandedOff).not.toHaveBeenCalled() - }) - it('keeps target mode open and does not run delivery callback when send fails', async () => { const store = createAgentSendStore() const onPromptDelivered = vi.fn() @@ -495,31 +292,6 @@ describe('createUISlice agent send target mode', () => { }) }) - it('sends to a working agent row through the selected-target note helper', async () => { - const store = createAgentSendStore() - seedAgentSendState(store) - store.getState().openAgentSendPopoverTargetMode({ - id: 'send-1', - worktreeId, - source: 'browser-annotations', - prompt: 'Review this', - label: 'Browser annotations', - launchSource: 'notes_send' - }) - - await expect(store.getState().sendPromptToSidebarAgentTarget(workingPaneKey)).resolves.toBe( - true - ) - - expect(mocks.sendNotesToActiveAgentSession).toHaveBeenCalledWith({ - worktreeId, - prompt: 'Review this', - noteTarget: { tabId, leafId: workingLeafId } - }) - expect(mocks.toastSuccess).toHaveBeenCalledWith('Sent to Codex') - expect(store.getState().agentSendPopoverTargetMode).toBeNull() - }) - it('acknowledges delivery when the picker closes before the send completes', async () => { const store = createAgentSendStore() const onPromptDelivered = vi.fn() @@ -741,133 +513,4 @@ describe('createUISlice acknowledgeAgents notification dismissal', () => { // Nothing rebuilt twice; main still gets the subjects so it can retire what it announced. expect(dismiss).toHaveBeenCalledWith([], [livePaneKey, retainedPaneKey]) }) - - it('falls back to live entry worktree attribution and skips unresolved live entries', () => { - const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 }) - vi.stubGlobal('window', { api: { notifications: { dismiss } } }) - const store = createAgentSendStore() - const fallbackPaneKey = makePaneKey('tab-fallback', '44444444-4444-4444-8444-444444444444') - store.setState({ - tabsByWorktree: {}, - agentStatusByPaneKey: { - [fallbackPaneKey]: { - ...makeAgentEntry(fallbackPaneKey, 1_000), - worktreeId: 'wt-from-entry' - }, - [livePaneKey]: makeAgentEntry(livePaneKey, 2_000) - }, - retainedAgentsByPaneKey: {} - } as Partial) - - store.getState().acknowledgeAgents([fallbackPaneKey, livePaneKey]) - - expect(dismiss).toHaveBeenCalledWith( - [ - buildAgentNotificationId({ - worktreeId: 'wt-from-entry', - paneKey: fallbackPaneKey, - stateStartedAt: 1_000 - }) - ], - [fallbackPaneKey, livePaneKey] - ) - }) - - it('dedupes identical live and retained notification ids for the same pane', () => { - const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 }) - vi.stubGlobal('window', { api: { notifications: { dismiss } } }) - const store = createAgentSendStore() - store.setState({ - tabsByWorktree: { - 'wt-live': [makeTerminalTab(tabId, 'wt-live')] - }, - agentStatusByPaneKey: { - [livePaneKey]: makeAgentEntry(livePaneKey, 1_000) - }, - retainedAgentsByPaneKey: { - [livePaneKey]: { - entry: makeAgentEntry(livePaneKey, 1_000), - worktreeId: 'wt-live', - tab: makeTerminalTab(tabId, 'wt-live'), - agentType: 'codex', - startedAt: 1_000 - } - } - } as Partial) - - store.getState().acknowledgeAgents([livePaneKey]) - - expect(dismiss).toHaveBeenCalledWith( - [ - buildAgentNotificationId({ - worktreeId: 'wt-live', - paneKey: livePaneKey, - stateStartedAt: 1_000 - }) - ], - [livePaneKey] - ) - }) -}) - -describe('openDiffNotesSendMenuForActiveWorktree', () => { - function stubDiffNotesStore( - comments: { sentAt?: number }[], - activeWorktreeId: string | null = 'wt-1' - ): { store: StoreApi; setRightSidebarTab: ReturnType } { - const store = createAgentSendStore() - const setRightSidebarTab = vi.fn() - store.setState({ - activeWorktreeId, - getDiffComments: () => comments, - setRightSidebarTab, - setRightSidebarOpen: vi.fn() - } as unknown as Partial) - return { store, setRightSidebarTab } - } - - it('reveals Source Control and bumps the open request when unsent notes exist', () => { - const { store, setRightSidebarTab } = stubDiffNotesStore([{ sentAt: 10 }, {}]) - - expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(true) - expect(setRightSidebarTab).toHaveBeenCalledWith('source-control') - expect(store.getState().diffNotesSendMenuOpenRequest).toMatchObject({ - worktreeId: 'wt-1', - nonce: 1 - }) - expect(store.getState().diffNotesSendMenuOpenRequest?.issuedAt).toBeTypeOf('number') - - // A second request increments the nonce so the menu reopens. - expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(true) - expect(store.getState().diffNotesSendMenuOpenRequest).toMatchObject({ - worktreeId: 'wt-1', - nonce: 2 - }) - }) - - it('is a no-op when every note is already sent', () => { - const { store, setRightSidebarTab } = stubDiffNotesStore([{ sentAt: 10 }]) - - expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(false) - expect(setRightSidebarTab).not.toHaveBeenCalled() - expect(store.getState().diffNotesSendMenuOpenRequest).toBeNull() - }) - - it('is a no-op when there is no active worktree', () => { - const { store } = stubDiffNotesStore([{}], null) - - expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(false) - expect(store.getState().diffNotesSendMenuOpenRequest).toBeNull() - }) - - it('clears the request only for the matching worktree', () => { - const { store } = stubDiffNotesStore([{}]) - store.getState().openDiffNotesSendMenuForActiveWorktree() - - store.getState().consumeDiffNotesSendMenuOpenRequest('other-wt') - expect(store.getState().diffNotesSendMenuOpenRequest).not.toBeNull() - - store.getState().consumeDiffNotesSendMenuOpenRequest('wt-1') - expect(store.getState().diffNotesSendMenuOpenRequest).toBeNull() - }) }) diff --git a/src/renderer/src/store/slices/ui-contextual-tours.test.ts b/src/renderer/src/store/slices/ui-contextual-tours.test.ts deleted file mode 100644 index 3db02f6e587..00000000000 --- a/src/renderer/src/store/slices/ui-contextual-tours.test.ts +++ /dev/null @@ -1,542 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' -import type { ContextualTourId } from '../../../../shared/contextual-tours' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -const mocks = vi.hoisted(() => ({ - sendNotesToActiveAgentSession: vi.fn(), - track: vi.fn(), - toastMessage: vi.fn(), - toastSuccess: vi.fn(), - toastError: vi.fn() -})) - -vi.mock('@/lib/active-agent-note-send', () => ({ - activeAgentNotesSendFailureMessage: ( - status: string, - options: { explicitTarget?: boolean } = {} - ) => (options.explicitTarget ? `selected:${status}` : status), - sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession -})) - -vi.mock('@/lib/telemetry', () => ({ - track: mocks.track -})) - -vi.mock('sonner', () => ({ - toast: { - message: mocks.toastMessage, - success: mocks.toastSuccess, - error: mocks.toastError - } -})) - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -beforeEach(() => { - mocks.sendNotesToActiveAgentSession.mockReset() - mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' }) - mocks.track.mockReset() - mocks.toastMessage.mockReset() - mocks.toastSuccess.mockReset() - mocks.toastError.mockReset() -}) - -function stubContextualTourTargets(selectors: readonly string[]): void { - const selectorSet = new Set(selectors) - vi.stubGlobal('document', { - querySelector: vi.fn((selector: string) => - selectorSet.has(selector) - ? { - getBoundingClientRect: () => ({ - left: 10, - top: 10, - right: 110, - bottom: 50, - width: 100, - height: 40 - }) - } - : null - ) - }) -} - -describe('createUISlice contextual tours', () => { - function makeAutoTourEligibleUI(overrides: Partial = {}): PersistedUIState { - return makePersistedUI({ - contextualToursAutoEligible: true, - ...overrides - }) - } - - it('normalizes persisted contextual tour ids during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - contextualToursSeenIds: ['tasks', 'unknown', 'tasks', 'browser'] as never - }) - ) - - expect(store.getState().contextualToursSeenIds).toEqual(['tasks', 'browser']) - }) - - it('normalizes persisted contextual tour auto eligibility during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI()) - expect(store.getState().contextualToursAutoEligible).toBeNull() - - store.getState().hydratePersistedUI(makePersistedUI({ contextualToursAutoEligible: false })) - expect(store.getState().contextualToursAutoEligible).toBe(false) - - store - .getState() - .hydratePersistedUI(makePersistedUI({ contextualToursAutoEligible: 'yes' as never })) - expect(store.getState().contextualToursAutoEligible).toBeNull() - }) - - it('persists contextual tour auto eligibility once classified', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().setContextualToursAutoEligible(false) - store.getState().setContextualToursAutoEligible(false) - - expect(store.getState().contextualToursAutoEligible).toBe(false) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ contextualToursAutoEligible: false }) - }) - - it('marks contextual tours seen and persists them once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().markContextualToursSeen(['tasks']) - store.getState().markContextualToursSeen(['tasks']) - - expect(store.getState().contextualToursSeenIds).toEqual(['tasks']) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ contextualToursSeenIds: ['tasks'] }) - }) - - it('starts a tour only after persisted UI and required first target are ready', () => { - const store = createUIStore() - const tasksFirstSelector = '[data-contextual-tour-target="tasks-source-filters"]' - stubContextualTourTargets([tasksFirstSelector]) - - store.getState().requestContextualTour('tasks', 'tasks_open') - expect(store.getState().activeContextualTourId).toBeNull() - - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - store.getState().requestContextualTour('tasks', 'tasks_open') - - expect(store.getState().activeContextualTourId).toBe('tasks') - expect(store.getState().activeContextualTourStepIndex).toBe(0) - expect(store.getState().activeContextualTourSource).toBe('tasks_open') - expect(store.getState().contextualTourShownThisSession).toBe(true) - expect(store.getState().contextualToursSeenIds).toEqual([]) - }) - - it('stores whether the feature was interacted with before the tour request', () => { - const store = createUIStore() - const tasksFirstSelector = '[data-contextual-tour-target="tasks-source-filters"]' - stubContextualTourTargets([tasksFirstSelector]) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - - store.getState().recordFeatureInteraction('tasks') - store.getState().requestContextualTour('tasks', 'tasks_open') - - expect(store.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(true) - }) - - it('lets the caller preserve the pre-enable interaction snapshot for telemetry', () => { - const store = createUIStore() - const tasksFirstSelector = '[data-contextual-tour-target="tasks-source-filters"]' - stubContextualTourTargets([tasksFirstSelector]) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - - store.getState().recordFeatureInteraction('tasks') - store.getState().requestContextualTour('tasks', 'tasks_open', false) - - expect(store.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false) - }) - - it('does not bias first-visit contextual tour telemetry from navigation actions', () => { - stubContextualTourTargets([ - '[data-contextual-tour-target="tasks-source-filters"]', - '[data-contextual-tour-target="automations-create"]', - '[data-contextual-tour-target="workspace-creation-project"]' - ]) - - const tasksStore = createUIStore() - tasksStore.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - tasksStore.getState().openTaskPage() - tasksStore.getState().requestContextualTour('tasks', 'tasks_open') - expect(tasksStore.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false) - - const automationsStore = createUIStore() - automationsStore.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - automationsStore.getState().openAutomationsPage() - automationsStore.getState().requestContextualTour('automations', 'automations_open') - expect(automationsStore.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe( - false - ) - - const composerStore = createUIStore() - composerStore.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - composerStore.getState().openModal('new-workspace-composer') - composerStore.getState().requestContextualTour('workspace-creation', 'workspace_creation_modal') - expect(composerStore.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false) - }) - - it('does not mark seen when the required first target is absent', () => { - const store = createUIStore() - stubContextualTourTargets([]) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - - store.getState().requestContextualTour('tasks', 'tasks_open') - - expect(store.getState().activeContextualTourId).toBeNull() - expect(store.getState().contextualToursSeenIds).toEqual([]) - expect(store.getState().contextualTourShownThisSession).toBe(false) - }) - - it('does not start while a root confirmation surface is visible', () => { - const store = createUIStore() - stubContextualTourTargets(['[data-contextual-tour-target="tasks-source-filters"]']) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - - store.getState().setContextualToursBlockingSurfaceVisible(true) - store.getState().requestContextualTour('tasks', 'tasks_open') - - expect(store.getState().activeContextualTourId).toBeNull() - expect(store.getState().contextualTourShownThisSession).toBe(false) - }) - - it('does not auto-start tours for profiles that are not eligible', () => { - const store = createUIStore() - stubContextualTourTargets(['[data-contextual-tour-target="tasks-source-filters"]']) - store.getState().hydratePersistedUI(makePersistedUI({ contextualToursAutoEligible: false })) - - store.getState().requestContextualTour('tasks', 'tasks_open') - - expect(store.getState().activeContextualTourId).toBeNull() - expect(store.getState().contextualTourShownThisSession).toBe(false) - }) - - it('force-starts a tour from an explicit user action even after auto tours are unavailable', () => { - const store = createUIStore() - stubContextualTourTargets([ - '[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]' - ]) - store.getState().hydratePersistedUI( - makePersistedUI({ - contextualToursAutoEligible: false, - contextualToursSeenIds: ['workspace-agent-sessions'] - }) - ) - - store - .getState() - .requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, { - force: true - }) - - expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions') - expect(store.getState().activeContextualTourSource).toBe('setup_guide_parallel_work') - expect(store.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false) - }) - - it('preserves the bounded setup-guide parallel-work source on forced tour requests', () => { - const store = createUIStore() - stubContextualTourTargets([ - '[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]' - ]) - store.getState().hydratePersistedUI( - makePersistedUI({ - contextualToursAutoEligible: false, - contextualToursSeenIds: ['workspace-agent-sessions'] - }) - ) - - store - .getState() - .requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, { - force: true - }) - - expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions') - expect(store.getState().activeContextualTourSource).toBe('setup_guide_parallel_work') - }) - - it('allows only workspace creation over its workspace composer modal', () => { - const store = createUIStore() - stubContextualTourTargets([ - '[data-contextual-tour-target="tasks-source-filters"]', - '[data-contextual-tour-target="workspace-creation-project"]' - ]) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - - store.getState().openModal('new-workspace-composer') - store.getState().requestContextualTour('tasks', 'tasks_open') - expect(store.getState().activeContextualTourId).toBeNull() - - store.getState().requestContextualTour('workspace-creation', 'workspace_creation_modal') - expect(store.getState().activeContextualTourId).toBe('workspace-creation') - }) - - it('advances across visible steps and leaves completion to the overlay', () => { - const store = createUIStore() - const visibleSelectors = [ - '[data-contextual-tour-target="browser-grab-control"]', - '[data-contextual-tour-target="browser-annotation-control"]', - '[data-contextual-tour-target="browser-import-cookies-control"]' - ] - stubContextualTourTargets(visibleSelectors) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - store.getState().requestContextualTour('browser', 'browser_visible') - - store.getState().advanceContextualTour() - expect(store.getState().activeContextualTourStepIndex).toBe(1) - - store.getState().advanceContextualTour() - expect(store.getState().activeContextualTourId).toBe('browser') - expect(store.getState().activeContextualTourStepIndex).toBe(2) - }) - - it('advances the browser tour to the cookie step before Import Cookies is measurable', () => { - const store = createUIStore() - const visibleSelectors = [ - '[data-contextual-tour-target="browser-grab-control"]', - '[data-contextual-tour-target="browser-annotation-control"]' - ] - stubContextualTourTargets(visibleSelectors) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - store.getState().requestContextualTour('browser', 'browser_visible') - - store.getState().advanceContextualTour() - expect(store.getState().activeContextualTourStepIndex).toBe(1) - - store.getState().advanceContextualTour() - expect(store.getState().activeContextualTourStepIndex).toBe(2) - }) - - it('advances the active split step when the split command interaction is recorded', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - stubContextualTourTargets([ - '[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]', - '[data-contextual-tour-target="workspace-create-control"]' - ]) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI()) - setMock.mockClear() - store - .getState() - .requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, { - force: true - }) - - store.getState().recordFeatureInteraction('terminal-pane-split') - - expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions') - expect(store.getState().activeContextualTourStepIndex).toBe(1) - expect(store.getState().featureInteractions['terminal-pane-split']).toMatchObject({ - interactionCount: 1 - }) - }) - - it('opens the sidebar and advances the split step when the create-worktree target is hidden', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - stubContextualTourTargets([ - '[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]' - ]) - store.getState().hydratePersistedUI(makeAutoTourEligibleUI({ sidebarOpen: false })) - store - .getState() - .requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, { - force: true - }) - - store.getState().recordFeatureInteraction('terminal-pane-split') - - expect(store.getState().sidebarOpen).toBe(true) - expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions') - expect(store.getState().activeContextualTourStepIndex).toBe(1) - expect(store.getState().contextualToursSeenIds).toEqual([]) - expect(store.getState().lastCompletedContextualTourId).toBeNull() - }) - - it('marks the active contextual tour suppressed when its owning source disables', () => { - const store = createUIStore() - store.setState({ - activeContextualTourId: 'browser', - activeContextualTourStepIndex: 0, - activeContextualTourSource: 'browser_visible', - activeContextualTourWasFeaturePreviouslyInteracted: false, - contextualTourShownThisSession: true - }) - - store.getState().suppressContextualTour('tasks', 'tasks_open') - expect(store.getState().activeContextualTourSuppressed).toBe(false) - - store.getState().suppressContextualTour('browser', 'browser_visible') - expect(store.getState().activeContextualTourSuppressed).toBe(true) - }) - - it('keeps an intentionally detached contextual tour active when its owning source disables', () => { - const store = createUIStore() - store.setState({ - activeContextualTourId: 'workspace-agent-sessions', - activeContextualTourStepIndex: 3, - activeContextualTourSource: 'workspace_agent_sessions_visible', - activeContextualTourWasFeaturePreviouslyInteracted: false, - contextualTourShownThisSession: true - }) - - store - .getState() - .detachContextualTourSource('workspace-agent-sessions', 'workspace_agent_sessions_visible') - store - .getState() - .suppressContextualTour('workspace-agent-sessions', 'workspace_agent_sessions_visible') - - expect(store.getState().activeContextualTourSourceDetached).toBe(true) - expect(store.getState().activeContextualTourSuppressed).toBe(false) - expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions') - }) - - it('cancels a not-yet-rendered tour without persistence churn', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - store.setState({ - activeContextualTourId: 'tasks', - activeContextualTourStepIndex: 0, - activeContextualTourSource: 'tasks_open', - contextualTourShownThisSession: true - }) - - store.getState().cancelContextualTour('tasks') - - expect(store.getState().activeContextualTourId).toBeNull() - expect(store.getState().contextualTourShownThisSession).toBe(false) - expect(store.getState().lastCompletedContextualTourId).toBeNull() - expect(store.getState().contextualToursSeenIds).toEqual([]) - expect(setMock).not.toHaveBeenCalled() - }) - - it('preserves the session guard when canceling an already-rendered tour', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - store.setState({ - activeContextualTourId: 'tasks', - activeContextualTourStepIndex: 0, - activeContextualTourSource: 'tasks_open', - contextualTourShownThisSession: true, - contextualToursSeenIds: ['tasks'] - }) - - store.getState().cancelContextualTour('tasks') - - expect(store.getState().activeContextualTourId).toBeNull() - expect(store.getState().contextualTourShownThisSession).toBe(true) - expect(store.getState().contextualToursSeenIds).toEqual(['tasks']) - expect(setMock).not.toHaveBeenCalled() - }) - - it('dismisses active tours as seen', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - store.setState({ - activeContextualTourId: 'automations', - activeContextualTourStepIndex: 0, - activeContextualTourSource: 'automations_open', - contextualTourShownThisSession: true - }) - - store.getState().dismissContextualTour('automations') - - expect(store.getState().activeContextualTourId).toBeNull() - expect(store.getState().contextualToursSeenIds).toEqual(['automations']) - expect(store.getState().lastCompletedContextualTourId).toBeNull() - expect(setMock).toHaveBeenCalledWith({ contextualToursSeenIds: ['automations'] }) - }) - - it('ignores stale dismissals for a different active tour', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - store.setState({ - activeContextualTourId: 'tasks', - activeContextualTourStepIndex: 0, - activeContextualTourSource: 'tasks_open', - contextualTourShownThisSession: true - }) - - store.getState().dismissContextualTour('browser') - - expect(store.getState().activeContextualTourId).toBe('tasks') - expect(store.getState().contextualToursSeenIds).toEqual([]) - expect(setMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/slices/ui-host-filter-sync.test.ts b/src/renderer/src/store/slices/ui-host-filter-sync.test.ts index 566b45e4c4e..bb15fb3c0c8 100644 --- a/src/renderer/src/store/slices/ui-host-filter-sync.test.ts +++ b/src/renderer/src/store/slices/ui-host-filter-sync.test.ts @@ -7,20 +7,6 @@ beforeEach(() => { afterEach(() => vi.unstubAllGlobals()) describe('host visibility across saved UI broadcasts', () => { - it('keeps a newly revealed remote host when an older UI snapshot arrives', () => { - const store = createUIStore() - const previous = makePersistedUI({ - workspaceHostScope: 'local', - visibleWorkspaceHostIds: ['local'] - }) - store.getState().hydratePersistedUI(previous) - - store.getState().setVisibleWorkspaceHostIds(['local', 'runtime:m4air']) - store.getState().hydratePersistedUI(previous, 'sync') - - expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'runtime:m4air']) - }) - it('keeps All hosts while the prior selection is being saved', () => { const store = createUIStore() const previous = makePersistedUI({ workspaceHostScope: 'all', visibleWorkspaceHostIds: null }) @@ -40,19 +26,4 @@ describe('host visibility across saved UI broadcasts', () => { expect(store.getState().workspaceHostScope).toBe('all') expect(store.getState().visibleWorkspaceHostIds).toBeNull() }) - - it('accepts another client’s host selection when there is no local edit', () => { - const store = createUIStore() - store.getState().hydratePersistedUI(makePersistedUI()) - store.getState().hydratePersistedUI( - makePersistedUI({ - workspaceHostScope: 'runtime:m4air', - visibleWorkspaceHostIds: ['runtime:m4air'] - }), - 'sync' - ) - - expect(store.getState().workspaceHostScope).toBe('runtime:m4air') - expect(store.getState().visibleWorkspaceHostIds).toEqual(['runtime:m4air']) - }) }) diff --git a/src/renderer/src/store/slices/ui-hydration-view-layout.test.ts b/src/renderer/src/store/slices/ui-hydration-view-layout.test.ts deleted file mode 100644 index 2bbdb2bd34e..00000000000 --- a/src/renderer/src/store/slices/ui-hydration-view-layout.test.ts +++ /dev/null @@ -1,742 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultUIState } from '../../../../shared/constants' -import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' -import type { Repo } from '../../../../shared/repo-types' -import type { AppState } from '../types' -import { getSetupScriptPromptDismissalKey } from '../../lib/setup-script-prompt' -import { getRepoHostIdentityForParts } from './repo-host-identity' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -const mocks = vi.hoisted(() => ({ - sendNotesToActiveAgentSession: vi.fn(), - track: vi.fn(), - toastMessage: vi.fn(), - toastSuccess: vi.fn(), - toastError: vi.fn() -})) - -vi.mock('@/lib/active-agent-note-send', () => ({ - activeAgentNotesSendFailureMessage: ( - status: string, - options: { explicitTarget?: boolean } = {} - ) => (options.explicitTarget ? `selected:${status}` : status), - sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession -})) - -vi.mock('@/lib/telemetry', () => ({ - track: mocks.track -})) - -vi.mock('sonner', () => ({ - toast: { - message: mocks.toastMessage, - success: mocks.toastSuccess, - error: mocks.toastError - } -})) - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -beforeEach(() => { - mocks.sendNotesToActiveAgentSession.mockReset() - mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' }) - mocks.track.mockReset() - mocks.toastMessage.mockReset() - mocks.toastSuccess.mockReset() - mocks.toastError.mockReset() -}) - -describe('sidebar reveal actions', () => { - it('skip reveals while the activity view is showing instead of switching bodies', () => { - const store = createUIStore() - store.getState().setSidebarBody('agents') - - store.getState().revealWorktreeInSidebar('wt-1', { highlight: true }) - store.getState().revealSidebarRow('repo:r1') - - expect(store.getState().sidebarBody).toBe('agents') - expect(store.getState().pendingRevealWorktree).toBeNull() - expect(store.getState().pendingRevealSidebarRow).toBeNull() - }) - - it('reveal after an explicit switch to the workspace list', () => { - const store = createUIStore() - store.getState().setSidebarBody('agents') - - store.getState().setSidebarBody('workspaces') - store.getState().revealWorktreeInSidebar('wt-1', { highlight: true }) - store.getState().revealSidebarRow('repo:r1') - - expect(store.getState().sidebarBody).toBe('workspaces') - expect(store.getState().pendingRevealWorktree).toBeNull() - expect(store.getState().pendingRevealSidebarRow?.rowKey).toBe('repo:r1') - const oldRow = store.getState().pendingRevealSidebarRow - store.getState().revealWorktreeInSidebar('wt-2', { rowKey: 'pinned:wt-2' }) - const newer = store.getState().pendingRevealWorktree - store.getState().clearPendingRevealSidebarRow(oldRow) - store.getState().revealWorktreeInSidebar('wt-2', { rowKey: 'pinned:wt-2' }) - store.getState().clearPendingRevealWorktreeId(newer) - expect(store.getState().pendingRevealSidebarRow).toBeNull() - expect(store.getState().pendingRevealWorktree?.rowKey).toBe('pinned:wt-2') - }) -}) - -describe('createUISlice hydratePersistedUI', () => { - it('defaults persisted right sidebar visibility to open', () => { - expect(getDefaultUIState().rightSidebarOpen).toBe(true) - }) - - it('defaults to showing sleeping workspaces', () => { - const store = createUIStore() - - expect(store.getState().showSleepingWorkspaces).toBe(true) - }) - - it('defaults the default-branch sleeping exemption to on', () => { - expect(getDefaultUIState().alwaysShowDefaultBranchWorkspace).toBe(true) - expect(createUIStore().getState().alwaysShowDefaultBranchWorkspace).toBe(true) - }) - - it('treats a legacy profile with no default-branch exemption key as opted in', () => { - // Pre-#8873 profiles omit this key; absence must enable the exemption rather than hide main again. - const store = createUIStore() - const legacy = makePersistedUI() - delete (legacy as Partial).alwaysShowDefaultBranchWorkspace - - store.getState().hydratePersistedUI(legacy, 'startup') - - expect(store.getState().alwaysShowDefaultBranchWorkspace).toBe(true) - }) - - it('preserves an explicit default-branch exemption opt-out on hydration', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI(makePersistedUI({ alwaysShowDefaultBranchWorkspace: false }), 'startup') - - expect(store.getState().alwaysShowDefaultBranchWorkspace).toBe(false) - }) - - it('defaults workspace host scope to all hosts', () => { - expect(getDefaultUIState().workspaceHostScope).toBe('all') - expect(createUIStore().getState().workspaceHostScope).toBe('all') - expect(getDefaultUIState().visibleWorkspaceHostIds).toBeNull() - expect(createUIStore().getState().visibleWorkspaceHostIds).toBeNull() - expect(getDefaultUIState().workspaceHostOrder).toEqual([]) - expect(createUIStore().getState().workspaceHostOrder).toEqual([]) - expect(getDefaultUIState().manualRepoOrder).toEqual([]) - expect(createUIStore().getState().manualRepoOrder).toEqual([]) - }) - - it('defaults the persisted active view to terminal', () => { - expect(getDefaultUIState().activeView).toBe('terminal') - expect(createUIStore().getState().activeView).toBe('terminal') - }) - - it('restores the persisted active top-level view on hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'tasks' }), 'startup') - - expect(store.getState().activeView).toBe('tasks') - }) - - it('falls back to terminal when persisted active view is missing (older data)', () => { - const store = createUIStore() - store.setState({ activeView: 'tasks' }) - - store.getState().hydratePersistedUI( - { - ...makePersistedUI(), - activeView: undefined as unknown as PersistedUIState['activeView'] - }, - 'startup' - ) - - expect(store.getState().activeView).toBe('terminal') - }) - - it('restores a persisted skills view', () => { - const store = createUIStore() - store.setState({ activeView: 'tasks' }) - - store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'skills' }), 'startup') - - expect(store.getState().activeView).toBe('skills') - }) - - it('falls back to terminal when the persisted active view is not a known view', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - activeView: 'not-a-real-view' as unknown as PersistedUIState['activeView'] - }), - 'startup' - ) - - expect(store.getState().activeView).toBe('terminal') - }) - - it('keeps a persisted activity view when the settings fetch failed', () => { - // A failed window.api.settings.get() leaves settings null; downgrading here would let the - // persisted-UI writer overwrite the saved view with terminal. - const store = createUIStore() - store.setState({ settings: null as unknown as AppState['settings'] }) - - store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'activity' }), 'startup') - - expect(store.getState().activeView).toBe('activity') - }) - - it('restores a default-on view (mobile) even when its nav button is hidden', () => { - const store = createUIStore() - store.setState({ - settings: { showMobileButton: false } as AppState['settings'] - }) - - store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'mobile' }), 'startup') - - expect(store.getState().activeView).toBe('mobile') - }) - - it('does not overwrite the current view on a later cross-window sync hydration', () => { - const store = createUIStore() - store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'tasks' }), 'startup') - expect(store.getState().activeView).toBe('tasks') - - store - .getState() - .hydratePersistedUI( - makePersistedUI({ activeView: 'terminal', rightSidebarOpen: false }), - 'sync' - ) - - expect(store.getState().activeView).toBe('tasks') - expect(store.getState().rightSidebarOpen).toBe(false) - }) - - it('preserves the current right sidebar width when older persisted UI omits it', () => { - const store = createUIStore() - - store.setState({ rightSidebarWidth: 360 }) - store.getState().hydratePersistedUI({ - ...makePersistedUI(), - rightSidebarWidth: undefined as unknown as number - }) - - expect(store.getState().rightSidebarWidth).toBe(360) - }) - - it('hydrates a persisted closed left sidebar preference', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ sidebarOpen: false })) - - expect(store.getState().sidebarOpen).toBe(false) - }) - - it('hydrates a persisted open left sidebar preference', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ sidebarOpen: true })) - - expect(store.getState().sidebarOpen).toBe(true) - }) - - it('hydrates a missing left sidebar preference as open', () => { - const store = createUIStore() - - store.setState({ sidebarOpen: false }) - store.getState().hydratePersistedUI({ ...makePersistedUI(), sidebarOpen: undefined }) - - expect(store.getState().sidebarOpen).toBe(true) - }) - - it('keeps an unsaved left sidebar close when a sync omits the left sidebar preference', () => { - const store = createUIStore() - store.getState().hydratePersistedUI(makePersistedUI(), 'startup') - - store.getState().setSidebarOpen(false) - store.getState().hydratePersistedUI({ ...makePersistedUI(), sidebarOpen: undefined }, 'sync') - - // Why: the baseline must stay open or the writer sees no diff and the close never persists. - expect(store.getState().sidebarOpen).toBe(false) - expect(store.getState().persistedUIWriteBaseline?.sidebarOpen).toBe(true) - }) - - it('hydrates a persisted closed right sidebar preference', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarOpen: false })) - - expect(store.getState().rightSidebarOpen).toBe(false) - }) - - it('hydrates a persisted open right sidebar preference', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarOpen: true })) - - expect(store.getState().rightSidebarOpen).toBe(true) - }) - - it('hydrates a persisted right sidebar tab preference', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarTab: 'checks' })) - - expect(store.getState().rightSidebarTab).toBe('checks') - expect(store.getState().rightSidebarExplorerView).toBe('files') - }) - - it('preserves persisted repo filters until repos are loaded', () => { - const store = createUIStore() - const remoteDismissalKey = getSetupScriptPromptDismissalKey( - getRepoHostIdentityForParts('remote-repo', 'runtime:env-1') - ) - - store.getState().hydratePersistedUI( - makePersistedUI({ - filterRepoIds: ['remote-repo', 12 as never, 'stale-repo'], - trustedOrcaHooks: { - 'remote-repo': { all: { approvedAt: 1 } }, - 'bad-shape': 'yes' as never - }, - setupScriptPromptDismissedRepoIds: [remoteDismissalKey, 'remote-repo', remoteDismissalKey] - }) - ) - - expect(store.getState().filterRepoIds).toEqual(['remote-repo', 'stale-repo']) - expect(store.getState().trustedOrcaHooks).toEqual({ - 'remote-repo': { all: { approvedAt: 1 } } - }) - expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([remoteDismissalKey]) - }) - - it('validates persisted repo filters when repos are already loaded', () => { - const store = createUIStore() - const localDismissalKey = getSetupScriptPromptDismissalKey( - getRepoHostIdentityForParts('local-repo', 'local') - ) - const staleDismissalKey = getSetupScriptPromptDismissalKey( - getRepoHostIdentityForParts('stale-repo', 'local') - ) - store.setState({ - repos: [ - { id: 'local-repo', path: '/local', displayName: 'Local', badgeColor: '#000', addedAt: 1 } - ] - } as Partial) - - store.getState().hydratePersistedUI( - makePersistedUI({ - filterRepoIds: ['local-repo', 'stale-repo'], - trustedOrcaHooks: { - 'local-repo': { all: { approvedAt: 1 } }, - 'stale-repo': { all: { approvedAt: 2 } } - }, - setupScriptPromptDismissedRepoIds: [localDismissalKey, staleDismissalKey] - }) - ) - - expect(store.getState().filterRepoIds).toEqual(['local-repo']) - expect(store.getState().trustedOrcaHooks).toEqual({ - 'local-repo': { all: { approvedAt: 1 } } - }) - expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([localDismissalKey]) - }) - - it('hydrates legacy persisted search tab as Explorer search', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarTab: 'search' })) - - expect(store.getState().rightSidebarTab).toBe('explorer') - expect(store.getState().rightSidebarExplorerView).toBe('search') - }) - - it('hydrates persisted Explorer search view', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI( - makePersistedUI({ rightSidebarTab: 'explorer', rightSidebarExplorerView: 'search' }) - ) - - expect(store.getState().rightSidebarTab).toBe('explorer') - expect(store.getState().rightSidebarExplorerView).toBe('search') - }) - - it('hydrates a persisted workspace host scope', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ workspaceHostScope: 'ssh:win%20vm' })) - - expect(store.getState().workspaceHostScope).toBe('ssh:win%20vm') - expect(store.getState().visibleWorkspaceHostIds).toEqual(['ssh:win%20vm']) - }) - - it('hydrates a persisted visible workspace host set', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - workspaceHostScope: 'ssh:win%20vm', - visibleWorkspaceHostIds: [ - 'local', - 'ssh:win%20vm', - 'bogus' as NonNullable[number], - 'local' - ] - }) - ) - - expect(store.getState().workspaceHostScope).toBe('ssh:win%20vm') - expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'ssh:win%20vm']) - }) - - it('hydrates a persisted workspace host order', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - workspaceHostOrder: [ - 'ssh:win%20vm', - 'bogus' as NonNullable[number], - 'local', - 'ssh:win%20vm' - ] - }) - ) - - expect(store.getState().workspaceHostOrder).toEqual(['ssh:win%20vm', 'local']) - }) - - it('hydrates and immediately applies the manual cross-host repo order', () => { - const store = createUIStore() - const local: Repo = { - id: 'same', - path: '/local', - displayName: 'Local', - badgeColor: '#000', - addedAt: 1, - executionHostId: 'local' - } - const remote: Repo = { - ...local, - path: '/remote', - displayName: 'Remote', - executionHostId: 'runtime:node-b' - } - store.setState({ repos: [local, remote] }) - - store.getState().hydratePersistedUI( - makePersistedUI({ - manualRepoOrder: [ - { hostId: 'runtime:node-b', repoId: 'same' }, - { hostId: 'invalid' as never, repoId: 'ignored' }, - { hostId: 'local', repoId: 'same' } - ] - }) - ) - - expect(store.getState().manualRepoOrder).toEqual([ - { hostId: 'runtime:node-b', repoId: 'same' }, - { hostId: 'local', repoId: 'same' } - ]) - expect(store.getState().repos).toEqual([remote, local]) - }) - - it('falls back to all hosts for invalid persisted workspace host scopes', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI( - makePersistedUI({ workspaceHostScope: 'bogus' as PersistedUIState['workspaceHostScope'] }) - ) - - expect(store.getState().workspaceHostScope).toBe('all') - expect(store.getState().visibleWorkspaceHostIds).toBeNull() - }) - - it('tracks the per-project settings host selection without persisting it', () => { - const setUI = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setSettingsProjectHostSelection('git:acme/app', 'runtime:home-mac') - - expect(store.getState().settingsProjectHostSelection).toEqual({ - 'git:acme/app': 'runtime:home-mac' - }) - expect(store.getState().settingsProjectSetupSelection).toEqual({}) - - store - .getState() - .setSettingsProjectHostSelection('git:acme/app', 'runtime:home-mac', 'jump-setup') - expect(store.getState().settingsProjectSetupSelection).toEqual({ - 'git:acme/app': 'jump-setup' - }) - expect(setUI).not.toHaveBeenCalled() - }) - - it('updates workspace host scope for the guarded UI writer', () => { - const setUI = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setWorkspaceHostScope('runtime:env-1') - - expect(store.getState().workspaceHostScope).toBe('runtime:env-1') - expect(store.getState().visibleWorkspaceHostIds).toEqual(['runtime:env-1']) - expect(setUI).not.toHaveBeenCalled() - }) - - it('updates host visibility independently of focused host for the guarded UI writer', () => { - const setUI = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setWorkspaceHostScope('runtime:env-1') - store.getState().setVisibleWorkspaceHostIds(['local', 'runtime:env-1']) - - expect(store.getState().workspaceHostScope).toBe('runtime:env-1') - expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'runtime:env-1']) - expect(setUI).not.toHaveBeenCalled() - }) - - it('persists workspace host order changes', () => { - const setUI = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setWorkspaceHostOrder(['ssh:win%20vm', 'bogus' as never, 'local']) - - expect(store.getState().workspaceHostOrder).toEqual(['ssh:win%20vm', 'local']) - expect(setUI).toHaveBeenCalledWith({ workspaceHostOrder: ['ssh:win%20vm', 'local'] }) - }) - - it('persists group changes with collapsed groups cleared', () => { - const setUI = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.setState({ collapsedGroups: new Set(['repo:old']) }) - store.getState().setGroupBy('none') - - expect(store.getState().groupBy).toBe('none') - expect([...store.getState().collapsedGroups]).toEqual([]) - expect(setUI).toHaveBeenCalledWith({ groupBy: 'none', collapsedGroups: [] }) - }) - - it('hydrates persisted per-worktree explorer roots', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - explorerDisplayRootByWorktree: { - 'repo-1::/repo': '/', - 'repo-2::/repo': 'packages/app' - } - }) - ) - - expect(store.getState().explorerDisplayRootByWorktree).toEqual({ - 'repo-1::/repo': '/', - 'repo-2::/repo': 'packages/app' - }) - }) - - it('hydrates persisted per-worktree dotfile visibility', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - showDotfilesByWorktree: { - 'repo-1::/repo': false, - 'repo-2::/repo': true - } - }) - ) - - expect(store.getState().showDotfilesByWorktree).toEqual({ - 'repo-1::/repo': false, - 'repo-2::/repo': true - }) - }) - - it('does not churn persisted UI references when hydration is identical by value', () => { - const store = createUIStore() - const persistedUI = makePersistedUI({ - featureTipsSeenIds: ['voice-dictation'], - contextualToursSeenIds: ['tasks'], - showDotfilesByWorktree: { 'repo-1::/repo': false }, - collapsedGroups: ['repo:one'], - workspaceHostOrder: ['local'], - worktreeCardProperties: ['status', 'unread', 'ports'], - acknowledgedAgentsByPaneKey: { 'tab-1::pane-1': Date.now() } - }) - - store.getState().hydratePersistedUI(persistedUI) - const before = store.getState() - const references = { - acknowledgedAgentsByPaneKey: before.acknowledgedAgentsByPaneKey, - featureTipsSeenIds: before.featureTipsSeenIds, - contextualToursSeenIds: before.contextualToursSeenIds, - workspaceHostOrder: before.workspaceHostOrder, - showDotfilesByWorktree: before.showDotfilesByWorktree, - collapsedGroups: before.collapsedGroups, - worktreeCardProperties: before.worktreeCardProperties - } - - store.getState().hydratePersistedUI(makePersistedUI({ ...persistedUI })) - const after = store.getState() - - expect(after.acknowledgedAgentsByPaneKey).toBe(references.acknowledgedAgentsByPaneKey) - expect(after.featureTipsSeenIds).toBe(references.featureTipsSeenIds) - expect(after.contextualToursSeenIds).toBe(references.contextualToursSeenIds) - expect(after.workspaceHostOrder).toBe(references.workspaceHostOrder) - expect(after.showDotfilesByWorktree).toBe(references.showDotfilesByWorktree) - expect(after.collapsedGroups).toBe(references.collapsedGroups) - expect(after.worktreeCardProperties).toBe(references.worktreeCardProperties) - }) - - it('drops invalid persisted per-worktree dotfile visibility entries', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - showDotfilesByWorktree: { - 'repo-1::/repo': false, - 'repo-2::/repo': 'nope', - constructor: false - } as never - }) - ) - - expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-1::/repo': false }) - }) - - it('stores only per-worktree dotfile visibility opt-outs', () => { - const store = createUIStore() - - store.getState().setShowDotfilesForWorktree('repo-1::/repo', false) - expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-1::/repo': false }) - - store.getState().setShowDotfilesForWorktree('repo-1::/repo', true) - expect(store.getState().showDotfilesByWorktree).toEqual({}) - }) - - it('toggles per-worktree dotfile visibility independently', () => { - const store = createUIStore() - - store.getState().toggleShowDotfilesForWorktree('repo-1::/repo') - store.getState().toggleShowDotfilesForWorktree('repo-2::/repo') - store.getState().toggleShowDotfilesForWorktree('repo-2::/repo') - - expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-1::/repo': false }) - }) - - it('falls back to explorer for invalid persisted right sidebar tabs', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI( - makePersistedUI({ rightSidebarTab: 'bogus' as PersistedUIState['rightSidebarTab'] }) - ) - - expect(store.getState().rightSidebarTab).toBe('explorer') - expect(store.getState().rightSidebarExplorerView).toBe('files') - }) - - it('clamps persisted sidebar widths into the supported range', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - sidebarWidth: 100, - rightSidebarWidth: 100 - }) - ) - - expect(store.getState().sidebarWidth).toBe(220) - expect(store.getState().rightSidebarWidth).toBe(220) - }) - - it('clamps persisted markdown toc panel widths into the supported range', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - markdownTocPanelWidth: 100 - }) - ) - - expect(store.getState().markdownTocPanelWidth).toBe(200) - }) - - it('clamps persisted combined diff file tree widths into the supported range', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ combinedDiffFileTreeWidth: 100 })) - expect(store.getState().combinedDiffFileTreeWidth).toBe(200) - - store.getState().hydratePersistedUI(makePersistedUI({ combinedDiffFileTreeWidth: 5_000 })) - expect(store.getState().combinedDiffFileTreeWidth).toBe(640) - }) - - it('preserves right sidebar widths above the former 500px cap', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - sidebarWidth: 260, - rightSidebarWidth: 900 - }) - ) - - expect(store.getState().sidebarWidth).toBe(260) - expect(store.getState().rightSidebarWidth).toBe(900) - }) - - it('stores pending sidebar reveal rename requests', () => { - const store = createUIStore() - - store.getState().revealWorktreeInSidebar('repo1::/feature', { - behavior: 'smooth', - highlight: true, - beginRename: true - }) - - expect(store.getState().pendingRevealWorktree).toEqual({ - worktreeId: 'repo1::/feature', - behavior: 'smooth', - highlight: true, - beginRename: true - }) - }) - - it('falls back to existing sidebar widths when persisted values are not finite', () => { - const store = createUIStore() - - store.getState().setSidebarWidth(320) - store.setState({ rightSidebarWidth: 360 }) - - store.getState().hydratePersistedUI( - makePersistedUI({ - sidebarWidth: Number.NaN, - rightSidebarWidth: Number.POSITIVE_INFINITY - }) - ) - - expect(store.getState().sidebarWidth).toBe(320) - expect(store.getState().rightSidebarWidth).toBe(360) - }) -}) diff --git a/src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts b/src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts deleted file mode 100644 index 326bc002362..00000000000 --- a/src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createDefaultWorkspaceCleanupBrowseState } from '../../../../shared/workspace-cleanup-browse-state' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -function persistedWithIdleDays(idleMinDays: number | null) { - const browse = createDefaultWorkspaceCleanupBrowseState() - browse.filters.activity.idleMinDays = idleMinDays - return makePersistedUI({ workspaceCleanup: { dismissals: {}, browse } }) -} - -describe('workspace cleanup browse hydration', () => { - it('restores persisted filters on startup', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(persistedWithIdleDays(30), 'startup') - - expect(store.getState().workspaceCleanupBrowse.filters.activity.idleMinDays).toBe(30) - }) - - it('does not let a sync broadcast revert a filter the user just set', () => { - // Other ui.set broadcasts carry stale browse state until its debounced writer runs. - const store = createUIStore() - store.getState().hydratePersistedUI(persistedWithIdleDays(30), 'startup') - - const edited = createDefaultWorkspaceCleanupBrowseState() - edited.filters.activity.idleMinDays = 45 - store.setState({ workspaceCleanupBrowse: edited }) - - store.getState().hydratePersistedUI(persistedWithIdleDays(30), 'sync') - - expect(store.getState().workspaceCleanupBrowse.filters.activity.idleMinDays).toBe(45) - }) - - it('does not let a sync broadcast revert a typed query', () => { - const store = createUIStore() - const edited = createDefaultWorkspaceCleanupBrowseState() - edited.filters.query = 'release' - store.setState({ workspaceCleanupBrowse: edited }) - - store.getState().hydratePersistedUI(persistedWithIdleDays(null), 'sync') - - expect(store.getState().workspaceCleanupBrowse.filters.query).toBe('release') - }) - - it('defaults an absent source to sync, so an unlabelled broadcast cannot revert either', () => { - const store = createUIStore() - const edited = createDefaultWorkspaceCleanupBrowseState() - edited.filters.activity.idleMinDays = 45 - store.setState({ workspaceCleanupBrowse: edited }) - - store.getState().hydratePersistedUI(persistedWithIdleDays(30)) - - expect(store.getState().workspaceCleanupBrowse.filters.activity.idleMinDays).toBe(45) - }) - - it('still hydrates dismissals on sync, which are main-owned and not edited here', () => { - const store = createUIStore() - const dismissal = { - worktreeId: 'repo-1::/repo/one', - dismissedAt: Date.now(), - fingerprint: 'fp-1', - classifierVersion: 2 - } - - store.getState().hydratePersistedUI( - makePersistedUI({ - workspaceCleanup: { - dismissals: { [dismissal.worktreeId]: dismissal }, - browse: createDefaultWorkspaceCleanupBrowseState() - } - }), - 'sync' - ) - - expect(store.getState().workspaceCleanupDismissals[dismissal.worktreeId]).toBeDefined() - }) -}) diff --git a/src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts b/src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts deleted file mode 100644 index c5034469194..00000000000 --- a/src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts +++ /dev/null @@ -1,928 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getWorktreeCardModeProperties } from '../../../../shared/constants' -import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' -import type { AppState } from '../types' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -const mocks = vi.hoisted(() => ({ - sendNotesToActiveAgentSession: vi.fn(), - track: vi.fn(), - toastMessage: vi.fn(), - toastSuccess: vi.fn(), - toastError: vi.fn() -})) - -vi.mock('@/lib/active-agent-note-send', () => ({ - activeAgentNotesSendFailureMessage: ( - status: string, - options: { explicitTarget?: boolean } = {} - ) => (options.explicitTarget ? `selected:${status}` : status), - sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession -})) - -vi.mock('@/lib/telemetry', () => ({ - track: mocks.track -})) - -vi.mock('sonner', () => ({ - toast: { - message: mocks.toastMessage, - success: mocks.toastSuccess, - error: mocks.toastError - } -})) - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -beforeEach(() => { - mocks.sendNotesToActiveAgentSession.mockReset() - mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' }) - mocks.track.mockReset() - mocks.toastMessage.mockReset() - mocks.toastSuccess.mockReset() - mocks.toastError.mockReset() -}) - -describe('createUISlice hydratePersistedUI', () => { - it('does not restore the retired active-only filter from persisted UI state', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - showActiveOnly: true - }) - ) - - expect(store.getState().showActiveOnly).toBe(false) - }) - - it('restores the new hide-sleeping filter from persisted UI state', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - hideSleepingWorkspaces: true - }) - ) - - expect(store.getState().showSleepingWorkspaces).toBe(false) - }) - - it('ignores legacy hidden-sleeping preference so existing users start with sleeping visible', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - showSleepingWorkspaces: false - }) - ) - - expect(store.getState().showSleepingWorkspaces).toBe(true) - }) - - it('ignores the legacy show-inactive filter so existing users start with sleeping visible', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - showSleepingWorkspaces: undefined, - showInactiveWorkspaces: false - }) - ) - - expect(store.getState().showSleepingWorkspaces).toBe(true) - }) - - it('restores the hide-default-branch filter from persisted UI state', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - hideDefaultBranchWorkspace: true - }) - ) - - expect(store.getState().hideDefaultBranchWorkspace).toBe(true) - }) - - it('restores selected card properties during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - worktreeCardProperties: ['inline-agents'] - }) - ) - - expect(store.getState().worktreeCardProperties).toEqual(['status', 'unread', 'inline-agents']) - }) - - it('adds default-on status items once for older persisted UI', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - statusBarItems: ['claude', 'resource-usage'], - _portsStatusBarDefaultAdded: false - }) - ) - - expect(store.getState().statusBarItems).toEqual([ - 'claude', - 'resource-usage', - 'ports', - 'kimi', - 'minimax', - 'antigravity', - 'grok', - 'cursor', - 'zcode' - ]) - expect(setUI).toHaveBeenCalledWith({ - statusBarItems: [ - 'claude', - 'resource-usage', - 'ports', - 'kimi', - 'minimax', - 'antigravity', - 'grok', - 'cursor', - 'zcode' - ], - _portsStatusBarDefaultAdded: true, - _kimiStatusBarDefaultAdded: true, - _minimaxStatusBarDefaultAdded: true, - _antigravityStatusBarDefaultAdded: true, - _grokStatusBarDefaultAdded: true, - _cursorStatusBarDefaultAdded: true, - _zcodeStatusBarDefaultAdded: true - }) - }) - - it('preserves user-hidden default-on status items after one-shot migrations ran', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - statusBarItems: ['claude', 'resource-usage'], - _portsStatusBarDefaultAdded: true, - _kimiStatusBarDefaultAdded: true, - _minimaxStatusBarDefaultAdded: true, - _antigravityStatusBarDefaultAdded: true, - _grokStatusBarDefaultAdded: true, - _cursorStatusBarDefaultAdded: true, - _zcodeStatusBarDefaultAdded: true - }) - ) - - expect(store.getState().statusBarItems).toEqual(['claude', 'resource-usage']) - expect(setUI).not.toHaveBeenCalled() - }) - - it('persists and hydrates the usage percentage display preference', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setUsagePercentageDisplay('used') - - expect(store.getState().usagePercentageDisplay).toBe('used') - // Why: adapting the control also permanently dismisses the one-time change notice. - expect(setUI).toHaveBeenCalledWith({ - usagePercentageDisplay: 'used', - usagePercentageDisplayChangeNoticeDismissed: true - }) - expect(store.getState().usagePercentageDisplayChangeNoticeDismissed).toBe(true) - - store.getState().hydratePersistedUI(makePersistedUI({ usagePercentageDisplay: 'remaining' })) - expect(store.getState().usagePercentageDisplay).toBe('remaining') - }) - - it('hydrates and dismisses the usage percentage display change notice', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store - .getState() - .hydratePersistedUI(makePersistedUI({ usagePercentageDisplayChangeNoticeDismissed: false })) - expect(store.getState().usagePercentageDisplayChangeNoticeDismissed).toBe(false) - - store.getState().dismissUsagePercentageDisplayChangeNotice() - expect(store.getState().usagePercentageDisplayChangeNoticeDismissed).toBe(true) - expect(setUI).toHaveBeenCalledWith({ usagePercentageDisplayChangeNoticeDismissed: true }) - - setUI.mockClear() - store.getState().dismissUsagePercentageDisplayChangeNotice() - expect(setUI).not.toHaveBeenCalled() - }) - - it('defaults invalid usage percentage display values to used', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - usagePercentageDisplay: 'left' as PersistedUIState['usagePercentageDisplay'] - }) - ) - - expect(store.getState().usagePercentageDisplay).toBe('used') - }) - - it('initializes new users with compact status bar usage', () => { - expect(createUIStore().getState().statusBarUsageMode).toBe('compact') - }) - - it.each(['verbose', 'compact'] as const)( - 'persists and hydrates explicit %s usage mode', - (mode) => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setStatusBarUsageMode(mode) - - expect(store.getState().statusBarUsageMode).toBe(mode) - expect(setUI).toHaveBeenCalledWith({ statusBarUsageMode: mode }) - - const restoredStore = createUIStore() - restoredStore.getState().hydratePersistedUI(makePersistedUI({ statusBarUsageMode: mode })) - expect(restoredStore.getState().statusBarUsageMode).toBe(mode) - } - ) - - it.each([undefined, null, 'expanded'])( - 'hydrates missing or invalid status bar usage mode %j as compact', - (value) => { - const store = createUIStore() - const ui = makePersistedUI() - if (value === undefined) { - delete ui.statusBarUsageMode - } else { - Reflect.set(ui, 'statusBarUsageMode', value) - } - - store.getState().hydratePersistedUI(ui) - - expect(store.getState().statusBarUsageMode).toBe('compact') - } - ) - - it('hydrates and permanently dismisses the Compact change notice', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true) - - store - .getState() - .hydratePersistedUI(makePersistedUI({ statusBarCompactChangeNoticeDismissed: false })) - expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(false) - setUI.mockClear() - store.getState().dismissStatusBarCompactChangeNotice() - expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true) - expect(setUI).toHaveBeenCalledWith({ statusBarCompactChangeNoticeDismissed: true }) - store.getState().dismissStatusBarCompactChangeNotice() - expect(setUI).toHaveBeenCalledTimes(1) - }) - - it.each(['verbose', 'compact'] as const)( - 'dismisses the Compact notice when choosing %s', - (mode) => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - store - .getState() - .hydratePersistedUI(makePersistedUI({ statusBarCompactChangeNoticeDismissed: false })) - - store.getState().setStatusBarUsageMode(mode) - - expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true) - expect(setUI).toHaveBeenCalledWith({ - statusBarUsageMode: mode, - statusBarCompactChangeNoticeDismissed: true - }) - } - ) - - it('keeps the Compact notice hidden with an older host that omits its flag', () => { - const store = createUIStore() - const ui = makePersistedUI() - delete ui.statusBarCompactChangeNoticeDismissed - store.getState().hydratePersistedUI(ui) - expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true) - }) - - it('clamps persisted workspace board column width', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - workspaceBoardColumnWidth: 900 - }) - ) - - expect(store.getState().workspaceBoardColumnWidth).toBe(520) - }) - - it('defaults workspace board task status sync off and persists changes', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - expect(store.getState().syncTaskStatusFromWorkspaceBoard).toBe(false) - - store.getState().hydratePersistedUI( - makePersistedUI({ - syncTaskStatusFromWorkspaceBoard: true - }) - ) - expect(store.getState().syncTaskStatusFromWorkspaceBoard).toBe(true) - - store.getState().setSyncTaskStatusFromWorkspaceBoard(false) - - expect(store.getState().syncTaskStatusFromWorkspaceBoard).toBe(false) - expect(setUI).toHaveBeenCalledWith({ syncTaskStatusFromWorkspaceBoard: false }) - }) - - it('hydrates a valid Kagi session link', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - browserKagiSessionLink: 'https://kagi.com/search?token=secret&q=%s' - }) - ) - - expect(store.getState().browserKagiSessionLink).toBe('https://kagi.com/search?token=secret') - }) - - it('hydrates and normalizes the default browser zoom level', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - browserDefaultZoomLevel: 1.26 - }) - ) - - // 1.26 is about 130%, which snaps to Chrome's 125% preset. - expect(1.2 ** store.getState().browserDefaultZoomLevel).toBeCloseTo(1.25) - }) - - it('persists normalized default browser zoom changes', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setBrowserDefaultZoomLevel(10) - - // Clamped to Chrome's 500% maximum. - const { browserDefaultZoomLevel } = store.getState() - expect(1.2 ** browserDefaultZoomLevel).toBeCloseTo(5) - expect(setUI).toHaveBeenCalledWith({ browserDefaultZoomLevel }) - }) - - it('drops an invalid Kagi session link during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - browserKagiSessionLink: 'https://example.com/search?token=secret' - }) - ) - - expect(store.getState().browserKagiSessionLink).toBeNull() - }) - - it('hydrates legacy sidekick persisted keys into pet state', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - petVisible: undefined, - petId: undefined, - petSize: undefined, - customPets: undefined, - sidekickVisible: false, - sidekickId: 'custom-pet', - sidekickSize: 240, - customSidekicks: [ - { - id: 'custom-pet', - label: 'Legacy pet', - fileName: 'custom-pet.webp', - mimeType: 'image/webp', - kind: 'image' - } - ] - }) - ) - - expect(store.getState().petVisible).toBe(false) - expect(store.getState().petId).toBe('custom-pet') - expect(store.getState().petSize).toBe(240) - expect(store.getState().customPets).toEqual([ - { - id: 'custom-pet', - label: 'Legacy pet', - fileName: 'custom-pet.webp', - mimeType: 'image/webp', - kind: 'image' - } - ]) - }) - - it('sanitizes task resume state field-by-field during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - taskResumeState: { - githubMode: 'project', - githubItemsPreset: 'invalid', - githubItemsQuery: 42, - linearPreset: 'completed', - linearQuery: 'label:bug', - jiraPreset: 'reported', - jiraQuery: 99 - } as unknown as PersistedUIState['taskResumeState'] - }) - ) - - expect(store.getState().taskResumeState).toEqual({ - githubMode: 'project', - linearPreset: 'completed', - linearQuery: 'label:bug', - jiraPreset: 'reported' - }) - }) - - // Ignore legacy host-persisted Linear views: now device-local, their key is rejected by strict ui.set. - it('ignores a stale host-persisted Linear issue view during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - taskResumeState: { - linearQuery: 'label:bug', - linearIssueView: { viewMode: 'board', groupBy: 'assignee' } - } as unknown as PersistedUIState['taskResumeState'] - }) - ) - - expect(store.getState().taskResumeState).toEqual({ linearQuery: 'label:bug' }) - }) - - it('restores acknowledgedAgentsByPaneKey from persisted UI state', () => { - const now = 1_700_000_000_000 - vi.useFakeTimers() - vi.setSystemTime(now) - - try { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: { 'tab-a:0': now, 'tab-b:1': now - 5_000 } - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({ - 'tab-a:0': now, - 'tab-b:1': now - 5_000 - }) - } finally { - vi.useRealTimers() - } - }) - - it('falls back to an empty ack map when persisted UI omits acknowledgedAgentsByPaneKey', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI()) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({}) - }) - - it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is null', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: - null as unknown as PersistedUIState['acknowledgedAgentsByPaneKey'] - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({}) - }) - - it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is a string', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: - 'oops' as unknown as PersistedUIState['acknowledgedAgentsByPaneKey'] - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({}) - }) - - it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is an array', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: [ - 'a', - 'b' - ] as unknown as PersistedUIState['acknowledgedAgentsByPaneKey'] - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({}) - }) - - it('drops non-number / non-finite / non-positive entries from acknowledgedAgentsByPaneKey', () => { - const now = 1_700_000_000_000 - vi.useFakeTimers() - vi.setSystemTime(now) - - try { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: { - 'tab-a:0': now, - 'tab-b:1': now - 1000, - 'tab-c:2': 'not-a-number', - 'tab-d:3': Number.NaN, - 'tab-e:4': Number.POSITIVE_INFINITY, - 'tab-f:5': -1 - } as unknown as Record - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({ - 'tab-a:0': now, - 'tab-b:1': now - 1000 - }) - } finally { - vi.useRealTimers() - } - }) - - it('keeps agents scope filter array identities stable across unchanged re-hydrations', () => { - const store = createUIStore() - const persisted = makePersistedUI({ - agentsVisibleHostIds: ['ssh:devbox'], - agentsFilterRepoIds: ['repo-1'] - }) - - store.getState().hydratePersistedUI(persisted) - const firstHostIds = store.getState().agentsVisibleHostIds - const firstRepoIds = store.getState().agentsFilterRepoIds - - // Sync fires on every ui:changed; preserve array identity to avoid rebuilding agent scope memos. - store.getState().hydratePersistedUI(makePersistedUI({ ...persisted })) - expect(store.getState().agentsVisibleHostIds).toBe(firstHostIds) - expect(store.getState().agentsFilterRepoIds).toBe(firstRepoIds) - - store - .getState() - .hydratePersistedUI(makePersistedUI({ ...persisted, agentsVisibleHostIds: ['ssh:otherbox'] })) - expect(store.getState().agentsVisibleHostIds).toEqual(['ssh:otherbox']) - expect(store.getState().agentsFilterRepoIds).toBe(firstRepoIds) - }) - - it('hydrates agents view preferences with safe defaults for absent fields', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({})) - - expect(store.getState().agentsVisibleHostIds).toBeNull() - expect(store.getState().agentsFilterRepoIds).toEqual([]) - expect(store.getState().agentsHideWorkspacesFromOtherDevices).toBe(false) - expect(store.getState().agentsHideAutomationGeneratedWorkspaces).toBe(false) - expect(store.getState().agentsHideCliCreatedWorkspaces).toBe(false) - expect(store.getState().agentsShowChildAgents).toBe(false) - expect(store.getState().agentsCompactMode).toBe(true) - expect(store.getState().agentsShowSearch).toBe(true) - expect(store.getState().agentsReadFilter).toBe('all') - expect(store.getState().agentsGroupBy).toBe('status') - }) - - it('restores the agents workspace-origin filters independently of the workspace-nav ones', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - agentsHideWorkspacesFromOtherDevices: true, - agentsHideAutomationGeneratedWorkspaces: true, - agentsHideCliCreatedWorkspaces: true, - hideCliCreatedWorkspaces: false - }) - ) - - expect(store.getState().agentsHideWorkspacesFromOtherDevices).toBe(true) - expect(store.getState().agentsHideAutomationGeneratedWorkspaces).toBe(true) - expect(store.getState().agentsHideCliCreatedWorkspaces).toBe(true) - expect(store.getState().hideCliCreatedWorkspaces).toBe(false) - }) - - it('restores a hidden agents search field', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ agentsShowSearch: false })) - - expect(store.getState().agentsShowSearch).toBe(false) - }) - - it('restores the persisted agents read filter and grouping, rejecting unknown values', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI(makePersistedUI({ agentsReadFilter: 'unread', agentsGroupBy: 'project' })) - expect(store.getState().agentsReadFilter).toBe('unread') - expect(store.getState().agentsGroupBy).toBe('project') - - store.getState().hydratePersistedUI( - makePersistedUI({ - agentsReadFilter: 'bogus' as unknown as PersistedUIState['agentsReadFilter'], - agentsGroupBy: 'bogus' as unknown as PersistedUIState['agentsGroupBy'] - }) - ) - expect(store.getState().agentsReadFilter).toBe('all') - expect(store.getState().agentsGroupBy).toBe('status') - }) - - it('sanitizes malformed agents repo filters before the repo catalog loads', () => { - const store = createUIStore() - - expect(() => - store.getState().hydratePersistedUI( - makePersistedUI({ - agentsFilterRepoIds: 'repo-1' as unknown as PersistedUIState['agentsFilterRepoIds'] - }) - ) - ).not.toThrow() - expect(store.getState().agentsFilterRepoIds).toEqual([]) - - store.getState().hydratePersistedUI( - makePersistedUI({ - agentsFilterRepoIds: [ - 'repo-1', - 42, - 'missing' - ] as unknown as PersistedUIState['agentsFilterRepoIds'] - }) - ) - expect(store.getState().agentsFilterRepoIds).toEqual(['repo-1', 'missing']) - }) - - it('sanitizes and prunes agents repo filters against a loaded repo catalog', () => { - const store = createUIStore() - store.setState({ - repos: [ - { - id: 'repo-1', - path: '/tmp/repo-1', - displayName: 'Repo 1', - badgeColor: 'gray', - addedAt: 1, - kind: 'git' - } - ] - }) - - expect(() => - store.getState().hydratePersistedUI( - makePersistedUI({ - agentsFilterRepoIds: [ - 'repo-1', - null, - 'missing' - ] as unknown as PersistedUIState['agentsFilterRepoIds'] - }) - ) - ).not.toThrow() - expect(store.getState().agentsFilterRepoIds).toEqual(['repo-1']) - }) - - it('prunes acknowledgedAgentsByPaneKey entries older than the 7-day TTL during hydration', () => { - // HYDRATE_MAX_AGE_MS lives in src/renderer/src/store/slices/ui.ts and matches - // the constant in src/main/agent-hooks/server.ts. - const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000 - const now = 1_700_000_000_000 - vi.useFakeTimers() - vi.setSystemTime(now) - - try { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: { - 'tab-recent:0': now, - 'tab-old:1': now - SEVEN_DAYS_MS - 1 - } - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({ - 'tab-recent:0': now - }) - } finally { - // Shared teardown leaves timers intact; restore real timers so later tests cannot inherit this clock. - vi.useRealTimers() - } - }) - - it('drops prototype-pollution keys from acknowledgedAgentsByPaneKey during hydration', () => { - const now = 1_700_000_000_000 - vi.useFakeTimers() - vi.setSystemTime(now) - - try { - const store = createUIStore() - const malicious: Record = {} - // Define __proto__ as an own enumerable property rather than changing Object.prototype. - Object.defineProperty(malicious, '__proto__', { - value: now, - enumerable: true, - configurable: true, - writable: true - }) - Object.defineProperty(malicious, 'constructor', { - value: now, - enumerable: true, - configurable: true, - writable: true - }) - Object.defineProperty(malicious, 'prototype', { - value: now, - enumerable: true, - configurable: true, - writable: true - }) - malicious['tab-safe:0'] = now - - store.getState().hydratePersistedUI( - makePersistedUI({ - acknowledgedAgentsByPaneKey: malicious - }) - ) - - expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({ - 'tab-safe:0': now - }) - } finally { - vi.useRealTimers() - } - }) - - it('merges and persists partial task resume updates', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.setState({ taskResumeState: { githubMode: 'project', linearPreset: 'all' } }) - store.getState().setTaskResumeState({ githubItemsPreset: 'my-prs' }) - - const expected = { githubMode: 'project', linearPreset: 'all', githubItemsPreset: 'my-prs' } - expect(store.getState().taskResumeState).toEqual(expected) - expect(setUI).toHaveBeenCalledWith({ taskResumeState: expected }) - }) - - it('sets Default worktree card mode with matching settings and UI writes', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - const setSettings = vi.fn().mockResolvedValue({ compactWorktreeCards: false }) - vi.stubGlobal('window', { - api: { ui: { set: setUI }, settings: { set: setSettings } } - }) - const store = createUIStore() - store.setState({ - settings: { compactWorktreeCards: true } as AppState['settings'], - worktreeCardProperties: ['status', 'branch'] - }) - - store.getState().setWorktreeCardMode('Default') - - const expected = getWorktreeCardModeProperties('Default') - expect(store.getState().settings?.compactWorktreeCards).toBe(false) - expect(store.getState().worktreeCardProperties).toEqual(expected) - expect(setSettings).toHaveBeenCalledWith({ compactWorktreeCards: false }) - expect(setUI).toHaveBeenCalledWith({ - worktreeCardProperties: expected, - _worktreeCardModeDefaulted: true - }) - }) - - it('sets Compact worktree card mode and removes migrated branch', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - const setSettings = vi.fn().mockResolvedValue({ compactWorktreeCards: true }) - vi.stubGlobal('window', { - api: { ui: { set: setUI }, settings: { set: setSettings } } - }) - const store = createUIStore() - store.setState({ - settings: { compactWorktreeCards: false } as AppState['settings'], - worktreeCardProperties: ['status', 'branch', 'inline-agents'] - }) - - store.getState().setWorktreeCardMode('Compact') - - const expected = getWorktreeCardModeProperties('Compact') - expect(store.getState().settings?.compactWorktreeCards).toBe(true) - expect(store.getState().worktreeCardProperties).toEqual(expected) - expect(store.getState().worktreeCardProperties).not.toContain('branch') - expect(store.getState().worktreeCardProperties).not.toContain('inline-agents') - expect(setSettings).toHaveBeenCalledWith({ compactWorktreeCards: true }) - expect(setUI).toHaveBeenCalledWith({ - worktreeCardProperties: expected, - _worktreeCardModeDefaulted: true - }) - }) - - it('sets custom worktree card properties', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setWorktreeCardProperties(['inline-agents', 'inline-agents']) - - expect(store.getState().worktreeCardProperties).toEqual(['status', 'unread', 'inline-agents']) - expect(store.getState()._worktreeCardModeDefaulted).toBe(false) - expect(setUI).toHaveBeenCalledWith({ - worktreeCardProperties: ['status', 'unread', 'inline-agents'], - _worktreeCardModeDefaulted: false - }) - }) - - it('persists the agent activity display mode', () => { - const setUI = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().setAgentActivityDisplayMode('full') - - expect(store.getState().agentActivityDisplayMode).toBe('full') - expect(setUI).toHaveBeenCalledWith({ agentActivityDisplayMode: 'full' }) - }) - - it('normalizes invalid persisted agent activity display modes', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - agentActivityDisplayMode: 'bogus' as PersistedUIState['agentActivityDisplayMode'] - }) - ) - - expect(store.getState().agentActivityDisplayMode).toBe('compact') - }) -}) - -describe('createUISlice hydratePersistedUI manual unread turns', () => { - it('restores manual unread stamps and prunes malformed or stale ones', () => { - const store = createUIStore() - const fresh = Date.now() - 60_000 - const stale = Date.now() - 8 * 24 * 60 * 60 * 1000 - - store.getState().hydratePersistedUI( - makePersistedUI({ - manuallyUnreadTurnsByPaneKey: { - 'tab-a:1': fresh, - 'tab-b:1': stale, - 'tab-c:1': 'bogus' as unknown as number - } - }) - ) - - expect(store.getState().manuallyUnreadTurnsByPaneKey).toEqual({ 'tab-a:1': fresh }) - }) - - it('hydrates to an empty record when the field is absent from an older profile', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI(makePersistedUI({ manuallyUnreadTurnsByPaneKey: undefined })) - - expect(store.getState().manuallyUnreadTurnsByPaneKey).toEqual({}) - }) -}) diff --git a/src/renderer/src/store/slices/ui-modal-slot-dismissal.test.ts b/src/renderer/src/store/slices/ui-modal-slot-dismissal.test.ts index c858e0d507e..7558a775818 100644 --- a/src/renderer/src/store/slices/ui-modal-slot-dismissal.test.ts +++ b/src/renderer/src/store/slices/ui-modal-slot-dismissal.test.ts @@ -7,36 +7,6 @@ function dismissalData(onDismissed: () => void): Record { } describe('UI modal slot dismissal', () => { - it('dismisses replaced and closed entries once', () => { - const store = createUIStore() - const firstDismissed = vi.fn() - const secondDismissed = vi.fn() - - store.getState().openModal('worktree-palette', dismissalData(firstDismissed)) - store.getState().openModal('quick-open', dismissalData(secondDismissed)) - store.getState().closeModal() - store.getState().closeModal() - - expect(firstDismissed).toHaveBeenCalledOnce() - expect(secondDismissed).toHaveBeenCalledOnce() - }) - - it('dismisses each entry across consecutive replacements', () => { - const store = createUIStore() - const firstDismissed = vi.fn() - const secondDismissed = vi.fn() - const thirdDismissed = vi.fn() - - store.getState().openModal('worktree-palette', dismissalData(firstDismissed)) - store.getState().openModal('quick-open', dismissalData(secondDismissed)) - store.getState().openModal('add-repo', dismissalData(thirdDismissed)) - store.getState().closeModal() - - expect(firstDismissed).toHaveBeenCalledOnce() - expect(secondDismissed).toHaveBeenCalledOnce() - expect(thirdDismissed).toHaveBeenCalledOnce() - }) - it('updates the slot before notifying the evicted entry', () => { const store = createUIStore() const observedModal = vi.fn(() => store.getState().activeModal) @@ -47,15 +17,6 @@ describe('UI modal slot dismissal', () => { expect(observedModal).toHaveReturnedWith('quick-open') }) - it('ignores modal data without a callable dismissal hook', () => { - const store = createUIStore() - - store.getState().openModal('worktree-palette', { [MODAL_DISMISSED_KEY]: 'invalid' }) - - expect(() => store.getState().openModal('quick-open')).not.toThrow() - expect(store.getState().activeModal).toBe('quick-open') - }) - it('settles reentrant replacement and close paths once', () => { const store = createUIStore() const replacementDismissed = vi.fn() @@ -73,24 +34,4 @@ describe('UI modal slot dismissal', () => { expect(reentrantDismissed).toHaveBeenCalledOnce() expect(store.getState().activeModal).toBe('none') }) - - it('performs one bounded notification per transition under repeated replacement', () => { - const store = createUIStore() - const dismissed = new Set() - const transitionCount = 1_000 - - for (let id = 0; id < transitionCount; id += 1) { - store.getState().openModal( - 'worktree-palette', - dismissalData(() => { - expect(dismissed.has(id)).toBe(false) - dismissed.add(id) - }) - ) - } - store.getState().closeModal() - - expect(dismissed.size).toBe(transitionCount) - expect(store.getState().modalData).toEqual({}) - }) }) diff --git a/src/renderer/src/store/slices/ui-notice-dismissals.test.ts b/src/renderer/src/store/slices/ui-notice-dismissals.test.ts deleted file mode 100644 index d038253d68c..00000000000 --- a/src/renderer/src/store/slices/ui-notice-dismissals.test.ts +++ /dev/null @@ -1,384 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -const mocks = vi.hoisted(() => ({ - sendNotesToActiveAgentSession: vi.fn(), - track: vi.fn(), - toastMessage: vi.fn(), - toastSuccess: vi.fn(), - toastError: vi.fn() -})) - -vi.mock('@/lib/active-agent-note-send', () => ({ - activeAgentNotesSendFailureMessage: ( - status: string, - options: { explicitTarget?: boolean } = {} - ) => (options.explicitTarget ? `selected:${status}` : status), - sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession -})) - -vi.mock('@/lib/telemetry', () => ({ - track: mocks.track -})) - -vi.mock('sonner', () => ({ - toast: { - message: mocks.toastMessage, - success: mocks.toastSuccess, - error: mocks.toastError - } -})) - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -beforeEach(() => { - mocks.sendNotesToActiveAgentSession.mockReset() - mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' }) - mocks.track.mockReset() - mocks.toastMessage.mockReset() - mocks.toastSuccess.mockReset() - mocks.toastError.mockReset() -}) - -describe('createUISlice feature tips', () => { - it('marks feature tips seen and persists them once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().markFeatureTipsSeen(['voice-dictation']) - store.getState().markFeatureTipsSeen(['voice-dictation']) - - expect(store.getState().featureTipsSeenIds).toEqual(['voice-dictation']) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ featureTipsSeenIds: ['voice-dictation'] }) - }) - - it('normalizes persisted feature tip ids during hydration', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - featureTipsSeenIds: ['voice-dictation', 'unknown', 'voice-dictation'] as never - }) - ) - - expect(store.getState().featureTipsSeenIds).toEqual(['voice-dictation']) - }) -}) - -describe('createUISlice setup guide sidebar dismissal', () => { - it('persists sidebar dismissal changes once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().setSetupGuideSidebarDismissed(true) - store.getState().setSetupGuideSidebarDismissed(true) - - expect(store.getState().setupGuideSidebarDismissed).toBe(true) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ setupGuideSidebarDismissed: true }) - }) - - it('hydrates only explicit sidebar dismissals as hidden', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ setupGuideSidebarDismissed: true })) - expect(store.getState().setupGuideSidebarDismissed).toBe(true) - - store.getState().hydratePersistedUI(makePersistedUI({ setupGuideSidebarDismissed: undefined })) - expect(store.getState().setupGuideSidebarDismissed).toBe(false) - }) - - it('persists browser milestone migration result once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().markSetupGuideBrowserMilestoneMigrated(true) - store.getState().markSetupGuideBrowserMilestoneMigrated(true) - - expect(store.getState().setupGuideBrowserMilestoneMigrated).toBe(true) - expect(store.getState().setupGuideBrowserMilestoneLegacyComplete).toBe(true) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ - setupGuideBrowserMilestoneMigrated: true, - setupGuideBrowserMilestoneLegacyComplete: true - }) - }) - - it('hydrates browser milestone migration fields explicitly', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI( - makePersistedUI({ - setupGuideBrowserMilestoneMigrated: true, - setupGuideBrowserMilestoneLegacyComplete: true - }) - ) - expect(store.getState().setupGuideBrowserMilestoneMigrated).toBe(true) - expect(store.getState().setupGuideBrowserMilestoneLegacyComplete).toBe(true) - - store.getState().hydratePersistedUI( - makePersistedUI({ - setupGuideBrowserMilestoneMigrated: undefined, - setupGuideBrowserMilestoneLegacyComplete: undefined - }) - ) - expect(store.getState().setupGuideBrowserMilestoneMigrated).toBe(false) - expect(store.getState().setupGuideBrowserMilestoneLegacyComplete).toBe(false) - }) -}) - -describe('createUISlice mobile emulator agent setup dismissal', () => { - it('persists mobile emulator agent setup dismissal once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().dismissMobileEmulatorAgentSetup() - store.getState().dismissMobileEmulatorAgentSetup() - - expect(store.getState().mobileEmulatorAgentSetupDismissed).toBe(true) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ mobileEmulatorAgentSetupDismissed: true }) - }) - - it('hydrates only explicit mobile emulator agent setup dismissals', () => { - const store = createUIStore() - - store - .getState() - .hydratePersistedUI(makePersistedUI({ mobileEmulatorAgentSetupDismissed: true })) - expect(store.getState().mobileEmulatorAgentSetupDismissed).toBe(true) - - store - .getState() - .hydratePersistedUI(makePersistedUI({ mobileEmulatorAgentSetupDismissed: undefined })) - expect(store.getState().mobileEmulatorAgentSetupDismissed).toBe(false) - }) -}) - -describe('createUISlice mobile emulator tab intro dismissal', () => { - it('persists mobile emulator tab intro dismissal once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().dismissMobileEmulatorTabIntro() - store.getState().dismissMobileEmulatorTabIntro() - - expect(store.getState().mobileEmulatorTabIntroDismissed).toBe(true) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ mobileEmulatorTabIntroDismissed: true }) - }) - - it('hydrates only explicit mobile emulator tab intro dismissals', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ mobileEmulatorTabIntroDismissed: true })) - expect(store.getState().mobileEmulatorTabIntroDismissed).toBe(true) - - store - .getState() - .hydratePersistedUI(makePersistedUI({ mobileEmulatorTabIntroDismissed: undefined })) - expect(store.getState().mobileEmulatorTabIntroDismissed).toBe(false) - }) -}) - -describe('createUISlice browser import hint dismissal', () => { - it('persists browser import hint dismissal changes once', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const store = createUIStore() - - store.getState().setBrowserImportHintHidden(true) - store.getState().setBrowserImportHintHidden(true) - - expect(store.getState().browserImportHintHidden).toBe(true) - expect(setMock).toHaveBeenCalledTimes(1) - expect(setMock).toHaveBeenCalledWith({ browserImportHintHidden: true }) - }) - - it('hydrates only explicit browser import hint dismissals as hidden', () => { - const store = createUIStore() - - store.getState().hydratePersistedUI(makePersistedUI({ browserImportHintHidden: true })) - expect(store.getState().browserImportHintHidden).toBe(true) - - store.getState().hydratePersistedUI(makePersistedUI({ browserImportHintHidden: undefined })) - expect(store.getState().browserImportHintHidden).toBe(false) - }) -}) - -describe('createUISlice Codex shared-settings notice', () => { - it('counts as seen until hydration, then follows the persisted flag', () => { - const store = createUIStore() - expect(store.getState().codexSharedSettingsNoticeSeen).toBe(true) - - store.getState().hydratePersistedUI(makePersistedUI({})) - expect(store.getState().codexSharedSettingsNoticeSeen).toBe(false) - - store.getState().hydratePersistedUI(makePersistedUI({ codexSharedSettingsNoticeSeen: true })) - expect(store.getState().codexSharedSettingsNoticeSeen).toBe(true) - }) -}) - -describe('createUISlice Claude diff panel notice', () => { - it('counts as seen until hydration, then follows the persisted flag', () => { - const store = createUIStore() - expect(store.getState().claudeDiffPanelNoticeSeen).toBe(true) - - store.getState().hydratePersistedUI(makePersistedUI({})) - expect(store.getState().claudeDiffPanelNoticeSeen).toBe(false) - - store.getState().hydratePersistedUI(makePersistedUI({ claudeDiffPanelNoticeSeen: true })) - expect(store.getState().claudeDiffPanelNoticeSeen).toBe(true) - }) -}) - -describe('createUISlice clearOsc52ClipboardDefaultOnNotice', () => { - it('restores the armed notice from persisted UI', () => { - const store = createUIStore() - - expect(store.getState().osc52ClipboardDefaultOnNoticePending).toBe(false) - store - .getState() - .hydratePersistedUI(makePersistedUI({ osc52ClipboardDefaultOnNoticePending: true })) - - expect(store.getState().osc52ClipboardDefaultOnNoticePending).toBe(true) - }) - - it('stops the toast this session even when the persist fails', () => { - // Dismiss locally before persisting so failure cannot repeatedly toast this session; next launch may re-arm. - const setUI = vi.fn(() => Promise.reject(new Error('runtime offline'))) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - store - .getState() - .hydratePersistedUI(makePersistedUI({ osc52ClipboardDefaultOnNoticePending: true })) - - store.getState().clearOsc52ClipboardDefaultOnNotice() - - expect(store.getState().osc52ClipboardDefaultOnNoticePending).toBe(false) - expect(setUI).toHaveBeenCalledWith({ osc52ClipboardDefaultOnNoticePending: false }) - }) -}) - -describe('unexpected sign-out dismissal persistence', () => { - it('persists a dismissal once even when effects repeat', () => { - const setUI = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { api: { ui: { set: setUI } } }) - const store = createUIStore() - - store.getState().dismissUnexpectedSignoutCard('1.2.3') - store.getState().dismissUnexpectedSignoutCard('1.2.3') - - expect(store.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3') - expect(setUI).toHaveBeenCalledExactlyOnceWith({ dismissedUnexpectedSignoutVersion: '1.2.3' }) - }) - - it.each([undefined, null, '1.2.2'])( - 'does not re-arm a local dismissal from stale hydration (%s)', - (dismissedUnexpectedSignoutVersion) => { - vi.stubGlobal('window', { api: { ui: { set: vi.fn(() => Promise.resolve()) } } }) - const store = createUIStore() - store.getState().dismissUnexpectedSignoutCard('1.2.3') - - store.getState().hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion })) - - expect(store.getState().unexpectedSignoutDismissedVersions).toContain('1.2.3') - } - ) - - it('defaults legacy profiles and restores dismissal on reopen', () => { - const store = createUIStore() - expect(store.getState().dismissedUnexpectedSignoutVersion).toBeNull() - store - .getState() - .hydratePersistedUI( - makePersistedUI({ dismissedUnexpectedSignoutVersion: undefined }), - 'startup' - ) - expect(store.getState().dismissedUnexpectedSignoutVersion).toBeNull() - const reopened = createUIStore() - reopened - .getState() - .hydratePersistedUI( - makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }), - 'startup' - ) - expect(reopened.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3') - }) - - it('accepts another window dismissal after hydrating an older version', () => { - const store = createUIStore() - store - .getState() - .hydratePersistedUI( - makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.2' }), - 'startup' - ) - store - .getState() - .hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' })) - expect(store.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3') - }) -}) - -describe('unexpected sign-out hydrated dismissal history', () => { - it.each([undefined, null, '1.2.2', '1.2.4'])( - 'retains an observed dismissal after a different version sync (%s)', - (dismissedUnexpectedSignoutVersion) => { - const store = createUIStore() - store - .getState() - .hydratePersistedUI( - makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }), - 'startup' - ) - store.getState().hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion })) - expect(store.getState().unexpectedSignoutDismissedVersions).toContain('1.2.3') - } - ) -}) diff --git a/src/renderer/src/store/slices/ui-page-navigation.test.ts b/src/renderer/src/store/slices/ui-page-navigation.test.ts deleted file mode 100644 index 2495f63a166..00000000000 --- a/src/renderer/src/store/slices/ui-page-navigation.test.ts +++ /dev/null @@ -1,756 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' -import type { LinearIssue } from '../../../../shared/linear/issue-types' -import type { GitLabWorkItem } from '../../../../shared/gitlab-types' -import type { Worktree } from '../../../../shared/worktree/types' -import type { FeatureInteractionState } from '../../../../shared/feature-interactions' -import type { TaskSourceContext } from '../../../../shared/task-source-context' -import type { AppState } from '../types' -import type { JiraIssue } from '../../../../shared/jira/jira-types' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -const mocks = vi.hoisted(() => ({ - sendNotesToActiveAgentSession: vi.fn(), - track: vi.fn(), - toastMessage: vi.fn(), - toastSuccess: vi.fn(), - toastError: vi.fn() -})) - -vi.mock('@/lib/active-agent-note-send', () => ({ - activeAgentNotesSendFailureMessage: ( - status: string, - options: { explicitTarget?: boolean } = {} - ) => (options.explicitTarget ? `selected:${status}` : status), - sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession -})) - -vi.mock('@/lib/telemetry', () => ({ - track: mocks.track -})) - -vi.mock('sonner', () => ({ - toast: { - message: mocks.toastMessage, - success: mocks.toastSuccess, - error: mocks.toastError - } -})) - -afterEach(() => { - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -beforeEach(() => { - mocks.sendNotesToActiveAgentSession.mockReset() - mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' }) - mocks.track.mockReset() - mocks.toastMessage.mockReset() - mocks.toastSuccess.mockReset() - mocks.toastError.mockReset() -}) - -function makeWorktree(id: string): Worktree { - return { id } as unknown as Worktree -} - -function makeGitHubWorkItem(overrides: Partial = {}): GitHubWorkItem { - return { - id: 'pr-95', - type: 'pr', - number: 95, - title: 'feat: add file upload command', - state: 'open', - url: 'https://github.com/acme/repo/pull/95', - labels: [], - updatedAt: '2026-05-20T00:00:00.000Z', - author: 'octocat', - repoId: 'repo-1', - ...overrides - } -} - -function makeLinearIssue(overrides: Partial = {}): LinearIssue { - return { - id: 'lin-1', - identifier: 'ORC-1', - title: 'Fix task flow', - url: 'https://linear.app/orca/issue/ORC-1/fix-task-flow', - state: { name: 'Todo', type: 'unstarted', color: '#999' }, - priority: 0, - estimate: null, - assignee: null, - labels: [], - labelIds: [], - team: { id: 'team-1', name: 'Orca', key: 'ORC' }, - workspaceId: 'workspace-1', - updatedAt: '2026-05-30T00:00:00.000Z', - createdAt: '2026-05-30T00:00:00.000Z', - ...overrides - } as LinearIssue -} - -function makeJiraIssue(overrides: Partial = {}): JiraIssue { - return { - id: 'ORC-1', - key: 'ORC-1', - title: 'Fix task source context', - url: 'https://example.atlassian.net/browse/ORC-1', - siteId: 'site-1', - siteName: 'Example Jira', - project: { id: '10000', key: 'ORC', name: 'Orca', siteId: 'site-1' }, - issueType: { id: '10001', name: 'Bug' }, - status: { id: '1', name: 'Todo', categoryKey: 'new', categoryName: 'To Do' }, - labels: [], - createdAt: '2026-05-30T00:00:00.000Z', - updatedAt: '2026-05-30T00:00:00.000Z', - ...overrides - } -} - -function makeGitLabWorkItem(overrides: Partial = {}): GitLabWorkItem { - return { - id: 'mr-12', - type: 'mr', - number: 12, - title: 'Fix runner routing', - state: 'opened', - url: 'https://gitlab.com/acme/repo/-/merge_requests/12', - labels: [], - updatedAt: '2026-05-30T00:00:00.000Z', - author: 'gitlab-user', - repoId: 'repo-1', - ...overrides - } -} - -describe('createUISlice settings navigation', () => { - it('accepts a host-qualified setup guide target', () => { - const store = createUIStore() - store.getState().openSettingsTarget({ pane: 'setup-guide', repoId: null, hostId: 'ssh:host-1' }) - expect(store.getState().settingsNavigationTarget).toEqual({ - pane: 'setup-guide', - repoId: null, - hostId: 'ssh:host-1' - }) - }) - - it('rejects malformed settings targets before storing them', () => { - const store = createUIStore() - const openSettingsTarget = store.getState().openSettingsTarget as unknown as ( - target: unknown - ) => void - - expect(() => - openSettingsTarget({ pane: 'repo', repoId: 'repo-1', hostId: 'invalid' }) - ).toThrowError('openSettingsTarget received an invalid navigation target') - expect(store.getState().settingsNavigationTarget).toBeNull() - }) - - it('prefetches the restored default task source when provider settings drifted', () => { - const store = createUIStore() - const prefetchWorkItems = vi.fn() - const prefetchLinearIssues = vi.fn() - - store.setState({ - repos: [ - { - id: 'repo-1', - path: '/repo', - displayName: 'Repo', - badgeColor: 'blue', - addedAt: 1, - kind: 'git' - } - ], - settings: { - visibleTaskProviders: ['linear'], - defaultTaskSource: 'github', - defaultTaskViewPreset: 'all' - } as unknown as AppState['settings'], - linearStatus: { connected: true } as AppState['linearStatus'], - preflightStatus: { glab: { installed: false } } as AppState['preflightStatus'], - prefetchWorkItems, - prefetchLinearIssues - } as unknown as Partial) - - store.getState().openTaskPage() - - expect(prefetchWorkItems).toHaveBeenCalledWith( - 'repo-1', - '/repo', - expect.any(Number), - 'is:issue is:open', - { sourceContext: null } - ) - expect(prefetchLinearIssues).not.toHaveBeenCalled() - }) - - it('prefetches direct GitHub task opens with their source context', () => { - const store = createUIStore() - const prefetchWorkItems = vi.fn() - const workItem = makeGitHubWorkItem() - const sourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'github', - projectId: 'project-1', - hostId: 'ssh:devbox', - projectHostSetupId: 'setup-1', - repoId: 'repo-1', - providerIdentity: { provider: 'github', owner: 'acme', repo: 'repo' } - } - - store.setState({ - repos: [ - { - id: 'repo-1', - path: '/repo', - displayName: 'Repo', - badgeColor: 'blue', - addedAt: 1, - kind: 'git' - } - ], - settings: { - visibleTaskProviders: ['github'], - defaultTaskSource: 'github', - defaultTaskViewPreset: 'all' - } as unknown as AppState['settings'], - prefetchWorkItems - } as unknown as Partial) - - store.getState().openTaskPage({ - taskSource: 'github', - preselectedRepoId: 'repo-1', - openGitHubWorkItem: workItem, - openGitHubSourceContext: sourceContext - }) - - expect(prefetchWorkItems).toHaveBeenCalledWith( - 'repo-1', - '/repo', - expect.any(Number), - 'is:issue is:open', - { sourceContext } - ) - }) - - it('prefetches direct Linear task opens with their source context', () => { - const store = createUIStore() - const prefetchLinearIssues = vi.fn() - const linearIssue = makeLinearIssue() - const sourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'linear', - projectId: 'project-1', - hostId: 'runtime:remote-server', - providerIdentity: { provider: 'linear', workspaceId: 'workspace-1' } - } - - store.setState({ - settings: { - visibleTaskProviders: ['linear'], - defaultTaskSource: 'linear' - } as unknown as AppState['settings'], - linearStatus: { connected: true } as AppState['linearStatus'], - prefetchLinearIssues - } as unknown as Partial) - - store.getState().openTaskPage({ - taskSource: 'linear', - openLinearIssue: linearIssue, - openLinearSourceContext: sourceContext - }) - - expect(prefetchLinearIssues).toHaveBeenCalledWith( - { kind: 'list', filter: 'all', limit: expect.any(Number) }, - { sourceContext } - ) - }) - - it('returns to the tasks page after visiting settings from an in-progress draft', () => { - const store = createUIStore() - - store.getState().openTaskPage({ preselectedRepoId: 'repo-1' }) - store.getState().openSettingsPage() - - expect(store.getState().activeView).toBe('settings') - expect(store.getState().previousViewBeforeSettings).toBe('tasks') - - store.getState().closeSettingsPage() - - expect(store.getState().activeView).toBe('tasks') - }) - - it('keeps the original return target when settings is reopened while already visible', () => { - const store = createUIStore() - - store.getState().openTaskPage() - store.getState().openSettingsPage() - store.getState().openSettingsPage() - - expect(store.getState().previousViewBeforeSettings).toBe('tasks') - - store.getState().closeSettingsPage() - - expect(store.getState().activeView).toBe('tasks') - }) - - it('returns to the graduated Agents view after visiting settings', () => { - const store = createUIStore() - - store.getState().openActivityPage() - expect(store.getState().activeView).toBe('activity') - - store.getState().openSettingsPage() - store.getState().closeSettingsPage() - - expect(store.getState().activeView).toBe('activity') - }) - - it('clears transient settings search when opening settings', () => { - const store = createUIStore() - - store.setState({ settingsSearchInputQuery: 'terminal', settingsSearchQuery: 'terminal' }) - store.getState().openSettingsPage() - - expect(store.getState().activeView).toBe('settings') - expect(store.getState().settingsSearchInputQuery).toBe('') - expect(store.getState().settingsSearchQuery).toBe('') - }) -}) - -describe('createUISlice page navigation history', () => { - it('records and rewinds Tasks visits on close', () => { - const store = createUIStore() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openTaskPage() - expect(store.getState().worktreeNavHistory).toEqual(['a', 'tasks']) - expect(store.getState().worktreeNavHistoryIndex).toBe(1) - - store.getState().closeTaskPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('rewinds Tasks detail visits on close', () => { - const store = createUIStore() - const workItem = makeGitHubWorkItem() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openTaskPage({ taskSource: 'github', openGitHubWorkItem: workItem }) - expect(store.getState().worktreeNavHistory).toEqual([ - 'a', - 'tasks', - { - kind: 'task-detail', - source: 'github', - workItem, - sourceContext: undefined, - initialTab: undefined - } - ]) - expect(store.getState().worktreeNavHistoryIndex).toBe(2) - - store.getState().closeTaskPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().taskPageData).toEqual({}) - expect(store.getState().githubTaskDrawerWorkItem).toBeNull() - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('records provider-depth interactions for direct Tasks detail opens', () => { - const store = createUIStore() - const recordFeatureInteraction = vi.fn() - store.setState({ recordFeatureInteraction } as Partial) - const workItem = makeGitHubWorkItem() - const linearIssue = makeLinearIssue() - const jiraIssue = makeJiraIssue() - - store.getState().openTaskPage({ taskSource: 'github', openGitHubWorkItem: workItem }) - store.getState().openTaskPage({ taskSource: 'linear', openLinearIssue: linearIssue }) - store.getState().openTaskPage({ taskSource: 'jira', openJiraIssue: jiraIssue }) - - expect(recordFeatureInteraction).toHaveBeenCalledWith('tasks') - expect(recordFeatureInteraction).toHaveBeenCalledWith('github-tasks') - expect(recordFeatureInteraction).toHaveBeenCalledWith('linear-tasks') - expect(recordFeatureInteraction).toHaveBeenCalledWith('jira-tasks') - }) - - it('preserves GitHub task detail source context in navigation history', () => { - const store = createUIStore() - const workItem = makeGitHubWorkItem({ repoId: 'repo-remote' }) - const sourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'github', - projectId: 'project-1', - hostId: 'ssh:devbox', - projectHostSetupId: 'setup-1', - repoId: 'repo-remote', - providerIdentity: { provider: 'github', owner: 'stablyai', repo: 'orca' } - } - - store.getState().openTaskPage({ - taskSource: 'github', - openGitHubWorkItem: workItem, - openGitHubSourceContext: sourceContext - }) - - expect(store.getState().worktreeNavHistory.at(-1)).toEqual({ - kind: 'task-detail', - source: 'github', - workItem, - sourceContext, - initialTab: undefined - }) - }) - - it('preserves Linear task detail source context in navigation history', () => { - const store = createUIStore() - const linearIssue = makeLinearIssue() - const sourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'linear', - projectId: 'project-1', - hostId: 'runtime:remote-server', - providerIdentity: { provider: 'linear', workspaceId: 'workspace-1' } - } - - store.getState().openTaskPage({ - taskSource: 'linear', - openLinearIssue: linearIssue, - openLinearSourceContext: sourceContext - }) - - expect(store.getState().worktreeNavHistory.at(-1)).toEqual({ - kind: 'task-detail', - source: 'linear', - issue: linearIssue, - sourceContext - }) - }) - - it('preserves GitLab task detail source context in navigation history', () => { - const store = createUIStore() - const workItem = makeGitLabWorkItem({ repoId: 'repo-remote' }) - const sourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'gitlab', - projectId: 'project-1', - hostId: 'ssh:devbox', - projectHostSetupId: 'setup-1', - repoId: 'repo-remote', - providerIdentity: { provider: 'gitlab', projectId: '1234' } - } - - store.getState().openTaskPage({ - taskSource: 'gitlab', - openGitLabWorkItem: workItem, - openGitLabSourceContext: sourceContext - }) - - expect(store.getState().worktreeNavHistory.at(-1)).toEqual({ - kind: 'task-detail', - source: 'gitlab', - workItem, - sourceContext - }) - }) - - it('preserves Jira task detail source context in navigation history', () => { - const store = createUIStore() - const issue = makeJiraIssue() - const sourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'jira', - projectId: 'project-1', - hostId: 'runtime:remote-server', - providerIdentity: { provider: 'jira', siteId: 'site-1' }, - accountLabel: 'Example Jira' - } - - store.getState().openTaskPage({ - taskSource: 'jira', - openJiraIssue: issue, - openJiraSourceContext: sourceContext - }) - - expect(store.getState().worktreeNavHistory.at(-1)).toEqual({ - kind: 'task-detail', - source: 'jira', - issue, - sourceContext - }) - }) - - it('can suppress the Tasks surface interaction for in-page provider navigation', () => { - const store = createUIStore() - const recordFeatureInteraction = vi.fn() - store.setState({ recordFeatureInteraction } as Partial) - const workItem = makeGitHubWorkItem() - const linearIssue = makeLinearIssue() - const jiraIssue = makeJiraIssue() - - store - .getState() - .openTaskPage( - { taskSource: 'github', openGitHubWorkItem: workItem }, - { recordTasksInteraction: false } - ) - store - .getState() - .openTaskPage( - { taskSource: 'linear', openLinearIssue: linearIssue }, - { recordTasksInteraction: false } - ) - store - .getState() - .openTaskPage( - { taskSource: 'jira', openJiraIssue: jiraIssue }, - { recordTasksInteraction: false } - ) - - expect(recordFeatureInteraction).not.toHaveBeenCalledWith('tasks') - expect(recordFeatureInteraction).toHaveBeenCalledWith('github-tasks') - expect(recordFeatureInteraction).toHaveBeenCalledWith('linear-tasks') - expect(recordFeatureInteraction).toHaveBeenCalledWith('jira-tasks') - }) - - it('skips the whole Tasks detail stack on close', () => { - const store = createUIStore() - const workItem = makeGitHubWorkItem() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openTaskPage({ taskSource: 'github', openGitHubWorkItem: workItem }) - store.getState().openTaskPage({ taskSource: 'linear' }) - expect(store.getState().worktreeNavHistory).toEqual([ - 'a', - 'tasks', - { - kind: 'task-detail', - source: 'github', - workItem, - sourceContext: undefined, - initialTab: undefined - }, - 'tasks' - ]) - - store.getState().closeTaskPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('records and rewinds Automations visits on close', () => { - const store = createUIStore() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openAutomationsPage() - expect(store.getState().worktreeNavHistory).toEqual(['a', 'automations']) - expect(store.getState().worktreeNavHistoryIndex).toBe(1) - - store.getState().closeAutomationsPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('dedupes repeated Automations opens against the current history entry', () => { - const store = createUIStore() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openAutomationsPage() - store.getState().openAutomationsPage() - - expect(store.getState().activeView).toBe('automations') - expect(store.getState().worktreeNavHistory).toEqual(['a', 'automations']) - expect(store.getState().worktreeNavHistoryIndex).toBe(1) - }) - - it('keeps the Automations history index when Automations is the only entry', () => { - const store = createUIStore() - - store.getState().openAutomationsPage() - expect(store.getState().worktreeNavHistory).toEqual(['automations']) - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - - store.getState().closeAutomationsPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('skips deleted prior worktrees when closing Automations', () => { - const store = createUIStore() - store.setState({ - activeView: 'automations', - previousViewBeforeAutomations: 'terminal', - worktreesByRepo: { 'repo-1': [makeWorktree('c')] }, - worktreeNavHistory: ['c', 'a', 'automations'], - worktreeNavHistoryIndex: 2 - }) - - store.getState().closeAutomationsPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) -}) - -describe('createUISlice space navigation', () => { - it('opens desktop Space without replacing the current view', () => { - const openWindow = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { set: vi.fn(() => Promise.resolve()) }, - workspaceSpace: { openWindow } - } - }) - const store = createUIStore() - store.getState().openTaskPage() - - store.getState().openSpacePage() - - expect(openWindow).toHaveBeenCalledOnce() - expect(store.getState().activeView).toBe('tasks') - }) - - it('records Space page opens as workspace cleanup interactions', () => { - const setMock = vi.fn(() => Promise.resolve()) - vi.stubGlobal('window', { - api: { - ui: { - set: setMock - } - } - }) - const now = 1_700_000_000_000 - vi.useFakeTimers() - vi.setSystemTime(now) - - try { - const store = createUIStore() - store.getState().hydratePersistedUI(makePersistedUI()) - setMock.mockClear() - - store.getState().openSpacePage() - - const expected: FeatureInteractionState = { - 'workspace-cleanup': { firstInteractedAt: now, interactionCount: 1 } - } - expect(store.getState().featureInteractions).toEqual(expected) - expect(setMock).toHaveBeenCalledWith({ featureInteractions: expected }) - } finally { - vi.useRealTimers() - } - }) - - it('returns to the tasks page after opening Space from an in-progress draft', () => { - const store = createUIStore() - - store.getState().openTaskPage({ preselectedRepoId: 'repo-1' }) - store.getState().openSpacePage() - - expect(store.getState().activeView).toBe('space') - expect(store.getState().previousViewBeforeSpace).toBe('tasks') - - store.getState().closeSpacePage() - - expect(store.getState().activeView).toBe('tasks') - }) - - it('keeps the original return target when Space is reopened while already visible', () => { - const store = createUIStore() - - store.getState().openTaskPage() - store.getState().openSpacePage() - store.getState().openSpacePage() - - expect(store.getState().previousViewBeforeSpace).toBe('tasks') - - store.getState().closeSpacePage() - - expect(store.getState().activeView).toBe('tasks') - }) - - it('returns to the originating view after closing Artifacts', () => { - const store = createUIStore() - - store.getState().openTaskPage() - store.getState().openArtifactsPage() - - expect(store.getState().activeView).toBe('artifacts') - expect(store.getState().previousViewBeforeArtifacts).toBe('tasks') - - store.getState().closeArtifactsPage() - - expect(store.getState().activeView).toBe('tasks') - }) - - it('records and rewinds Artifacts visits on close', () => { - const store = createUIStore() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openArtifactsPage() - expect(store.getState().worktreeNavHistory).toEqual(['a', 'artifacts']) - expect(store.getState().worktreeNavHistoryIndex).toBe(1) - - store.getState().closeArtifactsPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('records and rewinds Skills visits on close', () => { - const store = createUIStore() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openSkillsPage() - expect(store.getState().worktreeNavHistory).toEqual(['a', 'skills']) - expect(store.getState().worktreeNavHistoryIndex).toBe(1) - - store.getState().closeSkillsPage() - expect(store.getState().activeView).toBe('terminal') - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('records Artifacts and Skills as separate back/forward entries', () => { - const store = createUIStore() - store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } }) - - store.getState().recordWorktreeVisit('a') - store.getState().openArtifactsPage() - store.getState().openSkillsPage() - store.getState().openSkillsPage() - - expect(store.getState().worktreeNavHistory).toEqual(['a', 'artifacts', 'skills']) - expect(store.getState().worktreeNavHistoryIndex).toBe(2) - }) - - it('records a Skills visit when opening a shared skill link', () => { - const store = createUIStore() - - store.getState().openSkillShare('share-1') - store.getState().openSkillsSharedLinks() - - expect(store.getState().worktreeNavHistory).toEqual(['skills']) - expect(store.getState().worktreeNavHistoryIndex).toBe(0) - }) - - it('opens and restores Artifacts when its sidebar shortcut is hidden', () => { - const store = createUIStore() - store.setState({ settings: { ...getDefaultSettings('/tmp'), showArtifactsButton: false } }) - - store.getState().openArtifactsPage() - expect(store.getState().activeView).toBe('artifacts') - - store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'artifacts' }), 'startup') - expect(store.getState().activeView).toBe('artifacts') - }) -}) diff --git a/src/renderer/src/store/slices/workspace-activation-preparation.test.ts b/src/renderer/src/store/slices/workspace-activation-preparation.test.ts index 141cbaa3a89..53bfb81dd33 100644 --- a/src/renderer/src/store/slices/workspace-activation-preparation.test.ts +++ b/src/renderer/src/store/slices/workspace-activation-preparation.test.ts @@ -74,32 +74,6 @@ it.each([ ) }) -it.each(['folder', 'git'] as const)('preserves a live %s terminal on repeat activation', (kind) => { - const { store, workspaceId, activate } = seedWorkspace(kind, 'local') - store.setState({ ptyIdsByTabId: { terminal: ['live-pty'] } }) - activate() - const activated = store.getState() - - activate() - - expect(store.getState()).toBe(activated) - expect(store.getState().tabsByWorktree[workspaceId][0].generation).toBe(3) -}) - -it.each(['folder', 'git'] as const)( - 'wakes an already-selected %s after its PTY is released', - (kind) => { - const { store, workspaceId, activate } = seedWorkspace(kind, 'local') - store.setState({ ptyIdsByTabId: { terminal: ['live-pty'] } }) - activate() - store.setState({ ptyIdsByTabId: {} }) - - activate() - - expect(store.getState().tabsByWorktree[workspaceId][0].generation).toBe(4) - } -) - it('reads only the selected folder owner on screen and persists to that host', () => { const { store, activate } = seedWorkspace('folder', 'ssh:remote') const updateFolderWorkspace = vi.fn().mockResolvedValue(null) @@ -121,12 +95,3 @@ it('reads only the selected folder owner on screen and persists to that host', ( { executionHostId: 'ssh:remote' } ) }) - -it('leaves selection unchanged when the requested folder owner is absent', () => { - const { store } = seedWorkspace('folder', 'local') - const before = store.getState() - - store.getState().setActiveFolderWorkspace(FOLDER_ID, 'ssh:missing') - - expect(store.getState()).toBe(before) -})