mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
fix(terminal): drop saved scrollback of deleted worktrees in history GC (#42834)
* fix(terminal): drop saved scrollback of deleted worktrees in history GC * fix(terminal): keep session folders behind dangling links, WSL paths, empty mount points and saved tabs * fix(terminal): keep session folders of renamed worktrees and unproven mounts * refactor(terminal): read the ENOENT code through the shared errno helper * fix(terminal): match sibling worktree parents without case folding * fix(terminal): count only real sibling directories and recheck before pruning * fix(terminal): recheck each gone worktree once per parent probe and honor abort while pruning * fix(terminal): re-probe the proving sibling per worktree and stop pruning once cancelled
This commit is contained in:
@@ -63,7 +63,8 @@ describe('getOtherProfileWorktreeIdsForHistoryGc', () => {
|
||||
|
||||
expect(getOtherProfileWorktreeIdsForHistoryGc(root)).toEqual({
|
||||
unreadableProfiles: 1,
|
||||
ids: new Set()
|
||||
ids: new Set(),
|
||||
repoIds: new Set()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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<string>
|
||||
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<string>()
|
||||
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<string, unknown>, ids: Set<string>): 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<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
@@ -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:<id> PTY workspace keys; omitting folder workspaces makes their live shell history appear orphaned. */
|
||||
export function getKnownWorktreeIdsForHistoryGc(
|
||||
store: Pick<Store, 'getAllWorktreeMeta' | 'getFolderWorkspaces'>,
|
||||
store: Pick<
|
||||
Store,
|
||||
| 'getAllWorktreeMeta'
|
||||
| 'getFolderWorkspaces'
|
||||
| 'getRepos'
|
||||
| 'getWorkspaceSession'
|
||||
| 'getWorkspaceSessionHostIds'
|
||||
>,
|
||||
readOtherProfiles = getOtherProfileWorktreeIdsForHistoryGc
|
||||
): Set<string> {
|
||||
const live = new Set(Object.keys(store.getAllWorktreeMeta()))
|
||||
): Omit<HistoryGcOwners, 'liveSessionIds'> {
|
||||
const live = new Set<string>()
|
||||
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<string> {
|
||||
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<string>): Set<string> {
|
||||
const found = new Set<string>()
|
||||
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<Store, 'getRepos'>,
|
||||
otherProfileRepoIds: ReadonlySet<string>
|
||||
): Map<string, string> {
|
||||
const paths = new Map<string, string>()
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<string>) => void = () => {}
|
||||
let resolveLiveIds: (owners: HistoryGcOwners) => void = () => {}
|
||||
scheduleHistoryGc(
|
||||
() =>
|
||||
new Promise<Set<string>>((resolve) => {
|
||||
new Promise<HistoryGcOwners>((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)
|
||||
|
||||
@@ -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<void> | null = null
|
||||
let activeHistoryGcAbort: AbortController | null = null
|
||||
|
||||
export type HistoryGcOwners = {
|
||||
liveWorktreeIds: Set<string>
|
||||
localRepoPaths: ReadonlyMap<string, string>
|
||||
referencedSessionIds: SessionFolderGcOwners['referencedSessionIds']
|
||||
/** Null when the daemon inventory is unknown; session folders are then kept. */
|
||||
liveSessionIds?: ReadonlySet<string> | null
|
||||
}
|
||||
|
||||
type GcRootScan = {
|
||||
totalDirs: number
|
||||
orphaned: number
|
||||
@@ -41,6 +56,7 @@ async function gcScanEntry(
|
||||
root: string,
|
||||
entry: Dirent,
|
||||
liveWorktreeIds: Set<string>,
|
||||
sessionFolders: SessionFolderGcScan | null,
|
||||
now: number,
|
||||
result: GcRootScan
|
||||
): Promise<void> {
|
||||
@@ -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<string>,
|
||||
sessionFolders: SessionFolderGcScan | null,
|
||||
signal: AbortSignal
|
||||
): Promise<GcRootScan> {
|
||||
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<string>, signal: AbortSignal): Promise<void> {
|
||||
async function executeHistoryGc(
|
||||
liveWorktreeIds: Set<string>,
|
||||
sessionFolderOwners: SessionFolderGcOwners | null,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
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<string>, 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<string>, 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<string>, 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<string>, 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<string>, signal: AbortSigna
|
||||
}
|
||||
}
|
||||
|
||||
export function runHistoryGc(liveWorktreeIds: Set<string>): Promise<void> {
|
||||
/** 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<string, SessionFolderGcScan['candidates']>()
|
||||
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<string>,
|
||||
sessionFolderOwners: SessionFolderGcOwners | null = null
|
||||
): Promise<void> {
|
||||
// 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<Set<string>>): void {
|
||||
export function scheduleHistoryGc(getOwners: () => Promise<HistoryGcOwners>): void {
|
||||
if (scheduledHistoryGcTimer !== null || historyGcStarting || activeHistoryGc !== null) {
|
||||
return
|
||||
}
|
||||
@@ -213,11 +307,14 @@ export function scheduleHistoryGc(getLiveWorktreeIds: () => Promise<Set<string>>
|
||||
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)}`
|
||||
|
||||
@@ -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<string, string>
|
||||
/** Every daemon session still running, whatever its worktree. */
|
||||
liveSessionIds: ReadonlySet<string>
|
||||
/** The candidates' session ids that a saved session on any host still references. */
|
||||
referencedSessionIds: (
|
||||
candidates: readonly { sessionId: string; worktreeId: string }[]
|
||||
) => ReadonlySet<string>
|
||||
}
|
||||
|
||||
export type SessionFolderGcScan = SessionFolderGcOwners & {
|
||||
liveWorktreeIds: ReadonlySet<string>
|
||||
goneByWorktreeId: Map<string, Promise<boolean>>
|
||||
/** The known sibling that proved each parent's volume mounted, or null when none did. */
|
||||
mountProofByParentKey: Map<string, Promise<string | null>>
|
||||
knownPathsByParentKey?: Map<string, string[]>
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
const fresh = { ...scan, mountProofByParentKey: new Map<string, Promise<string | null>>() }
|
||||
return (worktreeId) => isLocalWorktreeGone(worktreeId, fresh)
|
||||
}
|
||||
|
||||
async function isLocalWorktreeGone(
|
||||
worktreeId: string,
|
||||
scan: SessionFolderGcScan
|
||||
): Promise<boolean> {
|
||||
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<boolean> {
|
||||
// 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<string | null> {
|
||||
const found = await Promise.all(siblings.map(isRealDirectory))
|
||||
return siblings[found.indexOf(true)] ?? null
|
||||
}
|
||||
|
||||
function knownPathsByParentKey(scan: SessionFolderGcScan): Map<string, string[]> {
|
||||
if (!scan.knownPathsByParentKey) {
|
||||
const byParent = new Map<string, string[]>()
|
||||
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<boolean> {
|
||||
return lstat(path).then(
|
||||
(info) => info.isDirectory(),
|
||||
() => false
|
||||
)
|
||||
}
|
||||
|
||||
function isDirectory(path: string): Promise<boolean> {
|
||||
return stat(path).then(
|
||||
(info) => info.isDirectory(),
|
||||
() => false
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user