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): 修复孤儿会话与预创建 worktree 回收 (#5898)

DavidShenXD559f6938903c
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts
index d39d9a4f8e..94d3c21125 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerCreate.test.ts
@@ -9,13 +9,16 @@ const gitExecMock = vi.fn();
const storeMap = new Map<string, WorktreeMeta>();
const storeSetMock = vi.fn();
const profile = vi.hoisted(() => ({ root: '' }));
+const checkoutLease = vi.hoisted(() => ({ record: vi.fn(), release: vi.fn() }));
vi.mock('electron', () => ({ app: { getPath: () => profile.root } }));
vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ readLocalWorktreeReferences: async () => [] }) }));
vi.mock('../worktree/piSubagentReferences', () => ({ readPiSubagentWorktreeReferences: async () => new Map() }));
vi.mock('../worktree/runtimeLeases', () => ({
readWorktreeRuntimePaths: async () => new Set(),
acquireWorktreeRuntimeLease: async () => ({}),
- releaseWorktreeRuntimeLease: async () => {},
+ recordWorktreeRuntimeLeaseChild: checkoutLease.record,
+ releaseWorktreeRuntimeLease: checkoutLease.release,
+ reclaimOrphanedWorktreeRuntimeLeases: async () => 0,
}));
const includeMock = vi.hoisted(() => vi.fn(async () => []));
@@ -102,6 +105,33 @@ describe('createWorktree naming authority', () => {
});
}
+ it('records the background checkout child and holds its lease until completion', async () => {
+ const previousGit = gitExecMock.getMockImplementation()!;
+ let finishCheckout!: () => void;
+ const checkout = new Promise<{ stdout: string; stderr: string }>((resolve) => {
+ finishCheckout = () => resolve({ stdout: '', stderr: '' });
+ });
+ const stagedPids = [4241, 4242, 4243];
+ let stagedIndex = 0;
+ gitExecMock.mockImplementation((args: string[], cwd?: string, opts?: { onSpawn?: (pid: number) => void }) => {
+ if (opts?.onSpawn && (args[0] === 'ls-tree' || args[0] === 'checkout')) {
+ opts.onSpawn(stagedPids[stagedIndex++]!);
+ }
+ if (args[0] === 'ls-tree') return { stdout: 'AGENTS.md\\n', stderr: '' };
+ if (args[0] === 'checkout' && args.includes(':(exclude).sivi')) return checkout;
+ return previousGit(args, cwd, opts);
+ });
+ try {
+ await expect(create('background')).resolves.toMatchObject({ ok: true });
+ expect(checkoutLease.record).toHaveBeenCalledTimes(3);
+ expect(checkoutLease.record.mock.calls.map((call) => call[1])).toEqual(stagedPids);
+ expect(checkoutLease.release).not.toHaveBeenCalled();
+ } finally {
+ finishCheckout();
+ }
+ await vi.waitFor(() => expect(checkoutLease.release).toHaveBeenCalledExactlyOnceWith({}));
+ });
+
it.each(['', ' \t'])('generates a meaningful final name for blank input %j', async (name) => {
const result = await create(name);
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
index ec5456322f..2850d7722f 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
@@ -1,8 +1,11 @@
// Normal archive/deletion coverage moved to managedWorktreeRecycle.test.ts:
// non-mutating content snapshots replace the former stash/reapply contract.
+const readWorktreeRuntimePathsMock = vi.hoisted(() => vi.fn(async () => new Set<string>()));
+const reclaimOrphanedRuntimeLeasesMock = vi.hoisted(() => vi.fn(async () => 0));
vi.mock('../worktree/runtimeLeases', () => ({
- readWorktreeRuntimePaths: async () => new Set(),
+ readWorktreeRuntimePaths: readWorktreeRuntimePathsMock,
acquireWorktreeRuntimeLease: async () => {}, releaseWorktreeRuntimeLease: async () => {},
+ reclaimOrphanedWorktreeRuntimeLeases: reclaimOrphanedRuntimeLeasesMock,
}));
/**
* removeWorktreeForSession / discardPrecreatedWorktree 删除守卫回归:
@@ -134,6 +137,8 @@ describe('removeWorktreeForSession', () => {
beforeEach(async () => {
vi.clearAllMocks();
+ readWorktreeRuntimePathsMock.mockReset().mockResolvedValue(new Set());
+ reclaimOrphanedRuntimeLeasesMock.mockReset().mockResolvedValue(0);
storeMap.clear();
cancelledIds.clear();
pendingSafeDirectoryCleanups.length = 0;
@@ -327,6 +332,27 @@ describe('removeWorktreeForSession', () => {
expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
});
+ it('cancellation rechecks live references after reclaiming a dead-owner lease', async () => {
+ const meta = { ...makeMeta('orphan'), recoveryKey: 'recovery-key-orphan-123456' };
+ storeMap.set(meta.sessionId, meta);
+ const runtimePaths = new Set<string>();
+ readWorktreeRuntimePathsMock.mockImplementation(async () => new Set(runtimePaths));
+ reclaimOrphanedRuntimeLeasesMock.mockImplementation(async () => {
+ runtimePaths.add(meta.path);
+ return 1;
+ });
+
+ await expect(manager.cancelPrecreatedWorktree(
+ meta.sessionId,
+ { recoveryKey: meta.recoveryKey },
+ { canRemove: async () => true },
+ )).resolves.toEqual({ status: 'preserved' });
+
+ expect(reclaimOrphanedRuntimeLeasesMock).toHaveBeenCalledWith(meta.path);
+ expect(storeMap.has(meta.sessionId)).toBe(true);
+ expect(gitExecMock).not.toHaveBeenCalledWith(['worktree', 'remove', meta.path], BASE_REPO);
+ });
+
it.each(['discard', 'cancel'])('%s waits for an in-flight create before deciding the record is absent', async (operation) => {
let releaseGitProbe!: () => void;
gitExecMock.mockImplementationOnce(
diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
index f20a9e15d2..03f03a2bf7 100644
--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
@@ -12,8 +12,18 @@ vi.mock('../desktopProcessIdentity', async (importOriginal) => ({
...await importOriginal<typeof import('../desktopProcessIdentity')>(),
readDesktopProcessIdentity: readIdentity,
}));
+vi.mock('../worktree/gitExec', () => ({
+ isGitProcessTreeAlive: vi.fn(async (pid: number) => pid === process.pid),
+}));
-import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths, retryPendingWorktreeRuntimeLeaseReleases } from '../worktree/runtimeLeases';
+import {
+ acquireWorktreeRuntimeLease,
+ recordWorktreeRuntimeLeaseChild,
+ reclaimOrphanedWorktreeRuntimeLeases,
+ releaseWorktreeRuntimeLease,
+ readWorktreeRuntimePaths,
+ retryPendingWorktreeRuntimeLeaseReleases,
+} from '../worktree/runtimeLeases';
import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';
import { createLinkedWorktreeMetadata } from './fixtures/linkedWorktree';
import { seedLegacySharedRuntimeLease } from './fixtures/legacySharedRuntimeLease';
@@ -412,6 +422,44 @@ describe('worktree runtime evidence and physical locks', () => {
expect(await readWorktreeRuntimePaths()).toEqual(new Set());
});
+ it('reclaims a dead-owner lease only through explicit orphan cancellation', async () => {
+ const lease = (await acquireWorktreeRuntimeLease('orphan', worktree))!;
+ recordWorktreeRuntimeLeaseChild(lease, 12345);
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });
+ });
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));
+ await expect(reclaimOrphanedWorktreeRuntimeLeases(worktree)).resolves.toBe(1);
+ await expect(fs.stat(lease.file)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ });
+
+ it('keeps an orphan lease while its detached checkout child is alive', async () => {
+ const lease = (await acquireWorktreeRuntimeLease('checkout:orphan', worktree))!;
+ recordWorktreeRuntimeLeaseChild(lease, process.pid);
+ const leaseValue = JSON.parse(await fs.readFile(lease.file, 'utf8')) as Record<string, unknown>;
+ const ownerPid = 12345;
+ await fs.writeFile(lease.file, JSON.stringify({ ...leaseValue, pid: ownerPid }));
+ vi.spyOn(process, 'kill').mockImplementation((pid) => {
+ if (pid === ownerPid) throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });
+ return true;
+ });
+
+ await expect(reclaimOrphanedWorktreeRuntimeLeases(worktree)).resolves.toBe(0);
+ await expect(fs.stat(lease.file)).resolves.toBeDefined();
+ });
+
+ it.each([undefined, null, 0, -1, '12345'])('preserves unknown child evidence: %s', async (childPid) => {
+ const lease = (await acquireWorktreeRuntimeLease('orphan', worktree))!;
+ const value = JSON.parse(await fs.readFile(lease.file, 'utf8'));
+ await fs.writeFile(lease.file, JSON.stringify({ ...value, childPid }));
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });
+ });
+ await expect(reclaimOrphanedWorktreeRuntimeLeases(worktree)).resolves.toBe(0);
+ await expect(fs.stat(lease.file)).resolves.toBeDefined();
+ });
+
it('does not treat a crashed owner partial lease as evidence of an idle directory', async () => {
const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;
await fs.writeFile(lease.file, '{');
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index dfa5767aef..cd81656761 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -45,7 +45,12 @@ import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionR
import { withWorktreeRestoreMutation } from './restoreLock';
import { recycleManagedWorktree } from './managedRecycle';
import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
-import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from './runtimeLeases';
+import {
+ acquireWorktreeRuntimeLease,
+ recordWorktreeRuntimeLeaseChild,
+ reclaimOrphanedWorktreeRuntimeLeases,
+ releaseWorktreeRuntimeLease,
+} from './runtimeLeases';
import * as store from './worktreeStore';
import { assertPrecreatedSessionNotCancelled, sealPrecreatedSessionCancellation, withPrecreatedSessionOperationLock } from './precreatedCancellation';
import { createLogger } from '../logger';
@@ -750,6 +755,7 @@ const STAGE_CHECKOUT_PATHS = [
*/
async function stageCheckout(
worktreePath: string,
+ onCheckoutChildSpawn?: (pid: number) => void,
): Promise<{ fullCheckoutPromise: Promise<void> }> {
const t0 = Date.now();
@@ -763,6 +769,7 @@ async function stageCheckout(
const { stdout } = await gitExec(
['ls-tree', '--name-only', 'HEAD', '--', ...STAGE_CHECKOUT_PATHS],
worktreePath,
+ { onSpawn: onCheckoutChildSpawn },
);
existingPaths = stdout
.split(/\r?\n/)
@@ -779,7 +786,9 @@ async function stageCheckout(
// 2. 选择性 checkout 白名单文件(同步, 用户可见)
if (existingPaths.length > 0) {
try {
- await gitExec(['checkout', 'HEAD', '--', ...existingPaths], worktreePath);
+ await gitExec(['checkout', 'HEAD', '--', ...existingPaths], worktreePath, {
+ onSpawn: onCheckoutChildSpawn,
+ });
log.info(
`[stageCheckout] selective checkout done in ${Date.now() - t0}ms (${existingPaths.length} paths)`,
);
@@ -798,7 +807,7 @@ async function stageCheckout(
const fullCheckoutPromise = gitExec(
['checkout', 'HEAD', '--', '.', ':(exclude).claude', ':(exclude).sivi'],
worktreePath,
- { extraEnv: { LC_ALL: 'C' } },
+ { extraEnv: { LC_ALL: 'C' }, onSpawn: onCheckoutChildSpawn },
)
.then(() => {
log.info(
@@ -1164,7 +1173,10 @@ async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktr
const checkoutLease = await acquireWorktreeRuntimeLease(`checkout:${req.sessionId}`, worktreePath);
if (!checkoutLease) throw new Error('managed checkout runtime lease is missing');
try {
- const stageRes = await timed('stage checkout', () => stageCheckout(worktreePath));
+ const stageRes = await timed('stage checkout', () => stageCheckout(
+ worktreePath,
+ (pid) => recordWorktreeRuntimeLeaseChild(checkoutLease, pid),
+ ));
bgPromise = stageRes.fullCheckoutPromise.finally(() => releaseWorktreeRuntimeLease(checkoutLease));
} catch (err) {
await releaseWorktreeRuntimeLease(checkoutLease);
@@ -1286,6 +1298,12 @@ export interface RemoveWorktreeOptions {
* 命中 dirty 时保留整个 worktree。
*/
preserveDirty?: boolean;
+ /**
+ * Explicit cancellation of an unclaimed pre-created worktree may reclaim
+ * dead-owner runtime leases for its exact path. Ordinary task removal keeps
+ * those leases protective because they may belong to detached children.
+ */
+ reclaimOrphanedRuntimeLeases?: boolean;
}
/**
@@ -1384,7 +1402,23 @@ async function removeWorktreeForSessionInner(
excludeSessionId: sessionId,
isSessionRuntimeAlive: options.isSessionRuntimeAlive,
});
- if (hasLiveSessionReference(meta, liveKeys)) {
+ if (options.reclaimOrphanedRuntimeLeases) {
+ const reclaimed = await reclaimOrphanedWorktreeRuntimeLeases(worktreePath);
+ if (reclaimed > 0) {
+ log.info(
+ '[worktree] reclaimed ' + reclaimed
+ + ' dead-owner runtime lease(s) for cancelled pre-created worktree at ' + worktreePath,
+ );
+ }
+ }
+ const refreshedLiveKeys = options.reclaimOrphanedRuntimeLeases
+ ? await loadLiveSessionPathKeys({
+ contextPath: worktreePath,
+ excludeSessionId: sessionId,
+ isSessionRuntimeAlive: options.isSessionRuntimeAlive,
+ })
+ : liveKeys;
+ if (hasLiveSessionReference(meta, refreshedLiveKeys)) {
log.info(
`[worktree] preserved worktree at ${worktreePath}: still referenced by another live session`,
);
@@ -1627,7 +1661,12 @@ export async function cancelPrecreatedWorktree(
if (meta?.ephemeral) return { status: 'preserved' };
if (!options.canRemove || !(await options.canRemove())) return { status: 'preserved' };
sealPrecreatedSessionCancellation(sessionId);
- return meta ? discardPrecreatedWorktree(sessionId, meta.path, options) : { status: 'absent' };
+ return meta
+ ? discardPrecreatedWorktree(sessionId, meta.path, {
+ ...options,
+ reclaimOrphanedRuntimeLeases: true,
+ })
+ : { status: 'absent' };
});
}
export { assertPrecreatedSessionNotCancelled } from './precreatedCancellation';
@@ -1640,7 +1679,7 @@ export { assertPrecreatedSessionNotCancelled } from './precreatedCancellation';
export async function discardPrecreatedWorktreeByRecoveryKey(
sessionId: string,
recoveryKey: string,
- options: Pick<RemoveWorktreeOptions, 'canRemove'> = {},
+ options: Pick<RemoveWorktreeOptions, 'canRemove' | 'reclaimOrphanedRuntimeLeases'> = {},
): Promise<DiscardPrecreatedWorktreeResult> {
return withPrecreatedWorktreeOperationQueue(sessionId, async () => {
const meta = store.get(sessionId);
@@ -1665,7 +1704,7 @@ export async function discardPrecreatedWorktreeByRecoveryKey(
export async function discardPrecreatedWorktree(
sessionId: string,
expectedPath: string,
- options: Pick<RemoveWorktreeOptions, 'canRemove'> = {},
+ options: Pick<RemoveWorktreeOptions, 'canRemove' | 'reclaimOrphanedRuntimeLeases'> = {},
): Promise<DiscardPrecreatedWorktreeResult> {
const meta = store.get(sessionId);
if (!meta) return { status: 'absent' };
diff --git a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
index b2a80e4cdf..5c3825512f 100644
--- a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
@@ -29,6 +29,7 @@ vi.mock('../../logger', () => ({
import {
gitExec,
GitExecError,
+ isGitProcessTreeAlive,
normalizeSafeDirectorySpelling,
safeDirectorySpellings,
} from '../gitExec';
@@ -178,6 +179,35 @@ afterEach(() => {
});
describe('gitExec timeoutMs', () => {
+ it('keeps a dead checkout root leased while a Windows descendant remains', async () => {
+ setPlatform('win32');
+ const state = installExecFileMock();
+ state.psTable = [{ ProcessId: 4343, ParentProcessId: 4242, CreationDate: 'x' }];
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw Object.assign(new Error('gone'), { code: 'ESRCH' });
+ });
+ await expect(isGitProcessTreeAlive(4242)).resolves.toBe(true);
+ });
+
+ it('keeps a lease when the Windows snapshot has already lost the checkout root', async () => {
+ setPlatform('win32');
+ const state = installExecFileMock();
+ state.psTable = [];
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw Object.assign(new Error('gone'), { code: 'ESRCH' });
+ });
+ await expect(isGitProcessTreeAlive(4242)).resolves.toBe(true);
+ });
+
+ it('records the spawned checkout PID before completion', async () => {
+ const state = installExecFileMock();
+ const onSpawn = vi.fn();
+ const result = gitExec(['checkout', 'HEAD', '--', '.'], undefined, { onSpawn });
+ expect(onSpawn).toHaveBeenCalledExactlyOnceWith(state.child.pid);
+ state.gitCb!(null, '', '');
+ await expect(result).resolves.toEqual({ stdout: '', stderr: '' });
+ });
+
it('stdout ENOTCONN 先完成整树清理,再收口为 GitExecError', async () => {
setPlatform('win32');
const state = installExecFileMock();
diff --git a/apps/desktop/src/main/worktree/gitExec.ts b/apps/desktop/src/main/worktree/gitExec.ts
index 486d984c12..2975225269 100644
--- a/apps/desktop/src/main/worktree/gitExec.ts
+++ b/apps/desktop/src/main/worktree/gitExec.ts
@@ -83,6 +83,8 @@ export interface GitExecOpts {
* 省略 = 不超时。
*/
timeoutMs?: number;
+ /** Called immediately after the git child is spawned. */
+ onSpawn?: (pid: number) => void;
}
/** POSIX 超时后 SIGTERM → SIGKILL 的宽限期:给 git 留出清理 .lock 的时间窗。 */
@@ -157,6 +159,50 @@ async function queryWin32ProcessTable(
}
}
+/**
+ * Check whether a detached git process or one of its descendants remains.
+ * Unknown process-table state is protective because reclaim must never race a
+ * filter/helper that still has the worktree open.
+ */
+export async function isGitProcessTreeAlive(pid: number): Promise<boolean> {
+ if (pid <= 0) return true;
+ if (process.platform !== 'win32') {
+ try {
+ process.kill(-pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+ }
+ if (pidMayBeAliveForGit(pid)) return true;
+ const rows = await queryWin32ProcessTable();
+ if (!rows) return true;
+ // Once the root has exited, a Windows snapshot may have already reparented
+ // or dropped its descendants. Missing ancestry cannot prove the tree is gone.
+ if (!rows.some((row) => row.pid === pid)) return true;
+ const descendants = new Set([pid]);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const row of rows) {
+ if (descendants.has(row.ppid) && !descendants.has(row.pid)) {
+ descendants.add(row.pid);
+ changed = true;
+ }
+ }
+ }
+ return descendants.size > 1;
+}
+
+function pidMayBeAliveForGit(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+}
+
/**
* 执行一次 git, 不做 dubious-ownership 自动重试(底层用)。
*/
@@ -271,6 +317,7 @@ function execFileOnce(
resolveWithResult({ stdout: stdoutStr, stderr: stderrStr });
},
);
+ if (child.pid !== undefined) opts?.onSpawn?.(child.pid);
} catch (error) {
const cause = error instanceof Error ? error : new Error(String(error));
rejectWithGitError(
diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.ts
index 4c50568c2b..0a0044f306 100644
--- a/apps/desktop/src/main/worktree/runtimeLeases.ts
+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts
@@ -1,4 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
+import fsSync from 'node:fs';
import fs from 'node:fs/promises';
import path from 'node:path';
import { app } from 'electron';
@@ -7,6 +8,7 @@ import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';
import { notifyWorktreeRecycleOpportunity } from './recycleEvents';
import { isReusedDesktopInstancePid, readDesktopProcessIdentity } from '../desktopProcessIdentity';
+import { isGitProcessTreeAlive } from './gitExec';
function runtimeRoot(): string {
return path.join(app.getPath('userData'), 'worktree-runtime-leases');
@@ -127,6 +129,29 @@ export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease):
await releaseRuntimeLeaseFile(lease);
}
+/** Record the detached git child that is still using a checkout lease. */
+export function recordWorktreeRuntimeLeaseChild(lease: WorktreeRuntimeLease, childPid: number): void {
+ if (!Number.isInteger(childPid) || childPid <= 0) return;
+ try {
+ const value = JSON.parse(fsSync.readFileSync(lease.file, 'utf8')) as {
+ version?: unknown;
+ pid?: unknown;
+ path?: unknown;
+ childPid?: unknown;
+ childPids?: unknown;
+ };
+ if (value.version !== 1 || value.pid !== process.pid || value.path !== lease.physicalPath) return;
+ const childPids = [
+ ...(Array.isArray(value.childPids) ? value.childPids : []),
+ ...(typeof value.childPid === 'number' ? [value.childPid] : []),
+ childPid,
+ ].filter((pid, index, all): pid is number => Number.isInteger(pid) && pid > 0 && all.indexOf(pid) === index);
+ fsSync.writeFileSync(lease.file, JSON.stringify({ ...value, childPid, childPids }), { mode: 0o600 });
+ } catch {
+ // Missing or partially written child evidence must stay protective.
+ }
+}
+
async function removeRuntimeLeaseFile(lease: WorktreeRuntimeLease): Promise<void> {
if (lease.keepSentinel) {
await withWorktreeResourceLock(lease.physicalPath, async () => {
@@ -300,3 +325,66 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {
}
return paths;
}
+
+/** A detached checkout can outlive git while its POSIX process group remains active. */
+/**
+ * Remove runtime leases left by a dead owner for an explicitly cancelled,
+ * unclaimed pre-created worktree.
+ *
+ * Normal recycle deliberately keeps leases from dead processes because they
+ * may belong to a detached child. A pre-created worktree has no claimed
+ * session yet, and the caller has already fenced late creation under the
+ * session lock. Reclaim only a recorded checkout child whose owner and child
+ * have both exited. Older leases without child evidence, malformed records,
+ * and unknown process liveness remain protective.
+ */
+export async function reclaimOrphanedWorktreeRuntimeLeases(
+ worktreePath: string,
+): Promise<number> {
+ const target = await physicalWorktreeKey(worktreePath);
+ let reclaimed = 0;
+ for (const directory of [runtimeRoot(), sharedRuntimeRoot()]) {
+ let names: string[];
+ try {
+ names = await fs.readdir(directory);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ continue;
+ }
+ for (const name of names) {
+ if (!leaseNamePattern.test(name)) continue;
+ const file = path.join(directory, name);
+ try {
+ const value = JSON.parse(await fs.readFile(file, 'utf8')) as {
+ version?: unknown;
+ pid?: unknown;
+ path?: unknown;
+ childPid?: unknown;
+ childPids?: unknown;
+ };
+ const childPids = Array.isArray(value.childPids)
+ ? value.childPids.filter((pid): pid is number => typeof pid === 'number' && Number.isInteger(pid) && pid > 0)
+ : typeof value.childPid === 'number' && Number.isInteger(value.childPid) && value.childPid > 0
+ ? [value.childPid]
+ : [];
+ if (value.version !== 1 || typeof value.pid !== 'number'
+ || !Number.isInteger(value.pid) || value.pid <= 0
+ || typeof value.path !== 'string'
+ || await physicalWorktreeKey(value.path) !== target
+ || pidMayBeAlive(value.pid)
+ || childPids.length === 0
+ || (await Promise.all(childPids.map((pid) => isGitProcessTreeAlive(pid))).then((alive) => alive.some(Boolean)))) {
+ continue;
+ }
+ await fs.unlink(file);
+ reclaimed += 1;
+ } catch (error) {
+ // A concurrent release may win the race. Any other read/parse/write
+ // failure stays protective and is retried by the normal maintenance
+ // path rather than authorizing deletion.
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') continue;
+ }
+ }
+ }
+ return reclaimed;
+}
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index d8fbf4f3a0..0f5d16dccc 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -40,6 +40,7 @@ import {
import { buildMainWindowLayout } from '@/components/mainWindowLayout';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { formatRemoteError } from '@/device-link/remoteStatus';
+import { isExplicitRemoteNotFoundError } from '@/session/newSessionWorktree';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { useRemoteSyncTask } from '@/device-link/remoteSyncTask';
import {
@@ -598,7 +599,12 @@ function DeviceDetailScreenContent() {
try {
const updated = await maker.patchSessionMeta(row.session.id, patch);
if (updated) remoteSessionStore.applySessionPatch(row.rowDeviceId, row.session.id, updated);
- } catch {
+ } catch (err) {
+ if (isExplicitRemoteNotFoundError(err) && patch.status !== undefined) {
+ remoteSessionStore.applySessionPatch(row.rowDeviceId, row.session.id, { status: 'deleted' });
+ remoteSessionStore.requestReseed(row.rowDeviceId);
+ return;
+ }
failed.push(row);
}
}));
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 3903cfc817..e61f87fbe4 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -149,6 +149,7 @@ import {
runSessionProjectionSnapshotSingleFlight,
} from '@/device-link/sessionSnapshotSingleFlight';
import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';
+import { isExplicitRemoteNotFoundError } from '@/session/newSessionWorktree';
import { shouldClearOperationErrorAfterSync, type SessionOperationError } from '@/session/sessionSyncErrorRecovery';
import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
@@ -8936,7 +8937,8 @@ export default function SessionScreen() {
// 同一解析):re-link 后两者可能不同,按路由 id 落 shard 会让归档移行落空、回滚插错 shard。
const { rpcDeviceId, shardId } = resolveSessionWriteDevices(sessionId, session, deviceId)
?? { rpcDeviceId: deviceId, shardId: deviceId };
- if (patch.status === 'archived' || patch.status === 'deleted') {
+ const leavesDetailScreen = patch.status === 'archived' || patch.status === 'deleted';
+ if (leavesDetailScreen) {
goBackToHome();
}
// 写序登记、出网链路、对账/回滚全部对齐首页字段级契约(review P1/P2 多轮:守卫
@@ -8979,6 +8981,14 @@ export default function SessionScreen() {
}
} catch (err) {
if (write.isLatest()) {
+ if (fields.includes('status') && isExplicitRemoteNotFoundError(err)) {
+ // A cached mobile row can outlive its desktop session. An exact
+ // NOT_FOUND proves that the remote row is gone, so retire the
+ // local mirror instead of restoring a row that can never sync.
+ remoteSessionStore.applySessionPatch(shardId, sessionId, { status: 'deleted' });
+ if (!leavesDetailScreen) goBackToHome();
+ return;
+ }
if (fields.includes('status')) {
// 归档/删除/恢复失败:行可能已被移出列表,反向 patch 复活不了,整对象
// 插回原物理 shard。回滚设备名优先取 shard 当前值(同首页 review P2 教训):
diff --git a/apps/mobile/src/__tests__/newSessionWorktree.test.ts b/apps/mobile/src/__tests__/newSessionWorktree.test.ts
index 86ea97c939..d266375205 100644
--- a/apps/mobile/src/__tests__/newSessionWorktree.test.ts
+++ b/apps/mobile/src/__tests__/newSessionWorktree.test.ts
@@ -285,6 +285,14 @@ describe('isExactRemoteSessionClaimed', () => {
}),
)).rejects.toThrow('proxy context: Error: [NOT_FOUND] incidental');
});
+
+ it.each([
+ new Error("[NOT_FOUND] no local IPC handler for channel 'local-db:sessions:patch-meta'"),
+ new Error('Error invoking remote method: Error: [NOT_FOUND] handler not registered yet'),
+ ])('does not treat a missing IPC handler as an absent session', async (error) => {
+ await expect(isExactRemoteSessionClaimed('s1', async () => { throw error; }))
+ .rejects.toBe(error);
+ });
});
describe('shouldAcceptWorktreeBranchListResult', () => {
diff --git a/apps/mobile/src/__tests__/orphanSessionActions.test.ts b/apps/mobile/src/__tests__/orphanSessionActions.test.ts
new file mode 100644
index 0000000000..dd81d1942e
--- /dev/null
+++ b/apps/mobile/src/__tests__/orphanSessionActions.test.ts
@@ -0,0 +1,115 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { isExplicitRemoteNotFoundError } from '@/session/newSessionWorktree';
+import { pickWriteFields, writeGuardFields } from '@/session/swipeRowRegistry';
+
+// Execute the production callbacks without mounting the entire native screen.
+function callback(file: string, name: string, bindings: Record<string, unknown>) {
+ const source = ts.createSourceFile(file, readFileSync(resolve(process.cwd(), file), 'utf8'),
+ ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ let expression: ts.Expression | undefined;
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name
+ && node.initializer && ts.isCallExpression(node.initializer)) {
+ expression = node.initializer.arguments[0];
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ if (!expression) throw new Error(`Missing production callback ${name}`);
+ const compiled = ts.transpileModule(`const fn = ${expression.getText(source)};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ return new Function(...Object.keys(bindings), `${compiled}; return fn;`)(...Object.values(bindings));
+}
+
+const session = { id: 's1', status: 'active', deviceLinkDeviceId: 'shard', deviceLinkDeviceName: 'PC' };
+function fixture() {
+ let reject!: (error: Error) => void;
+ const pending = new Promise((_resolve, fail) => { reject = fail; });
+ const store = {
+ applySessionPatch: vi.fn(), upsertDeviceSession: vi.fn(), requestReseed: vi.fn(),
+ getSessions: () => [session],
+ };
+ const release = vi.fn();
+ const isLatest = vi.fn(() => true);
+ const bindings = {
+ currentSession: session, deviceId: 'rpc', sessionId: session.id,
+ resolveSessionWriteDevices: () => ({ rpcDeviceId: 'rpc', shardId: 'shard' }),
+ sessionMetaWriteGuard: { begin: () => ({ isLatest }) },
+ sessionMetaWriteQueue: { enqueue: () => pending },
+ sessionPendingWrites: { track: () => release },
+ remoteSessionStore: store, isExplicitRemoteNotFoundError, pickWriteFields, writeGuardFields,
+ goBackToHome: vi.fn(), Alert: { alert: vi.fn() }, humanizeRemoteError: String,
+ animateListChange: undefined, t: (key: string) => key,
+ };
+ return { bindings, reject, store, release, isLatest };
+}
+const gone = () => new Error('[NOT_FOUND] Session does not exist');
+const tick = () => new Promise((done) => setTimeout(done, 0));
+
+describe('orphan task status actions', () => {
+ it.each(['archived', 'deleted', 'active'])('list status %s retires the mirror without rollback', async (status) => {
+ const f = fixture();
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', f.bindings);
+ const request = patch(session, { status });
+ f.reject(gone());
+ await request;
+ expect(f.store.applySessionPatch).toHaveBeenLastCalledWith('shard', 's1', { status: 'deleted' });
+ expect(f.store.upsertDeviceSession).not.toHaveBeenCalled();
+ expect(f.store.requestReseed).toHaveBeenCalledWith('shard');
+ expect(f.release).toHaveBeenCalled();
+ });
+
+ it('keeps ordinary failures on the rollback path', async () => {
+ const f = fixture();
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', f.bindings);
+ const request = patch(session, { status: 'archived' });
+ f.reject(new Error('network unavailable'));
+ await expect(request).rejects.toThrow('network unavailable');
+ expect(f.store.upsertDeviceSession).toHaveBeenCalledWith('shard', 'PC', session);
+ });
+
+ it('does not let an obsolete list write retire a newer task state', async () => {
+ const f = fixture();
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', f.bindings);
+ const request = patch(session, { status: 'archived' });
+ f.isLatest.mockReturnValue(false);
+ f.reject(gone());
+ await expect(request).rejects.toThrow('NOT_FOUND');
+ expect(f.store.applySessionPatch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['archived', 'deleted'])('late %s detail response does not navigate away from the next page', async (status) => {
+ const f = fixture();
+ const patch = callback('app/sessions/[sessionId].tsx', 'patchSessionMeta', f.bindings);
+ patch({ status });
+ expect(f.bindings.goBackToHome).toHaveBeenCalledTimes(1);
+ // The user may already have opened a different task by the time the RPC fails.
+ f.reject(gone());
+ await tick();
+ expect(f.bindings.goBackToHome).toHaveBeenCalledTimes(1);
+ expect(f.store.upsertDeviceSession).not.toHaveBeenCalled();
+ expect(f.bindings.Alert.alert).not.toHaveBeenCalled();
+ expect(f.release).toHaveBeenCalled();
+ });
+
+ it('bulk status changes omit confirmed orphans from the failed selection', async () => {
+ const f = fixture();
+ const selected = vi.fn();
+ const notice = vi.fn();
+ const bulk = callback('app/devices/[deviceId].tsx', 'executeBulkAction', {
+ ...f.bindings, bulkActionPending: null, setBulkActionPending: vi.fn(),
+ setBulkNotice: notice, setBulkConfirmAction: vi.fn(), setSelectedSessionIds: selected,
+ setSelectionRequested: vi.fn(), mobileSessionBulkPatch: () => ({ status: 'archived' }),
+ maker: { patchSessionMeta: vi.fn(async () => { throw gone(); }) }, loadSessions: vi.fn(),
+ });
+ await bulk('archive', [session]);
+ expect(f.store.applySessionPatch).toHaveBeenLastCalledWith('shard', 's1', { status: 'deleted' });
+ expect(f.store.upsertDeviceSession).not.toHaveBeenCalled();
+ expect(selected).toHaveBeenCalledExactlyOnceWith([]);
+ expect(notice).toHaveBeenCalledExactlyOnceWith(null);
+ });
+});
diff --git a/apps/mobile/src/session/newSessionWorktree.ts b/apps/mobile/src/session/newSessionWorktree.ts
index 716caa4c98..4b294a6891 100644
--- a/apps/mobile/src/session/newSessionWorktree.ts
+++ b/apps/mobile/src/session/newSessionWorktree.ts
@@ -186,6 +186,13 @@ export async function isExactRemoteSessionClaimed(
* proves absence. Incidental text containing NOT_FOUND remains unknown.
*/
export function isExplicitRemoteNotFoundError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : '';
+ // Missing invoke handlers reuse the transport's NOT_FOUND code while the
+ // host is starting or an older host lacks the channel; that is not proof
+ // that the remote session row was deleted.
+ if (/(?:no local IPC handler|handler not registered|no handler registered)/i.test(message)) {
+ return false;
+ }
if (error && typeof error === 'object' && !Array.isArray(error)) {
const code = (error as { code?: unknown }).code;
if (typeof code === 'string' && code.trim().toUpperCase() === 'NOT_FOUND') {
@@ -193,8 +200,7 @@ export function isExplicitRemoteNotFoundError(error: unknown): boolean {
}
}
if (!(error instanceof Error)) return false;
- return /^(?:\[NOT_FOUND\]|Error invoking remote method(?: '[^']+')?: Error: \[NOT_FOUND\])(?:\s|$)/
- .test(error.message);
+ return /^(?:\[NOT_FOUND\]|Error invoking remote method(?: '[^']+')?: Error: \[NOT_FOUND\])(?:\s|$)/.test(message);
}
/**
diff --git a/apps/mobile/src/session/useSessionListActions.ts b/apps/mobile/src/session/useSessionListActions.ts
index cd543660d7..37d92371cd 100644
--- a/apps/mobile/src/session/useSessionListActions.ts
+++ b/apps/mobile/src/session/useSessionListActions.ts
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { humanizeRemoteError } from '@/device-link/remoteStatus';
+import { isExplicitRemoteNotFoundError } from '@/session/newSessionWorktree';
import type { SessionMetaPatch } from '@/device-link/mobileMakerTransport';
import {
remoteSessionStore,
@@ -82,6 +83,11 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
} catch (err) {
if (write.isLatest()) {
if (fields.includes('status')) {
+ if (isExplicitRemoteNotFoundError(err)) {
+ remoteSessionStore.applySessionPatch(shardId, session.id, { status: 'deleted' });
+ remoteSessionStore.requestReseed(shardId);
+ return;
+ }
const shardName = remoteSessionStore.getSessions()
.find((s) => s.deviceLinkDeviceId === shardId)?.deviceLinkDeviceName
?? session.deviceLinkDeviceName