Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 持久化回收恢复中间状态
DavidShen2b1f0e8ba8b1
diff --git a/apps/desktop/src/main/localDb/ipc/session-share.ts b/apps/desktop/src/main/localDb/ipc/session-share.tsindex 331eca8dae..baa7518a31 100644--- a/apps/desktop/src/main/localDb/ipc/session-share.ts+++ b/apps/desktop/src/main/localDb/ipc/session-share.ts@@ -42,6 +42,7 @@ import { compactSessionToolResultsBestEffort } from '../toolResultCompaction.js'import {broadcastSessionPatched,captureSessionRecycleScope,+ requestSessionWorktreeRecycle,recycleSessionWorktreeForStatusChange,} from './sessions.js';@@ -190,7 +191,13 @@ export function registerSessionShareIpc(): void {};const result = await commitShareImport({ draftId, workingDir, draftPrefs, overwrite, useWorktree },- { dbClient: importDbClient, assertStillValid, refCompensationScope },+ {+ dbClient: importDbClient,+ assertStillValid,+ refCompensationScope,+ requestWorktreeRecycle: (sessionId) =>+ requestSessionWorktreeRecycle(importDbClient.drizzle, sessionId),+ },);// 覆盖事务成功后再执行不可随 SQLite 回滚的运行时/UI/资源收尾:// - 广播 patched 让 sidebar/会话视图立即移除旧任务;diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex a2a88ba1f2..6668304dc3 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -214,6 +214,14 @@ async function requestWorktreeRecycle(sessionId: string, resources: readonly strawait recycle(sessionId, resources);}+/** Persist a terminal cleanup intent using references from the same DB snapshot. */+export async function requestSessionWorktreeRecycle(+ db: DbClient['drizzle'],+ sessionId: string,+): Promise<void> {+ await requestWorktreeRecycle(sessionId, await readSessionWorktreeResources(db, sessionId));+}+/** Read from the same captured database that will receive the status/path update. */async function readSessionWorktreeResources(db: DbClient['drizzle'], sessionId: string): Promise<string[]> {try {diff --git a/apps/desktop/src/main/session-share/sessionShareImport.ts b/apps/desktop/src/main/session-share/sessionShareImport.tsindex 8c43f5350f..029153e8fe 100644--- a/apps/desktop/src/main/session-share/sessionShareImport.ts+++ b/apps/desktop/src/main/session-share/sessionShareImport.ts@@ -261,6 +261,8 @@ export interface CommitShareImportRuntimeScope {dbClient: DbClient;assertStillValid(): void;refCompensationScope: MediaRefCompensationScope;+ /** Persist cleanup intent before an overwrite transaction marks old sessions deleted. */+ requestWorktreeRecycle?: (sessionId: string) => Promise<void>;}export interface CommitShareImportResult {@@ -556,6 +558,15 @@ export async function commitShareImport(}}+ // The overwrite transaction below marks these sessions deleted. Persist the+ // worktree cleanup intent first so a process exit between the two operations+ // cannot strand their directories without a durable recycle request.+ if (runtimeScope.requestWorktreeRecycle) {+ for (const existing of conflictExisting) {+ await guarded(() => runtimeScope.requestWorktreeRecycle!(existing.id));+ }+ }+const projectsRoot =opts.projectsRootOverride ?? path.join(defaultClaudeConfigDirCandidates()[0], 'projects');// codex:desktop state DB / rollout 里的残留 thread 不再单独当冲突拦截,diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.tsindex 189a2e272a..780890fc3a 100644--- a/apps/desktop/src/main/worktree/recycleJournal.ts+++ b/apps/desktop/src/main/worktree/recycleJournal.ts@@ -27,6 +27,8 @@ export interface WorktreeRecycleRecord {directoryIdentity?: string | null;snapshot?: { head: string; headRef?: string | null; tree: string; indexTree: string; commit: string; ref: string; indexHash: string };restoredGeneration?: string;+ /** Temporary checkout used to repair a partially removed worktree. */+ restoreCheckoutPath?: string;archive?: WorktreeRecoveryArchive;}@@ -45,6 +47,8 @@ function parseRecord(raw: string, id: string): WorktreeRecycleRecord {|| typeof record.meta.sessionId !== 'string' || !record.meta.sessionId|| typeof record.meta.path !== 'string' || !path.isAbsolute(record.meta.path)|| typeof record.meta.baseRepo !== 'string' || !path.isAbsolute(record.meta.baseRepo)+ || (record.restoreCheckoutPath !== undefined+ && (typeof record.restoreCheckoutPath !== 'string' || !path.isAbsolute(record.restoreCheckoutPath)))|| typeof record.requestedAt !== 'string' || !Number.isFinite(Date.parse(record.requestedAt))|| !Number.isInteger(record.attempts) || record.attempts < 0|| !Number.isFinite(record.nextAttemptAt)diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.tsindex 8af4bed6d5..2e5af33c95 100644--- a/apps/desktop/src/main/worktree/restoreRecovery.ts+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts@@ -14,6 +14,17 @@ import * as store from './worktreeStore';import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';import { readWorktreeHeadRef } from './contentSnapshot';+function restoreCheckoutPathIsSafe(value: string): boolean {+ if (!path.isAbsolute(value)) return false;+ const root = path.resolve(os.tmpdir());+ const relative = path.relative(root, value);+ const parts = relative.split(path.sep);+ return parts.length === 2+ && parts[0].startsWith('cindy-worktree-restore-')+ && /^[0-9a-f-]{36}$/i.test(parts[0].slice('cindy-worktree-restore-'.length))+ && parts[1] === 'checkout';+}+async function indexIsRestorable(worktreePath: string, indexTree: string): Promise<boolean> {const { stdout } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);try { await fs.lstat(stdout.trim()); } catch (error) {@@ -109,23 +120,53 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: srecord.restoredGeneration ??= randomUUID();await writeRecycleRecord(record);const gitLink = path.join(worktreePath, '.git');+ let gitLinkExists = true;try {await fs.lstat(gitLink);} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ gitLinkExists = false;+ }+ if (!gitLinkExists || record.restoreCheckoutPath) {// Repair a partially deleted worktree without deleting any remaining user file.- const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-restore-'));- const checkout = path.join(temp, 'checkout');+ // Persist the temporary checkout before creating it so a crash after `worktree add`+ // can resume the same checkout instead of leaving its branch permanently occupied.+ const checkout = record.restoreCheckoutPath ?? path.join(+ os.tmpdir(), `cindy-worktree-restore-${randomUUID()}`, 'checkout',+ );+ if (!restoreCheckoutPathIsSafe(checkout)) return false;+ if (record.restoreCheckoutPath !== checkout) {+ record.restoreCheckoutPath = checkout;+ await writeRecycleRecord(record);+ }+ const checkoutRoot = path.dirname(checkout);+ let checkoutEntries: string[] | null = null;try {- await gitExec(['worktree', 'prune'], record.meta.baseRepo);- // Git checks branch occupancy itself; no --force/-B may bypass another checkout.- const target = headRef ? headRef.slice('refs/heads/'.length) : record.snapshot.head;+ const stat = await fs.lstat(checkout);+ if (!stat.isDirectory() || stat.isSymbolicLink()) return false;+ checkoutEntries = await fs.readdir(checkout);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ await gitExec(['worktree', 'prune'], record.meta.baseRepo);+ // Git checks branch occupancy itself; no --force/-B may bypass another checkout.+ const target = headRef ? headRef.slice('refs/heads/'.length) : record.snapshot.head;+ if (checkoutEntries === null || checkoutEntries.length === 0) {+ await fs.mkdir(checkoutRoot, { recursive: true });await gitExec(['worktree', 'add', '--no-checkout', ...(headRef ? [] : ['--detach']), checkout, target], record.meta.baseRepo);+ } else if (!checkoutEntries.includes('.git')) {+ // Never delete or adopt an unexpected non-empty temporary directory.+ return false;+ }+ try {await fs.copyFile(path.join(checkout, '.git'), gitLink, constants.COPYFILE_EXCL);- await gitExec(['worktree', 'repair', worktreePath], record.meta.baseRepo);- } finally {- await fs.rm(temp, { recursive: true, force: true });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;}+ await gitExec(['worktree', 'repair', worktreePath], record.meta.baseRepo);+ await fs.rm(checkoutRoot, { recursive: true, force: true });+ record.restoreCheckoutPath = undefined;+ await writeRecycleRecord(record);}await assertManagedResourcePath(record.meta, [worktreePath]);await assertWorktreeGitIdentity(record.meta);