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(desktop): schedule worktree recycling on demand and limit concurrency

DavidShenf8d267660789
diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
index 7fc9a37dc6..bd62e084a3 100644
--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
@@ -65,6 +65,28 @@ describe('shared worktree recycling', () => {
});
const recycle = () => recycleManagedWorktree(meta, { canRemove: async () => removable });
+ it('limits simultaneous recycling of distinct resources to one', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ let active = 0;
+ let peak = 0;
+ let checked = 0;
+ const jobs = Array.from({ length: 12 }, (_, index) => {
+ const candidate = { ...meta, sessionId: `batch-${index}`, path: path.join(path.dirname(meta.path), `batch-${index}`) };
+ state.registry.set(candidate.sessionId, candidate);
+ return recycleManagedWorktree(candidate, { canRemove: async () => {
+ active++; peak = Math.max(peak, active); checked++;
+ try { await gate; return false; } finally { active--; }
+ } });
+ });
+ try {
+ await vi.waitFor(() => expect(active).toBe(1));
+ expect(checked).toBe(1);
+ } finally { release(); }
+ expect(await Promise.all(jobs)).toEqual(Array(12).fill(false));
+ expect(checked).toBe(12); expect(peak).toBe(1);
+ });
+
it('keeps content recoverable and drops registration only after the directory is gone', async () => {
const order: string[] = [];
archive.mockImplementation(async () => { order.push('archive'); return { files: await inventoryWorktree(meta.path) }; });
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 46c4cedff1..7147585e06 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -90,6 +90,7 @@ import {
setSessionsStatusInDb,
} from '../localDb/ipc/sessions.js';
import { setSessionRouteLockImplementation } from '../localDb/sessionRouteLock.js';
+import { queueSessionWorktreeRecycle } from '../worktree/recycleQueue';
beforeEach(() => {
vi.clearAllMocks();
@@ -121,6 +122,50 @@ afterEach(() => {
});
describe('setSessionsStatusInDb', () => {
+ it('returns batch status changes promptly and serializes their cleanup chains', async () => {
+ const ids = ['one', 'two', 'three'];
+ h.tx.mockResolvedValueOnce(ids.map((sessionId) => ({ sessionId, status: 'archived', workingDir: null })));
+ let finish!: () => void;
+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ await setSessionsStatusInDb(ids, 'archived');
+ try {
+ await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());
+ expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');
+ for (const sessionId of ids) expect(h.webContentsSend).toHaveBeenCalledWith(
+ 'local-db:sessions:patched', { sessionId, patch: { status: 'archived' } },
+ );
+ } finally { finish?.(); }
+ await queueSessionWorktreeRecycle(async () => {});
+ expect(h.recycleWorktreeForRemovedSession.mock.calls.map(([id]) => id)).toEqual(ids);
+ });
+
+ it('rechecks a queued task restored to active while an earlier cleanup runs', async () => {
+ let finish!: () => void;
+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const first = recycleSessionWorktreeForStatusChange('one', 'archived');
+ const second = recycleSessionWorktreeForStatusChange('two', 'archived');
+ try {
+ await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());
+ h.isSessionStillRemovable.mockImplementation(async (id) => id !== 'two');
+ } finally { finish?.(); }
+ await Promise.all([first, second]);
+ expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');
+ });
+
+ it('retains the captured database while cleanup waits in the queue', async () => {
+ let finish!: () => void;
+ const savedDb = h.drizzle;
+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const first = recycleSessionWorktreeForStatusChange('one', 'archived');
+ const second = recycleSessionWorktreeForStatusChange('two', 'archived');
+ try {
+ await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());
+ h.drizzle = {};
+ finish(); await Promise.all([first, second]);
+ expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');
+ } finally { finish?.(); h.drizzle = savedDb; }
+ });
+
it('persists shared resource intent before the terminal transaction', async () => {
const worktree = path.join(h.userDataPath, 'repo', '.cindy-worktrees', 'one');
h.readBindings.mockResolvedValue([{ workingDir: path.join(worktree, 'src'), worktreePath: null, remoteHostId: null }]);
diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleJournalFilesystem.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleJournalFilesystem.test.ts
new file mode 100644
index 0000000000..5da40a5f03
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/worktreeRecycleJournalFilesystem.test.ts
@@ -0,0 +1,28 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+const state = vi.hoisted(() => ({ root: '' }));
+vi.mock('electron', () => ({ app: { getPath: () => state.root } }));
+import { recycleJournalRoot, watchRecycleJournal } from '../worktree/recycleJournal';
+
+describe('native worktree journal watcher', () => {
+ let stop: (() => void) | undefined;
+ beforeEach(async () => { state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-recycle-watch-')); });
+ afterEach(async () => { stop?.(); await fs.rm(state.root, { recursive: true, force: true }); });
+
+ it('detects atomic replacements from an independent file writer', async () => {
+ const changed = vi.fn(); const error = vi.fn();
+ stop = await watchRecycleJournal(changed, error);
+ const target = path.join(recycleJournalRoot(), 'a'.repeat(64) + '.json');
+ await fs.writeFile(target + '.tmp', '{}');
+ await fs.rename(target + '.tmp', target);
+ await vi.waitFor(() => expect(changed).toHaveBeenCalled());
+ changed.mockClear();
+ await fs.writeFile(target + '.tmp', '{"updated":true}');
+ await fs.rename(target + '.tmp', target);
+ await vi.waitFor(() => expect(changed).toHaveBeenCalled());
+ expect(error).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleJournalWatch.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleJournalWatch.test.ts
new file mode 100644
index 0000000000..7bf4f32eaf
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/worktreeRecycleJournalWatch.test.ts
@@ -0,0 +1,36 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
+
+const mocks = vi.hoisted(() => ({ watch: vi.fn(), mkdir: vi.fn(), close: vi.fn(), on: vi.fn() }));
+vi.mock('electron', () => ({ app: { getPath: () => path.resolve('test-user-data') } }));
+vi.mock('node:fs', async (original) => ({ ...await original<typeof import('node:fs')>(), watch: mocks.watch }));
+vi.mock('node:fs/promises', async (original) => {
+ const fs = await original<typeof import('node:fs/promises')>();
+ return { ...fs, default: { ...fs, mkdir: mocks.mkdir } };
+});
+import { watchRecycleJournal } from '../worktree/recycleJournal';
+
+describe('worktree journal notifications', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.mkdir.mockResolvedValue(undefined);
+ mocks.watch.mockReturnValue({ on: mocks.on, close: mocks.close });
+ });
+ it('listens for atomic journal replacements without watching recovery archive writes', async () => {
+ const changed = vi.fn(); const error = vi.fn();
+ const stop = await watchRecycleJournal(changed, error);
+ expect(mocks.watch).toHaveBeenCalledWith(path.join(path.resolve('test-user-data'), 'worktree-recycle'), { persistent: false }, expect.any(Function));
+ const listener = mocks.watch.mock.calls[0][2];
+ const id = 'a'.repeat(64);
+ for (const name of [id + '.json.tmp', id + '.tar.gz.enc', 'history']) listener('rename', name);
+ expect(changed).not.toHaveBeenCalled();
+ listener('rename', id + '.json'); listener('change', Buffer.from(id + '.json')); listener('rename', null);
+ expect(changed).toHaveBeenCalledTimes(3);
+ expect(mocks.on).toHaveBeenCalledWith('error', error);
+ stop(); expect(mocks.close).toHaveBeenCalledOnce();
+ });
+ it('propagates watch setup failures so maintenance can retry them', async () => {
+ mocks.watch.mockImplementationOnce(() => { throw new Error('watch unavailable'); });
+ await expect(watchRecycleJournal(vi.fn(), vi.fn())).rejects.toThrow('watch unavailable');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
index 30d5fae5be..80a4bdd0a9 100644
--- a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
@@ -1,73 +1,199 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
import type { WorktreeRecycleRecord } from '../worktree/recycleJournal';
-const state = vi.hoisted(() => ({ rows: [] as Array<{ id: string; status: string; source: string; currentDatabase: boolean }>, records: [] as WorktreeRecycleRecord[] }));
+const state = vi.hoisted(() => ({
+ rows: [] as Array<{ id: string; status: string; source: string; currentDatabase: boolean }>,
+ records: [] as WorktreeRecycleRecord[],
+ changed: () => {},
+ watchError: (_error: unknown) => {},
+}));
const remove = vi.hoisted(() => vi.fn());
+const list = vi.hoisted(() => vi.fn());
+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('../localDb/client/current', () => ({ getDbClient: () => client }));
vi.mock('../worktree/managedRecycle', () => ({ recycleManagedWorktree: remove }));
vi.mock('../worktree/worktreeStore', () => ({ get: () => null, getAll: () => [] }));
vi.mock('../worktree/liveSessionRefs', () => ({ loadLiveSessionPathKeys: async () => new Set(), hasLiveSessionReference: () => false, pathKey: (value: string) => value }));
vi.mock('../worktree/recycleJournal', () => ({
- listRecycleRecords: async () => state.records,
- readRecycleRecord: async () => state.records[0] ?? null,
+ listRecycleRecords: list,
+ readRecycleRecord: read,
worktreeGeneration: () => 'one',
+ watchRecycleJournal: watch,
}));
-import { runWorktreeRecycleMaintenance, stopWorktreeRecycleMaintenance } from '../worktree/recycleMaintenance';
+import { WorktreeRecycleMaintenance } from '../worktree/recycleMaintenance';
+import { notifyWorktreeRecycleOpportunity, notifyWorktreeRecycleRecordChanged } from '../worktree/recycleEvents';
+import { worktreeResourceId } from '../worktree/resourceLock';
+
+function record(sessionId = 'owner', nextAttemptAt = 0): WorktreeRecycleRecord {
+ const baseRepo = path.resolve('test-repo');
+ const worktreePath = path.join(baseRepo, '.cindy-worktrees', sessionId);
+ return {
+ version: 1, id: worktreeResourceId(worktreePath), generation: 'one', phase: 'pending',
+ meta: { sessionId, path: worktreePath, baseRepo, name: sessionId, branch: 'cindy/' + sessionId, sourceBranch: 'main', createdAt: '2026-09-08T00:00:00Z' },
+ requestedAt: '2026-09-08T00:00:00Z', nextAttemptAt, attempts: 0,
+ };
+}
describe('durable worktree maintenance', () => {
let ready: boolean;
+ let maintenance: WorktreeRecycleMaintenance;
const closeAndRecycle = vi.fn();
- const run = (force = false) => runWorktreeRecycleMaintenance({ isReady: () => ready, recycleCurrentSession: closeAndRecycle }, force);
beforeEach(() => {
- stopWorktreeRecycleMaintenance(); ready = true;
- state.records = [{ version: 1, id: 'resource', generation: 'one', meta: { sessionId: 'owner', path: 'resource' }, phase: 'pending', nextAttemptAt: 0, attempts: 0 }] as WorktreeRecycleRecord[];
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-08T00:00:00Z'));
+ ready = true;
+ state.records = [record()];
state.rows = [{ id: 'owner', status: 'archived', source: 'desktop', currentDatabase: true }];
closeAndRecycle.mockReset().mockResolvedValue(undefined);
remove.mockReset().mockResolvedValue(true);
+ list.mockReset().mockImplementation(async () => [...state.records]);
+ read.mockReset().mockImplementation(async (value: string) => state.records.find((item) => item.meta.path === value) ?? null);
+ closeWatch.mockReset();
+ watch.mockReset().mockImplementation(async (changed, error) => {
+ state.changed = changed; state.watchError = error; return closeWatch;
+ });
client.readLocalWorktreeReferences.mockReset().mockImplementation(async () => state.rows);
+ maintenance = new WorktreeRecycleMaintenance({ isReady: () => ready, recycleCurrentSession: closeAndRecycle });
});
- it('waits for both database and runtime services', async () => {
- ready = false; await run(); expect(closeAndRecycle).not.toHaveBeenCalled();
- ready = true; await run(); expect(closeAndRecycle).toHaveBeenCalledWith('owner', 'archived');
+ afterEach(() => { maintenance.stop(); vi.useRealTimers(); });
+
+ it('waits for both database and runtime services without polling readiness', async () => {
+ ready = false; await maintenance.start();
+ expect(vi.getTimerCount()).toBe(0); expect(watch).not.toHaveBeenCalled();
+ expect(closeAndRecycle).not.toHaveBeenCalled();
+ ready = true; await maintenance.start();
+ expect(closeAndRecycle).toHaveBeenCalledWith('owner', 'archived'); expect(watch).toHaveBeenCalledOnce();
});
it('does not infer deletion from a row missing in the local view', async () => {
- state.rows = []; await run(); expect(remove).not.toHaveBeenCalled(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ state.rows = []; await maintenance.start();
+ expect(remove).not.toHaveBeenCalled(); expect(closeAndRecycle).not.toHaveBeenCalled();
});
- it('does not re-enqueue historical registrations without an explicit request', async () => {
- state.records = []; await run(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ it('leaves an empty queue idle without reading databases or scanning historical registrations', async () => {
+ state.records = []; await maintenance.start();
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ expect(list).toHaveBeenCalledOnce(); expect(client.readLocalWorktreeReferences).not.toHaveBeenCalled();
+ expect(closeAndRecycle).not.toHaveBeenCalled();
+ });
+ it('does not schedule completed recovery records', async () => {
+ state.records[0].phase = 'removed';
+ state.records.push({ ...record('restored'), phase: 'restored' });
+ await maintenance.start();
+ expect(vi.getTimerCount()).toBe(0); expect(client.readLocalWorktreeReferences).not.toHaveBeenCalled();
});
it('does not close a task through another selected database', async () => {
state.rows[0].currentDatabase = false;
- await run(); expect(closeAndRecycle).not.toHaveBeenCalled(); expect(remove).toHaveBeenCalledOnce();
+ await maintenance.start(); expect(closeAndRecycle).not.toHaveBeenCalled(); expect(remove).toHaveBeenCalledOnce();
const guard = remove.mock.calls[0][1].canRemove;
expect(await guard()).toBe(true);
state.rows[0].status = 'active'; expect(await guard()).toBe(false);
});
+ it('uses one timer for the earliest request with no intermediate 30-second scans', async () => {
+ state.records[0].nextAttemptAt = Date.now() + 90_000;
+ state.records.push(record('second', Date.now() + 120_000)); state.rows.push({ ...state.rows[0], id: 'second' });
+ closeAndRecycle.mockImplementation(async (id) => { state.records.find((r) => r.meta.sessionId === id)!.phase = 'removed'; });
+ await maintenance.start(); expect(vi.getTimerCount()).toBe(1);
+ await vi.advanceTimersByTimeAsync(89_999);
+ expect(list).toHaveBeenCalledOnce(); expect(client.readLocalWorktreeReferences).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(closeAndRecycle).toHaveBeenCalledExactlyOnceWith('owner', 'archived'); expect(vi.getTimerCount()).toBe(1);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(closeAndRecycle).toHaveBeenLastCalledWith('second', 'archived'); expect(vi.getTimerCount()).toBe(0);
+ });
it('coalesces overlapping ready events without concurrent cleanup', async () => {
let finish!: () => void;
closeAndRecycle.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
- const first = run();
- await vi.waitFor(() => expect(closeAndRecycle).toHaveBeenCalledOnce());
- const second = run();
- expect(second).toBe(first);
+ const first = maintenance.start(); await vi.advanceTimersByTimeAsync(0);
+ const second = maintenance.run(); expect(second).toBe(first);
expect(closeAndRecycle).toHaveBeenCalledOnce(); finish(); await first;
- expect(closeAndRecycle).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(100); expect(closeAndRecycle).toHaveBeenCalledOnce();
});
- it('honors backoff but permits a wakeup after runtime occupancy changes', async () => {
+ it('wakes only the released resource instead of bypassing every request backoff', async () => {
state.records[0].nextAttemptAt = Date.now() + 60_000;
- await run(); expect(closeAndRecycle).not.toHaveBeenCalled();
- await run(true); expect(closeAndRecycle).toHaveBeenCalledOnce();
+ state.records.push(record('second', Date.now() + 60_000)); state.rows.push({ ...state.rows[0], id: 'second' });
+ await maintenance.start(); notifyWorktreeRecycleOpportunity(state.records[0].meta.path);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(closeAndRecycle).toHaveBeenCalledExactlyOnceWith('owner', 'archived');
});
- it('bounds automatic attempts within a process lifetime', async () => {
- for (let index = 0; index < 12; index++) await run();
- expect(closeAndRecycle).toHaveBeenCalledTimes(8);
+ it('bounds automatic retries and lets a resource event renew that budget', async () => {
+ await maintenance.start(); await vi.runAllTimersAsync();
+ expect(closeAndRecycle).toHaveBeenCalledTimes(8); expect(vi.getTimerCount()).toBe(0);
+ notifyWorktreeRecycleOpportunity(state.records[0].meta.path);
+ await vi.advanceTimersByTimeAsync(100); expect(closeAndRecycle).toHaveBeenCalledTimes(9);
});
it('continues with other resources after one request fails', async () => {
- state.records.push({ ...state.records[0], id: 'another-resource', meta: { ...state.records[0].meta, sessionId: 'second' } });
- state.rows.push({ ...state.rows[0], id: 'second' });
+ state.records.push(record('second')); state.rows.push({ ...state.rows[0], id: 'second' });
closeAndRecycle.mockRejectedValueOnce(new Error('lock busy'));
- await run();
- expect(closeAndRecycle).toHaveBeenLastCalledWith('second', 'archived');
+ await maintenance.start(); expect(closeAndRecycle).toHaveBeenLastCalledWith('second', 'archived');
+ });
+ it('isolates a journal read failure to its own resource', async () => {
+ state.records.push(record('second')); state.rows.push({ ...state.rows[0], id: 'second' });
+ read.mockRejectedValueOnce(new Error('journal unavailable'));
+ await maintenance.start(); expect(closeAndRecycle).toHaveBeenCalledExactlyOnceWith('second', 'archived');
+ });
+ it('rechecks readiness after asynchronously reading a request', async () => {
+ read.mockImplementationOnce(async () => { ready = false; return state.records[0]; });
+ await maintenance.start(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it('does not fan out a startup batch while the first cleanup is still running', async () => {
+ state.records.push(record('second')); state.rows.push({ ...state.rows[0], id: 'second' });
+ let finish!: () => void;
+ closeAndRecycle.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const running = maintenance.start();
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ expect(closeAndRecycle).toHaveBeenCalledExactlyOnceWith('owner', 'archived');
+ } finally { finish?.(); }
+ await running; expect(closeAndRecycle).toHaveBeenLastCalledWith('second', 'archived');
+ });
+ it('coalesces cross-instance journal notifications and local writes without idle database reads', async () => {
+ state.records = []; await maintenance.start();
+ state.records.push(record('owner', Date.now() + 60_000));
+ for (let i = 0; i < 20; i++) { state.changed(); notifyWorktreeRecycleRecordChanged(state.records[0].id); }
+ await vi.advanceTimersByTimeAsync(100);
+ expect(list).toHaveBeenCalledTimes(2); expect(client.readLocalWorktreeReferences).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(1);
+ state.records[0].phase = 'removed'; state.changed();
+ await vi.advanceTimersByTimeAsync(100); expect(vi.getTimerCount()).toBe(0);
+ });
+ it('resumes durable deadlines after a restart', async () => {
+ state.records[0].nextAttemptAt = Date.now() + 60_000;
+ await maintenance.start(); maintenance.stop();
+ maintenance = new WorktreeRecycleMaintenance({ isReady: () => true, recycleCurrentSession: closeAndRecycle });
+ await maintenance.start(); await vi.advanceTimersByTimeAsync(59_999); expect(closeAndRecycle).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1); expect(closeAndRecycle).toHaveBeenCalledOnce();
+ });
+ it('backs off unavailable reference reads without a hot loop', async () => {
+ client.readLocalWorktreeReferences.mockRejectedValue(new Error('database unavailable'));
+ await maintenance.start(); await vi.advanceTimersByTimeAsync(9_999);
+ expect(client.readLocalWorktreeReferences).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(1); expect(client.readLocalWorktreeReferences).toHaveBeenCalledTimes(2);
+ expect(closeAndRecycle).not.toHaveBeenCalled();
+ });
+ it('reconnects a failed watcher with backoff without querying an empty task queue', async () => {
+ state.records = []; watch.mockRejectedValueOnce(new Error('watch unavailable'));
+ await maintenance.start();
+ await vi.advanceTimersByTimeAsync(9_999); expect(watch).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(1); expect(watch).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBe(0); expect(client.readLocalWorktreeReferences).not.toHaveBeenCalled();
+ state.watchError(new Error('watch lost')); expect(closeWatch).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(10_000); expect(watch).toHaveBeenCalledTimes(3);
+ });
+ it('stops pending timers and ignores events after disposal', async () => {
+ await maintenance.start(); maintenance.stop();
+ state.changed(); notifyWorktreeRecycleOpportunity(state.records[0].meta.path);
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ expect(closeWatch).toHaveBeenCalledOnce(); expect(closeAndRecycle).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it('stops a startup batch before the next resource when readiness is lost', async () => {
+ state.records.push(record('second')); state.rows.push({ ...state.rows[0], id: 'second' });
+ closeAndRecycle.mockImplementationOnce(async () => { ready = false; });
+ await maintenance.start(); expect(closeAndRecycle).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0);
});
});
diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
index d420d4cf95..229b6bccaf 100644
--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
@@ -6,7 +6,7 @@ import path from 'node:path';
const state = vi.hoisted(() => ({ root: '' }));
const notify = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({ app: { getPath: () => state.root } }));
-vi.mock('../worktree/recycleMaintenance', () => ({ notifyWorktreeRecycleOpportunity: notify }));
+vi.mock('../worktree/recycleEvents', () => ({ notifyWorktreeRecycleOpportunity: notify }));
import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths } from '../worktree/runtimeLeases';
import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 25ea1a2df7..8ce3a294b2 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,4 +1,4 @@
-import { startWorktreeRecycleMaintenance, auditRegisteredWorktrees } from './worktree/recycleMaintenance';
+import { startWorktreeRecycleMaintenance, stopWorktreeRecycleMaintenance, auditRegisteredWorktrees } from './worktree/recycleMaintenance';
import { recycleSessionWorktreeForStatusChange } from './localDb/ipc/sessions';
import { tryGetDbClient } from './localDb/client/current';
import {
@@ -130,6 +130,7 @@ app.commandLine.appendSwitch('enable-features', 'SharedArrayBuffer');
// Windows 上 codex app-server 子进程不会随父死 → 残留孤儿, 持有 binary 文件锁,
// 用户下次启动时撞 EBUSY / 端口占用 (anthropic-compat-proxy 等)。
async function shutdownMaker(): Promise<{ piSessionFailures: number }> {
+ stopWorktreeRecycleMaintenance();
// Do not terminate Main while one workspace patch command is settling.
await waitForTurnChangeSetActions();
// 退出前先把 onClose 重副作用(worktree stash/删除、临时附件清理)一刀切抑制掉:
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index d39578328e..41879ec56d 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -5,8 +5,10 @@
* 失败时 throw `Error("[CODE] message")`,service 层包装回 `ApiError`。
*/
-import { withWorktreeResourceLocks } from '../../worktree/resourceLock';
+import { physicalWorktreeKey, withWorktreeResourceLocks } from '../../worktree/resourceLock';
import { managedWorktreeRoot } from '../../worktree/runtimeLeases';
+import { queueSessionWorktreeRecycle } from '../../worktree/recycleQueue';
+import { notifyWorktreeRecycleOpportunity } from '../../worktree/recycleEvents';
import fs from 'node:fs/promises';
import path from 'node:path';
@@ -184,9 +186,12 @@ async function withStatusWriteLock<T>(
): Promise<T> {
const write = async () => {
const resources = status === undefined ? [] : await readSessionWorktreeResources(db, sessionId);
+ const physicalResources = await Promise.all(resources.map(physicalWorktreeKey));
const mutate = async () => {
if (status === 'archived' || status === 'deleted') await requestWorktreeRecycle(sessionId, resources);
- return task();
+ const result = await task();
+ for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);
+ return result;
};
return withWorktreeMutation(resources, mutate);
};
@@ -363,13 +368,26 @@ export async function recycleSessionWorktreeForStatusChange(
capturedScope?: SessionRecycleScope,
): Promise<void> {
if (status !== 'deleted' && status !== 'archived') return;
+ // Capture before queueing: an account switch while waiting cannot redirect cleanup.
+ try {
+ const scope = capturedScope ?? captureSessionRecycleScope();
+ await queueSessionWorktreeRecycle(() => recycleSessionWorktreeInQueue(sessionId, scope));
+ } catch (error) {
+ log.warn('worktree recycle scheduling postponed', {
+ sessionId, code: (error as NodeJS.ErrnoException).code ?? 'unavailable',
+ });
+ }
+}
+
+async function recycleSessionWorktreeInQueue(
+ sessionId: string,
+ capturedScope: SessionRecycleScope,
+): Promise<void> {
const affectedWorktreeSessionIds = new Set<string>();
try {
- // Callers that already crossed an async status write pass the owner/DB
- // captured at operation entry. The fallback is only for direct callers.
- const ownerScope = capturedScope?.ownerScope ?? captureOwnerScope();
- const mediaDb = capturedScope?.mediaDb ?? getDbClient().drizzle;
- if (!isOwnerScopeCurrent(ownerScope)) return;
+ const { ownerScope, mediaDb } = capturedScope;
+ const ownerIsCurrent = (): boolean => isOwnerScopeCurrent(ownerScope) && getDbClient().drizzle === mediaDb;
+ if (!ownerIsCurrent()) return;
const cancelOperations = sessionRemovalCancelOperations;
const cleanupRemovedSession = sessionRemovalCleanup;
if (!cancelOperations || !cleanupRemovedSession) {
@@ -379,7 +397,6 @@ export async function recycleSessionWorktreeForStatusChange(
import('../../maker-host/index.js'),
import('../../worktree/sessionRemovalRecycle.js'),
]);
- const ownerIsCurrent = (): boolean => isOwnerScopeCurrent(ownerScope);
const isStillRemovable = async (id: string): Promise<boolean> =>
ownerIsCurrent() && recycle.isSessionStillRemovable(id, mediaDb);
const closeAndRecycle = async (targetSessionId: string, scanOwners: boolean): Promise<void> => {
@@ -2114,6 +2131,7 @@ export async function setSessionsStatusInDb(
perSession.set(id, paths);
resources.push(...paths);
}
+ const physicalResources = await Promise.all([...new Set(resources)].map(physicalWorktreeKey));
return withWorktreeMutation(resources, async () => {
if (status === 'archived') {
for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));
@@ -2129,6 +2147,7 @@ export async function setSessionsStatusInDb(
for (const item of rows) {
cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);
}
+ for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);
return rows;
});
});
diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.ts
index 9060887c8c..5da7329a73 100644
--- a/apps/desktop/src/main/worktree/managedRecycle.ts
+++ b/apps/desktop/src/main/worktree/managedRecycle.ts
@@ -16,6 +16,7 @@ import { assertManagedResourcePath, assertWorktreeGitIdentity } from './resource
import * as store from './worktreeStore';
import type { WorktreeMeta } from './types';
import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';
+import { withWorktreeRecycleSlot } from './recycleQueue';
export interface ManagedRecycleOptions {
canRemove?: () => Promise<boolean>;
@@ -84,6 +85,10 @@ export async function requestWorktreeRecycle(sessionId: string, resourcePaths: r
/** Complete a single durable request. Failure preserves registration and retry evidence. */
export async function recycleManagedWorktree(meta: WorktreeMeta, options: ManagedRecycleOptions): Promise<boolean> {
+ return withWorktreeRecycleSlot(() => recycleManagedWorktreeInSlot(meta, options));
+}
+
+async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: ManagedRecycleOptions): Promise<boolean> {
return withWorktreeResourceLock(meta.path, () => withLegacyWorktreeRuntimeGuard(async (legacyGuardHeld) => {
const registered = store.get(meta.sessionId);
if (registered && worktreeGeneration(registered) !== worktreeGeneration(meta)) return false;
diff --git a/apps/desktop/src/main/worktree/recycleEvents.ts b/apps/desktop/src/main/worktree/recycleEvents.ts
new file mode 100644
index 0000000000..9391be48bc
--- /dev/null
+++ b/apps/desktop/src/main/worktree/recycleEvents.ts
@@ -0,0 +1,23 @@
+import { worktreeResourceId } from './resourceLock';
+
+/** Hints wake scheduling only; the durable journal and live guards remain authoritative. */
+export interface WorktreeRecycleEvent {
+ resourceId: string;
+ opportunity: boolean;
+}
+
+const listeners = new Set<(event: WorktreeRecycleEvent) => void>();
+
+export function subscribeWorktreeRecycleEvents(listener: (event: WorktreeRecycleEvent) => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
+
+export function notifyWorktreeRecycleRecordChanged(resourceId: string): void {
+ for (const listener of listeners) listener({ resourceId, opportunity: false });
+}
+
+/** The caller supplies the resolved physical path, as recorded by the runtime lease. */
+export function notifyWorktreeRecycleOpportunity(physicalPath: string): void {
+ for (const listener of listeners) listener({ resourceId: worktreeResourceId(physicalPath), opportunity: true });
+}
diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.ts
index f7d322e200..ba04c9ebc3 100644
--- a/apps/desktop/src/main/worktree/recycleJournal.ts
+++ b/apps/desktop/src/main/worktree/recycleJournal.ts
@@ -1,4 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
+import { watch } from 'node:fs';
import fs from 'node:fs/promises';
import path from 'node:path';
import { app } from 'electron';
@@ -7,6 +8,7 @@ import { physicalWorktreeKey, worktreeResourceId } from './resourceLock';
import type { WorktreeMeta } from './types';
import type { WorktreeRecoveryArchive } from './recoveryArchive';
import { createLogger } from '../logger';
+import { notifyWorktreeRecycleRecordChanged } from './recycleEvents';
const log = createLogger('worktreeRecycleJournal');
@@ -86,6 +88,18 @@ export async function writeRecycleRecord(record: WorktreeRecycleRecord): Promise
await writeRecordFile(path.join(history, `${record.id}-${key}.json`), record);
}
await writeRecordFile(path.join(root, `${record.id}.json`), record);
+ notifyWorktreeRecycleRecordChanged(record.id);
+}
+
+/** Watch atomic journal replacements, not archive bytes, temporary files or history. */
+export async function watchRecycleJournal(onChange: () => void, onError: (error: unknown) => void): Promise<() => void> {
+ const root = recycleJournalRoot();
+ await fs.mkdir(root, { recursive: true });
+ const watcher = watch(root, { persistent: false }, (_event, filename) => {
+ if (filename === null || /^[a-f0-9]{64}\.json$/.test(filename.toString())) onChange();
+ });
+ watcher.on('error', onError);
+ return () => watcher.close();
}
async function writeRecordFile(target: string, record: WorktreeRecycleRecord): Promise<void> {
diff --git a/apps/desktop/src/main/worktree/recycleMaintenance.ts b/apps/desktop/src/main/worktree/recycleMaintenance.ts
index 95875c8050..4415875765 100644
--- a/apps/desktop/src/main/worktree/recycleMaintenance.ts
+++ b/apps/desktop/src/main/worktree/recycleMaintenance.ts
@@ -4,19 +4,18 @@ import { app } from 'electron';
import { getDbClient } from '../localDb/client/current';
import { createLogger } from '../logger';
-import { listRecycleRecords, readRecycleRecord, worktreeGeneration } from './recycleJournal';
+import { listRecycleRecords, readRecycleRecord, watchRecycleJournal, worktreeGeneration, type WorktreeRecycleRecord } from './recycleJournal';
import { recycleManagedWorktree } from './managedRecycle';
import { hasLiveSessionReference, loadLiveSessionPathKeys, pathKey } from './liveSessionRefs';
import * as store from './worktreeStore';
-import { physicalWorktreeKey, worktreeResourceId } from './resourceLock';
+import { physicalWorktreeKey } from './resourceLock';
+import { subscribeWorktreeRecycleEvents } from './recycleEvents';
const log = createLogger('worktreeRecycleMaintenance');
-let timer: ReturnType<typeof setInterval> | null = null;
-let running: Promise<void> | null = null;
-let pending = false;
-let pendingForce = false;
-let lastOptions: WorktreeMaintenanceOptions | null = null;
-const attemptsThisRun = new Map<string, number>();
+let maintenance: WorktreeRecycleMaintenance | null = null;
+const MAX_ATTEMPTS = 8;
+const EVENT_COALESCE_MS = 100;
+const retryDelay = (attempt: number): number => Math.min(30 * 60_000, 5_000 * 2 ** Math.min(attempt, 9));
export interface WorktreeMaintenanceOptions {
isReady(): boolean;
@@ -24,94 +23,189 @@ export interface WorktreeMaintenanceOptions {
onAttemptComplete?(): Promise<void>;
}
-/** Starts once both task storage and runtime-close services are usable. Repeated ready signals coalesce. */
-export function startWorktreeRecycleMaintenance(options: WorktreeMaintenanceOptions): void {
- lastOptions = options;
- if (!timer) {
- timer = setInterval(() => { void runWorktreeRecycleMaintenance(options); }, 30_000);
- timer.unref();
+/** Event-driven, single-flight maintenance with one timer for the earliest pending deadline. */
+export class WorktreeRecycleMaintenance {
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private timerAt = Infinity;
+ private running: Promise<void> | null = null;
+ private dirty = false;
+ private stopped = false;
+ private stopWatching: (() => void) | null = null;
+ private unsubscribe: (() => void) | null = null;
+ private watchFailures = 0;
+ private watchRetryAt = 0;
+ private scanFailures = 0;
+ private readonly wakeIds = new Set<string>();
+ private readonly attempts = new Map<string, { count: number; notBefore: number }>();
+
+ constructor(public options: WorktreeMaintenanceOptions) {}
+
+ start(): Promise<void> {
+ if (this.stopped) return Promise.resolve();
+ this.unsubscribe ??= subscribeWorktreeRecycleEvents((event) => {
+ if (event.opportunity) this.wakeIds.add(event.resourceId);
+ this.changed();
+ });
+ return this.run();
}
- void runWorktreeRecycleMaintenance(options);
-}
-export function stopWorktreeRecycleMaintenance(): void {
- if (timer) clearInterval(timer);
- timer = null;
- attemptsThisRun.clear();
- lastOptions = null;
-}
+ stop(): void {
+ this.stopped = true;
+ this.clearTimer();
+ this.unsubscribe?.();
+ this.unsubscribe = null;
+ this.stopWatching?.();
+ this.stopWatching = null;
+ }
-/** A stopped runtime is new evidence, so it can wake a request held by backoff. */
-export function notifyWorktreeRecycleOpportunity(physicalPath: string): void {
- if (!lastOptions) return;
- const prefix = `${worktreeResourceId(physicalPath)}:`;
- for (const key of attemptsThisRun.keys()) if (key.startsWith(prefix)) attemptsThisRun.delete(key);
- void runWorktreeRecycleMaintenance(lastOptions, true);
-}
+ private clearTimer(): void {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = null;
+ this.timerAt = Infinity;
+ }
+
+ private schedule(at: number): void {
+ if (this.stopped || !Number.isFinite(at) || (this.timer && this.timerAt <= at)) return;
+ this.clearTimer();
+ this.timerAt = at;
+ this.timer = setTimeout(() => { this.clearTimer(); void this.run(); }, Math.max(1, at - Date.now()));
+ this.timer.unref();
+ }
+
+ private changed(): void {
+ if (this.stopped) return;
+ if (this.running) this.dirty = true;
+ else this.schedule(Date.now() + EVENT_COALESCE_MS);
+ }
-export function runWorktreeRecycleMaintenance(options: WorktreeMaintenanceOptions, force = false): Promise<void> {
- pendingForce ||= force;
- if (running) {
- pending = true;
- return running;
+ run(): Promise<void> {
+ if (this.stopped) return Promise.resolve();
+ if (this.running) { this.dirty = true; return this.running; }
+ this.clearTimer();
+ this.dirty = false;
+ this.running = this.runPass().catch((error) => {
+ log.warn('worktree retry postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });
+ if (++this.scanFailures <= MAX_ATTEMPTS) this.schedule(Date.now() + retryDelay(this.scanFailures));
+ }).finally(() => {
+ this.running = null;
+ if (this.dirty) this.schedule(Date.now() + EVENT_COALESCE_MS);
+ });
+ return this.running;
}
- running = (async () => {
- do {
- pending = false;
- const forcePass = pendingForce;
- pendingForce = false;
- if (!options.isReady()) return;
- try {
- await retryRequestedWorktrees(options, forcePass);
- } catch (error) {
- log.warn('worktree retry postponed', error instanceof Error ? error.message : String(error));
+
+ private async ensureWatcher(): Promise<void> {
+ if (this.stopWatching || this.watchFailures >= MAX_ATTEMPTS || this.watchRetryAt > Date.now()) return;
+ const failed = (error: unknown) => {
+ this.stopWatching?.();
+ this.stopWatching = null;
+ log.warn('worktree journal watch postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });
+ this.watchRetryAt = Date.now() + retryDelay(++this.watchFailures);
+ if (this.watchFailures < MAX_ATTEMPTS) this.schedule(this.watchRetryAt);
+ };
+ try {
+ const close = await watchRecycleJournal(() => this.changed(), failed);
+ if (this.stopped) close();
+ else { this.stopWatching = close; this.watchFailures = 0; this.watchRetryAt = 0; }
+ } catch (error) { failed(error); }
+ }
+
+ private key(record: WorktreeRecycleRecord): string { return `${record.id}:${record.generation}`; }
+
+ private eligible(record: WorktreeRecycleRecord): boolean {
+ if (record.phase === 'restored' || record.phase === 'restoring' || record.meta.ephemeral) return false;
+ const current = store.get(record.meta.sessionId);
+ if (record.phase === 'removed' && !current) return false;
+ return (!current || worktreeGeneration(current) === record.generation)
+ && (this.attempts.get(this.key(record))?.count ?? 0) < MAX_ATTEMPTS;
+ }
+
+ private deadline(record: WorktreeRecycleRecord): number {
+ return Math.max(record.nextAttemptAt, this.attempts.get(this.key(record))?.notBefore ?? 0);
+ }
+
+ private async runPass(): Promise<void> {
+ if (!this.options.isReady()) return;
+ await this.ensureWatcher();
+ if (this.stopped) return;
+ const records = await listRecycleRecords();
+ const wakeIds = new Set(this.wakeIds);
+ this.wakeIds.clear();
+ for (const record of records) if (wakeIds.has(record.id)) this.attempts.delete(this.key(record));
+ const due = records.filter((record) => this.eligible(record)
+ && (wakeIds.has(record.id) || this.deadline(record) <= Date.now()));
+ // Empty queues and not-yet-due requests never open task databases.
+ if (due.length) {
+ for (const record of due) {
+ const count = (this.attempts.get(this.key(record))?.count ?? 0) + 1;
+ // Also back off errors before the removal core can persist nextAttemptAt.
+ this.attempts.set(this.key(record), { count, notBefore: Date.now() + retryDelay(count) });
}
- } while (pending);
- })().finally(() => { running = null; });
- return running;
-}
+ await this.retry(due, wakeIds);
+ }
+ if (this.stopped || !this.options.isReady()) return;
+ this.scanFailures = 0;
+ // Removal and other instances may have changed these records while we waited.
+ const latest = due.length ? await listRecycleRecords() : records;
+ for (const record of latest) if (this.eligible(record)) this.schedule(this.deadline(record));
+ if (!this.stopWatching && this.watchFailures < MAX_ATTEMPTS) this.schedule(this.watchRetryAt);
+ }
-async function retryRequestedWorktrees(options: WorktreeMaintenanceOptions, force: boolean): Promise<void> {
- const db = getDbClient();
- if (!db.readLocalWorktreeReferences) return;
- const rows = await db.readLocalWorktreeReferences();
- let attempted = false;
- for (const record of await listRecycleRecords()) {
- if (!options.isReady() || getDbClient() !== db) return;
- if (record.phase === 'restored' || record.phase === 'restoring') continue;
- if (record.phase === 'removed' && !store.get(record.meta.sessionId)) continue;
- if (!force && record.nextAttemptAt > Date.now()) continue;
- const budgetKey = `${record.id}:${record.generation}`;
- if ((attemptsThisRun.get(budgetKey) ?? 0) >= 8) continue;
- const currentMeta = store.get(record.meta.sessionId);
- if (currentMeta && worktreeGeneration(currentMeta) !== record.generation) continue;
- const ownerRows = rows.filter((row) => row.id === record.meta.sessionId);
- // Unknown is not an orphan, including after switching the selected account.
- if (!ownerRows.length || ownerRows.some((row) => row.source === 'bot' || (row.status !== 'archived' && row.status !== 'deleted'))) continue;
- attemptsThisRun.set(budgetKey, (attemptsThisRun.get(budgetKey) ?? 0) + 1);
- attempted = true;
+ private async retry(records: WorktreeRecycleRecord[], wakeIds: ReadonlySet<string>): Promise<void> {
+ const db = getDbClient();
+ if (!db.readLocalWorktreeReferences) return;
+ let attempted = false;
try {
- const currentRow = ownerRows.find((row) => row.currentDatabase);
- if (currentRow) {
- await options.recycleCurrentSession(record.meta.sessionId, currentRow.status!);
- } else {
- // Other local databases contribute evidence only. Their runtimes must be
- // absent by the machine-wide lease guard; never close a task through the wrong DB.
- await recycleManagedWorktree(record.meta, {
- canRemove: async () => {
- if (!options.isReady() || getDbClient() !== db) return false;
- const latest = (await db.readLocalWorktreeReferences!()).filter((row) => row.id === record.meta.sessionId);
- const request = await readRecycleRecord(record.meta.path);
- return request?.generation === record.generation && latest.length > 0
- && latest.every((row) => row.source !== 'bot' && (row.status === 'archived' || row.status === 'deleted'));
- },
- });
+ const rows = await db.readLocalWorktreeReferences();
+ for (const record of records) {
+ if (this.stopped || !this.options.isReady() || getDbClient() !== db) return;
+ try {
+ const latest = await readRecycleRecord(record.meta.path);
+ if (this.stopped || !this.options.isReady() || getDbClient() !== db) return;
+ if (!latest || latest.generation !== record.generation
+ || latest.phase === 'restored' || latest.phase === 'restoring'
+ || (latest.phase === 'removed' && !store.get(latest.meta.sessionId))
+ || (!wakeIds.has(record.id) && latest.nextAttemptAt > Date.now())) continue;
+ const ownerRows = rows.filter((row) => row.id === record.meta.sessionId);
+ // Unknown is not an orphan, including after switching the selected account.
+ if (!ownerRows.length || ownerRows.some((row) => row.source === 'bot'
+ || (row.status !== 'archived' && row.status !== 'deleted'))) continue;
+ attempted = true;
+ const currentRow = ownerRows.find((row) => row.currentDatabase);
+ if (currentRow) {
+ await this.options.recycleCurrentSession(record.meta.sessionId, currentRow.status!);
+ } else {
+ // Other databases supply evidence only; never close their tasks through the selected DB.
+ await recycleManagedWorktree(record.meta, {
+ canRemove: async () => {
+ if (this.stopped || !this.options.isReady() || getDbClient() !== db) return false;
+ const refs = (await db.readLocalWorktreeReferences!()).filter((row) => row.id === record.meta.sessionId);
+ const request = await readRecycleRecord(record.meta.path);
+ return request?.generation === record.generation && refs.length > 0
+ && refs.every((row) => row.source !== 'bot' && (row.status === 'archived' || row.status === 'deleted'));
+ },
+ });
+ }
+ } catch (error) {
+ log.warn('worktree request postponed', { resourceId: record.id, code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });
+ }
}
} catch (error) {
- log.warn('worktree request postponed', { resourceId: record.id, code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });
+ log.warn('worktree references postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });
}
+ if (attempted && !this.stopped) await this.options.onAttemptComplete?.();
}
- if (attempted) await options.onAttemptComplete?.();
+}
+
+/** Starts once both task storage and runtime-close services are usable. */
+export function startWorktreeRecycleMaintenance(options: WorktreeMaintenanceOptions): void {
+ maintenance ??= new WorktreeRecycleMaintenance(options);
+ maintenance.options = options;
+ void maintenance.start();
+}
+
+export function stopWorktreeRecycleMaintenance(): void {
+ maintenance?.stop();
+ maintenance = null;
}
/** Read-only classification: upgrading never turns historical registrations into deletion requests. */
diff --git a/apps/desktop/src/main/worktree/recycleQueue.ts b/apps/desktop/src/main/worktree/recycleQueue.ts
new file mode 100644
index 0000000000..7b5c96e940
--- /dev/null
+++ b/apps/desktop/src/main/worktree/recycleQueue.ts
@@ -0,0 +1,19 @@
+import { setImmediate } from 'node:timers/promises';
+
+/** FIFO, concurrency one. Yield between jobs so a batch does not monopolize Main. */
+function serialQueue() {
+ let tail = Promise.resolve();
+ return <T>(task: () => Promise<T>): Promise<T> => {
+ const run = tail.then(async () => {
+ await setImmediate();
+ return task();
+ });
+ tail = run.then(() => undefined, () => undefined);
+ return run;
+ };
+}
+
+// Session shutdown must be queued before taking route locks. The lower queue is
+// shared with pool eviction and cross-database retries; neither queue is reentrant.
+export const queueSessionWorktreeRecycle = serialQueue();
+export const withWorktreeRecycleSlot = serialQueue();
diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.ts
index c668270370..39e780d2aa 100644
--- a/apps/desktop/src/main/worktree/runtimeLeases.ts
+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts
@@ -5,6 +5,7 @@ import { app } from 'electron';
import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';
+import { notifyWorktreeRecycleOpportunity } from './recycleEvents';
function runtimeRoot(): string {
return path.join(app.getPath('userData'), 'worktree-runtime-leases');
@@ -50,7 +51,6 @@ export async function releaseWorktreeRuntimeLease(sessionId: string): Promise<vo
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
throw error;
}
- const { notifyWorktreeRecycleOpportunity } = await import('./recycleMaintenance');
if (physicalPath) notifyWorktreeRecycleOpportunity(physicalPath);
}