fix(session): remove a deleted workspace's saved session state (#42580)

* fix(session): drop a removed workspace's saved session state everywhere

Workspace removal is now driven by one per-field table, main's terminal-membership
rebase no longer re-writes empty rows for worktrees the window stopped listing, and
the post-scan local prune also drops saved session state of worktrees whose folders
are gone (keeping unsaved drafts, archived, active and otherwise-owned workspaces).

* fix(session): address review pass 1 on deleted-workspace session cleanup

Match Windows path casing for protected metadata, filter cleanup candidates before
probing paths, batch recency deletion, count only references removal deletes, and
keep paused WSL moves out of repo removal.

* fix(session): keep repo removal's existing WSL freeze guard placement

* fix(session): count only row owners removal can delete

* refactor(session): let repo removal rely on shared owner removal

Drop repo removal's per-field loops that the shared owner removal already covers,
remove type assertions from the new tests, and lower the layout-writer baseline
(net four fewer main-process writers; the new cleanup module adds two).

* refactor(session): read session record rows through a type guard

* fix(session): drop default-tab flags of worktrees a loaded repo no longer lists

QA found the window kept these flags for deleted workspaces and saved them back
after main removed them, so cleanup kept re-selecting those workspaces.

* fix(session): address CodeRabbit on deleted-workspace cleanup

Match unsaved-draft owners path-equivalently, drop rejected unified tab and group
records when the rebase skips a dropped worktree, and pin the POSIX test fixtures'
platform.

* fix(session): address council review on deleted-workspace cleanup

Keep default-tab flags any worktree list still shows, read only eligible
candidates' files for the draft guard, drop a dropped worktree's active-tab entry
in the rebase, and save only the local session after cleanup.

* fix(session): keep a workspace marked archived without an archived checkout

