Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(worktree): close cleanup races
Kafeifei0b423d6a6d86
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.tsindex 763c8eb7ed..b621cac095 100644--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts@@ -601,6 +601,45 @@ describe('removeWorktreeForSession', () => {);});+ it('quarantines the worktree before the final ignored-file scan', async () => {+ const tmpRoot = fsSync.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-quarantine-'));+ try {+ const base = path.join(tmpRoot, 'repo');+ const worktreePath = path.join(base, '.xdt-worktrees', 's1');+ fsSync.mkdirSync(worktreePath, { recursive: true });+ const meta: WorktreeMeta = {+ ...makeMeta('s1'),+ baseRepo: base,+ path: worktreePath,+ };+ storeMap.set('s1', meta);+ ignoredFilesMock+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce(['.env']);++ await expect(+ manager.discardPrecreatedWorktree('s1', meta.path),+ ).resolves.toEqual({ status: 'preserved' });++ const moves = gitExecMock.mock.calls.filter(+ ([args]) => Array.isArray(args) && args[0] === 'worktree' && args[1] === 'move',+ );+ expect(moves).toHaveLength(2);+ const quarantinePath = moves[0][0][3] as string;+ expect(moves[0][0]).toEqual(['worktree', 'move', meta.path, quarantinePath]);+ expect(moves[1][0]).toEqual(['worktree', 'move', quarantinePath, meta.path]);+ expect(ignoredFilesMock).toHaveBeenNthCalledWith(1, base, meta.path);+ expect(ignoredFilesMock).toHaveBeenNthCalledWith(2, base, quarantinePath);+ expect(gitExecMock).not.toHaveBeenCalledWith(+ ['worktree', 'remove', quarantinePath],+ base,+ );+ expect(storeMap.get('s1')).toBe(meta);+ } finally {+ fsSync.rmSync(tmpRoot, { recursive: true, force: true });+ }+ });+it('discard pre-created: removes a clean worktree and its commit-equivalent generated branch', async () => {const meta = makeMeta('s1');storeMap.set('s1', meta);diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex 2f817eeef2..775af9ca36 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -10,6 +10,7 @@* 记录精确匹配的预创建 worktree,调用方还必须注入实时 ownership guard。*/+import { randomUUID } from 'node:crypto';import path from 'node:path';import fs from 'node:fs/promises';@@ -859,6 +860,29 @@ async function removeWorktreeForSessionInner(if (!(await canRemoveWorktree(options, meta.path, sessionId))) return;+ if (options.preserveDirty) {+ let ignoredFiles: string[];+ try {+ ignoredFiles = await listNonReproducibleIgnoredFiles(meta.baseRepo, meta.path);+ } catch (err) {+ log.warn(+ `[worktree] preserve worktree at ${meta.path}: ignored-file check failed`,+ err instanceof Error ? err.message : String(err),+ );+ return;+ }+ if (ignoredFiles.length > 0) {+ log.warn(+ `[worktree] preserved worktree at ${meta.path}: non-reproducible ignored files`,+ ignoredFiles.slice(0, 10),+ );+ return;+ }+ // ignored-file 对比可能读盘;完成后再核对一次 ownership,避免检查期间晚到的+ // maker:create-session 已认领目录却仍继续删除。+ if (!(await canRemoveWorktree(options, meta.path, sessionId))) return;+ }+const finishRemoval = async (snapshotted: boolean): Promise<void> => {if (snapshotted) {// The shared mutation lock is already installed before auto-stash starts. Unregister only@@ -882,27 +906,77 @@ async function removeWorktreeForSessionInner(return;}- if (options.preserveDirty) {+ let removalPath = meta.path;+ let quarantinePath: string | null = null;+ const restoreQuarantine = async (): Promise<boolean> => {+ if (!quarantinePath) return true;+ const currentQuarantinePath = quarantinePath;+ try {+ await gitExec(+ ['worktree', 'move', currentQuarantinePath, meta.path],+ meta.baseRepo,+ );+ quarantinePath = null;+ return true;+ } catch (err) {+ log.error(+ `[worktree] failed to restore quarantined worktree ${currentQuarantinePath}:`,+ err instanceof Error ? err.message : String(err),+ );+ // Preserve the actual path if the move-back itself fails; losing the+ // store entry would make the quarantined user data unreachable.+ await store.set(sessionId, { ...meta, path: currentQuarantinePath });+ return false;+ }+ };++ if (options.preserveDirty && await pathExists(meta.path)) {+ const candidate = `${meta.path}.xdt-removing-${randomUUID()}`;+ try {+ // Atomically move the registered worktree out of its user-visible path+ // before the final ignored-file scan. New writes through the old path+ // can no longer race the scan and the subsequent remove.+ await gitExec(['worktree', 'move', meta.path, candidate], meta.baseRepo);+ quarantinePath = candidate;+ removalPath = candidate;+ } catch (err) {+ log.warn(+ `[worktree] preserve worktree at ${meta.path}: quarantine move failed`,+ err instanceof Error ? err.message : String(err),+ );+ return;+ }++ // The move updates Git's worktree metadata, so both the final ownership+ // check and ignored-file scan can use the quarantined path.+ if (!(await canRemoveWorktree(options, removalPath, sessionId))) {+ await restoreQuarantine();+ return;+ }+let ignoredFiles: string[];try {- ignoredFiles = await listNonReproducibleIgnoredFiles(meta.baseRepo, meta.path);+ ignoredFiles = await listNonReproducibleIgnoredFiles(meta.baseRepo, removalPath);} catch (err) {log.warn(- `[worktree] preserve worktree at ${meta.path}: ignored-file check failed`,+ `[worktree] preserve worktree at ${removalPath}: ignored-file check failed`,err instanceof Error ? err.message : String(err),);+ await restoreQuarantine();return;}if (ignoredFiles.length > 0) {log.warn(- `[worktree] preserved worktree at ${meta.path}: non-reproducible ignored files`,+ `[worktree] preserved worktree at ${removalPath}: non-reproducible ignored files`,ignoredFiles.slice(0, 10),);+ await restoreQuarantine();+ return;+ }+ if (!(await canRemoveWorktree(options, removalPath, sessionId))) {+ await restoreQuarantine();return;}- // ignored-file 对比可能读盘;完成后再核对一次 ownership,避免检查期间晚到的- // maker:create-session 已认领目录却仍继续删除。- if (!(await canRemoveWorktree(options, meta.path, sessionId))) return;}let removedByGit = false;@@ -911,7 +985,7 @@ async function removeWorktreeForSessionInner(// preserveDirty 的前置探测与这里之间可能有人刚写入文件,非强制 remove 会拒绝,// 从而保留目录。普通会话删除已经有 auto-stash 保护,仍沿用 --force。const removeArgs = options.preserveDirty- ? ['worktree', 'remove', meta.path]+ ? ['worktree', 'remove', removalPath]: ['worktree', 'remove', '--force', meta.path];await gitExec(removeArgs, meta.baseRepo);removedByGit = true;@@ -922,7 +996,10 @@ async function removeWorktreeForSessionInner();// preserveDirty 是补偿口的“绝不丢用户新写内容”承诺。git 拒绝非强制删除时// 不能再用 fs.rm 绕过它,否则会重新打开 dirty check 后写入的竞态窗口。- if (options.preserveDirty) return;+ if (options.preserveDirty) {+ await restoreQuarantine();+ return;+ }// fallback: fs.rm —— 必须三条校验通过if (isManagedWorktreePath(meta.path, meta.baseRepo, [...store.getAllPaths(), meta.path])) {try {diff --git a/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts b/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.tsindex ac1c8b7131..11c19c73f6 100644--- a/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts+++ b/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts@@ -339,7 +339,7 @@ describe('createRemoteSessionWithPrecreatedWorktree', () => {expect(ledgerRecords).toHaveLength(1);});- it('does not attach an unowned legacy record to the current owner', async () => {+ it('migrates a path-only legacy record under an explicit owner binding', async () => {localStorage.setItem(__testing.storageKey, JSON.stringify({version: 1,records: [{@@ -350,6 +350,34 @@ describe('createRemoteSessionWithPrecreatedWorktree', () => {}],}));+ await expect(+ registerPendingRemotePrecreatedWorktree({+ dataOwnerId: 'owner-b',+ deviceId: DEVICE_ID,+ sessionId: SESSION_ID,+ path: WORKTREE_PATH,+ createdAt: Date.now(),+ }),+ ).resolves.toBe(true);+ expect(localStorage.getItem(__testing.storageKey)).toBeNull();+ expect(localStorage.getItem(__testing.storageOwnerKey)).toBeNull();+ expect(ledgerRecords).toEqual([+ expect.objectContaining({ dataOwnerId: 'owner-b' }),+ ]);+ });++ it('does not let another owner claim a legacy key already bound to the first owner', async () => {+ localStorage.setItem(__testing.storageKey, JSON.stringify({+ version: 1,+ records: [{+ deviceId: DEVICE_ID,+ sessionId: SESSION_ID,+ path: WORKTREE_PATH,+ createdAt: Date.now(),+ }],+ }));+ localStorage.setItem(__testing.storageOwnerKey, 'owner-a');+await expect(registerPendingRemotePrecreatedWorktree({dataOwnerId: 'owner-b',@@ -360,6 +388,7 @@ describe('createRemoteSessionWithPrecreatedWorktree', () => {}),).resolves.toBe(false);expect(localStorage.getItem(__testing.storageKey)).not.toBeNull();+ expect(localStorage.getItem(__testing.storageOwnerKey)).toBe('owner-a');expect(ledgerRecords).toEqual([]);});diff --git a/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts b/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.tsindex 60cfa10b1a..685c713ce6 100644--- a/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts+++ b/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts@@ -39,6 +39,7 @@ export interface RecoverPendingRemotePrecreatedWorktreesResult {}const STORAGE_KEY = 'xdt.desktop.remote-precreated-worktree-recovery.v1';+const STORAGE_OWNER_KEY = `${STORAGE_KEY}.owner`;const CLEANUP_PENDING_CODE = 'REMOTE_PRECREATED_WORKTREE_CLEANUP_PENDING';interface RemotePrecreatedWorktreeLedgerApi {@@ -106,28 +107,45 @@ async function migrateLegacyLedger(dataOwnerId?: string): Promise<boolean> {if (records.length === 0) {try {localStorage.removeItem(STORAGE_KEY);+ localStorage.removeItem(STORAGE_OWNER_KEY);return true;} catch {return false;}}- // A legacy global key has no trustworthy account context. Never attach an- // unowned record (or one belonging to another owner) to the currently- // signed-in account; retaining the key makes the obligation fail closed- // until a caller with an explicit matching owner can migrate it.- if (- !dataOwnerId- || records.some((record) => record.dataOwnerId !== dataOwnerId)- ) {+ if (!dataOwnerId) {return false;}try {+ const storedOwner = localStorage.getItem(STORAGE_OWNER_KEY)?.trim() || null;+ if (storedOwner && storedOwner !== dataOwnerId) {+ // The legacy key was first observed under another owner. Keep it+ // quarantined until that owner can complete the migration; otherwise an+ // account switch would attach old path-only records to the wrong user.+ return false;+ }+ if (+ records.some(+ (record) => record.dataOwnerId !== undefined && record.dataOwnerId !== dataOwnerId,+ )+ ) {+ return false;+ }+ if (!storedOwner) {+ // Bind the one-time migration before registering any record. A failed+ // write leaves the marker behind, so a later account cannot claim it.+ localStorage.setItem(STORAGE_OWNER_KEY, dataOwnerId);+ }for (const record of records) {- const result = await getLedgerApi().register(record);+ const result = await getLedgerApi().register({+ ...record,+ dataOwnerId,+ });if (!result.persisted) return false;}localStorage.removeItem(STORAGE_KEY);+ localStorage.removeItem(STORAGE_OWNER_KEY);return true;} catch {return false;@@ -331,6 +349,7 @@ export async function createRemoteSessionWithPrecreatedWorktree(export const __testing = {storageKey: STORAGE_KEY,+ storageOwnerKey: STORAGE_OWNER_KEY,setLedgerApi: (api: RemotePrecreatedWorktreeLedgerApi | null): void => {ledgerApiOverride = api;},