From 376cf18634b147e5b79fa2c195041b20c4302cb1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:19:13 -0800 Subject: [PATCH] perf(native-chat): addressed tab-map transitions for chat membership (#40098) * perf(native-chat): project structured chat tabs per workspace bucket The shared chat-tab list was keyed on the whole unifiedTabsByWorktree identity, so every tab write anywhere (terminal title batches included) rescanned all tabs and handed every consumer a new list. Rebuild only the buckets whose identity changed and return the previous list while no chat tab changed. Co-Authored-By: Claude Opus 5.5 (1M context) * perf(native-chat): reconcile chat status membership per changed tab The status bridge rebuilt every member and host group and captured every chat on any tab-map or owner-input change, and recaptured every chat on any launch notification. Membership now updates only the tabs whose identity changed; owner-input changes re-resolve only unstamped tabs, the only ones whose host depends on them; launch notifications name their session so only its tabs are recaptured (unaddressed ones still recapture all). The sleep and launch-directory companions of one projection land in one store write. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(ratchets): guard whole tab-map triggers and hot-map listeners Add a count ratchet for identity comparisons of the whole unifiedTabsByWorktree/tabsByWorktree map in renderer code (counts may only fall), wired into pnpm lint, run-ratchets discovery and changed-check selection. Extend the advisory no-whole-hot-map-selector rule to inline store listeners that compare a whole hot map and to effect bodies that use one whole from getState(). Co-Authored-By: Claude Opus 5.5 (1M context) * revert(lint): drop the hot-map listener/effect extension The guard stays scoped to the repaired seams; no repository-wide rule change. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(native-chat): capture chat status on semantic tab changes; address tombstone retirement Focus, preview and order-only tab writes no longer recapture a chat's status: membership and the projection fences compare the fields the projection reads. Absent-tombstone retirement now names the sessions it retired, so no launch producer sends an unaddressed notification. Co-Authored-By: Claude Opus 5.5 (1M context) * feat(store): keyed-record transition seam for tab maps and companion records Writers build next tab buckets and keyed companion records through replaceTabBuckets / replaceRecordEntries (or name the keys of a record they already built), which record exactly which keys and tab IDs changed against the produced record. Readers ask readTabMapChanges / readRecordChanges for an addressed delta; any unannotated link reads as a full resync. Adds subscribeTabTransitions and a store-observer installer registry. The chat-tab list and the status bridge now consume addressed deltas and keep the whole-list walk only as the cold path. Co-Authored-By: Claude Opus 5.5 (1M context) * feat(store): annotate every shared tab-map writer through the seam Shared tabsByWorktree/unifiedTabsByWorktree writers (tab, editor, browser, worktree, ssh, terminal create/close/navigation/title-batch/reconnect/ hydration, web-session mirroring and layout frames) now build or annotate their next tab buckets and companion records with the exact workspace and tab IDs they changed; full hydration, full frame builds and reconnect inventories are named full resyncs. Writers that copied every bucket for one tab (preview promotion, dirty-file preview clear, worktree removal filters, sleeping-record identity rename) now keep unchanged buckets. Replace the renderer-wide tab-map comparison ratchet with a narrow seam guard: the repaired consumers may walk a whole tab map only in named cold paths, and the pinned writer modules may not build raw seam records. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(store): name seam fields once; type seam records; record moved respawn writes Writers stop repeating tracked field names (centralized in seam-record-fields.ts), the seam takes a named KeyedSnapshot record type instead of casts, and the layout-writer baseline records the respawn helpers moved unchanged out of worktree-layout-lifecycle.ts. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(store): drop seam field cast; record the seam field list in the layout-writer baseline Co-Authored-By: Claude Opus 5.5 (1M context) * fix(native-chat): keep chat-tab list in source workspace order (C3/F1) Every source workspace keeps a projection slot, even without chats, and the seam reports when a write added or deleted a workspace key or moved a surviving bucket, so the incremental list never reorders first-match consumers; those transitions take the cold rebuild. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(native-chat): keep projection and retirement debt awake (C2, F3) A member is owed from attach or semantic change, members without a host feed keep their own debt, and every reconciliation drains existing owed or retired work even when no new member changed, including a closed last chat whose feed is gone. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(store): stop inferring host-mirror companion IDs from visible tabs (C1) A host retraction can delete PTY or layout records for tabs neither inventory lists, so the mirror funnel marks its tab-keyed records full resync instead of advertising an incomplete addressed set. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(ratchets): close indirect paths in the tab-map seam guard (C4) The guard now rejects ordinary callers of the bridge cold path, value imports the repaired consumers have not reviewed, and raw seam records built into a local binding without a seam helper annotating it. Co-Authored-By: Claude Opus 5.5 (1M context) * test(native-chat): drive real tab actions through the status bridge (F2) Close, session rebind with a late old-session tick, and a legacy owner change, through createUnifiedTab/setTabLabel/closeUnifiedTab, so the addressed reconciliation path is exercised. Co-Authored-By: Claude Opus 5.5 (1M context) * chore: exempt seam field-name constants from the layout-writer ratchet; drop dead setters (F4) The seam's SEAM_*_FIELDS lists name fields without writing them, so the ratchet skips them and the raised baseline row is gone (renderer total 569, main 571). setStructuredChatSleptAt and the two launch-directory setters lost their last callers to the batched companion write. Co-Authored-By: Claude Opus 5.5 (1M context) * feat(store): Map provenance and source-ordered change keys in the seam (PR A addenda) replaceMapEntries gives Map-typed fields (runtimeStatusByEnvironmentId) the same weak provenance and readRecordChanges protocol. Change keys compose forward through a chain, oldest write first, so added keys come out in source order (index keys first for records, as Object.keys orders them). A surviving key deleted and re-added, in one write or across a chain, and a record builder that moves a surviving key, read as a 'reordered' full resync. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(store): writers declare key order; seam reports ordered additions (N1c, N1a) The seam no longer scans both records to rediscover order on every annotation. replace* helpers know insertion order by construction; annotate* takes a declared order ('appended' by default, 'reordered' for a builder that moves keys, read as a full resync), verified only under test. Addressed changes now report keys, source-ordered added keys and deleted keys, so a reader holding its own key ranks places changes in O(changed). Worktree removal declares its editor-transfer records reordered. Co-Authored-By: Claude Opus 5.5 (1M context) * perf(native-chat): scope the chat-tab projection to chat-bearing workspaces (N2c) The projection keeps chat subsets only for workspaces that have chats, plus per-workspace source ranks that change only when a workspace is added or deleted. A focus, label or title write costs O(that workspace); the ordered list is materialized lazily, only for full-list readers, and keeps its identity while no chat changed. Workspace adds and deletes are addressed through the ranks instead of a cold rebuild. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(ratchets): resolve aliases and require annotation before publication (C4) Any reference to a cold helper or Object enumerator outside its named callers counts, including aliases and callbacks; writer values are followed through local aliases and must be annotated before the write that publishes them. Co-Authored-By: Claude Opus 5.5 (1M context) * test(native-chat): scoped hydration keeps the warm chat list equal to a cold read (D1) Drives the real scoped hydrateTabsSession on early/later chats of one session: source order, list order and first-match precedence match a cold rebuild, including when the selection order differs from hydrated order. Co-Authored-By: Claude Opus 5.5 (1M context) * perf(native-chat): cache the chat-workspace order across chat edits (D1 item 5) The lineage keeps chat-bearing workspaces in rank order and only inserts or removes one when it gains its first or loses its last chat; a chat object change re-flattens the list without re-sorting. Full resyncs rebuild it. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(ratchets): the seam guard recognizes only construction helpers and cold marks (D1) Co-Authored-By: Claude Opus 5.5 (1M context) * refactor(store): addressed provenance only from constructing helpers (D1) Remove annotateRecordReplacement/annotateTabBucketReplacement and their caller-declared order: only replace*/recordDraft/tabBucketDraft, which perform the construction, derive changed keys, additions and deletions from their operations (delete-then-reinsert reads as reordered); opaque reconstructions use markFullResync. Every former annotate caller is migrated: ordinary local writes build their records once through helpers or drafts with today's operations and order; scoped tab and terminal hydration, the reconnect inventory, host-mirror application and layout flush are full resyncs. Change readers move to keyed-record-change-reads.ts. Renderer layout-writer total 567 (main 571). Co-Authored-By: Claude Opus 5.5 (1M context) * test(native-chat): type the hydration fixture without a cast Co-Authored-By: Claude Opus 5.5 (1M context) * fix(store): seam record writes define own entries, even __proto__ (N5c) replaceRecordEntries and drafts assigned through the inherited __proto__ setter, so a tab id '__proto__' lost its own PTY, layout and startup entries. Both now define an own data property, as the computed-key literals they replaced did; contract test included. Co-Authored-By: Claude Opus 5.5 (1M context) * perf(terminal): build each createTab record once (N4c) createTab took ensureGroup's and insertSplitGroup's whole records and the orphan cleanup's seam records, then rebuilt them through the seam. It now takes the per-worktree group and split results and gives the orphan cleanup only the bucket it reads, so every seam record is constructed once with its ordered operations. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(ratchets): record createTab's orphan-cleanup input view (renderer total 570, main 571) Co-Authored-By: Claude Opus 5.5 (1M context) * refactor(terminal): split orphan cleanup so createTab cleans only companion caches (N6c) buildOrphanTerminalCompanionCleanupPatch holds the per-tab cache, tab-bar order and selection cleanup; buildOrphanTerminalCleanupPatch adds the seam record deletes on top, unchanged for reconciliation. createTab calls only the companion part with real state and deletes the seam entries through its single construction, so the stub input view and its layout-writer baseline rise are gone (terminal-tab-creation.ts back to 10). Co-Authored-By: Claude Opus 5.5 (1M context) * perf(terminal): filter the orphan cleanup's kept bucket once (N7c) The full cleanup filters the workspace's tabs once and hands the kept bucket to the companion part, which takes its replacement active tab from it; createTab's companion-only call still makes its single find pass. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(tabs): keep removed worktrees' group entries deleted on removal The second emptied-group collapse in removeWorktreeLayout also visited removed worktrees and wrote their deleted groupsByWorktree entry back as an empty list, a delete-then-set the seam read as a reordered full resync. It now visits only surviving workspaces, so removal stays addressed. Co-Authored-By: Claude Opus 5.5 (1M context) * chore(tabs): closeEmptyGroup collapses through the shared builder again collapseGroupLayout takes the record builder, and the renderer passes the seam's replaceRecordEntries, so the per-worktree collapse publishes with provenance without new counted layout writes (tabs-group-actions back to 12). Co-Authored-By: Claude Opus 5.5 (1M context) * chore(tabs): reconciliation names its draft fields once (2 + 4 <= 9) The written-field sets come from SEAM_ field-name constants instead of string literals, so the reconciliation split no longer raises the combined layout-writer count (tabs-reconciliation 2, tabs-reconciliation-batch 4, against the original 9). Co-Authored-By: Claude Opus 5.5 (1M context) * chore(tabs): publish reconciliation drafts with explicit field writes (N9c) Revert the SEAM_ field-name constants: the drafts are held under their own names and finishReconciliationDrafts publishes each written draft as an explicit unifiedTabsByWorktree/groupsByWorktree/activeGroupIdByWorktree/ layoutByWorktree property, so the counter sees every real write and the split totals 2 + 4 against the original 9, with no exemption. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- config/main-layout-writer-baseline.txt | 4 +- config/renderer-layout-writer-baseline.txt | 18 +- .../check-changed-selection.mjs | 1 + .../preflight/changed-checks/run-lint.mjs | 1 + .../check-layout-writer-ratchets.mjs | 21 +- .../check-tab-map-seam-ratchet.mjs | 380 ++++++++++++++++++ .../check-tab-map-seam-ratchet.test.mjs | 87 ++++ package.json | 1 + .../StructuredAgentSessionStatusBridge.tsx | 332 +++++++-------- ...session-status-bridge-tab-actions.test.tsx | 234 +++++++++++ ...uctured-agent-session-status-membership.ts | 199 +++++++++ ...agent-session-tabs-hydration-order.test.ts | 96 +++++ .../structured-agent-session-tabs.test.ts | 66 +++ .../status/structured-agent-session-tabs.ts | 212 ++++++++-- ...uctured-chat-activity-status-live.test.tsx | 18 +- .../structured-agent-session-action-launch.ts | 2 +- .../structured-agent-session-launch-cancel.ts | 2 +- ...red-agent-session-launch-create-message.ts | 4 +- .../structured-agent-session-launch-input.ts | 2 +- ...d-agent-session-launch-outcome-tracking.ts | 12 +- ...d-agent-session-launch-persistence.test.ts | 2 +- ...ctured-agent-session-launch-persistence.ts | 10 +- ...red-agent-session-launch-prompt-outcome.ts | 4 +- ...session-launch-publication-confirmation.ts | 2 +- ...ctured-agent-session-launch-publication.ts | 4 +- ...tructured-agent-session-launch-registry.ts | 27 +- .../launch/structured-agent-session-launch.ts | 10 +- ...tured-agent-session-launch-cancellation.ts | 8 +- .../scoped-patch-annotation.ts | 13 + .../web-session-tabs-sync/store-patch.ts | 2 + .../frames/workspace-layout-frame-sync.ts | 4 +- src/renderer/src/store/index.ts | 7 + .../src/store/keyed-record-change-reads.ts | 109 +++++ .../src/store/keyed-record-index-keys.ts | 5 + .../store/keyed-record-transitions.test.ts | 186 +++++++++ .../src/store/keyed-record-transitions.ts | 289 +++++++++++++ src/renderer/src/store/seam-record-fields.ts | 46 +++ .../structured-chat-companion-writes.ts | 67 +++ .../agent-status/structured-chat-slept-at.ts | 29 +- .../structured-session-launch-directories.ts | 78 ++-- .../pages/browser-page-state-actions.ts | 29 +- .../file-ids/hydrated-editor-file-ids.ts | 30 +- .../restored-editor-owner-in-place.ts | 49 ++- .../restored-editor-owner-transition.ts | 70 ++-- .../markdown/markdown-preview-actions.ts | 16 +- .../editor/opening/open-file-mutations.ts | 41 +- .../store/slices/ssh/ssh-target-cleanup.ts | 24 +- .../tabs/collapse-emptied-kept-groups.ts | 61 +-- .../tabs/kept-worktree-surface-pruning.ts | 32 +- .../slices/tabs/rename-worktree-layout.ts | 44 +- .../src/store/slices/tabs/tab-group-state.ts | 42 +- .../store/slices/tabs/tabs-close-actions.ts | 49 ++- .../store/slices/tabs/tabs-create-actions.ts | 100 +++-- .../slices/tabs/tabs-drag-preview-actions.ts | 66 +-- .../store/slices/tabs/tabs-drop-actions.ts | 78 ++-- .../store/slices/tabs/tabs-focus-actions.ts | 66 +-- .../store/slices/tabs/tabs-group-actions.ts | 89 ++-- .../store/slices/tabs/tabs-host-mirroring.ts | 3 +- .../store/slices/tabs/tabs-label-actions.ts | 60 +-- .../store/slices/tabs/tabs-move-actions.ts | 58 +-- .../slices/tabs/tabs-reconciliation-batch.ts | 71 +++- .../store/slices/tabs/tabs-reconciliation.ts | 97 ++--- .../store/slices/tabs/tabs-session-actions.ts | 33 +- .../slices/tabs/tabs-split-ratio-actions.ts | 17 +- .../slices/tabs/worktree-layout-lifecycle.ts | 173 ++++---- .../tabs/worktree-terminal-tab-respawn.ts | 68 ++++ .../worktrees/session/set-active-worktree.ts | 2 +- .../session/worktree-identity-rename-state.ts | 19 +- .../session/worktree-slice-lookups.ts | 15 +- .../worktrees/teardown/record-key-omission.ts | 12 +- .../src/store/store-observer-installers.ts | 11 + .../src/store/tab-transition-subscription.ts | 33 ++ .../terminal-companion-record-operations.ts | 17 + .../terminals/terminal-orphan-cleanup.ts | 116 ++++-- .../src/store/terminals/terminal-tab-close.ts | 50 ++- .../store/terminals/terminal-tab-creation.ts | 156 ++++--- .../terminals/terminal-tab-navigation.ts | 5 +- .../terminals/terminal-tab-title-batch.ts | 24 +- .../workspace-terminal-hydration-patch.ts | 46 ++- .../terminals/workspace-terminal-hydration.ts | 9 +- .../terminals/workspace-terminal-reconnect.ts | 28 +- .../store/testing/app-store-test-fixture.ts | 2 + src/renderer/src/store/types.ts | 2 + .../workspace-layout-frame-store-patch.ts | 10 +- .../workspace-layout/tab-group-layout-tree.ts | 46 ++- 85 files changed, 3517 insertions(+), 1146 deletions(-) create mode 100644 config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs create mode 100644 config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs create mode 100644 src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx create mode 100644 src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts create mode 100644 src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts create mode 100644 src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts create mode 100644 src/renderer/src/runtime/web-session-tabs-sync/scoped-patch-annotation.ts create mode 100644 src/renderer/src/store/keyed-record-change-reads.ts create mode 100644 src/renderer/src/store/keyed-record-index-keys.ts create mode 100644 src/renderer/src/store/keyed-record-transitions.test.ts create mode 100644 src/renderer/src/store/keyed-record-transitions.ts create mode 100644 src/renderer/src/store/seam-record-fields.ts create mode 100644 src/renderer/src/store/slices/agent-status/structured-chat-companion-writes.ts create mode 100644 src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts create mode 100644 src/renderer/src/store/store-observer-installers.ts create mode 100644 src/renderer/src/store/tab-transition-subscription.ts create mode 100644 src/renderer/src/store/terminals/terminal-companion-record-operations.ts diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 096973f7717..00c1afab41e 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -32,6 +32,7 @@ 2 src/main/persistence/migrating-orcad-catalog/orcad-destination-client-state.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts 3 src/main/persistence/migrating-orcad-catalog/orcad-dormant-state-records.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts 2 src/main/persistence/migrating-orcad-catalog/orcad-source-client-subtraction.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-source-dormant-state.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-source-scrollback-state.ts @@ -53,11 +54,11 @@ 2 src/main/pty/scrollback/terminal-scrollback-snapshots.ts 1 src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.ts 1 src/main/runtime/client/runtime-client-state.ts -1 src/main/runtime/session-tabs/headless-editor-tabs.ts 4 src/main/runtime/orchestration/terminal-authority/runtime-legacy-worker-terminal-recovery-persistence.ts 2 src/main/runtime/session-graph/session-graph-promotion.ts 2 src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts 2 src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts +1 src/main/runtime/session-tabs/headless-editor-tabs.ts 2 src/main/runtime/session-tabs/headless-tab-group-moves.ts 6 src/main/runtime/session-tabs/headless-tab-properties.ts 2 src/main/runtime/session-tabs/headless-terminal-tab-titles.ts @@ -72,5 +73,4 @@ 3 src/main/runtime/terminal/surface/mobile-session-layout-projection.ts 1 src/main/runtime/workspaces/session-hosts/get-runtime-id.ts 1 src/main/runtime/workspaces/session-hosts/runtime-workspace-session-controller.ts -1 src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts 1 src/main/ssh/targets/ssh-target-id-migration.ts diff --git a/config/renderer-layout-writer-baseline.txt b/config/renderer-layout-writer-baseline.txt index 96f667bb196..1c132f4e79c 100644 --- a/config/renderer-layout-writer-baseline.txt +++ b/config/renderer-layout-writer-baseline.txt @@ -27,6 +27,7 @@ 3 src/renderer/src/lib/workspace/persistence/workspace-session-staged-browser-tabs.ts 1 src/renderer/src/lib/workspace/persistence/workspace-session-unified-tabs.ts 17 src/renderer/src/lib/workspace/persistence/workspace-session.ts +13 src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts 3 src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-recovery-snapshot-validation.ts 1 src/renderer/src/runtime/hosted-terminals/recovery/surfaces/web-session-terminal-orphan-recovery-surface.ts 2 src/renderer/src/runtime/hosted-terminals/recovery/surfaces/web-session-terminal-orphan-topology.ts @@ -35,15 +36,14 @@ 10 src/renderer/src/runtime/sync-runtime-graph/mobile-session-group-projection.ts 2 src/renderer/src/runtime/sync-runtime-graph/mobile-session-snapshots.ts 2 src/renderer/src/runtime/sync-runtime-graph/sync-key.ts -13 src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts -1 src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot.ts -3 src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-client-owned-tab-placement.ts 1 src/renderer/src/runtime/web-session-tabs-sync/agent-status-primitives.ts 8 src/renderer/src/runtime/web-session-tabs-sync/apply-active-state.ts 18 src/renderer/src/runtime/web-session-tabs-sync/apply-final-patch.ts 2 src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-groups.ts 5 src/renderer/src/runtime/web-session-tabs-sync/apply-terminal-records.ts 4 src/renderer/src/runtime/web-session-tabs-sync/apply-worktree-records.ts +1 src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot.ts +3 src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-client-owned-tab-placement.ts 2 src/renderer/src/runtime/web-session-tabs-sync/session-tabs-inventory-absence.ts 10 src/renderer/src/store/slices/browser/cleanup/browser-close-actions.ts 2 src/renderer/src/store/slices/browser/create-browser-slice.ts @@ -57,7 +57,7 @@ 9 src/renderer/src/store/slices/editor/checks/check-run-details-actions.ts 6 src/renderer/src/store/slices/editor/closing/close-file-action.ts 10 src/renderer/src/store/slices/editor/closing/recently-closed-editor-tabs.ts -3 src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts +1 src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts 2 src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-selection.ts 1 src/renderer/src/store/slices/editor/file-ids/open-file-path-rekey.ts 2 src/renderer/src/store/slices/editor/file-ids/rekey-open-files-action.ts @@ -82,7 +82,7 @@ 4 src/renderer/src/store/slices/tabs/tab-group-state.ts 9 src/renderer/src/store/slices/tabs/tabs-close-actions.ts 14 src/renderer/src/store/slices/tabs/tabs-create-actions.ts -23 src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts +22 src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts 11 src/renderer/src/store/slices/tabs/tabs-drop-actions.ts 8 src/renderer/src/store/slices/tabs/tabs-empty-workspace.ts 4 src/renderer/src/store/slices/tabs/tabs-focus-actions.ts @@ -91,11 +91,13 @@ 1 src/renderer/src/store/slices/tabs/tabs-hydration.ts 8 src/renderer/src/store/slices/tabs/tabs-label-actions.ts 10 src/renderer/src/store/slices/tabs/tabs-move-actions.ts -9 src/renderer/src/store/slices/tabs/tabs-reconciliation.ts +4 src/renderer/src/store/slices/tabs/tabs-reconciliation-batch.ts # split from tabs-reconciliation.ts (9 -> 2 + 4) +2 src/renderer/src/store/slices/tabs/tabs-reconciliation.ts 4 src/renderer/src/store/slices/tabs/tabs-session-actions.ts 1 src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts 5 src/renderer/src/store/slices/tabs/tabs-surface.ts -24 src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts +19 src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts +3 src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts # moved unchanged out of worktree-layout-lifecycle.ts (24 -> 19 + 3) 5 src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts 2 src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts 6 src/renderer/src/store/terminals/create-terminal-slice.ts @@ -112,7 +114,7 @@ 10 src/renderer/src/store/terminals/terminal-tab-creation.ts 7 src/renderer/src/store/terminals/terminal-tab-navigation.ts 3 src/renderer/src/store/terminals/terminal-tab-presentation.ts -4 src/renderer/src/store/terminals/terminal-tab-title-batch.ts +2 src/renderer/src/store/terminals/terminal-tab-title-batch.ts 5 src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts 2 src/renderer/src/store/terminals/workspace-terminal-hydration.ts 2 src/renderer/src/store/terminals/workspace-terminal-reconnect.ts diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 99d3c46bff0..f8f576a27a5 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -47,6 +47,7 @@ const RATCHET_INPUTS = { 'check-render-path-translate-ratchet.mjs': ['src/renderer/src/'], 'check-repo-host-read-ratchet.mjs': ['src/cli/', 'src/main/', 'src/shared/'], 'check-runtime-electron-ratchet.mjs': ['src/main/', 'src/cli/', 'src/shared/'], + 'check-tab-map-seam-ratchet.mjs': ['src/renderer/src/'], 'check-unproven-pty-retirement-ratchet.mjs': ['src/main/'], 'check-workspace-record-read-ratchet.mjs': ['src/renderer/src/'], 'check-worktree-id-composer-ratchet.mjs': ['src/', 'mobile/src/'] diff --git a/config/scripts/preflight/changed-checks/run-lint.mjs b/config/scripts/preflight/changed-checks/run-lint.mjs index 0a2bbe3c723..e882fcb03d2 100644 --- a/config/scripts/preflight/changed-checks/run-lint.mjs +++ b/config/scripts/preflight/changed-checks/run-lint.mjs @@ -39,6 +39,7 @@ export const LINT_STEPS = [ 'check:mobile-shared-dependency-versions', 'check:ts-nocheck-ratchet', 'check:workspace-record-read-ratchet', + 'check:tab-map-seam-ratchet', 'check:unproven-pty-retirement-ratchet', 'check:daemon-blocking-call-ratchet', 'check:main-sync-fs-ratchet', diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs index 29b0247827e..009f48c981c 100644 --- a/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs @@ -320,6 +320,24 @@ function isSameNameCopy(property, name) { return ts.isPropertyAccessExpression(value) && value.name.text === name } +// The transition seam names the fields it tracks in `const SEAM_*_FIELDS = [...] as const` lists; names, not writes. +function isSeamFieldNameConstant(literal) { + let list = literal.parent + if (!ts.isArrayLiteralExpression(list)) { + return false + } + let declaration = list.parent + while (ts.isAsExpression(declaration) || ts.isSatisfiesExpression(declaration)) { + declaration = declaration.parent + } + return ( + ts.isVariableDeclaration(declaration) && + ts.isIdentifier(declaration.name) && + /^SEAM_[A-Z_]+_FIELDS$/.test(declaration.name.text) && + (declaration.parent.flags & ts.NodeFlags.Const) !== 0 + ) +} + /** Layout writes in one file under one ratchet's rules. */ export function countLayoutWrites(sourceText, ratchet, fileName = 'file.tsx') { const names = [...ratchet.writerNames, ...ratchet.assignedFields] @@ -392,7 +410,8 @@ export function countLayoutWrites(sourceText, ratchet, fileName = 'file.tsx') { node.parent.expression.expression.text === 'Object' && node.parent.expression.name.text === 'hasOwn' ) && - !ts.isLiteralTypeNode(node.parent) + !ts.isLiteralTypeNode(node.parent) && + !isSeamFieldNameConstant(node) ) { count += 1 } diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs new file mode 100644 index 00000000000..c6743a1ae76 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs @@ -0,0 +1,380 @@ +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import ts from 'typescript-api' + +// The tab-map transition seam (store/keyed-record-transitions.ts) only works if its writers annotate and its +// consumers enumerate whole maps only on named cold paths; this pins both for the repaired modules, nothing wider. + +const R = 'src/renderer/src/' +const STATUS = `${R}components/native-chat/session/status/` + +/** + * Repaired consumers: the only functions allowed to walk a whole map (`coldPaths`), which callers + * may reach a cold helper (`helpers`), and the only values they may import, so a new walking helper + * can't arrive through an import unreviewed. + */ +export const CONSUMERS = new Map([ + [ + `${STATUS}structured-agent-session-tabs.ts`, + { + coldPaths: new Set(['rebuildFromSnapshot']), + helpers: { rebuildFromSnapshot: ['advance'] }, + imports: new Set(['structuredAgentSessionPaneKey', 'isStructuredTab', 'readTabMapChanges']) + } + ], + [ + `${STATUS}StructuredAgentSessionStatusBridge.tsx`, + { + coldPaths: new Set(['reconcileFromSnapshot']), + helpers: { + getStructuredAgentSessionTabs: ['reconcileFromSnapshot'], + reconcileFromSnapshot: ['reconcile'] + }, + imports: new Set([ + 'useEffect', + 'projectStatus', + 'getStructuredAgentSessionLaunchLifecycle', + 'subscribeStructuredAgentLaunchStatus', + 'getStructuredAgentSessionLaunchFailedAt', + 'useAppStore', + 'structuredAgentSessionTargetForHost', + 'getStructuredAgentSessionStatusFeed', + 'structuredAgentSessionStatusFeedKey', + 'getStructuredAgentSessionTabs', + 'getStructuredAgentSessionTabsInWorkspace', + 'readTabMapChanges', + 'createTabOwnerCache', + 'ownerInputChanged', + 'ownerInputs', + 'createStructuredSessionMembership', + 'sameSemanticTab' + ]) + } + ], + [ + `${STATUS}structured-agent-session-status-membership.ts`, + { + coldPaths: new Set(), + helpers: { getStructuredAgentSessionTabs: [] }, + imports: new Set(['structuredAgentSessionPaneKey']) + } + ] +]) +const ENUMERATING_CALLS = new Set(['keys', 'values', 'entries']) + +/** Shared tab-map writers wired to the seam: a raw record literal for these fields bypasses provenance. */ +export const WRITERS = [ + 'src/renderer/src/runtime/web-session-tabs-sync/scoped-patch-annotation.ts', + 'src/renderer/src/runtime/web-session-tabs-sync/store-patch.ts', + 'src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.ts', + 'src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts', + 'src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts', + 'src/renderer/src/store/slices/editor/hydration/restored-editor-owner-in-place.ts', + 'src/renderer/src/store/slices/editor/hydration/restored-editor-owner-transition.ts', + 'src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts', + 'src/renderer/src/store/slices/editor/opening/open-file-mutations.ts', + 'src/renderer/src/store/slices/ssh/ssh-target-cleanup.ts', + 'src/renderer/src/store/slices/tabs/rename-worktree-layout.ts', + 'src/renderer/src/store/slices/tabs/tab-group-state.ts', + 'src/renderer/src/store/slices/tabs/tabs-close-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-create-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-drop-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-focus-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-group-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts', + 'src/renderer/src/store/slices/tabs/tabs-label-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-move-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-reconciliation.ts', + 'src/renderer/src/store/slices/tabs/tabs-session-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts', + 'src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts', + 'src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts', + 'src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts', + 'src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-state.ts', + 'src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts', + 'src/renderer/src/store/slices/worktrees/teardown/record-key-omission.ts', + 'src/renderer/src/store/terminals/terminal-tab-close.ts', + 'src/renderer/src/store/terminals/terminal-tab-creation.ts', + 'src/renderer/src/store/terminals/terminal-tab-navigation.ts', + 'src/renderer/src/store/terminals/terminal-tab-title-batch.ts', + 'src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts', + 'src/renderer/src/store/terminals/workspace-terminal-hydration.ts', + 'src/renderer/src/store/terminals/workspace-terminal-reconnect.ts', + 'src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts' +] +export const SEAM_FIELDS = new Set([ + 'tabsByWorktree', + 'unifiedTabsByWorktree', + 'terminalLayoutsByTabId', + 'ptyIdsByTabId', + 'lastKnownRelayPtyIdByTabId', + 'runtimePaneTitlesByTabId', + 'pendingStartupByTabId', + 'pendingReconnectPtyIdByTabId', + 'sleepingAgentSessionsByPaneKey', + 'layoutByWorktree', + 'groupsByWorktree', + 'activeGroupIdByWorktree' +]) + +function parse(file, text) { + return ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) +} + +function line(source, node) { + return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1 +} + +function enclosingFunctionNames(node) { + const names = [] + for (let current = node.parent; current; current = current.parent) { + if (ts.isFunctionDeclaration(current) && current.name) { + names.push(current.name.text) + } else if ( + (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) && + ts.isVariableDeclaration(current.parent) && + ts.isIdentifier(current.parent.name) + ) { + names.push(current.parent.name.text) + } + } + return names +} + +function valueImports(source) { + const imported = [] + for (const statement of source.statements) { + const clause = ts.isImportDeclaration(statement) ? statement.importClause : null + if (!clause || clause.isTypeOnly) { + continue + } + if (clause.name) { + imported.push(clause.name) + } + const bindings = clause.namedBindings + if (bindings && ts.isNamespaceImport(bindings)) { + imported.push(bindings.name) + } else if (bindings) { + imported.push( + ...bindings.elements.filter((element) => !element.isTypeOnly).map((e) => e.name) + ) + } + } + return imported +} + +function isHelperReference(node, helpers) { + if (!ts.isIdentifier(node) || !Object.hasOwn(helpers, node.text)) { + return false + } + const parent = node.parent + const declares = + ((ts.isVariableDeclaration(parent) || ts.isFunctionDeclaration(parent)) && + parent.name === node) || + (ts.isPropertyAccessExpression(parent) && parent.name === node) || + (ts.isPropertyAssignment(parent) && parent.name === node) || + ts.isImportSpecifier(parent) + return !declares +} + +export function consumerViolations(file, text, { coldPaths, helpers, imports }) { + const source = parse(file, text) + const violations = [] + for (const name of valueImports(source)) { + if (!imports.has(name.text)) { + violations.push( + `${file}:${line(source, name)} imports ${name.text}; repaired consumers import only reviewed helpers` + ) + } + } + const visit = (node) => { + let what = null + let allowed = coldPaths + if ( + ts.isPropertyAccessExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === 'Object' && + ENUMERATING_CALLS.has(node.name.text) + ) { + // Any reference, called or aliased (`const keys = Object.keys`). + what = `Object.${node.name.text}` + } else if (isHelperReference(node, helpers)) { + // Calls, aliases (`const resync = reconcileFromSnapshot`) and callbacks alike. + what = `${node.text}()` + allowed = new Set(helpers[node.text]) + } else if (ts.isForInStatement(node)) { + what = 'for…in' + } + if (what && !enclosingFunctionNames(node).some((name) => allowed.has(name))) { + violations.push(`${file}:${line(source, node)} ${what} outside a named cold path`) + } + if ( + ts.isFunctionDeclaration(node) && + node.name?.text === 'rebuildFromSnapshot' && + node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) { + violations.push(`${file}:${line(source, node)} rebuildFromSnapshot must stay module-private`) + } + ts.forEachChild(node, visit) + } + visit(source) + return violations +} + +function isRawRecord(expression) { + if (ts.isObjectLiteralExpression(expression)) { + return expression.properties.some((property) => ts.isSpreadAssignment(property)) + } + return ( + ts.isCallExpression(expression) && + ts.isPropertyAccessExpression(expression.expression) && + ts.isIdentifier(expression.expression.expression) && + expression.expression.expression.text === 'Object' && + ['fromEntries', 'assign'].includes(expression.expression.name.text) + ) +} + +// Only an explicit cold-path mark certifies a record built outside a construction helper or draft. +const ANNOTATED_ARGUMENT = { + markFullResync: 0 +} + +function enclosingScope(node) { + let current = node.parent + while (current && !ts.isFunctionLike(current) && !ts.isSourceFile(current)) { + current = current.parent + } + return current +} + +/** The value a local name holds at `use`: its declaration's initializer, followed through aliases. */ +function bindingSource(name, scope, use, seen = new Set()) { + if (seen.has(name)) { + return null + } + seen.add(name) + let found = null + const visit = (node) => { + if (node.pos >= use.pos) { + return + } + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) { + found = node.initializer ?? null + } else if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.EqualsToken && + ts.isIdentifier(node.left) && + node.left.text === name + ) { + found = node.right + } + ts.forEachChild(node, visit) + } + visit(scope) + if (found && ts.isIdentifier(found)) { + const aliased = bindingSource(found.text, scope, use, seen) + return aliased && { ...aliased, names: [name, ...aliased.names] } + } + return found && { value: found, names: [name] } +} + +/** Whether a seam helper annotates one of `names` in place before `use` publishes it. */ +function annotatedBefore(names, scope, use) { + let annotated = false + const visit = (node) => { + if (node.pos >= use.pos) { + return + } + if ( + node.end <= use.pos && + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + Object.hasOwn(ANNOTATED_ARGUMENT, node.expression.text) + ) { + const argument = node.arguments[ANNOTATED_ARGUMENT[node.expression.text]] + annotated ||= + argument !== undefined && ts.isIdentifier(argument) && names.includes(argument.text) + } + ts.forEachChild(node, visit) + } + visit(scope) + return annotated +} + +function rawValue(node) { + const initializer = ts.isShorthandPropertyAssignment(node) ? node.name : node.initializer + if (isRawRecord(initializer)) { + return true + } + if (!ts.isIdentifier(initializer)) { + return false + } + // Follow the local binding and its aliases; the record must be annotated before it is published. + for (let scope = enclosingScope(node); scope; scope = scope.parent && enclosingScope(scope)) { + const binding = bindingSource(initializer.text, scope, node) + if (binding) { + return isRawRecord(binding.value) && !annotatedBefore(binding.names, scope, node) + } + if (ts.isSourceFile(scope)) { + break + } + } + return false +} + +export function writerViolations(file, text) { + const source = parse(file, text) + const violations = [] + const visit = (node) => { + if ( + (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) && + (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) && + SEAM_FIELDS.has(node.name.text) && + rawValue(node) + ) { + violations.push( + `${file}:${line(source, node)} raw ${node.name.text} record; build it with a replace helper or draft, or mark it full resync` + ) + } + ts.forEachChild(node, visit) + } + visit(source) + return violations +} + +export function collect(root = process.cwd()) { + const violations = [] + for (const [file, rules] of CONSUMERS) { + violations.push( + ...consumerViolations(file, fs.readFileSync(path.join(root, file), 'utf8'), rules) + ) + } + for (const file of WRITERS) { + violations.push(...writerViolations(file, fs.readFileSync(path.join(root, file), 'utf8'))) + } + return violations +} + +export function main(root = process.cwd()) { + const violations = collect(root) + if (violations.length) { + for (const violation of violations) { + console.error(violation) + } + console.error( + 'Tab-map seam: ordinary handlers use addressed deltas (readTabMapChanges); whole-map walks belong only in the named cold paths.' + ) + return 1 + } + console.log( + `tab-map-seam ratchet OK — ${CONSUMERS.size} consumer and ${WRITERS.length} writer modules pinned.` + ) + return 0 +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit(main(process.cwd())) +} diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs new file mode 100644 index 00000000000..7f4a6dfb6b1 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { CONSUMERS, consumerViolations, writerViolations } from './check-tab-map-seam-ratchet.mjs' + +const BRIDGE = + 'src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx' +const rules = CONSUMERS.get(BRIDGE) + +describe('tab-map seam guard', () => { + it('rejects an ordinary handler reaching the cold path or walking a map', () => { + const text = [ + 'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)', + 'const reconcile = () => reconcileFromSnapshot()', + 'const ordinary = () => { reconcileFromSnapshot(); Object.keys(source) }' + ].join('\n') + expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ + 'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path', + 'bridge.tsx:3 Object.keys outside a named cold path' + ]) + }) + + it('rejects an unreviewed value import, not type imports', () => { + const text = [ + "import { wholeMap } from './new-walk'", + "import type { Walk } from './new-walk'" + ].join('\n') + expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ + 'bridge.tsx:1 imports wholeMap; repaired consumers import only reviewed helpers' + ]) + }) + + it('follows a raw record through a local binding unless it is marked full resync', () => { + const text = [ + 'function raw(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' set({ unifiedTabsByWorktree: next })', + '}', + 'function annotated(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' markFullResync(next, "hydration")', + ' set({ unifiedTabsByWorktree: next })', + '}' + ].join('\n') + expect(writerViolations('writer.ts', text)).toEqual([ + 'writer.ts:3 raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync' + ]) + }) + + it('follows aliases of cold helpers and enumerators', () => { + const text = [ + 'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)', + 'const reconcile = () => reconcileFromSnapshot()', + 'const resync = reconcileFromSnapshot', + 'const keys = Object.keys' + ].join('\n') + expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ + 'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path', + 'bridge.tsx:4 Object.keys outside a named cold path' + ]) + }) + + it('follows aliased raw records and requires annotation before publication', () => { + const raw = + 'raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync' + const text = [ + 'function aliased(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' const unifiedTabsByWorktree = next', + ' set({ unifiedTabsByWorktree })', + '}', + 'function late(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' set({ unifiedTabsByWorktree: next })', + ' markFullResync(next, "hydration")', + '}', + 'function early(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' const alias = next', + ' markFullResync(alias, "hydration")', + ' set({ unifiedTabsByWorktree: alias })', + '}' + ].join('\n') + expect(writerViolations('writer.ts', text)).toEqual([ + `writer.ts:4 ${raw}`, + `writer.ts:8 ${raw}` + ]) + }) +}) diff --git a/package.json b/package.json index 4a038ca5fbd..3c157b155c9 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,7 @@ "check:id-only-store-write-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-id-only-store-write-ratchet.mjs", "check:repo-host-read-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-repo-host-read-ratchet.mjs", "check:workspace-record-read-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-workspace-record-read-ratchet.mjs", + "check:tab-map-seam-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs", "check:worktree-id-composer-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-worktree-id-composer-ratchet.mjs", "check:direct-link-open-ratchet": "node config/scripts/static-analysis/ratchets/renderer-state/check-direct-link-open-ratchet.mjs", "check:e2e-typecheck-ratchet": "node config/scripts/typecheck/e2e-admission/check-e2e-typecheck-ratchet.mjs", diff --git a/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx b/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx index f6346cceb1a..231300f0d93 100644 --- a/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx +++ b/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx @@ -1,6 +1,4 @@ import { useEffect } from 'react' -import type { AgentSessionStatusSummary } from '../../../../../../shared/agent-session/agent-session-wire' -import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' import { projectStatus } from './structured-agent-session-status-projection' import { getStructuredAgentSessionLaunchLifecycle, @@ -9,52 +7,36 @@ import { import { getStructuredAgentSessionLaunchFailedAt } from '@/lib/agent-session/launch/structured-agent-session-launch-failed-at' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' +import type { StructuredChatCompanionWrite } from '@/store/slices/agent-status/structured-chat-companion-writes' import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import { getStructuredAgentSessionStatusFeed, - structuredAgentSessionStatusFeedKey, - type StructuredAgentSessionStatusFeedOwner + structuredAgentSessionStatusFeedKey } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import { getStructuredAgentSessionTabs, type StructuredTab } from './structured-agent-session-tabs' +import { + getStructuredAgentSessionTabs, + getStructuredAgentSessionTabsInWorkspace, + type StructuredTab +} from './structured-agent-session-tabs' +import { readTabMapChanges } from '@/store/keyed-record-change-reads' import { createTabOwnerCache, ownerInputChanged, ownerInputs } from './structured-agent-session-tab-owner-cache' +import { + createStructuredSessionMembership, + type HostGroup, + type Member, + type ProjectionInput, + sameSemanticTab +} from './structured-agent-session-status-membership' -// Re-exported so the bridge stays the one import site its consumers already know. - -type HostGroup = { - members: Member[] - /** A host tick names its sessions; this finds their tabs without walking every member. */ - membersBySession: Map - /** Captured but not yet projected (a throwing commit); retried on this host's next tick. */ - owed: Set - feed: StructuredAgentSessionStatusFeedOwner - unsubscribe: () => void - release?: () => void -} -type ProjectionInput = { - tab: StructuredTab - member: Member - summary: AgentSessionStatusSummary | null - observation: 'live' | 'unverifiable' - failedAt: number | null - sleptAt: number | null | undefined - directory: string | undefined -} -type Member = { - paneKey: string - tab: StructuredTab - hostKey: string | null - group: HostGroup | null - status?: ProjectionInput - captured?: ProjectionInput -} /** Unchanged feed facts for an unchanged tab cannot change its projection or companions. */ function sameCapturedInput(previous: ProjectionInput | undefined, next: ProjectionInput): boolean { return ( - previous?.tab === next.tab && + previous !== undefined && + sameSemanticTab(previous.tab, next.tab) && previous.summary === next.summary && previous.observation === next.observation && previous.failedAt === next.failedAt && @@ -65,7 +47,8 @@ function sameCapturedInput(previous: ProjectionInput | undefined, next: Projecti function sameStatusInput(previous: ProjectionInput | undefined, next: ProjectionInput): boolean { return ( - previous?.tab === next.tab && + previous !== undefined && + sameSemanticTab(previous.tab, next.tab) && previous.summary === next.summary && previous.observation === next.observation && previous.failedAt === next.failedAt @@ -73,9 +56,11 @@ function sameStatusInput(previous: ProjectionInput | undefined, next: Projection } function installStatusProjection(): () => void { - const members = new Map() - const membersByTabId = new Map() + const membership = createStructuredSessionMembership() + const { members, membersByTabId, legacy } = membership const retired = new Set() + let tabs: readonly StructuredTab[] | null = null + let tabsSource: AppState['unifiedTabsByWorktree'] | null = null const groups = new Map() const queue: (() => void)[] = [] const ownerForTab = createTabOwnerCache() @@ -120,20 +105,17 @@ function installStatusProjection(): () => void { const target = tab && structuredAgentSessionTargetForHost(ownerForTab(useAppStore.getState(), tab)) return ( - tab === input.tab && + sameSemanticTab(tab, input.tab) && (target ? structuredAgentSessionStatusFeedKey(target) : null) === input.member.hostKey ) } - const companions = (input: ProjectionInput): void => { + const companions = (input: ProjectionInput, writes: StructuredChatCompanionWrite[]): void => { const { member, tab, sleptAt, directory } = input if ( current(input) && (member.group ? member.group.feed.getSessionSleepState(tab.entityId) : null) === sleptAt ) { - const store = useAppStore.getState() - if (store.structuredChatSleptAtByPaneKey[member.paneKey] !== sleptAt) { - store.setStructuredChatSleptAt(member.paneKey, sleptAt) - } + writes.push({ kind: 'slept-at', paneKey: member.paneKey, sleptAt }) } if (!current(input)) { return @@ -145,19 +127,16 @@ function installStatusProjection(): () => void { if (latestDirectory !== directory) { return } - const store = useAppStore.getState() - const pin = store.structuredSessionLaunchDirectoryByTabId[tab.id] - if ( + writes.push( directory - ? pin?.sessionId !== tab.entityId || pin.launchDirectory !== directory - : pin?.sessionId === tab.entityId - ) { - if (directory) { - store.setStructuredSessionLaunchDirectory(tab.id, tab.entityId, directory) - } else { - store.clearStructuredSessionLaunchDirectory(tab.id, tab.entityId) - } - } + ? { + kind: 'launch-directory', + tabId: tab.id, + sessionId: tab.entityId, + launchDirectory: directory + } + : { kind: 'clear-launch-directory', tabId: tab.id, sessionId: tab.entityId } + ) } const project = (inputs: ProjectionInput[]): void => { const removed = [...retired] @@ -165,18 +144,26 @@ function installStatusProjection(): () => void { (input) => current(input) && !sameStatusInput(input.member.status, input) ) const clean = (): void => { + const writes: StructuredChatCompanionWrite[] = [] for (const old of removed) { if (!members.has(old.paneKey)) { - useAppStore.getState().setStructuredChatSleptAt(old.paneKey, undefined) + writes.push({ kind: 'slept-at', paneKey: old.paneKey, sleptAt: undefined }) } - const replacement = membersByTabId.get(old.tab.id) - if (!replacement || replacement.tab.entityId !== old.tab.entityId) { - useAppStore.getState().clearStructuredSessionLaunchDirectory(old.tab.id, old.tab.entityId) + const replacements = membersByTabId.get(old.tab.id) ?? [] + if (![...replacements].some((member) => member.tab.entityId === old.tab.entityId)) { + writes.push({ + kind: 'clear-launch-directory', + tabId: old.tab.id, + sessionId: old.tab.entityId + }) } - retired.delete(old) } for (const input of inputs) { - companions(input) + companions(input, writes) + } + useAppStore.getState().applyStructuredChatCompanionWrites(writes) + for (const old of removed) { + retired.delete(old) } } if (dirty.length || removed.length) { @@ -204,14 +191,14 @@ function installStatusProjection(): () => void { // Mark consumed only after a normal return: a throwing commit leaves the input for the next emission to retry. for (const input of inputs) { input.member.captured = input - input.member.group?.owed.delete(input.member) + membership.settle(input.member) } } const activateGroups = (): void => { for (const [hostKey, group] of groups) { - if (groups.get(hostKey) === group && group.members.length && !group.release) { + if (groups.get(hostKey) === group && group.members.size && !group.release) { const release = group.feed.activate() - if (disposed || groups.get(hostKey) !== group || !group.members.length) { + if (disposed || groups.get(hostKey) !== group || !group.members.size) { release() } else { group.release = release @@ -240,7 +227,9 @@ function installStatusProjection(): () => void { // Launch ticks and full host ticks carry every member; skip the unchanged ones. if (!sameCapturedInput(member.captured, input)) { inputs.push(input) - member.group?.owed.add(member) + membership.owe(member) + } else { + membership.settle(member) } } enqueue( @@ -251,125 +240,145 @@ function installStatusProjection(): () => void { inputs.map(({ member }) => ({ host: member.hostKey, paneKey: member.paneKey })) ) } - const reconcile = (): void => { + const withOwed = (selected: Iterable) => membership.withDebt(selected, groups.values()) + const groupFor = ( + state: AppState, + tab: StructuredTab + ): { hostKey: string | null; group: HostGroup | null } => { + const target = structuredAgentSessionTargetForHost(ownerForTab(state, tab)) + const hostKey = target ? structuredAgentSessionStatusFeedKey(target) : null + const existing = hostKey ? groups.get(hostKey) : undefined + if (existing || !target || !hostKey) { + return { hostKey, group: existing ?? null } + } + const feed = getStructuredAgentSessionStatusFeed(target) + const created: HostGroup = { + members: new Set(), + membersBySession: new Map(), + owed: new Set(), + feed, + unsubscribe: () => {} + } + groups.set(hostKey, created) + created.unsubscribe = feed.subscribe((change) => + boundary(() => { + if (disposed) { + return + } + if (change === null) { + capture(created.members) + return + } + const selected = new Set() + for (const sessionId of change) { + created.membersBySession.get(sessionId)?.forEach((member) => selected.add(member)) + } + // Membership changes prune superseded members, so the debt holds only current tabs. + created.owed.forEach((member) => selected.add(member)) + capture(selected) + }) + ) + return { hostKey, group: created } + } + const place = (state: AppState, tab: StructuredTab, paneKey: string, changed: Set) => { + const { hostKey, group } = groupFor(state, tab) + const member = membership.place(tab, paneKey, hostKey, group) + if (member) { + changed.add(member) + } + } + // Cold path (bootstrap, hydration, unannotated replacement): the whole projected chat list. + const reconcileFromSnapshot = ( + source: AppState['unifiedTabsByWorktree'], + placeTab: (tab: StructuredTab, paneKey: string) => void + ): Member[] => { + const nextTabs = getStructuredAgentSessionTabs(source) + if (nextTabs === tabs) { + return [] + } + const retiring = membership.reconcileTabs(nextTabs, null, placeTab) + tabs = nextTabs + return retiring + } + const reconcile = (ownersChanged: boolean): void => { const state = useAppStore.getState() - const next = new Map() - for (const tab of getStructuredAgentSessionTabs(state.unifiedTabsByWorktree)) { - const paneKey = structuredAgentSessionPaneKey(tab.id, tab.entityId) - const target = structuredAgentSessionTargetForHost(ownerForTab(state, tab)) - const hostKey = target ? structuredAgentSessionStatusFeedKey(target) : null - let group = hostKey ? groups.get(hostKey) : undefined - if (!group && target && hostKey) { - const feed = getStructuredAgentSessionStatusFeed(target) - const created: HostGroup = { - members: [], - membersBySession: new Map(), - owed: new Set(), - feed, - unsubscribe: () => {} - } - groups.set(hostKey, created) - created.unsubscribe = feed.subscribe((change) => - boundary(() => { - if (disposed) { - return - } - if (change === null) { - capture(created.members) - return - } - const selected = new Set() - for (const sessionId of change) { - for (const member of created.membersBySession.get(sessionId) ?? []) { - selected.add(member) - } - } - // Reconcile prunes superseded members, so the debt holds only current tabs. - created.owed.forEach((member) => selected.add(member)) - capture(selected) - }) - ) - group = created - } - const old = members.get(paneKey) - const member: Member = - old?.group === (group ?? null) - ? old - : { - paneKey, - tab, - hostKey, - group: group ?? null - } - member.tab = tab - next.set(paneKey, member) - } - for (const member of members.values()) { - if (!next.has(member.paneKey)) { - retired.add(member) + const source = state.unifiedTabsByWorktree + const changed = new Set() + const retiring: Member[] = [] + const placeTab = (tab: StructuredTab, paneKey: string) => place(state, tab, paneKey, changed) + if (source !== tabsSource) { + const changes = tabsSource ? readTabMapChanges(source, tabsSource) : null + if (changes?.kind === 'addressed') { + const listed = [...changes.workspaceIds].flatMap((workspaceId) => [ + ...getStructuredAgentSessionTabsInWorkspace(source, workspaceId) + ]) + retiring.push(...membership.reconcileTabs(listed, changes.tabIds, placeTab)) + tabs = null + } else { + retiring.push(...reconcileFromSnapshot(source, placeTab)) } } - members.clear() - membersByTabId.clear() - for (const group of groups.values()) { - group.members = [] - group.membersBySession = new Map() - // A rebound pane gets a new member without retiring the old one; drop every superseded identity. - for (const member of group.owed) { - if (next.get(member.paneKey) !== member) { - group.owed.delete(member) - } - } + for (const member of retiring) { + membership.detach(member) + retired.add(member) } - for (const [key, member] of next) { - members.set(key, member) - membersByTabId.set(member.tab.id, member) - if (member.group) { - member.group.members.push(member) - const sessionMembers = member.group.membersBySession.get(member.tab.entityId) - if (sessionMembers) { - sessionMembers.push(member) - } else { - member.group.membersBySession.set(member.tab.entityId, [member]) - } + // Advanced only after a normal return, so a throwing pass is retried by the next tab write. + tabsSource = source + if (ownersChanged) { + for (const member of legacy) { + place(state, member.tab, member.paneKey, changed) } } for (const [key, group] of groups) { - if (groups.get(key) === group && !group.members.length) { + if (groups.get(key) === group && !group.members.size) { groups.delete(key) - group.members = [] group.unsubscribe() group.release?.() } } - enqueue(() => { - activateGroups() - capture(members.values()) - }) + // Existing projection or retirement debt drains on any reconciliation, not only on new changes. + if (changed.size || retired.size || membership.hasDebt(groups.values())) { + enqueue(() => { + activateGroups() + capture(withOwed(changed)) + }) + } } const unsubscribeApp = useAppStore.subscribe((state: AppState, previous: AppState) => { - if ( - !disposed && - (state.unifiedTabsByWorktree !== previous.unifiedTabsByWorktree || - ownerInputs.some((key) => ownerInputChanged(state, previous, key))) - ) { - boundary(reconcile) + if (disposed) { + return + } + const ownersChanged = ownerInputs.some((key) => ownerInputChanged(state, previous, key)) + if (ownersChanged || useAppStore.getState().unifiedTabsByWorktree !== tabsSource) { + boundary(() => reconcile(ownersChanged)) } }) - const unsubscribeLaunch = subscribeStructuredAgentLaunchStatus(() => + const unsubscribeLaunch = subscribeStructuredAgentLaunchStatus((sessionIds) => boundary(() => { - if (!disposed) { - capture(members.values()) + if (disposed) { + return } + // Full resync: the writer could not name its sessions. + if (sessionIds === null) { + capture(members.values()) + return + } + const selected = new Set() + for (const group of groups.values()) { + for (const sessionId of sessionIds) { + group.membersBySession.get(sessionId)?.forEach((member) => selected.add(member)) + } + } + capture(withOwed(selected)) }) ) - boundary(reconcile) + boundary(() => reconcile(false)) return () => { disposed = true unsubscribeApp() unsubscribeLaunch() for (const group of groups.values()) { - group.members = [] + group.members.clear() group.unsubscribe() boundary(() => group.release?.()) } @@ -377,8 +386,7 @@ function installStatusProjection(): () => void { for (const member of members.values()) { retired.add(member) } - members.clear() - membersByTabId.clear() + membership.clear() enqueue(() => project([])) } } diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx new file mode 100644 index 00000000000..61bf01b6e34 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx @@ -0,0 +1,234 @@ +import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof' +// @vitest-environment happy-dom + +import { act, cleanup, render, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + AgentSessionStatusEvent, + AgentSessionStatusSummary +} from '../../../../../../shared/agent-session/agent-session-wire' +import { + LOCAL_EXECUTION_HOST_ID, + type ExecutionHostId +} from '../../../../../../shared/execution-host' +import type { Tab } from '../../../../../../shared/tab-types' +import type { AppState } from '@/store/types' + +import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' + +type TestStore = { + getState: () => AppState + setState: (state: Partial) => void +} + +const mocks = vi.hoisted(() => { + const hoisted: { + store: TestStore | null + subscribeStatus: ReturnType + supportsCapability: ReturnType + unsubscribe: ReturnType + applyStatus: ReturnType void>> + } = { + store: null, + subscribeStatus: vi.fn(), + supportsCapability: vi.fn(), + unsubscribe: vi.fn(), + applyStatus: vi.fn() + } + return hoisted +}) + +vi.mock('@/store', async () => { + const { createTestStore } = await import('@/store/testing/app-store-test-fixture') + const useAppStore = createTestStore() + const { transactAgentStatuses } = useAppStore.getState() + useAppStore.setState({ + transactAgentStatuses: (operation) => + transactAgentStatuses((transaction) => + operation({ + ...transaction, + apply: (update) => { + mocks.applyStatus(update) + return transaction.apply(update) + } + }) + ) + }) + mocks.store = useAppStore + return { useAppStore } +}) + +vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({ + ...(await importOriginal()), + runtimeEnvironmentSupportsCapability: mocks.supportsCapability +})) + +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: vi.fn() +})) + +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ + subscribeStructuredAgentSession: vi.fn(), + subscribeStructuredAgentSessionStatus: mocks.subscribeStatus +})) + +import { useAppStore } from '@/store' + +import { StructuredAgentSessionStatusBridge } from './StructuredAgentSessionStatusBridge' +import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' + +import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' + +function summary(overrides: Partial = {}): AgentSessionStatusSummary { + return { + sessionId: 'session-1', + workspaceId: 'wt-1', + agent: 'codex', + status: 'idle', + latestPrompt: 'hello', + updatedAt: 1, + ...overrides + } +} + +function feed(index = 0): { target: unknown; emit: (event: AgentSessionStatusEvent) => void } { + const calls = mocks.subscribeStatus.mock.calls + const call = calls[index < 0 ? calls.length + index : index] + return { target: call[0], emit: call[1] } +} + +function statusFor(tabId: string, sessionId: string) { + return useAppStore.getState().agentStatusByPaneKey[ + structuredAgentSessionPaneKey(tabId, sessionId) + ] +} + +function openChat(id: string, sessionId: string, executionHostId?: ExecutionHostId): void { + useAppStore.getState().createUnifiedTab('wt-1', 'agent-session', { + id, + entityId: sessionId, + agentSessionAgent: 'codex', + label: 'Codex Chat', + ...(executionHostId ? { executionHostId } : {}) + }) +} + +// Real tab actions annotate their writes, so these reach the bridge's addressed reconciliation. +describe('StructuredAgentSessionStatusBridge with tab actions', () => { + beforeEach(() => { + vi.clearAllMocks() + resetStructuredAgentSessionStatusFeedsForTests() + mocks.subscribeStatus.mockResolvedValue({ unsubscribe: mocks.unsubscribe }) + mocks.supportsCapability.mockResolvedValue(true) + mocks.store?.setState({ + agentStatusByPaneKey: {}, + structuredChatSleptAtByPaneKey: {}, + structuredSessionLaunchDirectoryByTabId: {}, + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + activeGroupIdByWorktree: {}, + layoutByWorktree: {} + }) + }) + + afterEach(() => { + cleanup() + resetStructuredAgentSessionStatusFeedsForTests() + }) + + it('removes a closed chat status and keeps an unrelated tab write quiet', async () => { + render() + act(() => openChat('chat-1', 'session-1', LOCAL_EXECUTION_HOST_ID)) + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) + act(() => + feed().emit({ type: 'snapshot', sessions: [summary({ status: 'working', updatedAt: 5 })] }) + ) + expect(statusFor('chat-1', 'session-1')).toEqual( + expect.objectContaining({ state: 'working', updatedAt: 5 }) + ) + + act(() => useAppStore.getState().setTabLabel('chat-1', 'Renamed')) + expect(statusFor('chat-1', 'session-1')).toEqual( + expect.objectContaining({ state: 'working', terminalTitle: 'Renamed' }) + ) + + act(() => useAppStore.getState().closeUnifiedTab('chat-1')) + expect(statusFor('chat-1', 'session-1')).toBeUndefined() + }) + + it('retires the old pane when a tab is rebound to another session and ignores its late tick', async () => { + render() + act(() => openChat('chat-1', 'session-1', LOCAL_EXECUTION_HOST_ID)) + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) + act(() => feed().emit({ type: 'snapshot', sessions: [summary()] })) + expect(statusFor('chat-1', 'session-1')).toBeDefined() + + act(() => { + useAppStore.getState().closeUnifiedTab('chat-1') + openChat('chat-1', 'session-2', LOCAL_EXECUTION_HOST_ID) + }) + // The last chat's close released the host feed, so the rebound chat subscribes afresh. + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledTimes(2)) + act(() => + feed(-1).emit({ + type: 'snapshot', + sessions: [summary({ sessionId: 'session-2', status: 'working', updatedAt: 9 })] + }) + ) + act(() => + feed(-1).emit({ type: 'status', session: summary({ status: 'working', updatedAt: 10 }) }) + ) + expect(statusFor('chat-1', 'session-1')).toBeUndefined() + expect(statusFor('chat-1', 'session-2')).toEqual( + expect.objectContaining({ state: 'working', updatedAt: 9 }) + ) + }) + + it('rebinds an unstamped chat to its new owner host without changing membership', async () => { + useAppStore.setState({ + unifiedTabsByWorktree: { + 'wt-1': [ + { + id: 'chat-1', + worktreeId: 'wt-1', + groupId: 'group-1', + contentType: 'agent-session', + entityId: 'session-1', + label: 'Codex Chat', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0, + isPinned: false, + agentSessionAgent: 'codex' + } satisfies Tab + ] + } + }) + render() + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) + act(() => feed().emit({ type: 'snapshot', sessions: [summary({ updatedAt: 2 })] })) + act(() => + useAppStore.setState({ + worktreesByRepo: { + repo: [ + makeWorktree({ + id: 'wt-1', + repoId: 'repo', + hostId: 'runtime:env-1', + runtimeOwnerEnvironmentId: 'env-1' + }) + ] + } + }) + ) + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledTimes(2)) + expect(feed(1).target).toEqual({ kind: 'environment', environmentId: 'env-1' }) + act(() => feed(1).emit({ type: 'snapshot', sessions: [summary({ updatedAt: 20 })] })) + act(() => feed().emit({ type: 'status', session: summary({ updatedAt: 30 }) })) + expect(Object.keys(useAppStore.getState().agentStatusByPaneKey)).toEqual([ + structuredAgentSessionPaneKey('chat-1', 'session-1') + ]) + expect(statusFor('chat-1', 'session-1')?.updatedAt).toBe(20) + }) +}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts new file mode 100644 index 00000000000..abe86d9f200 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts @@ -0,0 +1,199 @@ +import type { AgentSessionStatusSummary } from '../../../../../../shared/agent-session/agent-session-wire' +import type { StructuredAgentSessionStatusFeedOwner } from '@/runtime/native-chat/status/structured-agent-session-status-feed' +import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' +import type { StructuredTab } from './structured-agent-session-tabs' + +export type HostGroup = { + members: Set + /** A host tick names its sessions; this finds their tabs without walking every member. */ + membersBySession: Map> + /** Captured but not yet projected (a throwing commit); retried on this host's next tick. */ + owed: Set + feed: StructuredAgentSessionStatusFeedOwner + unsubscribe: () => void + release?: () => void +} +export type ProjectionInput = { + tab: StructuredTab + member: Member + summary: AgentSessionStatusSummary | null + observation: 'live' | 'unverifiable' + failedAt: number | null + sleptAt: number | null | undefined + directory: string | undefined +} +export type Member = { + paneKey: string + tab: StructuredTab + hostKey: string | null + group: HostGroup | null + status?: ProjectionInput + captured?: ProjectionInput +} + +/** The tab fields a status projection reads; focus, preview and order metadata never change it. */ +export function sameSemanticTab(previous: StructuredTab, next: StructuredTab): boolean { + return ( + previous === next || + (previous.id === next.id && + previous.entityId === next.entityId && + previous.worktreeId === next.worktreeId && + previous.label === next.label && + previous.agentSessionAgent === next.agentSessionAgent && + previous.createdAt === next.createdAt && + previous.executionHostId === next.executionHostId) + ) +} + +/** Which chat tabs the status bridge projects, updated per changed tab rather than rebuilt. */ +export function createStructuredSessionMembership() { + const members = new Map() + /** Every member per tab; a tab rebound to another session briefly has two until the old retires. */ + const membersByTabId = new Map>() + const indexTab = (member: Member): void => { + const tabMembers = membersByTabId.get(member.tab.id) + if (tabMembers) { + tabMembers.add(member) + } else { + membersByTabId.set(member.tab.id, new Set([member])) + } + } + /** Unstamped tabs resolve their host from workspace owner inputs; stamped tabs never do. */ + const legacy = new Set() + /** Projection debt of members no host feed owns (SSH, unresolved); grouped debt lives on the group. */ + const ungroupedOwed = new Set() + const owe = (member: Member): void => { + if (member.group) { + member.group.owed.add(member) + } else { + ungroupedOwed.add(member) + } + } + const settle = (member: Member): void => { + member.group?.owed.delete(member) + ungroupedOwed.delete(member) + } + const withDebt = (selected: Iterable, groups: Iterable): Set => { + const result = new Set([...selected, ...ungroupedOwed]) + for (const group of groups) { + group.owed.forEach((member) => result.add(member)) + } + return result + } + const hasDebt = (groups: Iterable): boolean => + ungroupedOwed.size > 0 || [...groups].some((group) => group.owed.size > 0) + + const attach = (member: Member): void => { + members.set(member.paneKey, member) + indexTab(member) + const group = member.group + if (group) { + group.members.add(member) + const sessionMembers = group.membersBySession.get(member.tab.entityId) + if (sessionMembers) { + sessionMembers.add(member) + } else { + group.membersBySession.set(member.tab.entityId, new Set([member])) + } + } + } + const detach = (member: Member): void => { + if (members.get(member.paneKey) === member) { + members.delete(member.paneKey) + } + const tabMembers = membersByTabId.get(member.tab.id) + tabMembers?.delete(member) + if (tabMembers && !tabMembers.size) { + membersByTabId.delete(member.tab.id) + } + legacy.delete(member) + ungroupedOwed.delete(member) + const group = member.group + if (group) { + group.members.delete(member) + group.owed.delete(member) + const sessionMembers = group.membersBySession.get(member.tab.entityId) + sessionMembers?.delete(member) + if (sessionMembers && !sessionMembers.size) { + group.membersBySession.delete(member.tab.entityId) + } + } + } + /** Same host keeps the member, null when nothing it projects changed; a new host rebinds the pane. */ + const place = ( + tab: StructuredTab, + paneKey: string, + hostKey: string | null, + group: HostGroup | null + ): Member | null => { + const old = members.get(paneKey) + let member: Member + let semanticChange = true + if (old?.group === group) { + if (old.tab === tab) { + return null + } + semanticChange = !sameSemanticTab(old.tab, tab) + member = old + } else { + if (old) { + detach(old) + } + member = { paneKey, tab, hostKey, group } + attach(member) + } + member.tab = tab + if (tab.executionHostId) { + legacy.delete(member) + } else { + legacy.add(member) + } + if (!semanticChange) { + return null + } + // Owed from attach or change on, so a pass that throws before capturing still retries it. + owe(member) + return member + } + /** Places listed tabs that changed and returns members no longer listed: all of them, or within `tabIds`. */ + const reconcileTabs = ( + listedTabs: Iterable, + tabIds: ReadonlySet | null, + placeTab: (tab: StructuredTab, paneKey: string) => void + ): Member[] => { + const listed = new Set() + for (const tab of listedTabs) { + if (tabIds && !tabIds.has(tab.id)) { + continue + } + const paneKey = structuredAgentSessionPaneKey(tab.id, tab.entityId) + listed.add(paneKey) + if (members.get(paneKey)?.tab !== tab) { + placeTab(tab, paneKey) + } + } + const candidates = tabIds + ? [...tabIds].flatMap((tabId) => [...(membersByTabId.get(tabId) ?? [])]) + : members.values() + return [...candidates].filter((member) => !listed.has(member.paneKey)) + } + const clear = (): void => { + members.clear() + membersByTabId.clear() + legacy.clear() + ungroupedOwed.clear() + } + return { + members, + membersByTabId, + legacy, + owe, + settle, + withDebt, + hasDebt, + place, + detach, + reconcileTabs, + clear + } +} diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts new file mode 100644 index 00000000000..c4ffc2bb913 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest' +import type { Tab } from '../../../../../../shared/tab-types' +import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types' +import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' +import { createTestStore } from '@/store/testing/app-store-test-fixture' +import { getStructuredAgentSessionTabs } from './structured-agent-session-tabs' + +function chat(id: string, worktreeId: string): Tab { + return { + id, + entityId: 'session-shared', + groupId: `group-${worktreeId}`, + worktreeId, + contentType: 'agent-session', + agentSessionAgent: 'codex', + label: id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0 + } +} + +function session(worktreeIds: readonly string[]): WorkspaceSessionState { + const entries = (value: (worktreeId: string) => V): Record => + Object.fromEntries(worktreeIds.map((worktreeId) => [worktreeId, value(worktreeId)])) + return { + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + unifiedTabs: entries((worktreeId) => [chat(`chat-${worktreeId}`, worktreeId)]), + tabGroups: entries((worktreeId) => [ + { + id: `group-${worktreeId}`, + worktreeId, + activeTabId: `chat-${worktreeId}`, + tabOrder: [`chat-${worktreeId}`], + recentTabIds: [`chat-${worktreeId}`] + } + ]), + activeGroupIdByWorktree: entries((worktreeId) => `group-${worktreeId}`) + } +} + +const ids = (tabs: readonly Tab[]) => tabs.map((tab) => tab.id) +// Folder workspace keys are real tab-map keys and valid hydration workspace keys. +const EARLY = folderWorkspaceKey('early') +const LATER = folderWorkspaceKey('later') + +// Scoped hydration rebuilds the workspaces it names; the warm chat list must match a cold read. +describe('chat-tab list after scoped session hydration', () => { + it('follows the hydrated source order for the shared session first match', () => { + const store = createTestStore() + const keys = [EARLY, LATER] + store.getState().hydrateTabsSession(session(keys), { additionalValidWorkspaceKeys: keys }) + expect(ids(getStructuredAgentSessionTabs(store.getState().unifiedTabsByWorktree))).toEqual([ + `chat-${EARLY}`, + `chat-${LATER}` + ]) + + store.getState().hydrateTabsSession(session([EARLY]), { + additionalValidWorkspaceKeys: keys, + replaceWorkspaceKeys: [EARLY] + }) + const source = store.getState().unifiedTabsByWorktree + expect(Object.keys(source)).toEqual([LATER, EARLY]) + const warm = getStructuredAgentSessionTabs(source) + expect(ids(warm)).toEqual([`chat-${LATER}`, `chat-${EARLY}`]) + expect(ids(getStructuredAgentSessionTabs({ ...source }))).toEqual(ids(warm)) + expect(warm.find((tab) => tab.entityId === 'session-shared')?.worktreeId).toBe(LATER) + }) + + it('takes hydrated record order over the selection order', () => { + const store = createTestStore() + const keys = [EARLY, LATER] + store.getState().hydrateTabsSession(session([LATER, EARLY]), { + additionalValidWorkspaceKeys: keys + }) + expect(ids(getStructuredAgentSessionTabs(store.getState().unifiedTabsByWorktree))).toEqual([ + `chat-${LATER}`, + `chat-${EARLY}` + ]) + + store.getState().hydrateTabsSession(session([EARLY, LATER]), { + additionalValidWorkspaceKeys: keys, + replaceWorkspaceKeys: [LATER, EARLY] + }) + const source = store.getState().unifiedTabsByWorktree + expect(Object.keys(source)).toEqual([EARLY, LATER]) + const warm = getStructuredAgentSessionTabs(source) + expect(ids(warm)).toEqual([`chat-${EARLY}`, `chat-${LATER}`]) + expect(ids(getStructuredAgentSessionTabs({ ...source }))).toEqual(ids(warm)) + }) +}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts new file mode 100644 index 00000000000..4eb18bec2be --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import type { Tab } from '../../../../../../shared/tab-types' +import { replaceTabBuckets } from '@/store/keyed-record-transitions' +import { getStructuredAgentSessionTabs } from './structured-agent-session-tabs' + +function tab(id: string, worktreeId: string, contentType: Tab['contentType']): Tab { + return { + id, + worktreeId, + groupId: 'group', + contentType, + entityId: contentType === 'agent-session' ? 'session-shared' : id, + label: id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0, + isPinned: false, + ...(contentType === 'agent-session' ? { agentSessionAgent: 'codex' as const } : {}) + } +} + +const ids = (map: Record) => getStructuredAgentSessionTabs(map).map((t) => t.id) + +describe('getStructuredAgentSessionTabs order', () => { + it('keeps source workspace order through addressed close and reopen', () => { + const start = { + early: [tab('t1', 'early', 'terminal'), tab('c1', 'early', 'agent-session')], + later: [tab('c2', 'later', 'agent-session')] + } + expect(ids(start)).toEqual(['c1', 'c2']) + const closed = replaceTabBuckets(start, [['early', [start.early[0]]]]) + expect(ids(closed)).toEqual(['c2']) + const reopened = replaceTabBuckets(closed, [ + ['early', [start.early[0], tab('c1b', 'early', 'agent-session')]] + ]) + expect(ids(reopened)).toEqual(['c1b', 'c2']) + expect(ids({ ...reopened })).toEqual(['c1b', 'c2']) + }) + + it('follows source order when a workspace is deleted and added back', () => { + const start = { + early: [tab('c1', 'early', 'agent-session')], + later: [tab('c2', 'later', 'agent-session')] + } + expect(ids(start)).toEqual(['c1', 'c2']) + const removed = replaceTabBuckets(start, [['early', null]]) + const restored = replaceTabBuckets(removed, [['early', start.early]]) + expect(ids(restored)).toEqual(['c2', 'c1']) + expect(ids({ ...restored })).toEqual(['c2', 'c1']) + }) + + it('keeps the list through chatless workspace changes and places new workspaces last', () => { + const start = { a: [tab('c1', 'a', 'agent-session')] } + const list = getStructuredAgentSessionTabs(start) + const added = replaceTabBuckets(start, [['b', [tab('t1', 'b', 'terminal')]]]) + expect(getStructuredAgentSessionTabs(added)).toBe(list) + const chat = replaceTabBuckets(added, [ + ['b', [tab('t1', 'b', 'terminal'), tab('cb', 'b', 'agent-session')]] + ]) + expect(ids(chat)).toEqual(['c1', 'cb']) + const removed = replaceTabBuckets(chat, [['a', null]]) + expect(ids(removed)).toEqual(['cb']) + expect(ids({ ...removed })).toEqual(['cb']) + }) +}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts index ab6c1273c59..c59c783c480 100644 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts @@ -1,49 +1,207 @@ import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' import { isStructuredTab } from '../../../../../../shared/agent-session/view/structured-agent-session-tab' import type { Tab } from '../../../../../../shared/tab-types' +import { readTabMapChanges } from '@/store/keyed-record-change-reads' export type StructuredTab = Tab & { contentType: 'agent-session' } -const structuredTabsByUnifiedTabsSnapshot = new WeakMap< - Record, - readonly StructuredTab[] ->() +type TabsByWorktree = Record -/** Project structured-session tabs once per immutable tab-map snapshot. */ -export function getStructuredAgentSessionTabs( - unifiedTabsByWorktree: Record +const NO_TABS: readonly StructuredTab[] = Object.freeze([]) +const structuredTabsByBucket = new WeakMap() +const listsBySnapshot = new WeakMap() +const INDEX_KEY = /^(?:0|[1-9]\d*)$/ + +/** + * The latest source's chat subsets, kept only for chat-bearing workspaces, plus each source + * workspace's rank. Ranks change only when a workspace is added or deleted, so a focus, label or + * title write costs O(that workspace) and the list keeps source order. + */ +type Lineage = { + source: TabsByWorktree + rank: Map + nextRank: number + chats: Map + /** Chat-bearing workspaces in rank order; changes only when one gains its first or loses its last chat. */ + order: string[] | null + list: readonly StructuredTab[] | null + /** The last materialized list, reused when a rebuild yields the same chats. */ + stale: readonly StructuredTab[] | null +} +let lineage: Lineage | null = null + +function sameTabs(previous: readonly StructuredTab[], next: readonly StructuredTab[]): boolean { + return previous.length === next.length && previous.every((tab, index) => tab === next[index]) +} + +// A terminal title or focus write replaces its bucket; keep the chat subset when no chat changed. +function structuredTabsOf( + bucket: readonly Tab[], + previous: readonly StructuredTab[] | undefined ): readonly StructuredTab[] { - const cached = structuredTabsByUnifiedTabsSnapshot.get(unifiedTabsByWorktree) + const cached = structuredTabsByBucket.get(bucket) if (cached) { return cached } - - const tabs: StructuredTab[] = [] - for (const worktreeTabs of Object.values(unifiedTabsByWorktree)) { - for (const tab of worktreeTabs) { - if (isStructuredTab(tab)) { - tabs.push(tab) - } - } - } - structuredTabsByUnifiedTabsSnapshot.set(unifiedTabsByWorktree, tabs) - return tabs + const tabs = bucket.filter(isStructuredTab) + const result = !tabs.length ? NO_TABS : previous && sameTabs(previous, tabs) ? previous : tabs + structuredTabsByBucket.set(bucket, result) + return result } -const paneTabs = new WeakMap, ReadonlyMap>() +function rankOf(target: Lineage, worktreeId: string): number { + return target.rank.get(worktreeId) ?? 0 +} + +// Insert or drop one workspace in the cached order: O(log K) to find, one splice to place. +function placeInOrder(target: Lineage, worktreeId: string, present: boolean): void { + const order = target.order + if (!order) { + return + } + const rank = rankOf(target, worktreeId) + let low = 0 + let high = order.length + while (low < high) { + const middle = (low + high) >> 1 + if (rankOf(target, order[middle]) < rank) { + low = middle + 1 + } else { + high = middle + } + } + if (present) { + order.splice(low, 0, worktreeId) + } else if (order[low] === worktreeId) { + order.splice(low, 1) + } else { + target.order = null + } +} + +function setChats(target: Lineage, worktreeId: string, tabs: readonly StructuredTab[]): void { + const before = target.chats.get(worktreeId) ?? NO_TABS + if (tabs === before) { + return + } + if (!before.length !== !tabs.length) { + placeInOrder(target, worktreeId, tabs.length > 0) + } + if (tabs.length) { + target.chats.set(worktreeId, tabs) + } else { + target.chats.delete(worktreeId) + } + target.stale = target.list ?? target.stale + target.list = null +} + +// Cold path: bootstrap, hydration, an unannotated or reordering replacement; the only whole-map walk. +function rebuildFromSnapshot(source: TabsByWorktree, previous: Lineage | null): Lineage { + const rebuilt: Lineage = { + source, + rank: new Map(), + nextRank: 0, + chats: new Map(), + order: null, + list: null, + stale: previous?.list ?? previous?.stale ?? null + } + for (const worktreeId of Object.keys(source)) { + rebuilt.rank.set(worktreeId, rebuilt.nextRank++) + const tabs = structuredTabsOf(source[worktreeId] ?? [], previous?.chats.get(worktreeId)) + if (tabs.length) { + rebuilt.chats.set(worktreeId, tabs) + } + } + return rebuilt +} + +/** False when the change can't be placed by ranks alone (an index-like workspace key). */ +function applyAddressed( + target: Lineage, + source: TabsByWorktree, + changes: Extract, { kind: 'addressed' }> +): boolean { + if (changes.addedWorkspaceIds.some((worktreeId) => INDEX_KEY.test(worktreeId))) { + return false + } + for (const worktreeId of changes.addedWorkspaceIds) { + target.rank.set(worktreeId, target.nextRank++) + } + for (const worktreeId of changes.workspaceIds) { + const bucket = Object.hasOwn(source, worktreeId) ? source[worktreeId] : undefined + setChats( + target, + worktreeId, + bucket ? structuredTabsOf(bucket, target.chats.get(worktreeId)) : NO_TABS + ) + } + // Ranks of deleted workspaces go after their chats leave the cached order. + for (const worktreeId of changes.deletedWorkspaceIds) { + target.rank.delete(worktreeId) + } + target.source = source + return true +} + +function advance(source: TabsByWorktree): Lineage { + if (lineage?.source === source) { + return lineage + } + const changes = lineage ? readTabMapChanges(source, lineage.source) : null + if (!(lineage && changes?.kind === 'addressed' && applyAddressed(lineage, source, changes))) { + lineage = rebuildFromSnapshot(source, lineage) + } + return lineage +} + +function materialize(current: Lineage): readonly StructuredTab[] { + if (!current.list) { + // Sorted only after a full resync; ordinary chat edits reuse the cached order. + current.order ??= [...current.chats.keys()].sort( + (a, b) => rankOf(current, a) - rankOf(current, b) + ) + const built = current.order.flatMap((worktreeId) => current.chats.get(worktreeId) ?? NO_TABS) + current.list = current.stale && sameTabs(current.stale, built) ? current.stale : built + current.stale = null + } + return current.list +} + +/** Structured-session tabs; the same list while no chat tab changed, so non-chat tab writes stay quiet. */ +export function getStructuredAgentSessionTabs( + unifiedTabsByWorktree: TabsByWorktree +): readonly StructuredTab[] { + const cached = listsBySnapshot.get(unifiedTabsByWorktree) + if (cached) { + return cached + } + const list = materialize(advance(unifiedTabsByWorktree)) + listsBySnapshot.set(unifiedTabsByWorktree, list) + return list +} + +const paneTabs = new WeakMap>() export function getStructuredAgentSessionTabsByPaneKey( - tabs: Record + tabs: TabsByWorktree ): ReadonlyMap { - const cached = paneTabs.get(tabs) + const structuredTabs = getStructuredAgentSessionTabs(tabs) + const cached = paneTabs.get(structuredTabs) if (cached) { return cached } const result = new Map( - getStructuredAgentSessionTabs(tabs).map((tab) => [ - structuredAgentSessionPaneKey(tab.id, tab.entityId), - tab - ]) + structuredTabs.map((tab) => [structuredAgentSessionPaneKey(tab.id, tab.entityId), tab]) ) - paneTabs.set(tabs, result) + paneTabs.set(structuredTabs, result) return result } + +/** One workspace's structured tabs, from the same addressed projection. */ +export function getStructuredAgentSessionTabsInWorkspace( + unifiedTabsByWorktree: TabsByWorktree, + worktreeId: string +): readonly StructuredTab[] { + return advance(unifiedTabsByWorktree).chats.get(worktreeId) ?? NO_TABS +} diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/structured-chat-activity-status-live.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/structured-chat-activity-status-live.test.tsx index b38141f4ad9..ae65b41dda2 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/structured-chat-activity-status-live.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/structured-chat-activity-status-live.test.tsx @@ -106,11 +106,23 @@ describe.each(['sidebar', 'parent picker', 'palette'])( expect(chatStatusLabels()).toEqual(['inactive']) const tab = useAppStore.getState().unifiedTabsByWorktree[TARGET_WORKTREE_ID][0] const paneKey = structuredAgentSessionPaneKey(tab.id, tab.entityId) - act(() => useAppStore.getState().setStructuredChatSleptAt(paneKey, undefined)) + act(() => + useAppStore + .getState() + .applyStructuredChatCompanionWrites([{ kind: 'slept-at', paneKey, sleptAt: undefined }]) + ) expect(chatStatusLabels()).toEqual(['active']) - act(() => useAppStore.getState().setStructuredChatSleptAt(paneKey, 1)) + act(() => + useAppStore + .getState() + .applyStructuredChatCompanionWrites([{ kind: 'slept-at', paneKey, sleptAt: 1 }]) + ) expect(chatStatusLabels()).toEqual(['inactive']) - act(() => useAppStore.getState().setStructuredChatSleptAt(paneKey, null)) + act(() => + useAppStore + .getState() + .applyStructuredChatCompanionWrites([{ kind: 'slept-at', paneKey, sleptAt: null }]) + ) expect(chatStatusLabels()).toEqual(['active']) const working: AgentStatusEntry = { paneKey, diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-action-launch.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-action-launch.ts index 3a8a78ca962..f4c2a93b34b 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-action-launch.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-action-launch.ts @@ -123,7 +123,7 @@ export async function openTerminalForDeclinedChat( code: 'structured_agent_session_unsupported', causeText } - publishStructuredLaunchChange() + publishStructuredLaunchChange(launchState.intent.sessionId) } if (completed.outcome.status !== 'created') { if (terminal.refusal) { diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-cancel.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-cancel.ts index 48569f33edb..9d5ba6b7db2 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-cancel.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-cancel.ts @@ -63,7 +63,7 @@ function markStructuredAgentSessionLaunchCancelledInternal( removeStructuredLaunchSlot(owner, worktreeId, sessionId) } if (!alreadyCancelled && owner) { - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(sessionId) } return !alreadyCancelled } diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-message.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-message.ts index 73d23a88021..c0cc637ad90 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-message.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-message.ts @@ -56,7 +56,7 @@ export function prepareStructuredLaunchCreateMessage( if (intent.createMessageSupport !== true) { prepareLegacyStructuredLaunchPrompts(intent.sessionId) intent.createPrepared = true - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(intent.sessionId) return } const hadPrompt = hasStagedStructuredLaunchPrompt(intent.sessionId) @@ -94,7 +94,7 @@ export function prepareStructuredLaunchCreateMessage( } } intent.createPrepared = true - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(intent.sessionId) } /** Hosts before options-mode may refuse an action's mode (older permission tables): the chat takes diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-input.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-input.ts index f666dc1b6d8..72eb37bd1f8 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-input.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-input.ts @@ -64,7 +64,7 @@ export function settleStructuredLaunchFirstMessageFromJournal( ) } deleteStructuredAgentLaunchRecord(sessionId) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(sessionId) } /** The launch adopts an existing conversation, which may keep a model of its own. */ diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-outcome-tracking.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-outcome-tracking.ts index 331bcaad405..f19ea8db67a 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-outcome-tracking.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-outcome-tracking.ts @@ -28,7 +28,7 @@ import { forgetStructuredSessionSelection } from '../options/structured-agent-se function cleanupLaunchState(state: StructuredLaunchState): void { if (deleteStructuredLaunchStateIfCurrent(state)) { - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } } @@ -70,7 +70,7 @@ function settleStructuredLaunchRefusal(state: StructuredLaunchState): void { ) { state.operationEnded = true state.callers.outcome = 'unknown' - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) return } retireStructuredAgentSessionLaunchCancellationTombstone( @@ -83,7 +83,7 @@ function settleStructuredLaunchRefusal(state: StructuredLaunchState): void { if (cleanupUnmaterializedLaunch(state)) { retireStructuredAgentSessionReadOwner(state.intent.sessionId, state.intent.target) } - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } export function trackLaunchSettlement( @@ -134,7 +134,7 @@ export function trackLaunchSettlement( receipt.cursor ) } - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) }, (error) => { if (state.promise !== promise) { @@ -162,7 +162,7 @@ export function trackLaunchSettlement( } else if (!state.visibilityUnknown) { settleStructuredLaunchCallers(state.callers, 'failed') cleanupUnmaterializedLaunch(state) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } else { if (state.intent.params.firstMessage) { state.operationEnded = true @@ -170,7 +170,7 @@ export function trackLaunchSettlement( } state.callers.outcome = 'unknown' materializeStructuredLaunchSurface(state.intent) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } } ) diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts index cedb756a0d8..da802e7ddbc 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts @@ -150,7 +150,7 @@ describe('structured agent launch persistence', () => { expect( retireAbsentStructuredAgentLaunchCancellationTombstonesPersisted(new Set(), 'local') - ).toBe(true) + ).toEqual(['local_session']) expect(hasStructuredAgentLaunchCancellationTombstonePersisted('local_session')).toBe(false) expect(hasStructuredAgentLaunchCancellationTombstonePersisted('remote_session')).toBe(true) }) diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.ts index da294059c0b..0b0458013d4 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.ts @@ -250,20 +250,20 @@ export function retireStructuredAgentLaunchCancellationTombstonePersisted( export function retireAbsentStructuredAgentLaunchCancellationTombstonesPersisted( publishedSessionIds: ReadonlySet, executionHostId: ExecutionHostId -): boolean { +): string[] { load() - let changed = false + const retired: string[] = [] for (const [sessionId, owner] of tombstones) { if (owner === executionHostId && !publishedSessionIds.has(sessionId)) { tombstones.delete(sessionId) remoteTombstoneCancelledAt.delete(sessionId) - changed = true + retired.push(sessionId) } } - if (changed) { + if (retired.length) { writeTombstones() } - return changed + return retired } export function resetStructuredAgentLaunchPersistenceForTests(): void { diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prompt-outcome.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prompt-outcome.ts index b463f6aa516..043d5b9a0a7 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prompt-outcome.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prompt-outcome.ts @@ -38,7 +38,7 @@ export function trackStructuredLaunchPromptOutcome( state.visibilityUnknown = true group.outcome = 'unknown' } - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) }) } @@ -61,7 +61,7 @@ export function trackStructuredLaunchConfirmationDeadline( } state.visibilityUnknown = true state.callers.outcome = 'unknown' - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) }, STRUCTURED_AGENT_SESSION_SEND_BUDGET_MS) const clear = (): void => clearTimeout(deadline) void promise.then(clear, clear) diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication-confirmation.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication-confirmation.ts index f47bccbe369..a17fd6f242e 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication-confirmation.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication-confirmation.ts @@ -46,5 +46,5 @@ export function confirmStructuredLaunchFirstMessagePublication( }) trackLaunchSettlement(state, state.promise) trackStructuredLaunchConfirmationDeadline(state, state.promise) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication.ts index cd893175065..a0dc7496bf0 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-publication.ts @@ -43,7 +43,7 @@ export function markStructuredAgentSessionLaunchPublished( return false } deleteStructuredAgentLaunchRecord(sessionId) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(sessionId) return true } if ( @@ -71,7 +71,7 @@ export function markStructuredAgentSessionLaunchPublished( state.callers.outcome = 'published' deleteStructuredAgentLaunchRecord(sessionId) state.callers.onSettled() - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(sessionId) return true } diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-registry.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-registry.ts index a401aa58777..f402eda1673 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-registry.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-registry.ts @@ -56,7 +56,9 @@ export type StructuredAgentSessionLaunchLifecycle = | 'cancelled' const structuredLaunchesBySessionId = new Map() -const structuredLaunchListeners = new Set<() => void>() +/** Null when the writer can't name its sessions, so subscribers re-read every launch. */ +type StructuredLaunchListener = (sessionIds: readonly string[] | null) => void +const structuredLaunchListeners = new Set() export function resetStructuredAgentLaunchRegistryForTests(): void { for (const sessionId of structuredLaunchesBySessionId.keys()) { @@ -68,23 +70,26 @@ export function resetStructuredAgentLaunchRegistryForTests(): void { resetStructuredAgentLocalLaunchCancelsForTests() } -export function notifyStructuredLaunchListeners(): void { +export function notifyStructuredLaunchListeners(sessionIds?: string | readonly string[]): void { function* changes(): Generator { for (const state of structuredLaunchesBySessionId.values()) { yield [state.intent.sessionId, structuredLaunchRecord(state)] } } updateStructuredAgentLaunchRecords(changes()) - publishStructuredLaunchChange() + publishStructuredLaunchChange(sessionIds) } -export function publishStructuredLaunchChange(): void { +export function publishStructuredLaunchChange(sessionIds?: string | readonly string[]): void { + const changed = typeof sessionIds === 'string' ? [sessionIds] : (sessionIds ?? null) for (const listener of structuredLaunchListeners) { - listener() + listener(changed) } } -export function subscribeStructuredAgentLaunchStatus(listener: () => void): () => void { +export function subscribeStructuredAgentLaunchStatus( + listener: StructuredLaunchListener +): () => void { structuredLaunchListeners.add(listener) return () => structuredLaunchListeners.delete(listener) } @@ -251,7 +256,7 @@ export function retireStructuredAgentSessionLaunchCancellationTombstone( return false } retireStructuredAgentLaunchCancellation(sessionId) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(sessionId) return true } @@ -260,13 +265,13 @@ export function retireAbsentStructuredAgentSessionLaunchCancellationTombstones( authoritativeInventory: number, executionHostId: ExecutionHostId ): boolean { - const changed = retireAbsentStructuredAgentLaunchCancellations( + const retired = retireAbsentStructuredAgentLaunchCancellations( publishedSessionIds, authoritativeInventory, executionHostId ) - if (changed) { - notifyStructuredLaunchListeners() + if (retired.length) { + notifyStructuredLaunchListeners(retired) } - return changed + return retired.length > 0 } diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts index 386caf77d29..9571ccf1f6a 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts @@ -91,7 +91,7 @@ function adoptPairedHostSeed( delete state.intent.seedOptions } state.selection = { ...selection, seed: seedOptions } - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } function resetStructuredLaunchCallers( @@ -133,7 +133,7 @@ function restartStructuredLaunchState( ) trackLaunchSettlement(state, state.promise) trackStructuredLaunchConfirmationDeadline(state, state.promise) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) } function joinStructuredLaunchState( @@ -230,7 +230,7 @@ function structuredAgentLaunchState( promise: Promise.resolve({ sessionId: '', fence: 0 }), visibilityUnknown: false, cancelled: false, - onVisibilityChanged: notifyStructuredLaunchListeners, + onVisibilityChanged: () => notifyStructuredLaunchListeners(intent.sessionId), callers, selection: initialStructuredLaunchSelection(intent) } @@ -250,7 +250,7 @@ function structuredAgentLaunchState( }) trackStructuredLaunchPromptOutcome(state, caller) setStructuredLaunchState(state) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(state.intent.sessionId) trackLaunchSettlement(state, state.promise) return { state, caller, joined: false } } @@ -268,7 +268,7 @@ export function cancelStructuredAgentLaunch(worktreeId: string, sessionId: strin ) discardStructuredAgentSessionChatSends(state.intent.sessionId) abandonStructuredAgentSessionLaunchIntent(state.intent) - notifyStructuredLaunchListeners() + notifyStructuredLaunchListeners(sessionId) return true } diff --git a/src/renderer/src/lib/launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation.ts b/src/renderer/src/lib/launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation.ts index 3c78941be1d..eff11b75515 100644 --- a/src/renderer/src/lib/launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation.ts +++ b/src/renderer/src/lib/launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation.ts @@ -130,7 +130,7 @@ export function retireAbsentStructuredAgentLaunchCancellations( publishedSessionIds: ReadonlySet, authoritativeInventory: number, executionHostId: ExecutionHostId -): boolean { +): string[] { restoreCancellationRetirementFences() const retainedSessionIds = new Set(publishedSessionIds) for (const [sessionId, retirement] of cancellationRetirementBySessionId) { @@ -141,16 +141,16 @@ export function retireAbsentStructuredAgentLaunchCancellations( retainedSessionIds.add(sessionId) } } - const changed = retireAbsentStructuredAgentLaunchCancellationTombstonesPersisted( + const retired = retireAbsentStructuredAgentLaunchCancellationTombstonesPersisted( retainedSessionIds, executionHostId ) - if (changed) { + if (retired.length) { for (const sessionId of cancellationRetirementBySessionId.keys()) { if (!hasStructuredAgentLaunchCancellationTombstonePersisted(sessionId)) { cancellationRetirementBySessionId.delete(sessionId) } } } - return changed + return retired } diff --git a/src/renderer/src/runtime/web-session-tabs-sync/scoped-patch-annotation.ts b/src/renderer/src/runtime/web-session-tabs-sync/scoped-patch-annotation.ts new file mode 100644 index 00000000000..ca8bf60380f --- /dev/null +++ b/src/renderer/src/runtime/web-session-tabs-sync/scoped-patch-annotation.ts @@ -0,0 +1,13 @@ +import type { AppState } from '../../store/types' +import { markPatchFullResync } from '../../store/seam-record-fields' + +/** Host-mirror funnel: imported host snapshots replace each tracked record they touch wholesale. */ +export function markHostMirrorPatchFullResync( + state: Partial, + patch: Partial +): void { + if (patch !== state) { + // Cold path: host session snapshots are rebuilt into the store, not written key by key. + markPatchFullResync(patch, 'host-mirror-frame', state) + } +} diff --git a/src/renderer/src/runtime/web-session-tabs-sync/store-patch.ts b/src/renderer/src/runtime/web-session-tabs-sync/store-patch.ts index 7aa50ba4384..c1684c62eb3 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/store-patch.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/store-patch.ts @@ -23,6 +23,7 @@ import { hostWorkingClientBoundaryByPaneKey, type WebSessionTabsSyncState } from './state' +import { markHostMirrorPatchFullResync } from './scoped-patch-annotation' import { reportVisibleTabPickToHost } from './navigation/web-session-visible-tab-pick-report' import { createHostSessionMirrorSettle, @@ -63,6 +64,7 @@ export function applyWebSessionTabsStorePatch( changedAgentPaneKeys: Set ): WebSessionTabsSyncState | Partial => { const patch = buildPatch(state, changedAgentPaneKeys) + markHostMirrorPatchFullResync(state, patch) mirroredAgentStatusChanged = patch !== state && Object.hasOwn(patch, 'agentStatusByPaneKey') if (agentStatusSnapshots) { const nextAgentStatuses = patch.agentStatusByPaneKey ?? state.agentStatusByPaneKey diff --git a/src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.ts b/src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.ts index 7be766f6354..e4b9208b154 100644 --- a/src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.ts +++ b/src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.ts @@ -190,7 +190,9 @@ export function openWorkspaceLayoutFrameSync( const rekeyed = shownContentRekeyPatch(state, cache) const base: AppState = { ...state, ...rekeyed } const builtKeys = [...fullBuilt, ...workspaceBuilt] - const patch = layoutFrameFlushPatch(base, cache, { fullBuilt, workspaceBuilt, rebound }, holds) + const builds = { fullBuilt, workspaceBuilt, rebound } + const patch = layoutFrameFlushPatch(base, cache, builds, holds) + // The flush's builds mark their own records full resync; rekeys keep their writers' provenance. show({ ...rekeyed, ...patch }, builtKeys) if (titleUpdates.length > 0) { store.getState().updateTabTitles(titleUpdates) diff --git a/src/renderer/src/store/index.ts b/src/renderer/src/store/index.ts index 8572890fb3f..b464e29ea7c 100644 --- a/src/renderer/src/store/index.ts +++ b/src/renderer/src/store/index.ts @@ -53,6 +53,7 @@ import { createRemoteServerUpdatesSlice } from './slices/runtime-host-updates/re import { createTerminalQuickCommandHostsSlice } from './terminals/terminal-quick-command-hosts' import { createStructuredSessionLaunchDirectorySlice } from './slices/agent-status/structured-session-launch-directories' import { createStructuredChatSleptAtSlice } from './slices/agent-status/structured-chat-slept-at' +import { createStructuredChatCompanionWritesSlice } from './slices/agent-status/structured-chat-companion-writes' import { createEphemeralVmLifecycleSlice } from './slices/ephemeral-vm/ephemeral-vm-lifecycle' import { createWorkspaceAttentionSlice } from './slices/workspace-attention/workspace-attention-slice' import { e2eConfig } from '@/lib/e2e-config' @@ -77,6 +78,7 @@ import { } from '@/lib/renderer-memory-profile' import { estimateStateCollectionKB } from '@/lib/state-collection-byte-estimate' import { registerWindowsPathAccessEnvironments } from '@/lib/windows-path-access' +import { STORE_OBSERVER_INSTALLERS } from './store-observer-installers' // Dev-only churn probe cannot be armed in shipped builds; avoid its per-write wrapper. Cascade probe stays enabled for field crash telemetry. const withDevelopmentStoreProbes = (createState: StateCreator) => @@ -150,6 +152,7 @@ export const useAppStore = create()( ...createTerminalQuickCommandHostsSlice(...a), ...createStructuredSessionLaunchDirectorySlice(...a), ...createStructuredChatSleptAtSlice(...a), + ...createStructuredChatCompanionWritesSlice(...a), ...createWorkspaceAttentionSlice(...a), ...createEphemeralVmLifecycleSlice(...a) } @@ -159,6 +162,10 @@ export const useAppStore = create()( ) ) +for (const install of STORE_OBSERVER_INSTALLERS) { + install(useAppStore) +} + registerStructuredSelectionCatalogStore({ read: useAppStore.getState, subscribe: useAppStore.subscribe diff --git a/src/renderer/src/store/keyed-record-change-reads.ts b/src/renderer/src/store/keyed-record-change-reads.ts new file mode 100644 index 00000000000..2e449b7a451 --- /dev/null +++ b/src/renderer/src/store/keyed-record-change-reads.ts @@ -0,0 +1,109 @@ +import { isIndexKey } from './keyed-record-index-keys' +import { + linkOf, + type AddressedKeyChanges, + type FullResyncReason, + type Keyed, + type KeyedSnapshot, + type Link, + type RecordChanges, + type TabMapChanges +} from './keyed-record-transitions' + +// Readers that skipped intermediate states still get an exact union; deeper gaps resync. +const MAX_CHAIN = 64 + +type Walked = AddressedKeyChanges & { tabIds: Set | null } + +// Composes forward, oldest write first, so added keys come out in the order the source holds them. +function walk(next: Keyed, previous: Keyed): Walked | FullResyncReason { + const steps: Exclude[] = [] + let current: Keyed = next + for (let depth = 0; ; depth++) { + if (depth === MAX_CHAIN) { + return 'unknown' + } + const step = linkOf(current) + if (!step) { + return 'unknown' + } + if ('reason' in step) { + return step.reason + } + steps.push(step) + const before = step.previous.deref() + if (!before) { + return 'unknown' + } + if (before === previous) { + break + } + current = before + } + const keys = new Set() + const added = new Set() + const deleted = new Set() + let tabIds: Set | null = new Set() + for (const step of steps.toReversed()) { + for (const key of step.deleted) { + if (!added.delete(key)) { + deleted.add(key) + } + } + for (const key of step.added) { + // A key the start held, deleted and added back, has moved; only a walk can place it. + if (deleted.has(key)) { + return 'reordered' + } + added.add(key) + } + step.keys.forEach((key) => keys.add(key)) + if (step.tabIds && tabIds) { + step.tabIds.forEach((id) => tabIds?.add(id)) + } else { + tabIds = null + } + } + const ordered = steps[0]?.integerKeysFirst + ? [ + ...[...added].filter(isIndexKey).sort((a, b) => Number(a) - Number(b)), + ...[...added].filter((key) => !isIndexKey(key)) + ] + : [...added] + return { keys, added: ordered, deleted, tabIds } +} + +/** null: same identity. Addressed only when every write from `previous` to `next` was annotated. */ +export function readRecordChanges(next: Keyed, previous: Keyed): RecordChanges | null { + if (next === previous) { + return null + } + const result = walk(next, previous) + return typeof result === 'string' + ? { kind: 'full-resync', reason: result } + : { kind: 'addressed', keys: result.keys, added: result.added, deleted: result.deleted } +} + +export function readTabMapChanges( + next: KeyedSnapshot, + previous: KeyedSnapshot +): TabMapChanges | null { + if (next === previous) { + return null + } + const result = walk(next, previous) + if (typeof result === 'string') { + return { kind: 'full-resync', reason: result } + } + // A plain record link names no tabs, so it cannot address a tab map. + return result.tabIds + ? { + kind: 'addressed', + workspaceIds: result.keys, + tabIds: result.tabIds, + workspaceSetChanged: result.added.length > 0 || result.deleted.size > 0, + addedWorkspaceIds: result.added, + deletedWorkspaceIds: result.deleted + } + : { kind: 'full-resync', reason: 'unknown' } +} diff --git a/src/renderer/src/store/keyed-record-index-keys.ts b/src/renderer/src/store/keyed-record-index-keys.ts new file mode 100644 index 00000000000..acaee86b05a --- /dev/null +++ b/src/renderer/src/store/keyed-record-index-keys.ts @@ -0,0 +1,5 @@ +const INTEGER_KEY = /^(?:0|[1-9]\d*)$/ +// Object.keys lists array-index keys first, ascending; only the others carry insertion order. +export function isIndexKey(key: string): boolean { + return INTEGER_KEY.test(key) && Number(key) < 2 ** 32 - 1 +} diff --git a/src/renderer/src/store/keyed-record-transitions.test.ts b/src/renderer/src/store/keyed-record-transitions.test.ts new file mode 100644 index 00000000000..ad428b9e57a --- /dev/null +++ b/src/renderer/src/store/keyed-record-transitions.test.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from 'vitest' +import { + markFullResync, + recordDraft, + replaceMapEntries, + replaceRecordEntries, + replaceTabBuckets, + tabBucketDraft +} from './keyed-record-transitions' +import { readRecordChanges, readTabMapChanges } from './keyed-record-change-reads' + +const a1 = { id: 'a1' } +const a2 = { id: 'a2' } +const b1 = { id: 'b1' } + +describe('keyed record transitions', () => { + it('names the replaced buckets and the tabs that changed in them', () => { + const start = { a: [a1, a2], b: [b1] } + const renamed = { id: 'a2', label: 'renamed' } + const next = replaceTabBuckets(start, [['a', [a1, renamed]]]) + expect(readTabMapChanges(next, start)).toEqual({ + kind: 'addressed', + workspaceIds: new Set(['a']), + tabIds: new Set(['a2']), + workspaceSetChanged: false, + addedWorkspaceIds: [], + deletedWorkspaceIds: new Set() + }) + expect(next.b).toBe(start.b) + }) + + it('unions a chain of annotated writes and covers both owners of a move', () => { + const start = { a: [a1, a2], b: [b1] } + const created = replaceTabBuckets(start, [['c', [{ id: 'c1' }]]]) + const moved = replaceTabBuckets(created, [ + ['a', [a1]], + ['b', [b1, a2]] + ]) + expect(readTabMapChanges(moved, start)).toEqual({ + kind: 'addressed', + workspaceIds: new Set(['a', 'b', 'c']), + tabIds: new Set(['a2', 'c1']), + workspaceSetChanged: true, + addedWorkspaceIds: ['c'], + deletedWorkspaceIds: new Set() + }) + }) + + it('reads an unannotated or cold replacement as a full resync', () => { + const start = { a: [a1] } + expect(readTabMapChanges({ ...start, a: [a1, a2] }, start)).toEqual({ + kind: 'full-resync', + reason: 'unknown' + }) + const hydrated = replaceTabBuckets(markFullResync({ a: [a2] }, 'hydration'), [['b', [b1]]]) + expect(readTabMapChanges(hydrated, start)).toEqual({ kind: 'full-resync', reason: 'hydration' }) + }) + + it('derives changes and order from the operations a draft performed', () => { + const start = { a: [a1], b: [b1] } + const draft = tabBucketDraft(start) + draft.set('c', [{ id: 'c1' }]) + draft.set('a', [a1, a2]) + draft.delete('b') + const next = draft.finish() + expect(Object.keys(next)).toEqual(['a', 'c']) + expect(readTabMapChanges(next, start)).toEqual({ + kind: 'addressed', + workspaceIds: new Set(['c', 'a', 'b']), + tabIds: new Set(['c1', 'a2', 'b1']), + workspaceSetChanged: true, + addedWorkspaceIds: ['c'], + deletedWorkspaceIds: new Set(['b']) + }) + const ordered = { early: 1, later: 2 } + const moved = recordDraft(ordered) + moved.delete('early') + moved.set('early', 1) + expect(readRecordChanges(moved.finish(), ordered)).toEqual({ + kind: 'full-resync', + reason: 'reordered' + }) + const untouched = recordDraft(start) + untouched.set('a', start.a) + expect(untouched.finish()).toBe(start) + }) + + it('reports keys added across a chain in source order, index keys first', () => { + const start = { base: 1 } + const one = replaceRecordEntries(start, [['earlier', 2]]) + const two = replaceRecordEntries(one, [ + ['later', 3], + ['7', 4] + ]) + expect(Object.keys(two)).toEqual(['7', 'base', 'earlier', 'later']) + const changes = readRecordChanges(two, start) + expect(changes?.kind === 'addressed' && changes.added).toEqual(['7', 'earlier', 'later']) + }) + + it('keeps modified keys out of the ordered additions; survivors keep their source order', () => { + const start = { a: 1, b: 1 } + const one = replaceRecordEntries(start, [['c', 1]]) + const two = replaceRecordEntries(one, [ + ['b', 2], + ['a', 2] + ]) + expect(Object.keys(two)).toEqual(['a', 'b', 'c']) + expect(readRecordChanges(two, start)).toEqual({ + kind: 'addressed', + keys: new Set(['c', 'b', 'a']), + added: ['c'], + deleted: new Set() + }) + }) + + it('reads a delete then re-add of a surviving key as reordered, across a chain or in one write', () => { + const start = { earlier: 1, later: 2 } + const removed = replaceRecordEntries(start, [['earlier', null]]) + const readded = replaceRecordEntries(removed, [['earlier', 1]]) + expect(Object.keys(readded)).toEqual(['later', 'earlier']) + expect(readRecordChanges(readded, start)).toEqual({ kind: 'full-resync', reason: 'reordered' }) + const sameWrite = replaceRecordEntries(start, [ + ['earlier', null], + ['earlier', 1] + ]) + expect(readRecordChanges(sameWrite, start)).toEqual({ + kind: 'full-resync', + reason: 'reordered' + }) + }) + + it('tracks Map-typed fields with the same protocol', () => { + const start = new Map([ + ['env-1', 'online'], + ['env-2', 'online'] + ]) + const next = replaceMapEntries(start, [ + ['env-1', 'revoked'], + ['env-2', null], + ['env-3', 'online'] + ]) + expect([...next]).toEqual([ + ['env-1', 'revoked'], + ['env-3', 'online'] + ]) + expect(readRecordChanges(next, start)).toEqual({ + kind: 'addressed', + keys: new Set(['env-1', 'env-2', 'env-3']), + added: ['env-3'], + deleted: new Set(['env-2']) + }) + expect(readRecordChanges(new Map(next), start)).toEqual({ + kind: 'full-resync', + reason: 'unknown' + }) + }) + + it('names deleted record keys', () => { + const start = { t1: 'pty-1', t2: 'pty-2' } + const next = replaceRecordEntries(start, [['t1', null]]) + expect(next).toEqual({ t2: 'pty-2' }) + expect(readRecordChanges(next, start)).toEqual({ + kind: 'addressed', + keys: new Set(['t1']), + added: [], + deleted: new Set(['t1']) + }) + }) + + it('keeps a __proto__ key as an own entry in records and drafts', () => { + const start = { t1: 'pty-1' } + const replaced = replaceRecordEntries(start, [['__proto__', 'pty-2']]) + const draft = recordDraft(start) + draft.set('__proto__', 'pty-2') + for (const next of [replaced, draft.finish()]) { + expect(Object.hasOwn(next, '__proto__')).toBe(true) + expect(JSON.stringify(next)).toBe('{"t1":"pty-1","__proto__":"pty-2"}') + expect(readRecordChanges(next, start)).toEqual({ + kind: 'addressed', + keys: new Set(['__proto__']), + added: ['__proto__'], + deleted: new Set() + }) + } + }) +}) diff --git a/src/renderer/src/store/keyed-record-transitions.ts b/src/renderer/src/store/keyed-record-transitions.ts new file mode 100644 index 00000000000..fc89c6c609a --- /dev/null +++ b/src/renderer/src/store/keyed-record-transitions.ts @@ -0,0 +1,289 @@ +// Accepted-write provenance for keyed store records: the writer's helper names what it replaced, +// so readers update only those keys; anything it did not annotate reads as a full resync. + +export type FullResyncReason = + | 'bootstrap' + | 'hydration' + | 'host-mirror-frame' + | 'reconnect-inventory' + | 'teardown' + | 'reordered' + | 'unknown' + +/** + * Addressed order contract: surviving keys keep their relative order (writers declare a move as + * `reordered`, a full resync) and `added` lists the keys now present that weren't, in source + * order. A reader holding its own key ranks places every change exactly in O(changed). + */ +export type AddressedKeyChanges = { + /** Every added, deleted or replaced key; not ordered. */ + keys: ReadonlySet + /** In source order: index keys ascending first for records, then insertion order. */ + added: readonly string[] + deleted: ReadonlySet +} + +export type RecordChanges = + | ({ kind: 'addressed' } & AddressedKeyChanges) + | { kind: 'full-resync'; reason: FullResyncReason } + +export type TabMapChanges = + | { + kind: 'addressed' + workspaceIds: ReadonlySet + tabIds: ReadonlySet + /** A workspace key was added or deleted; `addedWorkspaceIds` is in source order. */ + workspaceSetChanged: boolean + addedWorkspaceIds: readonly string[] + deletedWorkspaceIds: ReadonlySet + } + | { kind: 'full-resync'; reason: FullResyncReason } + +/** Any keyed store record a writer replaces: tab buckets or a companion record. */ +export type KeyedSnapshot = Readonly> +/** A Map-typed store field (for example runtime status by environment). */ +export type KeyedMapSnapshot = ReadonlyMap +export type Keyed = KeyedSnapshot | KeyedMapSnapshot +type KeyedRecord = Readonly> +type TabRow = { id: string } + +export type Link = + | { + previous: WeakRef + /** Changed keys in write order. */ + keys: readonly string[] + added: readonly string[] + deleted: readonly string[] + /** Records list integer-like keys first, ascending, as Object.keys does; Maps keep insertion order. */ + integerKeysFirst: boolean + tabIds?: ReadonlySet + } + | { reason: FullResyncReason } + +const links = new WeakMap() + +function hasKey(record: Keyed, key: string): boolean { + return record instanceof Map ? record.has(key) : Object.hasOwn(record, key) +} + +function link(next: Keyed, previous: Keyed, keys: Iterable, tabIds?: Set): void { + const ordered = [...keys] + links.set(next, { + previous: new WeakRef(previous), + keys: ordered, + added: ordered.filter((key) => !hasKey(previous, key) && hasKey(next, key)), + deleted: ordered.filter((key) => hasKey(previous, key) && !hasKey(next, key)), + integerKeysFirst: !(next instanceof Map), + ...(tabIds ? { tabIds } : {}) + }) +} + +// An own data property even for `__proto__`, as a computed-key literal or spread would make. +function defineEntry(record: Record, key: string, value: V): void { + Object.defineProperty(record, key, { + value, + writable: true, + enumerable: true, + configurable: true + }) +} + +type Replacement = readonly [key: string, value: V | null] + +// Deleting then re-adding a surviving key moves it to the end, which an addressed key set can't express. +function replaceEntries( + has: (key: string) => boolean, + get: (key: string) => V | undefined, + set: (key: string, value: V) => void, + remove: (key: string) => void, + replacements: Iterable> +): { keys: Set; reordered: boolean } { + const keys = new Set() + const removed = new Set() + let reordered = false + for (const [key, value] of replacements) { + if (value === null) { + if (has(key)) { + remove(key) + removed.add(key) + keys.add(key) + } + } else if (!has(key) || get(key) !== value) { + reordered ||= removed.has(key) + set(key, value) + keys.add(key) + } + } + return { keys, reordered } +} + +/** The next record from `previous` plus replacements (null deletes); its changed keys are exact by construction. */ +export function replaceRecordEntries( + previous: KeyedRecord, + replacements: Iterable> +): Record { + const next: Record = { ...previous } + const { keys, reordered } = replaceEntries( + (key) => Object.hasOwn(next, key), + (key) => next[key], + (key, value) => { + defineEntry(next, key, value) + }, + (key) => { + delete next[key] + }, + replacements + ) + if (reordered) { + links.set(next, { reason: 'reordered' }) + } else { + link(next, previous, keys) + } + return next +} + +/** Map form of replaceRecordEntries, read with the same readRecordChanges protocol. */ +export function replaceMapEntries( + previous: ReadonlyMap, + replacements: Iterable> +): Map { + const next = new Map(previous) + const { keys, reordered } = replaceEntries( + (key) => next.has(key), + (key) => next.get(key), + (key, value) => next.set(key, value), + (key) => next.delete(key), + replacements + ) + if (reordered) { + links.set(next, { reason: 'reordered' }) + } else { + link(next, previous, keys) + } + return next +} + +/** Ordered set/delete operations on a copy-on-write record; the operations are the provenance. */ +export type RecordDraft = { + has: (key: string) => boolean + get: (key: string) => V | undefined + set: (key: string, value: V) => void + delete: (key: string) => void + /** The built record linked to `previous`, or `previous` itself when no operation changed it. */ + finish: () => Record +} + +function createDraft( + previous: KeyedRecord, + linkBuilt: (next: Record, keys: Set) => void +): RecordDraft { + let next: Record | null = null + const keys = new Set() + const removed = new Set() + let reordered = false + const current = (): KeyedRecord => next ?? previous + const writable = (): Record => (next ??= { ...previous }) + return { + has: (key) => Object.hasOwn(current(), key), + get: (key) => (Object.hasOwn(current(), key) ? current()[key] : undefined), + set: (key, value) => { + if (Object.hasOwn(current(), key) && current()[key] === value) { + return + } + reordered ||= removed.has(key) + defineEntry(writable(), key, value) + keys.add(key) + }, + delete: (key) => { + if (!Object.hasOwn(current(), key)) { + return + } + delete writable()[key] + removed.add(key) + keys.add(key) + }, + finish: () => { + if (!next) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: unchanged; callers publish the same object they read. + return previous as Record + } + if (reordered) { + links.set(next, { reason: 'reordered' }) + } else { + linkBuilt(next, keys) + } + return next + } + } +} + +/** A draft for a keyed companion record. */ +export function recordDraft(previous: KeyedRecord): RecordDraft { + return createDraft(previous, (next, keys) => link(next, previous, keys)) +} + +function tabRows(record: KeyedSnapshot, key: string): readonly TabRow[] | undefined { + const value = Object.hasOwn(record, key) ? record[key] : undefined + return Array.isArray(value) ? value : undefined +} + +function changedTabIds( + previous: readonly TabRow[] | undefined, + next: readonly TabRow[] | undefined, + into: Set +): void { + if (previous === next) { + return + } + const before = new Map((previous ?? []).map((tab) => [tab.id, tab])) + for (const tab of next ?? []) { + if (before.get(tab.id) !== tab) { + into.add(tab.id) + } + before.delete(tab.id) + } + for (const id of before.keys()) { + into.add(id) + } +} + +function linkTabBuckets( + previous: KeyedSnapshot, + next: KeyedSnapshot, + keys: Iterable +): void { + const tabIds = new Set() + for (const workspaceId of keys) { + changedTabIds(tabRows(previous, workspaceId), tabRows(next, workspaceId), tabIds) + } + link(next, previous, keys, tabIds) +} + +/** Tab-bucket form; tab IDs come from diffing only the replaced buckets. */ +export function replaceTabBuckets( + previous: KeyedRecord, + replacements: Iterable +): Record { + const next = replaceRecordEntries(previous, replacements) + const recorded = links.get(next) + if (recorded && 'keys' in recorded) { + linkTabBuckets(previous, next, recorded.keys) + } + return next +} + +/** A draft for a tab-bucket map; tab IDs come from diffing only the buckets it replaced. */ +export function tabBucketDraft(previous: KeyedRecord): RecordDraft { + return createDraft(previous, (next, keys) => linkTabBuckets(previous, next, keys)) +} + +/** Named cold path: the whole record was rebuilt from a snapshot. */ +export function markFullResync(next: R, reason: FullResyncReason): R { + links.set(next, { reason }) + return next +} + +/** Read-only access to a record's provenance link, for the change reader. */ +export function linkOf(record: Keyed): Readonly | undefined { + return links.get(record) +} diff --git a/src/renderer/src/store/seam-record-fields.ts b/src/renderer/src/store/seam-record-fields.ts new file mode 100644 index 00000000000..7bb6829d40f --- /dev/null +++ b/src/renderer/src/store/seam-record-fields.ts @@ -0,0 +1,46 @@ +import type { AppState } from './types' +import { markFullResync, type FullResyncReason } from './keyed-record-transitions' + +// The one place that names the seam's tracked fields, so annotating writers name none themselves. +export const SEAM_TAB_MAP_FIELDS = ['tabsByWorktree', 'unifiedTabsByWorktree'] as const +export const SEAM_WORKSPACE_RECORD_FIELDS = [ + 'groupsByWorktree', + 'layoutByWorktree', + 'activeGroupIdByWorktree' +] as const +export const SEAM_SCOPED_TAB_RECORD_FIELDS = [ + 'ptyIdsByTabId', + 'terminalLayoutsByTabId', + 'runtimePaneTitlesByTabId', + 'pendingStartupByTabId' +] as const + +type SeamTabMapField = (typeof SEAM_TAB_MAP_FIELDS)[number] +type TrackedField = + | SeamTabMapField + | (typeof SEAM_WORKSPACE_RECORD_FIELDS)[number] + | (typeof SEAM_SCOPED_TAB_RECORD_FIELDS)[number] + +export function isSeamTabMapField(field: string): field is SeamTabMapField { + return SEAM_TAB_MAP_FIELDS.some((name) => name === field) +} + +/** Cold path: every tracked record this patch replaces was rebuilt wholesale. Records equal to + * `previous`'s are left alone: the patch passes them through rather than replacing them. */ +export function markPatchFullResync

>>( + patch: P, + reason: FullResyncReason, + previous?: Partial> +): P { + for (const field of [ + ...SEAM_TAB_MAP_FIELDS, + ...SEAM_WORKSPACE_RECORD_FIELDS, + ...SEAM_SCOPED_TAB_RECORD_FIELDS + ]) { + const next = patch[field] + if (next && next !== previous?.[field]) { + markFullResync(next, reason) + } + } + return patch +} diff --git a/src/renderer/src/store/slices/agent-status/structured-chat-companion-writes.ts b/src/renderer/src/store/slices/agent-status/structured-chat-companion-writes.ts new file mode 100644 index 00000000000..952c4ab8ef6 --- /dev/null +++ b/src/renderer/src/store/slices/agent-status/structured-chat-companion-writes.ts @@ -0,0 +1,67 @@ +import type { StateCreator } from 'zustand' +import type { AppState } from '../../types' +import { withStructuredChatSleptAt } from './structured-chat-slept-at' +import { + withoutStructuredSessionLaunchDirectory, + withStructuredSessionLaunchDirectory +} from './structured-session-launch-directories' + +/** A status projection's sleep and launch-directory side facts, applied in order. */ +export type StructuredChatCompanionWrite = + | { kind: 'slept-at'; paneKey: string; sleptAt: number | null | undefined } + | { kind: 'launch-directory'; tabId: string; sessionId: string; launchDirectory: string } + | { kind: 'clear-launch-directory'; tabId: string; sessionId: string } + +export type StructuredChatCompanionWritesSlice = { + /** One store write per projection, so a reconnect snapshot does not notify once per chat. */ + applyStructuredChatCompanionWrites: (writes: readonly StructuredChatCompanionWrite[]) => void +} + +export const createStructuredChatCompanionWritesSlice: StateCreator< + AppState, + [], + [], + StructuredChatCompanionWritesSlice +> = (set) => ({ + applyStructuredChatCompanionWrites: (writes) => { + if (!writes.length) { + return + } + set((state) => { + let sleptAt = state.structuredChatSleptAtByPaneKey + let directories = state.structuredSessionLaunchDirectoryByTabId + for (const write of writes) { + if (write.kind === 'slept-at') { + sleptAt = withStructuredChatSleptAt(sleptAt, write.paneKey, write.sleptAt) + } else if (write.kind === 'launch-directory') { + directories = withStructuredSessionLaunchDirectory( + directories, + write.tabId, + write.sessionId, + write.launchDirectory + ) + } else { + directories = withoutStructuredSessionLaunchDirectory( + directories, + write.tabId, + write.sessionId + ) + } + } + if ( + sleptAt === state.structuredChatSleptAtByPaneKey && + directories === state.structuredSessionLaunchDirectoryByTabId + ) { + return state + } + return { + ...(sleptAt !== state.structuredChatSleptAtByPaneKey + ? { structuredChatSleptAtByPaneKey: sleptAt } + : {}), + ...(directories !== state.structuredSessionLaunchDirectoryByTabId + ? { structuredSessionLaunchDirectoryByTabId: directories } + : {}) + } + }) + } +}) diff --git a/src/renderer/src/store/slices/agent-status/structured-chat-slept-at.ts b/src/renderer/src/store/slices/agent-status/structured-chat-slept-at.ts index 8c294d630d0..885fa0aa8dd 100644 --- a/src/renderer/src/store/slices/agent-status/structured-chat-slept-at.ts +++ b/src/renderer/src/store/slices/agent-status/structured-chat-slept-at.ts @@ -10,7 +10,6 @@ export type StructuredChatSleptAtByPaneKey = Readonly void } const EMPTY_SLEPT_CHATS: StructuredChatSleptAtByPaneKey = Object.freeze({}) @@ -54,23 +53,23 @@ export const hasAwakeStructuredChat = createStructuredChatPresenceSelector( (sleptAt) => typeof sleptAt !== 'number' ) +export function withStructuredChatSleptAt( + current: StructuredChatSleptAtByPaneKey, + paneKey: string, + sleptAt: number | null | undefined +): StructuredChatSleptAtByPaneKey { + if (current[paneKey] === sleptAt) { + return current + } + const { [paneKey]: _previous, ...rest } = current + return sleptAt === undefined ? rest : { ...rest, [paneKey]: sleptAt } +} + export const createStructuredChatSleptAtSlice: StateCreator< AppState, [], [], StructuredChatSleptAtSlice -> = (set) => ({ - structuredChatSleptAtByPaneKey: {}, - setStructuredChatSleptAt: (paneKey, sleptAt) => - set((state) => { - const current = state.structuredChatSleptAtByPaneKey - if (current[paneKey] === sleptAt) { - return state - } - const { [paneKey]: _previous, ...rest } = current - return { - structuredChatSleptAtByPaneKey: - sleptAt === undefined ? rest : { ...rest, [paneKey]: sleptAt } - } - }) +> = () => ({ + structuredChatSleptAtByPaneKey: {} }) diff --git a/src/renderer/src/store/slices/agent-status/structured-session-launch-directories.ts b/src/renderer/src/store/slices/agent-status/structured-session-launch-directories.ts index dba220eaef1..f02196a209a 100644 --- a/src/renderer/src/store/slices/agent-status/structured-session-launch-directories.ts +++ b/src/renderer/src/store/slices/agent-status/structured-session-launch-directories.ts @@ -10,64 +10,44 @@ export type StructuredSessionLaunchDirectory = { /** Mirror host-pinned chat directories; absent uses workspace resolution except floating chats, which remain unknown until pinned. */ export type StructuredSessionLaunchDirectorySlice = { structuredSessionLaunchDirectoryByTabId: Record - setStructuredSessionLaunchDirectory: ( - tabId: string, - sessionId: string, - launchDirectory: string | undefined - ) => void - /** Only drops the entry while it still belongs to `sessionId`. */ - clearStructuredSessionLaunchDirectory: (tabId: string, sessionId: string) => void } -function withoutTab( - byTabId: Record, - tabId: string -): Record { +type LaunchDirectoriesByTabId = Record + +function withoutTab(byTabId: LaunchDirectoriesByTabId, tabId: string): LaunchDirectoriesByTabId { const { [tabId]: _removed, ...rest } = byTabId return rest } +export function withStructuredSessionLaunchDirectory( + byTabId: LaunchDirectoriesByTabId, + tabId: string, + sessionId: string, + launchDirectory: string | undefined +): LaunchDirectoriesByTabId { + const current = byTabId[tabId] + if (!launchDirectory) { + return current ? withoutTab(byTabId, tabId) : byTabId + } + if (current?.sessionId === sessionId && current.launchDirectory === launchDirectory) { + return byTabId + } + return { ...byTabId, [tabId]: { sessionId, launchDirectory } } +} + +export function withoutStructuredSessionLaunchDirectory( + byTabId: LaunchDirectoriesByTabId, + tabId: string, + sessionId: string +): LaunchDirectoriesByTabId { + return byTabId[tabId]?.sessionId === sessionId ? withoutTab(byTabId, tabId) : byTabId +} + export const createStructuredSessionLaunchDirectorySlice: StateCreator< AppState, [], [], StructuredSessionLaunchDirectorySlice -> = (set) => ({ - structuredSessionLaunchDirectoryByTabId: {}, - setStructuredSessionLaunchDirectory: (tabId, sessionId, launchDirectory) => { - set((state) => { - const current = state.structuredSessionLaunchDirectoryByTabId[tabId] - if (!launchDirectory) { - return current - ? { - structuredSessionLaunchDirectoryByTabId: withoutTab( - state.structuredSessionLaunchDirectoryByTabId, - tabId - ) - } - : state - } - if (current?.sessionId === sessionId && current.launchDirectory === launchDirectory) { - return state - } - return { - structuredSessionLaunchDirectoryByTabId: { - ...state.structuredSessionLaunchDirectoryByTabId, - [tabId]: { sessionId, launchDirectory } - } - } - }) - }, - clearStructuredSessionLaunchDirectory: (tabId, sessionId) => { - set((state) => - state.structuredSessionLaunchDirectoryByTabId[tabId]?.sessionId === sessionId - ? { - structuredSessionLaunchDirectoryByTabId: withoutTab( - state.structuredSessionLaunchDirectoryByTabId, - tabId - ) - } - : state - ) - } +> = () => ({ + structuredSessionLaunchDirectoryByTabId: {} }) diff --git a/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts b/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts index ebe5d899ec9..65c73269684 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts @@ -11,6 +11,7 @@ import { normalizeUrl } from './browser-page-records' import { normalizeBrowserHistoryUrl } from '../../../../../../shared/workspace-session/workspace-session-browser-history' +import { replaceTabBuckets } from '../../../keyed-record-transitions' export function createBrowserPageStateActions( set: BrowserSliceSet, @@ -85,12 +86,14 @@ export function createBrowserPageStateActions( } } if (unifiedLabelNeedsRepair) { - nextState.unifiedTabsByWorktree = { - ...s.unifiedTabsByWorktree, - [workspace.worktreeId]: unifiedTabs.map((entry, index) => - index === unifiedIndex ? { ...entry, label: nextPage.title } : entry - ) - } + nextState.unifiedTabsByWorktree = replaceTabBuckets(s.unifiedTabsByWorktree, [ + [ + workspace.worktreeId, + unifiedTabs.map((entry, index) => + index === unifiedIndex ? { ...entry, label: nextPage.title } : entry + ) + ] + ]) } return nextState } @@ -127,12 +130,14 @@ export function createBrowserPageStateActions( unifiedIndex !== -1 ) { if (unifiedLabelNeedsRepair || unifiedTabs[unifiedIndex]?.label !== nextWorkspace.title) { - nextState.unifiedTabsByWorktree = { - ...s.unifiedTabsByWorktree, - [workspace.worktreeId]: unifiedTabs.map((entry, index) => - index === unifiedIndex ? { ...entry, label: nextWorkspace.title } : entry - ) - } + nextState.unifiedTabsByWorktree = replaceTabBuckets(s.unifiedTabsByWorktree, [ + [ + workspace.worktreeId, + unifiedTabs.map((entry, index) => + index === unifiedIndex ? { ...entry, label: nextWorkspace.title } : entry + ) + ] + ]) } } return nextState diff --git a/src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts b/src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts index 314e02a53f2..c256414a670 100644 --- a/src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts +++ b/src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts @@ -5,6 +5,7 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constant import type { OpenFile } from '../types/open-file' import { isEditorTabContentType } from '../tabs/editor-tab-content-type' import { buildOwnedEditorFileId, runtimeOwnerKey } from './editor-file-ids' +import { recordDraft, tabBucketDraft } from '../../../keyed-record-transitions' export function shouldHydrateWithOwnedEditorFileId( worktreeId: string, @@ -129,9 +130,7 @@ export function migrateHydratedEditorTabsAndGroups( state: Pick, migrationsByWorktree: Record> ): Partial> { - let tabsChanged = false - let groupsChanged = false - const nextUnifiedTabsByWorktree: Record = { ...state.unifiedTabsByWorktree } + const tabsDraft = tabBucketDraft(state.unifiedTabsByWorktree) const tabIdMigrationsByWorktree: Record> = {} for (const [worktreeId, idMigrations] of Object.entries(migrationsByWorktree)) { @@ -140,6 +139,7 @@ export function migrateHydratedEditorTabsAndGroups( continue } const tabIdMigrations = new Map() + let bucketChanged = false const nextTabs = tabs.map((tab) => { // Live-move rekey covers all editor-family tabs, including diff/conflict/check-details. if (!isEditorTabContentType(tab.contentType)) { @@ -150,7 +150,7 @@ export function migrateHydratedEditorTabsAndGroups( if (nextId === tab.id && nextEntityId === tab.entityId) { return tab } - tabsChanged = true + bucketChanged = true if (nextId !== tab.id) { tabIdMigrations.set(tab.id, nextId) } @@ -159,17 +159,20 @@ export function migrateHydratedEditorTabsAndGroups( if (tabIdMigrations.size > 0) { tabIdMigrationsByWorktree[worktreeId] = tabIdMigrations } - nextUnifiedTabsByWorktree[worktreeId] = nextTabs + if (bucketChanged) { + tabsDraft.set(worktreeId, nextTabs) + } } - const nextGroupsByWorktree: Record = { ...state.groupsByWorktree } + const groupsDraft = recordDraft(state.groupsByWorktree) for (const [worktreeId, tabIdMigrations] of Object.entries(tabIdMigrationsByWorktree)) { const groups = state.groupsByWorktree[worktreeId] if (!groups) { continue } - const validTabIds = new Set((nextUnifiedTabsByWorktree[worktreeId] ?? []).map((tab) => tab.id)) - nextGroupsByWorktree[worktreeId] = groups.map((group) => { + const validTabIds = new Set((tabsDraft.get(worktreeId) ?? []).map((tab) => tab.id)) + let bucketChanged = false + const nextGroups = groups.map((group) => { const tabOrder = dedupeEditorTabOrder( group.tabOrder.map((tabId) => tabIdMigrations.get(tabId) ?? tabId), validTabIds @@ -191,7 +194,7 @@ export function migrateHydratedEditorTabsAndGroups( ) { return group } - groupsChanged = true + bucketChanged = true return { ...group, activeTabId: validActiveTabId, @@ -199,10 +202,15 @@ export function migrateHydratedEditorTabsAndGroups( recentTabIds } }) + if (bucketChanged) { + groupsDraft.set(worktreeId, nextGroups) + } } + const unifiedTabsByWorktree = tabsDraft.finish() + const groupsByWorktree = groupsDraft.finish() return { - ...(tabsChanged ? { unifiedTabsByWorktree: nextUnifiedTabsByWorktree } : {}), - ...(groupsChanged ? { groupsByWorktree: nextGroupsByWorktree } : {}) + ...(unifiedTabsByWorktree !== state.unifiedTabsByWorktree ? { unifiedTabsByWorktree } : {}), + ...(groupsByWorktree !== state.groupsByWorktree ? { groupsByWorktree } : {}) } } diff --git a/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-in-place.ts b/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-in-place.ts index 8369679c58c..00b69d40dbe 100644 --- a/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-in-place.ts +++ b/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-in-place.ts @@ -1,5 +1,6 @@ import type { ExecutionHostId } from '../../../../../../shared/execution-host' import type { AppState } from '../../../types' +import { replaceRecordEntries, replaceTabBuckets } from '../../../keyed-record-transitions' type InPlaceTabState = Pick< AppState, @@ -31,28 +32,32 @@ export function rekeyRestoredEditorTabsInPlace( activeGroupIdByWorktree: s.activeGroupIdByWorktree, activeTabTypeByWorktree: s.activeTabTypeByWorktree, layoutByWorktree: s.layoutByWorktree, - groupsByWorktree: { - ...s.groupsByWorktree, - [worktreeId]: (s.groupsByWorktree[worktreeId] ?? []).map((group) => ({ - ...group, - activeTabId: group.activeTabId ? tabId(group.activeTabId) : group.activeTabId, - tabOrder: group.tabOrder.map(tabId), - ...(group.recentTabIds ? { recentTabIds: group.recentTabIds.map(tabId) } : {}) - })) - }, - unifiedTabsByWorktree: { - ...s.unifiedTabsByWorktree, - [worktreeId]: (s.unifiedTabsByWorktree[worktreeId] ?? []).map((tab) => - tabIdMigrations.has(tab.id) || fileIdMigrations.has(tab.entityId) - ? { - ...tab, - id: tabId(tab.id), - entityId: fileId(tab.entityId), - ...(tab.executionHostId ? { executionHostId } : {}) - } - : tab - ) - }, + groupsByWorktree: replaceRecordEntries(s.groupsByWorktree, [ + [ + worktreeId, + (s.groupsByWorktree[worktreeId] ?? []).map((group) => ({ + ...group, + activeTabId: group.activeTabId ? tabId(group.activeTabId) : group.activeTabId, + tabOrder: group.tabOrder.map(tabId), + ...(group.recentTabIds ? { recentTabIds: group.recentTabIds.map(tabId) } : {}) + })) + ] + ]), + unifiedTabsByWorktree: replaceTabBuckets(s.unifiedTabsByWorktree, [ + [ + worktreeId, + (s.unifiedTabsByWorktree[worktreeId] ?? []).map((tab) => + tabIdMigrations.has(tab.id) || fileIdMigrations.has(tab.entityId) + ? { + ...tab, + id: tabId(tab.id), + entityId: fileId(tab.entityId), + ...(tab.executionHostId ? { executionHostId } : {}) + } + : tab + ) + ] + ]), tabBarOrderByWorktree: { ...s.tabBarOrderByWorktree, [worktreeId]: (s.tabBarOrderByWorktree[worktreeId] ?? []).map(fileId) diff --git a/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-transition.ts b/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-transition.ts index e4c2d2aec51..d9f8e05bcc8 100644 --- a/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-transition.ts +++ b/src/renderer/src/store/slices/editor/hydration/restored-editor-owner-transition.ts @@ -17,6 +17,7 @@ import type { } from '../types/restored-editor-owner' import { resolveRestoredEditorOwnerDestination } from './restored-editor-owner-destination' import { rekeyRestoredEditorTabsInPlace } from './restored-editor-owner-in-place' +import { replaceRecordEntries, replaceTabBuckets } from '../../../keyed-record-transitions' /** The group a moved restored tab joins: the workspace's active one, else its first, else a new one. */ export function restoredEditorTargetGroupId( @@ -123,13 +124,12 @@ export function buildRestoredEditorOwnerTransition( updatedTargetGroup ] - const nextUnifiedTabsByWorktree = { ...s.unifiedTabsByWorktree } - nextUnifiedTabsByWorktree[sourceWorktreeId] = ( - nextUnifiedTabsByWorktree[sourceWorktreeId] ?? [] - ).filter((tab) => !movedTabIds.has(tab.id)) - nextUnifiedTabsByWorktree[targetWorktreeId] = [ + const nextSourceTabs = (s.unifiedTabsByWorktree[sourceWorktreeId] ?? []).filter( + (tab) => !movedTabIds.has(tab.id) + ) + const nextTargetTabs = [ // Why: a leftover target tab carrying a migrated id would duplicate the id that destinationOrder keeps only once. - ...(nextUnifiedTabsByWorktree[targetWorktreeId] ?? []).filter( + ...(s.unifiedTabsByWorktree[targetWorktreeId] ?? []).filter( (tab) => !mappedMovedTabIdSet.has(tab.id) ), ...movedTabs.map((tab) => ({ @@ -142,20 +142,12 @@ export function buildRestoredEditorOwnerTransition( })) ] - const nextGroupsByWorktree = { - ...s.groupsByWorktree, - [sourceWorktreeId]: sourceGroupState.groups, - [targetWorktreeId]: nextTargetGroups - } - const nextLayoutByWorktree = { ...s.layoutByWorktree } - if (sourceGroupState.layout) { - nextLayoutByWorktree[sourceWorktreeId] = sourceGroupState.layout - } else { - delete nextLayoutByWorktree[sourceWorktreeId] - } - if (targetGroups.length === 0 || !nextLayoutByWorktree[targetWorktreeId]) { - nextLayoutByWorktree[targetWorktreeId] = { type: 'leaf', groupId: targetGroupId } - } + const sourceLayout = sourceGroupState.layout ?? null + // Built only for the cross-workspace branch, where the source write can't touch the target key. + const targetLayoutEntry: [string, AppState['layoutByWorktree'][string]][] = + targetGroups.length === 0 || !s.layoutByWorktree[targetWorktreeId] + ? [[targetWorktreeId, { type: 'leaf', groupId: targetGroupId }]] + : [] const nextActiveFileIdByWorktree = { ...s.activeFileIdByWorktree } const sourceActiveFileId = nextActiveFileIdByWorktree[sourceWorktreeId] @@ -176,18 +168,12 @@ export function buildRestoredEditorOwnerTransition( ), ...mappedMovedTabBarIds ] - const nextActiveGroupIdByWorktree = { ...s.activeGroupIdByWorktree } - if (sourceGroupState.groups.length > 0) { - const previousActiveGroupId = nextActiveGroupIdByWorktree[sourceWorktreeId] - nextActiveGroupIdByWorktree[sourceWorktreeId] = sourceGroupState.groups.some( - (group) => group.id === previousActiveGroupId - ) - ? previousActiveGroupId - : sourceGroupState.groups[0].id - } else { - delete nextActiveGroupIdByWorktree[sourceWorktreeId] - } - nextActiveGroupIdByWorktree[targetWorktreeId] = targetGroupId + const previousActiveGroupId = s.activeGroupIdByWorktree[sourceWorktreeId] + const sourceActiveGroupId = + sourceGroupState.groups.length === 0 + ? null + : (sourceGroupState.groups.find((group) => group.id === previousActiveGroupId)?.id ?? + sourceGroupState.groups[0].id) const tabState = sourceWorktreeId === targetWorktreeId ? rekeyRestoredEditorTabsInPlace( @@ -199,15 +185,27 @@ export function buildRestoredEditorOwnerTransition( ) : { activeFileIdByWorktree: nextActiveFileIdByWorktree, - activeGroupIdByWorktree: nextActiveGroupIdByWorktree, + activeGroupIdByWorktree: replaceRecordEntries(s.activeGroupIdByWorktree, [ + [sourceWorktreeId, sourceActiveGroupId], + [targetWorktreeId, targetGroupId] + ]), activeTabTypeByWorktree: { ...s.activeTabTypeByWorktree, [targetWorktreeId]: 'editor' as const }, - groupsByWorktree: nextGroupsByWorktree, - layoutByWorktree: nextLayoutByWorktree, + groupsByWorktree: replaceRecordEntries(s.groupsByWorktree, [ + [sourceWorktreeId, sourceGroupState.groups], + [targetWorktreeId, nextTargetGroups] + ]), + layoutByWorktree: replaceRecordEntries(s.layoutByWorktree, [ + [sourceWorktreeId, sourceLayout], + ...targetLayoutEntry + ]), tabBarOrderByWorktree: nextTabBarOrderByWorktree, - unifiedTabsByWorktree: nextUnifiedTabsByWorktree + unifiedTabsByWorktree: replaceTabBuckets(s.unifiedTabsByWorktree, [ + [sourceWorktreeId, nextSourceTabs], + [targetWorktreeId, nextTargetTabs] + ]) } assignResult({ ok: true, fileId: newFileId }) diff --git a/src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts b/src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts index 4d514cd72ec..a2773de60f7 100644 --- a/src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts +++ b/src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts @@ -19,6 +19,7 @@ import { endsPreviewHere, promotePreviewTabsThroughLayoutOwner } from '../../tabs/preview-tab-promotion' +import { replaceTabBuckets } from '../../../keyed-record-transitions' type FileReadAuthority = Pick< OpenFile, @@ -205,9 +206,10 @@ export function createMarkdownPreviewActions( changed = true return { ...file, isPreview: undefined } }) - const unifiedTabsByWorktree: typeof s.unifiedTabsByWorktree = {} + const replacements: [string, Tab[]][] = [] for (const [worktreeId, tabs] of Object.entries(s.unifiedTabsByWorktree ?? {})) { - unifiedTabsByWorktree[worktreeId] = tabs.map((tab) => { + let bucketChanged = false + const nextTabs = tabs.map((tab) => { if (tab.entityId !== fileId || (tabId && tab.id !== tabId) || !tab.isPreview) { return tab } @@ -215,10 +217,18 @@ export function createMarkdownPreviewActions( if (!endsPreviewHere(s, worktreeId)) { return tab } - changed = true + bucketChanged = true return withPreviewEnded(tab) }) + if (bucketChanged) { + changed = true + replacements.push([worktreeId, nextTabs]) + } } + const unifiedTabsByWorktree = + replacements.length > 0 + ? replaceTabBuckets(s.unifiedTabsByWorktree ?? {}, replacements) + : s.unifiedTabsByWorktree return changed ? { openFiles, unifiedTabsByWorktree } : s }) // Switch point: main makes the preview tabs the user kept permanent. diff --git a/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts b/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts index 121dec6501d..7313aa6fab3 100644 --- a/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts +++ b/src/renderer/src/store/slices/editor/opening/open-file-mutations.ts @@ -18,6 +18,8 @@ import { getDiskBaselineSignature } from '../../../../../../shared/file-write/di import { captureEditorFileOperationProvenance } from '@/lib/editor/file-operations/editor-file-operation-provenance' import { isSameEditorFileOperationIdentity } from '@/lib/editor/file-operations/editor-file-operation-owner' import { editorBufferSiblingViewIds } from '../buffers/editor-buffer-views' +import { replaceTabBuckets } from '../../../keyed-record-transitions' +import type { AppState } from '../../../types' function withoutKeys(record: Record, keys: readonly string[]): Record { const next = { ...record } @@ -27,6 +29,31 @@ function withoutKeys(record: Record, keys: readonly string[]): Rec return next } +function endPreviewTabsOfFile(s: AppState, fileId: string): AppState['unifiedTabsByWorktree'] { + const replacements: [string, Tab[]][] = [] + for (const [worktreeId, tabs] of Object.entries(s.unifiedTabsByWorktree ?? {})) { + let bucketChanged = false + const nextTabs = tabs.map((tab) => { + if ( + tab.entityId !== fileId || + !isEditorTabContentType(tab.contentType) || + // Switch point: main's frame ends a preview main owns. + !endsPreviewHere(s, worktreeId) + ) { + return tab + } + bucketChanged = true + return withPreviewEnded(tab) + }) + if (bucketChanged) { + replacements.push([worktreeId, nextTabs]) + } + } + return replacements.length > 0 + ? replaceTabBuckets(s.unifiedTabsByWorktree ?? {}, replacements) + : s.unifiedTabsByWorktree +} + export function createOpenFileMutations( set: EditorSet, get: EditorGet @@ -161,19 +188,7 @@ export function createOpenFileMutations( : {}), ...(needsPreviewClear ? { - unifiedTabsByWorktree: Object.fromEntries( - Object.entries(s.unifiedTabsByWorktree ?? {}).map(([worktreeId, tabs]) => [ - worktreeId, - tabs.map((tab) => - tab.entityId === fileId && - isEditorTabContentType(tab.contentType) && - // Switch point: main's frame ends a preview main owns. - endsPreviewHere(s, worktreeId) - ? withPreviewEnded(tab) - : tab - ) - ]) - ) + unifiedTabsByWorktree: endPreviewTabsOfFile(s, fileId) } : {}) } diff --git a/src/renderer/src/store/slices/ssh/ssh-target-cleanup.ts b/src/renderer/src/store/slices/ssh/ssh-target-cleanup.ts index 49a787cb246..766b584d495 100644 --- a/src/renderer/src/store/slices/ssh/ssh-target-cleanup.ts +++ b/src/renderer/src/store/slices/ssh/ssh-target-cleanup.ts @@ -1,7 +1,8 @@ import type { AppState } from '../../types' import { parseAppSshPtyId } from '../../../../../shared/ssh-pty-id' import { resolveDirectSshTargetWorktreeIds } from '../../../lib/workspace/ownership/direct-ssh-target-scope' -import { unbindTerminalTabPtys } from '../tabs/worktree-layout-lifecycle' +import { unbindTerminalTabPtys } from '../tabs/worktree-terminal-tab-respawn' +import { recordDraft } from '../../keyed-record-transitions' import { selectDetectedWorktreesByRepo, selectWorktreesByRepo @@ -48,9 +49,14 @@ function filterRecordIfChanged( record: Record, keep: (key: string, value: T) => boolean ): Record | undefined { - const entries = Object.entries(record) - const kept = entries.filter(([key, value]) => keep(key, value)) - return kept.length === entries.length ? undefined : Object.fromEntries(kept) + const draft = recordDraft(record) + for (const [key, value] of Object.entries(record)) { + if (!keep(key, value)) { + draft.delete(key) + } + } + const next = draft.finish() + return next === record ? undefined : next } function omitKey(record: Record, key: string): Record | undefined { @@ -95,9 +101,7 @@ function clearSshTargetTabPtyState( | 'codexRestartNoticeByPtyId' > & { changed: boolean } { const unboundTabIds = new Set() - const nextLastKnownRelayPtyIdByTabId = { - ...state.lastKnownRelayPtyIdByTabId - } + const lastKnownRelayPtyIdDraft = recordDraft(state.lastKnownRelayPtyIdByTabId) const nextPendingPaneAccountRestarts = { ...state.pendingPaneAccountRestarts } @@ -118,11 +122,11 @@ function clearSshTargetTabPtyState( if (!shouldClearTab) { continue } - if (!tab.ptyId && ptyIds.length === 0 && nextLastKnownRelayPtyIdByTabId[tab.id] == null) { + if (!tab.ptyId && ptyIds.length === 0 && lastKnownRelayPtyIdDraft.get(tab.id) == null) { continue } unboundTabIds.add(tab.id) - delete nextLastKnownRelayPtyIdByTabId[tab.id] + lastKnownRelayPtyIdDraft.delete(tab.id) for (const ptyId of ptyIds) { delete nextPendingPaneAccountRestarts[ptyId] delete nextCodexRestartNoticeByPtyId[ptyId] @@ -133,7 +137,7 @@ function clearSshTargetTabPtyState( return { changed: unboundTabIds.size > 0, ...unbindTerminalTabPtys(state, unboundTabIds), - lastKnownRelayPtyIdByTabId: nextLastKnownRelayPtyIdByTabId, + lastKnownRelayPtyIdByTabId: lastKnownRelayPtyIdDraft.finish(), pendingPaneAccountRestarts: nextPendingPaneAccountRestarts, codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId } diff --git a/src/renderer/src/store/slices/tabs/collapse-emptied-kept-groups.ts b/src/renderer/src/store/slices/tabs/collapse-emptied-kept-groups.ts index 6abceb33d96..bb0d7ccf15f 100644 --- a/src/renderer/src/store/slices/tabs/collapse-emptied-kept-groups.ts +++ b/src/renderer/src/store/slices/tabs/collapse-emptied-kept-groups.ts @@ -1,50 +1,57 @@ import type { AppState } from '../../types' -import { collapseGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree' +import type { RecordDraft } from '../../keyed-record-transitions' +import { collapseWorktreeGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree' + +export type GroupLayoutDrafts = { + groups: RecordDraft + layout: RecordDraft + activeGroups: RecordDraft +} /** Collapse kept splits emptied by purge, giving their space/selection to the surviving twin’s group. */ export function collapseEmptiedKeptGroups( - s: Pick, - groupsByWorktree: AppState['groupsByWorktree'], + groupsBefore: AppState['groupsByWorktree'], + drafts: GroupLayoutDrafts, worktreeIds: ReadonlySet -): { - groups: AppState['groupsByWorktree'] - layout: AppState['layoutByWorktree'] - activeGroups: AppState['activeGroupIdByWorktree'] -} { - let groupsOut = groupsByWorktree - let layoutOut = s.layoutByWorktree - let activeOut = s.activeGroupIdByWorktree +): void { for (const worktreeId of worktreeIds) { - const before = s.groupsByWorktree[worktreeId] ?? [] - let groups = groupsOut[worktreeId] ?? [] + const before = groupsBefore[worktreeId] ?? [] + const stored = drafts.groups.get(worktreeId) + let groups = stored ?? [] const emptied = groups.filter( (group) => group.tabOrder.length === 0 && (before.find((prior) => prior.id === group.id)?.tabOrder.length ?? 0) > 0 ) for (const group of emptied) { - if (groups.length <= 1 || !layoutOut[worktreeId]) { + const layout = drafts.layout.get(worktreeId) + if (groups.length <= 1 || !layout) { break } groups = groups.filter((candidate) => candidate.id !== group.id) - const collapsed = collapseGroupLayout( - layoutOut, - activeOut, - worktreeId, + const activeGroupId = drafts.activeGroups.get(worktreeId) + const collapsed = collapseWorktreeGroupLayout( + layout, + activeGroupId, group.id, groups[0]?.id ?? null ) - layoutOut = collapsed.layoutByWorktree + if (collapsed.layout) { + drafts.layout.set(worktreeId, collapsed.layout) + } else { + drafts.layout.delete(worktreeId) + } // Why: only the collapsed group's own focus moves; an untouched active group keeps it. - const activeGroupId = activeOut[worktreeId] - activeOut = - activeGroupId === undefined || activeGroupId === group.id - ? collapsed.activeGroupIdByWorktree - : { ...collapsed.activeGroupIdByWorktree, [worktreeId]: activeGroupId } + if ( + (activeGroupId === undefined || activeGroupId === group.id) && + collapsed.activeGroupId !== undefined + ) { + drafts.activeGroups.set(worktreeId, collapsed.activeGroupId) + } } - if (groups !== (groupsOut[worktreeId] ?? [])) { - groupsOut = { ...groupsOut, [worktreeId]: groups } + // An absent entry is written even when empty, as the record spread this replaces did. + if (stored === undefined || groups !== stored) { + drafts.groups.set(worktreeId, groups) } } - return { groups: groupsOut, layout: layoutOut, activeGroups: activeOut } } diff --git a/src/renderer/src/store/slices/tabs/kept-worktree-surface-pruning.ts b/src/renderer/src/store/slices/tabs/kept-worktree-surface-pruning.ts index 8bf3d4de78b..d0358d445ea 100644 --- a/src/renderer/src/store/slices/tabs/kept-worktree-surface-pruning.ts +++ b/src/renderer/src/store/slices/tabs/kept-worktree-surface-pruning.ts @@ -1,6 +1,7 @@ import type { AppState } from '../../types' import { toVisibleTabType, type Tab, type TabGroup } from '../../../../../shared/tab-types' import { sanitizeRecentTabIds } from './tab-selection-history' +import type { RecordDraft } from '../../keyed-record-transitions' /** Surfaces leaving workspaces that stay, such as one host's tabs under an id its twin publishes. */ export type KeptWorktreeSurfaceRemoval = { @@ -69,6 +70,20 @@ function pruneEntries( return next ?? map } +/** pruneEntries as draft operations, for seam records whose entries are never undefined. */ +export function pruneKeptEntries( + draft: RecordDraft, + worktreeIds: ReadonlySet, + prune: (value: T) => T +): void { + for (const worktreeId of worktreeIds) { + const current = draft.get(worktreeId) + if (current !== undefined) { + draft.set(worktreeId, prune(current)) + } + } +} + function withoutIds(items: T[], ids: ReadonlySet): T[] { return items.some((item) => ids.has(item.id)) ? items.filter((item) => !ids.has(item.id)) : items } @@ -99,16 +114,19 @@ export function createKeptWorktreeSurfacePruners( pruneEntries(map, worktreeIds, (value) => typeof value === 'string' && ids.has(value) ? undefined : value ) + const pruneGroups = (groups: TabGroup[]): TabGroup[] => { + const next = groups.map((group) => pruneGroup(group, removedIds)) + return next.every((group, index) => group === groups[index]) ? groups : next + } return { - tabs: (map: AppState['tabsByWorktree']) => - pruneEntries(map, worktreeIds, (tabs) => withoutIds(tabs, removed.terminalTabIds)), + /** Seam records prune through draft operations; see pruneKeptEntries. */ + entries: { + tabs: (tabs: AppState['tabsByWorktree'][string]) => withoutIds(tabs, removed.terminalTabIds), + unifiedTabs: (tabs: Tab[]) => withoutIds(tabs, removedUnifiedIds), + groups: pruneGroups + }, unifiedTabs: (map: AppState['unifiedTabsByWorktree']) => pruneEntries(map, worktreeIds, (tabs) => withoutIds(tabs, removedUnifiedIds)), - groups: (map: AppState['groupsByWorktree']) => - pruneEntries(map, worktreeIds, (groups) => { - const next = groups.map((group) => pruneGroup(group, removedIds)) - return next.every((group, index) => group === groups[index]) ? groups : next - }), tabBarOrder: (map: AppState['tabBarOrderByWorktree']) => pruneEntries(map, worktreeIds, (order) => order.some((id) => removedIds.has(id)) ? order.filter((id) => !removedIds.has(id)) : order diff --git a/src/renderer/src/store/slices/tabs/rename-worktree-layout.ts b/src/renderer/src/store/slices/tabs/rename-worktree-layout.ts index 303ad84ee82..98780d7943f 100644 --- a/src/renderer/src/store/slices/tabs/rename-worktree-layout.ts +++ b/src/renderer/src/store/slices/tabs/rename-worktree-layout.ts @@ -1,6 +1,7 @@ import type { AppState } from '../../types' import type { BrowserWorkspace } from '../../../../../shared/browser-workspace-types' import type { WorktreeLayoutPatch } from './worktree-layout-lifecycle' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' function rekeyWorktreeEntry( map: Record | undefined, @@ -17,6 +18,21 @@ function rekeyWorktreeEntry( return next } +// Seam records rebuild through the same set-new-then-delete-old operations, so a held new key is overwritten in place. +function rekeyOperations( + map: Record | undefined, + oldWorktreeId: string, + newWorktreeId: string, + mapValue: (value: T) => T +): [string, T | null][] | undefined { + return map && oldWorktreeId in map + ? [ + [newWorktreeId, mapValue(map[oldWorktreeId])], + [oldWorktreeId, null] + ] + : undefined +} + /** Moves a renamed worktree's tabs, groups, pane layouts and selection to its new id. */ export function renameWorktreeLayoutKeys( s: AppState, @@ -28,6 +44,18 @@ export function renameWorktreeLayoutKeys( value.worktreeId === oldWorktreeId ? { ...value, worktreeId: newWorktreeId } : value const rekey = (map: Record | undefined, mapValue?: (value: T) => T) => rekeyWorktreeEntry(map, oldWorktreeId, newWorktreeId, mapValue) + const rekeyRecord = (map: Record, mapValue: (value: T) => T = (value) => value) => { + const operations = rekeyOperations(map, oldWorktreeId, newWorktreeId, mapValue) + return operations && replaceRecordEntries(map, operations) + } + const rekeyTabBuckets = ( + map: Record + ) => { + const operations = rekeyOperations(map, oldWorktreeId, newWorktreeId, (tabs) => + tabs.map(withNewWorktreeId) + ) + return operations && replaceTabBuckets(map, operations) + } const patch: Partial = {} const assign = ( key: K, @@ -37,10 +65,7 @@ export function renameWorktreeLayoutKeys( patch[key] = value } } - assign( - 'tabsByWorktree', - rekey(s.tabsByWorktree, (tabs) => tabs.map(withNewWorktreeId)) - ) + assign('tabsByWorktree', rekeyTabBuckets(s.tabsByWorktree)) assign( 'browserTabsByWorktree', rekey(s.browserTabsByWorktree, (workspaces) => workspaces.map(renameBrowserWorkspace)) @@ -50,16 +75,13 @@ export function renameWorktreeLayoutKeys( assign('activeTabTypeByWorktree', rekey(s.activeTabTypeByWorktree)) assign('activeTabIdByWorktree', rekey(s.activeTabIdByWorktree)) assign('tabBarOrderByWorktree', rekey(s.tabBarOrderByWorktree)) - assign( - 'unifiedTabsByWorktree', - rekey(s.unifiedTabsByWorktree, (tabs) => tabs.map(withNewWorktreeId)) - ) + assign('unifiedTabsByWorktree', rekeyTabBuckets(s.unifiedTabsByWorktree)) assign( 'groupsByWorktree', - rekey(s.groupsByWorktree, (groups) => groups.map(withNewWorktreeId)) + rekeyRecord(s.groupsByWorktree, (groups) => groups.map(withNewWorktreeId)) ) - assign('layoutByWorktree', rekey(s.layoutByWorktree)) - assign('activeGroupIdByWorktree', rekey(s.activeGroupIdByWorktree)) + assign('layoutByWorktree', rekeyRecord(s.layoutByWorktree)) + assign('activeGroupIdByWorktree', rekeyRecord(s.activeGroupIdByWorktree)) if (s.openFiles?.some((f) => f.worktreeId === oldWorktreeId)) { assign('openFiles', s.openFiles.map(withNewWorktreeId)) } diff --git a/src/renderer/src/store/slices/tabs/tab-group-state.ts b/src/renderer/src/store/slices/tabs/tab-group-state.ts index c1fd8b70dbc..87f85c0dd41 100644 --- a/src/renderer/src/store/slices/tabs/tab-group-state.ts +++ b/src/renderer/src/store/slices/tabs/tab-group-state.ts @@ -2,6 +2,7 @@ import type { Tab, TabGroup } from '../../../../../shared/tab-types' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../shared/non-secure-context-uuid' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' import { workspaceRootGroupId } from '../../../../../shared/workspace-layout/workspace-layout-minted-ids' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' export function findTabAndWorktree( tabsByWorktree: Record, @@ -66,20 +67,34 @@ export function ensureGroup( groupsByWorktree: Record activeGroupIdByWorktree: Record } { - const existing = - groupsByWorktree[worktreeId]?.find((group) => group.id === preferredGroupId) ?? - groupsByWorktree[worktreeId]?.[0] + const { group, created } = ensureWorktreeGroup( + groupsByWorktree[worktreeId], + worktreeId, + preferredGroupId + ) + if (!created) { + return { group, groupsByWorktree, activeGroupIdByWorktree } + } + return { + group, + groupsByWorktree: replaceRecordEntries(groupsByWorktree, [[worktreeId, [group]]]), + activeGroupIdByWorktree: replaceRecordEntries(activeGroupIdByWorktree, [[worktreeId, group.id]]) + } +} + +/** ensureGroup for one worktree's groups; a created group becomes the worktree's only and active group. */ +export function ensureWorktreeGroup( + groups: TabGroup[] | undefined, + worktreeId: string, + preferredGroupId?: string +): { group: TabGroup; created: boolean } { + const existing = groups?.find((group) => group.id === preferredGroupId) ?? groups?.[0] if (existing) { - return { group: existing, groupsByWorktree, activeGroupIdByWorktree } + return { group: existing, created: false } } // Switch point: the root group id main and the Loader mint for a workspace with no group. const groupId = ORCA_LAYOUT_OWNER_IS_MAIN ? workspaceRootGroupId(worktreeId) : createBrowserUuid() - const group: TabGroup = { id: groupId, worktreeId, activeTabId: null, tabOrder: [] } - return { - group, - groupsByWorktree: { ...groupsByWorktree, [worktreeId]: [group] }, - activeGroupIdByWorktree: { ...activeGroupIdByWorktree, [worktreeId]: groupId } - } + return { group: { id: groupId, worktreeId, activeTabId: null, tabOrder: [] }, created: true } } export function updateGroup(groups: TabGroup[], updated: TabGroup): TabGroup[] { @@ -105,9 +120,8 @@ export function patchTab( const { worktreeId } = found const tabs = tabsByWorktree[worktreeId] ?? [] return { - unifiedTabsByWorktree: { - ...tabsByWorktree, - [worktreeId]: tabs.map((t) => (t.id === tabId ? { ...t, ...patch } : t)) - } + unifiedTabsByWorktree: replaceTabBuckets(tabsByWorktree, [ + [worktreeId, tabs.map((t) => (t.id === tabId ? { ...t, ...patch } : t))] + ]) } } diff --git a/src/renderer/src/store/slices/tabs/tabs-close-actions.ts b/src/renderer/src/store/slices/tabs/tabs-close-actions.ts index d05c98f22fa..8fe6a3e0b4b 100644 --- a/src/renderer/src/store/slices/tabs/tabs-close-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-close-actions.ts @@ -8,7 +8,7 @@ export { landOnEmptiedWorktree } from './tabs-empty-workspace' import { retireRemovedNativeChatDraftPositions } from '@/components/native-chat/drafts/native-chat-draft-position-retirement' import { retireStructuredAgentSessionReadOwner } from '@/components/native-chat/session/structured/read/structured-agent-session-read-owner-registry' import type { TabsSlice, TabsSliceGet, TabsSliceSet } from './tabs-slice-contract' -import { collapseGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree' +import { collapseWorktreeGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree' import { findGroupForTab, findTabAndWorktree } from './tab-group-state' import { pickNextActiveTab, sanitizeRecentTabIds } from './tab-selection-history' import { dedupeTabOrder } from '../../../../../shared/workspace-layout/tab-order' @@ -34,6 +34,7 @@ import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-ag import { isTuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent-config' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { forgetDesktopCreatedServerTab } from '@/lib/desktop-created-server-tabs' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' export function createTabsCloseActions( set: TabsSliceSet, @@ -150,33 +151,35 @@ export function createTabsCloseActions( ) let nextLayoutByWorktree = current.layoutByWorktree let nextActiveGroupIdByWorktree = current.activeGroupIdByWorktree - if ( - group && - wasLastTab && - current.layoutByWorktree[worktreeId] && - nextGroups.length > 1 - ) { + const currentLayout = current.layoutByWorktree[worktreeId] + if (group && wasLastTab && currentLayout && nextGroups.length > 1) { nextGroups = nextGroups.filter((candidate) => candidate.id !== group.id) - const collapsedState = collapseGroupLayout( - current.layoutByWorktree, - current.activeGroupIdByWorktree, - worktreeId, + const collapsed = collapseWorktreeGroupLayout( + currentLayout, + current.activeGroupIdByWorktree[worktreeId], group.id, nextGroups[0]?.id ?? null ) - nextLayoutByWorktree = collapsedState.layoutByWorktree - nextActiveGroupIdByWorktree = collapsedState.activeGroupIdByWorktree + nextLayoutByWorktree = replaceRecordEntries(current.layoutByWorktree, [ + [worktreeId, collapsed.layout] + ]) + nextActiveGroupIdByWorktree = replaceRecordEntries(current.activeGroupIdByWorktree, [ + [worktreeId, collapsed.activeGroupId] + ]) } + const nextUnifiedTabsByWorktree = replaceTabBuckets(current.unifiedTabsByWorktree, [ + [worktreeId, nextTabs] + ]) + const nextGroupsByWorktree = replaceRecordEntries(current.groupsByWorktree, [ + [worktreeId, nextGroups] + ]) // Unwinding a failed create added no tab; preserve the original selection instead of landing on welcome. const shouldDeactivateWorktree = !opts?.preserveWorktreeSelection && landsOnEmptiedWorktree(current, worktreeId, nextTabs.length) return { - unifiedTabsByWorktree: { ...current.unifiedTabsByWorktree, [worktreeId]: nextTabs }, - groupsByWorktree: { - ...current.groupsByWorktree, - [worktreeId]: nextGroups - }, + unifiedTabsByWorktree: nextUnifiedTabsByWorktree, + groupsByWorktree: nextGroupsByWorktree, layoutByWorktree: nextLayoutByWorktree, activeGroupIdByWorktree: nextActiveGroupIdByWorktree, // Avoid no-op unread allocations that wake full-state selectors. @@ -190,14 +193,8 @@ export function createTabsCloseActions( ? buildActiveSurfacePatch( { ...current, - unifiedTabsByWorktree: { - ...current.unifiedTabsByWorktree, - [worktreeId]: nextTabs - }, - groupsByWorktree: { - ...current.groupsByWorktree, - [worktreeId]: nextGroups - }, + unifiedTabsByWorktree: nextUnifiedTabsByWorktree, + groupsByWorktree: nextGroupsByWorktree, layoutByWorktree: nextLayoutByWorktree, activeGroupIdByWorktree: nextActiveGroupIdByWorktree }, diff --git a/src/renderer/src/store/slices/tabs/tabs-create-actions.ts b/src/renderer/src/store/slices/tabs/tabs-create-actions.ts index dd34a7a72c6..f1f180a5aa1 100644 --- a/src/renderer/src/store/slices/tabs/tabs-create-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-create-actions.ts @@ -6,7 +6,7 @@ import { getActiveExecutionHostIdForWorktree } from '@/lib/workspace/ownership/u import type { Tab, TabGroup } from '../../../../../shared/tab-types' import type { TabsSlice, TabsSliceGet, TabsSliceSet } from './tabs-slice-contract' import { buildActiveSurfacePatch } from './tabs-surface' -import { ensureGroup, findGroupForTab, updateGroup } from './tab-group-state' +import { ensureWorktreeGroup, findGroupForTab, updateGroup } from './tab-group-state' import { pushRecentTabId, sanitizeRecentTabIds } from './tab-selection-history' import { applyTabOrderSortValues, @@ -15,10 +15,11 @@ import { insertTabIdIntoOrder } from '../../../../../shared/workspace-layout/tab-order' import { resolveUnifiedTabCreatePlacement } from './tabs-create-placement' -import { emptySplitGroup, insertSplitGroup } from './tabs-group-actions' +import { emptySplitGroup, insertSplitGroup, splitGroupEntries } from './tabs-group-actions' import { folderWorkspaceToWorktree } from '../../../../../shared/folder-workspaces/folder-workspace-worktree' import { createdTabPreviewFlag } from './tab-preview-flag' import { selectFolderWorkspaces } from '../../workspaces/catalog/workspace-record-fields' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' export function createTabsCreateActions( set: TabsSliceSet, @@ -32,38 +33,39 @@ export function createTabsCreateActions( let created!: Tab set((current) => { init?.validatePlacement?.(current) - const state = + // Every write below lands on this worktree's entries, so each record is built once at the end. + const split = init?.split && splitGroupId - ? { - ...current, - ...insertSplitGroup( - current, - worktreeId, - init.split, - emptySplitGroup(worktreeId, splitGroupId) - ) - } - : current - const existingTabs = state.unifiedTabsByWorktree[worktreeId] ?? [] + ? splitGroupEntries( + current, + worktreeId, + init.split, + emptySplitGroup(worktreeId, splitGroupId) + ) + : null + const worktreeGroups = split ? split.groups : current.groupsByWorktree[worktreeId] + const worktreeActiveGroupId = + split?.activeGroupId ?? current.activeGroupIdByWorktree[worktreeId] + const existingTabs = current.unifiedTabsByWorktree[worktreeId] ?? [] const placement = resolveUnifiedTabCreatePlacement({ - groups: state.groupsByWorktree[worktreeId] ?? [], + groups: worktreeGroups ?? [], tabs: existingTabs, - activeGroupId: state.activeGroupIdByWorktree[worktreeId], + activeGroupId: worktreeActiveGroupId, targetGroupId: splitGroupId ?? init?.targetGroupId, afterTabId: init?.afterTabId, executionHostId: init?.executionHostId, lookupWorktrees: () => [ - ...(state.allWorktrees?.() ?? []), - ...(selectFolderWorkspaces(state) ?? []).map(folderWorkspaceToWorktree) + ...(current.allWorktrees?.() ?? []), + ...(selectFolderWorkspaces(current) ?? []).map(folderWorkspaceToWorktree) ].filter((worktree) => worktree.id === worktreeId) }) - const { group, groupsByWorktree, activeGroupIdByWorktree } = ensureGroup( - state.groupsByWorktree, - state.activeGroupIdByWorktree, + const { group, created: groupCreated } = ensureWorktreeGroup( + worktreeGroups, worktreeId, placement.groupId ) + const nextActiveGroupId = groupCreated ? group.id : split?.activeGroupId let nextTabs = existingTabs let nextOrder = dedupeTabOrder(group.tabOrder) @@ -87,7 +89,7 @@ export function createTabsCreateActions( const recordsFocus = shouldActivate && init?.recordFocus !== false const createdAt = Date.now() const executionHostId = - init?.executionHostId ?? getActiveExecutionHostIdForWorktree(state, worktreeId) + init?.executionHostId ?? getActiveExecutionHostIdForWorktree(current, worktreeId) // Why: preview replacement may have removed the anchor; the order then appends in-partition. nextOrder = contentType === 'agent-session' && @@ -136,25 +138,36 @@ export function createTabsCreateActions( const nextRecent = shouldActivate ? pushRecentTabId(sanitizedRecent, created.id) : sanitizedRecent + // The split insert and ensureGroup touch only this workspace. return { - unifiedTabsByWorktree: { - ...state.unifiedTabsByWorktree, - [worktreeId]: [...nextTabs, created] - }, - groupsByWorktree: { - ...groupsByWorktree, - [worktreeId]: updateGroup(groupsByWorktree[worktreeId] ?? [], { - ...group, - activeTabId: nextActiveTabId, - tabOrder: nextOrder, - recentTabIds: nextRecent - }) - }, - activeGroupIdByWorktree, - layoutByWorktree: { - ...state.layoutByWorktree, - [worktreeId]: state.layoutByWorktree[worktreeId] ?? { type: 'leaf', groupId: group.id } - } + unifiedTabsByWorktree: replaceTabBuckets(current.unifiedTabsByWorktree, [ + [worktreeId, [...nextTabs, created]] + ]), + groupsByWorktree: replaceRecordEntries(current.groupsByWorktree, [ + [ + worktreeId, + updateGroup(groupCreated ? [group] : (worktreeGroups ?? []), { + ...group, + activeTabId: nextActiveTabId, + tabOrder: nextOrder, + recentTabIds: nextRecent + }) + ] + ]), + activeGroupIdByWorktree: nextActiveGroupId + ? replaceRecordEntries(current.activeGroupIdByWorktree, [ + [worktreeId, nextActiveGroupId] + ]) + : current.activeGroupIdByWorktree, + layoutByWorktree: replaceRecordEntries(current.layoutByWorktree, [ + [ + worktreeId, + (split ? split.layout : current.layoutByWorktree[worktreeId]) ?? { + type: 'leaf', + groupId: group.id + } + ] + ]) } }) if (replacedEditorId) { @@ -220,10 +233,9 @@ export function createTabsCreateActions( recentTabIds: shouldActivate ? [id] : [] } created = createdTab - const nextUnifiedTabsByWorktree = { - ...state.unifiedTabsByWorktree, - [worktreeId]: [...existingTabs, createdTab] - } + const nextUnifiedTabsByWorktree = replaceTabBuckets(state.unifiedTabsByWorktree, [ + [worktreeId, [...existingTabs, createdTab]] + ]) const { groupsByWorktree: nextGroupsByWorktree, layoutByWorktree: nextLayoutByWorktree, diff --git a/src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts b/src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts index 7fe1f379887..891147f496d 100644 --- a/src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts @@ -1,5 +1,6 @@ import type { AppState } from '../../types' import type { TabsSlice, TabsSliceSet } from './tabs-slice-contract' +import { replaceRecordEntries } from '../../keyed-record-transitions' function previewActiveSurfacePatch( state: AppState, @@ -113,18 +114,19 @@ export function createTabsDragPreviewActions( const next: Partial = { ...surfacePatch } if (!groupUnchanged) { - next.groupsByWorktree = { - ...state.groupsByWorktree, - [worktreeId]: groups.map((group) => - group.id === groupId ? { ...group, activeTabId: tabId } : group - ) - } + next.groupsByWorktree = replaceRecordEntries(state.groupsByWorktree, [ + [ + worktreeId, + groups.map((group) => + group.id === groupId ? { ...group, activeTabId: tabId } : group + ) + ] + ]) } if (!focusUnchanged) { - next.activeGroupIdByWorktree = { - ...state.activeGroupIdByWorktree, - [worktreeId]: activeGroupId - } + next.activeGroupIdByWorktree = replaceRecordEntries(state.activeGroupIdByWorktree, [ + [worktreeId, activeGroupId] + ]) } return next }) @@ -141,25 +143,21 @@ export function createTabsDragPreviewActions( const next: Partial = {} if (!groupsUnchanged) { - next.groupsByWorktree = { - ...state.groupsByWorktree, - [worktreeId]: groups.map((group) => ({ - ...group, - activeTabId: snapshot.activeTabIdByGroup[group.id] ?? null - })) - } + next.groupsByWorktree = replaceRecordEntries(state.groupsByWorktree, [ + [ + worktreeId, + groups.map((group) => ({ + ...group, + activeTabId: snapshot.activeTabIdByGroup[group.id] ?? null + })) + ] + ]) } if (!focusUnchanged) { - if (snapshot.activeGroupId === null) { - const nextActiveGroupIdByWorktree = { ...state.activeGroupIdByWorktree } - delete nextActiveGroupIdByWorktree[worktreeId] - next.activeGroupIdByWorktree = nextActiveGroupIdByWorktree - } else { - next.activeGroupIdByWorktree = { - ...state.activeGroupIdByWorktree, - [worktreeId]: snapshot.activeGroupId - } - } + // A null snapshot group deletes the entry. + next.activeGroupIdByWorktree = replaceRecordEntries(state.activeGroupIdByWorktree, [ + [worktreeId, snapshot.activeGroupId] + ]) } const restoredGroupId = snapshot.activeGroupId @@ -194,12 +192,14 @@ export function createTabsDragPreviewActions( return state } return { - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: groups.map((group) => - group.id === sourceGroupId ? { ...group, activeTabId: preDragActiveTabId } : group - ) - } + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [ + [ + worktreeId, + groups.map((group) => + group.id === sourceGroupId ? { ...group, activeTabId: preDragActiveTabId } : group + ) + ] + ]) } }) } diff --git a/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts b/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts index 7c05d447873..365ea2723d4 100644 --- a/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts @@ -1,9 +1,9 @@ import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../shared/non-secure-context-uuid' -import type { TabGroup } from '../../../../../shared/tab-types' +import type { TabGroup, TabGroupLayoutNode } from '../../../../../shared/tab-types' import type { TabsSlice, TabsSliceGet, TabsSliceSet } from './tabs-slice-contract' import { isPaneColumnSplitDropNoOp } from '../../../../../shared/workspace-layout/pane-column-split-drop-no-op' import { - collapseGroupLayout, + collapseWorktreeGroupLayout, buildSplitNode, replaceLeaf } from '../../../../../shared/workspace-layout/tab-group-layout-tree' @@ -11,6 +11,7 @@ import { buildActiveSurfacePatch } from './tabs-surface' import { findGroupAndWorktree, findGroupForTab, findTabAndWorktree } from './tab-group-state' import { pickNextActiveTab, pushRecentTabId, sanitizeRecentTabIds } from './tab-selection-history' import { dedupeTabOrder } from '../../../../../shared/workspace-layout/tab-order' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' export function createTabsDropActions( set: TabsSliceSet, @@ -55,8 +56,9 @@ export function createTabsDropActions( moved = true let nextGroups = state.groupsByWorktree[worktreeId] ?? [] - let nextLayoutByWorktree = state.layoutByWorktree - let nextActiveGroupIdByWorktree = state.activeGroupIdByWorktree + // Pending writes to this worktree's layout and active-group entries; null deletes the layout. + let nextLayout: TabGroupLayoutNode | null | undefined + let nextActiveGroupId: string | undefined let resolvedTargetGroupId = target.groupId if (target.splitDirection) { @@ -68,7 +70,8 @@ export function createTabsDropActions( tabOrder: [] } const currentLayout = - nextLayoutByWorktree[worktreeId] ?? ({ type: 'leaf', groupId: target.groupId } as const) + state.layoutByWorktree[worktreeId] ?? + ({ type: 'leaf', groupId: target.groupId } as const) const replacement = buildSplitNode( target.groupId, newGroupId, @@ -80,14 +83,8 @@ export function createTabsDropActions( resolvedTargetGroupId = newGroupId nextGroups = [...nextGroups, newGroup] - nextLayoutByWorktree = { - ...nextLayoutByWorktree, - [worktreeId]: replaceLeaf(currentLayout, target.groupId, replacement) - } - nextActiveGroupIdByWorktree = { - ...nextActiveGroupIdByWorktree, - [worktreeId]: newGroupId - } + nextLayout = replaceLeaf(currentLayout, target.groupId, replacement) + nextActiveGroupId = newGroupId } const dedupedSourceGroupOrder = dedupeTabOrder(sourceGroup.tabOrder) @@ -140,32 +137,41 @@ export function createTabsDropActions( if (sourceOrder.length === 0) { nextGroups = nextGroups.filter((group) => group.id !== sourceGroup.id) - const collapsedState = collapseGroupLayout( - nextLayoutByWorktree, - nextActiveGroupIdByWorktree, - worktreeId, - sourceGroup.id, - resolvedTargetGroupId - ) - nextLayoutByWorktree = collapsedState.layoutByWorktree - nextActiveGroupIdByWorktree = collapsedState.activeGroupIdByWorktree - } else { - nextActiveGroupIdByWorktree = { - ...nextActiveGroupIdByWorktree, - [worktreeId]: resolvedTargetGroupId + const currentLayout = + nextLayout === undefined ? state.layoutByWorktree[worktreeId] : nextLayout + if (currentLayout) { + const collapsed = collapseWorktreeGroupLayout( + currentLayout, + nextActiveGroupId ?? state.activeGroupIdByWorktree[worktreeId], + sourceGroup.id, + resolvedTargetGroupId + ) + nextLayout = collapsed.layout + nextActiveGroupId = collapsed.activeGroupId } + } else { + nextActiveGroupId = resolvedTargetGroupId } - const nextUnifiedTabsByWorktree = { - ...state.unifiedTabsByWorktree, - [worktreeId]: (state.unifiedTabsByWorktree[worktreeId] ?? []).map((candidate) => - candidate.id === tabId ? { ...candidate, groupId: resolvedTargetGroupId } : candidate - ) - } - const nextGroupsByWorktree = { - ...state.groupsByWorktree, - [worktreeId]: nextGroups - } + const nextLayoutByWorktree = + nextLayout === undefined + ? state.layoutByWorktree + : replaceRecordEntries(state.layoutByWorktree, [[worktreeId, nextLayout]]) + const nextActiveGroupIdByWorktree = + nextActiveGroupId === undefined + ? state.activeGroupIdByWorktree + : replaceRecordEntries(state.activeGroupIdByWorktree, [[worktreeId, nextActiveGroupId]]) + const nextUnifiedTabsByWorktree = replaceTabBuckets(state.unifiedTabsByWorktree, [ + [ + worktreeId, + (state.unifiedTabsByWorktree[worktreeId] ?? []).map((candidate) => + candidate.id === tabId ? { ...candidate, groupId: resolvedTargetGroupId } : candidate + ) + ] + ]) + const nextGroupsByWorktree = replaceRecordEntries(state.groupsByWorktree, [ + [worktreeId, nextGroups] + ]) return { unifiedTabsByWorktree: nextUnifiedTabsByWorktree, diff --git a/src/renderer/src/store/slices/tabs/tabs-focus-actions.ts b/src/renderer/src/store/slices/tabs/tabs-focus-actions.ts index dc049271874..82f0b47d35b 100644 --- a/src/renderer/src/store/slices/tabs/tabs-focus-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-focus-actions.ts @@ -7,6 +7,7 @@ import type { AppState } from '../../types' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' import { withPreviewEnded } from './tab-preview-flag' import { endsPreviewHere, promotePreviewTabsThroughLayoutOwner } from './preview-tab-promotion' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' /** Activation ends a preview unless it preserves it; main's frame ends one main owns. */ function withPreviewOnActivation(tab: Tab, preservePreview: boolean, endsHere: boolean): Tab { @@ -32,37 +33,40 @@ export function tabActivationPatch( ): ActivationState { const tabId = tab.id return { - unifiedTabsByWorktree: { - ...state.unifiedTabsByWorktree, - [worktreeId]: (state.unifiedTabsByWorktree[worktreeId] ?? []).map((item) => - item.id === tabId - ? { - ...withPreviewOnActivation(item, opts?.preservePreview === true, endsPreview), - ...(opts?.recordFocus === false ? {} : { lastFocusedAt: Date.now() }) - } - : item - ) - }, - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: (state.groupsByWorktree[worktreeId] ?? []).map((group) => - group.id === tab.groupId - ? { - ...group, - activeTabId: tabId, - // Track MRU for close-time selection, pruning removed IDs. - recentTabIds: pushRecentTabId( - sanitizeRecentTabIds(group.recentTabIds, group.tabOrder), - tabId - ) - } - : group - ) - }, - activeGroupIdByWorktree: { - ...state.activeGroupIdByWorktree, - [worktreeId]: tab.groupId - } + unifiedTabsByWorktree: replaceTabBuckets(state.unifiedTabsByWorktree, [ + [ + worktreeId, + (state.unifiedTabsByWorktree[worktreeId] ?? []).map((item) => + item.id === tabId + ? { + ...withPreviewOnActivation(item, opts?.preservePreview === true, endsPreview), + ...(opts?.recordFocus === false ? {} : { lastFocusedAt: Date.now() }) + } + : item + ) + ] + ]), + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [ + [ + worktreeId, + (state.groupsByWorktree[worktreeId] ?? []).map((group) => + group.id === tab.groupId + ? { + ...group, + activeTabId: tabId, + // Track MRU for close-time selection, pruning removed IDs. + recentTabIds: pushRecentTabId( + sanitizeRecentTabIds(group.recentTabIds, group.tabOrder), + tabId + ) + } + : group + ) + ] + ]), + activeGroupIdByWorktree: replaceRecordEntries(state.activeGroupIdByWorktree, [ + [worktreeId, tab.groupId] + ]) } } diff --git a/src/renderer/src/store/slices/tabs/tabs-group-actions.ts b/src/renderer/src/store/slices/tabs/tabs-group-actions.ts index 02067c21041..d736376685a 100644 --- a/src/renderer/src/store/slices/tabs/tabs-group-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-group-actions.ts @@ -1,7 +1,7 @@ import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../shared/non-secure-context-uuid' import type { TabSplitTarget, TabsSlice, TabsSliceGet, TabsSliceSet } from './tabs-slice-contract' import { activeSurfacePatchMatchesState, buildActiveSurfacePatch } from './tabs-surface' -import type { TabGroup } from '../../../../../shared/tab-types' +import type { TabGroup, TabGroupLayoutNode } from '../../../../../shared/tab-types' import { buildSplitNode, collapseGroupLayout, @@ -11,6 +11,7 @@ import { workspaceRootGroupId } from '../../../../../shared/workspace-layout/wor import { insertTabIdIntoOrder } from '../../../../../shared/workspace-layout/tab-order' import { resolveUnifiedTabCreatePlacement } from './tabs-create-placement' import { ownsGlobalSelection } from '../../workspaces/selection/global-selection-owner' +import { replaceRecordEntries } from '../../keyed-record-transitions' type SplitGroupState = Pick< TabsSlice, @@ -24,6 +25,24 @@ export function insertSplitGroup( target: TabSplitTarget, newGroup: TabGroup ): SplitGroupState { + const split = splitGroupEntries(state, worktreeId, target, newGroup) + return { + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [[worktreeId, split.groups]]), + layoutByWorktree: replaceRecordEntries(state.layoutByWorktree, [[worktreeId, split.layout]]), + activeGroupIdByWorktree: + split.activeGroupId === null + ? state.activeGroupIdByWorktree + : replaceRecordEntries(state.activeGroupIdByWorktree, [[worktreeId, split.activeGroupId]]) + } +} + +/** insertSplitGroup's values for its one worktree; a null active group id leaves the entry unwritten. */ +export function splitGroupEntries( + state: SplitGroupState, + worktreeId: string, + target: TabSplitTarget, + newGroup: TabGroup +): { groups: TabGroup[]; layout: TabGroupLayoutNode; activeGroupId: string | null } { const { sourceGroupId, splitDirection } = target const currentLayout = state.layoutByWorktree[worktreeId] ?? ({ type: 'leaf', groupId: sourceGroupId } as const) @@ -34,18 +53,9 @@ export function insertSplitGroup( splitDirection === 'left' || splitDirection === 'up' ? 'first' : 'second' ) return { - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: [...(state.groupsByWorktree[worktreeId] ?? []), newGroup] - }, - layoutByWorktree: { - ...state.layoutByWorktree, - [worktreeId]: replaceLeaf(currentLayout, sourceGroupId, replacement) - }, - activeGroupIdByWorktree: - target.activate === false - ? state.activeGroupIdByWorktree - : { ...state.activeGroupIdByWorktree, [worktreeId]: newGroup.id } + groups: [...(state.groupsByWorktree[worktreeId] ?? []), newGroup], + layout: replaceLeaf(currentLayout, sourceGroupId, replacement), + activeGroupId: target.activate === false ? null : newGroup.id } } @@ -106,25 +116,26 @@ export function createTabsGroupActions( // A new root and its first order member must become observable together. const nextGroup = { ...group, tabOrder } return { - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: groups.length - ? groups.map((entry) => (entry.id === groupId ? nextGroup : entry)) - : [nextGroup] - }, - layoutByWorktree: { - ...state.layoutByWorktree, - [worktreeId]: (orderSlot && state.layoutByWorktree[worktreeId]) || { - type: 'leaf', - groupId - } - }, + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [ + [ + worktreeId, + groups.length + ? groups.map((entry) => (entry.id === groupId ? nextGroup : entry)) + : [nextGroup] + ] + ]), + layoutByWorktree: replaceRecordEntries(state.layoutByWorktree, [ + [ + worktreeId, + (orderSlot && state.layoutByWorktree[worktreeId]) || { + type: 'leaf', + groupId + } + ] + ]), activeGroupIdByWorktree: groups.length ? state.activeGroupIdByWorktree - : { - ...state.activeGroupIdByWorktree, - [worktreeId]: groupId - } + : replaceRecordEntries(state.activeGroupIdByWorktree, [[worktreeId, groupId]]) } }) return groupId @@ -135,10 +146,7 @@ export function createTabsGroupActions( const groupAlreadyFocused = state.activeGroupIdByWorktree[worktreeId] === groupId const nextActiveGroupIdByWorktree = groupAlreadyFocused ? state.activeGroupIdByWorktree - : { - ...state.activeGroupIdByWorktree, - [worktreeId]: groupId - } + : replaceRecordEntries(state.activeGroupIdByWorktree, [[worktreeId, groupId]]) // Only surface tabs of the active workspace; focusing an unseen group must not consume its bell. if (state.activeWorktreeId !== worktreeId) { if (groupAlreadyFocused) { @@ -186,13 +194,17 @@ export function createTabsGroupActions( current.activeGroupIdByWorktree, worktreeId, groupId, - remainingGroups[0]?.id ?? null + remainingGroups[0]?.id ?? null, + replaceRecordEntries ) + const nextGroupsByWorktree = replaceRecordEntries(current.groupsByWorktree, [ + [worktreeId, remainingGroups] + ]) // Why: drop the dead group's recent-quick-command entry so the map can't grow unbounded as groups open/close. const { [groupId]: _droppedRecent, ...remainingRecent } = current.recentQuickCommandIdByGroup return { - groupsByWorktree: { ...current.groupsByWorktree, [worktreeId]: remainingGroups }, + groupsByWorktree: nextGroupsByWorktree, layoutByWorktree: collapsedState.layoutByWorktree, activeGroupIdByWorktree: collapsedState.activeGroupIdByWorktree, recentQuickCommandIdByGroup: remainingRecent, @@ -200,10 +212,7 @@ export function createTabsGroupActions( ? buildActiveSurfacePatch( { ...current, - groupsByWorktree: { - ...current.groupsByWorktree, - [worktreeId]: remainingGroups - }, + groupsByWorktree: nextGroupsByWorktree, layoutByWorktree: collapsedState.layoutByWorktree, activeGroupIdByWorktree: collapsedState.activeGroupIdByWorktree }, diff --git a/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts b/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts index b6c72881df1..5b647e13ac3 100644 --- a/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts +++ b/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts @@ -3,6 +3,7 @@ import type { TerminalTab } from '../../../../../shared/workspace-layout/termina import { findTabAndWorktree } from './tab-group-state' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' import { locateTerminalTab } from '../../terminals/terminal-tab-location' +import { replaceTabBuckets } from '../../keyed-record-transitions' /** Mirror host-tracked fields onto terminal rows: reconciliation derives unified fields there and recovery reads row ownership, so unified-only writes revert or remount hidden chat. */ export function patchTerminalTabRow( @@ -16,7 +17,7 @@ export function patchTerminalTabRow( } const nextTabs = tabsByWorktree[location.worktreeId].slice() nextTabs[location.index] = { ...location.tab, ...patch } - return { tabsByWorktree: { ...tabsByWorktree, [location.worktreeId]: nextTabs } } + return { tabsByWorktree: replaceTabBuckets(tabsByWorktree, [[location.worktreeId, nextTabs]]) } } // Mirror terminal pins so reconnect/peers retain them; dynamic import avoids a static store-to-runtime dependency. diff --git a/src/renderer/src/store/slices/tabs/tabs-label-actions.ts b/src/renderer/src/store/slices/tabs/tabs-label-actions.ts index 9eaf18b153f..1b4e03c7ccb 100644 --- a/src/renderer/src/store/slices/tabs/tabs-label-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-label-actions.ts @@ -19,6 +19,7 @@ import { recordTabOrderInLayoutOwner } from './tab-order-layout-owner' import { withPreviewEnded } from './tab-preview-flag' import { endsPreviewHere, promotePreviewTabsThroughLayoutOwner } from './preview-tab-promotion' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' function oppositeViewMode(mode: 'terminal' | 'chat'): 'terminal' | 'chat' { return mode === 'chat' ? 'terminal' : 'chat' @@ -179,17 +180,18 @@ export function createTabsLabelActions( changes.push({ worktreeId, from: group.tabOrder, to: nextTabOrder }) const orderMap = new Map(nextTabOrder.map((id, index) => [id, index])) return { - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: updateGroup(groups, { ...group, tabOrder: nextTabOrder }) - }, - unifiedTabsByWorktree: { - ...state.unifiedTabsByWorktree, - [worktreeId]: (state.unifiedTabsByWorktree[worktreeId] ?? []).map((tab) => { - const sortOrder = orderMap.get(tab.id) - return sortOrder === undefined ? tab : { ...tab, sortOrder } - }) - } + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [ + [worktreeId, updateGroup(groups, { ...group, tabOrder: nextTabOrder })] + ]), + unifiedTabsByWorktree: replaceTabBuckets(state.unifiedTabsByWorktree, [ + [ + worktreeId, + (state.unifiedTabsByWorktree[worktreeId] ?? []).map((tab) => { + const sortOrder = orderMap.get(tab.id) + return sortOrder === undefined ? tab : { ...tab, sortOrder } + }) + ] + ]) } } return state @@ -261,21 +263,21 @@ export function createTabsLabelActions( const group = groups.find((candidate) => candidate.id === tab.groupId) if (!group) { return { - unifiedTabsByWorktree: { ...state.unifiedTabsByWorktree, [worktreeId]: tabs } + unifiedTabsByWorktree: replaceTabBuckets(state.unifiedTabsByWorktree, [ + [worktreeId, tabs] + ]) } } const tabOrder = partitionPinnedTabOrder(group.tabOrder, tabs, tabId) return { - unifiedTabsByWorktree: { - ...state.unifiedTabsByWorktree, - [worktreeId]: applyTabOrderSortValues(tabs, tabOrder) - }, + unifiedTabsByWorktree: replaceTabBuckets(state.unifiedTabsByWorktree, [ + [worktreeId, applyTabOrderSortValues(tabs, tabOrder)] + ]), // Reconciliation derives pin from terminal rows; mirror it there or host echoes unpin during the round trip. ...patchTerminalTabRow(state.tabsByWorktree, tabId, { isPinned: true }), - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: updateGroup(groups, { ...group, tabOrder }) - } + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [ + [worktreeId, updateGroup(groups, { ...group, tabOrder })] + ]) } }) mirrorTabPinnedToHost(get(), tabId, true) @@ -302,20 +304,20 @@ export function createTabsLabelActions( const group = groups.find((candidate) => candidate.id === tab.groupId) if (!group) { return { - unifiedTabsByWorktree: { ...state.unifiedTabsByWorktree, [worktreeId]: tabs } + unifiedTabsByWorktree: replaceTabBuckets(state.unifiedTabsByWorktree, [ + [worktreeId, tabs] + ]) } } const tabOrder = partitionPinnedTabOrder(group.tabOrder, tabs, tabId) return { - unifiedTabsByWorktree: { - ...state.unifiedTabsByWorktree, - [worktreeId]: applyTabOrderSortValues(tabs, tabOrder) - }, + unifiedTabsByWorktree: replaceTabBuckets(state.unifiedTabsByWorktree, [ + [worktreeId, applyTabOrderSortValues(tabs, tabOrder)] + ]), ...patchTerminalTabRow(state.tabsByWorktree, tabId, { isPinned: false }), - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: updateGroup(groups, { ...group, tabOrder }) - } + groupsByWorktree: replaceRecordEntries(state.groupsByWorktree, [ + [worktreeId, updateGroup(groups, { ...group, tabOrder })] + ]) } }) mirrorTabPinnedToHost(get(), tabId, false) diff --git a/src/renderer/src/store/slices/tabs/tabs-move-actions.ts b/src/renderer/src/store/slices/tabs/tabs-move-actions.ts index 2f041f35fed..edbc2badd24 100644 --- a/src/renderer/src/store/slices/tabs/tabs-move-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-move-actions.ts @@ -1,9 +1,10 @@ import type { TabsSlice, TabsSliceGet, TabsSliceSet } from './tabs-slice-contract' -import { collapseGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree' +import { collapseWorktreeGroupLayout } from '../../../../../shared/workspace-layout/tab-group-layout-tree' import { buildActiveSurfacePatch } from './tabs-surface' import { findGroupAndWorktree, findGroupForTab, findTabAndWorktree } from './tab-group-state' import { pickNextActiveTab, pushRecentTabId, sanitizeRecentTabIds } from './tab-selection-history' import { dedupeTabOrder } from '../../../../../shared/workspace-layout/tab-order' +import { replaceRecordEntries, replaceTabBuckets } from '../../keyed-record-transitions' export function createTabsMoveActions( set: TabsSliceSet, @@ -38,10 +39,9 @@ export function createTabsMoveActions( Math.min(opts?.index ?? targetOrder.length, targetOrder.length) ) targetOrder.splice(targetIndex, 0, tabId) - const nextActiveGroupIdByWorktree = { - ...state.activeGroupIdByWorktree, - [worktreeId]: opts?.activate ? targetGroupId : state.activeGroupIdByWorktree[worktreeId] - } + let nextActiveGroupId = opts?.activate + ? targetGroupId + : state.activeGroupIdByWorktree[worktreeId] const sourceRecentTabIds = sanitizeRecentTabIds( (sourceGroup.recentTabIds ?? []).filter((id) => id !== tabId), sourceOrder @@ -78,30 +78,38 @@ export function createTabsMoveActions( return group }) let nextLayoutByWorktree = state.layoutByWorktree - let nextActiveGroupIdByWorktreeResolved = nextActiveGroupIdByWorktree let filteredGroups = nextGroups + const currentLayout = state.layoutByWorktree[worktreeId] if (sourceOrder.length === 0) { filteredGroups = nextGroups.filter((group) => group.id !== sourceGroup.id) - const collapsedState = collapseGroupLayout( - nextLayoutByWorktree, - nextActiveGroupIdByWorktreeResolved, + if (currentLayout) { + const collapsed = collapseWorktreeGroupLayout( + currentLayout, + nextActiveGroupId, + sourceGroup.id, + targetGroupId + ) + nextLayoutByWorktree = replaceRecordEntries(state.layoutByWorktree, [ + [worktreeId, collapsed.layout] + ]) + nextActiveGroupId = collapsed.activeGroupId + } + } + const nextActiveGroupIdByWorktreeResolved = replaceRecordEntries( + state.activeGroupIdByWorktree, + [[worktreeId, nextActiveGroupId]] + ) + const nextGroupsByWorktree = replaceRecordEntries(state.groupsByWorktree, [ + [worktreeId, filteredGroups] + ]) + const nextUnifiedTabsByWorktree = replaceTabBuckets(state.unifiedTabsByWorktree, [ + [ worktreeId, - sourceGroup.id, - targetGroupId - ) - nextLayoutByWorktree = collapsedState.layoutByWorktree - nextActiveGroupIdByWorktreeResolved = collapsedState.activeGroupIdByWorktree - } - const nextGroupsByWorktree = { - ...state.groupsByWorktree, - [worktreeId]: filteredGroups - } - const nextUnifiedTabsByWorktree = { - ...state.unifiedTabsByWorktree, - [worktreeId]: (state.unifiedTabsByWorktree[worktreeId] ?? []).map((candidate) => - candidate.id === tabId ? { ...candidate, groupId: targetGroupId } : candidate - ) - } + (state.unifiedTabsByWorktree[worktreeId] ?? []).map((candidate) => + candidate.id === tabId ? { ...candidate, groupId: targetGroupId } : candidate + ) + ] + ]) return { unifiedTabsByWorktree: nextUnifiedTabsByWorktree, groupsByWorktree: nextGroupsByWorktree, diff --git a/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch.ts b/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch.ts index 5cea197bf3f..2a429afdf45 100644 --- a/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch.ts +++ b/src/renderer/src/store/slices/tabs/tabs-reconciliation-batch.ts @@ -1,39 +1,68 @@ import type { AppState } from '../../types' +import { recordDraft, tabBucketDraft, type RecordDraft } from '../../keyed-record-transitions' + +type ReconciledRecords = Pick< + AppState, + 'unifiedTabsByWorktree' | 'groupsByWorktree' | 'activeGroupIdByWorktree' | 'layoutByWorktree' +> + +/** Drafts of the workspace records reconciliation rewrites, one entry per reconciled workspace. */ +export type ReconciliationDrafts = { + unifiedTabs: RecordDraft + groups: RecordDraft + // A workspace with no group stores an undefined active group, as the spread it replaced did. + activeGroups: RecordDraft + layout: RecordDraft +} + +export type ReconciliationDraftField = keyof ReconciliationDrafts /** One multi-workspace fold clones each shared map once and indexes read-only openFiles once, avoiding repeated map spreads and file scans per workspace. */ export type WorktreeTabModelReconciliationBatch = { /** Top-level `AppState` keys this fold already cloned and therefore owns. */ readonly ownedStateKeys: Set readonly liveEditorIds: ReadonlySet + /** Held across the fold and finished once before the merged patch publishes. */ + readonly drafts: ReconciliationDrafts + /** Draft fields some workspace's patch wrote, so the merged patch carries them. */ + readonly writtenDraftFields: Set +} + +export function createReconciliationDrafts(state: ReconciledRecords): ReconciliationDrafts { + return { + unifiedTabs: tabBucketDraft(state.unifiedTabsByWorktree), + groups: recordDraft(state.groupsByWorktree), + activeGroups: recordDraft(state.activeGroupIdByWorktree), + layout: recordDraft(state.layoutByWorktree) + } } export function createWorktreeTabModelReconciliationBatch( - state: Pick + state: Pick & ReconciledRecords ): WorktreeTabModelReconciliationBatch { return { ownedStateKeys: new Set(), - liveEditorIds: new Set(state.openFiles.map((file) => file.id)) + liveEditorIds: new Set(state.openFiles.map((file) => file.id)), + drafts: createReconciliationDrafts(state), + writtenDraftFields: new Set() } } -/** Mutate only batch-owned maps; preserve spread insertion order (existing keys keep their slot, new keys append). */ -export function writeBatchedWorkspaceRecordEntry( - current: Record, - stateKey: string, - worktreeId: string, - // `undefined` is accepted because the spread this replaces also stored it. - value: T | undefined, - batch: WorktreeTabModelReconciliationBatch | undefined -): Record { - if (batch?.ownedStateKeys.has(stateKey)) { - ;(current as Record)[worktreeId] = value - return current +/** Finishes the written drafts; each becomes one published record. */ +export function finishReconciliationDrafts( + drafts: ReconciliationDrafts, + written: ReadonlySet +): Partial { + return { + ...(written.has('unifiedTabs') ? { unifiedTabsByWorktree: drafts.unifiedTabs.finish() } : {}), + ...(written.has('groups') ? { groupsByWorktree: drafts.groups.finish() } : {}), + ...(written.has('activeGroups') + ? { + activeGroupIdByWorktree: + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: undefined entries were stored before too; readers treat them as absent. + drafts.activeGroups.finish() as AppState['activeGroupIdByWorktree'] + } + : {}), + ...(written.has('layout') ? { layoutByWorktree: drafts.layout.finish() } : {}) } - // Equal present entries preserve identity without claiming ownership; absent keys still insert, matching spread semantics. - if (worktreeId in current && Object.is(current[worktreeId], value)) { - return current - } - const next = { ...current, [worktreeId]: value } as Record - batch?.ownedStateKeys.add(stateKey) - return next } diff --git a/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts b/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts index 0a06ec8db77..f28c588461a 100644 --- a/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts +++ b/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts @@ -2,7 +2,7 @@ import { structuredLaunchSlotIds } from '@/lib/agent-session/launch/structured-a import type { AppState } from '../../types' import type { Tab } from '../../../../../shared/tab-types' import { dedupeTabOrder } from '../../../../../shared/workspace-layout/tab-order' -import { ensureGroup, updateGroup } from './tab-group-state' +import { ensureWorktreeGroup, updateGroup } from './tab-group-state' import { sanitizeRecentTabIds } from './tab-selection-history' import { pruneTabGroupLayoutForGroups } from './tabs-hydration' import { @@ -11,7 +11,9 @@ import { terminalTabHasReconnectablePty } from '../../terminals/terminal-orphan-cleanup' import { - writeBatchedWorkspaceRecordEntry, + createReconciliationDrafts, + finishReconciliationDrafts, + type ReconciliationDraftField, type WorktreeTabModelReconciliationBatch } from './tabs-reconciliation-batch' @@ -27,8 +29,13 @@ export function projectWorktreeTabModelReconciliation( worktreeId: string, batch?: WorktreeTabModelReconciliationBatch ): WorktreeTabModelReconciliation { - const unifiedTabs = state.unifiedTabsByWorktree[worktreeId] ?? [] - const groups = state.groupsByWorktree[worktreeId] ?? [] + // A batch's drafts hold earlier workspaces' writes; a single reconciliation drafts from `state`. + const drafts = batch?.drafts ?? createReconciliationDrafts(state) + const unifiedTabs = drafts.unifiedTabs.get(worktreeId) ?? [] + const storedGroups = drafts.groups.get(worktreeId) + const groups = storedGroups ?? [] + const storedActiveGroupId = drafts.activeGroups.get(worktreeId) + const storedLayout = drafts.layout.get(worktreeId) const runtimeTerminalTabs = state.tabsByWorktree[worktreeId] ?? [] const unifiedTerminalEntityIds = new Set( unifiedTabs.filter((tab) => tab.contentType === 'terminal').map((tab) => tab.entityId) @@ -43,17 +50,23 @@ export function projectWorktreeTabModelReconciliation( state.unverifiedPtyLossTabIds[tab.id] === true ) }) - const orphanTerminalIds = getOrphanTerminalIds(state, worktreeId) - const ensuredGroupState = + const orphanTerminalIds = getOrphanTerminalIds( + { + tabsByWorktree: state.tabsByWorktree, + unifiedTabsByWorktree: { [worktreeId]: unifiedTabs }, + ptyIdsByTabId: state.ptyIdsByTabId, + lastKnownRelayPtyIdByTabId: state.lastKnownRelayPtyIdByTabId, + deferredSshSessionIdsByTabId: state.deferredSshSessionIdsByTabId, + pendingReconnectPtyIdByTabId: state.pendingReconnectPtyIdByTabId, + unverifiedPtyLossTabIds: state.unverifiedPtyLossTabIds + }, + worktreeId + ) + const ensuredGroup = legacyRuntimeTerminalTabs.length > 0 - ? ensureGroup( - state.groupsByWorktree, - state.activeGroupIdByWorktree, - worktreeId, - state.activeGroupIdByWorktree[worktreeId] - ) + ? ensureWorktreeGroup(storedGroups, worktreeId, storedActiveGroupId) : null - const reconciliationGroup = ensuredGroupState?.group ?? groups[0] ?? null + const reconciliationGroup = ensuredGroup?.group ?? groups[0] ?? null const restoredLegacyTabs = reconciliationGroup == null ? [] @@ -86,7 +99,7 @@ export function projectWorktreeTabModelReconciliation( : (restoredLegacyTabs[0]?.id ?? null) const reconciledGroups = restoredLegacyTabs.length > 0 && reconciliationGroup - ? updateGroup(ensuredGroupState!.groupsByWorktree[worktreeId] ?? [], { + ? updateGroup(ensuredGroup?.created ? [ensuredGroup.group] : groups, { ...reconciliationGroup, // Why: restore runtime tabs into the active/root group so reattach cannot spawn a duplicate. activeTabId: reconciliationGroup.activeTabId ?? legacyFallbackActiveTabId, @@ -155,8 +168,7 @@ export function projectWorktreeTabModelReconciliation( prunedGroups.some((group, index) => group !== groups[index]) const nextGroups = groupsChanged ? prunedGroups : groups const currentActiveGroupId = - state.activeGroupIdByWorktree[worktreeId] ?? - ensuredGroupState?.activeGroupIdByWorktree[worktreeId] + storedActiveGroupId ?? (ensuredGroup?.created ? ensuredGroup.group.id : undefined) const activeGroupStillExists = nextGroups.some((group) => group.id === currentActiveGroupId) const nextActiveGroupId = activeGroupStillExists ? currentActiveGroupId @@ -167,8 +179,8 @@ export function projectWorktreeTabModelReconciliation( const activeGroupChanged = nextActiveGroupId !== currentActiveGroupId const baseNextLayout = restoredLegacyTabs.length > 0 && reconciliationGroup - ? (state.layoutByWorktree[worktreeId] ?? { type: 'leaf', groupId: reconciliationGroup.id }) - : state.layoutByWorktree[worktreeId] + ? (storedLayout ?? { type: 'leaf', groupId: reconciliationGroup.id }) + : storedLayout const validGroupIds = new Set(nextGroups.map((group) => group.id)) const prunedNextLayout = baseNextLayout && validGroupIds.size > 0 @@ -176,8 +188,7 @@ export function projectWorktreeTabModelReconciliation( : baseNextLayout const nextLayout = prunedNextLayout ?? (nextGroups[0] ? { type: 'leaf', groupId: nextGroups[0].id } : undefined) - const currentLayout = state.layoutByWorktree[worktreeId] - const layoutChanged = nextLayout !== currentLayout + const layoutChanged = nextLayout !== storedLayout let patch: Partial = {} if ( @@ -208,43 +219,23 @@ export function projectWorktreeTabModelReconciliation( batch?.ownedStateKeys.add('unreadTerminalTabs') } } + const written = new Set(['unifiedTabs', 'groups', 'activeGroups']) + drafts.unifiedTabs.set(worktreeId, validTabs) + drafts.groups.set(worktreeId, nextGroups) + drafts.activeGroups.set(worktreeId, nextActiveGroupId) + if (nextLayout && layoutChanged) { + // Why: restored runtime terminals need a concrete leaf before activation. + drafts.layout.set(worktreeId, nextLayout) + written.add('layout') + } + if (batch) { + written.forEach((field) => batch.writtenDraftFields.add(field)) + } patch = { - unifiedTabsByWorktree: writeBatchedWorkspaceRecordEntry( - state.unifiedTabsByWorktree, - 'unifiedTabsByWorktree', - worktreeId, - validTabs, - batch - ), - groupsByWorktree: writeBatchedWorkspaceRecordEntry( - state.groupsByWorktree, - 'groupsByWorktree', - worktreeId, - nextGroups, - batch - ), - activeGroupIdByWorktree: writeBatchedWorkspaceRecordEntry( - state.activeGroupIdByWorktree, - 'activeGroupIdByWorktree', - worktreeId, - nextActiveGroupId, - batch - ), + ...(batch ? {} : finishReconciliationDrafts(drafts, written)), ...(nextUnreadTerminalTabs !== state.unreadTerminalTabs ? { unreadTerminalTabs: nextUnreadTerminalTabs } : {}), - ...(nextLayout && layoutChanged - ? { - // Why: restored runtime terminals need a concrete leaf before activation. - layoutByWorktree: writeBatchedWorkspaceRecordEntry( - state.layoutByWorktree, - 'layoutByWorktree', - worktreeId, - nextLayout, - batch - ) - } - : {}), ...(orphanTerminalIds.size > 0 ? buildOrphanTerminalCleanupPatch(state, worktreeId, orphanTerminalIds) : {}) diff --git a/src/renderer/src/store/slices/tabs/tabs-session-actions.ts b/src/renderer/src/store/slices/tabs/tabs-session-actions.ts index deef7addf29..6a0fae74d91 100644 --- a/src/renderer/src/store/slices/tabs/tabs-session-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-session-actions.ts @@ -8,20 +8,29 @@ import { } from '../../../../../shared/worktree/degraded-repo-worktree-validity' import { buildHydratedTabState } from './tabs-hydration' import { projectWorktreeTabModelReconciliation } from './tabs-reconciliation' -import { createWorktreeTabModelReconciliationBatch } from './tabs-reconciliation-batch' +import { + createWorktreeTabModelReconciliationBatch, + finishReconciliationDrafts +} from './tabs-reconciliation-batch' import type { AppState } from '../../types' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' import { selectFolderWorkspaces } from '../../workspaces/catalog/workspace-record-fields' +import { markFullResync } from '../../keyed-record-transitions' +import { markPatchFullResync } from '../../seam-record-fields' -function replaceWorkspaceRecordKeys( - current: Record, - hydrated: Record, +// Cold path: scoped hydration rebuilds the selected workspaces' entries from the session snapshot. +function replaceWorkspaceRecordKeys( + current: Record, + hydrated: Record, workspaceKeys: ReadonlySet -): Record { - return { - ...Object.fromEntries(Object.entries(current).filter(([key]) => !workspaceKeys.has(key))), - ...Object.fromEntries(Object.entries(hydrated).filter(([key]) => workspaceKeys.has(key))) - } +): Record { + return markFullResync( + { + ...Object.fromEntries(Object.entries(current).filter(([key]) => !workspaceKeys.has(key))), + ...Object.fromEntries(Object.entries(hydrated).filter(([key]) => workspaceKeys.has(key))) + }, + 'hydration' + ) } /** Fold in workspace order so shared unread/orphan maps see prior patches; defer only the store write and subscriber notifications. */ @@ -41,7 +50,8 @@ function projectWorktreeTabModelReconciliations( Object.assign(merged, patch) Object.assign(working, patch) } - return merged + // The fold's drafts finish once, after every workspace has written its entries. + return Object.assign(merged, finishReconciliationDrafts(batch.drafts, batch.writtenDraftFields)) } export function createTabsSessionActions( @@ -94,7 +104,8 @@ export function createTabsSessionActions( new Set(options?.wslMovedChatWorkspaceKeys) ) if (!options?.replaceWorkspaceKeys) { - set(hydrated) + // Cold path: a full session hydration rebuilds every workspace's tab state. + set(markPatchFullResync(hydrated, 'hydration')) return } const replaceWorkspaceKeys = new Set(options.replaceWorkspaceKeys) diff --git a/src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts b/src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts index c764b1879a4..bc2fa192641 100644 --- a/src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts @@ -1,6 +1,7 @@ import type { TabGroupLayoutNode } from '../../../../../shared/tab-types' import type { TabsSlice, TabsSliceSet } from './tabs-slice-contract' import { updateSplitRatio } from '../../../../../shared/workspace-layout/tab-group-layout-tree' +import { replaceRecordEntries } from '../../keyed-record-transitions' export function createTabsSplitRatioActions( set: TabsSliceSet @@ -26,15 +27,13 @@ export function createTabsSplitRatioActions( return state } return { - layoutByWorktree: { - ...state.layoutByWorktree, - // Why: split ratios belong to the tab-group model (not transient UI), so persist them for restores and multi-step group ops. - [worktreeId]: updateSplitRatio( - currentLayout, - nodePath.length > 0 ? nodePath.split('.') : [], - ratio - ) - } + // Why: split ratios belong to the tab-group model (not transient UI), so persist them for restores and multi-step group ops. + layoutByWorktree: replaceRecordEntries(state.layoutByWorktree, [ + [ + worktreeId, + updateSplitRatio(currentLayout, nodePath.length > 0 ? nodePath.split('.') : [], ratio) + ] + ]) } }) } diff --git a/src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts b/src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts index 9c2186b5130..9319e3b3fa5 100644 --- a/src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts +++ b/src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts @@ -7,12 +7,12 @@ import { isEditorTabContentType } from '../editor/tabs/editor-tab-content-type' import { buildActiveSurfacePatch } from './tabs-surface' import type { AppState } from '../../types' export { renameWorktreeLayoutKeys } from './rename-worktree-layout' -import type { TerminalTab } from '../../../../../shared/workspace-layout/terminal-tab-types' import { omitRecordKeys } from '../worktrees/teardown/record-key-omission' -import { getTerminalActivationSpawnSuppression } from '../../terminals/terminal-activation-spawn-suppression' -import { collapseEmptiedKeptGroups } from './collapse-emptied-kept-groups' +import { recordDraft, tabBucketDraft } from '../../keyed-record-transitions' +import { collapseEmptiedKeptGroups, type GroupLayoutDrafts } from './collapse-emptied-kept-groups' import { createKeptWorktreeSurfacePruners, + pruneKeptEntries, type KeptWorktreeSurfaceRemoval } from './kept-worktree-surface-pruning' @@ -62,13 +62,24 @@ export function removeWorktreeLayout( const kept = removed.kept ? createKeptWorktreeSurfacePruners(s, removed.kept) : null const keep = (value: T, prune: ((value: T) => T) | undefined): T => prune ? prune(value) : value - const groupLayout = removed.kept - ? collapseEmptiedKeptGroups( - s, - keep(omitByWorktree(s.groupsByWorktree), kept?.groups), - removed.kept.worktreeIds - ) - : null + // Seam records are built once each, through the same operations, in the order this teardown applies them. + const tabs = tabBucketDraft(s.tabsByWorktree ?? {}) + const unifiedTabs = tabBucketDraft(s.unifiedTabsByWorktree) + const drafts: GroupLayoutDrafts = { + groups: recordDraft(s.groupsByWorktree ?? {}), + layout: recordDraft(s.layoutByWorktree ?? {}), + activeGroups: recordDraft(s.activeGroupIdByWorktree ?? {}) + } + for (const worktreeId of worktreeIds) { + tabs.delete(worktreeId) + unifiedTabs.delete(worktreeId) + drafts.groups.delete(worktreeId) + } + if (removed.kept && kept) { + pruneKeptEntries(tabs, removed.kept.worktreeIds, kept.entries.tabs) + pruneKeptEntries(drafts.groups, removed.kept.worktreeIds, kept.entries.groups) + collapseEmptiedKeptGroups(s.groupsByWorktree, drafts, removed.kept.worktreeIds) + } const removedContentIds = new Set( s.openFiles.filter((file) => worktreeIds.has(file.worktreeId)).map((file) => file.id) ) @@ -94,24 +105,36 @@ export function removeWorktreeLayout( hasPendingEntityTab(null, file.id) || file.mode === 'edit') ) + // Removed workspaces' entries are source-only here, so the kept groups stand in for the pruned record. + const keptGroups = removed.kept + ? Object.fromEntries( + [...removed.kept.worktreeIds].flatMap((id) => { + const groups = drafts.groups.get(id) + return groups ? [[id, groups]] : [] + }) + ) + : null const transferred = editorPlacementsInContentOwners( remainingFiles, s.unifiedTabsByWorktree, - groupLayout?.groups ?? s.groupsByWorktree, + keptGroups ? { ...s.groupsByWorktree, ...keptGroups } : s.groupsByWorktree, worktreeIds ) - const transferredPlacements = keep(omitByWorktree(transferred.sourceTabs), kept?.unifiedTabs) const survivingIds = new Set(remainingFiles.map((file) => file.id)) - const unifiedTabs = Object.fromEntries( - Object.entries(transferredPlacements).map(([id, tabs]) => [ - id, - tabs.filter( - (tab) => !isEditorTabContentType(tab.contentType) || survivingIds.has(tab.entityId) - ) - ]) - ) + for (const [id, sourceTabs] of Object.entries(transferred.sourceTabs)) { + if (worktreeIds.has(id)) { + continue + } + const pruned = + kept && removed.kept?.worktreeIds.has(id) ? kept.entries.unifiedTabs(sourceTabs) : sourceTabs + const live = pruned.filter( + (tab) => !isEditorTabContentType(tab.contentType) || survivingIds.has(tab.entityId) + ) + unifiedTabs.set(id, live.length === pruned.length ? pruned : live) + } + const nextUnifiedTabs = unifiedTabs.finish() const liveTabIds = new Set( - Object.values(unifiedTabs).flatMap((tabs) => tabs.map((tab) => tab.id)) + Object.values(nextUnifiedTabs).flatMap((tabs) => tabs.map((tab) => tab.id)) ) const removedPlacementIds = new Set( Object.values(s.unifiedTabsByWorktree).flatMap((tabs) => @@ -123,8 +146,11 @@ export function removeWorktreeLayout( .filter(([, tabs]) => tabs.some((tab) => removedPlacementIds.has(tab.id))) .map(([id]) => id) ) - const cleanGroups = Object.fromEntries( - Object.entries(omitByWorktree(transferred.sourceGroups)).map(([id, groups]) => [ + for (const [id, groups] of Object.entries(transferred.sourceGroups)) { + if (worktreeIds.has(id)) { + continue + } + drafts.groups.set( id, affectedWorkspaces.has(id) ? groups.map((group) => { @@ -140,16 +166,13 @@ export function removeWorktreeLayout( } }) : groups - ]) - ) - const collapsed = collapseEmptiedKeptGroups( - { - ...s, - layoutByWorktree: groupLayout?.layout ?? s.layoutByWorktree, - activeGroupIdByWorktree: groupLayout?.activeGroups ?? s.activeGroupIdByWorktree - }, - cleanGroups, - affectedWorkspaces + ) + } + // Removed worktrees' entries stay deleted; collapsing them would write an empty group list back. + collapseEmptiedKeptGroups( + s.groupsByWorktree, + drafts, + new Set([...affectedWorkspaces].filter((id) => !worktreeIds.has(id))) ) const recentEditors = Object.fromEntries( Object.entries(omitByWorktree(s.recentlyClosedEditorTabsByWorktree)).map(([id, rows]) => [ @@ -175,27 +198,33 @@ export function removeWorktreeLayout( ([id, selected]) => [id, selected && survivingIds.has(selected) ? selected : null] ) ) - const ownerLayouts = { ...collapsed.layout } - const ownerActiveGroups = { ...collapsed.activeGroups } const ownerOrders = { ...keep(omitByWorktree(s.tabBarOrderByWorktree), kept?.tabBarOrder) } const ownerActiveTypes = { ...omitByWorktree(s.activeTabTypeByWorktree) } for (const tab of transferred.movedTabs) { affectedWorkspaces.add(tab.worktreeId) - ownerLayouts[tab.worktreeId] ??= { type: 'leaf', groupId: tab.groupId } - ownerActiveGroups[tab.worktreeId] ??= tab.groupId + if (drafts.layout.get(tab.worktreeId) == null) { + drafts.layout.set(tab.worktreeId, { type: 'leaf', groupId: tab.groupId }) + } + if (drafts.activeGroups.get(tab.worktreeId) == null) { + drafts.activeGroups.set(tab.worktreeId, tab.groupId) + } ownerOrders[tab.worktreeId] = [...(ownerOrders[tab.worktreeId] ?? []), tab.entityId] activeFiles[tab.worktreeId] ??= tab.entityId ownerActiveTypes[tab.worktreeId] ??= 'editor' } + for (const worktreeId of worktreeIds) { + drafts.layout.delete(worktreeId) + drafts.activeGroups.delete(worktreeId) + } const patch: WorktreeLayoutPatch = { - tabsByWorktree: keep(omitByWorktree(s.tabsByWorktree), kept?.tabs), + tabsByWorktree: tabs.finish(), terminalLayoutsByTabId: omitByTabId(s.terminalLayoutsByTabId), ptyIdsByTabId: omitByTabId(s.ptyIdsByTabId), // Why: split-tab layout/group state is worktree-owned; leaving it makes a deleted worktree look restorable. - unifiedTabsByWorktree: unifiedTabs, - groupsByWorktree: collapsed.groups, - layoutByWorktree: omitByWorktree(ownerLayouts), - activeGroupIdByWorktree: omitByWorktree(ownerActiveGroups), + unifiedTabsByWorktree: nextUnifiedTabs, + groupsByWorktree: drafts.groups.finish(), + layoutByWorktree: drafts.layout.finish(), + activeGroupIdByWorktree: drafts.activeGroups.finish(), tabBarOrderByWorktree: Object.fromEntries( Object.entries(ownerOrders).map(([id, order]) => [ id, @@ -240,63 +269,3 @@ export function removeWorktreeLayout( } return patch } - -/** - * Tags a worktree's wakeable terminal tabs for an activation spawn, optionally bumping their - * generation so dead panes remount. - */ -export function markWorktreeTabsForActivationSpawn( - s: AppState, - worktreeId: string, - options: { isWakeable: (tab: TerminalTab) => boolean; bumpGeneration: boolean } -): Pick { - const { isWakeable, bumpGeneration } = options - return { - tabsByWorktree: { - ...s.tabsByWorktree, - [worktreeId]: (s.tabsByWorktree[worktreeId] ?? []).map((tab) => - !isWakeable(tab) - ? tab - : { - ...tab, - ...(bumpGeneration ? { generation: (tab.generation ?? 0) + 1 } : {}), - // Why: slept terminal remount/spawn is click-driven wake work; tag its PTY updates so they don't reshuffle Recent. - pendingActivationSpawn: getTerminalActivationSpawnSuppression( - s.terminalLayoutsByTabId[tab.id] - ) - } - ) - } - } -} - -/** Detaches terminal tabs from their PTYs, leaving the tabs in place to respawn. */ -export function unbindTerminalTabPtys( - s: AppState, - tabIds: ReadonlySet -): Pick { - let nextTabsByWorktree = s.tabsByWorktree - const nextPtyIdsByTabId = { ...s.ptyIdsByTabId } - for (const [worktreeId, tabs] of Object.entries(s.tabsByWorktree)) { - let nextTabs = tabs - for (const [index, tab] of tabs.entries()) { - if (!tabIds.has(tab.id)) { - continue - } - if (nextTabs === tabs) { - nextTabs = [...tabs] - } - const { pendingActivationSpawn: _pendingActivationSpawn, ...tabWithoutActivationSpawn } = tab - void _pendingActivationSpawn - nextTabs[index] = { ...tabWithoutActivationSpawn, ptyId: null } - nextPtyIdsByTabId[tab.id] = [] - } - if (nextTabs !== tabs) { - if (nextTabsByWorktree === s.tabsByWorktree) { - nextTabsByWorktree = { ...nextTabsByWorktree } - } - nextTabsByWorktree[worktreeId] = nextTabs - } - } - return { tabsByWorktree: nextTabsByWorktree, ptyIdsByTabId: nextPtyIdsByTabId } -} diff --git a/src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts b/src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts new file mode 100644 index 00000000000..11d2327a060 --- /dev/null +++ b/src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts @@ -0,0 +1,68 @@ +import type { AppState } from '../../types' +import type { TerminalTab } from '../../../../../shared/workspace-layout/terminal-tab-types' +import { getTerminalActivationSpawnSuppression } from '../../terminals/terminal-activation-spawn-suppression' +import { + replaceRecordEntries, + replaceTabBuckets, + tabBucketDraft +} from '../../keyed-record-transitions' + +/** + * Tags a worktree's wakeable terminal tabs for an activation spawn, optionally bumping their + * generation so dead panes remount. + */ +export function markWorktreeTabsForActivationSpawn( + s: AppState, + worktreeId: string, + options: { isWakeable: (tab: TerminalTab) => boolean; bumpGeneration: boolean } +): Pick { + const { isWakeable, bumpGeneration } = options + return { + tabsByWorktree: replaceTabBuckets(s.tabsByWorktree, [ + [ + worktreeId, + (s.tabsByWorktree[worktreeId] ?? []).map((tab) => + !isWakeable(tab) + ? tab + : { + ...tab, + ...(bumpGeneration ? { generation: (tab.generation ?? 0) + 1 } : {}), + // Why: slept terminal remount/spawn is click-driven wake work; tag its PTY updates so they don't reshuffle Recent. + pendingActivationSpawn: getTerminalActivationSpawnSuppression( + s.terminalLayoutsByTabId[tab.id] + ) + } + ) + ] + ]) + } +} + +/** Detaches terminal tabs from their PTYs, leaving the tabs in place to respawn. */ +export function unbindTerminalTabPtys( + s: AppState, + tabIds: ReadonlySet +): Pick { + const tabs = tabBucketDraft(s.tabsByWorktree) + const ptyIdOperations: [string, string[]][] = [] + for (const [worktreeId, worktreeTabs] of Object.entries(s.tabsByWorktree)) { + let nextTabs = worktreeTabs + for (const [index, tab] of worktreeTabs.entries()) { + if (!tabIds.has(tab.id)) { + continue + } + if (nextTabs === worktreeTabs) { + nextTabs = [...worktreeTabs] + } + const { pendingActivationSpawn: _pendingActivationSpawn, ...tabWithoutActivationSpawn } = tab + void _pendingActivationSpawn + nextTabs[index] = { ...tabWithoutActivationSpawn, ptyId: null } + ptyIdOperations.push([tab.id, []]) + } + tabs.set(worktreeId, nextTabs) + } + return { + tabsByWorktree: tabs.finish(), + ptyIdsByTabId: replaceRecordEntries(s.ptyIdsByTabId, ptyIdOperations) + } +} diff --git a/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts b/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts index 7641a17d672..a8fa1b22f27 100644 --- a/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts +++ b/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts @@ -10,7 +10,7 @@ import { ACTIVE_WORKTREE_TERMINAL_PREP_IDLE_TIMEOUT_MS, ACTIVE_WORKTREE_TERMINAL_PREP_INPUT_QUIET_MS } from '../listing/worktree-slice-constants' -import { markWorktreeTabsForActivationSpawn } from '../../tabs/worktree-layout-lifecycle' +import { markWorktreeTabsForActivationSpawn } from '../../tabs/worktree-terminal-tab-respawn' import { isWorkspaceKey, parseWorkspaceKey, diff --git a/src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-state.ts b/src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-state.ts index 18acab2fad9..3602289890b 100644 --- a/src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-state.ts +++ b/src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-state.ts @@ -12,6 +12,7 @@ import { type ClosedTerminalTabSnapshot } from '../../../terminals/recently-closed-terminal-tabs' import { renameWorktreeLayoutKeys } from '../../tabs/worktree-layout-lifecycle' +import { replaceRecordEntries } from '../../../keyed-record-transitions' import { renameCombinedDiffViewOwner } from '@/components/editor/combined-diff/remember-view/combined-diff-view-cache' // Inventory non-layout worktree-keyed maps; layout migrates separately, while surviving tab/file IDs keep their keys. @@ -214,16 +215,16 @@ export function buildWorktreeRenameState( s.pairedTerminalTabCloseIntentsByEnvironment ) const currentSleepingAgentSessionsByPaneKey = s.sleepingAgentSessionsByPaneKey ?? {} - const sleepingAgentSessionsByPaneKey = Object.values(currentSleepingAgentSessionsByPaneKey).some( - (record) => record.worktreeId === oldWorktreeId + const repointedSleepingSessions = Object.entries(currentSleepingAgentSessionsByPaneKey).flatMap( + ([paneKey, record]) => + record.worktreeId === oldWorktreeId + ? [[paneKey, { ...record, worktreeId: newWorktreeId }] as const] + : [] ) - ? Object.fromEntries( - Object.entries(currentSleepingAgentSessionsByPaneKey).map(([paneKey, record]) => [ - paneKey, - record.worktreeId === oldWorktreeId ? { ...record, worktreeId: newWorktreeId } : record - ]) - ) - : s.sleepingAgentSessionsByPaneKey + const sleepingAgentSessionsByPaneKey = + repointedSleepingSessions.length > 0 + ? replaceRecordEntries(currentSleepingAgentSessionsByPaneKey, repointedSleepingSessions) + : s.sleepingAgentSessionsByPaneKey // Groups keep their ids across the rename, so their chooser marks move with them. const splitLandingGroupIds = Object.values(s.splitLandingGroupIds ?? {}).includes(oldWorktreeId) ? Object.fromEntries( diff --git a/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts b/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts index 8e6f7739601..c731b44527c 100644 --- a/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts +++ b/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts @@ -17,6 +17,7 @@ import type { import { settleAttentionRemovedBy } from '../../workspace-attention/attention-removal-follow-up' import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' import { flushPurgedWorkspaceEdits } from '../teardown/removed-workspace-unsaved-files' +import { replaceRecordEntries, replaceTabBuckets } from '../../../keyed-record-transitions' export function createSetRenamingWorktreeId( set: WorktreeSliceSet, @@ -81,17 +82,13 @@ export function createRemountTerminalTabForRecovery( } result = { remounted: true, generation: recovery?.generation ?? 0 } return { - tabsByWorktree: { - ...s.tabsByWorktree, - [worktreeId]: nextTabs - }, + tabsByWorktree: replaceTabBuckets(s.tabsByWorktree, [[worktreeId, nextTabs]]), ...(pendingStartup ? { // Remount needs a distinct startup record so stale-pane teardown cannot consume the successor’s command. - pendingStartupByTabId: { - ...s.pendingStartupByTabId, - [tabId]: { ...pendingStartup } - } + pendingStartupByTabId: replaceRecordEntries(s.pendingStartupByTabId, [ + [tabId, { ...pendingStartup }] + ]) } : {}) } @@ -117,7 +114,7 @@ export function createSettleTerminalTabRecovery( } const nextTabs = s.tabsByWorktree[worktreeId].slice() nextTabs[index] = { ...tab, recovery } - return { tabsByWorktree: { ...s.tabsByWorktree, [worktreeId]: nextTabs } } + return { tabsByWorktree: replaceTabBuckets(s.tabsByWorktree, [[worktreeId, nextTabs]]) } }) } } diff --git a/src/renderer/src/store/slices/worktrees/teardown/record-key-omission.ts b/src/renderer/src/store/slices/worktrees/teardown/record-key-omission.ts index 4efb24c215e..6d5464564eb 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/record-key-omission.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/record-key-omission.ts @@ -1,3 +1,5 @@ +import { recordDraft } from '../../../keyed-record-transitions' + /** Preserve identity when no key matches or teardown rerenders selectors for dozens of unchanged maps. Nullish partial-test slices normalize to {}, matching spread/delete; production initializes them. */ export function omitRecordKeys( record: Record | undefined, @@ -6,13 +8,9 @@ export function omitRecordKeys( if (!record) { return {} } - let next: Record | null = null + const draft = recordDraft(record) for (const key of keys) { - if (!(key in record)) { - continue - } - next ??= { ...record } - delete next[key] + draft.delete(key) } - return next ?? record + return draft.finish() } diff --git a/src/renderer/src/store/store-observer-installers.ts b/src/renderer/src/store/store-observer-installers.ts new file mode 100644 index 00000000000..6b2dbde8996 --- /dev/null +++ b/src/renderer/src/store/store-observer-installers.ts @@ -0,0 +1,11 @@ +import type { AppState } from './types' + +export type StoreObserverHost = { + getState: () => AppState + subscribe: (listener: (state: AppState, previous: AppState) => void) => () => void +} + +/** Observers installed once at store creation, before app consumers subscribe; none may wrap `set`. */ +export type StoreObserverInstaller = (store: StoreObserverHost) => void + +export const STORE_OBSERVER_INSTALLERS: readonly StoreObserverInstaller[] = [] diff --git a/src/renderer/src/store/tab-transition-subscription.ts b/src/renderer/src/store/tab-transition-subscription.ts new file mode 100644 index 00000000000..cf9404bf3c7 --- /dev/null +++ b/src/renderer/src/store/tab-transition-subscription.ts @@ -0,0 +1,33 @@ +import type { AppState } from './types' +import { readTabMapChanges } from './keyed-record-change-reads' +import type { TabMapChanges } from './keyed-record-transitions' + +type ObservedStore = { + getState: () => AppState + subscribe: (listener: (state: AppState, previous: AppState) => void) => () => void +} + +export type TabTransition = { + /** Current accepted state; under reentrant writes one callback may span several writes. */ + state: AppState + tabs: TabMapChanges | null + unifiedTabs: TabMapChanges | null +} + +/** Tab-map deltas since this subscriber's last delivery, read from the store's current state. */ +export function subscribeTabTransitions( + store: ObservedStore, + listener: (transition: TabTransition) => void +): () => void { + let { tabsByWorktree, unifiedTabsByWorktree } = store.getState() + return store.subscribe(() => { + const state = store.getState() + const tabs = readTabMapChanges(state.tabsByWorktree, tabsByWorktree) + const unifiedTabs = readTabMapChanges(state.unifiedTabsByWorktree, unifiedTabsByWorktree) + tabsByWorktree = state.tabsByWorktree + unifiedTabsByWorktree = state.unifiedTabsByWorktree + if (tabs || unifiedTabs) { + listener({ state, tabs, unifiedTabs }) + } + }) +} diff --git a/src/renderer/src/store/terminals/terminal-companion-record-operations.ts b/src/renderer/src/store/terminals/terminal-companion-record-operations.ts new file mode 100644 index 00000000000..6b91a963607 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-companion-record-operations.ts @@ -0,0 +1,17 @@ +import { recordDraft } from '../keyed-record-transitions' + +/** Ordered set/delete operations (null deletes); returns `previous` when none changed it. */ +export function applyRecordOperations( + previous: Record, + entries: Iterable +): Record { + const draft = recordDraft(previous) + for (const [key, value] of entries) { + if (value === null) { + draft.delete(key) + } else { + draft.set(key, value) + } + } + return draft.finish() +} diff --git a/src/renderer/src/store/terminals/terminal-orphan-cleanup.ts b/src/renderer/src/store/terminals/terminal-orphan-cleanup.ts index b2ee9f350a6..0431acaf97f 100644 --- a/src/renderer/src/store/terminals/terminal-orphan-cleanup.ts +++ b/src/renderer/src/store/terminals/terminal-orphan-cleanup.ts @@ -74,19 +74,10 @@ export function getOrphanTerminalIds( ) } -export function buildOrphanTerminalCleanupPatch( - state: OrphanTerminalCleanupState, - worktreeId: string, - orphanTerminalIds: Set -): Pick< +type OrphanTerminalCompanionCleanup = Pick< AppState, - | 'tabsByWorktree' - | 'ptyIdsByTabId' - | 'runtimePaneTitlesByTabId' | 'expandedPaneByTabId' | 'canExpandPaneByTabId' - | 'terminalLayoutsByTabId' - | 'pendingStartupByTabId' | 'pendingInitialCwdByTabId' | 'pendingIssueCommandSplitByTabId' | 'automaticAgentResumeClaimsByTabId' @@ -96,16 +87,26 @@ export function buildOrphanTerminalCleanupPatch( | 'cacheTimerByKey' | 'activeTabIdByWorktree' | 'activeTabId' -> { +> + +/** The orphans' per-tab caches and selection; callers that build seam records themselves use only this part. */ +export function buildOrphanTerminalCompanionCleanupPatch( + state: Omit< + OrphanTerminalCleanupState, + | 'ptyIdsByTabId' + | 'runtimePaneTitlesByTabId' + | 'terminalLayoutsByTabId' + | 'pendingStartupByTabId' + >, + worktreeId: string, + orphanTerminalIds: Set, + // The full cleanup already filtered this bucket; reuse it instead of a second pass. + keptTabs?: AppState['tabsByWorktree'][string] +): OrphanTerminalCompanionCleanup { if (orphanTerminalIds.size === 0) { return { - tabsByWorktree: state.tabsByWorktree, - ptyIdsByTabId: state.ptyIdsByTabId, - runtimePaneTitlesByTabId: state.runtimePaneTitlesByTabId, expandedPaneByTabId: state.expandedPaneByTabId, canExpandPaneByTabId: state.canExpandPaneByTabId, - terminalLayoutsByTabId: state.terminalLayoutsByTabId, - pendingStartupByTabId: state.pendingStartupByTabId, pendingInitialCwdByTabId: state.pendingInitialCwdByTabId, pendingIssueCommandSplitByTabId: state.pendingIssueCommandSplitByTabId, automaticAgentResumeClaimsByTabId: state.automaticAgentResumeClaimsByTabId, @@ -118,15 +119,11 @@ export function buildOrphanTerminalCleanupPatch( } } - const nextTabs = (state.tabsByWorktree[worktreeId] ?? []).filter( - (tab) => !orphanTerminalIds.has(tab.id) - ) - const nextPtyIdsByTabId = { ...state.ptyIdsByTabId } - const nextRuntimePaneTitlesByTabId = { ...state.runtimePaneTitlesByTabId } + const firstKeptTab = keptTabs + ? keptTabs[0] + : (state.tabsByWorktree[worktreeId] ?? []).find((tab) => !orphanTerminalIds.has(tab.id)) const nextExpandedPaneByTabId = { ...state.expandedPaneByTabId } const nextCanExpandPaneByTabId = { ...state.canExpandPaneByTabId } - const nextTerminalLayoutsByTabId = { ...state.terminalLayoutsByTabId } - const nextPendingStartupByTabId = { ...state.pendingStartupByTabId } const nextPendingInitialCwdByTabId = { ...state.pendingInitialCwdByTabId } const nextPendingIssueCommandSplitByTabId = { ...state.pendingIssueCommandSplitByTabId } const nextAutomaticAgentResumeClaimsByTabId = { @@ -144,12 +141,8 @@ export function buildOrphanTerminalCleanupPatch( // Share per-tab cache teardown across creation/reconciliation so orphan detection and cleanup cannot diverge. for (const orphanTabId of orphanTerminalIds) { - delete nextPtyIdsByTabId[orphanTabId] - delete nextRuntimePaneTitlesByTabId[orphanTabId] delete nextExpandedPaneByTabId[orphanTabId] delete nextCanExpandPaneByTabId[orphanTabId] - delete nextTerminalLayoutsByTabId[orphanTabId] - delete nextPendingStartupByTabId[orphanTabId] delete nextPendingInitialCwdByTabId[orphanTabId] delete nextPendingIssueCommandSplitByTabId[orphanTabId] delete nextAutomaticAgentResumeClaimsByTabId[orphanTabId] @@ -162,24 +155,9 @@ export function buildOrphanTerminalCleanupPatch( } } - const nextActiveTabIdByWorktree = { - ...state.activeTabIdByWorktree, - [worktreeId]: orphanTerminalIds.has(state.activeTabIdByWorktree[worktreeId] ?? '') - ? (nextTabs[0]?.id ?? null) - : state.activeTabIdByWorktree[worktreeId] - } - return { - tabsByWorktree: { - ...state.tabsByWorktree, - [worktreeId]: nextTabs - }, - ptyIdsByTabId: nextPtyIdsByTabId, - runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId, expandedPaneByTabId: nextExpandedPaneByTabId, canExpandPaneByTabId: nextCanExpandPaneByTabId, - terminalLayoutsByTabId: nextTerminalLayoutsByTabId, - pendingStartupByTabId: nextPendingStartupByTabId, pendingInitialCwdByTabId: nextPendingInitialCwdByTabId, pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId, automaticAgentResumeClaimsByTabId: nextAutomaticAgentResumeClaimsByTabId, @@ -187,8 +165,60 @@ export function buildOrphanTerminalCleanupPatch( nativeChatLaunchDraftByTabId: nextNativeChatLaunchDraftByTabId, tabBarOrderByWorktree: nextTabBarOrderByWorktree, cacheTimerByKey: nextCacheTimerByKey, - activeTabIdByWorktree: nextActiveTabIdByWorktree, + activeTabIdByWorktree: { + ...state.activeTabIdByWorktree, + [worktreeId]: orphanTerminalIds.has(state.activeTabIdByWorktree[worktreeId] ?? '') + ? (firstKeptTab?.id ?? null) + : state.activeTabIdByWorktree[worktreeId] + }, activeTabId: state.activeTabId && orphanTerminalIds.has(state.activeTabId) ? null : state.activeTabId } } + +export function buildOrphanTerminalCleanupPatch( + state: OrphanTerminalCleanupState, + worktreeId: string, + orphanTerminalIds: Set +): Pick { + if (orphanTerminalIds.size === 0) { + return { + ...buildOrphanTerminalCompanionCleanupPatch(state, worktreeId, orphanTerminalIds), + tabsByWorktree: state.tabsByWorktree, + ptyIdsByTabId: state.ptyIdsByTabId, + runtimePaneTitlesByTabId: state.runtimePaneTitlesByTabId, + terminalLayoutsByTabId: state.terminalLayoutsByTabId, + pendingStartupByTabId: state.pendingStartupByTabId + } + } + const keptTabs = (state.tabsByWorktree[worktreeId] ?? []).filter( + (tab) => !orphanTerminalIds.has(tab.id) + ) + const companions = buildOrphanTerminalCompanionCleanupPatch( + state, + worktreeId, + orphanTerminalIds, + keptTabs + ) + const nextPtyIdsByTabId = { ...state.ptyIdsByTabId } + const nextRuntimePaneTitlesByTabId = { ...state.runtimePaneTitlesByTabId } + const nextTerminalLayoutsByTabId = { ...state.terminalLayoutsByTabId } + const nextPendingStartupByTabId = { ...state.pendingStartupByTabId } + for (const orphanTabId of orphanTerminalIds) { + delete nextPtyIdsByTabId[orphanTabId] + delete nextRuntimePaneTitlesByTabId[orphanTabId] + delete nextTerminalLayoutsByTabId[orphanTabId] + delete nextPendingStartupByTabId[orphanTabId] + } + return { + ...companions, + tabsByWorktree: { + ...state.tabsByWorktree, + [worktreeId]: keptTabs + }, + ptyIdsByTabId: nextPtyIdsByTabId, + runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId, + terminalLayoutsByTabId: nextTerminalLayoutsByTabId, + pendingStartupByTabId: nextPendingStartupByTabId + } +} diff --git a/src/renderer/src/store/terminals/terminal-tab-close.ts b/src/renderer/src/store/terminals/terminal-tab-close.ts index d7b25c01a49..849b1df102b 100644 --- a/src/renderer/src/store/terminals/terminal-tab-close.ts +++ b/src/renderer/src/store/terminals/terminal-tab-close.ts @@ -5,10 +5,7 @@ import { pushClosedTerminalTabSnapshot } from './recently-closed-terminal-tabs' import { pushRecentlyClosedTabKind } from '../slices/tabs/recently-closed-tabs' // Use store-free registry to avoid reentering slice creation through terminal-parked-tab-watchers. import { retireParkedTerminalTab } from '@/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-registry' -import { - buildTerminalTabRetirementPlan, - removeSleepingAgentSessionsForTab -} from './terminal-tab-retirement' +import { buildTerminalTabRetirementPlan } from './terminal-tab-retirement' import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' import { startTerminalTabProviderRetirement } from './terminal-tab-close-providers' import { stopLegacyRelayBridgedShellsForTab } from './legacy-relay-bridged-tab-close' @@ -25,6 +22,7 @@ import { noteAgentLaunchPaneClosedByUser } from '@/lib/agent-session/launch/pane import { settleAgentLaunchPaneStart } from '@/lib/agent-session/launch/pane/agent-launch-pane-start' import { settleAttentionRemovedBy } from '../slices/workspace-attention/attention-removal-follow-up' import { runAsAutomaticDeselection } from '../workspaces/selection/active-worktree-deselection-intent' +import { recordDraft, tabBucketDraft } from '../keyed-record-transitions' export function createTerminalTabCloseActions( set: TerminalStoreSet, @@ -62,11 +60,19 @@ export function createTerminalTabCloseActions( const closingTabIds = [tabId] const omitByTabId = (record: Record): Record => omitRecordKeys(record, closingTabIds) - const next = { ...s.tabsByWorktree } + // Partial test slices may lack a record; omitRecordKeys normalizes those to {}. + const omitAddressedByTabId = (record: Record): Record => { + if (!record) { + return {} + } + const draft = recordDraft(record) + draft.delete(tabId) + return draft.finish() + } + const tabsDraft = tabBucketDraft(s.tabsByWorktree) let closedTab: TerminalTab | null = null let closedWorktreeId: string | null = null - for (const wId of Object.keys(next)) { - const before = next[wId] + for (const [wId, before] of Object.entries(s.tabsByWorktree)) { const closing = before.find((t) => t.id === tabId) if (closing) { closingWorktreeId = wId @@ -86,9 +92,10 @@ export function createTerminalTabCloseActions( } const after = before.filter((t) => t.id !== tabId) if (after.length !== before.length) { - next[wId] = after + tabsDraft.set(wId, after) } } + const next = tabsDraft.finish() // Session-only tombstone fences synchronous SSH pulls before main acknowledges close; retire once merge moves to main. const nextClosedTombstones = intentReason && closedWorktreeId && opts?.remoteCloseOwnedByHost !== true @@ -121,13 +128,15 @@ export function createTerminalTabCloseActions( : null const nextExpanded = omitByTabId(s.expandedPaneByTabId) const nextCanExpand = omitByTabId(s.canExpandPaneByTabId) - const nextLayouts = omitByTabId(s.terminalLayoutsByTabId) + const nextLayouts = omitAddressedByTabId(s.terminalLayoutsByTabId) const nextLocalOnlyScrollback = omitByTabId(s.localOnlyScrollbackByTabId) - const nextPtyIdsByTabId = omitByTabId(s.ptyIdsByTabId) - const nextLastKnownRelay = omitByTabId(s.lastKnownRelayPtyIdByTabId) + const nextPtyIdsByTabId = omitAddressedByTabId(s.ptyIdsByTabId) + const nextLastKnownRelay = omitAddressedByTabId(s.lastKnownRelayPtyIdByTabId) const nextDeferredSshSessionIdsByTabId = omitByTabId(s.deferredSshSessionIdsByTabId) - const nextPendingReconnectPtyIdByTabId = omitByTabId(s.pendingReconnectPtyIdByTabId) - const nextRuntimePaneTitlesByTabId = omitByTabId(s.runtimePaneTitlesByTabId) + const nextPendingReconnectPtyIdByTabId = omitAddressedByTabId( + s.pendingReconnectPtyIdByTabId + ) + const nextRuntimePaneTitlesByTabId = omitAddressedByTabId(s.runtimePaneTitlesByTabId) const nextUnverifiedPtyLossTabIds = omitUnverifiedPtyLossTabIds( s.unverifiedPtyLossTabIds, [tabId] @@ -138,10 +147,17 @@ export function createTerminalTabCloseActions( s.lastTerminalInputAtByPaneKey, tabId ) - const nextSleepingAgentSessionsByPaneKey = retiresSession - ? removeSleepingAgentSessionsForTab(s.sleepingAgentSessionsByPaneKey, tabId) - : s.sleepingAgentSessionsByPaneKey - const nextPendingStartupByTabId = omitByTabId(s.pendingStartupByTabId) + // Same pane-key/tab match as removeSleepingAgentSessionsForTab, as delete operations. + const sleepingDraft = recordDraft(s.sleepingAgentSessionsByPaneKey) + if (retiresSession) { + for (const [paneKey, record] of Object.entries(s.sleepingAgentSessionsByPaneKey)) { + if (paneKey.startsWith(`${tabId}:`) || record.tabId === tabId) { + sleepingDraft.delete(paneKey) + } + } + } + const nextSleepingAgentSessionsByPaneKey = sleepingDraft.finish() + const nextPendingStartupByTabId = omitAddressedByTabId(s.pendingStartupByTabId) const nextAutomaticAgentResumeClaimsByTabId = omitByTabId( s.automaticAgentResumeClaimsByTabId ) diff --git a/src/renderer/src/store/terminals/terminal-tab-creation.ts b/src/renderer/src/store/terminals/terminal-tab-creation.ts index fb4893786ce..0a6fbefaaf9 100644 --- a/src/renderer/src/store/terminals/terminal-tab-creation.ts +++ b/src/renderer/src/store/terminals/terminal-tab-creation.ts @@ -9,12 +9,19 @@ import { import { getNextTerminalOrdinal } from '../../../../shared/workspace-layout/terminal-tab-ordinal' import { singlePaneLayoutSnapshot } from './terminal-single-pane-layout' import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' -import { buildOrphanTerminalCleanupPatch, getOrphanTerminalIds } from './terminal-orphan-cleanup' -import { ensureGroup, findTabByEntityInGroup, updateGroup } from '../slices/tabs/tab-group-state' +import { + buildOrphanTerminalCompanionCleanupPatch, + getOrphanTerminalIds +} from './terminal-orphan-cleanup' +import { + ensureWorktreeGroup, + findTabByEntityInGroup, + updateGroup +} from '../slices/tabs/tab-group-state' import { pushRecentTabId, sanitizeRecentTabIds } from '../slices/tabs/tab-selection-history' import { dedupeTabOrder } from '../../../../shared/workspace-layout/tab-order' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/non-secure-context-uuid' -import { emptySplitGroup, insertSplitGroup } from '../slices/tabs/tabs-group-actions' +import { emptySplitGroup, splitGroupEntries } from '../slices/tabs/tabs-group-actions' import { ownsGlobalSelection } from '../workspaces/selection/global-selection-owner' import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' @@ -25,6 +32,8 @@ import { } from './terminal-tab-create-through-layout-owner' import type { AppState } from '../types' import { normalizeTabStartupCommand } from './terminal-startup-queues' +import { replaceRecordEntries, replaceTabBuckets } from '../keyed-record-transitions' +import { applyRecordOperations } from './terminal-companion-record-operations' export function createTerminalTabCreationActions( set: TerminalStoreSet, @@ -37,21 +46,29 @@ export function createTerminalTabCreationActions( const split = options?.split const splitGroupId = split ? createBrowserUuid() : undefined set((current) => { - const s = + const s = current + // The split's per-worktree group, layout and focus; each record is built once in the patch below. + const splitEntries = split && splitGroupId - ? { - ...current, - ...insertSplitGroup( - current, - worktreeId, - split, - emptySplitGroup(worktreeId, splitGroupId) - ) - } - : current + ? splitGroupEntries( + current, + worktreeId, + split, + emptySplitGroup(worktreeId, splitGroupId) + ) + : null + const worktreeGroups = splitEntries?.groups ?? current.groupsByWorktree[worktreeId] + const worktreeActiveGroupId = + splitEntries?.activeGroupId ?? current.activeGroupIdByWorktree[worktreeId] + const worktreeLayout = splitEntries?.layout ?? current.layoutByWorktree[worktreeId] const requestedGroupId = splitGroupId ?? targetGroupId const orphanTerminalIds = getOrphanTerminalIds(s, worktreeId) - const orphanCleanupPatch = buildOrphanTerminalCleanupPatch(s, worktreeId, orphanTerminalIds) + // Seam records are built once below from the orphan IDs; this cleans only the orphans' caches. + const orphanCleanupPatch = buildOrphanTerminalCompanionCleanupPatch( + s, + worktreeId, + orphanTerminalIds + ) const existing = (s.tabsByWorktree[worktreeId] ?? []).filter( (entry) => !orphanTerminalIds.has(entry.id) ) @@ -122,20 +139,21 @@ export function createTerminalTabCreationActions( void warnIfZCodeCannotOpenSession() } const validTargetGroupId = - requestedGroupId && - s.groupsByWorktree[worktreeId]?.some((group) => group.id === requestedGroupId) + requestedGroupId && worktreeGroups?.some((group) => group.id === requestedGroupId) ? requestedGroupId : undefined - const { group, groupsByWorktree, activeGroupIdByWorktree } = ensureGroup( - s.groupsByWorktree, - s.activeGroupIdByWorktree, + // Per-worktree group result; the records are built once in the patch below. + const { group, created: createdGroup } = ensureWorktreeGroup( + worktreeGroups, worktreeId, - validTargetGroupId ?? s.activeGroupIdByWorktree[worktreeId] + validTargetGroupId ?? worktreeActiveGroupId ) - const nextActiveGroupIdByWorktree = + const nextActiveGroupId = shouldActivate && validTargetGroupId - ? { ...activeGroupIdByWorktree, [worktreeId]: validTargetGroupId } - : activeGroupIdByWorktree + ? validTargetGroupId + : createdGroup + ? group.id + : worktreeActiveGroupId const existingUnifiedTabs = s.unifiedTabsByWorktree[worktreeId] ?? [] const existingTerminalTab = findTabByEntityInGroup( s.unifiedTabsByWorktree, @@ -144,7 +162,7 @@ export function createTerminalTabCreationActions( id, 'terminal' ) - const groupsForWorktree = groupsByWorktree[worktreeId] ?? [] + const groupsForWorktree = createdGroup ? [group] : (worktreeGroups ?? []) const cleanedGroups = orphanTerminalIds.size === 0 ? groupsForWorktree @@ -203,35 +221,39 @@ export function createTerminalTabCreationActions( const nextActiveTabIdForWorktree = shouldActivate ? tab.id : (cleanedActiveTabIdForWorktree ?? cleanedGroupActiveTabId ?? tab.id) + // Against the updater's state: the orphan cleanup's per-tab deletes, in its order, then the created tab. + const orphanDeletes = [...orphanTerminalIds].map((orphanId) => [orphanId, null] as const) return { ...orphanCleanupPatch, - tabsByWorktree: { - ...orphanCleanupPatch.tabsByWorktree, - [worktreeId]: [...existing, tab] - }, + tabsByWorktree: replaceTabBuckets(current.tabsByWorktree, [ + [worktreeId, [...existing, tab]] + ]), // Why: publish the unified tab atomically with the runtime tab so a transient legacy mount can't race the split host. - unifiedTabsByWorktree: { - ...s.unifiedTabsByWorktree, - [worktreeId]: existingTerminalTab - ? existingUnifiedTabs - : [...existingUnifiedTabs, unifiedTab] - }, - groupsByWorktree: { - ...groupsByWorktree, - [worktreeId]: updateGroup(cleanedGroups, { - ...cleanedTargetGroup, - activeTabId: shouldActivate - ? unifiedTab.id - : (cleanedGroupActiveTabId ?? unifiedTab.id), - tabOrder: nextGroupOrder, - recentTabIds: nextRecent - }) - }, - activeGroupIdByWorktree: nextActiveGroupIdByWorktree, - layoutByWorktree: { - ...s.layoutByWorktree, - [worktreeId]: s.layoutByWorktree[worktreeId] ?? { type: 'leaf', groupId: group.id } - }, + unifiedTabsByWorktree: replaceTabBuckets(current.unifiedTabsByWorktree, [ + [ + worktreeId, + existingTerminalTab ? existingUnifiedTabs : [...existingUnifiedTabs, unifiedTab] + ] + ]), + groupsByWorktree: replaceRecordEntries(current.groupsByWorktree, [ + [ + worktreeId, + updateGroup(cleanedGroups, { + ...cleanedTargetGroup, + activeTabId: shouldActivate + ? unifiedTab.id + : (cleanedGroupActiveTabId ?? unifiedTab.id), + tabOrder: nextGroupOrder, + recentTabIds: nextRecent + }) + ] + ]), + activeGroupIdByWorktree: applyRecordOperations(current.activeGroupIdByWorktree, [ + [worktreeId, nextActiveGroupId ?? null] + ]), + layoutByWorktree: replaceRecordEntries(current.layoutByWorktree, [ + [worktreeId, worktreeLayout ?? { type: 'leaf', groupId: group.id }] + ]), activeTabId: shouldActivate && ownsGlobalSelection(s, worktreeId) ? tab.id @@ -240,26 +262,30 @@ export function createTerminalTabCreationActions( ...orphanCleanupPatch.activeTabIdByWorktree, [worktreeId]: nextActiveTabIdForWorktree }, - ptyIdsByTabId: { - ...orphanCleanupPatch.ptyIdsByTabId, - [tab.id]: options?.initialPtyId ? [options.initialPtyId] : [] - }, - pendingStartupByTabId: options?.pendingStartup - ? { - ...orphanCleanupPatch.pendingStartupByTabId, - [tab.id]: normalizeTabStartupCommand(options.pendingStartup) - } - : orphanCleanupPatch.pendingStartupByTabId, + ptyIdsByTabId: applyRecordOperations(current.ptyIdsByTabId, [ + ...orphanDeletes, + [tab.id, options?.initialPtyId ? [options.initialPtyId] : []] + ]), + runtimePaneTitlesByTabId: applyRecordOperations( + current.runtimePaneTitlesByTabId, + orphanDeletes + ), + pendingStartupByTabId: applyRecordOperations(current.pendingStartupByTabId, [ + ...orphanDeletes, + ...(options?.pendingStartup + ? [[tab.id, normalizeTabStartupCommand(options.pendingStartup)] as const] + : []) + ]), automaticAgentResumeClaimsByTabId: options?.automaticResumeClaim ? { ...orphanCleanupPatch.automaticAgentResumeClaimsByTabId, [tab.id]: options.automaticResumeClaim } : orphanCleanupPatch.automaticAgentResumeClaimsByTabId, - terminalLayoutsByTabId: { - ...orphanCleanupPatch.terminalLayoutsByTabId, - [tab.id]: singlePaneLayoutSnapshot(initialLeafId, options?.initialPtyId) - } + terminalLayoutsByTabId: applyRecordOperations(current.terminalLayoutsByTabId, [ + ...orphanDeletes, + [tab.id, singlePaneLayoutSnapshot(initialLeafId, options?.initialPtyId)] + ]) } }) // Switch point: main writes the tab under these ids before any later command names it. diff --git a/src/renderer/src/store/terminals/terminal-tab-navigation.ts b/src/renderer/src/store/terminals/terminal-tab-navigation.ts index baa48e076c5..391121f581d 100644 --- a/src/renderer/src/store/terminals/terminal-tab-navigation.ts +++ b/src/renderer/src/store/terminals/terminal-tab-navigation.ts @@ -2,6 +2,7 @@ import { resolveActiveTabOwnerWorktreeId } from './active-tab-owner-worktree' import { getTerminalTabOwnerWorktreeId } from './terminal-tab-owner-index' import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' import { ownsGlobalSelection } from '../workspaces/selection/global-selection-owner' +import { replaceTabBuckets } from '../keyed-record-transitions' export function createTerminalTabNavigationActions( set: TerminalStoreSet, @@ -26,7 +27,7 @@ export function createTerminalTabNavigationActions( ...missingTabs ].map((tab, i) => ({ ...tab, sortOrder: i })) return { - tabsByWorktree: { ...s.tabsByWorktree, [worktreeId]: reordered } + tabsByWorktree: replaceTabBuckets(s.tabsByWorktree, [[worktreeId, reordered]]) } }) }, @@ -48,7 +49,7 @@ export function createTerminalTabNavigationActions( ].map((tab, i) => ({ ...tab, sortOrder: i })) return { tabBarOrderByWorktree: newTabBarOrder, - tabsByWorktree: { ...s.tabsByWorktree, [worktreeId]: updatedTabs } + tabsByWorktree: replaceTabBuckets(s.tabsByWorktree, [[worktreeId, updatedTabs]]) } }) }, diff --git a/src/renderer/src/store/terminals/terminal-tab-title-batch.ts b/src/renderer/src/store/terminals/terminal-tab-title-batch.ts index 5848c51b4bc..4462d88d97c 100644 --- a/src/renderer/src/store/terminals/terminal-tab-title-batch.ts +++ b/src/renderer/src/store/terminals/terminal-tab-title-batch.ts @@ -8,6 +8,7 @@ import { import type { Tab } from '../../../../shared/tab-types' import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types' import type { AppState } from '../types' +import { replaceTabBuckets } from '../keyed-record-transitions' import { adoptTerminalTabOwnerMetadataOnlyBuckets, getTerminalTabOwners @@ -138,19 +139,22 @@ function finishTitleStages( return { patch: null, runtimeGraphChanged: false } } const patch: TitlePatch = {} + const stageEntries = [...stages] if (tabsChanged) { - patch.tabsByWorktree = { ...state.tabsByWorktree } + patch.tabsByWorktree = replaceTabBuckets( + state.tabsByWorktree, + stageEntries.flatMap(([worktreeId, stage]) => + stage.tabsChanged ? [[worktreeId, stage.tabs] as const] : [] + ) + ) } if (unifiedTabsChanged) { - patch.unifiedTabsByWorktree = { ...state.unifiedTabsByWorktree } - } - for (const [worktreeId, stage] of stages) { - if (stage.tabsChanged) { - patch.tabsByWorktree![worktreeId] = stage.tabs - } - if (stage.unifiedTabsChanged) { - patch.unifiedTabsByWorktree![worktreeId] = stage.unifiedTabs - } + patch.unifiedTabsByWorktree = replaceTabBuckets( + state.unifiedTabsByWorktree, + stageEntries.flatMap(([worktreeId, stage]) => + stage.unifiedTabsChanged ? [[worktreeId, stage.unifiedTabs] as const] : [] + ) + ) } if (sortEpochIncrement > 0) { patch.sortEpoch = state.sortEpoch + sortEpochIncrement diff --git a/src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts b/src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts index 09112ab3be2..b703084365a 100644 --- a/src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts +++ b/src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts @@ -8,6 +8,7 @@ import { import { resolveAgentPaneAuthorityKey } from '../slices/agent-status/agent-pane-authority' import type { HydrateWorkspaceSessionOptions } from './terminal-contracts' import { omitUnverifiedPtyLossTabIds } from './terminal-unverified-pty-loss' +import { markFullResync, replaceRecordEntries } from '../keyed-record-transitions' export type WorkspaceHydrationPatch = Pick< AppState, @@ -103,6 +104,18 @@ export function transferNormalizedTerminalLayoutPtyOwnership( } } +// Cold path: a full hydration rebuilds every tracked record from the session. +export function markFullWorkspaceHydration( + hydrated: WorkspaceHydrationPatch +): WorkspaceHydrationPatch { + markFullResync(hydrated.tabsByWorktree, 'hydration') + markFullResync(hydrated.sleepingAgentSessionsByPaneKey, 'hydration') + markFullResync(hydrated.pendingReconnectPtyIdByTabId, 'hydration') + markFullResync(hydrated.ptyIdsByTabId, 'hydration') + markFullResync(hydrated.terminalLayoutsByTabId, 'hydration') + return hydrated +} + export function targetScopedWorkspaceHydrationPatch( state: AppState, hydrated: WorkspaceHydrationPatch, @@ -131,10 +144,9 @@ export function targetScopedWorkspaceHydrationPatch( state.unverifiedPtyLossTabIds, deletedTargetTabIds ) - const pendingReconnectPtyIdByTabId = replaceHydratedRecordKeys( + const pendingReconnectPtyIdByTabId = replaceRecordEntries( state.pendingReconnectPtyIdByTabId, - {}, - targetTabIds + [...targetTabIds].map((tabId) => [tabId, null] as const) ) const activeOutsideScope = state.activeWorktreeId != null && !workspaceKeys.has(state.activeWorktreeId) @@ -152,6 +164,7 @@ export function targetScopedWorkspaceHydrationPatch( everActivatedWorktreeIds.add(workspaceKey) } } + // Cold path: scoped hydration filters out the target keys and re-appends them from the session. return { activeRepoId: activeOutsideScope ? state.activeRepoId : hydrated.activeRepoId, activeWorktreeId: activeOutsideScope ? state.activeWorktreeId : hydrated.activeWorktreeId, @@ -165,10 +178,9 @@ export function targetScopedWorkspaceHydrationPatch( hydrated.activeTabIdByWorktree, workspaceKeys ), - tabsByWorktree: replaceHydratedRecordKeys( - state.tabsByWorktree, - hydrated.tabsByWorktree, - workspaceKeys + tabsByWorktree: markFullResync( + replaceHydratedRecordKeys(state.tabsByWorktree, hydrated.tabsByWorktree, workspaceKeys), + 'hydration' ), lastVisitedAtByWorktreeId: replaceHydratedRecordKeys( state.lastVisitedAtByWorktreeId, @@ -192,7 +204,7 @@ export function targetScopedWorkspaceHydrationPatch( hydrated.automaticAgentResumeClaimsByTabId, targetTabIds ), - sleepingAgentSessionsByPaneKey, + sleepingAgentSessionsByPaneKey: markFullResync(sleepingAgentSessionsByPaneKey, 'hydration'), pendingReconnectWorktreeIds: [ ...state.pendingReconnectWorktreeIds.filter((key) => !workspaceKeys.has(key)), ...hydrated.pendingReconnectWorktreeIds.filter((key) => workspaceKeys.has(key)) @@ -207,15 +219,17 @@ export function targetScopedWorkspaceHydrationPatch( ...(nextUnverifiedPtyLossTabIds !== state.unverifiedPtyLossTabIds ? { unverifiedPtyLossTabIds: nextUnverifiedPtyLossTabIds } : {}), - ptyIdsByTabId: replaceHydratedRecordKeys( - state.ptyIdsByTabId, - hydrated.ptyIdsByTabId, - targetTabIds + ptyIdsByTabId: markFullResync( + replaceHydratedRecordKeys(state.ptyIdsByTabId, hydrated.ptyIdsByTabId, targetTabIds), + 'hydration' ), - terminalLayoutsByTabId: replaceHydratedRecordKeys( - state.terminalLayoutsByTabId, - hydrated.terminalLayoutsByTabId, - targetTabIds + terminalLayoutsByTabId: markFullResync( + replaceHydratedRecordKeys( + state.terminalLayoutsByTabId, + hydrated.terminalLayoutsByTabId, + targetTabIds + ), + 'hydration' ), localOnlyScrollbackByTabId: replaceHydratedRecordKeys( state.localOnlyScrollbackByTabId, diff --git a/src/renderer/src/store/terminals/workspace-terminal-hydration.ts b/src/renderer/src/store/terminals/workspace-terminal-hydration.ts index 2e15762cc3f..c6369a3a2a7 100644 --- a/src/renderer/src/store/terminals/workspace-terminal-hydration.ts +++ b/src/renderer/src/store/terminals/workspace-terminal-hydration.ts @@ -1,3 +1,4 @@ +import { markFullResync } from '@/store/keyed-record-transitions' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { type WorkspaceKey, @@ -14,6 +15,7 @@ import { import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' import { buildRuntimeSessionPlaceholders } from './workspace-terminal-placeholders' import { + markFullWorkspaceHydration, targetScopedWorkspaceHydrationPatch, transferNormalizedTerminalLayoutPtyOwnership, type TerminalLayoutPtyOwnershipTransfer, @@ -197,7 +199,10 @@ export function createWorkspaceTerminalHydrationActions( // Why: seed hydrated active worktrees so the first activation has a Back target. worktreeNavHistory: activeWorktreeId ? [activeWorktreeId] : [], worktreeNavHistoryIndex: activeWorktreeId ? 0 : -1, - ptyIdsByTabId: Object.fromEntries(allTabs.map((tab) => [tab.id, []] as const)), + ptyIdsByTabId: markFullResync( + Object.fromEntries(allTabs.map((tab) => [tab.id, []] as const)), + 'hydration' + ), terminalLayoutsByTabId: buildWorkspaceTerminalLayoutPlan({ ownershipTransfersByTabId, ownershipTransferTabIds, @@ -214,7 +219,7 @@ export function createWorkspaceTerminalHydrationActions( } return options?.replaceWorkspaceKeys ? targetScopedWorkspaceHydrationPatch(s, hydrated, session, options) - : hydrated + : markFullWorkspaceHydration(hydrated) }) for (const [tabId, transfers] of ownershipTransfersByTabId) { transferNormalizedTerminalLayoutPtyOwnership(get(), tabId, transfers) diff --git a/src/renderer/src/store/terminals/workspace-terminal-reconnect.ts b/src/renderer/src/store/terminals/workspace-terminal-reconnect.ts index 3be0e12a57c..824472531a7 100644 --- a/src/renderer/src/store/terminals/workspace-terminal-reconnect.ts +++ b/src/renderer/src/store/terminals/workspace-terminal-reconnect.ts @@ -4,6 +4,7 @@ import { buildWorktreeByIdIndex } from './workspace-terminal-worktree-index' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' import { selectWorktreesByRepo } from '../workspaces/catalog/workspace-record-fields' +import { markFullResync, recordDraft, tabBucketDraft } from '../keyed-record-transitions' export function createWorkspaceTerminalReconnectActions( set: TerminalStoreSet, @@ -28,13 +29,14 @@ export function createWorkspaceTerminalReconnectActions( workspaceSessionReady: true, pendingReconnectWorktreeIds: [], pendingReconnectTabByWorktree: {}, - pendingReconnectPtyIdByTabId: {} + // Cold path: the whole reconnect inventory is consumed. + pendingReconnectPtyIdByTabId: markFullResync({}, 'reconnect-inventory') }) return } // Why: defer daemon attachment for real dimensions; eager 80×24 flushes garble output. - let reconnectedTabsByWorktree: Record | null = null - let reconnectedPtyIdsByTabId: Record | null = null + const reconnectedTabsByWorktree = tabBucketDraft(tabsByWorktree) + const reconnectedPtyIdsByTabId = recordDraft(ptyIdsByTabId) // No writes/awaits in the loop, so one store-snapshot index serves every iteration. const worktreeById = buildWorktreeByIdIndex(selectWorktreesByRepo(get())) const repoById = buildByIdIndex(get().repos) @@ -65,17 +67,16 @@ export function createWorkspaceTerminalReconnectActions( : [] if (allPtyIds.length > 0) { // Why: hide-sleeping reads ptyIdsByTabId for liveness; restored daemon sessions run before their pane remounts, so advertise them. - reconnectedPtyIdsByTabId ??= { ...ptyIdsByTabId } - reconnectedPtyIdsByTabId[tabId] = allPtyIds + reconnectedPtyIdsByTabId.set(tabId, allPtyIds) } if (tabLevelPtyId) { - reconnectedTabsByWorktree ??= { ...tabsByWorktree } - const nextTabs = reconnectedTabsByWorktree[worktreeId] + const nextTabs = reconnectedTabsByWorktree.get(worktreeId) if (!nextTabs) { continue } - reconnectedTabsByWorktree[worktreeId] = nextTabs.map((t) => - t.id === tabId ? { ...t, ptyId: tabLevelPtyId } : t + reconnectedTabsByWorktree.set( + worktreeId, + nextTabs.map((t) => (t.id === tabId ? { ...t, ptyId: tabLevelPtyId } : t)) ) } } @@ -110,14 +111,17 @@ export function createWorkspaceTerminalReconnectActions( if (signal?.aborted) { return } + const nextTabsByWorktree = reconnectedTabsByWorktree.finish() + const nextPtyIdsByTabId = reconnectedPtyIdsByTabId.finish() set({ // Only each row's ptyId changes, a field the frame merge leaves to the window. - ...(reconnectedTabsByWorktree ? { tabsByWorktree: reconnectedTabsByWorktree } : {}), - ...(reconnectedPtyIdsByTabId ? { ptyIdsByTabId: reconnectedPtyIdsByTabId } : {}), + ...(nextTabsByWorktree !== tabsByWorktree ? { tabsByWorktree: nextTabsByWorktree } : {}), + ...(nextPtyIdsByTabId !== ptyIdsByTabId ? { ptyIdsByTabId: nextPtyIdsByTabId } : {}), workspaceSessionReady: true, pendingReconnectWorktreeIds: [], pendingReconnectTabByWorktree: {}, - pendingReconnectPtyIdByTabId: {}, + // Cold path: the whole reconnect inventory is consumed. + pendingReconnectPtyIdByTabId: markFullResync({}, 'reconnect-inventory'), deferredSshSessionIdsByTabId }) } diff --git a/src/renderer/src/store/testing/app-store-test-fixture.ts b/src/renderer/src/store/testing/app-store-test-fixture.ts index 99e2e459142..75587a48103 100644 --- a/src/renderer/src/store/testing/app-store-test-fixture.ts +++ b/src/renderer/src/store/testing/app-store-test-fixture.ts @@ -52,6 +52,7 @@ import { createRemoteServerUpdatesSlice } from '../slices/runtime-host-updates/r import { createTerminalQuickCommandHostsSlice } from '../terminals/terminal-quick-command-hosts' import { createStructuredSessionLaunchDirectorySlice } from '../slices/agent-status/structured-session-launch-directories' import { createStructuredChatSleptAtSlice } from '../slices/agent-status/structured-chat-slept-at' +import { createStructuredChatCompanionWritesSlice } from '../slices/agent-status/structured-chat-companion-writes' import { createWorkspaceAttentionSlice } from '../slices/workspace-attention/workspace-attention-slice' import { createEphemeralVmLifecycleSlice } from '../slices/ephemeral-vm/ephemeral-vm-lifecycle' import '@/i18n/i18n' @@ -118,6 +119,7 @@ export function createTestStore( ...createTerminalQuickCommandHostsSlice(...a), ...createStructuredSessionLaunchDirectorySlice(...a), ...createStructuredChatSleptAtSlice(...a), + ...createStructuredChatCompanionWritesSlice(...a), ...createWorkspaceAttentionSlice(...a), ...createEphemeralVmLifecycleSlice(...a) }), diff --git a/src/renderer/src/store/types.ts b/src/renderer/src/store/types.ts index ae33ff2ac20..946f34993d3 100644 --- a/src/renderer/src/store/types.ts +++ b/src/renderer/src/store/types.ts @@ -49,6 +49,7 @@ import type { RemoteServerUpdatesSlice } from './slices/runtime-host-updates/rem import type { TerminalQuickCommandHostsSlice } from './terminals/terminal-quick-command-hosts' import type { StructuredSessionLaunchDirectorySlice } from './slices/agent-status/structured-session-launch-directories' import type { StructuredChatSleptAtSlice } from './slices/agent-status/structured-chat-slept-at' +import type { StructuredChatCompanionWritesSlice } from './slices/agent-status/structured-chat-companion-writes' import type { EphemeralVmLifecycleSlice } from './slices/ephemeral-vm/ephemeral-vm-lifecycle' import type { WorkspaceAttentionSlice } from './slices/workspace-attention/workspace-attention-contract' @@ -101,5 +102,6 @@ export type AppState = RepoSlice & TerminalQuickCommandHostsSlice & StructuredSessionLaunchDirectorySlice & StructuredChatSleptAtSlice & + StructuredChatCompanionWritesSlice & WorkspaceAttentionSlice & EphemeralVmLifecycleSlice diff --git a/src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts b/src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts index b872513b8c7..cee2dd751b6 100644 --- a/src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts +++ b/src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts @@ -13,6 +13,7 @@ import { type HeldDrawnTabs } from './workspace-layout-frame-held-tabs' import { noteFramesTakingOverStagedBrowserTabs } from './workspace-layout-frame-browser-handover' +import { markFullResync } from '../../keyed-record-transitions' /** Keep window spawn/recovery and live bindings; main publishes saved bindings until it owns live ones. */ const WINDOW_TERMINAL_TAB_FIELDS = [ @@ -146,7 +147,8 @@ export function buildLayoutFrameStorePatch( next = setKey(next, key, value(key)) ?? next } if (next !== state[slice]) { - Object.assign(patch, { [slice]: next }) + // Cold path: main's layout frame is imported over these workspaces. + Object.assign(patch, { [slice]: markFullResync(next, 'host-mirror-frame') }) } } @@ -297,5 +299,9 @@ export function terminalLayoutsPatch( state: Pick, layouts: LayoutFrameStoreState['terminalLayoutsByTabId'] ): Partial { - return layouts === state.terminalLayoutsByTabId ? {} : { terminalLayoutsByTabId: layouts } + if (layouts === state.terminalLayoutsByTabId) { + return {} + } + // Cold path: pane trees are imported from main's layout frames. + return { terminalLayoutsByTabId: markFullResync(layouts, 'host-mirror-frame') } } diff --git a/src/shared/workspace-layout/tab-group-layout-tree.ts b/src/shared/workspace-layout/tab-group-layout-tree.ts index 3f24c6622a5..352b2e89603 100644 --- a/src/shared/workspace-layout/tab-group-layout-tree.ts +++ b/src/shared/workspace-layout/tab-group-layout-tree.ts @@ -96,12 +96,19 @@ export function removeGroupLayoutLeaf( return { ...root, first, second } } +/** Builds a record from `previous` with one entry set, or deleted for null; the renderer passes its seam helper. */ +export type ReplaceRecordEntries = ( + previous: Readonly>, + replacements: Iterable +) => Record + export function collapseGroupLayout( layoutByWorktree: Record, activeGroupIdByWorktree: Record, worktreeId: string, groupId: string, - fallbackGroupId?: string | null + fallbackGroupId: string | null | undefined, + replaceEntries: ReplaceRecordEntries ): { layoutByWorktree: Record activeGroupIdByWorktree: Record @@ -110,20 +117,31 @@ export function collapseGroupLayout( if (!currentLayout) { return { layoutByWorktree, activeGroupIdByWorktree } } - const siblingId = findSiblingGroupId(currentLayout, groupId) - const collapsed = removeGroupLayoutLeaf(currentLayout, groupId) - const nextLayoutByWorktree = { ...layoutByWorktree } - if (collapsed) { - nextLayoutByWorktree[worktreeId] = collapsed - } else { - delete nextLayoutByWorktree[worktreeId] - } + const collapsed = collapseWorktreeGroupLayout( + currentLayout, + activeGroupIdByWorktree[worktreeId], + groupId, + fallbackGroupId + ) return { - layoutByWorktree: nextLayoutByWorktree, - activeGroupIdByWorktree: { - ...activeGroupIdByWorktree, - [worktreeId]: siblingId ?? fallbackGroupId ?? activeGroupIdByWorktree[worktreeId] - } + layoutByWorktree: replaceEntries(layoutByWorktree, [[worktreeId, collapsed.layout]]), + activeGroupIdByWorktree: replaceEntries(activeGroupIdByWorktree, [ + [worktreeId, collapsed.activeGroupId] + ]) + } +} + +/** collapseGroupLayout's values for its one worktree: a null layout deletes the entry. */ +export function collapseWorktreeGroupLayout( + currentLayout: TabGroupLayoutNode, + currentActiveGroupId: A, + groupId: string, + fallbackGroupId?: string | null +): { layout: TabGroupLayoutNode | null; activeGroupId: string | A } { + return { + layout: removeGroupLayoutLeaf(currentLayout, groupId), + activeGroupId: + findSiblingGroupId(currentLayout, groupId) ?? fallbackGroupId ?? currentActiveGroupId } }