* fix(session): follow the moved workspace-scope module after merging main
This commit is contained in:
Brennan Benson
2026-11-15 15:33:52 -08:00
committed by GitHub
parent 8221969006
commit 9f3fcd65ad
16 changed files with 1001 additions and 191 deletions
+8 -7
View File
@@ -11,7 +11,7 @@
1 src/main/ipc/runtime-environments/catalog/runtime-environment-removal-cleanup.ts
1 src/main/ipc/runtime-environments/catalog/runtime-environment-session-reconcile.ts
2 src/main/ipc/session.ts
6 src/main/orca-profiles/project-transfer/profile-project-session-state.ts
3 src/main/orca-profiles/project-transfer/profile-project-session-state.ts
4 src/main/orca-profiles/project-transfer/profile-project-source-removal.ts
2 src/main/orca-profiles/project-transfer/profile-project-state-file.ts
4 src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts
@@ -19,15 +19,15 @@
9 src/main/orca-profiles/project-transfer/profile-session-owner-transfer.ts
3 src/main/persistence/leasing-ssh-ptys/ssh-pty-binding-cleanup.ts
1 src/main/persistence/loading-store/profile-loading/loaded-state-parsing.ts
1 src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts
1 src/main/persistence/loading-store/profile-preferences/mobile-tab-selection-persistence.ts
1 src/main/persistence/loading-store/profile-loading/normalize-loaded-profile-state.ts
1 src/main/persistence/loading-store/profile-preferences/mobile-tab-selection-persistence.ts
2 src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts
10 src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts
8 src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts
10 src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts
10 src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts
1 src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts
10 src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts
9 src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts
2 src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts
4 src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts
4 src/main/persistence/loading-store/workspace-sessions/workspace-session-terminal-binding-replay.ts
2 src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-client-state.ts
@@ -44,10 +44,11 @@
2 src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-main-rewrite-stores.ts
1 src/main/persistence/restoring-sessions/folder-workspace-operations.ts
1 src/main/persistence/restoring-sessions/invalid-workspace-layout-purge.ts
5 src/main/persistence/restoring-sessions/session-owner-fields.ts
12 src/main/persistence/restoring-sessions/session-owner-removal.ts
3 src/main/persistence/restoring-sessions/session-owner-fields.ts
11 src/main/persistence/restoring-sessions/session-owner-removal.ts
2 src/main/persistence/restoring-sessions/workspace-pane-normalization.ts
4 src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts
2 src/main/persistence/tracking-repos/missing-local-worktree-session-pruning.ts
1 src/main/persistence/tracking-repos/project-group-operations.ts
4 src/main/persistence/tracking-repos/repo-worktree-pruning.ts
3 src/main/persistence/tracking-repos/worktree-identity-migration.ts
+16 -16
View File
@@ -5,6 +5,7 @@
3 src/renderer/src/attention/notification-subject-owner.ts
1 src/renderer/src/components/activity/use-agent-pane-threads.ts
3 src/renderer/src/components/cmd-j/palette-live-status.tsx
4 src/renderer/src/components/floating-terminal/workspace/floating-workspace-terminal-actions.ts
1 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts
1 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-statuses.ts
4 src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-send-target-inputs.ts
@@ -16,8 +17,6 @@
4 src/renderer/src/components/terminal-pane/render-health/recovery/terminal-recovery-ledger-test-store.ts
3 src/renderer/src/components/worktree-jump/state/worktree-jump-palette-status-inputs.ts
1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts
4 src/renderer/src/components/floating-terminal/workspace/floating-workspace-terminal-actions.ts
1 src/renderer/src/runtime/browser/client-hosting/client-hosted-browser-row-state.ts
4 src/renderer/src/lib/workspace/persistence/session-write-subscriber.ts
1 src/renderer/src/lib/workspace/persistence/workspace-session-browser-tabs.ts
7 src/renderer/src/lib/workspace/persistence/workspace-session-host-hydration.ts
@@ -26,6 +25,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
1 src/renderer/src/runtime/browser/client-hosting/client-hosted-browser-row-state.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
@@ -100,23 +100,23 @@
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
5 src/renderer/src/store/terminals/layout/terminal-layout-state.ts
6 src/renderer/src/store/terminals/retirement/terminal-orphan-cleanup.ts
2 src/renderer/src/store/terminals/sleep/terminal-pane-hibernation.ts
3 src/renderer/src/store/terminals/pty/terminal-pty-bindings.ts
2 src/renderer/src/store/terminals/pty/terminal-pty-release.ts
1 src/renderer/src/store/terminals/sleep/terminal-shutdown-guards.ts
3 src/renderer/src/store/terminals/sleep/terminal-shutdown-state.ts
1 src/renderer/src/store/terminals/tabs/creation/terminal-tab-agent-launch-pane.ts
2 src/renderer/src/store/terminals/tabs/presentation/terminal-tab-appearance.ts
6 src/renderer/src/store/terminals/retirement/terminal-tab-close.ts
10 src/renderer/src/store/terminals/tabs/creation/terminal-tab-creation.ts
7 src/renderer/src/store/terminals/tabs/terminal-tab-navigation.ts
3 src/renderer/src/store/terminals/tabs/presentation/terminal-tab-presentation.ts
2 src/renderer/src/store/terminals/tabs/presentation/terminal-tab-title-batch.ts
5 src/renderer/src/store/terminals/hydration/workspace-terminal-hydration-patch.ts
2 src/renderer/src/store/terminals/hydration/workspace-terminal-hydration.ts
2 src/renderer/src/store/terminals/hydration/workspace-terminal-reconnect.ts
5 src/renderer/src/store/terminals/layout/terminal-layout-state.ts
3 src/renderer/src/store/terminals/pty/terminal-pty-bindings.ts
2 src/renderer/src/store/terminals/pty/terminal-pty-release.ts
6 src/renderer/src/store/terminals/retirement/terminal-orphan-cleanup.ts
6 src/renderer/src/store/terminals/retirement/terminal-tab-close.ts
2 src/renderer/src/store/terminals/sleep/terminal-pane-hibernation.ts
1 src/renderer/src/store/terminals/sleep/terminal-shutdown-guards.ts
3 src/renderer/src/store/terminals/sleep/terminal-shutdown-state.ts
1 src/renderer/src/store/terminals/tabs/creation/terminal-tab-agent-launch-pane.ts
10 src/renderer/src/store/terminals/tabs/creation/terminal-tab-creation.ts
2 src/renderer/src/store/terminals/tabs/presentation/terminal-tab-appearance.ts
3 src/renderer/src/store/terminals/tabs/presentation/terminal-tab-presentation.ts
2 src/renderer/src/store/terminals/tabs/presentation/terminal-tab-title-batch.ts
7 src/renderer/src/store/terminals/tabs/terminal-tab-navigation.ts
7 src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-held-tabs.ts
4 src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-slices.ts
12 src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts
@@ -22,7 +22,14 @@ type AuthoritativeLocalMetadataPruneStore = Pick<
Store,
'getRepos' | 'pruneSessionlessMissingLocalWorktreeMetadataForRepo' | 'getProfileStorageDirectory'
> &
Partial<Pick<Store, 'selectProbeableLocalWorktreeMetadataCandidates'>>
Partial<
Pick<
Store,
| 'selectProbeableLocalWorktreeMetadataCandidates'
| 'selectRemovableLocalWorktreeSessionOwnersForRepo'
| 'pruneMissingLocalWorktreeSessionsForRepo'
>
>
export function canPruneAuthoritativeLocalMetadata<
T extends Partial<AuthoritativeLocalMetadataPruneStore>
@@ -105,11 +112,7 @@ export async function pruneMetadataMissingFromAuthoritativeLocalScan({
worktreeRetentionPathComparisonKey(repo.path, platform),
...gitWorktrees.map((worktree) => worktreeRetentionPathComparisonKey(worktree.path, platform))
])
// Advisory eligibility shrinks stat fan-out; deletion still rechecks authoritatively (#17775).
const removableCandidates =
store.selectProbeableLocalWorktreeMetadataCandidates?.(scan) ?? scan.metadata
const probeCandidates = removableCandidates.flatMap((metadata) => {
const { worktreeId } = metadata
const isProbeable = (worktreeId: string): string | null => {
const parsed = splitWorktreeId(worktreeId)
const nativeAbsolute = parsed
? platform === 'win32'
@@ -123,21 +126,43 @@ export async function pruneMetadataMissingFromAuthoritativeLocalScan({
worktreeId.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR) ||
livePathKeys.has(worktreeRetentionPathComparisonKey(parsed.worktreePath, platform))
) {
return []
return null
}
return [{ metadata, pathValue: parsed.worktreePath }]
return parsed.worktreePath
}
// Advisory eligibility shrinks stat fan-out; deletion still rechecks authoritatively (#17775).
const removableCandidates =
store.selectProbeableLocalWorktreeMetadataCandidates?.(scan) ?? scan.metadata
const probeCandidates = removableCandidates.flatMap((metadata) => {
const pathValue = isProbeable(metadata.worktreeId)
return pathValue ? [{ metadata, pathValue }] : []
})
// Saved session state of a deleted worktree outlives its metadata; probe those owners too.
const sessionCandidates = (
store.selectRemovableLocalWorktreeSessionOwnersForRepo?.(repo.id) ?? []
).flatMap((worktreeId) => {
const pathValue = isProbeable(worktreeId)
return pathValue ? [{ worktreeId, pathValue }] : []
})
const presenceByPath = await pathsExistOrAreUnverifiable(
probeCandidates.map(({ pathValue }) => pathValue),
[
...new Set([
...probeCandidates.map(({ pathValue }) => pathValue),
...sessionCandidates.map(({ pathValue }) => pathValue)
])
],
{ signal }
)
if (!generationCurrent() || !isCallerCurrent()) {
return result([], generationCurrent())
}
const missingMetadata = probeCandidates.flatMap(({ metadata, pathValue }) =>
const missingSessionIds = sessionCandidates.flatMap(({ worktreeId, pathValue }) =>
presenceByPath.get(pathValue) === false ? [worktreeId] : []
)
let missingMetadata = probeCandidates.flatMap(({ metadata, pathValue }) =>
presenceByPath.get(pathValue) === false ? [metadata] : []
)
if (missingMetadata.length === 0) {
if (missingMetadata.length === 0 && missingSessionIds.length === 0) {
return result([], generationCurrent())
}
@@ -145,10 +170,25 @@ export async function pruneMetadataMissingFromAuthoritativeLocalScan({
if (!generationCurrent() || !isCallerCurrent() || isWslMoveRepoBlocked(repo)) {
return result([], generationCurrent())
}
const removedIds = store.pruneSessionlessMissingLocalWorktreeMetadataForRepo(
scan,
missingMetadata
const releasedIds = new Set(
missingSessionIds.length > 0
? (store.pruneMissingLocalWorktreeSessionsForRepo?.(scan, missingSessionIds) ?? [])
: []
)
if (releasedIds.size > 0) {
// The advisory filter skipped these rows while a session still owned them.
const probedIds = new Set(probeCandidates.map(({ metadata }) => metadata.worktreeId))
missingMetadata = [
...missingMetadata,
...scan.metadata.filter(
({ worktreeId }) => releasedIds.has(worktreeId) && !probedIds.has(worktreeId)
)
]
}
const removedIds =
missingMetadata.length > 0
? store.pruneSessionlessMissingLocalWorktreeMetadataForRepo(scan, missingMetadata)
: []
if (removedIds.length > 0) {
const snapshotDirectory = store.getProfileStorageDirectory()
const targets: {
@@ -16,108 +16,219 @@ export type SessionFieldTransferDisposition =
/** Source-profile-only entities cannot transfer. */
| 'notTransferred'
export type SessionFieldWorkspaceRemovalDisposition =
/** Delete the removed workspace's key. */
| 'ownerKey'
/** Delete entries keyed by the removed workspace's terminal tab IDs. */
| 'ownerTabKey'
/** Delete `tabId:leafId` entries of the removed workspace's terminal tabs. */
| 'ownerPaneKey'
/** Delete entries whose record names the removed workspace. */
| 'ownerRow'
/** Removed by a rule in removeWorkspaceSessionOwners. */
| 'bespoke'
/** Not workspace-scoped. */
| 'kept'
type SessionFieldDisposition = {
onRepoRemoval: SessionFieldRepoRemovalDisposition
onTransfer: SessionFieldTransferDisposition
onWorkspaceRemoval: SessionFieldWorkspaceRemovalDisposition
}
/** Classify every persisted field so owner-keyed pruning/transfer cannot omit additions.
* Transferable additions still require manual updates to mergeWorkspaceSessions. */
export const WORKSPACE_SESSION_FIELD_DISPOSITION = {
// Residue: renderer reads validate this ID against live repos, so dead IDs resolve to none.
activeRepoId: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
activeWorkspaceKey: { onRepoRemoval: 'prunedByBespokeRule', onTransfer: 'copiedByBespokeRule' },
activeWorkspaceExecutionHostId: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
activeWorktreeId: { onRepoRemoval: 'prunedByBespokeRule', onTransfer: 'copiedByBespokeRule' },
activeRepoId: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
activeWorkspaceKey: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
activeWorkspaceExecutionHostId: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
activeWorktreeId: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
// Owner removal clears this when its tab dies; repo removal can leave it stale.
activeTabId: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
tabsByWorktree: { onRepoRemoval: 'prunedByBespokeRule', onTransfer: 'copiedByBespokeRule' },
activeTabId: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'bespoke'
},
tabsByWorktree: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
// Follow tab IDs removed or carried by terminal maps.
terminalLayoutsByTabId: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerTabKey'
},
localOnlyScrollbackByTabId: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerTabKey'
},
activeWorktreeIdsOnShutdown: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
openFilesByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerKey'
},
activeFileIdByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
openFilesByWorktree: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByBespokeRule' },
activeFileIdByWorktree: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByOwnerKey' },
markdownFrontmatterVisible: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
browserTabsByWorktree: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
// Follow browser workspace IDs resolved above.
browserPagesByWorkspace: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'bespoke'
},
activeBrowserTabIdByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey'
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
// Paired devices/browser profiles are source-scoped; copying rows would strand unavailable tabs.
clientHostedBrowserPagesByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'notTransferred'
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'ownerKey'
},
// Environment cleanup debt outlives individual repos.
clientHostedBrowserCloseIntentsByEnvironment: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred'
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
pairedTerminalTabCloseIntentsByEnvironment: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred'
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
activeTabTypeByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
browserUrlHistory: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
workspaceDocHistory: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
activeTabIdByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
unifiedTabs: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerKey'
},
tabGroups: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerKey'
},
tabGroupLayouts: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
activeGroupIdByWorktree: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
activeConnectionIdsAtShutdown: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'kept'
},
activeTabTypeByWorktree: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByOwnerKey' },
browserUrlHistory: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
workspaceDocHistory: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
activeTabIdByWorktree: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByOwnerKey' },
unifiedTabs: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByBespokeRule' },
tabGroups: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByBespokeRule' },
tabGroupLayouts: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByOwnerKey' },
activeGroupIdByWorktree: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByOwnerKey' },
activeConnectionIdsAtShutdown: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
// Residue: neither path prunes removed tabs’ remote session IDs.
remoteSessionIdsByTabId: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
lastVisitedAtByWorktreeId: { onRepoRemoval: 'prunedByOwnerKey', onTransfer: 'copiedByOwnerKey' },
remoteSessionIdsByTabId: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'ownerTabKey'
},
lastVisitedAtByWorktreeId: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'bespoke'
},
defaultTerminalTabsAppliedByWorktreeId: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey'
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'ownerKey'
},
// Owner scans prune by worktreeId, but cross-profile source removal has no scan and leaves residue.
sleepingAgentSessionsByPaneKey: { onRepoRemoval: 'notRepoScoped', onTransfer: 'notTransferred' },
sleepingAgentSessionsByPaneKey: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'ownerRow'
},
terminalPtyIncarnationsByPaneKey: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerPaneKey'
},
// Owner-key helpers also accept bare repo IDs.
terminalTopologyRevisionByRepoId: {
onRepoRemoval: 'prunedByOwnerKey',
onTransfer: 'copiedByOwnerKey'
onTransfer: 'copiedByOwnerKey',
onWorkspaceRemoval: 'bespoke'
},
terminalSurfaceTombstonesByPaneKey: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
onTransfer: 'copiedByBespokeRule',
onWorkspaceRemoval: 'ownerRow'
},
// Pruned by worktreeId during owner removal; transferred source residue clears on next profile load.
closedTerminalTabTombstonesByTabId: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred'
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'ownerRow'
},
// Owner removal prunes by worktreeId; closed panes do not transfer.
closedTerminalPanesByPaneKey: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred'
onTransfer: 'notTransferred',
onWorkspaceRemoval: 'ownerRow'
}
} as const satisfies Record<keyof WorkspaceSessionState, SessionFieldDisposition>
@@ -140,3 +251,11 @@ export const SESSION_FIELDS_PRUNED_BY_OWNER_KEY = SESSION_FIELDS.filter(
export const SESSION_FIELDS_COPIED_BY_OWNER_KEY = SESSION_FIELDS.filter(
(field) => WORKSPACE_SESSION_FIELD_DISPOSITION[field].onTransfer === 'copiedByOwnerKey'
)
export function sessionFieldsRemovedWithWorkspace(
disposition: SessionFieldWorkspaceRemovalDisposition
): (keyof WorkspaceSessionState)[] {
return SESSION_FIELDS.filter(
(field) => WORKSPACE_SESSION_FIELD_DISPOSITION[field].onWorkspaceRemoval === disposition
)
}
@@ -2,8 +2,11 @@ import { getDefaultWorkspaceSession } from '../../../shared/constants'
import type { ExecutionHostId } from '../../../shared/execution-host'
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
import { parseWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope'
import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from './profile-project-session-field-disposition'
import { markdownFileIdCandidates } from './profile-session-markdown-transfer'
import {
SESSION_FIELDS_PRUNED_BY_OWNER_KEY,
sessionFieldsRemovedWithWorkspace
} from './profile-project-session-field-disposition'
import { removeWorkspaceSessionOwners } from '../../persistence/restoring-sessions/session-owner-removal'
import {
isRepoWorktreeId,
ownerKeyBelongsToRepo,
@@ -148,54 +151,27 @@ export function removeRepoFromWorkspaceSession(
session: WorkspaceSessionState | undefined,
repoId: string
): WorkspaceSessionState {
const next = structuredClone(session ?? getDefaultWorkspaceSession())
const removedTerminalTabIds = new Set<string>()
const removedMarkdownFileIds = new Set<string>()
for (const [ownerKey, files] of Object.entries(next.openFilesByWorktree ?? {})) {
if (!ownerKeyBelongsToRepo(ownerKey, repoId)) {
continue
}
for (const file of files) {
markdownFileIdCandidates(file.filePath, ownerKey, file.runtimeEnvironmentId).forEach((id) =>
removedMarkdownFileIds.add(id)
)
}
}
for (const [ownerKey, tabs] of Object.entries(next.tabsByWorktree)) {
if (!ownerKeyBelongsToRepo(ownerKey, repoId)) {
continue
}
tabs.forEach((tab) => removedTerminalTabIds.add(tab.id))
delete next.tabsByWorktree[ownerKey]
}
for (const tabId of removedTerminalTabIds) {
delete next.terminalLayoutsByTabId[tabId]
delete next.localOnlyScrollbackByTabId?.[tabId]
}
const removedBrowserWorkspaceIds = new Set<string>()
for (const [ownerKey, workspaces] of Object.entries(next.browserTabsByWorktree ?? {})) {
if (!ownerKeyBelongsToRepo(ownerKey, repoId)) {
continue
}
workspaces.forEach((workspace) => removedBrowserWorkspaceIds.add(workspace.id))
delete next.browserTabsByWorktree![ownerKey]
}
if (next.browserPagesByWorkspace) {
for (const workspaceId of removedBrowserWorkspaceIds) {
delete next.browserPagesByWorkspace[workspaceId]
const base = session ?? getDefaultWorkspaceSession()
// Workspace removal owns the per-workspace field census, including tab, pane and file entries;
// the rules below cover keys no workspace owner names (bare repo IDs, orphaned rows).
const ownerKeys = new Set<string>()
for (const field of [
'tabsByWorktree',
'browserTabsByWorktree',
...sessionFieldsRemovedWithWorkspace('ownerKey')
] as const) {
for (const ownerKey of Object.keys(base[field] ?? {})) {
if (ownerKeyBelongsToRepo(ownerKey, repoId)) {
ownerKeys.add(ownerKey)
}
}
}
const next =
ownerKeys.size > 0 ? removeWorkspaceSessionOwners(base, ownerKeys)! : structuredClone(base)
for (const field of SESSION_FIELDS_PRUNED_BY_OWNER_KEY) {
const record = next[field] as Record<string, unknown> | undefined
;(next as Record<string, unknown>)[field] = removeRepoWorktreeRecord(record, repoId)
}
if (next.markdownFrontmatterVisible) {
next.markdownFrontmatterVisible = Object.fromEntries(
Object.entries(next.markdownFrontmatterVisible).filter(
([fileId]) => !removedMarkdownFileIds.has(fileId)
)
)
}
if (next.terminalSurfaceTombstonesByPaneKey) {
next.terminalSurfaceTombstonesByPaneKey = Object.fromEntries(
Object.entries(next.terminalSurfaceTombstonesByPaneKey).filter(
@@ -203,14 +179,6 @@ export function removeRepoFromWorkspaceSession(
)
)
}
if (next.terminalPtyIncarnationsByPaneKey) {
next.terminalPtyIncarnationsByPaneKey = Object.fromEntries(
Object.entries(next.terminalPtyIncarnationsByPaneKey).filter(([paneKey]) => {
const separator = paneKey.lastIndexOf(':')
return separator < 1 || !removedTerminalTabIds.has(paneKey.slice(0, separator))
})
)
}
if (next.activeWorktreeId && isRepoWorktreeId(repoId, next.activeWorktreeId)) {
next.activeWorktreeId = null
}
@@ -28,6 +28,13 @@ import {
} from '../../restoring-sessions/session-owner-removal'
import type { StoreRuntimeState } from '../store-runtime-state'
import { WORKSPACE_SESSION_DOMAINS } from '../../workspace-session-domains'
import {
pruneMissingLocalWorktreeSessionsForRepo as pruneMissingLocalWorktreeSessions,
selectLocalWorktreeSessionOwnersForRepo,
selectRemovableLocalWorktreeSessionOwners
} from '../../tracking-repos/missing-local-worktree-session-pruning'
import type { NativeLocalWorktreeMetadataScanExpectation } from '../../tracking-repos/local-worktree-metadata-scan-expectation'
import { type WriteSchedulingOperations, scheduleSave } from '../profile-writing/write-scheduling'
import {
@@ -138,6 +145,35 @@ export class SessionHostPartitionOperations {
removeWorkspaceSessionOwnerInPartition(this, target.id, resolved, options)
}
}
/** Candidates for the post-scan cleanup, filtered before any path probe. */
selectRemovableLocalWorktreeSessionOwnersForRepo(repoId: string): string[] {
const { state } = this[sessionHostPartitionOperationsContext].runtime
return selectRemovableLocalWorktreeSessionOwners(
state,
repoId,
selectLocalWorktreeSessionOwnersForRepo(state.workspaceSession, repoId)
)
}
/** Drops local saved session state of worktrees a scan no longer lists and whose folders are gone. */
pruneMissingLocalWorktreeSessionsForRepo(
scan: NativeLocalWorktreeMetadataScanExpectation,
missingWorktreeIds: readonly string[]
): string[] {
const context = this[sessionHostPartitionOperationsContext]
const removed = pruneMissingLocalWorktreeSessions(
context.runtime.state,
scan,
missingWorktreeIds
)
if (removed.length > 0) {
// Releasing session ownership unblocks metadata pruning for the same worktrees.
invalidateLocalWorktreeMetadataPruneInputs()
scheduleSave(context.scheduling, [WORKSPACE_SESSION_DOMAINS[0]], LOCAL_EXECUTION_HOST_ID)
}
return removed
}
}
export function resolveHostId(hostId?: string | null): ExecutionHostId {
@@ -1,18 +1,15 @@
import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types'
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id'
import {
getWorktreeIdFromHostIdentity,
isWorktreeHostIdentity
} from '../../../shared/worktree/host-qualified-identity'
import { worktreeWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope'
import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition'
import { sessionFieldsRemovedWithWorkspace } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition'
import { markdownFileIdCandidates } from '../../orca-profiles/project-transfer/profile-session-markdown-transfer'
// Repo-keyed topology revisions advance rather than delete; host-qualified recency keys need a scan.
export const OWNER_KEYED_SESSION_FIELDS_DELETED_WITH_THEIR_OWNER =
SESSION_FIELDS_PRUNED_BY_OWNER_KEY.filter(
(field) => field !== 'terminalTopologyRevisionByRepoId' && field !== 'lastVisitedAtByWorktreeId'
)
const OWNER_KEYED_FIELDS = sessionFieldsRemovedWithWorkspace('ownerKey')
const OWNER_TAB_KEYED_FIELDS = sessionFieldsRemovedWithWorkspace('ownerTabKey')
/** IDs a removed workspace's files may use in markdownFrontmatterVisible. */
export type RemovedOwnerFileIds = Set<string>
export function createMinimalPersistedTerminalTab(args: {
worktreeId: string
@@ -46,19 +43,37 @@ export function deleteOwnerKeyedSessionFields(
next: WorkspaceSessionState,
ownerKey: string,
removedTabIds: Set<string>,
options: { advanceTerminalTopologyRevision?: boolean } = {}
options: { advanceTerminalTopologyRevision?: boolean } = {},
removedFileIds: RemovedOwnerFileIds = new Set()
): void {
const removedTerminalTabs = next.tabsByWorktree?.[ownerKey] ?? []
// Why both: unified terminal tabs can outlive their legacy row, and their layouts key by entityId.
const ownerTabIds = new Set((next.tabsByWorktree?.[ownerKey] ?? []).map((tab) => tab.id))
for (const tab of next.unifiedTabs?.[ownerKey] ?? []) {
if (tab.contentType === 'terminal') {
ownerTabIds.add(tab.entityId)
ownerTabIds.add(tab.id)
}
}
if (next.tabsByWorktree) {
delete next.tabsByWorktree[ownerKey]
}
for (const tab of removedTerminalTabs) {
removedTabIds.add(tab.id)
delete next.terminalLayoutsByTabId[tab.id]
if (next.activeTabId === tab.id) {
for (const tabId of ownerTabIds) {
removedTabIds.add(tabId)
for (const field of OWNER_TAB_KEYED_FIELDS) {
const record = next[field] as Record<string, unknown> | undefined
if (record) {
delete record[tabId]
}
}
if (next.activeTabId === tabId) {
next.activeTabId = null
}
}
for (const file of next.openFilesByWorktree?.[ownerKey] ?? []) {
for (const id of markdownFileIdCandidates(file.filePath, ownerKey, file.runtimeEnvironmentId)) {
removedFileIds.add(id)
}
}
if (options.advanceTerminalTopologyRevision) {
const repoId = getRepoIdFromWorktreeId(ownerKey)
const previousTopologyRevision = next.terminalTopologyRevisionByRepoId?.[repoId] ?? 0
@@ -77,21 +92,12 @@ export function deleteOwnerKeyedSessionFields(
}
}
// Share the removal census so new fields cannot be pruned on only one path.
for (const field of OWNER_KEYED_SESSION_FIELDS_DELETED_WITH_THEIR_OWNER) {
for (const field of OWNER_KEYED_FIELDS) {
const record = next[field] as Record<string, unknown> | undefined
if (record) {
delete record[ownerKey]
}
}
// Include host-qualified executionHostId|worktreeId keys.
if (next.lastVisitedAtByWorktreeId) {
for (const key of Object.keys(next.lastVisitedAtByWorktreeId)) {
const rawId = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
if (key === ownerKey || rawId === ownerKey) {
delete next.lastVisitedAtByWorktreeId[key]
}
}
}
// Worktree owners are raw ids, but the active key stores their canonical worktree: form.
if (
next.activeWorkspaceKey === ownerKey ||
@@ -0,0 +1,122 @@
import { describe, expect, it } from 'vitest'
import { getDefaultWorkspaceSession } from '../../../shared/constants'
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
import { removeWorkspaceSessionOwners } from './session-owner-removal'
const GONE = 'repo-1::/workspaces/gone'
const KEPT = 'repo-1::/workspaces/kept'
type Workspace = { id: string; name: string }
const entries = <T>(workspaces: Workspace[], entry: (workspace: Workspace) => [string, T][]) =>
Object.fromEntries(workspaces.flatMap(entry))
/** Every per-workspace field a workspace can own, keyed by owner, tab or pane. */
function sessionFor(...workspaces: Workspace[]): WorkspaceSessionState {
// Why a unified-only terminal: its legacy row can be gone while its layout and scrollback remain.
const terminal = ({ name }: Workspace) => `${name}-terminal`
const unifiedTerminal = ({ name }: Workspace) => `${name}-unified-terminal`
const filePath = ({ name }: Workspace) => `/workspaces/${name}/README.md`
const emptyLayout = { root: null, activeLeafId: null, expandedLeafId: null }
return {
...getDefaultWorkspaceSession(),
tabsByWorktree: entries(workspaces, (w) => [
[
w.id,
[
{
id: terminal(w),
ptyId: null,
worktreeId: w.id,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
]
]),
unifiedTabs: entries(workspaces, (w) => [
[
w.id,
[
{
id: unifiedTerminal(w),
entityId: unifiedTerminal(w),
groupId: `${w.name}-group`,
worktreeId: w.id,
contentType: 'terminal',
label: 'Terminal 2',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 1
}
]
]
]),
tabGroups: entries(workspaces, (w) => [
[
w.id,
[
{
id: `${w.name}-group`,
worktreeId: w.id,
activeTabId: unifiedTerminal(w),
tabOrder: [unifiedTerminal(w)]
}
]
]
]),
tabGroupLayouts: entries(workspaces, (w) => [
[w.id, { type: 'leaf', groupId: `${w.name}-group` }]
]),
activeGroupIdByWorktree: entries(workspaces, (w) => [[w.id, `${w.name}-group`]]),
activeTabIdByWorktree: entries(workspaces, (w) => [[w.id, terminal(w)]]),
activeTabTypeByWorktree: entries(workspaces, (w) => [[w.id, 'terminal']]),
terminalLayoutsByTabId: entries(workspaces, (w) => [
[terminal(w), emptyLayout],
[unifiedTerminal(w), emptyLayout]
]),
localOnlyScrollbackByTabId: entries(workspaces, (w) => [
[unifiedTerminal(w), { leaf: 'scrollback' }]
]),
remoteSessionIdsByTabId: entries(workspaces, (w) => [[terminal(w), `${w.name}-relay`]]),
terminalPtyIncarnationsByPaneKey: entries(workspaces, (w) => [
[`${unifiedTerminal(w)}:leaf`, `${w.name}-incarnation`]
]),
openFilesByWorktree: entries(workspaces, (w) => [
[
w.id,
[
{
filePath: filePath(w),
relativePath: 'README.md',
worktreeId: w.id,
language: 'markdown'
}
]
]
]),
activeFileIdByWorktree: entries(workspaces, (w) => [[w.id, filePath(w)]]),
markdownFrontmatterVisible: entries(workspaces, (w) => [[filePath(w), false]]),
defaultTerminalTabsAppliedByWorktreeId: entries(workspaces, (w) => [[w.id, true]]),
lastVisitedAtByWorktreeId: entries(workspaces, (w) => [[w.id, 1]]),
closedTerminalTabTombstonesByTabId: entries(workspaces, (w) => [
[`${w.name}-closed`, { closedAt: 1, worktreeId: w.id }]
]),
activeWorktreeIdsOnShutdown: workspaces.map((w) => w.id)
}
}
describe('removeWorkspaceSessionOwners', () => {
it('drops every owner-, tab- and pane-keyed entry of a removed workspace and keeps its sibling', () => {
const gone = { id: GONE, name: 'gone' }
const kept = { id: KEPT, name: 'kept' }
const next = removeWorkspaceSessionOwners(sessionFor(gone, kept), new Set([GONE]))
expect(next).toEqual(sessionFor(kept))
})
})
@@ -6,8 +6,21 @@ import {
type ExecutionHostId
} from '../../../shared/execution-host'
import '../../../shared/workspace-session/workspace-session-partition-owner'
import {
getWorktreeIdFromHostIdentity,
isWorktreeHostIdentity
} from '../../../shared/worktree/host-qualified-identity'
import { isWslMoveWorkspaceSessionFrozen } from '../moving-wsl-projects/quiescence/wsl-move-scope-guard'
import { cloneWorkspaceSessionState, deleteOwnerKeyedSessionFields } from './session-owner-fields'
import {
cloneWorkspaceSessionState,
deleteOwnerKeyedSessionFields,
type RemovedOwnerFileIds
} from './session-owner-fields'
import { sessionFieldsRemovedWithWorkspace } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition'
import { markdownFileIdCandidates } from '../../orca-profiles/project-transfer/profile-session-markdown-transfer'
const OWNER_PANE_KEYED_FIELDS = sessionFieldsRemovedWithWorkspace('ownerPaneKey')
const OWNER_ROW_FIELDS = sessionFieldsRemovedWithWorkspace('ownerRow')
/** Frozen WSL sessions must survive pruning for downgrade. */
export function withoutWslMoveFrozenOwners(ownerKeys: ReadonlySet<string>): ReadonlySet<string> {
@@ -19,44 +32,56 @@ export function withoutWslMoveFrozenOwners(ownerKeys: ReadonlySet<string>): Read
export function deleteScannedSessionFieldsForOwners(
next: WorkspaceSessionState,
removedTabIds: ReadonlySet<string>,
isRemovedOwner: (worktreeId: string) => boolean
isRemovedOwner: (worktreeId: string) => boolean,
removedFileIds: RemovedOwnerFileIds = new Set()
): void {
if (next.terminalPtyIncarnationsByPaneKey) {
next.terminalPtyIncarnationsByPaneKey = Object.fromEntries(
Object.entries(next.terminalPtyIncarnationsByPaneKey).filter(([paneKey]) => {
if (removedTabIds.size > 0) {
for (const field of OWNER_PANE_KEYED_FIELDS) {
const record = next[field] as Record<string, unknown> | undefined
for (const paneKey of Object.keys(record ?? {})) {
const separator = paneKey.lastIndexOf(':')
return separator < 1 || !removedTabIds.has(paneKey.slice(0, separator))
})
)
}
if (next.terminalSurfaceTombstonesByPaneKey) {
next.terminalSurfaceTombstonesByPaneKey = Object.fromEntries(
Object.entries(next.terminalSurfaceTombstonesByPaneKey).filter(
([, tombstone]) => !isRemovedOwner(tombstone.worktreeId)
)
)
}
if (next.sleepingAgentSessionsByPaneKey) {
for (const [paneKey, record] of Object.entries(next.sleepingAgentSessionsByPaneKey)) {
if (isRemovedOwner(record.worktreeId)) {
delete next.sleepingAgentSessionsByPaneKey[paneKey]
if (separator > 0 && removedTabIds.has(paneKey.slice(0, separator))) {
delete record![paneKey]
}
}
}
}
// Close evidence expires with the workspace it governs.
if (next.closedTerminalTabTombstonesByTabId) {
for (const [tabId, record] of Object.entries(next.closedTerminalTabTombstonesByTabId)) {
if (isRemovedOwner(record.worktreeId)) {
delete next.closedTerminalTabTombstonesByTabId[tabId]
// Close evidence and resume records expire with the workspace they govern.
for (const field of OWNER_ROW_FIELDS) {
const record = next[field]
if (!isSessionRecord(record)) {
continue
}
for (const [key, row] of Object.entries(record)) {
const worktreeId = sessionRowWorktreeId(row)
if (worktreeId && isRemovedOwner(worktreeId)) {
delete record[key]
}
}
}
if (next.closedTerminalPanesByPaneKey) {
for (const [paneKey, record] of Object.entries(next.closedTerminalPanesByPaneKey)) {
if (isRemovedOwner(record.worktreeId)) {
delete next.closedTerminalPanesByPaneKey[paneKey]
if (removedFileIds.size > 0 && next.markdownFrontmatterVisible) {
// A surviving workspace may open the same path; its file keeps the shared ID.
for (const [ownerKey, files] of Object.entries(next.openFilesByWorktree ?? {})) {
for (const file of files) {
for (const id of markdownFileIdCandidates(
file.filePath,
ownerKey,
file.runtimeEnvironmentId
)) {
removedFileIds.delete(id)
}
}
}
for (const id of removedFileIds) {
delete next.markdownFrontmatterVisible[id]
}
}
// One scan for all owners; keys may be host-qualified executionHostId|worktreeId.
for (const key of Object.keys(next.lastVisitedAtByWorktreeId ?? {})) {
const rawId = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
if (isRemovedOwner(key) || isRemovedOwner(rawId)) {
delete next.lastVisitedAtByWorktreeId![key]
}
}
next.activeWorktreeIdsOnShutdown = next.activeWorktreeIdsOnShutdown?.filter(
(worktreeId) => !isRemovedOwner(worktreeId)
@@ -106,8 +131,14 @@ export function removeWorkspaceSessionOwner(
}
const next = cloneWorkspaceSessionState(session)
const removedTabIds = new Set<string>()
deleteOwnerKeyedSessionFields(next, ownerKey, removedTabIds, options)
deleteScannedSessionFieldsForOwners(next, removedTabIds, (worktreeId) => worktreeId === ownerKey)
const removedFileIds: RemovedOwnerFileIds = new Set()
deleteOwnerKeyedSessionFields(next, ownerKey, removedTabIds, options, removedFileIds)
deleteScannedSessionFieldsForOwners(
next,
removedTabIds,
(worktreeId) => worktreeId === ownerKey,
removedFileIds
)
return next
}
@@ -121,11 +152,15 @@ export function removeWorkspaceSessionOwners(
}
const next = cloneWorkspaceSessionState(session)
const removedTabIds = new Set<string>()
const removedFileIds: RemovedOwnerFileIds = new Set()
for (const ownerKey of ownerKeys) {
deleteOwnerKeyedSessionFields(next, ownerKey, removedTabIds)
deleteOwnerKeyedSessionFields(next, ownerKey, removedTabIds, {}, removedFileIds)
}
deleteScannedSessionFieldsForOwners(next, removedTabIds, (worktreeId) =>
ownerKeys.has(worktreeId)
deleteScannedSessionFieldsForOwners(
next,
removedTabIds,
(worktreeId) => ownerKeys.has(worktreeId),
removedFileIds
)
return next
}
@@ -151,3 +186,17 @@ export function removeWorkspaceSessionOwnersEverywhere(
}
state.workspaceSessionsByHostId = next
}
/** The workspace a session record row names, if it names one. */
export function sessionRowWorktreeId(row: unknown): string | undefined {
return typeof row === 'object' &&
row !== null &&
'worktreeId' in row &&
typeof row.worktreeId === 'string'
? row.worktreeId
: undefined
}
function isSessionRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
@@ -10,6 +10,7 @@ import {
captureNativeLocalWorktreeMetadataScanExpectation,
pruneSessionlessMissingLocalWorktreeMetadataForRepo
} from './missing-local-worktree-metadata-pruning'
import { pruneMissingLocalWorktreeSessionsForRepo } from './missing-local-worktree-session-pruning'
const REPO_ID = 'repo-1'
const LIVE_ID = `${REPO_ID}::/workspace/live`
@@ -265,3 +266,125 @@ describe('pruneSessionlessMissingLocalWorktreeMetadataForRepo', () => {
expect(state.worktreeMeta[worktreeId]).toBeDefined()
})
})
describe('pruneMissingLocalWorktreeSessionsForRepo', () => {
it('drops saved tabs of deleted worktrees but keeps unsaved drafts, archived and active workspaces', () => {
const state = makeState()
const goneId = `${REPO_ID}::/workspace/gone`
const draftId = `${REPO_ID}::/workspace/draft`
const archivedId = `${REPO_ID}::/workspace/archived`
const activeId = `${REPO_ID}::/workspace/active`
state.worktreeMeta[archivedId] = {
...makeMeta(archivedId),
isArchived: true,
archivedCheckout: { branch: 'feature/archived', archivedAt: 1 }
}
const draft = {
filePath: '/workspace/draft/notes.md',
relativePath: 'notes.md',
worktreeId: draftId,
language: 'markdown',
dirtyDraftContent: 'unsaved'
}
state.workspaceSession = {
...getDefaultWorkspaceSession(),
activeWorktreeId: activeId,
unifiedTabs: {
[goneId]: [],
[draftId]: [],
[archivedId]: [],
[activeId]: []
},
activeTabIdByWorktree: { [goneId]: null },
openFilesByWorktree: { [draftId]: [draft] }
}
const removed = pruneMissingLocalWorktreeSessionsForRepo(
state,
capture(state),
[goneId, draftId, archivedId, activeId],
'linux'
)
expect(removed).toEqual([goneId])
expect(state.workspaceSession.unifiedTabs).toEqual({
[draftId]: [],
[archivedId]: [],
[activeId]: []
})
expect(state.workspaceSession.activeTabIdByWorktree).toEqual({})
expect(state.workspaceSession.openFilesByWorktree).toEqual({ [draftId]: [draft] })
})
it('keeps an archived workspace whose saved key differs only in Windows path casing', () => {
const state = makeState(makeRepo({ path: 'C:\\Work\\repo' }))
state.worktreeMeta[`${REPO_ID}::C:\\Work\\archived`] = {
...makeMeta(`${REPO_ID}::C:\\Work\\archived`),
isArchived: true,
archivedCheckout: { branch: 'feature/archived', archivedAt: 1 }
}
const savedKey = `${REPO_ID}::c:\\work\\archived`
state.workspaceSession = { ...getDefaultWorkspaceSession(), unifiedTabs: { [savedKey]: [] } }
expect(
pruneMissingLocalWorktreeSessionsForRepo(state, capture(state), [savedKey], 'win32')
).toEqual([])
expect(state.workspaceSession.unifiedTabs).toEqual({ [savedKey]: [] })
})
it('keeps a workspace marked archived without an archived checkout', () => {
const state = makeState()
const archivedId = `${REPO_ID}::/workspace/hidden`
state.worktreeMeta[archivedId] = { ...makeMeta(archivedId), isArchived: true }
state.workspaceSession = { ...getDefaultWorkspaceSession(), unifiedTabs: { [archivedId]: [] } }
expect(
pruneMissingLocalWorktreeSessionsForRepo(state, capture(state), [archivedId], 'linux')
).toEqual([])
expect(state.workspaceSession.unifiedTabs).toEqual({ [archivedId]: [] })
})
// A reference removal never deletes must not count as pruned, or every scan re-arms cleanup.
it('reports nothing and keeps the session when only a kept close intent names the worktree', () => {
const state = makeState()
const goneId = `${REPO_ID}::/workspace/gone`
const session = {
...getDefaultWorkspaceSession(),
pairedTerminalTabCloseIntentsByEnvironment: {
env: [{ hostTabIds: ['host-tab'], worktreeId: goneId, closedAt: 1 }]
}
}
state.workspaceSession = session
expect(
pruneMissingLocalWorktreeSessionsForRepo(state, capture(state), [goneId], 'linux')
).toEqual([])
expect(state.workspaceSession).toBe(session)
})
it('keeps a workspace whose draft is saved under a differently cased Windows key', () => {
const state = makeState(makeRepo({ path: 'C:\\Work\\repo' }))
const draftKey = `${REPO_ID}::C:\\Work\\gone`
const tabsKey = `${REPO_ID}::c:\\work\\gone`
state.workspaceSession = {
...getDefaultWorkspaceSession(),
unifiedTabs: { [tabsKey]: [] },
openFilesByWorktree: {
[draftKey]: [
{
filePath: 'C:\\Work\\gone\\notes.md',
relativePath: 'notes.md',
worktreeId: draftKey,
language: 'markdown',
dirtyDraftContent: 'unsaved'
}
]
}
}
expect(
pruneMissingLocalWorktreeSessionsForRepo(state, capture(state), [tabsKey], 'win32')
).toEqual([])
expect(state.workspaceSession.unifiedTabs).toEqual({ [tabsKey]: [] })
})
})
@@ -10,7 +10,8 @@ import { isFinalAutomationRunStatus } from '../../../shared/automations/history/
import { pruneUnreferencedWorktreeIdentityMeta } from '../loading-store/worktree-metadata/worktree-identity-metadata'
import {
addPersistedSessionWorktreeOwners,
createWorktreeOwnerCandidateCollector
createWorktreeOwnerCandidateCollector,
type WorktreeOwnerCandidateCollector
} from '../restoring-sessions/session-worktree-ownership'
import {
indexMetadataAliasesForWorktreeIds,
@@ -33,6 +34,15 @@ function collectPersistedWorkspaceOwners(
): Set<string> {
const collector = createWorktreeOwnerCandidateCollector(candidateIds, platform)
addPersistedSessionWorktreeOwners(state, collector)
addNonSessionWorkspaceOwners(state, collector)
return collector.owners
}
/** Owners outside saved session layout: a live lease, automation or phone selection still uses the workspace. */
export function addNonSessionWorkspaceOwners(
state: PersistedState,
collector: WorktreeOwnerCandidateCollector
): void {
const add = collector.addOwner
add(state.ui.lastActiveWorktreeId)
for (const selections of Object.values(state.mobileClientTabSelectionsByDeviceId ?? {})) {
@@ -60,10 +70,9 @@ function collectPersistedWorkspaceOwners(
add(run.workspaceId)
}
}
return collector.owners
}
function repoStillMatches(
export function repoStillMatches(
state: PersistedState,
expected: NativeLocalWorktreeMetadataScanExpectation['repo']
): boolean {
@@ -83,7 +92,7 @@ function repoStillMatches(
)
}
function routingStillMatches(
export function routingStillMatches(
state: PersistedState,
expected: NativeLocalWorktreeMetadataScanExpectation
): boolean {
@@ -97,7 +106,7 @@ function routingStillMatches(
)
}
function isValidCandidateId(
export function isValidCandidateId(
repoId: string,
worktreeId: string,
platform: NodeJS.Platform
@@ -0,0 +1,216 @@
import type { PersistedState } from '../../../shared/persisted-state-types'
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
import { worktreeWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope'
import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id'
import {
getWorktreeIdFromHostIdentity,
isWorktreeHostIdentity
} from '../../../shared/worktree/host-qualified-identity'
import { worktreeRetentionIdComparisonKey } from '../../workspaces/catalog/worktree-retention-path-comparison'
import {
createWorktreeOwnerCandidateCollector,
getPersistedWorktreeOwnerId
} from '../restoring-sessions/session-worktree-ownership'
import { sessionFieldsRemovedWithWorkspace } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition'
const OWNER_KEYED_FIELDS = [
'tabsByWorktree',
'browserTabsByWorktree',
'lastVisitedAtByWorktreeId',
...sessionFieldsRemovedWithWorkspace('ownerKey')
] as const
const OWNER_ROW_FIELDS = sessionFieldsRemovedWithWorkspace('ownerRow')
import {
removeWorkspaceSessionOwners,
sessionRowWorktreeId,
withoutWslMoveFrozenOwners
} from '../restoring-sessions/session-owner-removal'
import {
indexMetadataAliasesForWorktreeIds,
isLocallyRemovableWorktreeMetadataRow,
type NativeLocalWorktreeMetadataScanExpectation
} from './local-worktree-metadata-scan-expectation'
import {
addNonSessionWorkspaceOwners,
isValidCandidateId,
repoStillMatches,
routingStillMatches
} from './missing-local-worktree-metadata-pruning'
/** Worktree IDs of this repo that only the local saved session still names. */
export function selectLocalWorktreeSessionOwnersForRepo(
session: WorkspaceSessionState,
repoId: string,
platform = process.platform
): string[] {
const owners = new Set<string>()
const add = (ownerKey: string | null | undefined): void => {
const worktreeId = getPersistedWorktreeOwnerId(ownerKey)
if (
worktreeId &&
getRepoIdFromWorktreeId(worktreeId) === repoId &&
isValidCandidateId(repoId, worktreeId, platform)
) {
owners.add(worktreeId)
}
}
// Only references removal deletes; a row filed under a live workspace must not re-arm cleanup.
for (const field of OWNER_KEYED_FIELDS) {
for (const key of Object.keys(session[field] ?? {})) {
// Removal deletes host-qualified keys only from the recency map.
if (field === 'lastVisitedAtByWorktreeId' || !isWorktreeHostIdentity(key)) {
add(key)
}
}
}
for (const field of OWNER_ROW_FIELDS) {
for (const row of Object.values(session[field] ?? {})) {
const worktreeId = sessionRowWorktreeId(row)
// Removal matches row owners exactly, so a host-qualified one would never be deleted.
if (worktreeId && !isWorktreeHostIdentity(worktreeId)) {
add(worktreeId)
}
}
}
session.activeWorktreeIdsOnShutdown?.forEach(add)
return [...owners]
}
/** Which candidate comparison keys hold an unsaved draft in any partition; only candidates' files are read. */
function draftedCandidateKeys(
state: PersistedState,
candidateKeys: ReadonlySet<string>,
platform: NodeJS.Platform
): Set<string> {
const drafted = new Set<string>()
for (const session of [
state.workspaceSession,
...Object.values(state.workspaceSessionsByHostId ?? {})
]) {
for (const [ownerKey, files] of Object.entries(session?.openFilesByWorktree ?? {})) {
const worktreeId = getPersistedWorktreeOwnerId(ownerKey)
const key = worktreeId ? worktreeRetentionIdComparisonKey(worktreeId, platform) : null
if (
key &&
candidateKeys.has(key) &&
files.some((file) => file.dirtyDraftContent !== undefined)
) {
drafted.add(key)
}
}
}
return drafted
}
// Session cleanup also keeps a workspace hidden with isArchived and no archived checkout.
function isArchivedMetadataRow(
state: PersistedState,
worktreeId: string,
aliases: readonly (readonly [alias: string, identityKeys: string[]])[]
): boolean {
return (
state.worktreeMeta[worktreeId]?.isArchived === true ||
aliases.some(([, identityKeys]) =>
identityKeys.some((key) => state.worktreeMetaByIdentity?.[key]?.isArchived === true)
)
)
}
/** Comparison keys of metadata rows that still name a workspace (archived, another host). */
function protectedMetadataComparisonKeys(
state: PersistedState,
repoId: string,
platform: NodeJS.Platform
): Set<string> {
const ids = new Set<string>()
for (const key of [
...Object.keys(state.worktreeMeta),
...Object.keys(state.worktreeIdentityAliases ?? {})
]) {
const worktreeId = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
if (getRepoIdFromWorktreeId(worktreeId) === repoId) {
ids.add(worktreeId)
}
}
const aliasesByWorktreeId = indexMetadataAliasesForWorktreeIds(state, ids)
const keys = new Set<string>()
for (const worktreeId of ids) {
const aliases = aliasesByWorktreeId.get(worktreeId) ?? []
const comparisonKey = worktreeRetentionIdComparisonKey(worktreeId, platform)
if (
comparisonKey &&
(isArchivedMetadataRow(state, worktreeId, aliases) ||
!isLocallyRemovableWorktreeMetadataRow(state, worktreeId, aliases))
) {
keys.add(comparisonKey)
}
}
return keys
}
/** Session-only owners a cleanup may drop: never the active workspace, an unsaved draft, a
* protected metadata row (matched path-equivalently) or a lease/automation/phone owner. */
export function selectRemovableLocalWorktreeSessionOwners(
state: PersistedState,
repoId: string,
worktreeIds: readonly string[],
platform = process.platform
): string[] {
const candidateIds = new Set(
worktreeIds.filter((worktreeId) => isValidCandidateId(repoId, worktreeId, platform))
)
if (candidateIds.size === 0) {
return []
}
const collector = createWorktreeOwnerCandidateCollector(candidateIds, platform)
addNonSessionWorkspaceOwners(state, collector)
collector.addOwner(state.workspaceSession.activeWorktreeId)
collector.addOwner(state.workspaceSession.activeWorkspaceKey)
const protectedKeys = protectedMetadataComparisonKeys(state, repoId, platform)
const comparisonKey = (worktreeId: string): string =>
worktreeRetentionIdComparisonKey(worktreeId, platform) ?? ''
const eligible = [...candidateIds].filter(
(worktreeId) =>
!collector.owners.has(worktreeId) && !protectedKeys.has(comparisonKey(worktreeId))
)
if (eligible.length === 0) {
return []
}
const drafted = draftedCandidateKeys(state, new Set(eligible.map(comparisonKey)), platform)
return eligible.filter((worktreeId) => !drafted.has(comparisonKey(worktreeId)))
}
/** Drop local saved session state for worktrees an authoritative scan no longer lists and whose
* folders are gone; ownership is rechecked because path probes yield. */
export function pruneMissingLocalWorktreeSessionsForRepo(
state: PersistedState,
scan: NativeLocalWorktreeMetadataScanExpectation,
missingWorktreeIds: readonly string[],
platform = process.platform
): string[] {
if (
missingWorktreeIds.length === 0 ||
!repoStillMatches(state, scan.repo) ||
!routingStillMatches(state, scan)
) {
return []
}
// Only owners removal can delete count; any other reference would re-arm cleanup forever.
const present = new Set(
selectLocalWorktreeSessionOwnersForRepo(state.workspaceSession, scan.repo.id, platform)
)
const removedIds = selectRemovableLocalWorktreeSessionOwners(
state,
scan.repo.id,
missingWorktreeIds.filter((worktreeId) => present.has(worktreeId)),
platform
)
const ownerKeys = withoutWslMoveFrozenOwners(
new Set(removedIds.flatMap((worktreeId) => [worktreeId, worktreeWorkspaceKey(worktreeId)]))
)
if (ownerKeys.size === 0) {
return []
}
state.workspaceSession = removeWorkspaceSessionOwners(state.workspaceSession, ownerKeys)!
return removedIds.filter((worktreeId) => ownerKeys.has(worktreeId))
}
@@ -215,6 +215,19 @@ export function rebaseWorkspaceSessionTerminalMembership(
prior.unifiedTabs?.[worktreeId] ?? [],
terminalTabIds
)
// Why: writing empty rows for a workspace the window dropped kept removed workspaces on disk forever.
if (
tabs.length === 0 &&
rebasedUnifiedTabs.length === 0 &&
!Object.hasOwn(incoming.tabsByWorktree, worktreeId)
) {
// Rebasing left nothing valid, so any incoming record here is rejected too.
delete unifiedTabs[worktreeId]
delete tabGroups[worktreeId]
delete tabGroupLayouts[worktreeId]
delete activeTabIdByWorktree[worktreeId]
continue
}
if (includeUnifiedTabs || rebasedUnifiedTabs.length > 0) {
unifiedTabs[worktreeId] = rebasedUnifiedTabs
includeUnifiedTabs = true
@@ -164,6 +164,40 @@ describe('worktree removal across host session partitions', () => {
expect(store.getWorkspaceSession(ENV_A).tabsByWorktree[STALE]).toEqual([])
})
it('forgets a removed worktree once a late window save that still listed it is followed by one that does not', async () => {
const store = await createStore()
const liveTab = makeTerminalTab({ id: 'live-tab', worktreeId: LIVE })
store.setWorkspaceSession({
...getDefaultWorkspaceSession(),
tabsByWorktree: {
[STALE]: [makeTerminalTab({ id: 'stale-tab', worktreeId: STALE })],
[LIVE]: [liveTab]
}
})
removeWorktreeMetaRow(store, STALE, undefined)
// A save queued before the window purged the worktree lands after main removed it.
store.setWorkspaceSession({
...getDefaultWorkspaceSession(),
tabsByWorktree: {
[STALE]: [makeTerminalTab({ id: 'stale-tab', worktreeId: STALE })],
[LIVE]: [liveTab]
},
unifiedTabs: {}
})
store.setWorkspaceSession({
...getDefaultWorkspaceSession(),
tabsByWorktree: { [LIVE]: [liveTab] },
unifiedTabs: {}
})
const session = store.getWorkspaceSession()
expect(Object.keys(session.tabsByWorktree)).toEqual([LIVE])
expect(session.unifiedTabs?.[STALE]).toBeUndefined()
expect(session.tabGroups?.[STALE]).toBeUndefined()
expect(session.activeTabIdByWorktree).not.toHaveProperty(STALE)
})
// omarchy: one removal left a repo revision that froze every sibling at [] across restarts.
it('keeps saving live and new workspaces of a repo after a sibling removal and a restart', async () => {
const NEW = 'repo-gone::/workspace/new'
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest'
import { useAppStore } from '@/store'
import { makeWorktree } from '../worktree.test-fixture'
const LIVE = 'repo-1::/workspaces/live'
const CREATED = 'repo-1::/workspaces/created'
const GONE = 'repo-1::/workspaces/gone'
const UNLOADED = 'repo-2::/workspaces/unloaded'
describe('pruneLastVisitedTimestamps', () => {
// QA on #42580: the window kept a deleted workspace's flag and saved it back after main removed it.
it('drops default-tab flags only of worktrees no list still shows', () => {
const live = makeWorktree({ id: LIVE, repoId: 'repo-1' })
useAppStore.setState({
// A worktree created after the scan is listed before the scan sees it.
worktreesByRepo: { 'repo-1': [live, makeWorktree({ id: CREATED, repoId: 'repo-1' })] },
detectedWorktreesByRepo: {
'repo-1': {
repoId: 'repo-1',
authoritative: true,
source: 'git',
worktrees: [
{ ...live, ownership: 'orca-managed', selectedCheckout: false, visible: true }
]
}
},
defaultTerminalTabsAppliedByWorktreeId: {
[LIVE]: true,
[CREATED]: true,
[GONE]: true,
[UNLOADED]: true,
'folder:workspace-1': true
}
})
useAppStore.getState().pruneLastVisitedTimestamps()
expect(useAppStore.getState().defaultTerminalTabsAppliedByWorktreeId).toEqual({
[LIVE]: true,
[CREATED]: true,
[UNLOADED]: true,
'folder:workspace-1': true
})
})
})
@@ -3,7 +3,10 @@ import type { WorktreeSlice } from '../worktree-slice-contract'
import type { AppState } from '../../../types'
import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-slice-types'
import { getRepoIdFromWorktreeId } from '../../../../../../shared/worktree/id'
import { worktreeWorkspaceKey } from '../../../../../../shared/workspace/identity/workspace-scope'
import {
parseWorkspaceKey,
worktreeWorkspaceKey
} from '../../../../../../shared/workspace/identity/workspace-scope'
import type { ExecutionHostId } from '../../../../../../shared/execution-host'
import {
getWorktreeIdFromVisitKey,
@@ -116,7 +119,30 @@ export function createPruneLastVisitedTimestamps(
changed = true
}
}
// Default-tab admission is a write-once guard: drop it only when no list still shows the id,
// since a just-created worktree or a restored placeholder can be missing from the scan.
const listedIds = new Set<string>()
for (const list of Object.values(selectWorktreesByRepo(s))) {
list.forEach((worktree) => listedIds.add(worktree.id))
}
for (const result of Object.values(selectDetectedWorktreesByRepo(s))) {
result.worktrees.forEach((worktree) => listedIds.add(worktree.id))
}
let defaultsChanged = false
const nextDefaults: Record<string, true> = {}
for (const [key, applied] of Object.entries(s.defaultTerminalTabsAppliedByWorktreeId ?? {})) {
const scope = parseWorkspaceKey(key)
const id = scope?.type === 'worktree' ? scope.worktreeId : key
const repoIds =
scope?.type === 'folder' ? undefined : validIdsByRepo.get(getRepoIdFromWorktreeId(id))
if (repoIds && !repoIds.has(id) && !listedIds.has(id)) {
defaultsChanged = true
} else {
nextDefaults[key] = applied
}
}
const patch: {
defaultTerminalTabsAppliedByWorktreeId?: Record<string, true>
lastVisitedAtByWorktreeId?: Record<string, number>
activeWorktreeId?: null
activeWorkspaceKey?: null
@@ -125,6 +151,9 @@ export function createPruneLastVisitedTimestamps(
if (changed) {
patch.lastVisitedAtByWorktreeId = next
}
if (defaultsChanged) {
patch.defaultTerminalTabsAppliedByWorktreeId = nextDefaults
}
// Web localStorage lacks main’s stale-pointer GC; clear active worktrees only after their repo proves them gone or phantom workspaces survive.
const activeId = s.activeWorktreeId
if (activeId) {