diff --git a/src/main/ipc/remote-workspace-snapshot-normalization.test.ts b/src/main/ipc/remote-workspace-snapshot-normalization.test.ts new file mode 100644 index 000000000000..bf44cb47ffb4 --- /dev/null +++ b/src/main/ipc/remote-workspace-snapshot-normalization.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import type { + RemoteWorkspaceSession, + RemoteWorkspaceSnapshot +} from '../../shared/remote-workspace-types' +import { + normalizeSnapshot, + remoteWorkspaceSessionMatchesSnapshot +} from './remote-workspace-snapshot-normalization' + +function emptyRemoteWorkspaceSession(): RemoteWorkspaceSession { + return { + activeWorktreePath: null, + activeTabId: null, + tabsByWorktreePath: {}, + terminalLayoutsByTabId: {} + } +} + +function snapshot(session: RemoteWorkspaceSession, revision = 7): RemoteWorkspaceSnapshot { + return { + namespace: 'target', + revision, + updatedAt: 123, + schemaVersion: 1, + session + } +} + +describe('remote workspace snapshot normalization: close tombstones', () => { + it('closedTabTombstonesByTabId survives normalizeSnapshot', () => { + const raw = snapshot({ + ...emptyRemoteWorkspaceSession(), + closedTabTombstonesByTabId: { + 'tab-ghost': { closedAt: 111, worktreePath: '/home/user/bug-cats' } + } + }) + + const normalized = normalizeSnapshot(raw, 'target') + + expect(normalized.session.closedTabTombstonesByTabId).toEqual({ + 'tab-ghost': { closedAt: 111, worktreePath: '/home/user/bug-cats' } + }) + }) + + it('remoteWorkspaceSessionMatchesSnapshot reports NOT-matching when only tombstones differ', () => { + const base = snapshot(emptyRemoteWorkspaceSession()) + const sessionWithTombstone: RemoteWorkspaceSession = { + ...emptyRemoteWorkspaceSession(), + closedTabTombstonesByTabId: { + 'tab-ghost': { closedAt: 111, worktreePath: '/home/user/bug-cats' } + } + } + + expect(remoteWorkspaceSessionMatchesSnapshot(base, sessionWithTombstone)).toBe(false) + }) + + it('drops invalid tombstone entries while keeping the valid one', () => { + const raw = snapshot({ + ...emptyRemoteWorkspaceSession(), + closedTabTombstonesByTabId: { + 'tab-valid': { closedAt: 111, worktreePath: '/home/user/bug-cats' }, + 'tab-null': null, + 'tab-missing-worktree-path': { closedAt: 222 }, + 'tab-bad-closed-at': { closedAt: 'x', worktreePath: '/home/user/bug-cats' } + } as never + }) + + const normalized = normalizeSnapshot(raw, 'target') + + expect(normalized.session.closedTabTombstonesByTabId).toEqual({ + 'tab-valid': { closedAt: 111, worktreePath: '/home/user/bug-cats' } + }) + }) + + it('normalizes an all-invalid tombstone map to undefined', () => { + const raw = snapshot({ + ...emptyRemoteWorkspaceSession(), + closedTabTombstonesByTabId: { + 'tab-null': null, + 'tab-missing-worktree-path': { closedAt: 222 } + } as never + }) + + const normalized = normalizeSnapshot(raw, 'target') + + expect(normalized.session.closedTabTombstonesByTabId).toBeUndefined() + }) +}) diff --git a/src/main/ipc/remote-workspace-snapshot-normalization.ts b/src/main/ipc/remote-workspace-snapshot-normalization.ts index 1d24063ec4d6..96265c246bab 100644 --- a/src/main/ipc/remote-workspace-snapshot-normalization.ts +++ b/src/main/ipc/remote-workspace-snapshot-normalization.ts @@ -1,5 +1,6 @@ import { isDeepStrictEqual } from 'node:util' import type { + RemoteClosedTabTombstone, RemoteWorkspaceSession, RemoteWorkspaceSnapshot } from '../../shared/remote-workspace-types' @@ -30,6 +31,35 @@ function normalizeOptionalRecord>(value: unkno return Object.keys(value).length > 0 ? (value as T) : undefined } +function isValidRemoteClosedTabTombstone(value: unknown): value is RemoteClosedTabTombstone { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const candidate = value as Partial + return ( + typeof candidate.closedAt === 'number' && + Number.isFinite(candidate.closedAt) && + typeof candidate.worktreePath === 'string' && + candidate.worktreePath.length > 0 + ) +} + +// Why: a corrupt inbound snapshot (e.g. `{"tab-1": null}`) later crashes +// importRemoteWorkspaceSession, which reads tombstone.worktreePath without +// re-checking its shape. Dropping invalid entries here keeps that read safe. +function normalizeClosedTabTombstonesByTabId( + value: unknown +): Record | undefined { + const record = normalizeOptionalRecord>(value) + if (!record) { + return undefined + } + const entries = Object.entries(record).filter(([, tombstone]) => + isValidRemoteClosedTabTombstone(tombstone) + ) as [string, RemoteClosedTabTombstone][] + return entries.length > 0 ? Object.fromEntries(entries) : undefined +} + function normalizeRemoteSession(raw: unknown): RemoteWorkspaceSession { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { return emptyRemoteSession() @@ -62,6 +92,9 @@ function normalizeRemoteSession(raw: unknown): RemoteWorkspaceSession { ), lastVisitedAtByWorktreePath: normalizeOptionalRecord>( input.lastVisitedAtByWorktreePath + ), + closedTabTombstonesByTabId: normalizeClosedTabTombstonesByTabId( + input.closedTabTombstonesByTabId ) } } diff --git a/src/main/orca-profiles/profile-project-session-field-disposition.ts b/src/main/orca-profiles/profile-project-session-field-disposition.ts index d1f9dffa6c46..1ca0c5cade8d 100644 --- a/src/main/orca-profiles/profile-project-session-field-disposition.ts +++ b/src/main/orca-profiles/profile-project-session-field-disposition.ts @@ -121,6 +121,12 @@ export const WORKSPACE_SESSION_FIELD_DISPOSITION = { terminalSurfaceTombstonesByPaneKey: { onRepoRemoval: 'prunedByBespokeRule', onTransfer: 'copiedByBespokeRule' + }, + // Residue: keyed by tab id and pruned by neither path, like remoteSessionIdsByTabId. Bounded + // regardless: the tombstone helpers TTL- and cap-prune the map on every write and merge. + closedTerminalTabTombstonesByTabId: { + onRepoRemoval: 'notRepoScoped', + onTransfer: 'notTransferred' } } as const satisfies Record diff --git a/src/renderer/src/hooks/remote-workspace-session-merge-tombstones.test.ts b/src/renderer/src/hooks/remote-workspace-session-merge-tombstones.test.ts new file mode 100644 index 000000000000..2ec661497cf2 --- /dev/null +++ b/src/renderer/src/hooks/remote-workspace-session-merge-tombstones.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from 'vitest' + +import { mergeDirectSshRemoteWorkspaceSession } from './remote-workspace-session-merge' +import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' +import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' +import type { TerminalTab } from '../../../shared/terminal-tab-types' +import type { AppState } from '../store/types' + +const WORKTREE = 'repo-1::/home/user/bug-cats' + +function terminalTab(id: string, overrides: Partial = {}): TerminalTab { + return { + id, + title: id, + type: 'terminal', + worktreeId: WORKTREE, + ...overrides + } as TerminalTab +} + +function sessionState(overrides: Partial = {}): WorkspaceSessionState { + return { + activeRepoId: 'repo-1', + activeWorktreeId: WORKTREE, + activeWorkspaceKey: worktreeWorkspaceKey(WORKTREE), + activeTabId: 'agent', + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + activeTabIdByWorktree: {}, + ...overrides + } as WorkspaceSessionState +} + +function merge( + current: WorkspaceSessionState, + remote: WorkspaceSessionState, + liveTabs: AppState['tabsByWorktree'] = {} +): WorkspaceSessionState { + return mergeDirectSshRemoteWorkspaceSession( + current, + remote, + new Set([WORKTREE]), + liveTabs, + new Set() + ) +} + +describe('direct-SSH pull merge: closed-tab tombstones', () => { + it('a remote tab with a local tombstone is not re-inserted', () => { + const ghost = terminalTab('tab-ghost') + const current = sessionState({ + tabsByWorktree: { [WORKTREE]: [] }, + closedTerminalTabTombstonesByTabId: { + 'tab-ghost': { closedAt: Date.now(), worktreeId: WORKTREE } + } + }) + const remote = sessionState({ + tabsByWorktree: { [WORKTREE]: [ghost] }, + terminalLayoutsByTabId: { 'tab-ghost': { type: 'single', tabId: 'tab-ghost' } as never } + }) + + const merged = merge(current, remote, { [WORKTREE]: [] }) + + expect(merged.tabsByWorktree[WORKTREE] ?? []).toEqual([]) + expect(merged.terminalLayoutsByTabId['tab-ghost']).toBeUndefined() + expect(merged.closedTerminalTabTombstonesByTabId?.['tab-ghost']).toBeDefined() + }) + + it('a remote tombstone kills the matching local tab-list entry too', () => { + const tabX = terminalTab('tab-x') + const current = sessionState({ + tabsByWorktree: { [WORKTREE]: [tabX] } + }) + const remote = sessionState({ + tabsByWorktree: {}, + closedTerminalTabTombstonesByTabId: { + 'tab-x': { closedAt: Date.now(), worktreeId: WORKTREE } + } + }) + + const merged = merge(current, remote, {}) + + expect((merged.tabsByWorktree[WORKTREE] ?? []).map((t) => t.id)).not.toContain('tab-x') + }) + + it('a live local tab invalidates a stale tombstone for its id', () => { + const tabLive = terminalTab('tab-live') + const current = sessionState({ + tabsByWorktree: { [WORKTREE]: [tabLive] }, + closedTerminalTabTombstonesByTabId: { + 'tab-live': { closedAt: Date.now(), worktreeId: WORKTREE } + } + }) + const remote = sessionState({ + tabsByWorktree: { [WORKTREE]: [tabLive] } + }) + + const merged = merge(current, remote, { [WORKTREE]: [tabLive] }) + + expect((merged.tabsByWorktree[WORKTREE] ?? []).map((t) => t.id)).toContain('tab-live') + expect(merged.closedTerminalTabTombstonesByTabId?.['tab-live']).toBeUndefined() + }) + + it('a tombstone wins over preserveLocalTerminalTabIds when the tab is not live locally', () => { + // preserveLocalTerminalTabIds (recovery tabs) only matters for a REMOTE tab that also exists + // locally with a newer generation — it never revives a tab the tombstone filter already dropped. + const ghost = terminalTab('tab-recovery-ghost') + const current = sessionState({ + tabsByWorktree: { [WORKTREE]: [] }, + closedTerminalTabTombstonesByTabId: { + 'tab-recovery-ghost': { closedAt: Date.now(), worktreeId: WORKTREE } + } + }) + const remote = sessionState({ + tabsByWorktree: { [WORKTREE]: [ghost] } + }) + + const merged = mergeDirectSshRemoteWorkspaceSession( + current, + remote, + new Set([WORKTREE]), + {}, + new Set(['tab-recovery-ghost']) + ) + + expect((merged.tabsByWorktree[WORKTREE] ?? []).map((t) => t.id)).not.toContain( + 'tab-recovery-ghost' + ) + }) + + it('clears activeTabId and activeTabIdByWorktree entries that name a tombstoned tab', () => { + const ghost = terminalTab('tab-ghost') + const survivor = terminalTab('tab-survivor') + const current = sessionState({ + tabsByWorktree: { [WORKTREE]: [] } + }) + const remote = sessionState({ + tabsByWorktree: { [WORKTREE]: [ghost, survivor] }, + activeTabId: 'tab-ghost', + activeTabIdByWorktree: { [WORKTREE]: 'tab-ghost' }, + closedTerminalTabTombstonesByTabId: { + 'tab-ghost': { closedAt: Date.now(), worktreeId: WORKTREE } + } + }) + + const merged = merge(current, remote, { [WORKTREE]: [] }) + + expect(merged.activeTabId).toBeNull() + expect(merged.activeTabIdByWorktree?.[WORKTREE]).toBeNull() + }) + + it('a non-tombstoned active tab id passes through unchanged', () => { + const survivor = terminalTab('tab-survivor') + const current = sessionState({ + tabsByWorktree: { [WORKTREE]: [] } + }) + const remote = sessionState({ + tabsByWorktree: { [WORKTREE]: [survivor] }, + activeTabId: 'tab-survivor', + activeTabIdByWorktree: { [WORKTREE]: 'tab-survivor' } + }) + + const merged = merge(current, remote, { [WORKTREE]: [] }) + + expect(merged.activeTabId).toBe('tab-survivor') + expect(merged.activeTabIdByWorktree?.[WORKTREE]).toBe('tab-survivor') + }) + + it('without any tombstone the local-survival trade is unchanged', () => { + // Copied from remote-workspace-session-merge-local-survival.test.ts: the host still lists a tab + // closed elsewhere, and absence alone must keep letting it survive. + const agent = terminalTab('agent') + const closedElsewhere = terminalTab('closed-elsewhere') + const current = sessionState({ tabsByWorktree: { [WORKTREE]: [agent, closedElsewhere] } }) + const remote = sessionState({ tabsByWorktree: { [WORKTREE]: [agent] } }) + + const merged = merge(current, remote, { [WORKTREE]: [agent, closedElsewhere] }) + + expect(merged.tabsByWorktree[WORKTREE].map((tab) => tab.id)).toContain('closed-elsewhere') + }) +}) diff --git a/src/renderer/src/hooks/remote-workspace-session-merge.ts b/src/renderer/src/hooks/remote-workspace-session-merge.ts index 731b14120681..d2586fd7757e 100644 --- a/src/renderer/src/hooks/remote-workspace-session-merge.ts +++ b/src/renderer/src/hooks/remote-workspace-session-merge.ts @@ -1,6 +1,7 @@ import type { TerminalTab } from '../../../shared/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' import type { ExecutionHostId } from '../../../shared/execution-host' +import { mergeClosedTerminalTabTombstones } from '../../../shared/closed-terminal-tab-tombstones' import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' import { splitWorktreeId } from '../../../shared/worktree/id' import { @@ -33,6 +34,23 @@ export function mergeDirectSshRemoteWorkspaceSession( .flatMap((worktreeId) => liveTabsByWorktree[worktreeId] ?? []) .map((tab) => [tab.id, tab]) ) + // Why merged first: a tombstone from either side must beat that same side's + // stale tab list. A live local tab overrides its own tombstone for THIS + // merge pass — the id is a uuid, so a live tab under a tombstoned id means + // the tombstone is stale (e.g. a close that was undone before it ever + // persisted), not a revival. This is not a durable deletion: it is + // recomputed every pass while the tab stays live, because hydration + // re-unions the store's own tombstone map back in afterwards. + const closedTombstones = Object.fromEntries( + Object.entries( + mergeClosedTerminalTabTombstones( + current.closedTerminalTabTombstonesByTabId, + remote.closedTerminalTabTombstonesByTabId, + Date.now() + ) + ).filter(([tabId]) => !currentTabsById.has(tabId)) + ) + const isTombstoned = (tabId: string): boolean => tabId in closedTombstones const locallyPreservedTabIds = new Set() const localTabsFor = (worktreeId: string): TerminalTab[] => liveTabsByWorktree[worktreeId] ?? current.tabsByWorktree[worktreeId] ?? [] @@ -92,19 +110,21 @@ export function mergeDirectSshRemoteWorkspaceSession( const tabsByWorktree = Object.fromEntries( orderedWorktreeIds.map((worktreeId) => { const remoteTabs = remote.tabsByWorktree[worktreeId] ?? [] - const reconciled = remoteTabs.map((tab) => { - const local = currentTabsById.get(tab.id) - if ( - !local || - ((local.generation ?? 0) <= (tab.generation ?? 0) && - !local.pendingActivationSpawn && - !preserveLocalTerminalTabIds.has(tab.id)) - ) { - return tab - } - locallyPreservedTabIds.add(tab.id) - return preserveNewerLocalTerminalFields(tab, local) - }) + const reconciled = remoteTabs + .filter((tab) => !isTombstoned(tab.id)) + .map((tab) => { + const local = currentTabsById.get(tab.id) + if ( + !local || + ((local.generation ?? 0) <= (tab.generation ?? 0) && + !local.pendingActivationSpawn && + !preserveLocalTerminalTabIds.has(tab.id)) + ) { + return tab + } + locallyPreservedTabIds.add(tab.id) + return preserveNewerLocalTerminalFields(tab, local) + }) for (const tab of reconciled) { emittedTabIds.add(tab.id) } @@ -128,6 +148,9 @@ export function mergeDirectSshRemoteWorkspaceSession( if (remoteKnownTabIds.has(tab.id) || emittedTabIds.has(tab.id)) { return false } + if (isTombstoned(tab.id)) { + return false + } const localSessionId = current.remoteSessionIdsByTabId?.[tab.id] return localSessionId == null || !remoteKnownSessionIds.has(localSessionId) }) @@ -179,7 +202,7 @@ export function mergeDirectSshRemoteWorkspaceSession( ), ...Object.fromEntries( Object.entries(remote.terminalLayoutsByTabId).filter( - ([tabId]) => !locallyPreservedTabIds.has(tabId) + ([tabId]) => !locallyPreservedTabIds.has(tabId) && !isTombstoned(tabId) ) ) } @@ -216,11 +239,28 @@ export function mergeDirectSshRemoteWorkspaceSession( : activeWorktreeId ? worktreeWorkspaceKey(activeWorktreeId) : null, - activeTabId: activeOutsideTarget ? current.activeTabId : remote.activeTabId, - tabsByWorktree: { - ...omitTargetWorktrees(current.tabsByWorktree), - ...tabsByWorktree - }, + // Why nulling here is still safe despite the null-deselect contract above: + // hydration re-picks a valid tab whenever activeTabId is null, and the + // duplicate-tab repair pass already tolerates a null activeTabId — so a + // tombstoned id is treated the same as a deliberate deselect rather than + // surfacing a dead reference downstream. + activeTabId: + !activeOutsideTarget && remote.activeTabId != null && isTombstoned(remote.activeTabId) + ? null + : activeOutsideTarget + ? current.activeTabId + : remote.activeTabId, + // Why sweeping the WHOLE map (not just replaceWorktreeIds) is safe: this + // function's sole caller applies the merge through target-scoped + // hydration, which replaces only `workspaceKeys` (targetScopedWorkspaceHydrationPatch + // in workspace-terminal-hydration-patch.ts) — so an out-of-scope worktree + // entry produced here is never consumed, and filtering it too costs nothing. + tabsByWorktree: Object.fromEntries( + Object.entries({ + ...omitTargetWorktrees(current.tabsByWorktree), + ...tabsByWorktree + }).map(([worktreeId, tabs]) => [worktreeId, tabs.filter((tab) => !isTombstoned(tab.id))]) + ), terminalLayoutsByTabId, activeWorktreeIdsOnShutdown: [ ...(current.activeWorktreeIdsOnShutdown ?? []).filter((id) => !replaceWorktreeIds.has(id)), @@ -236,7 +276,15 @@ export function mergeDirectSshRemoteWorkspaceSession( return localActiveTabId == null ? [] : [[worktreeId, localActiveTabId] as const] }) ), - ...remote.activeTabIdByWorktree + // Why nulling a tombstoned entry is safe here too: same reasoning as + // activeTabId above — hydration re-picks a valid tab and the + // duplicate-tab repair pass tolerates the null. + ...Object.fromEntries( + Object.entries(remote.activeTabIdByWorktree ?? {}).map(([worktreeId, tabId]) => [ + worktreeId, + tabId != null && isTombstoned(tabId) ? null : tabId + ]) + ) }, remoteSessionIdsByTabId: { ...Object.fromEntries( @@ -246,7 +294,7 @@ export function mergeDirectSshRemoteWorkspaceSession( ), ...Object.fromEntries( Object.entries(remote.remoteSessionIdsByTabId ?? {}).filter( - ([tabId]) => !locallyPreservedTabIds.has(tabId) + ([tabId]) => !locallyPreservedTabIds.has(tabId) && !isTombstoned(tabId) ) ) }, @@ -257,7 +305,9 @@ export function mergeDirectSshRemoteWorkspaceSession( defaultTerminalTabsAppliedByWorktreeId: { ...omitTargetWorktrees(current.defaultTerminalTabsAppliedByWorktreeId), ...remote.defaultTerminalTabsAppliedByWorktreeId - } + }, + closedTerminalTabTombstonesByTabId: + Object.keys(closedTombstones).length > 0 ? closedTombstones : undefined } } diff --git a/src/renderer/src/lib/session-write-subscriber.test.ts b/src/renderer/src/lib/session-write-subscriber.test.ts index 535a151e658a..6645e8d89f9a 100644 --- a/src/renderer/src/lib/session-write-subscriber.test.ts +++ b/src/renderer/src/lib/session-write-subscriber.test.ts @@ -632,6 +632,36 @@ describe('createSessionWriteSubscriber', () => { cleanup() }) + it('defers (not drops) a change made while persistence is suppressed', () => { + const persist = vi.fn<(payload: WorkspaceSessionWrite) => void>() + let gateOpen = false + const cleanup = createSessionWriteSubscriber({ + store: useAppStore, + persist, + shouldSchedulePersist: () => gateOpen + }) + + useAppStore.setState({ + workspaceSessionReady: true, + hydrationSucceeded: true, + ...makeTerminalSessionState('shell') + }) + vi.advanceTimersByTime(200) + expect(persist).not.toHaveBeenCalled() + + useAppStore.setState({ tabsByWorktree: { 'wt-1': [] } }) + vi.advanceTimersByTime(200) + + expect(persist).not.toHaveBeenCalled() + + gateOpen = true + vi.advanceTimersByTime(200) + + expect(persist).toHaveBeenCalledTimes(1) + expect(persist.mock.calls[0][0].patch.tabsByWorktree?.['wt-1']).toEqual([]) + cleanup() + }) + it('coalesces multiple relevant mutations within a debounce window', () => { const persist = vi.fn<(payload: WorkspaceSessionWrite) => void>() const cleanup = createSessionWriteSubscriber({ store: useAppStore, persist }) diff --git a/src/renderer/src/lib/session-write-subscriber.ts b/src/renderer/src/lib/session-write-subscriber.ts index 6e2eda4ed1f5..61ab16acd46d 100644 --- a/src/renderer/src/lib/session-write-subscriber.ts +++ b/src/renderer/src/lib/session-write-subscriber.ts @@ -112,6 +112,42 @@ export function createSessionWriteSubscriber({ const terminalTabsProjection = createTerminalSessionTabsProjection() const unifiedTabsProjection = createUnifiedSessionTabsProjection() + // Why: rebuild from the freshest store state rather than the snapshot + // captured when this timer was scheduled. Today this is equivalent + // because buildWorkspaceSessionPayload reads only SESSION_RELEVANT_FIELDS + // (the same fields gating the timer reset), so the captured `state` is + // already current for those fields. Calling getState() guards against a + // future refactor that adds a non-relevant field read to the payload + // builder — without this, such a change would silently start emitting + // stale values for that field. + const flush = (): void => { + timer = null + const fresh = store.getState() + if (!shouldPersistWorkspaceSession(fresh)) { + pendingChangedFields.clear() + return + } + if (shouldSchedulePersist && !shouldSchedulePersist()) { + // Why defer instead of drop: pendingChangedFields already absorbed any + // changes made while the gate was closed (e.g. a tab close during a + // snapshot apply) — clearing it here would lose that change forever. + // Keep rescheduling until the gate reopens. This is a behavior change + // from stop-to-poll: while the gate stays closed, flush now + // self-reschedules every debounceMs instead of going idle; bounded in + // practice because apply depth decrements in a finally and the + // trailing window is 1s. + timer = setTimeout(flush, debounceMs) + return + } + const changed = new Set(pendingChangedFields) + pendingChangedFields.clear() + const patch = buildWorkspaceSessionPatch(fresh, changed) + if (Object.keys(patch).length === 0) { + return + } + persist({ patch }) + } + const unsub = store.subscribe((state) => { if (!shouldPersistWorkspaceSession(state)) { return @@ -138,43 +174,21 @@ export function createSessionWriteSubscriber({ pendingChangedFields.add(field) } if (shouldSchedulePersist && !shouldSchedulePersist()) { + // Why defer instead of drop: `prev` above has already absorbed this + // change, so clearing the pending fields would lose it forever — a tab + // close made during a snapshot apply would never reach the session file + // or the remote mirror. Keep the fields and keep rescheduling until the + // gate reopens; the timer body re-checks the gate. if (timer !== null) { clearTimeout(timer) - timer = null } - pendingChangedFields.clear() + timer = setTimeout(flush, debounceMs) return } if (timer !== null) { clearTimeout(timer) } - timer = setTimeout(() => { - timer = null - // Why: rebuild from the freshest store state rather than the snapshot - // captured when this timer was scheduled. Today this is equivalent - // because buildWorkspaceSessionPayload reads only SESSION_RELEVANT_FIELDS - // (the same fields gating the timer reset), so the captured `state` is - // already current for those fields. Calling getState() guards against a - // future refactor that adds a non-relevant field read to the payload - // builder — without this, such a change would silently start emitting - // stale values for that field. - const fresh = store.getState() - if (!shouldPersistWorkspaceSession(fresh)) { - pendingChangedFields.clear() - return - } - if (shouldSchedulePersist && !shouldSchedulePersist()) { - pendingChangedFields.clear() - return - } - const changed = new Set(pendingChangedFields) - pendingChangedFields.clear() - const patch = buildWorkspaceSessionPatch(fresh, changed) - if (Object.keys(patch).length === 0) { - return - } - persist({ patch }) - }, debounceMs) + timer = setTimeout(flush, debounceMs) }) return () => { diff --git a/src/renderer/src/lib/workspace-session-browser-history.test.ts b/src/renderer/src/lib/workspace-session-browser-history.test.ts index c8c4c53480e0..152642f65aea 100644 --- a/src/renderer/src/lib/workspace-session-browser-history.test.ts +++ b/src/renderer/src/lib/workspace-session-browser-history.test.ts @@ -32,7 +32,8 @@ function createSnapshot(browserUrlHistory: BrowserHistoryEntry[]): WorkspaceSess worktreesByRepo: {}, lastKnownRelayPtyIdByTabId: {}, lastVisitedAtByWorktreeId: {}, - defaultTerminalTabsAppliedByWorktreeId: {} + defaultTerminalTabsAppliedByWorktreeId: {}, + closedTerminalTabTombstonesByTabId: {} } } diff --git a/src/renderer/src/lib/workspace-session-closed-tab-tombstones.ts b/src/renderer/src/lib/workspace-session-closed-tab-tombstones.ts new file mode 100644 index 000000000000..6dbc214e9c6f --- /dev/null +++ b/src/renderer/src/lib/workspace-session-closed-tab-tombstones.ts @@ -0,0 +1,11 @@ +import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' +import { pruneClosedTerminalTabTombstones } from '../../../shared/closed-terminal-tab-tombstones' + +/** Prunes the tombstone map for persistence. */ +// Why: omit an empty map, matching the defaultTerminalTabsAppliedByWorktreeId pattern. +export function buildPersistedClosedTabTombstones( + map: WorkspaceSessionState['closedTerminalTabTombstonesByTabId'] +): WorkspaceSessionState['closedTerminalTabTombstonesByTabId'] { + const pruned = pruneClosedTerminalTabTombstones(map, Date.now()) + return Object.keys(pruned).length > 0 ? pruned : undefined +} diff --git a/src/renderer/src/lib/workspace-session-editor-drafts.test.ts b/src/renderer/src/lib/workspace-session-editor-drafts.test.ts index ff740b6f5f8d..c1292a9c74db 100644 --- a/src/renderer/src/lib/workspace-session-editor-drafts.test.ts +++ b/src/renderer/src/lib/workspace-session-editor-drafts.test.ts @@ -34,6 +34,7 @@ function createSnapshot( lastKnownRelayPtyIdByTabId: {}, lastVisitedAtByWorktreeId: {}, defaultTerminalTabsAppliedByWorktreeId: {}, + closedTerminalTabTombstonesByTabId: {}, ...overrides } } diff --git a/src/renderer/src/lib/workspace-session-host-field-ownership.ts b/src/renderer/src/lib/workspace-session-host-field-ownership.ts index b24e7118c02a..272d05a8a36d 100644 --- a/src/renderer/src/lib/workspace-session-host-field-ownership.ts +++ b/src/renderer/src/lib/workspace-session-host-field-ownership.ts @@ -39,6 +39,8 @@ export const WORKSPACE_SESSION_FIELD_OWNERSHIP = { activeGroupIdByWorktree: 'worktreeKeyed', lastVisitedAtByWorktreeId: 'worktreeKeyed', defaultTerminalTabsAppliedByWorktreeId: 'worktreeKeyed', + // Why: tombstones are keyed by tab id and record which worktree the closed tab belonged to. + closedTerminalTabTombstonesByTabId: 'tabKeyed', activeWorkspaceKey: 'global', activeWorktreeIdsOnShutdown: 'worktreeArray', terminalLayoutsByTabId: 'tabKeyed', diff --git a/src/renderer/src/lib/workspace-session-liveness.test.ts b/src/renderer/src/lib/workspace-session-liveness.test.ts index f714230c2f9d..6c10d2d0c541 100644 --- a/src/renderer/src/lib/workspace-session-liveness.test.ts +++ b/src/renderer/src/lib/workspace-session-liveness.test.ts @@ -33,6 +33,7 @@ function createSnapshot( lastKnownRelayPtyIdByTabId: {}, lastVisitedAtByWorktreeId: {}, defaultTerminalTabsAppliedByWorktreeId: {}, + closedTerminalTabTombstonesByTabId: {}, ...overrides } } diff --git a/src/renderer/src/lib/workspace-session-patch.ts b/src/renderer/src/lib/workspace-session-patch.ts index 5558aab409a6..dea0b32c48ce 100644 --- a/src/renderer/src/lib/workspace-session-patch.ts +++ b/src/renderer/src/lib/workspace-session-patch.ts @@ -7,7 +7,6 @@ import { normalizeBrowserHistoryEntries } from '../../../shared/workspace-sessio import { buildActiveConnectionIdsAtShutdown, buildEditorSessionData, - buildSanitizedTabsByWorktree, buildTerminalSessionData, type WorkspaceSessionSnapshot } from './workspace-session' @@ -16,6 +15,8 @@ import { buildPersistedBrowserTabsByWorktree } from './workspace-session-browser-tabs' import { withoutStagedBrowserTabs } from './workspace-session-staged-browser-tabs' +import { buildPersistedClosedTabTombstones } from './workspace-session-closed-tab-tombstones' +import { buildSanitizedTabsByWorktree } from './workspace-session-tabs-sanitize' import { buildPersistedUnifiedTabSessionData } from './workspace-session-unified-tabs' import { buildLastVisitedAtByWorktreeId } from './workspace-session-focus-recency' import { buildSleepingAgentSessionData } from './workspace-session-sleeping-agents' @@ -160,6 +161,11 @@ export function buildWorkspaceSessionPatch( ? snapshot.defaultTerminalTabsAppliedByWorktreeId : undefined } + if (changed.has('closedTerminalTabTombstonesByTabId')) { + patch.closedTerminalTabTombstonesByTabId = buildPersistedClosedTabTombstones( + snapshot.closedTerminalTabTombstonesByTabId + ) + } if (changed.has('sleepingAgentSessionsByPaneKey')) { patch.sleepingAgentSessionsByPaneKey = buildSleepingAgentSessionData(snapshot).sleepingAgentSessionsByPaneKey diff --git a/src/renderer/src/lib/workspace-session-relevant-fields.test.ts b/src/renderer/src/lib/workspace-session-relevant-fields.test.ts index abed4b44e017..e20f4195d3ee 100644 --- a/src/renderer/src/lib/workspace-session-relevant-fields.test.ts +++ b/src/renderer/src/lib/workspace-session-relevant-fields.test.ts @@ -34,6 +34,7 @@ describe('SESSION_RELEVANT_FIELDS', () => { lastKnownRelayPtyIdByTabId: true, lastVisitedAtByWorktreeId: true, defaultTerminalTabsAppliedByWorktreeId: true, + closedTerminalTabTombstonesByTabId: true, sleepingAgentSessionsByPaneKey: true, clientHostedBrowserCloseIntentsByEnvironment: true } diff --git a/src/renderer/src/lib/workspace-session-tabs-sanitize.ts b/src/renderer/src/lib/workspace-session-tabs-sanitize.ts new file mode 100644 index 000000000000..c702785e32e9 --- /dev/null +++ b/src/renderer/src/lib/workspace-session-tabs-sanitize.ts @@ -0,0 +1,18 @@ +import type { TerminalTab } from '../../../shared/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' + +export function buildSanitizedTabsByWorktree( + tabsByWorktree: Record +): WorkspaceSessionState['tabsByWorktree'] { + // Why: strip transient pendingActivationSpawn — session:set persists without Zod re-parse, so a stale flag would drop the first PTY spawn on restart. + return Object.fromEntries( + Object.entries(tabsByWorktree).map(([worktreeId, tabs]) => [ + worktreeId, + tabs.map((tab) => { + const { pendingActivationSpawn: _unused, ...rest } = tab + void _unused + return rest + }) + ]) + ) +} diff --git a/src/renderer/src/lib/workspace-session-tombstone-roundtrip.test.ts b/src/renderer/src/lib/workspace-session-tombstone-roundtrip.test.ts new file mode 100644 index 000000000000..80cf7724d50c --- /dev/null +++ b/src/renderer/src/lib/workspace-session-tombstone-roundtrip.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { buildWorkspaceSessionPatch } from './workspace-session-patch' +import { SESSION_RELEVANT_FIELDS } from './workspace-session' + +describe('closed tab tombstones in the persisted session', () => { + it('is a session-relevant field', () => { + expect(SESSION_RELEVANT_FIELDS).toContain('closedTerminalTabTombstonesByTabId') + }) + + // Why browserPagesByWorkspace is stubbed: buildWorkspaceSessionPatch pre-filters staged + // browser tabs (withoutStagedBrowserTabs) before field dispatch, so the minimal fixture + // must carry the map it iterates. + it('patch includes pruned tombstones when the field changed', () => { + const snapshot = { + browserPagesByWorkspace: {}, + closedTerminalTabTombstonesByTabId: { + 'tab-1': { closedAt: Date.now(), worktreeId: 'wt-1' } + } + } as never + const patch = buildWorkspaceSessionPatch(snapshot, ['closedTerminalTabTombstonesByTabId']) + expect(patch.closedTerminalTabTombstonesByTabId).toEqual({ + 'tab-1': expect.objectContaining({ worktreeId: 'wt-1' }) + }) + }) + + it('patch omits the field when the map is empty', () => { + const snapshot = { + browserPagesByWorkspace: {}, + closedTerminalTabTombstonesByTabId: {} + } as never + const patch = buildWorkspaceSessionPatch(snapshot, ['closedTerminalTabTombstonesByTabId']) + expect(patch.closedTerminalTabTombstonesByTabId).toBeUndefined() + }) +}) diff --git a/src/renderer/src/lib/workspace-session.ts b/src/renderer/src/lib/workspace-session.ts index 59debdfc9a77..36aa0acce123 100644 --- a/src/renderer/src/lib/workspace-session.ts +++ b/src/renderer/src/lib/workspace-session.ts @@ -10,6 +10,8 @@ import type { OpenFile } from '../store/slices/editor' import { buildPersistedUnifiedTabSessionData } from './workspace-session-unified-tabs' import { buildLastVisitedAtByWorktreeId } from './workspace-session-focus-recency' import { buildSleepingAgentSessionData } from './workspace-session-sleeping-agents' +import { buildPersistedClosedTabTombstones } from './workspace-session-closed-tab-tombstones' +import { buildSanitizedTabsByWorktree } from './workspace-session-tabs-sanitize' import { buildActiveConnectionIdsAtShutdown } from './workspace-session-reconnect-targets' import { withoutStagedBrowserTabs } from './workspace-session-staged-browser-tabs' import { buildBrowserSessionData } from './workspace-session-browser-tabs' @@ -53,6 +55,7 @@ export type WorkspaceSessionSnapshot = Pick< | 'lastKnownRelayPtyIdByTabId' | 'lastVisitedAtByWorktreeId' | 'defaultTerminalTabsAppliedByWorktreeId' + | 'closedTerminalTabTombstonesByTabId' > & { activeWorkspaceExecutionHostId?: AppState['activeWorkspaceExecutionHostId'] sleepingAgentSessionsByPaneKey?: AppState['sleepingAgentSessionsByPaneKey'] @@ -90,6 +93,7 @@ export const SESSION_RELEVANT_FIELDS = [ 'lastKnownRelayPtyIdByTabId', 'lastVisitedAtByWorktreeId', 'defaultTerminalTabsAppliedByWorktreeId', + 'closedTerminalTabTombstonesByTabId', 'sleepingAgentSessionsByPaneKey', 'clientHostedBrowserCloseIntentsByEnvironment' ] as const satisfies readonly (keyof WorkspaceSessionSnapshot)[] @@ -189,22 +193,6 @@ export function buildEditorSessionData( } } -export function buildSanitizedTabsByWorktree( - tabsByWorktree: WorkspaceSessionSnapshot['tabsByWorktree'] -): WorkspaceSessionState['tabsByWorktree'] { - // Why: strip transient pendingActivationSpawn — session:set persists without Zod re-parse, so a stale flag would drop the first PTY spawn on restart. - return Object.fromEntries( - Object.entries(tabsByWorktree).map(([worktreeId, tabs]) => [ - worktreeId, - tabs.map((tab) => { - const { pendingActivationSpawn: _unused, ...rest } = tab - void _unused - return rest - }) - ]) - ) -} - export function buildTerminalSessionData( snapshot: WorkspaceSessionSnapshot ): Pick { @@ -303,6 +291,9 @@ export function buildWorkspaceSessionPayload( Object.keys(snapshot.defaultTerminalTabsAppliedByWorktreeId).length > 0 ? snapshot.defaultTerminalTabsAppliedByWorktreeId : undefined, + closedTerminalTabTombstonesByTabId: buildPersistedClosedTabTombstones( + snapshot.closedTerminalTabTombstonesByTabId + ), ...buildSleepingAgentSessionData(snapshot), // Why unconditional rather than omit-when-empty: a full write replaces the persisted object, // so an emptied map has to be written as empty or the last replay never sticks. diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 4286dd0ac53d..1e1a4b3e699f 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -49,6 +49,7 @@ export const createTerminalSlice: StateCreator workspaceSessionReady: false, restoredRuntimeHostIdByWorkspaceSessionKey: {}, defaultTerminalTabsAppliedByWorktreeId: {}, + closedTerminalTabTombstonesByTabId: {}, hydrationSucceeded: false, pendingReconnectWorktreeIds: [], pendingReconnectTabByWorktree: {}, diff --git a/src/renderer/src/store/terminals/terminal-state.ts b/src/renderer/src/store/terminals/terminal-state.ts index 5f754cc64630..4d5cbea82567 100644 --- a/src/renderer/src/store/terminals/terminal-state.ts +++ b/src/renderer/src/store/terminals/terminal-state.ts @@ -1,3 +1,4 @@ +import type { ClosedTerminalTabTombstonesByTabId } from '../../../../shared/closed-terminal-tab-tombstones' import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types' import type { TuiAgent } from '../../../../shared/tui-agent' import type { SetupSplitDirection } from '../../../../shared/worktree/launch-types' @@ -90,6 +91,7 @@ export type TerminalState = { workspaceSessionReady: boolean restoredRuntimeHostIdByWorkspaceSessionKey: Record defaultTerminalTabsAppliedByWorktreeId: Record + closedTerminalTabTombstonesByTabId: ClosedTerminalTabTombstonesByTabId hydrationSucceeded: boolean pendingReconnectWorktreeIds: string[] pendingReconnectTabByWorktree: Record diff --git a/src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts b/src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts new file mode 100644 index 000000000000..5173687c8ed4 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-tab-close-tombstone.test.ts @@ -0,0 +1,74 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import type * as AgentStatusModule from '@/lib/agent-status' +import { createTestStore, makeTab, makeWorktree, seedStore } from '../slices/store-test-helpers' +import { createStoreCascadesMockApi } from '../slices/store-cascades-test-harness' + +const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => [])) +const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn()) + +// Mock sonner (imported by repos.ts) +vi.mock('sonner', () => ({ + toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } +})) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown, + unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers +})) + +// Mock agent-status (imported by terminal-helpers) +vi.mock('@/lib/agent-status', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) + } +}) + +const mockApi = createStoreCascadesMockApi() + +describe('closeTab tombstone recording', () => { + beforeEach(() => { + vi.clearAllMocks() + mockApi.worktrees.updateMeta.mockResolvedValue({}) + }) + + it('user close records a tombstone for the closed tab', () => { + const store = createTestStore() + const wt = 'wt-1' + + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] + }, + tabsByWorktree: { + [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })] + } + }) + + store.getState().closeTab('tab-1') + + const tombstone = store.getState().closedTerminalTabTombstonesByTabId['tab-1'] + expect(tombstone).toBeDefined() + expect(tombstone.worktreeId).toBe(wt) + expect(tombstone.closedAt).toBeGreaterThan(0) + }) + + it('pty-exit close does not record a tombstone', () => { + const store = createTestStore() + const wt = 'wt-1' + + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] + }, + tabsByWorktree: { + [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })] + } + }) + + store.getState().closeTab('tab-1', { reason: 'pty-exit' }) + + expect(store.getState().closedTerminalTabTombstonesByTabId['tab-1']).toBeUndefined() + }) +}) diff --git a/src/renderer/src/store/terminals/terminal-tab-close.ts b/src/renderer/src/store/terminals/terminal-tab-close.ts index cea5f0bc4742..7211e5e08899 100644 --- a/src/renderer/src/store/terminals/terminal-tab-close.ts +++ b/src/renderer/src/store/terminals/terminal-tab-close.ts @@ -1,3 +1,4 @@ +import { recordClosedTerminalTabTombstone } from '../../../../shared/closed-terminal-tab-tombstones' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import { sweepRetiredTerminalTabState } from '../slices/retired-terminal-tab-state-sweep' import { @@ -58,6 +59,18 @@ export function createTerminalTabCloseActions( next[wId] = after } } + // Why: only a deliberate close (user/cleanup) is a durable "never + // bring this back" signal; a pty-exit close is the process ending, + // not the user retiring the tab. + const nextClosedTombstones = + retiresSession && closedWorktreeId + ? recordClosedTerminalTabTombstone( + s.closedTerminalTabTombstonesByTabId, + tabId, + closedWorktreeId, + Date.now() + ) + : s.closedTerminalTabTombstonesByTabId // Why: only explicit user closes feed the Cmd+Shift+T reopen stack; cleanup/PTY-exit closes must not pollute undo history. const closedPosition = closedWorktreeId && closedTab @@ -207,6 +220,9 @@ export function createTerminalTabCloseActions( ...(nextSleepingAgentSessionsByPaneKey !== s.sleepingAgentSessionsByPaneKey ? { sleepingAgentSessionsByPaneKey: nextSleepingAgentSessionsByPaneKey } : {}), + ...(nextClosedTombstones !== s.closedTerminalTabTombstonesByTabId + ? { closedTerminalTabTombstonesByTabId: nextClosedTombstones } + : {}), // Why: skip writing unreadTerminalTabs when unchanged to avoid a no-op state allocation that re-evaluates full-state selectors. Mirrors tabs.ts. ...(nextUnreadTerminalTabs !== s.unreadTerminalTabs ? { unreadTerminalTabs: nextUnreadTerminalTabs } 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 46fb906a9b95..f613db20b272 100644 --- a/src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts +++ b/src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts @@ -19,6 +19,7 @@ export type WorkspaceHydrationPatch = Pick< | 'worktreesByRepo' | 'lastVisitedAtByWorktreeId' | 'defaultTerminalTabsAppliedByWorktreeId' + | 'closedTerminalTabTombstonesByTabId' | 'automaticAgentResumeClaimsByTabId' | 'sleepingAgentSessionsByPaneKey' | 'pendingReconnectWorktreeIds' @@ -176,6 +177,8 @@ export function targetScopedWorkspaceHydrationPatch( hydrated.defaultTerminalTabsAppliedByWorktreeId, workspaceKeys ), + // Why: already unioned with local state in hydration.ts, so pass it through as-is here. + closedTerminalTabTombstonesByTabId: hydrated.closedTerminalTabTombstonesByTabId, automaticAgentResumeClaimsByTabId: replaceHydratedRecordKeys( state.automaticAgentResumeClaimsByTabId, hydrated.automaticAgentResumeClaimsByTabId, diff --git a/src/renderer/src/store/terminals/workspace-terminal-hydration.ts b/src/renderer/src/store/terminals/workspace-terminal-hydration.ts index 6d6169a22f42..9ccf1e395305 100644 --- a/src/renderer/src/store/terminals/workspace-terminal-hydration.ts +++ b/src/renderer/src/store/terminals/workspace-terminal-hydration.ts @@ -1,5 +1,6 @@ import type { WorkspaceKey } from '../../../../shared/folder-workspace-types' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { mergeClosedTerminalTabTombstones } from '../../../../shared/closed-terminal-tab-tombstones' import { folderWorkspaceKey, parseWorkspaceKey, @@ -178,6 +179,13 @@ export function createWorkspaceTerminalHydrationActions( lastVisitedAtByWorktreeId: session.lastVisitedAtByWorktreeId ?? {}, defaultTerminalTabsAppliedByWorktreeId: session.defaultTerminalTabsAppliedByWorktreeId ?? {}, + // Why union instead of replace: hydration must not erase a tombstone + // the user just created locally while the snapshot was in flight. + closedTerminalTabTombstonesByTabId: mergeClosedTerminalTabTombstones( + s.closedTerminalTabTombstonesByTabId, + session.closedTerminalTabTombstonesByTabId, + Date.now() + ), automaticAgentResumeClaimsByTabId: {}, sleepingAgentSessionsByPaneKey, pendingReconnectWorktreeIds, diff --git a/src/shared/closed-terminal-tab-tombstones.test.ts b/src/shared/closed-terminal-tab-tombstones.test.ts new file mode 100644 index 000000000000..4d31278132e3 --- /dev/null +++ b/src/shared/closed-terminal-tab-tombstones.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { + CLOSED_TAB_TOMBSTONE_TTL_MS, + MAX_CLOSED_TAB_TOMBSTONES, + mergeClosedTerminalTabTombstones, + pruneClosedTerminalTabTombstones, + recordClosedTerminalTabTombstone +} from './closed-terminal-tab-tombstones' + +const NOW = 1_800_000_000_000 + +describe('closed terminal tab tombstones', () => { + it('records a tombstone with the closing worktree and timestamp', () => { + const map = recordClosedTerminalTabTombstone({}, 'tab-1', 'wt-1', NOW) + expect(map).toEqual({ 'tab-1': { closedAt: NOW, worktreeId: 'wt-1' } }) + }) + + it('merge keeps the union and the newer closedAt per tab id', () => { + const a = { 'tab-1': { closedAt: NOW - 1000, worktreeId: 'wt-1' } } + const b = { + 'tab-1': { closedAt: NOW, worktreeId: 'wt-1' }, + 'tab-2': { closedAt: NOW - 500, worktreeId: 'wt-2' } + } + expect(mergeClosedTerminalTabTombstones(a, b, NOW)).toEqual({ + 'tab-1': { closedAt: NOW, worktreeId: 'wt-1' }, + 'tab-2': { closedAt: NOW - 500, worktreeId: 'wt-2' } + }) + }) + + it('prune drops entries older than the TTL', () => { + const map = { + fresh: { closedAt: NOW - 1000, worktreeId: 'wt-1' }, + stale: { closedAt: NOW - CLOSED_TAB_TOMBSTONE_TTL_MS - 1, worktreeId: 'wt-1' } + } + expect(pruneClosedTerminalTabTombstones(map, NOW)).toEqual({ + fresh: { closedAt: NOW - 1000, worktreeId: 'wt-1' } + }) + }) + + it('prune caps the map at the newest MAX entries', () => { + const map = Object.fromEntries( + Array.from({ length: MAX_CLOSED_TAB_TOMBSTONES + 10 }, (_, i) => [ + `tab-${i}`, + { closedAt: NOW - i, worktreeId: 'wt-1' } + ]) + ) + const pruned = pruneClosedTerminalTabTombstones(map, NOW) + expect(Object.keys(pruned)).toHaveLength(MAX_CLOSED_TAB_TOMBSTONES) + expect(pruned['tab-0']).toBeDefined() + expect(pruned[`tab-${MAX_CLOSED_TAB_TOMBSTONES + 9}`]).toBeUndefined() + }) + + it('merge tolerates undefined inputs', () => { + expect(mergeClosedTerminalTabTombstones(undefined, undefined, NOW)).toEqual({}) + }) +}) diff --git a/src/shared/closed-terminal-tab-tombstones.ts b/src/shared/closed-terminal-tab-tombstones.ts new file mode 100644 index 000000000000..a4b7e844796d --- /dev/null +++ b/src/shared/closed-terminal-tab-tombstones.ts @@ -0,0 +1,58 @@ +/** Why this exists: the remote workspace snapshot cannot distinguish "never + * uploaded" from "closed by the user" by absence alone (see the trade + * documented in remote-workspace-session-merge.ts). A tombstone is the + * explicit close signal that lets the pull merge drop a tab the user closed + * without ever deleting a tab the host merely has not been told about. + * Tab ids are uuids and reopen (Cmd+Shift+T) mints a fresh id, so a closed + * id never legitimately reappears — keying on tabId is safe. */ +export type ClosedTerminalTabTombstone = { + closedAt: number + worktreeId: string +} + +export type ClosedTerminalTabTombstonesByTabId = Record + +export const CLOSED_TAB_TOMBSTONE_TTL_MS = 30 * 24 * 60 * 60 * 1000 +// Why a cap on top of the TTL: a heavy multi-workspace user can close far more +// tabs in 30 days than the snapshot should carry; newest-first keeps the ones +// still able to race a stale snapshot. +export const MAX_CLOSED_TAB_TOMBSTONES = 500 + +/** Drops tombstones past the TTL and caps the rest at MAX_CLOSED_TAB_TOMBSTONES, + * keeping the newest so a heavy multi-workspace user's map stays bounded. */ +export function pruneClosedTerminalTabTombstones( + map: ClosedTerminalTabTombstonesByTabId | undefined, + now: number +): ClosedTerminalTabTombstonesByTabId { + const entries = Object.entries(map ?? {}).filter( + ([, tombstone]) => now - tombstone.closedAt <= CLOSED_TAB_TOMBSTONE_TTL_MS + ) + entries.sort(([, a], [, b]) => b.closedAt - a.closedAt) + return Object.fromEntries(entries.slice(0, MAX_CLOSED_TAB_TOMBSTONES)) +} + +/** Records the close as a tombstone for the given tab and prunes the map in the same pass. */ +export function recordClosedTerminalTabTombstone( + map: ClosedTerminalTabTombstonesByTabId | undefined, + tabId: string, + worktreeId: string, + now: number +): ClosedTerminalTabTombstonesByTabId { + return pruneClosedTerminalTabTombstones({ ...map, [tabId]: { closedAt: now, worktreeId } }, now) +} + +/** Combines two tombstone maps, keeping the newer closedAt on a shared tab id, then prunes. */ +export function mergeClosedTerminalTabTombstones( + a: ClosedTerminalTabTombstonesByTabId | undefined, + b: ClosedTerminalTabTombstonesByTabId | undefined, + now: number +): ClosedTerminalTabTombstonesByTabId { + const merged: ClosedTerminalTabTombstonesByTabId = { ...a } + for (const [tabId, tombstone] of Object.entries(b ?? {})) { + const existing = merged[tabId] + if (!existing || tombstone.closedAt > existing.closedAt) { + merged[tabId] = tombstone + } + } + return pruneClosedTerminalTabTombstones(merged, now) +} diff --git a/src/shared/remote-workspace-session-projection-tombstones.test.ts b/src/shared/remote-workspace-session-projection-tombstones.test.ts new file mode 100644 index 000000000000..5b11aacb6e16 --- /dev/null +++ b/src/shared/remote-workspace-session-projection-tombstones.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import { + exportRemoteWorkspaceSession, + importRemoteWorkspaceSession +} from './remote-workspace-session-projection' +import { getDefaultWorkspaceSession } from './constants' + +const NOW = 1_800_000_000_000 +// worktreeId ↔ worktreePath 규약은 splitWorktreeId를 따른다. 기존 projection +// 테스트의 worktreeId 픽스처를 재사용해 유효한 id/path 쌍을 만든다. +const WT_ID = 'repo-a::/srv/app' +const WT_PATH = '/srv/app' +const OTHER_WT_ID = 'repo-local::/tmp/local' + +describe('remote projection of closed tab tombstones', () => { + it('export carries tombstones for target worktrees as worktreePath entries', () => { + const session = { + ...getDefaultWorkspaceSession(), + closedTerminalTabTombstonesByTabId: { + 'tab-1': { closedAt: NOW, worktreeId: WT_ID }, + 'tab-2': { closedAt: NOW, worktreeId: OTHER_WT_ID } + } + } + const remote = exportRemoteWorkspaceSession(session, { + isTargetWorktree: (id) => id === WT_ID + }) + expect(remote.closedTabTombstonesByTabId).toEqual({ + 'tab-1': { closedAt: NOW, worktreePath: WT_PATH } + }) + }) + + it('import resolves tombstones back to worktree ids and drops unresolvable ones', () => { + const local = importRemoteWorkspaceSession( + { + activeWorktreePath: null, + activeTabId: null, + tabsByWorktreePath: {}, + terminalLayoutsByTabId: {}, + closedTabTombstonesByTabId: { + 'tab-1': { closedAt: NOW, worktreePath: WT_PATH }, + 'tab-9': { closedAt: NOW, worktreePath: '/nowhere' } + } + }, + { resolveWorktreeId: (p) => (p === WT_PATH ? WT_ID : null) } + ) + expect(local.closedTerminalTabTombstonesByTabId).toEqual({ + 'tab-1': { closedAt: NOW, worktreeId: WT_ID } + }) + }) +}) diff --git a/src/shared/remote-workspace-session-projection.ts b/src/shared/remote-workspace-session-projection.ts index 32ac87595279..08a576916c08 100644 --- a/src/shared/remote-workspace-session-projection.ts +++ b/src/shared/remote-workspace-session-projection.ts @@ -1,5 +1,9 @@ import { getDefaultWorkspaceSession } from './constants' -import type { RemoteWorkspaceSession, RemoteWorkspaceTerminalTab } from './remote-workspace-types' +import type { + RemoteClosedTabTombstone, + RemoteWorkspaceSession, + RemoteWorkspaceTerminalTab +} from './remote-workspace-types' import type { TerminalTab } from './terminal-tab-types' import type { WorkspaceSessionState } from './workspace-session-state-types' import { splitWorktreeId } from './worktree/id' @@ -109,6 +113,19 @@ export function exportRemoteWorkspaceSession( } } + const closedTabTombstonesByTabId: Record = {} + for (const [tabId, tombstone] of Object.entries( + session.closedTerminalTabTombstonesByTabId ?? {} + )) { + if (!options.isTargetWorktree(tombstone.worktreeId)) { + continue + } + const worktreePath = worktreePathFromId(tombstone.worktreeId) + if (worktreePath) { + closedTabTombstonesByTabId[tabId] = { closedAt: tombstone.closedAt, worktreePath } + } + } + return { activeWorktreePath, activeTabId, @@ -131,7 +148,9 @@ export function exportRemoteWorkspaceSession( ) : undefined, lastVisitedAtByWorktreePath, - defaultTerminalTabsAppliedByWorktreePath + defaultTerminalTabsAppliedByWorktreePath, + closedTabTombstonesByTabId: + Object.keys(closedTabTombstonesByTabId).length > 0 ? closedTabTombstonesByTabId : undefined } } @@ -199,6 +218,19 @@ export function importRemoteWorkspaceSession( } } + const closedTerminalTabTombstonesByTabId: Record< + string, + { closedAt: number; worktreeId: string } + > = {} + for (const [tabId, tombstone] of Object.entries(remote.closedTabTombstonesByTabId ?? {})) { + const worktreeId = resolvePath(tombstone.worktreePath) + // Why dropped when unresolvable: tabs of an unresolvable worktree are + // dropped by this import too, so there is nothing left to protect here. + if (worktreeId) { + closedTerminalTabTombstonesByTabId[tabId] = { closedAt: tombstone.closedAt, worktreeId } + } + } + return { ...session, activeRepoId: activeWorktreeId ? (splitWorktreeId(activeWorktreeId)?.repoId ?? null) : null, @@ -222,6 +254,10 @@ export function importRemoteWorkspaceSession( ) : undefined, lastVisitedAtByWorktreeId, - defaultTerminalTabsAppliedByWorktreeId + defaultTerminalTabsAppliedByWorktreeId, + closedTerminalTabTombstonesByTabId: + Object.keys(closedTerminalTabTombstonesByTabId).length > 0 + ? closedTerminalTabTombstonesByTabId + : undefined } } diff --git a/src/shared/remote-workspace-types.ts b/src/shared/remote-workspace-types.ts index 509ab83b436e..6661dc16e6f7 100644 --- a/src/shared/remote-workspace-types.ts +++ b/src/shared/remote-workspace-types.ts @@ -4,6 +4,11 @@ export type RemoteWorkspaceTerminalTab = Omit & { worktreePath: string } +export type RemoteClosedTabTombstone = { + closedAt: number + worktreePath: string +} + export type RemoteWorkspaceSession = { activeWorktreePath: string | null activeTabId: string | null @@ -14,6 +19,9 @@ export type RemoteWorkspaceSession = { remoteSessionIdsByTabId?: Record lastVisitedAtByWorktreePath?: Record defaultTerminalTabsAppliedByWorktreePath?: Record + /** Explicit close markers so pull merges can tell "closed" from "never + * uploaded"; absent in snapshots written by older builds. */ + closedTabTombstonesByTabId?: Record } export type RemoteWorkspaceSnapshot = { diff --git a/src/shared/workspace-session-state-types.ts b/src/shared/workspace-session-state-types.ts index 5e1191f4b08b..3d427ee26493 100644 --- a/src/shared/workspace-session-state-types.ts +++ b/src/shared/workspace-session-state-types.ts @@ -6,6 +6,7 @@ import type { TerminalLayoutSnapshot, TerminalTab } from './terminal-tab-types' import type { BrowserHistoryEntry, BrowserPage, BrowserWorkspace } from './browser-workspace-types' import type { ClientHostedBrowserCloseIntent } from './client-hosted-browser-close-intent' import type { PersistedClientHostedBrowserPage } from './client-hosted-browser-page-record' +import type { ClosedTerminalTabTombstonesByTabId } from './closed-terminal-tab-tombstones' /** Minimal subset of OpenFile persisted across restarts. * Only edit-mode files are saved — diffs, conflict reviews, and other @@ -124,6 +125,11 @@ export type WorkspaceSessionState = { retiredAt: number } > + /** Explicit user-close markers for terminal tabs, keyed by tab id. The + * direct-SSH pull merge consults these so a tab the user closed is not + * re-inserted from a stale remote snapshot (the resurrection loop in + * #10342). TTL/cap pruning lives in shared/closed-terminal-tab-tombstones. */ + closedTerminalTabTombstonesByTabId?: ClosedTerminalTabTombstonesByTabId } export type WorkspaceSessionPatch = Partial