/** Global workspace/session index shared by CLI, TUI, Desktop and Cron hosts. */ import { createHash, randomUUID } from 'node:crypto'; import { constants } from 'node:fs'; import { copyFile, mkdir, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile, } from 'node:fs/promises'; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { agentStateDir } from './agentHome.js'; import { legacyPathSessionFileFor, validateSessionId } from './sessionPath.js'; export interface WorkspaceSessionRecord { id: string; title: string; createdAt: number; updatedAt: number; lastMessagePreview?: string; modelId?: string; } export interface WorkspaceRecord { id: string; canonicalPath: string; displayPath: string; displayName: string; /** Historical mount points/symlink spellings that identify the same local workspace. */ pathAliases?: string[]; available: boolean; lastActiveAt: number; activeSessionId?: string; sessions: WorkspaceSessionRecord[]; } export interface RecoverableHistory { fileName: string; reason: 'temporary' | 'missing_cwd' | 'hash_mismatch' | 'invalid_session'; suggestedPath?: string; } export interface WorkspaceIndex { version: 1; revision: number; workspaces: WorkspaceRecord[]; recoverable: RecoverableHistory[]; migratedAt: number; } export interface RecoveryReport { workspaces: number; sessions: number; recoverable: RecoverableHistory[]; } const INDEX_VERSION = 1 as const; const LOCK_STALE_MS = 120_000; const LOCK_WAIT_MS = 15_000; const HISTORY_PREFIX_LIMIT = 1024 * 1024; let mutationQueue: Promise = Promise.resolve(); function indexPath(): string { return join(agentStateDir(), 'workspace-index.json'); } function lockPath(): string { return join(agentStateDir(), 'workspace-index.lock'); } function recentDirsPath(): string { return join(agentStateDir(), 'recent-dirs.json'); } function metadataPath(): string { return join(agentStateDir(), 'session-metadata.json'); } function activeSessionsPath(): string { return join(agentStateDir(), 'active-sessions.json'); } function sessionsPath(): string { return join(agentStateDir(), 'sessions'); } function outboxPath(): string { return join(agentStateDir(), 'workspace-index-outbox'); } type PendingIndexMutation = | { type: 'touch'; path: string; session: WorkspaceSessionRecord; createdAt: number } | { type: 'active'; path: string; sessionId: string; createdAt: number } | { type: 'remove-session'; path: string; sessionId: string; createdAt: number }; type PendingIndexMutationInput = | { type: 'touch'; path: string; session: WorkspaceSessionRecord } | { type: 'active'; path: string; sessionId: string } | { type: 'remove-session'; path: string; sessionId: string }; function cwdHash(cwd: string): string { return createHash('sha1').update(cwd).digest('hex').slice(0, 12); } function processIsAlive(pid: number): boolean { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } } async function acquireLock(): Promise<() => Promise> { const path = lockPath(); const ownerFile = join(path, 'owner.json'); const startedAt = Date.now(); await mkdir(agentStateDir(), { recursive: true, mode: 0o700 }); while (true) { try { await mkdir(path, { mode: 0o700 }); await writeFile(ownerFile, JSON.stringify({ pid: process.pid, createdAt: Date.now() }), { mode: 0o600 }); return async () => { await rm(path, { recursive: true, force: true }); }; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; let stale = false; try { const owner = JSON.parse(await readFile(ownerFile, 'utf8')) as { pid?: number }; stale = typeof owner.pid === 'number' && !processIsAlive(owner.pid); } catch { try { stale = Date.now() - (await stat(path)).mtimeMs > LOCK_STALE_MS; } catch { continue; } } if (stale) { await rm(path, { recursive: true, force: true }); continue; } if (Date.now() - startedAt > LOCK_WAIT_MS) throw new Error('等待工作区索引锁超时'); await new Promise((resolvePromise) => setTimeout(resolvePromise, 25)); } } } function enqueueMutation(mutate: () => Promise): Promise { const run = async () => { const release = await acquireLock(); try { return await mutate(); } finally { await release(); } }; const operation = mutationQueue.then(run, run); mutationQueue = operation.then(() => undefined, () => undefined); return operation; } async function volumeRemountCandidates(displayPath: string): Promise { const match = displayPath.match(/^\/Volumes\/([^/]+)(\/.*)?$/); if (!match) return []; const requestedName = match[1] ?? ''; const suffix = match[2] ?? ''; const baseName = requestedName.replace(/ \d+$/, ''); let names: string[] = []; try { names = await readdir('/Volumes'); } catch { return []; } return names .filter((name) => name.replace(/ \d+$/, '') === baseName && name !== requestedName) .sort((a, b) => Number(a.includes(' ')) - Number(b.includes(' '))) .map((name) => `/Volumes/${name}${suffix}`); } async function canonicalize(path: string): Promise<{ canonicalPath: string; displayPath: string; available: boolean }> { const displayPath = resolve(path); for (const candidate of [displayPath, ...(await volumeRemountCandidates(displayPath))]) { try { const canonicalPath = await realpath(candidate); if (!(await stat(canonicalPath)).isDirectory()) continue; return { canonicalPath, displayPath: candidate, available: true }; } catch { /* Try another spelling of the same removable volume. */ } } return { canonicalPath: displayPath, displayPath, available: false }; } function normalizeSession(value: unknown): WorkspaceSessionRecord | null { if (!value || typeof value !== 'object') return null; const raw = value as Record; if (typeof raw.id !== 'string') return null; try { validateSessionId(raw.id); } catch { return null; } const now = Date.now(); return { id: raw.id, title: typeof raw.title === 'string' && raw.title.trim() ? raw.title : raw.id === 'default' ? '默认会话' : raw.id, createdAt: typeof raw.createdAt === 'number' ? raw.createdAt : now, updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : now, ...(typeof raw.lastMessagePreview === 'string' ? { lastMessagePreview: raw.lastMessagePreview } : {}), ...(typeof raw.modelId === 'string' && raw.modelId.trim() ? { modelId: raw.modelId.trim() } : {}), }; } function normalizeIndex(value: unknown): WorkspaceIndex | null { if (!value || typeof value !== 'object') return null; const raw = value as Record; if (raw.version !== INDEX_VERSION || !Array.isArray(raw.workspaces)) return null; const workspaces = raw.workspaces.flatMap((item): WorkspaceRecord[] => { if (!item || typeof item !== 'object') return []; const workspace = item as Record; if (typeof workspace.id !== 'string' || typeof workspace.canonicalPath !== 'string') return []; const displayPath = typeof workspace.displayPath === 'string' ? workspace.displayPath : workspace.canonicalPath; return [{ id: workspace.id, canonicalPath: resolve(workspace.canonicalPath), displayPath: resolve(displayPath), displayName: typeof workspace.displayName === 'string' ? workspace.displayName : basename(displayPath), pathAliases: Array.isArray(workspace.pathAliases) ? [...new Set(workspace.pathAliases.filter((path): path is string => typeof path === 'string').map((path) => resolve(path)))] : [], available: workspace.available !== false, lastActiveAt: typeof workspace.lastActiveAt === 'number' ? workspace.lastActiveAt : 0, ...(typeof workspace.activeSessionId === 'string' ? { activeSessionId: workspace.activeSessionId } : {}), sessions: Array.isArray(workspace.sessions) ? workspace.sessions.flatMap((session) => { const normalized = normalizeSession(session); return normalized ? [normalized] : []; }) : [], }]; }); return { version: INDEX_VERSION, revision: typeof raw.revision === 'number' ? raw.revision : 0, workspaces, recoverable: Array.isArray(raw.recoverable) ? raw.recoverable as RecoverableHistory[] : [], migratedAt: typeof raw.migratedAt === 'number' ? raw.migratedAt : Date.now(), }; } async function readIndexIfPresent(): Promise { try { const parsed = JSON.parse(await readFile(indexPath(), 'utf8')) as unknown; const index = normalizeIndex(parsed); if (!index) throw new Error('工作区索引格式无效'); return index; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw new Error(`无法读取工作区索引:${error instanceof Error ? error.message : String(error)}`); } } async function writeIndex(index: WorkspaceIndex): Promise { const file = indexPath(); await mkdir(dirname(file), { recursive: true, mode: 0o700 }); const temp = `${file}.${process.pid}.${randomUUID()}.tmp`; const persisted = { ...index, workspaces: index.workspaces.map((workspace) => ({ ...workspace })), }; try { await writeFile(temp, `${JSON.stringify(persisted, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }); await rename(temp, file); } finally { await unlink(temp).catch(() => {}); } } async function readJsonObject(path: string): Promise> { try { const value = JSON.parse(await readFile(path, 'utf8')) as unknown; return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; } catch { return {}; } } function isTemporaryWorkspace(path: string): boolean { const normalized = path.replace(/\\/g, '/').toLowerCase(); const internalRoot = resolve(agentStateDir()); const insideAgentState = relative(internalRoot, resolve(path)); return normalized.includes('/cli-e2e-') || normalized.includes('/cron-workflow-cwd-') || isInternalWorkspace(path, normalized, insideAgentState); } function isNavigationTestWorkspace(path: string): boolean { const normalized = path.replace(/\\/g, '/').toLowerCase(); return normalized.includes('/cli-e2e-') || normalized.includes('/cron-workflow-cwd-') || normalized.includes('/run-agent-turn-code-'); } function isInternalWorkspace(path: string, normalized = path.replace(/\\/g, '/').toLowerCase(), insideAgentState?: string): boolean { const relativeToState = insideAgentState ?? relative(resolve(agentStateDir()), resolve(path)); // !isAbsolute:Windows 上跨盘(工作区在 D:、agent home 在 C:)时 path.relative 返回 // 目标绝对路径(不带 ..),会被下面的「不以 .. 开头 = 在 agent 目录内」误判成内部目录 // → 该盘工作区被静默丢弃(真机事故:home C:\ + 项目 D:\ 的用户索引里看不到项目)。 return normalized.includes('/.minimal-agent/gateway/') || normalized.endsWith('/.minimal-agent/plain-chat-workspace') || (relativeToState !== '' && relativeToState !== '..' && !relativeToState.startsWith(`..${sep}`) && !isAbsolute(relativeToState)); } async function readPrefix(path: string): Promise { const file = await open(path, 'r'); try { const buffer = Buffer.alloc(HISTORY_PREFIX_LIMIT); const { bytesRead } = await file.read(buffer, 0, buffer.length, 0); return buffer.subarray(0, bytesRead).toString('utf8'); } finally { await file.close(); } } function cwdFromHistoryPrefix(raw: string): string | null { const match = raw.match(/当前工作目录:\s*([^\\\n\r"]+)/); return match?.[1]?.trim() || null; } function sessionIdFromFile(name: string): string | null { const match = name.match(/--([^/]+)\.json$/); const id = match?.[1] ?? 'default'; try { return validateSessionId(id); } catch { return null; } } function workspaceIdFromStableFile(name: string): string | null { const match = name.match(/^workspace-([a-zA-Z0-9._-]+)--[^/]+\.json$/); return match?.[1] ?? null; } function fileMatchesWorkspace(fileName: string, cwd: string, sessionId: string): boolean { if (workspaceIdFromStableFile(fileName)) return true; const expected = basename(legacyPathSessionFileFor(cwd, sessionId)); if (fileName === expected) return true; return sessionId === 'default' && fileName === expected.replace(/--default\.json$/, '.json'); } function mergeSession(workspace: WorkspaceRecord, session: WorkspaceSessionRecord): void { const previous = workspace.sessions.find((item) => item.id === session.id); if (!previous) workspace.sessions.push(session); else Object.assign(previous, session, { createdAt: Math.min(previous.createdAt, session.createdAt) }); workspace.sessions.sort((a, b) => { if (a.id === 'default') return -1; if (b.id === 'default') return 1; return b.updatedAt - a.updatedAt; }); } async function legacyRecovery(): Promise { const now = Date.now(); const workspaces = new Map(); const recoverable: RecoverableHistory[] = []; const metadata = await readJsonObject(metadataPath()); const active = await readJsonObject(activeSessionsPath()); const ensureWorkspace = async (path: string, lastActiveAt = 0, preferredId?: string): Promise => { const resolved = await canonicalize(path); const key = resolved.canonicalPath; let workspace = workspaces.get(key); if (!workspace) { workspace = { id: preferredId ?? randomUUID(), canonicalPath: resolved.canonicalPath, displayPath: resolved.displayPath, displayName: basename(resolved.displayPath) || resolved.displayPath, available: resolved.available, lastActiveAt, sessions: [], }; workspaces.set(key, workspace); } else { workspace.lastActiveAt = Math.max(workspace.lastActiveAt, lastActiveAt); } return workspace; }; try { const recent = JSON.parse(await readFile(recentDirsPath(), 'utf8')) as unknown; if (Array.isArray(recent)) { for (const value of recent) { if (!value || typeof value !== 'object' || typeof (value as { path?: unknown }).path !== 'string') continue; const raw = value as Record; const workspace = await ensureWorkspace(raw.path as string, typeof raw.lastUsedAt === 'number' ? raw.lastUsedAt : 0); if (typeof raw.name === 'string') workspace.displayName = raw.name; } } } catch { /* Session scan can still recover workspaces. */ } let files: string[] = []; try { files = (await readdir(sessionsPath())).filter((name) => name.endsWith('.json') && !name.includes('.tmp')); } catch {} for (const fileName of files) { const sessionId = sessionIdFromFile(fileName); if (!sessionId) { recoverable.push({ fileName, reason: 'invalid_session' }); continue; } let cwd: string | null = null; try { cwd = cwdFromHistoryPrefix(await readPrefix(join(sessionsPath(), fileName))); } catch {} if (!cwd) { recoverable.push({ fileName, reason: 'missing_cwd' }); continue; } if (isTemporaryWorkspace(cwd)) { recoverable.push({ fileName, reason: 'temporary', suggestedPath: cwd }); continue; } if (!fileMatchesWorkspace(fileName, cwd, sessionId)) { recoverable.push({ fileName, reason: 'hash_mismatch', suggestedPath: cwd }); continue; } const info = await stat(join(sessionsPath(), fileName)); const workspace = await ensureWorkspace(cwd, info.mtimeMs, workspaceIdFromStableFile(fileName) ?? undefined); const hash = cwdHash(cwd); const group = metadata[hash] && typeof metadata[hash] === 'object' ? metadata[hash] as Record : {}; const stored = normalizeSession(group[sessionId]); mergeSession(workspace, stored ?? { id: sessionId, title: sessionId === 'default' ? '默认会话' : sessionId, createdAt: info.birthtimeMs || info.mtimeMs, updatedAt: info.mtimeMs, }); if (typeof active[hash] === 'string') workspace.activeSessionId = active[hash] as string; } return { version: INDEX_VERSION, revision: 1, workspaces: [...workspaces.values()].sort((a, b) => a.displayName.localeCompare(b.displayName, 'zh-CN')), recoverable, migratedAt: now, }; } async function backupLegacyFiles(): Promise { const backupDir = join(agentStateDir(), 'workspace-index-migration-v1'); await mkdir(backupDir, { recursive: true, mode: 0o700 }); for (const source of [recentDirsPath(), metadataPath(), activeSessionsPath()]) { await copyFile(source, join(backupDir, basename(source)), constants.COPYFILE_EXCL).catch(() => {}); } } async function backupCorruptIndex(error: unknown): Promise { const source = indexPath(); const target = `${source}.corrupt-${Date.now()}`; try { await copyFile(source, target, constants.COPYFILE_EXCL); await writeFile(`${target}.reason.txt`, error instanceof Error ? error.message : String(error), { mode: 0o600 }); } catch { // If the file disappeared between read and backup, legacy recovery is still safe. } } function addAlias(workspace: WorkspaceRecord, path: string): void { const alias = resolve(path); const aliases = new Set(workspace.pathAliases ?? []); if (alias !== workspace.canonicalPath && alias !== workspace.displayPath) aliases.add(alias); workspace.pathAliases = [...aliases]; } async function applyPendingMutation(index: WorkspaceIndex, mutation: PendingIndexMutation): Promise { const resolved = await canonicalize(mutation.path); const workspace = upsertWorkspace(index, resolved, mutation.path); if (mutation.type === 'touch') { mergeSession(workspace, mutation.session); workspace.lastActiveAt = Math.max(workspace.lastActiveAt, mutation.session.updatedAt); } else if (mutation.type === 'active') { workspace.activeSessionId = validateSessionId(mutation.sessionId); workspace.lastActiveAt = Math.max(workspace.lastActiveAt, mutation.createdAt); } else { workspace.sessions = workspace.sessions.filter((session) => session.id !== mutation.sessionId); if (workspace.activeSessionId === mutation.sessionId) workspace.activeSessionId = workspace.sessions[0]?.id; } } async function applyOutbox(index: WorkspaceIndex): Promise { let files: string[] = []; try { files = (await readdir(outboxPath())).filter((name) => name.endsWith('.json')); } catch { return []; } const applied: string[] = []; for (const name of files.sort()) { const file = join(outboxPath(), name); try { const mutation = JSON.parse(await readFile(file, 'utf8')) as PendingIndexMutation; if (!mutation || typeof mutation.path !== 'string' || typeof mutation.type !== 'string') throw new Error('invalid outbox record'); await applyPendingMutation(index, mutation); applied.push(file); } catch (error) { try { process.stderr.write(`[minimal-agent] 工作区索引补写失败:${error instanceof Error ? error.message : String(error)}\n`); } catch {} } } return applied; } async function acknowledgeOutbox(files: string[]): Promise { await Promise.all(files.map((file) => unlink(file).catch(() => {}))); } async function ensureIndexUnlocked(): Promise { let existing: WorkspaceIndex | null = null; try { existing = await readIndexIfPresent(); } catch (error) { await backupCorruptIndex(error); } if (existing) { const reconciled = await reconcileExistingIndex(existing); const applied = await applyOutbox(reconciled); if (applied.length) { reconciled.revision += 1; await writeIndex(reconciled); await acknowledgeOutbox(applied); } return reconciled; } await backupLegacyFiles(); const recovered = await legacyRecovery(); const applied = await applyOutbox(recovered); await writeIndex(recovered); await acknowledgeOutbox(applied); return recovered; } async function reconcileExistingIndex(index: WorkspaceIndex): Promise { const before = JSON.stringify(index.workspaces); const merged = new Map(); const recoverableKeys = new Set(index.recoverable.map((item) => `${item.fileName}:${item.reason}`)); for (const workspace of index.workspaces) { if (isInternalWorkspace(workspace.displayPath)) continue; if (isNavigationTestWorkspace(workspace.displayPath) || isNavigationTestWorkspace(workspace.canonicalPath)) { for (const session of workspace.sessions) { const fileName = `workspace-${workspace.id}--${session.id}.json`; const key = `${fileName}:temporary`; if (recoverableKeys.has(key)) continue; index.recoverable.push({ fileName, reason: 'temporary', suggestedPath: workspace.displayPath, }); recoverableKeys.add(key); } continue; } const resolved = await canonicalize(workspace.displayPath); const normalized: WorkspaceRecord = { ...workspace, canonicalPath: resolved.canonicalPath, displayPath: resolved.displayPath, displayName: basename(resolved.displayPath) || workspace.displayName, available: resolved.available, pathAliases: [...new Set([ ...(workspace.pathAliases ?? []), workspace.canonicalPath, workspace.displayPath, ].map((path) => resolve(path)).filter((path) => path !== resolved.canonicalPath && path !== resolved.displayPath))], sessions: [...workspace.sessions], }; const current = merged.get(normalized.canonicalPath); if (!current) { merged.set(normalized.canonicalPath, normalized); continue; } for (const session of normalized.sessions) mergeSession(current, session); for (const alias of normalized.pathAliases ?? []) addAlias(current, alias); if (normalized.lastActiveAt > current.lastActiveAt) { current.lastActiveAt = normalized.lastActiveAt; current.activeSessionId = normalized.activeSessionId ?? current.activeSessionId; current.displayPath = normalized.displayPath; current.displayName = normalized.displayName; } current.available ||= normalized.available; } index.workspaces = [...merged.values()].sort((a, b) => a.displayName.localeCompare(b.displayName, 'zh-CN')); if (before !== JSON.stringify(index.workspaces)) { index.revision += 1; await writeIndex(index); } return index; } async function refreshAvailability(index: WorkspaceIndex): Promise { const workspaces = await Promise.all(index.workspaces.map(async (workspace) => { try { return { ...workspace, available: (await stat(workspace.canonicalPath)).isDirectory() }; } catch { return { ...workspace, available: false }; } })); // 已登记工作区是用户导航数据,即使当前离线且尚无 Session 也必须保留。 // 外接盘暂时卸载不等于用户要求移除工作区;删除只能走显式 removeWorkspace。 const changed = workspaces.some((workspace, indexPosition) => workspace.available !== index.workspaces[indexPosition]?.available, ); if (changed) { index.workspaces = workspaces.sort((a, b) => b.lastActiveAt - a.lastActiveAt); index.revision += 1; await writeIndex(index); } return { ...index, workspaces }; } async function mutate(fn: (index: WorkspaceIndex) => Promise | T): Promise { return enqueueMutation(async () => { const index = await ensureIndexUnlocked(); const result = await fn(index); for (const workspace of index.workspaces) { workspace.sessions.sort((a, b) => { if (a.id === 'default') return -1; if (b.id === 'default') return 1; return b.updatedAt - a.updatedAt; }); } index.workspaces.sort((a, b) => a.displayName.localeCompare(b.displayName, 'zh-CN')); index.revision += 1; await writeIndex(index); return result; }); } function upsertWorkspace( index: WorkspaceIndex, resolved: { canonicalPath: string; displayPath: string; available: boolean }, requestedPath?: string, ): WorkspaceRecord { const candidates = new Set([resolved.canonicalPath, resolved.displayPath, ...(requestedPath ? [resolve(requestedPath)] : [])]); let workspace = index.workspaces.find((item) => [ item.canonicalPath, item.displayPath, ...(item.pathAliases ?? []), ].some((path) => candidates.has(path))); if (!workspace) { workspace = { id: randomUUID(), canonicalPath: resolved.canonicalPath, displayPath: resolved.displayPath, displayName: basename(resolved.displayPath) || resolved.displayPath, pathAliases: requestedPath ? [resolve(requestedPath)].filter((path) => path !== resolved.displayPath) : [], available: resolved.available, lastActiveAt: Date.now(), sessions: [], }; index.workspaces.push(workspace); } else { addAlias(workspace, workspace.canonicalPath); addAlias(workspace, workspace.displayPath); if (requestedPath) addAlias(workspace, requestedPath); workspace.canonicalPath = resolved.canonicalPath; workspace.displayPath = resolved.displayPath; workspace.available = resolved.available; workspace.lastActiveAt = Date.now(); } return workspace; } export const workspaceIndexService = { async recordPendingMutation(mutation: PendingIndexMutationInput): Promise { await mkdir(outboxPath(), { recursive: true, mode: 0o700 }); const target = join(outboxPath(), `${Date.now()}-${process.pid}-${randomUUID()}.json`); const temp = `${target}.tmp`; try { await writeFile(temp, `${JSON.stringify({ ...mutation, createdAt: Date.now() })}\n`, { mode: 0o600 }); await rename(temp, target); } finally { await unlink(temp).catch(() => {}); } }, async list(): Promise { return enqueueMutation(async () => { const index = await ensureIndexUnlocked(); return (await refreshAvailability(index)).workspaces.sort((a, b) => a.displayName.localeCompare(b.displayName, 'zh-CN')); }); }, async snapshot(): Promise { return enqueueMutation(async () => { const index = await ensureIndexUnlocked(); return refreshAvailability(index); }); }, async register(path: string, title?: string): Promise { const resolved = await canonicalize(path); if (!resolved.available) throw new Error('所选工作目录不存在或不可读取'); return mutate((index) => { const workspace = upsertWorkspace(index, resolved, path); if (title && !workspace.sessions.length) workspace.displayName ||= title.slice(0, 80); return { ...workspace, sessions: [...workspace.sessions] }; }); }, async findByPath(path: string): Promise { const resolved = await canonicalize(path); const workspaces = await workspaceIndexService.list(); const requested = resolve(path); return workspaces.find((item) => [item.canonicalPath, item.displayPath, ...(item.pathAliases ?? [])] .some((candidate) => candidate === resolved.canonicalPath || candidate === resolved.displayPath || candidate === requested)) ?? null; }, async touchSession(path: string, session: WorkspaceSessionRecord): Promise { if (isTemporaryWorkspace(path)) return; const resolved = await canonicalize(path); await mutate((index) => { const current = upsertWorkspace(index, resolved, path); mergeSession(current, session); current.lastActiveAt = Math.max(current.lastActiveAt, session.updatedAt); }); }, async setActive(path: string, sessionId: string): Promise { if (isTemporaryWorkspace(path)) return; const id = validateSessionId(sessionId); const resolved = await canonicalize(path); await mutate((index) => { const current = upsertWorkspace(index, resolved, path); current.activeSessionId = id; }); }, async removeSession(path: string, sessionId: string): Promise { const workspace = await workspaceIndexService.findByPath(path); if (!workspace) return; await mutate((index) => { const current = index.workspaces.find((item) => item.id === workspace.id); if (!current) return; current.sessions = current.sessions.filter((session) => session.id !== sessionId); if (current.activeSessionId === sessionId) current.activeSessionId = current.sessions[0]?.id; }); }, async removeWorkspace(pathOrId: string): Promise { const resolved = resolve(pathOrId); await mutate((index) => { index.workspaces = index.workspaces.filter((item) => item.id !== pathOrId && item.canonicalPath !== resolved && item.displayPath !== resolved); }); }, async recoverLegacy(): Promise { return mutate(async (index) => { const recovered = await legacyRecovery(); for (const candidate of recovered.workspaces) { const current = index.workspaces.find((item) => item.canonicalPath === candidate.canonicalPath); if (!current) index.workspaces.push(candidate); else { for (const session of candidate.sessions) mergeSession(current, session); current.lastActiveAt = Math.max(current.lastActiveAt, candidate.lastActiveAt); current.available ||= candidate.available; } } const known = new Set(index.recoverable.map((item) => `${item.fileName}:${item.reason}`)); for (const item of recovered.recoverable) { if (!known.has(`${item.fileName}:${item.reason}`)) index.recoverable.push(item); } return { workspaces: recovered.workspaces.length, sessions: recovered.workspaces.reduce((sum, workspace) => sum + workspace.sessions.length, 0), recoverable: recovered.recoverable, }; }); }, };