diff --git a/src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts index deb6498bf75..f7135f5af22 100644 --- a/src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts +++ b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts @@ -63,7 +63,8 @@ describe('getOtherProfileWorktreeIdsForHistoryGc', () => { expect(getOtherProfileWorktreeIdsForHistoryGc(root)).toEqual({ unreadableProfiles: 1, - ids: new Set() + ids: new Set(), + repoIds: new Set() }) }) diff --git a/src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts index a77e400827d..921850510e1 100644 --- a/src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts +++ b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts @@ -12,12 +12,10 @@ import { assertNoRetainedProfileStateExports } from '../../persistence/profile-s /** Histories lack profile segments, so include inactive profiles before GC. * Read persisted IDs without Store migrations; unreadable profiles must prevent pruning. */ -export function getOtherProfileWorktreeIdsForHistoryGc(userDataPath = getProfileUserDataPath()): { - ids: Set - unreadableProfiles: number -} { - const { ids, unreadableProfiles } = readOtherProfileWorkspaceCatalog(userDataPath) - return { ids, unreadableProfiles } +export function getOtherProfileWorktreeIdsForHistoryGc( + userDataPath = getProfileUserDataPath() +): ProfileWorkspaceIds & { unreadableProfiles: number } { + return readOtherProfileWorkspaceCatalog(userDataPath) } type ProfileWorkspaceIds = { @@ -122,9 +120,7 @@ function readProfileWorktreeIdsFromDatabase( } else if (!isRecord(worktreeMeta)) { return null } else { - for (const id of Object.keys(worktreeMeta)) { - ids.add(id) - } + addWorktreeMetaIds(worktreeMeta, ids) } } const folderWorkspaces = domains.values.get('folderWorkspaces') @@ -176,10 +172,8 @@ function readProfileWorktreeIdsFromJson(dataFile: string): ProfileWorkspaceIds | } const state = parsed const ids = new Set() - if (state.worktreeMeta && typeof state.worktreeMeta === 'object') { - for (const id of Object.keys(state.worktreeMeta)) { - ids.add(id) - } + if (isRecord(state.worktreeMeta)) { + addWorktreeMetaIds(state.worktreeMeta, ids) } if (Array.isArray(state.folderWorkspaces)) { for (const workspace of state.folderWorkspaces) { @@ -193,6 +187,17 @@ function readProfileWorktreeIdsFromJson(dataFile: string): ProfileWorkspaceIds | return repoIds ? { ids, repoIds } : null } +/** Prior ids count: a renamed worktree's panes keep session ids embedding its old path. */ +function addWorktreeMetaIds(worktreeMeta: Record, ids: Set): void { + for (const [id, meta] of Object.entries(worktreeMeta)) { + ids.add(id) + const prior = isRecord(meta) ? meta.priorWorktreeIds : undefined + if (Array.isArray(prior)) { + prior.forEach((priorId) => typeof priorId === 'string' && ids.add(priorId)) + } + } +} + function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } diff --git a/src/main/pty/history/history-gc-worktree-ids.ts b/src/main/pty/history/history-gc-worktree-ids.ts index d1ffce50d6a..b7bd252715f 100644 --- a/src/main/pty/history/history-gc-worktree-ids.ts +++ b/src/main/pty/history/history-gc-worktree-ids.ts @@ -1,13 +1,31 @@ import type { Store } from '../../persistence/loading-store/store' import { folderWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope' +import { isRepoOnCatalogHost } from '../../../shared/execution-host' import { getOtherProfileWorktreeIdsForHistoryGc } from '../../orca-profiles/catalog/other-profile-workspace-catalog' +import { + addWorkspaceSessionWorktreeOwners, + createWorktreeOwnerCandidateCollector +} from '../../persistence/restoring-sessions/session-worktree-ownership' +import type { HistoryGcOwners } from './terminal-history-gc' /** Include git and folder: PTY workspace keys; omitting folder workspaces makes their live shell history appear orphaned. */ export function getKnownWorktreeIdsForHistoryGc( - store: Pick, + store: Pick< + Store, + | 'getAllWorktreeMeta' + | 'getFolderWorkspaces' + | 'getRepos' + | 'getWorkspaceSession' + | 'getWorkspaceSessionHostIds' + >, readOtherProfiles = getOtherProfileWorktreeIdsForHistoryGc -): Set { - const live = new Set(Object.keys(store.getAllWorktreeMeta())) +): Omit { + const live = new Set() + for (const [worktreeId, meta] of Object.entries(store.getAllWorktreeMeta())) { + live.add(worktreeId) + // A renamed worktree's panes keep session ids that embed its old path. + meta.priorWorktreeIds?.forEach((id) => live.add(id)) + } for (const workspace of store.getFolderWorkspaces()) { live.add(folderWorkspaceKey(workspace.id)) } @@ -17,10 +35,76 @@ export function getKnownWorktreeIdsForHistoryGc( console.warn( `[pty:history:gc] Skipping GC: ${others.unreadableProfiles} profile(s) could not be read` ) - return new Set() + return { liveWorktreeIds: new Set(), localRepoPaths: new Map(), referencedSessionIds } } for (const id of others.ids) { live.add(id) } - return live + return { + liveWorktreeIds: live, + localRepoPaths: localOnlyRepoPaths(store, others.repoIds), + referencedSessionIds + } + + function referencedSessionIds( + candidates: readonly { sessionId: string; worktreeId: string }[] + ): Set { + const sessions = store.getWorkspaceSessionHostIds().map((id) => store.getWorkspaceSession(id)) + const collector = createWorktreeOwnerCandidateCollector( + new Set(candidates.map((candidate) => candidate.worktreeId)) + ) + for (const session of sessions) { + addWorkspaceSessionWorktreeOwners(session, collector) + } + // Any field may hold a pane's session id (tabs, layouts, sleep rows), so match ids anywhere. + const named = collectMatchingStrings(sessions, new Set(candidates.map((c) => c.sessionId))) + return new Set( + candidates + .filter( + ({ sessionId, worktreeId }) => collector.owners.has(worktreeId) || named.has(sessionId) + ) + .map(({ sessionId }) => sessionId) + ) + } +} + +function collectMatchingStrings(root: unknown, wanted: ReadonlySet): Set { + const found = new Set() + const stack: unknown[] = [root] + while (stack.length > 0) { + const value = stack.pop() + if (typeof value === 'string') { + if (wanted.has(value)) { + found.add(value) + } + } else if (value && typeof value === 'object') { + for (const [key, child] of Object.entries(value)) { + if (wanted.has(key)) { + found.add(key) + } + stack.push(child) + } + } + } + return found +} + +/** A local stat can only prove a worktree gone for repos this machine alone hosts. */ +function localOnlyRepoPaths( + store: Pick, + otherProfileRepoIds: ReadonlySet +): Map { + const paths = new Map() + const remote = new Set(otherProfileRepoIds) + for (const repo of store.getRepos()) { + if (isRepoOnCatalogHost(repo)) { + paths.set(repo.id, repo.path) + } else { + remote.add(repo.id) + } + } + for (const id of remote) { + paths.delete(id) + } + return paths } diff --git a/src/main/pty/history/terminal-history-gc.test.ts b/src/main/pty/history/terminal-history-gc.test.ts index 6601277ee26..1bed6b85394 100644 --- a/src/main/pty/history/terminal-history-gc.test.ts +++ b/src/main/pty/history/terminal-history-gc.test.ts @@ -3,8 +3,11 @@ import { mkdirSync, mkdtempSync, readdirSync, + readFileSync, rmSync, statSync, + symlinkSync, + utimesSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -26,7 +29,12 @@ import { cancelPendingHistoryTreeRemovalRetries, flushPendingWorktreeHistoryDeletions } from './terminal-history-deletion' -import { cancelHistoryGc, runHistoryGc, scheduleHistoryGc } from './terminal-history-gc' +import { + cancelHistoryGc, + runHistoryGc, + scheduleHistoryGc, + type HistoryGcOwners +} from './terminal-history-gc' const GC_MIN_AGE_MS = 5 * 60 * 1000 const PENDING_DELETE_DIR_NAME = '.pending-delete' @@ -163,6 +171,61 @@ describe('history GC prune decisions', () => { }) }) +describe('history GC daemon session folders', () => { + it('prunes only stopped sessions of forgotten worktrees whose folder is gone', async () => { + const workspaces = join(userDataDir, 'workspaces') + const repoPath = join(userDataDir, 'repo') + mkdirSync(join(workspaces, 'kept-on-disk'), { recursive: true }) + mkdirSync(join(workspaces, 'live')) + mkdirSync(join(userDataDir, 'unmounted-mount-point')) + writeFileSync(join(userDataDir, 'unmounted-mount-point', '.keep'), '') + mkdirSync(repoPath) + writeFileSync(join(repoPath, 'README'), 'x') + symlinkSync(join(userDataDir, 'ejected-volume', 'wt'), join(workspaces, 'linked'), 'junction') + const sessionFolder = (name: string, worktreeId: string, suffix = 'abcd1234'): void => { + const dir = seedDir(encodeURIComponent(`${worktreeId}@@${suffix}`), { + 'meta.json': JSON.stringify({ cwd: '/', cols: 80, rows: 24, startedAt: 'x' }), + 'scrollback.bin': name + }) + const old = new Date(Date.now() - OLD) + utimesSync(dir, old, old) + } + const deleted = `repo-1::${join(workspaces, 'deleted')}` + sessionFolder('deleted', deleted) + sessionFolder('deleted-running', deleted, 'running1') + sessionFolder('forgotten-on-disk', `repo-1::${join(workspaces, 'kept-on-disk')}`) + sessionFolder('live-missing', `repo-1::${join(workspaces, 'live-missing')}`) + sessionFolder('unmounted', `repo-1::${join(userDataDir, 'unmounted-volume', 'wt')}`) + sessionFolder('mount-point', `repo-1::${join(userDataDir, 'unmounted-mount-point', 'wt')}`) + sessionFolder('dangling-link', `repo-1::${join(workspaces, 'linked')}`) + sessionFolder('saved-tab', `repo-1::${join(workspaces, 'saved-tab')}`) + sessionFolder('remote-repo', `ssh-repo::${join(workspaces, 'deleted')}`) + sessionFolder('folder-workspace', 'folder:gone-folder') + + const live = ['live', 'live-missing'].map((name) => `repo-1::${join(workspaces, name)}`) + await runHistoryGc(new Set(live), { + localRepoPaths: new Map([['repo-1', repoPath]]), + liveSessionIds: new Set([`${deleted}@@running1`]), + referencedSessionIds: () => new Set([`repo-1::${join(workspaces, 'saved-tab')}@@abcd1234`]) + }) + + const kept = [...survivingDirs()].map((name) => + readFileSync(join(historyRoot, name, 'scrollback.bin'), 'utf8') + ) + expect(kept.sort()).toEqual([ + 'dangling-link', + 'deleted-running', + 'folder-workspace', + 'forgotten-on-disk', + 'live-missing', + 'mount-point', + 'remote-repo', + 'saved-tab', + 'unmounted' + ]) + }) +}) + describe('history GC concurrency behaviour', () => { it('joins a second call to the in-flight pass instead of walking twice', async () => { seedDecisionMatrix() @@ -201,17 +264,21 @@ describe('history GC concurrency behaviour', () => { it('does not run a scheduled pass that was cancelled while resolving live worktrees', async () => { seedDecisionMatrix() vi.useFakeTimers() - let resolveLiveIds: (ids: Set) => void = () => {} + let resolveLiveIds: (owners: HistoryGcOwners) => void = () => {} scheduleHistoryGc( () => - new Promise>((resolve) => { + new Promise((resolve) => { resolveLiveIds = resolve }) ) await vi.advanceTimersByTimeAsync(10_000) cancelHistoryGc() - resolveLiveIds(new Set([LIVE_WORKTREE_ID])) + resolveLiveIds({ + liveWorktreeIds: new Set([LIVE_WORKTREE_ID]), + localRepoPaths: new Map(), + referencedSessionIds: () => new Set() + }) await vi.advanceTimersByTimeAsync(0) expect(survivingDirs().has('orphan-old')).toBe(true) diff --git a/src/main/pty/history/terminal-history-gc.ts b/src/main/pty/history/terminal-history-gc.ts index dd69362f7a1..a2038a724af 100644 --- a/src/main/pty/history/terminal-history-gc.ts +++ b/src/main/pty/history/terminal-history-gc.ts @@ -15,6 +15,13 @@ import { resolveFishHistoryDir, sweepOrphanedFishHistoryFiles } from './fish-his import { hashWorktreeId } from './terminal-history-id' import { forEachWithConcurrency } from '../../../shared/concurrency/map-with-concurrency' import { yieldToEventLoop } from '../../../shared/concurrency/event-loop-yield' +import { + isSessionFolderOfGoneWorktree, + createStillGoneCheck, + sessionFolderOwner, + type SessionFolderGcOwners, + type SessionFolderGcScan +} from './terminal-history-session-folder-gc' // Protect history created after the live-worktree snapshot was taken. const GC_MIN_AGE_MS = 5 * 60 * 1000 @@ -30,6 +37,14 @@ let historyGcCancelled = false let activeHistoryGc: Promise | null = null let activeHistoryGcAbort: AbortController | null = null +export type HistoryGcOwners = { + liveWorktreeIds: Set + localRepoPaths: ReadonlyMap + referencedSessionIds: SessionFolderGcOwners['referencedSessionIds'] + /** Null when the daemon inventory is unknown; session folders are then kept. */ + liveSessionIds?: ReadonlySet | null +} + type GcRootScan = { totalDirs: number orphaned: number @@ -41,6 +56,7 @@ async function gcScanEntry( root: string, entry: Dirent, liveWorktreeIds: Set, + sessionFolders: SessionFolderGcScan | null, now: number, result: GcRootScan ): Promise { @@ -61,6 +77,14 @@ async function gcScanEntry( result.fishHistoryDirs.add(meta.fishHistoryDir) } if (!meta?.worktreeId) { + const owner = sessionFolders && sessionFolderOwner(entry.name) + if ( + owner && + (await isSessionFolderOfGoneWorktree(entryPath, owner, sessionFolders)) && + now - (await stat(entryPath)).mtimeMs >= GC_MIN_AGE_MS + ) { + sessionFolders.candidates.push({ root, entryPath, ...owner }) + } return } @@ -87,6 +111,7 @@ async function gcScanEntry( async function gcScanRoot( root: string, liveWorktreeIds: Set, + sessionFolders: SessionFolderGcScan | null, signal: AbortSignal ): Promise { const result: GcRootScan = { @@ -113,7 +138,7 @@ async function gcScanRoot( if (signal.aborted) { return } - await gcScanEntry(root, entry, liveWorktreeIds, now, result) + await gcScanEntry(root, entry, liveWorktreeIds, sessionFolders, now, result) if (index % HISTORY_GC_YIELD_EVERY === HISTORY_GC_YIELD_EVERY - 1) { await yieldToEventLoop() } @@ -122,7 +147,11 @@ async function gcScanRoot( return result } -async function executeHistoryGc(liveWorktreeIds: Set, signal: AbortSignal): Promise { +async function executeHistoryGc( + liveWorktreeIds: Set, + sessionFolderOwners: SessionFolderGcOwners | null, + signal: AbortSignal +): Promise { try { // Previously tombstoned entries are safe to drain even if the live set below is unavailable. await schedulePendingHistoryTreeRemovals(getHistoryRoot()) @@ -131,7 +160,15 @@ async function executeHistoryGc(liveWorktreeIds: Set, signal: AbortSigna console.log('[pty:history:gc] Skipped: live worktree set is empty') return } - const main = await gcScanRoot(getHistoryRoot(), liveWorktreeIds, signal) + // Shared across roots so each gone-worktree check stats its paths once. + const sessionFolders: SessionFolderGcScan | null = sessionFolderOwners && { + ...sessionFolderOwners, + liveWorktreeIds, + goneByWorktreeId: new Map(), + mountProofByParentKey: new Map(), + candidates: [] + } + const main = await gcScanRoot(getHistoryRoot(), liveWorktreeIds, sessionFolders, signal) const wslTotals = { totalDirs: 0, orphaned: 0, pruned: 0 } const liveFishHistoryDirs = new Set(main.fishHistoryDirs) @@ -140,7 +177,7 @@ async function executeHistoryGc(liveWorktreeIds: Set, signal: AbortSigna break } await schedulePendingHistoryTreeRemovals(distroRoot) - const r = await gcScanRoot(distroRoot, liveWorktreeIds, signal) + const r = await gcScanRoot(distroRoot, liveWorktreeIds, sessionFolders, signal) wslTotals.totalDirs += r.totalDirs wslTotals.orphaned += r.orphaned wslTotals.pruned += r.pruned @@ -154,6 +191,14 @@ async function executeHistoryGc(liveWorktreeIds: Set, signal: AbortSigna return } + const sessionTotals = sessionFolders + ? await pruneGoneWorktreeSessionFolders(sessionFolders, signal) + : { orphaned: 0, pruned: 0 } + if (signal.aborted) { + console.log('[pty:history:gc] Cancelled mid-prune') + return + } + // Fish files can outlive their metadata; include recorded dirs in case XDG_DATA_HOME changed. const fishDirs = new Set([resolveFishHistoryDir()]) for (const dir of liveFishHistoryDirs) { @@ -169,8 +214,8 @@ async function executeHistoryGc(liveWorktreeIds: Set, signal: AbortSigna } const totalDirs = main.totalDirs + wslTotals.totalDirs - const orphaned = main.orphaned + wslTotals.orphaned - const pruned = main.pruned + wslTotals.pruned + const orphaned = main.orphaned + wslTotals.orphaned + sessionTotals.orphaned + const pruned = main.pruned + wslTotals.pruned + sessionTotals.pruned console.log(`[pty:history:gc] totalDirs=${totalDirs} orphaned=${orphaned} pruned=${pruned}`) } catch (err) { @@ -178,14 +223,63 @@ async function executeHistoryGc(liveWorktreeIds: Set, signal: AbortSigna } } -export function runHistoryGc(liveWorktreeIds: Set): Promise { +/** Saved tabs are checked once over all candidates, after every root is scanned. */ +async function pruneGoneWorktreeSessionFolders( + scan: SessionFolderGcScan, + signal: AbortSignal +): Promise<{ orphaned: number; pruned: number }> { + if (scan.candidates.length === 0) { + return { orphaned: 0, pruned: 0 } + } + const referenced = scan.referencedSessionIds(scan.candidates) + const byWorktree = new Map() + for (const candidate of scan.candidates) { + if (referenced.has(candidate.sessionId)) { + continue + } + const folders = byWorktree.get(candidate.worktreeId) + if (folders) { + folders.push(candidate) + } else { + byWorktree.set(candidate.worktreeId, [candidate]) + } + } + const isStillGone = createStillGoneCheck(scan) + let orphaned = 0 + let pruned = 0 + // Each worktree's folders are removed right after its own recheck. + for (const [worktreeId, folders] of byWorktree) { + if (signal.aborted) { + break + } + if (!(await isStillGone(worktreeId)) || signal.aborted) { + continue + } + for (const { root, entryPath } of folders) { + orphaned++ + if (scheduleWorktreeHistoryTreeDeletion(entryPath, root)) { + pruned++ + } + } + } + return { orphaned, pruned } +} + +export function runHistoryGc( + liveWorktreeIds: Set, + sessionFolderOwners: SessionFolderGcOwners | null = null +): Promise { // Concurrent passes would race each other's tombstone renames. if (activeHistoryGc) { return activeHistoryGc } const controller = new AbortController() activeHistoryGcAbort = controller - activeHistoryGc = executeHistoryGc(liveWorktreeIds, controller.signal).finally(() => { + activeHistoryGc = executeHistoryGc( + liveWorktreeIds, + sessionFolderOwners, + controller.signal + ).finally(() => { activeHistoryGc = null activeHistoryGcAbort = null }) @@ -203,7 +297,7 @@ export function cancelHistoryGc(): void { } /** Use already-known worktree IDs; do not probe repo paths. */ -export function scheduleHistoryGc(getLiveWorktreeIds: () => Promise>): void { +export function scheduleHistoryGc(getOwners: () => Promise): void { if (scheduledHistoryGcTimer !== null || historyGcStarting || activeHistoryGc !== null) { return } @@ -213,11 +307,14 @@ export function scheduleHistoryGc(getLiveWorktreeIds: () => Promise> scheduledHistoryGcTimer = null historyGcStarting = true try { - const liveIds = await getLiveWorktreeIds() + const { liveWorktreeIds, liveSessionIds, ...sessionFolderOwners } = await getOwners() if (historyGcCancelled) { return } - await runHistoryGc(liveIds) + await runHistoryGc( + liveWorktreeIds, + liveSessionIds ? { ...sessionFolderOwners, liveSessionIds } : null + ) } catch (err) { console.warn( `[pty:history:gc] Failed to enumerate live worktrees for GC: ${err instanceof Error ? err.message : String(err)}` diff --git a/src/main/pty/history/terminal-history-session-folder-gc.ts b/src/main/pty/history/terminal-history-session-folder-gc.ts new file mode 100644 index 00000000000..3959ae58dda --- /dev/null +++ b/src/main/pty/history/terminal-history-session-folder-gc.ts @@ -0,0 +1,173 @@ +// Daemon session folders record no owner in meta.json; their name is the session id, which embeds the worktree id. + +import { lstat, stat } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { errnoCodeOrUnknown } from '../../../shared/errors/errno-code' +import { parsePtySessionId } from '../../../shared/terminal/pty/lifecycle/pty-session-id-format' +import { parseWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope' +import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, splitWorktreeId } from '../../../shared/worktree/id' +import { isTerminalHistorySessionDirRecoveryProtected } from '../../daemon/history/storage/terminal-history-recovery-quarantine' + +export type SessionFolderGcOwners = { + /** Repos only this machine hosts; only their worktrees can be proven gone by a local stat. */ + localRepoPaths: ReadonlyMap + /** Every daemon session still running, whatever its worktree. */ + liveSessionIds: ReadonlySet + /** The candidates' session ids that a saved session on any host still references. */ + referencedSessionIds: ( + candidates: readonly { sessionId: string; worktreeId: string }[] + ) => ReadonlySet +} + +export type SessionFolderGcScan = SessionFolderGcOwners & { + liveWorktreeIds: ReadonlySet + goneByWorktreeId: Map> + /** The known sibling that proved each parent's volume mounted, or null when none did. */ + mountProofByParentKey: Map> + knownPathsByParentKey?: Map + candidates: { root: string; entryPath: string; sessionId: string; worktreeId: string }[] +} + +/** Null for folders whose name does not prove a git worktree owner. */ +export function sessionFolderOwner(name: string): { sessionId: string; worktreeId: string } | null { + let sessionId: string + try { + sessionId = decodeURIComponent(name) + } catch { + return null + } + const { worktreeId } = parsePtySessionId(sessionId) + if (!worktreeId || parseWorkspaceKey(worktreeId)?.type === 'folder') { + return null + } + return { sessionId, worktreeId } +} + +/** Prune only a stopped session of a forgotten worktree whose folder is gone from a reachable volume. */ +export async function isSessionFolderOfGoneWorktree( + entryPath: string, + owner: { sessionId: string; worktreeId: string }, + scan: SessionFolderGcScan +): Promise { + if ( + scan.liveWorktreeIds.has(owner.worktreeId) || + scan.liveSessionIds.has(owner.sessionId) || + isTerminalHistorySessionDirRecoveryProtected(entryPath) + ) { + return false + } + let gone = scan.goneByWorktreeId.get(owner.worktreeId) + if (!gone) { + gone = isLocalWorktreeGone(owner.worktreeId, scan) + scan.goneByWorktreeId.set(owner.worktreeId, gone) + } + return gone +} + +/** A recheck just before deletion, in case a volume detached during the scan. */ +export function createStillGoneCheck( + scan: SessionFolderGcScan +): (worktreeId: string) => Promise { + const fresh = { ...scan, mountProofByParentKey: new Map>() } + return (worktreeId) => isLocalWorktreeGone(worktreeId, fresh) +} + +async function isLocalWorktreeGone( + worktreeId: string, + scan: SessionFolderGcScan +): Promise { + const parsed = splitWorktreeId(worktreeId) + const repoPath = parsed && scan.localRepoPaths.get(parsed.repoId) + if ( + !parsed || + !repoPath || + !isProbeableLocalPath(parsed.worktreePath) || + worktreeId.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR) + ) { + return false + } + // Only a known worktree present beside it proves the volume is mounted; a bare mount point can hold files. + const [repoReachable, volumeReachable] = await Promise.all([ + isDirectory(repoPath), + cachedKnownSiblingPresent(parsed.worktreePath, scan) + ]) + if (!repoReachable || !volumeReachable) { + return false + } + try { + // lstat: a dangling link to an ejected volume is not a deleted worktree. + await lstat(parsed.worktreePath) + return false + } catch (error) { + return errnoCodeOrUnknown(error) === 'ENOENT' + } +} + +/** Drive paths on Windows, absolute paths elsewhere; WSL and network shares can report ENOENT for live folders. */ +function isProbeableLocalPath(path: string): boolean { + return process.platform === 'win32' ? /^[A-Za-z]:[\\/]/.test(path) : path.startsWith('/') +} + +async function cachedKnownSiblingPresent( + worktreePath: string, + scan: SessionFolderGcScan +): Promise { + // No case folding: on a case-sensitive volume a differently-cased parent is another folder. + const parentKey = resolve(dirname(worktreePath)) + let proof = scan.mountProofByParentKey.get(parentKey) + if (!proof) { + proof = findRealSibling(knownPathsByParentKey(scan).get(parentKey) ?? []) + scan.mountProofByParentKey.set(parentKey, proof) + } + // Re-probe the proving sibling every call: one lstat keeps the proof current without rescanning siblings. + const sibling = await proof + return sibling !== null && (await isRealDirectory(sibling)) +} + +/** lstat: a symlinked sibling can point at another, still-mounted volume. */ +async function findRealSibling(siblings: readonly string[]): Promise { + const found = await Promise.all(siblings.map(isRealDirectory)) + return siblings[found.indexOf(true)] ?? null +} + +function knownPathsByParentKey(scan: SessionFolderGcScan): Map { + if (!scan.knownPathsByParentKey) { + const byParent = new Map() + const known = [...scan.localRepoPaths.values()] + for (const worktreeId of scan.liveWorktreeIds) { + const path = splitWorktreeId(worktreeId)?.worktreePath + if ( + path && + isProbeableLocalPath(path) && + !path.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR) + ) { + known.push(path) + } + } + for (const path of known) { + const key = resolve(dirname(path)) + const siblings = byParent.get(key) + if (siblings) { + siblings.push(path) + } else { + byParent.set(key, [path]) + } + } + scan.knownPathsByParentKey = byParent + } + return scan.knownPathsByParentKey +} + +function isRealDirectory(path: string): Promise { + return lstat(path).then( + (info) => info.isDirectory(), + () => false + ) +} + +function isDirectory(path: string): Promise { + return stat(path).then( + (info) => info.isDirectory(), + () => false + ) +} diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index d4657ec501d..79a10149f1a 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -117,7 +117,12 @@ export async function attachMainWindowServices( registerDaemonManagementHandlers() // Background git worktree list can trigger protected-folder prompts on macOS; use remembered IDs. scheduleHistoryGc(async () => { - return getKnownWorktreeIdsForHistoryGc(store) + // An unknown daemon inventory keeps every session folder but still runs the rest of the GC. + const liveSessionIds = await listLiveDaemonPtyIds().catch(() => null) + return { + ...getKnownWorktreeIdsForHistoryGc(store), + liveSessionIds: liveSessionIds && new Set(liveSessionIds) + } }) openCodeHookService.configDirGc.schedule(listLiveDaemonPtyIds) openCode2HookService.configDirGc.schedule(listLiveDaemonPtyIds)