Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(worktree): persist lease retries and recovery state

DavidShenc114a7263c7b
diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
index 0340b15655..01da67bb34 100644
--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
@@ -29,7 +29,7 @@ vi.mock('../worktree/gitExec', async (original) => {
import { recycleManagedWorktree } from '../worktree/managedRecycle';
import { restoreRecordedWorktree } from '../worktree/restoreRecovery';
-import { readRecycleRecord } from '../worktree/recycleJournal';
+import { readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournal';
import { captureWorktreeContent } from '../worktree/contentSnapshot';
import { gitExec } from '../worktree/gitExec';
@@ -211,6 +211,19 @@ describe('worktree recovery with real Git and encrypted archives', () => {
expect(await fs.readFile(path.join(previous.path, 'draft.txt'), 'utf8')).toBe('history contents\n');
}, 30_000);
+ it('resumes after a crash between recovery mkdir and directory identity journal', async () => {
+ const meta = await createFixture('mkdir-crash');
+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);
+ const record = (await readRecycleRecord(meta.path))!;
+ record.phase = 'restoring';
+ record.directoryIdentity = null;
+ record.restoredGeneration = 'resume-generation';
+ await writeRecycleRecord(record);
+ await fs.mkdir(meta.path);
+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);
+ expect((await readRecycleRecord(meta.path))?.phase).toBe('restored');
+ }, 30_000);
+
it('preserves submodule-only commits whose Git objects lie outside the archived directory', async () => {
const origin = path.join(state.root, 'child-origin');
await fs.mkdir(origin);
diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
index 80a4bdd0a9..997ef23730 100644
--- a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
@@ -14,6 +14,7 @@ const read = vi.hoisted(() => vi.fn());
const watch = vi.hoisted(() => vi.fn());
const closeWatch = vi.hoisted(() => vi.fn());
const client = vi.hoisted(() => ({ readLocalWorktreeReferences: vi.fn() }));
+vi.mock('../worktree/runtimeLeases', () => ({ retryPendingWorktreeRuntimeLeaseReleases: vi.fn(async () => 0) }));
vi.mock('../localDb/client/current', () => ({ getDbClient: () => client }));
vi.mock('../worktree/managedRecycle', () => ({ recycleManagedWorktree: remove }));
vi.mock('../worktree/worktreeStore', () => ({ get: () => null, getAll: () => [] }));
diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
index 131bae701f..1bf2bc1641 100644
--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
@@ -8,7 +8,7 @@ const notify = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({ app: { getPath: () => state.root } }));
vi.mock('../worktree/recycleEvents', () => ({ notifyWorktreeRecycleOpportunity: notify }));
-import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths } from '../worktree/runtimeLeases';
+import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths, retryPendingWorktreeRuntimeLeaseReleases } from '../worktree/runtimeLeases';
import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';
describe('worktree runtime evidence and physical locks', () => {
@@ -45,6 +45,19 @@ describe('worktree runtime evidence and physical locks', () => {
expect(await readWorktreeRuntimePaths()).toEqual(new Set());
});
+ it('persists a failed release and retries it without treating a dead PID as idle', async () => {
+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;
+ const unlink = vi.spyOn(fs, 'unlink').mockImplementationOnce(async () => {
+ throw Object.assign(new Error('busy'), { code: 'EBUSY' });
+ });
+ await expect(releaseWorktreeRuntimeLease(lease)).rejects.toMatchObject({ code: 'EBUSY' });
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));
+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(0);
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ expect(notify).toHaveBeenCalledTimes(2);
+ unlink.mockRestore();
+ });
+
it('cleans only the failed acquisition when publishing a replacement lease fails', async () => {
const oldLease = (await acquireWorktreeRuntimeLease('one', worktree))!;
const write = fs.writeFile.bind(fs);
diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.ts
index 4670c7b04b..189a2e272a 100644
--- a/apps/desktop/src/main/worktree/recycleJournal.ts
+++ b/apps/desktop/src/main/worktree/recycleJournal.ts
@@ -23,7 +23,8 @@ export interface WorktreeRecycleRecord {
attempts: number;
nextAttemptAt: number;
reason?: string;
- directoryIdentity?: string;
+ /** null is a durable marker that recovery has reserved a previously absent directory. */
+ directoryIdentity?: string | null;
snapshot?: { head: string; headRef?: string | null; tree: string; indexTree: string; commit: string; ref: string; indexHash: string };
restoredGeneration?: string;
archive?: WorktreeRecoveryArchive;
diff --git a/apps/desktop/src/main/worktree/recycleMaintenance.ts b/apps/desktop/src/main/worktree/recycleMaintenance.ts
index 4415875765..4d16de7a0b 100644
--- a/apps/desktop/src/main/worktree/recycleMaintenance.ts
+++ b/apps/desktop/src/main/worktree/recycleMaintenance.ts
@@ -10,6 +10,7 @@ import { hasLiveSessionReference, loadLiveSessionPathKeys, pathKey } from './liv
import * as store from './worktreeStore';
import { physicalWorktreeKey } from './resourceLock';
import { subscribeWorktreeRecycleEvents } from './recycleEvents';
+import { retryPendingWorktreeRuntimeLeaseReleases } from './runtimeLeases';
const log = createLogger('worktreeRecycleMaintenance');
let maintenance: WorktreeRecycleMaintenance | null = null;
@@ -127,6 +128,10 @@ export class WorktreeRecycleMaintenance {
if (!this.options.isReady()) return;
await this.ensureWatcher();
if (this.stopped) return;
+ let pendingLeaseReleases = 0;
+ try { pendingLeaseReleases = await retryPendingWorktreeRuntimeLeaseReleases(); }
+ catch (error) { log.warn('worktree runtime lease release retry postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' }); pendingLeaseReleases = 1; }
+ if (pendingLeaseReleases > 0) this.schedule(Date.now() + retryDelay(1));
const records = await listRecycleRecords();
const wakeIds = new Set(this.wakeIds);
this.wakeIds.clear();
diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.ts
index fa96619602..62d06a073c 100644
--- a/apps/desktop/src/main/worktree/restoreRecovery.ts
+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts
@@ -60,7 +60,15 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
- if (identity !== null && identity !== record.directoryIdentity) return false;
+ const reservedRecoveryDirectory = record.phase === 'restoring' && record.directoryIdentity == null;
+ if (identity !== null && !reservedRecoveryDirectory && identity !== record.directoryIdentity) return false;
+ if (identity !== null && reservedRecoveryDirectory) {
+ // A crash may have happened after mkdir and before its identity was journaled.
+ // Only an empty directory can be adopted; user bytes always stop recovery.
+ if ((await fs.readdir(worktreePath)).length !== 0) return false;
+ record.directoryIdentity = identity;
+ await writeRecycleRecord(record);
+ }
if (identity !== null) {
if (record.phase === 'snapshotted') {
// Snapshotting never mutates the live checkout. Cancelling recycling needs no apply.
@@ -80,6 +88,10 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s
}
if (!legacyGuardHeld()) return false;
if (identity === null) {
+ record.phase = 'restoring';
+ record.restoredGeneration ??= randomUUID();
+ record.directoryIdentity = null;
+ await writeRecycleRecord(record);
await fs.mkdir(worktreePath, { recursive: false });
const stat = await fs.lstat(worktreePath);
record.directoryIdentity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.ts
index 916cbb4859..488a34ef0d 100644
--- a/apps/desktop/src/main/worktree/runtimeLeases.ts
+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts
@@ -27,6 +27,9 @@ function leaseFile(sessionId: string): string {
return path.join(runtimeRoot(), `${process.pid}-${key}.json`);
}
+const leaseNamePattern = /^\d+-[a-f0-9]{64}\.json$/;
+const releaseRequestPattern = /^\d+-[a-f0-9]{64}\.json\.release$/;
+
/** A startup owns its own file, even when the business task id is reused. */
export interface WorktreeRuntimeLease {
readonly file: string;
@@ -58,12 +61,56 @@ export async function acquireWorktreeRuntimeLease(sessionId: string, cwd: string
export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease): Promise<void> {
try { await fs.unlink(lease.file); } catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ await fs.unlink(`${lease.file}.release`).catch(() => undefined);
+ return;
+ }
+ // Keep an explicit, durable intent. The lease itself remains protective until
+ // a later maintenance pass can prove that this terminal cleanup succeeded.
+ try {
+ await fs.mkdir(runtimeRoot(), { recursive: true });
+ await fs.writeFile(`${lease.file}.release`, JSON.stringify({ version: 1, file: lease.file, path: lease.physicalPath }), { flag: 'wx', mode: 0o600 });
+ } catch { /* preserving the lease is the safe fallback */ }
+ // Wake the event-driven maintenance loop; it will retry the durable intent
+ // while the still-present lease continues to protect the worktree.
+ notifyWorktreeRecycleOpportunity(lease.physicalPath);
throw error;
}
+ await fs.unlink(`${lease.file}.release`).catch(() => undefined);
notifyWorktreeRecycleOpportunity(lease.physicalPath);
}
+/** Retry only release intents written by a terminal close path. Unknown files stay protective. */
+export async function retryPendingWorktreeRuntimeLeaseReleases(): Promise<number> {
+ let names: string[];
+ try { names = await fs.readdir(runtimeRoot()); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 0;
+ throw error;
+ }
+ let pending = 0;
+ for (const name of names.filter((value) => releaseRequestPattern.test(value))) {
+ const requestFile = path.join(runtimeRoot(), name);
+ try {
+ const request = JSON.parse(await fs.readFile(requestFile, 'utf8')) as { version?: number; file?: string; path?: string };
+ if (request.version !== 1 || typeof request.file !== 'string' || typeof request.path !== 'string'
+ || path.dirname(request.file) !== runtimeRoot() || !leaseNamePattern.test(path.basename(request.file))) {
+ pending++;
+ continue;
+ }
+ try { await fs.unlink(request.file); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { pending++; continue; }
+ }
+ await fs.unlink(requestFile).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ });
+ notifyWorktreeRecycleOpportunity(request.path);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') pending++;
+ }
+ }
+ return pending;
+}
+
function pidMayBeAlive(pid: number): boolean {
try {
process.kill(pid, 0);
@@ -116,7 +163,7 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {
}
const paths = new Set<string>();
for (const name of leases) {
- const match = /^(\d+)-[a-f0-9]{64}\.json$/.exec(name);
+ const match = leaseNamePattern.exec(name);
if (!match) continue;
// Main may have crashed while a detached child still uses the directory.
// Only explicit lease release proves that startup stopped; a dead owner PID