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): close shared recycle loop (#2254)

Kafeifei88d693cd837d
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index c751669b6c..2501763ee5 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -20,6 +20,7 @@ const h = vi.hoisted(() => ({
tapWindowBroadcast: vi.fn(),
webContentsSend: vi.fn(),
closeSession: vi.fn(),
+ isSessionAlive: vi.fn(),
withSendToSessionLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>
task(),
) as SessionRouteLockMock,
@@ -66,7 +67,7 @@ vi.mock('../agent-island/service.js', () => ({
}));
vi.mock('../imageCacheStore', () => ({ removeSession: vi.fn() }));
vi.mock('../maker-host/index.js', () => ({
- getMakerIfReady: () => ({ closeSession: h.closeSession }),
+ getMakerIfReady: () => ({ closeSession: h.closeSession, isSessionAlive: h.isSessionAlive }),
}));
vi.mock('../maker-ipc/register.js', () => ({
withSendToSessionLock: h.withSendToSessionLock,
@@ -87,6 +88,7 @@ beforeEach(() => {
vi.clearAllMocks();
h.userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-set-sessions-status-'));
h.closeSession.mockResolvedValue(undefined);
+ h.isSessionAlive.mockReturnValue(false);
h.isSessionStillRemovable.mockResolvedValue(true);
h.cancelSessionOperations.mockResolvedValue(undefined);
h.cleanupRemovedSession.mockResolvedValue(undefined);
@@ -240,7 +242,12 @@ describe('setSessionsStatusInDb', () => {
expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
's1',
- expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
+ expect.objectContaining({
+ scanOwners: true,
+ recycleOwner: expect.any(Function),
+ db: h.drizzle,
+ isOwnerCurrent: expect.any(Function),
+ }),
);
});
@@ -268,7 +275,12 @@ describe('setSessionsStatusInDb', () => {
await vi.waitFor(() => {
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
's1',
- expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
+ expect.objectContaining({
+ scanOwners: true,
+ recycleOwner: expect.any(Function),
+ db: h.drizzle,
+ isOwnerCurrent: expect.any(Function),
+ }),
);
});
@@ -368,7 +380,12 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect(h.removeSessionRefs).toHaveBeenCalledWith('s1', h.drizzle);
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
's1',
- expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
+ expect.objectContaining({
+ scanOwners: true,
+ recycleOwner: expect.any(Function),
+ db: h.drizzle,
+ isOwnerCurrent: expect.any(Function),
+ }),
);
expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
expect(order).toEqual(['cancel', 'cleanup', 'remove-media-refs', 'recycle-worktree']);
@@ -410,6 +427,95 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect(h.webContentsSend).not.toHaveBeenCalledWith('worktree:changed', expect.anything());
});
+ it('routes scanned owners through lock and close before low-level recycle', async () => {
+ const order: string[] = [];
+ h.withSendToSessionLock.mockImplementation(
+ async (sessionId: string, task: () => Promise<unknown>) => {
+ order.push(`lock:${sessionId}`);
+ const result = await task();
+ order.push(`unlock:${sessionId}`);
+ return result;
+ },
+ );
+ h.closeSession.mockImplementation(async (sessionId: string) => {
+ order.push(`close:${sessionId}`);
+ });
+ h.recycleWorktreeForRemovedSession.mockImplementation(
+ async (
+ sessionId: string,
+ options?: { recycleOwner?: (ownerId: string) => Promise<void> },
+ ) => {
+ order.push(`remove:${sessionId}`);
+ if (sessionId === 'shared') await options?.recycleOwner?.('owner');
+ },
+ );
+
+ await recycleSessionWorktreeForStatusChange('shared', 'archived');
+
+ expect(order).toEqual([
+ 'lock:shared',
+ 'close:shared',
+ 'remove:shared',
+ 'lock:owner',
+ 'close:owner',
+ 'remove:owner',
+ 'unlock:owner',
+ 'unlock:shared',
+ ]);
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenNthCalledWith(
+ 2,
+ 'owner',
+ expect.objectContaining({
+ scanOwners: false,
+ isSessionRuntimeAlive: expect.any(Function),
+ recycleOwner: expect.any(Function),
+ }),
+ );
+ });
+
+ it('passes current Maker runtime liveness into the low-level live-reference guard', async () => {
+ h.isSessionAlive.mockImplementation((sessionId: string) => sessionId === 'borrower');
+
+ await recycleSessionWorktreeForStatusChange('owner', 'archived');
+
+ const options = h.recycleWorktreeForRemovedSession.mock.calls[0]?.[1] as
+ | { isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined }
+ | undefined;
+ expect(options?.isSessionRuntimeAlive?.('borrower')).toBe(true);
+ expect(options?.isSessionRuntimeAlive?.('closed')).toBe(false);
+ });
+
+ it('still recycles a scanned owner when its runtime close throws (error is swallowed)', async () => {
+ h.closeSession.mockImplementation(async (sessionId: string) => {
+ if (sessionId === 'owner') throw new Error('runtime still alive');
+ });
+ h.recycleWorktreeForRemovedSession.mockImplementation(
+ async (
+ sessionId: string,
+ options?: { recycleOwner?: (ownerId: string) => Promise<void> },
+ ) => {
+ if (sessionId === 'shared') await options?.recycleOwner?.('owner');
+ },
+ );
+
+ await recycleSessionWorktreeForStatusChange('shared', 'archived');
+
+ expect(h.closeSession).toHaveBeenCalledWith('owner');
+ // Close errors are caught (.catch(() => undefined)), so owner is still recycled.
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledTimes(2);
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
+ 'shared',
+ expect.objectContaining({ scanOwners: true, recycleOwner: expect.any(Function) }),
+ );
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
+ 'owner',
+ expect.objectContaining({ scanOwners: false, recycleOwner: expect.any(Function) }),
+ );
+ expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', {
+ sessionId: 'shared',
+ });
+ });
+
it('fails closed before closing or recycling when Host cleanup is not configured', async () => {
setSessionRemovalCancelOperations(null);
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
index 35c689047e..9274045750 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
@@ -1,11 +1,11 @@
/**
* removeWorktreeForSession / discardPrecreatedWorktree 删除守卫回归:
- * - live-ref 守卫:其它未删除会话仍引用路径 → 保留
- * - 排除自身:owning session(可能已归档,status 仍非 deleted)不算引用
+ * - live-ref 守卫:其它 live 会话仍引用路径 → 保留;终态引用需确认 runtime 已关闭
+ * - 排除自身:owning session 自己的路径不算引用
* - dirty → stash 失败保留 / 成功后继续删
* - clean 无引用 → git remove + store.del
*/
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
import fsSync from 'node:fs';
import os from 'node:os';
@@ -24,6 +24,7 @@ const storeSetMock = vi.fn();
const storeMap = new Map<string, WorktreeMeta>();
const liveSessionRows: Array<{
id: string;
+ status: string | null;
workingDir: string | null;
worktreePath: string | null;
}> = [];
@@ -91,8 +92,15 @@ describe('removeWorktreeForSession', () => {
let manager: typeof import('../worktree/WorktreeManager');
beforeEach(async () => {
+ vi.clearAllMocks();
storeMap.clear();
liveSessionRows.length = 0;
+ liveSessionRows.push({
+ id: '__unrelated_active_session__',
+ status: 'active',
+ workingDir: path.join(BASE_REPO, 'unrelated'),
+ worktreePath: null,
+ });
liveSessionLookupError = null;
gitExecMock.mockReset().mockImplementation(async (args: string[], cwd?: string) => {
if (args[0] === 'symbolic-ref') {
@@ -115,10 +123,6 @@ describe('removeWorktreeForSession', () => {
manager = await import('../worktree/WorktreeManager');
});
- afterEach(() => {
- vi.clearAllMocks();
- });
-
it('no store entry → no-op', async () => {
await manager.removeWorktreeForSession('nope');
expect(gitExecMock).not.toHaveBeenCalled();
@@ -236,7 +240,101 @@ describe('removeWorktreeForSession', () => {
it('preserves worktree still referenced by another live session', async () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
- liveSessionRows.push({ id: 'other', workingDir: meta.path, worktreePath: null });
+ liveSessionRows.push({
+ id: 'other',
+ status: 'active',
+ workingDir: meta.path,
+ worktreePath: null,
+ });
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(gitExecMock).not.toHaveBeenCalled();
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
+ it('archived session references block recycle without runtime observer', async () => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ liveSessionRows.push({
+ id: 'other',
+ status: 'archived',
+ workingDir: meta.path,
+ worktreePath: null,
+ });
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(gitExecMock).not.toHaveBeenCalled();
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
+ it('deleted session references do not block recycle without runtime observer', async () => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ liveSessionRows.push({
+ id: 'other',
+ status: 'deleted',
+ workingDir: meta.path,
+ worktreePath: null,
+ });
+
+ await manager.removeWorktreeForSession('s1');
+
+ expect(gitExecMock).toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
+ expect(storeMap.has('s1')).toBe(false);
+ });
+
+ it('terminal session reference still blocks when its runtime is alive', async () => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ liveSessionRows.push({
+ id: 'other',
+ status: 'archived',
+ workingDir: meta.path,
+ worktreePath: null,
+ });
+
+ await manager.removeWorktreeForSession('s1', {
+ isSessionRuntimeAlive: (sessionId) => sessionId === 'other',
+ });
+
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
+ expect(storeMap.has('s1')).toBe(true);
+ });
+
+ it.each(['archived', 'deleted'])(
+ '%s session reference stops blocking after its runtime is closed',
+ async (status) => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ liveSessionRows.push({ id: 'other', status, workingDir: meta.path, worktreePath: null });
+
+ await manager.removeWorktreeForSession('s1', {
+ isSessionRuntimeAlive: () => false,
+ });
+
+ expect(gitExecMock).toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
+ expect(storeMap.has('s1')).toBe(false);
+ },
+ );
+
+ it.each([
+ ['NULL', null],
+ ['unknown', 'paused'],
+ ])('%s session status conservatively keeps its reference live', async (_label, status) => {
+ const meta = makeMeta('s1');
+ storeMap.set('s1', meta);
+ liveSessionRows.push({ id: 'other', status, workingDir: meta.path, worktreePath: null });
await manager.removeWorktreeForSession('s1');
@@ -313,8 +411,13 @@ describe('removeWorktreeForSession', () => {
it('owning session row does not block its own recycle (archived owner)', async () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
- // 归档会话 status 仍非 deleted,自己的行必须被排除,否则永远删不掉
- liveSessionRows.push({ id: 's1', workingDir: null, worktreePath: meta.path });
+ // owning session 自己的路径必须被排除,否则其终态回收永远无法推进
+ liveSessionRows.push({
+ id: 's1',
+ status: 'archived',
+ workingDir: null,
+ worktreePath: meta.path,
+ });
await manager.removeWorktreeForSession('s1');
@@ -405,6 +508,62 @@ describe('removeWorktreeForSession', () => {
expect(storeSetMock).toHaveBeenCalledWith('s1', meta);
});
+ it('rechecks borrower references before removing a clean owner worktree', async () => {
+ const meta = makeMeta('owner');
+ storeMap.set('owner', meta);
+ const borrower = {
+ id: 'borrower',
+ status: 'archived',
+ workingDir: meta.path,
+ worktreePath: meta.path,
+ };
+ liveSessionRows.push(borrower);
+ const isSessionRuntimeAlive = vi.fn(() => false);
+ const canRemove = vi.fn().mockImplementation(async () => {
+ if (canRemove.mock.calls.length === 2) borrower.status = 'active';
+ return true;
+ });
+
+ await manager.removeWorktreeForSession('owner', { canRemove, isSessionRuntimeAlive });
+
+ expect(canRemove).toHaveBeenCalledTimes(2);
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
+ expect(storeMap.has('owner')).toBe(true);
+ });
+
+ it('restores a dirty owner snapshot when a borrower becomes active before removal', async () => {
+ const meta = makeMeta('owner');
+ storeMap.set('owner', meta);
+ isWorktreeDirtyMock.mockResolvedValue(true);
+ const borrower = {
+ id: 'borrower',
+ status: 'archived',
+ workingDir: meta.path,
+ worktreePath: meta.path,
+ };
+ liveSessionRows.push(borrower);
+ const isSessionRuntimeAlive = vi.fn(() => false);
+ const canRemove = vi.fn().mockImplementation(async () => {
+ if (canRemove.mock.calls.length === 2) borrower.status = 'active';
+ return true;
+ });
+
+ await manager.removeWorktreeForSession('owner', { canRemove, isSessionRuntimeAlive });
+
+ expect(canRemove).toHaveBeenCalledTimes(2);
+ expect(autoStashMock).toHaveBeenCalledWith(meta.path, 'owner');
+ expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 'owner');
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'remove', '--force', meta.path],
+ BASE_REPO,
+ );
+ expect(storeMap.has('owner')).toBe(true);
+ expect(storeSetMock).toHaveBeenCalledWith('owner', meta);
+ });
+
it('keeps a preserved worktree unregistered when cancelled snapshot reapply fails', async () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
@@ -479,6 +638,7 @@ describe('removeWorktreeForSession', () => {
storeMap.set('s1', meta);
liveSessionRows.push({
id: 'other',
+ status: 'active',
workingDir: path.join(meta.path, 'packages', 'app'),
worktreePath: null,
});
@@ -522,7 +682,12 @@ describe('removeWorktreeForSession', () => {
it('clean + unreferenced → removed and store entry dropped', async () => {
const meta = makeMeta('s1');
storeMap.set('s1', meta);
- liveSessionRows.push({ id: 'other', workingDir: '/somewhere/else', worktreePath: null });
+ liveSessionRows.push({
+ id: 'other',
+ status: 'active',
+ workingDir: '/somewhere/else',
+ worktreePath: null,
+ });
await manager.removeWorktreeForSession('s1');
diff --git a/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts b/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
index a5a11ccf83..97c9d756b8 100644
--- a/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
@@ -13,6 +13,7 @@ const createWorktreeMock = vi.fn();
const storeMap = new Map<string, WorktreeMeta>();
const liveSessionRows: Array<{
id: string;
+ status: string | null;
workingDir: string | null;
worktreePath: string | null;
}> = [];
@@ -38,8 +39,7 @@ vi.mock('../worktree/worktreeStore', () => ({
vi.mock('../worktree/WorktreeManager', () => ({
copyClaudeSiviDirs: vi.fn(),
createWorktree: (...args: unknown[]) => createWorktreeMock(...args),
- resolveAvailableWorktreeName: (...args: unknown[]) =>
- resolveAvailableWorktreeNameMock(...args),
+ resolveAvailableWorktreeName: (...args: unknown[]) => resolveAvailableWorktreeNameMock(...args),
}));
vi.mock('../localDb/client/current', () => ({
@@ -89,6 +89,12 @@ describe('WorktreePool safety', () => {
storeMap.clear();
liveSessionRows.length = 0;
+ liveSessionRows.push({
+ id: '__unrelated_active_session__',
+ status: 'active',
+ workingDir: path.join(baseRepo, 'unrelated'),
+ worktreePath: null,
+ });
liveSessionLookupError = null;
liveSessionQueryCount = 0;
gitExecMock.mockReset();
@@ -109,7 +115,7 @@ describe('WorktreePool safety', () => {
fsSync.rmSync(tmpRoot, { recursive: true, force: true });
});
- it('does not evict a worktree still referenced by a non-deleted session', async () => {
+ it('does not evict a worktree still referenced by an active session', async () => {
const protectedMeta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
const evictableMeta = makeMeta(baseRepo, 'session-2', '2026-05-26T00:01:00.000Z');
const releaseMeta = makeMeta(baseRepo, 'session-6', '2026-05-26T00:05:00.000Z');
@@ -128,6 +134,7 @@ describe('WorktreePool safety', () => {
}
liveSessionRows.push({
id: protectedMeta.sessionId,
+ status: 'active',
workingDir: protectedMeta.path,
worktreePath: null,
});
@@ -149,6 +156,24 @@ describe('WorktreePool safety', () => {
storeMap.set(meta.sessionId, meta);
liveSessionRows.push({
id: meta.sessionId,
+ status: 'active',
+ workingDir: meta.path,
+ worktreePath: meta.path,
+ });
+
+ await expect(pool.releaseWorktree(meta.sessionId)).resolves.toBe('preserved');
+
+ expect(gitExecMock).not.toHaveBeenCalled();
+ expect(storeMap.has(meta.sessionId)).toBe(true);
+ });
+
+ it('does not return an archived session worktree to the pool without runtime truth', async () => {
+ const meta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ liveSessionRows.push({
+ id: meta.sessionId,
+ status: 'archived',
workingDir: meta.path,
worktreePath: meta.path,
});
@@ -165,6 +190,25 @@ describe('WorktreePool safety', () => {
storeMap.set(meta.sessionId, meta);
liveSessionRows.push({
id: meta.sessionId,
+ status: 'active',
+ workingDir: null,
+ worktreePath: meta.path,
+ });
+
+ await pool.recoverPool();
+ await pool.drainOne(baseRepo);
+
+ expect(gitExecMock).not.toHaveBeenCalled();
+ expect(storeMap.has(meta.sessionId)).toBe(true);
+ });
+
+ it('does not recover an archived session worktree without runtime truth', async () => {
+ const meta = makeMeta(baseRepo, 'session-1', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ liveSessionRows.push({
+ id: meta.sessionId,
+ status: 'archived',
workingDir: null,
worktreePath: meta.path,
});
@@ -278,9 +322,7 @@ describe('WorktreePool safety', () => {
['checkout', '--no-track', '-b', 'cindy/reuse-1', 'main'],
meta.path,
);
- expect(
- gitExecMock.mock.calls.some((call) => (call[0] as string[]).includes('-B')),
- ).toBe(false);
+ expect(gitExecMock.mock.calls.some((call) => (call[0] as string[]).includes('-B'))).toBe(false);
});
it('uses the Manager-reserved name when reusing a pooled worktree', async () => {
diff --git a/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts b/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
index 69220e33b7..2037970b51 100644
--- a/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
@@ -2,16 +2,24 @@
* sessionRemovalRecycle 回归(P0 重构:回收唯一驱动点):
* - ephemeral worktree 跳过(池生命周期)
* - 非 ephemeral → removeWorktreeForSession
+ * - 共享会话进入 archived/deleted 后按安全路径关系重试 owner 回收
* - 启动对账:只补收 deleted / 行缺失的孤儿,active / archived 保留;DB 失败零删除
*/
-import { beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { WorktreeMeta } from '../worktree/types';
+interface SessionRow {
+ id: string;
+ status: string | null | undefined;
+ workingDir: string | null;
+ worktreePath: string | null;
+}
+
const removeMock = vi.fn();
const storeMap = new Map<string, WorktreeMeta>();
-const sessionRows: Array<{ id: string; status: string | null }> = [];
+const sessionRows: SessionRow[] = [];
let sessionLookupError: Error | null = null;
vi.mock('../worktree/WorktreeManager', () => ({
@@ -28,9 +36,13 @@ vi.mock('../localDb/client/current', () => ({
drizzle: {
select: () => ({
from: () => ({
- where: () => {
+ where: (condition: { queryChunks?: unknown[] }) => {
if (sessionLookupError) throw sessionLookupError;
- return sessionRows;
+ const sessionId = (condition?.queryChunks?.[3] as { value?: unknown } | undefined)
+ ?.value;
+ return typeof sessionId === 'string'
+ ? sessionRows.filter((row) => row.id === sessionId)
+ : sessionRows;
},
}),
}),
@@ -40,19 +52,34 @@ vi.mock('../localDb/client/current', () => ({
const BASE_REPO = path.resolve('/repo');
-function makeMeta(sessionId: string, ephemeral = false): WorktreeMeta {
+function makeMeta(sessionId: string, ephemeral = false, name = sessionId): WorktreeMeta {
return {
sessionId,
- name: sessionId,
- path: path.join(BASE_REPO, '.xdt-worktrees', sessionId),
+ name,
+ path: path.join(BASE_REPO, '.xdt-worktrees', name),
baseRepo: BASE_REPO,
- branch: `xdt/${sessionId}`,
+ branch: `xdt/${name}`,
sourceBranch: 'main',
createdAt: '2026-07-01T00:00:00.000Z',
ephemeral,
};
}
+function addSession(
+ id: string,
+ status: string | null | undefined,
+ paths: Partial<Pick<SessionRow, 'workingDir' | 'worktreePath'>> = {},
+): SessionRow {
+ const row: SessionRow = {
+ id,
+ status,
+ workingDir: paths.workingDir ?? null,
+ worktreePath: paths.worktreePath ?? null,
+ };
+ sessionRows.push(row);
+ return row;
+}
+
function dbFor(rows: Array<{ id: string; status: string | null }>) {
return {
select: () => ({
@@ -75,21 +102,24 @@ describe('sessionRemovalRecycle', () => {
});
describe('recycleWorktreeForRemovedSession', () => {
- it('no store entry → no-op', async () => {
+ it('no store entry and no matching owner → no-op', async () => {
+ addSession('nope', 'archived');
+
await mod.recycleWorktreeForRemovedSession('nope');
+
expect(removeMock).not.toHaveBeenCalled();
});
it('ephemeral worktree is pool-managed, skipped', async () => {
storeMap.set('s1', makeMeta('s1', true));
- sessionRows.push({ id: 's1', status: 'archived' });
+ addSession('s1', 'archived');
await mod.recycleWorktreeForRemovedSession('s1');
expect(removeMock).not.toHaveBeenCalled();
});
it('non-ephemeral worktree is removed', async () => {
storeMap.set('s1', makeMeta('s1'));
- sessionRows.push({ id: 's1', status: 'archived' });
+ addSession('s1', 'archived');
await mod.recycleWorktreeForRemovedSession('s1');
expect(removeMock).toHaveBeenCalledWith(
's1',
@@ -99,11 +129,11 @@ describe('sessionRemovalRecycle', () => {
it('passes a live status guard that observes an unarchive during recycle', async () => {
storeMap.set('s1', makeMeta('s1'));
- sessionRows.push({ id: 's1', status: 'archived' });
+ const owner = addSession('s1', 'archived');
removeMock.mockImplementationOnce(
async (_sessionId: string, options: { canRemove: () => Promise<boolean> }) => {
await expect(options.canRemove()).resolves.toBe(true);
- sessionRows[0]!.status = 'active';
+ owner.status = 'active';
await expect(options.canRemove()).resolves.toBe(false);
},
);
@@ -115,7 +145,7 @@ describe('sessionRemovalRecycle', () => {
it('active again before recycle runs → preserves worktree', async () => {
storeMap.set('s1', makeMeta('s1'));
- sessionRows.push({ id: 's1', status: 'active' });
+ addSession('s1', 'active');
await mod.recycleWorktreeForRemovedSession('s1');
@@ -131,9 +161,205 @@ describe('sessionRemovalRecycle', () => {
expect(removeMock).not.toHaveBeenCalled();
});
+ it('shared session with its own store meta still retries the owner after processing itself', async () => {
+ const ownerMeta = makeMeta('owner');
+ const sharedMeta = makeMeta('shared');
+ storeMap.set('owner', ownerMeta);
+ storeMap.set('shared', sharedMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ addSession('shared', 'archived', { workingDir: ownerMeta.path });
+ const removalOrder: string[] = [];
+ removeMock.mockImplementation(async (sessionId: string) => {
+ removalOrder.push(sessionId);
+ });
+ const recycleOwner = vi.fn(async (ownerSessionId: string) => {
+ await mod.recycleWorktreeForRemovedSession(ownerSessionId, { scanOwners: false });
+ });
+
+ await mod.recycleWorktreeForRemovedSession('shared', { recycleOwner });
+
+ expect(recycleOwner).toHaveBeenCalledWith('owner');
+ expect(removalOrder).toEqual(['shared', 'owner']);
+ expect(removeMock).toHaveBeenNthCalledWith(
+ 1,
+ 'shared',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ expect(removeMock).toHaveBeenNthCalledWith(
+ 2,
+ 'owner',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ });
+
+ it('ephemeral terminal session still scans and retries a matching owner', async () => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('shared', makeMeta('shared', true));
+ storeMap.set('owner', ownerMeta);
+ addSession('shared', 'archived', { workingDir: ownerMeta.path });
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ const recycleOwner = vi.fn(async (ownerSessionId: string) => {
+ await mod.recycleWorktreeForRemovedSession(ownerSessionId, { scanOwners: false });
+ });
+
+ await mod.recycleWorktreeForRemovedSession('shared', { recycleOwner });
+
+ expect(recycleOwner).toHaveBeenCalledWith('owner');
+ expect(removeMock).toHaveBeenCalledTimes(1);
+ expect(removeMock).toHaveBeenCalledWith(
+ 'owner',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ });
+
+ it('owner scan is fail-closed when its status lookup fails', async () => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('shared', 'archived', { workingDir: ownerMeta.path });
+ sessionLookupError = new Error('db closed');
+
+ await mod.recycleWorktreeForRemovedSession('shared');
+
+ expect(removeMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['archived', 'deleted'])(
+ 'shared session %s retriggers an archived owner by exact worktree path',
+ async (sharedStatus) => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ addSession('shared', sharedStatus, { workingDir: ownerMeta.path });
+ const recycleOwner = vi.fn(async (ownerSessionId: string) => {
+ await mod.recycleWorktreeForRemovedSession(ownerSessionId, { scanOwners: false });
+ });
+
+ await mod.recycleWorktreeForRemovedSession('shared', { recycleOwner });
+
+ expect(recycleOwner).toHaveBeenCalledWith('owner');
+ expect(removeMock).toHaveBeenCalledWith(
+ 'owner',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ },
+ );
+
+ it('shared nested workingDir safely retriggers its owner, not a sibling prefix', async () => {
+ const ownerMeta = makeMeta('owner', false, 'project');
+ const siblingMeta = makeMeta('sibling', false, 'project-copy');
+ storeMap.set('owner', ownerMeta);
+ storeMap.set('sibling', siblingMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ addSession('sibling', 'archived', { worktreePath: siblingMeta.path });
+ addSession('shared', 'archived', {
+ workingDir: path.join(ownerMeta.path, 'packages', 'desktop'),
+ });
+ const recycleOwner = vi.fn(async (ownerSessionId: string) => {
+ await mod.recycleWorktreeForRemovedSession(ownerSessionId, { scanOwners: false });
+ });
+
+ await mod.recycleWorktreeForRemovedSession('shared', { recycleOwner });
+
+ expect(recycleOwner).toHaveBeenCalledTimes(1);
+ expect(recycleOwner).toHaveBeenCalledWith('owner');
+ expect(removeMock).toHaveBeenCalledTimes(1);
+ expect(removeMock).toHaveBeenCalledWith(
+ 'owner',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ });
+
+ it('owner archived first, then shared archived → first retry can preserve and later event retries', async () => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ const shared = addSession('shared', 'active', { workingDir: ownerMeta.path });
+
+ await mod.recycleWorktreeForRemovedSession('owner');
+ expect(removeMock).toHaveBeenCalledTimes(1);
+
+ removeMock.mockClear();
+ shared.status = 'archived';
+ const recycleOwner = vi.fn(async (ownerSessionId: string) => {
+ await mod.recycleWorktreeForRemovedSession(ownerSessionId, { scanOwners: false });
+ });
+ await mod.recycleWorktreeForRemovedSession('shared', { recycleOwner });
+
+ expect(recycleOwner).toHaveBeenCalledWith('owner');
+ expect(removeMock).toHaveBeenCalledTimes(1);
+ expect(removeMock).toHaveBeenCalledWith(
+ 'owner',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ });
+
+ it('batch-style and duplicate terminal events are idempotent after owner store removal', async () => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ addSession('shared-1', 'archived', { workingDir: ownerMeta.path });
+ addSession('shared-2', 'archived', { workingDir: ownerMeta.path });
+ removeMock.mockImplementation(async (sessionId: string) => {
+ storeMap.delete(sessionId);
+ });
+ const recycleOwner = async (ownerSessionId: string): Promise<void> => {
+ await mod.recycleWorktreeForRemovedSession(ownerSessionId, { scanOwners: false });
+ };
+
+ await mod.recycleWorktreeForRemovedSession('shared-1', { recycleOwner });
+ await mod.recycleWorktreeForRemovedSession('shared-2', { recycleOwner });
+ await mod.recycleWorktreeForRemovedSession('shared-1', { recycleOwner });
+
+ expect(removeMock).toHaveBeenCalledTimes(1);
+ expect(removeMock).toHaveBeenCalledWith(
+ 'owner',
+ expect.objectContaining({ canRemove: expect.any(Function) }),
+ );
+ });
+
+ it.each([
+ ['active', 'active'],
+ ['NULL', null],
+ ['unknown', 'paused'],
+ ] as const)(
+ 'shared %s status conservatively preserves the owner',
+ async (_label, sharedStatus) => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ addSession('shared', sharedStatus, { workingDir: ownerMeta.path });
+
+ await mod.recycleWorktreeForRemovedSession('shared');
+
+ expect(removeMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('shared session lookup failure conservatively preserves the owner', async () => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('owner', 'archived', { worktreePath: ownerMeta.path });
+ sessionLookupError = new Error('db closed');
+
+ await mod.recycleWorktreeForRemovedSession('shared');
+
+ expect(removeMock).not.toHaveBeenCalled();
+ });
+
+ it('owner restored to active before shared terminal event is not removed', async () => {
+ const ownerMeta = makeMeta('owner');
+ storeMap.set('owner', ownerMeta);
+ addSession('owner', 'active', { worktreePath: ownerMeta.path });
+ addSession('shared', 'archived', { workingDir: ownerMeta.path });
+
+ await mod.recycleWorktreeForRemovedSession('shared');
+
+ expect(removeMock).not.toHaveBeenCalled();
+ });
+
it('uses the captured owner database and stops its live guard after owner switch', async () => {
storeMap.set('shared-session-id', makeMeta('shared-session-id'));
- sessionRows.push({ id: 'shared-session-id', status: 'active' });
+ sessionRows.push({ id: 'shared-session-id', status: 'active', workingDir: null, worktreePath: null });
const capturedRows = [{ id: 'shared-session-id', status: 'deleted' as string | null }];
let ownerCurrent = true;
removeMock.mockImplementationOnce(
@@ -155,10 +381,10 @@ describe('sessionRemovalRecycle', () => {
describe('isSessionStillRemovable', () => {
it('accepts only the current deleted/archived states', async () => {
- sessionRows.push({ id: 's1', status: 'archived' });
+ const row = addSession('s1', 'archived');
await expect(mod.isSessionStillRemovable('s1')).resolves.toBe(true);
- sessionRows[0]!.status = 'active';
+ row.status = 'active';
await expect(mod.isSessionStillRemovable('s1')).resolves.toBe(false);
});
@@ -168,7 +394,7 @@ describe('sessionRemovalRecycle', () => {
});
it('uses an explicitly captured database instead of the current global owner', async () => {
- sessionRows.push({ id: 'shared-session-id', status: 'active' });
+ sessionRows.push({ id: 'shared-session-id', status: 'active', workingDir: null, worktreePath: null });
const capturedDb = dbFor([{ id: 'shared-session-id', status: 'archived' }]);
await expect(
@@ -184,12 +410,10 @@ describe('sessionRemovalRecycle', () => {
storeMap.set('deleted', makeMeta('deleted'));
storeMap.set('missing', makeMeta('missing'));
storeMap.set('eph', makeMeta('eph', true));
- sessionRows.push(
- { id: 'active', status: 'active' },
- { id: 'archived', status: 'archived' },
- { id: 'deleted', status: 'deleted' },
- // 'missing' 无行 → 视为孤儿; 'eph' 是 ephemeral 不进候选
- );
+ addSession('active', 'active');
+ addSession('archived', 'archived');
+ addSession('deleted', 'deleted');
+ // 'missing' 无行 → 视为孤儿; 'eph' 是 ephemeral 不进候选
await mod.reconcileWorktreesForDeletedSessions();
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index e127731397..3fbb72a9d5 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -246,41 +246,48 @@ export async function recycleSessionWorktreeForStatusChange(
const ownerIsCurrent = (): boolean => isOwnerScopeCurrent(ownerScope);
const isStillRemovable = async (id: string): Promise<boolean> =>
ownerIsCurrent() && recycle.isSessionStillRemovable(id, mediaDb);
- if (!(await isStillRemovable(sessionId))) return;
- await withSessionRouteLock(sessionId, async () => {
- const shouldRecycle = await quiesceSessionBeforeWorktreeRecycle(sessionId, {
- isOwnerCurrent: ownerIsCurrent,
- isSessionStillRemovable: isStillRemovable,
- cancelSessionOperations: cancelOperations,
- cleanupRemovedSession,
- closeSession: async (id) => {
- await mh
- .getMakerIfReady()
- ?.closeSession(id)
- .catch(() => undefined);
- },
- });
- if (!shouldRecycle || !ownerIsCurrent()) return;
-
- // Keep irreversible cleanup under the same task route lock as the final
- // status check. A concurrent restore/start/send must not slip between
- // quiescence and ref/worktree deletion.
- await removeDeletedSessionMediaRefs(sessionId, mediaDb)
- .then((count) => {
- if (count > 0) log.info('session media refs removed', { sessionId, count });
- })
- .catch((err) => {
- log.warn('session media ref cleanup failed', {
- sessionId,
- err: err instanceof Error ? err.message : String(err),
+ const closeAndRecycle = async (targetSessionId: string, scanOwners: boolean): Promise<void> => {
+ if (!(await isStillRemovable(targetSessionId))) return;
+ await withSessionRouteLock(targetSessionId, async () => {
+ const shouldRecycle = await quiesceSessionBeforeWorktreeRecycle(targetSessionId, {
+ isOwnerCurrent: ownerIsCurrent,
+ isSessionStillRemovable: isStillRemovable,
+ cancelSessionOperations: cancelOperations,
+ cleanupRemovedSession,
+ closeSession: async (id) => {
+ await mh
+ .getMakerIfReady()
+ ?.closeSession(id)
+ .catch(() => undefined);
+ },
+ });
+ if (!shouldRecycle || !ownerIsCurrent()) return;
+
+ // Keep irreversible cleanup under the same task route lock as the final
+ // status check. A concurrent restore/start/send must not slip between
+ // quiescence and ref/worktree deletion.
+ await removeDeletedSessionMediaRefs(targetSessionId, mediaDb)
+ .then((count) => {
+ if (count > 0) log.info('session media refs removed', { sessionId: targetSessionId, count });
+ })
+ .catch((err) => {
+ log.warn('session media ref cleanup failed', {
+ sessionId: targetSessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
});
+ if (!ownerIsCurrent()) return;
+ await recycle.recycleWorktreeForRemovedSession(targetSessionId, {
+ scanOwners,
+ db: mediaDb,
+ isOwnerCurrent: ownerIsCurrent,
+ isSessionRuntimeAlive: (candidateSessionId) =>
+ mh.getMakerIfReady()?.isSessionAlive(candidateSessionId),
+ recycleOwner: (ownerSessionId) => closeAndRecycle(ownerSessionId, false),
});
- if (!ownerIsCurrent()) return;
- await recycle.recycleWorktreeForRemovedSession(sessionId, {
- db: mediaDb,
- isOwnerCurrent: ownerIsCurrent,
});
- });
+ };
+ await closeAndRecycle(sessionId, true);
} catch (err) {
log.warn('worktree recycle after session status change failed', {
sessionId,
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index c0d862bbe1..210364b078 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -922,6 +922,8 @@ const removeWorktreeQueues = new Map<string, Promise<void>>();
export interface RemoveWorktreeOptions {
/** destructive remove 前确认 owning session 仍处于允许回收的状态。 */
canRemove?: () => Promise<boolean>;
+ /** archived/deleted 引用只有在对应 runtime 已关闭时才可忽略。 */
+ isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined;
/**
* 预创建补偿回收不能把用户可能已经手动写入的内容变成无会话可恢复的快照;
* 命中 dirty 时保留整个 worktree,而不是走常规删除/归档的 auto-stash 流程。
@@ -938,8 +940,8 @@ export interface RemoveWorktreeOptions {
*
* 流程:
* 1. meta = store.get(sid); null → return
- * 2. live-ref 守卫: 其它未删除会话仍引用该路径 → 保留(排除 sid 自身,
- * 归档会话自己的行不算引用)
+ * 2. live-ref 守卫: 其它会话仍引用该路径 → 保留(排除 sid 自身;其它终态会话
+ * 只有在 runtime 已确认关闭时才不阻挡)
* 3. dirty → auto-stash(失败 → 保留);成功后先撤销 store 登记,阻断 SEND
* 4. try git worktree remove --force <meta.path>
* 5. fail → isManagedWorktreePath 三条校验通过 → fs.rm -rf
@@ -1006,11 +1008,12 @@ async function removeWorktreeForSessionInner(
return;
}
- // live-ref 守卫: worktree 路径仍被其它未删除会话的 workingDir / worktreePath
- // 指向时不删(典型: 用户在该目录另开了会话)。查询失败按"在用"保守处理。
+ // live-ref 守卫: worktree 路径仍被其它会话的 workingDir / worktreePath 指向时不删。
+ // 产品终态不代表 runtime 已关闭;显式回收路径用 Maker 的运行态观察器确认。
const liveKeys = await loadLiveSessionPathKeys({
contextPath: worktreePath,
excludeSessionId: sessionId,
+ isSessionRuntimeAlive: options.isSessionRuntimeAlive,
});
if (hasLiveSessionReference(meta, liveKeys)) {
log.info(
@@ -1146,6 +1149,31 @@ async function removeWorktreeForSessionInner(
}
};
+ const restorePreservedWorktree = async (): Promise<void> => {
+ if (!(await restoreQuarantine())) return;
+ if (!snapshotted) return;
+ if (await restoreAutoStashToPreservedWorktree(meta.path, sessionId)) {
+ await store.set(sessionId, meta);
+ } else {
+ log.warn(
+ `[worktree] recycle cancelled for ${meta.path}, but snapshot reapply failed; ` +
+ 'worktree stays unregistered so SEND remains blocked until restore succeeds',
+ );
+ }
+ };
+
+ const hasCurrentLiveReference = async (): Promise<boolean> => {
+ const currentLiveKeys = await loadLiveSessionPathKeys({
+ contextPath: removalPath,
+ excludeSessionId: sessionId,
+ isSessionRuntimeAlive: removalOptions.isSessionRuntimeAlive,
+ });
+ return hasLiveSessionReference(
+ quarantinePath ? { ...meta, quarantinePath } : meta,
+ currentLiveKeys,
+ );
+ };
+
if (removalOptions.preserveDirty && !quarantinePath && (await pathExists(meta.path))) {
const candidate = `${meta.path}.xdt-removing-${randomUUID()}`;
try {
@@ -1201,6 +1229,14 @@ async function removeWorktreeForSessionInner(
}
}
+ if (await hasCurrentLiveReference()) {
+ log.info(
+ `[worktree] preserved worktree at ${removalPath}: another session referenced it before removal`,
+ );
+ await restorePreservedWorktree();
+ return;
+ }
+
let removedByGit = false;
try {
// 预创建补偿回收必须让 git 在删除瞬间再次确认 worktree 仍然干净:
@@ -1222,6 +1258,13 @@ async function removeWorktreeForSessionInner(
await restoreQuarantine();
return;
}
+ if (await hasCurrentLiveReference()) {
+ log.info(
+ `[worktree] preserved worktree at ${removalPath}: another session referenced it before fallback removal`,
+ );
+ await restorePreservedWorktree();
+ return;
+ }
// fallback: fs.rm —— 必须三条校验通过
if (
isManagedWorktreePath(removalPath, meta.baseRepo, [...store.getAllPaths(), removalPath])
diff --git a/apps/desktop/src/main/worktree/liveSessionRefs.ts b/apps/desktop/src/main/worktree/liveSessionRefs.ts
index 98accce668..787e8fe486 100644
--- a/apps/desktop/src/main/worktree/liveSessionRefs.ts
+++ b/apps/desktop/src/main/worktree/liveSessionRefs.ts
@@ -1,9 +1,11 @@
/**
* live-session 引用判定(WorktreePool 与 WorktreeManager 删除路径共用)。
*
- * 语义:某 worktree 路径若仍被任何**未删除**会话的 workingDir / worktreePath 指向,
- * 就视为"在用",删除/淘汰路径必须保留它。查询失败时返回 null,消费方按
- * "无法确认 → 视为在用"的保守方向处理——所有分支都倾向保留而非删除。
+ * 语义:某 worktree 路径若仍被其它会话的 workingDir / worktreePath 指向,就视为"在用",
+ * 删除/淘汰路径必须保留它。显式归档/删除回收可提供运行态观察器:archived/deleted 只在确认
+ * 对应 runtime 已关闭后才不再阻挡;其它调用方没有观察器时保守保留 archived,但继续忽略
+ * deleted。查询失败时返回 null,消费方按"无法确认 → 视为在用"的保守方向处理。未知或 NULL
+ * status 同样按在用处理。
*
* 原实现内联在 WorktreePool.ts(MR1),P0 重构把它抽出来给
* removeWorktreeForSession 的删除守卫复用,并支持排除会话自身
@@ -11,7 +13,7 @@
*/
import path from 'node:path';
-import { ne } from 'drizzle-orm';
+import { sql } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current';
import { sessions } from '../localDb/schema';
@@ -47,9 +49,11 @@ export interface LoadLiveSessionPathKeysOptions {
contextPath?: string;
/**
* 排除的会话 id:显式删除/归档会话时,该会话自己的 workingDir/worktreePath
- * 不构成"仍在用"(归档会话 status 仍非 deleted,不排除会永远挡住自己的回收)。
+ * 不构成"仍在用";显式回收观察器存在时,其它终态会话仍需运行态证明才能排除。
*/
excludeSessionId?: string;
+ /** 终态会话只有在该观察器明确返回 false 时才不再视为 live。 */
+ isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined;
}
export async function loadLiveSessionPathKeys(
@@ -60,16 +64,27 @@ export async function loadLiveSessionPathKeys(
const rows = await db
.select({
id: sessions.id,
+ status: sessions.status,
workingDir: sessions.workingDir,
worktreePath: sessions.worktreePath,
})
.from(sessions)
- .where(ne(sessions.status, 'deleted'));
+ .where(
+ opts.isSessionRuntimeAlive
+ ? sql`${sessions.workingDir} IS NOT NULL OR ${sessions.worktreePath} IS NOT NULL`
+ : sql`${sessions.status} != 'deleted' OR ${sessions.status} IS NULL`,
+ );
const keys = new Set<string>();
for (const row of rows) {
- // 排除放在 JS 层而非 SQL:语义单测无需解析 drizzle 条件表达式。
if (opts.excludeSessionId && row.id === opts.excludeSessionId) continue;
+ const isTerminal = row.status === 'archived' || row.status === 'deleted';
+ if (!opts.isSessionRuntimeAlive && row.status === 'deleted') {
+ continue;
+ }
+ if (isTerminal && opts.isSessionRuntimeAlive?.(row.id) === false) {
+ continue;
+ }
const workingDirKey = pathKey(row.workingDir);
const worktreePathKey = pathKey(row.worktreePath);
if (workingDirKey) keys.add(workingDirKey);
diff --git a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
index bf10cae7a4..96427e8f43 100644
--- a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
+++ b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
@@ -16,6 +16,7 @@
import { eq, inArray } from 'drizzle-orm';
+import { hasLiveSessionReference, pathKey } from './liveSessionRefs';
import { removeWorktreeForSession } from './WorktreeManager';
import * as store from './worktreeStore';
import { getDbClient } from '../localDb/client/current';
@@ -39,11 +40,47 @@ const log = createLogger('sessionRemovalRecycle');
export interface RecycleWorktreeForRemovedSessionOptions {
db?: DbClient['drizzle'];
isOwnerCurrent?: () => boolean;
+ /** Internal guard: owner retries reuse this entry point without starting another owner scan. */
+ scanOwners?: boolean;
+ /** Runtime truth used by the live-reference guard for archived/deleted borrowers. */
+ isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined;
+ /**
+ * Owner retries must go back through the caller's route lock + CLI close chain before
+ * entering this low-level remover. Omitted callers preserve the owner rather than
+ * deleting it without the required runtime shutdown.
+ */
+ recycleOwner?: (sessionId: string) => Promise<void>;
}
export async function recycleWorktreeForRemovedSession(
sessionId: string,
options: RecycleWorktreeForRemovedSessionOptions = {},
+): Promise<void> {
+ try {
+ await recycleOwnWorktreeForRemovedSession(sessionId, options);
+ } finally {
+ if (options.scanOwners !== false) {
+ const ownerSessionIds = await findOwningWorktreeSessionIds(sessionId);
+ for (const ownerSessionId of ownerSessionIds) {
+ if (options.recycleOwner) {
+ await options.recycleOwner(ownerSessionId);
+ } else {
+ log.warn(
+ `[sessionRemovalRecycle] preserving owner ${ownerSessionId}: no runtime-close callback`,
+ );
+ }
+ }
+ }
+ }
+}
+
+/**
+ * 只处理 session 自身登记的 worktree。是否存在自身 meta、是否为 ephemeral,均不影响
+ * 顶层入口随后扫描共享 owner。
+ */
+async function recycleOwnWorktreeForRemovedSession(
+ sessionId: string,
+ options: Pick<RecycleWorktreeForRemovedSessionOptions, 'db' | 'isOwnerCurrent' | 'isSessionRuntimeAlive'>,
): Promise<void> {
const meta = store.get(sessionId);
if (!meta) return;
@@ -64,6 +101,7 @@ export async function recycleWorktreeForRemovedSession(
return;
}
await removeWorktreeForSession(sessionId, {
+ isSessionRuntimeAlive: options.isSessionRuntimeAlive,
canRemove: async () => {
if (!isOwnerCurrent()) return false;
const currentStatus = await readCurrentSessionStatus(sessionId, db);
@@ -72,6 +110,62 @@ export async function recycleWorktreeForRemovedSession(
});
}
+/**
+ * 读取终态共享 session 的路径,并从 store 中找精确匹配或安全父子路径关系的 owner。
+ * 这个 helper 只负责一次扫描,不递归触发其它 session 的扫描;owner 回收由调用方
+ * 重新经过 recycleWorktreeForRemovedSession 与 removeWorktreeForSession 安全门。
+ */
+async function findOwningWorktreeSessionIds(sessionId: string): Promise<string[]> {
+ const row = await readSessionRecycleSnapshot(sessionId);
+ if (!row || (row.status !== 'deleted' && row.status !== 'archived')) return [];
+
+ const sharedPathKeys = new Set<string>();
+ const workingDirKey = pathKey(row.workingDir);
+ const worktreePathKey = pathKey(row.worktreePath);
+ if (workingDirKey) sharedPathKeys.add(workingDirKey);
+ if (worktreePathKey) sharedPathKeys.add(worktreePathKey);
+ if (sharedPathKeys.size === 0) return [];
+
+ return store
+ .getAll()
+ .filter(
+ (owner) =>
+ !owner.ephemeral &&
+ owner.sessionId !== sessionId &&
+ hasLiveSessionReference(owner, sharedPathKeys),
+ )
+ .map((owner) => owner.sessionId);
+}
+
+interface SessionRecycleSnapshot {
+ status: string | null | undefined;
+ workingDir: string | null;
+ worktreePath: string | null;
+}
+
+async function readSessionRecycleSnapshot(
+ sessionId: string,
+): Promise<SessionRecycleSnapshot | null> {
+ try {
+ const db = getDbClient().drizzle;
+ const [row] = await db
+ .select({
+ status: sessions.status,
+ workingDir: sessions.workingDir,
+ worktreePath: sessions.worktreePath,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId));
+ return row ?? null;
+ } catch (err) {
+ log.warn(
+ `[sessionRemovalRecycle] session recycle snapshot lookup failed for ${sessionId}; preserving worktree`,
+ err instanceof Error ? err.message : String(err),
+ );
+ return null;
+ }
+}
+
/**
* 动态回收任务在关闭 CLI / 删除 worktree 前共用的实时状态守卫。
* 查询失败按不可回收处理,宁可保留也不误关已恢复为 active 的会话。