Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 识别 launch fence 暂存残留,worktree 回收不再永久停在“仍在使用”(#4767) (#4769)
FicoWang9e34e295815c
diff --git a/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.ts b/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.tsindex 8721339f74..860c590ac7 100644--- a/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.ts+++ b/apps/desktop/src/main/__tests__/worktreePiSubagentReferences.test.ts@@ -112,6 +112,48 @@ describe('detached Pi Subagent worktree references', () => {expect(await protects()).toBe(true);});+ it('reads past the host launch fence and the staging file a crash leaves in the run root', async () => {+ const root = path.dirname(runRoot());+ await fs.mkdir(root, { recursive: true });+ const fence = JSON.stringify({ version: 1, hostPid: 4_194_303, hostStartTimeSec: 1, createdAt: 0 });+ const staging = '.launch-fence-4194303.json.tmp-4194303-89aea6ae-a2c7-4fa4-8856-82503af66389';+ await fs.writeFile(path.join(root, '.launch-fence-4194303.json'), fence);+ await fs.writeFile(path.join(root, staging), fence);+ await fs.writeFile(path.join(root, '.launch-fence.json.tmp-4194303-89aea6ae-a2c7-4fa4-8856-82503af66389'), '{"vers');++ // No session holds a reference, so the recycle may go on to its own checks.+ expect(await readPiSubagentWorktreeReferences()).toEqual(new Map());+ expect(await livePaths()).not.toBeNull();+ expect(await protects()).toBe(false);++ // And a real reference beside the debris is still read in full.+ await writeRun();+ expect(await readPiSubagentWorktreeReferences()).toEqual(new Map([['parent', [worktree]]]));+ expect(await protects()).toBe(true);+ });++ it.each(['directory', 'link'])('preserves when a fence-named entry is a %s', async (shape) => {+ await writeRun();+ const entry = path.join(path.dirname(runRoot()), '.launch-fence-4194303.json.tmp-4194303-89aea6ae-a2c7-4fa4-8856-82503af66389');+ if (shape === 'directory') {+ await fs.mkdir(entry);+ } else {+ const target = path.join(state.root, 'link-target');+ await fs.writeFile(target, '{}');+ await fs.symlink(target, entry, process.platform === 'win32' ? 'file' : undefined);+ }+ expect(await livePaths()).toBeNull();+ });++ it.each(['notes.txt', '.launch-fence-backup.json', '.launch-fence-.json'])(+ 'preserves when a plain file it does not know (%s) sits in the run root',+ async (name) => {+ await writeRun();+ await fs.writeFile(path.join(path.dirname(runRoot()), name), 'x');+ expect(await livePaths()).toBeNull();+ },+ );+it('does not filter out unfinished or malformed run directories', async () => {await fs.mkdir(path.join(runRoot(), 'not-a-uuid'), { recursive: true });expect(await livePaths()).toBeNull();diff --git a/apps/desktop/src/main/worktree/piSubagentReferences.ts b/apps/desktop/src/main/worktree/piSubagentReferences.tsindex 24b9e25369..46716d864f 100644--- a/apps/desktop/src/main/worktree/piSubagentReferences.ts+++ b/apps/desktop/src/main/worktree/piSubagentReferences.ts@@ -2,7 +2,7 @@ import fs from 'node:fs/promises';import type { Stats } from 'node:fs';import path from 'node:path';import { app } from 'electron';-import { piSubagentRunRoot } from '@cindy/maker-core/pi-subagent-runs';+import { piSubagentLaunchFenceArtifact, piSubagentRunRoot } from '@cindy/maker-core/pi-subagent-runs';import { createLogger } from '../logger';@@ -59,6 +59,19 @@ export async function readPiSubagentWorktreeReferences(): Promise<ReadonlyMap<stconst rootSnapshot = await readDirectory(root);const references = new Map<string, readonly string[]>();for (const sessionId of rootSnapshot.entries) {+ if (piSubagentLaunchFenceArtifact(sessionId)) {+ // The Host's own launch fence — and the staging file a crash can leave+ // between its write and the rename — sits in this root beside the+ // session directories. As a plain file it is not a session and holds no+ // reference, so it is skipped rather than failing the whole read: that+ // failure is what kept every recycle on a machine with one leftover+ // staging file waiting on "still referenced" for good. Anything else+ // wearing that name is not something the fence machinery writes, and+ // stays fail-closed like any other suspicious entry.+ const stat = await fs.lstat(path.join(root, sessionId));+ if (stat.isSymbolicLink() || !stat.isFile()) return null;+ continue;+ }const sessionRoot = piSubagentRunRoot(agentHome, sessionId);const sessionSnapshot = await readDirectory(sessionRoot);const paths = new Set<string>();diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.tsindex 181274b9fb..5ff2cbdf03 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts@@ -16,6 +16,7 @@ import {scanPiSubagentRuns,acquirePiSubagentLaunchFence,clearStalePiSubagentLaunchFence,+ piSubagentLaunchFenceArtifact,isPiSubagentLaunchFenceActive,piSubagentDeletedTombstonePath,writePiSubagentDeletedTombstone,@@ -2084,6 +2085,81 @@ describe('PI durable subagent run store', () => {expect(isPiSubagentLaunchFenceActive(agentHome, otherHostPid)).toBe(true);});+ it('names the fence artifacts the runs root may contain, and nothing else', () => {+ expect(piSubagentLaunchFenceArtifact('.launch-fence.json')).toEqual({ kind: 'published' });+ expect(piSubagentLaunchFenceArtifact('.launch-fence-10596.json')).toEqual({ kind: 'published' });+ expect(piSubagentLaunchFenceArtifact(+ '.launch-fence-10596.json.tmp-10596-89aea6ae-a2c7-4fa4-8856-82503af66389',+ )).toEqual({ kind: 'staging', writerPid: 10596 });+ expect(piSubagentLaunchFenceArtifact(+ '.launch-fence.json.tmp-10596-89aea6ae-a2c7-4fa4-8856-82503af66389',+ )).toEqual({ kind: 'staging', writerPid: 10596 });+ // A parent-session directory, a run directory, and near-misses stay out.+ expect(piSubagentLaunchFenceArtifact('123e4567-e89b-42d3-a456-4266141740e0')).toBeNull();+ expect(piSubagentLaunchFenceArtifact('session-1')).toBeNull();+ expect(piSubagentLaunchFenceArtifact('.launch-fence-10596.json.bak')).toBeNull();+ // Only a numeric pid sits between the prefix and the suffix.+ expect(piSubagentLaunchFenceArtifact('.launch-fence-backup.json')).toBeNull();+ expect(piSubagentLaunchFenceArtifact('.launch-fence-.json')).toBeNull();+ expect(piSubagentLaunchFenceArtifact('.launch-fence-10596x.json')).toBeNull();+ expect(piSubagentLaunchFenceArtifact(+ '.launch-fence-backup.json.tmp-10596-89aea6ae-a2c7-4fa4-8856-82503af66389',+ )).toBeNull();+ expect(piSubagentLaunchFenceArtifact('.launch-fence-10596.json.tmp-10596-not-a-uuid')).toBeNull();+ expect(piSubagentLaunchFenceArtifact('status.json.tmp-10596-89aea6ae-a2c7-4fa4-8856-82503af66389')).toBeNull();+ });++ describe('a staging file a crash left between write and rename', () => {+ const stagingUuid = '89aea6ae-a2c7-4fa4-8856-82503af66389';+ const stagingPath = (agentHome: string, writerPid: number, base = `.launch-fence-${writerPid}.json`) => path.join(+ path.dirname(piSubagentLaunchFencePath(agentHome)),+ `${base}.tmp-${writerPid}-${stagingUuid}`,+ );+ const payload = (hostPid: number, hostStartTimeSec?: number) => `${JSON.stringify({+ version: 1,+ hostPid,+ ...(hostStartTimeSec === undefined ? {} : { hostStartTimeSec }),+ leaseId: '5ae20afc-0789-4d90-98dc-9f577e05acef',+ createdAt: 1_789_436_177_945,+ })}\n`;++ it('sweeps it once its writer is gone, whether complete or half-written', async () => {+ const agentHome = await makeRoot();+ await mkdir(path.dirname(piSubagentLaunchFencePath(agentHome)), { recursive: true });+ const complete = stagingPath(agentHome, 4_194_303);+ const halfWritten = stagingPath(agentHome, 4_194_303, '.launch-fence.json');+ await writeFile(complete, payload(4_194_303, 1_789_385_816));+ await writeFile(halfWritten, '{"version":1,"hostPid":4194');+ // And one the OS handed our own pid to after the writer crashed.+ const recycled = stagingPath(agentHome, process.pid);+ await writeFile(recycled, payload(process.pid, 1));++ await clearStalePiSubagentLaunchFence(agentHome);++ for (const file of [complete, halfWritten, recycled]) {+ await expect(readFile(file, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });+ }+ });++ it('leaves it alone while its writer is still alive', async () => {+ const agentHome = await makeRoot();+ await mkdir(path.dirname(piSubagentLaunchFencePath(agentHome)), { recursive: true });+ const complete = stagingPath(agentHome, process.pid);+ await writeFile(complete, payload(process.pid));+ // Half-written by a live host: the only proof of ownership is the pid+ // in the name, and that host may be one rename away from publishing.+ const halfWritten = stagingPath(agentHome, process.pid, '.launch-fence.json');+ await writeFile(halfWritten, '{"version":1,"hostPid":');++ await clearStalePiSubagentLaunchFence(agentHome);++ await expect(readFile(complete, 'utf8')).resolves.toContain('"version":1');+ await expect(readFile(halfWritten, 'utf8')).resolves.toBe('{"version":1,"hostPid":');+ // It never counts as a fence either: only the named path does.+ expect(isPiSubagentLaunchFenceActive(agentHome, process.pid)).toBe(false);+ });+ });+it('ignores and sweeps a fence its pid inherited from a previous life', async () => {// A crash leaves the file behind and the OS hands the same pid to the// next instance. Without a start time that instance's own fence checkdiff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex 9096717870..d19fb92896 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -262,6 +262,51 @@ export type PiSubagentControlAction = 'stop' | 'steer' | 'follow_up' | 'approvalexport const PI_SUBAGENT_LAUNCH_FENCE_FILENAME = '.launch-fence.json';const PI_SUBAGENT_LAUNCH_FENCE_PREFIX = '.launch-fence-';const PI_SUBAGENT_LAUNCH_FENCE_SUFFIX = '.json';+/**+ * The staging name `writeAtomicJson` publishes through: `<file>.tmp-<pid>-<uuid>`,+ * where `<pid>` is the writer. A host killed between that write and the rename+ * leaves the staging file behind in the runs root, next to the session dirs.+ */+const ATOMIC_STAGING_NAME_RE = /^(.+)\.tmp-(\d{1,10})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** A file in the runs root that belongs to the launch fence, not to a session. */+export type PiSubagentLaunchFenceArtifact =+ | { readonly kind: 'published' }+ | { readonly kind: 'staging'; readonly writerPid: number };++/**+ * Exactly the names `piSubagentLaunchFencePath` produces (a numeric pid between+ * the prefix and the suffix) plus the legacy shared name. Anything looser —+ * `.launch-fence-backup.json`, `.launch-fence-.json` — is not something the+ * fence writer ever emits, so it must neither be swept as a fence nor skipped by+ * the reference scan as one.+ */+const PUBLISHED_LAUNCH_FENCE_NAME_RE = new RegExp(+ `^${PI_SUBAGENT_LAUNCH_FENCE_PREFIX.replace(/[.]/g, '\\.')}\\d{1,10}${PI_SUBAGENT_LAUNCH_FENCE_SUFFIX.replace(/[.]/g, '\\.')}$`,+);++function isPublishedLaunchFenceName(entry: string): boolean {+ return entry === PI_SUBAGENT_LAUNCH_FENCE_FILENAME || PUBLISHED_LAUNCH_FENCE_NAME_RE.test(entry);+}++/**+ * The one naming contract for what the fence machinery leaves in the runs root.+ *+ * Two readers walk that directory and must agree on it: the stale sweep, which+ * decides what it may delete, and the Host's worktree-reference scan, which has+ * to know which names are *not* parent-session directories. They drifted once —+ * the sweep only knew the published names, the scan knew none — and a staging+ * file a crash left behind (`.launch-fence-<pid>.json.tmp-<pid>-<uuid>`) was+ * then neither swept nor skipped, so every worktree recycle on that machine+ * read as "still referenced" for good. Returns null for anything else, which+ * the callers treat as a session directory (or as something suspicious).+ */+export function piSubagentLaunchFenceArtifact(entry: string): PiSubagentLaunchFenceArtifact | null {+ if (isPublishedLaunchFenceName(entry)) return { kind: 'published' };+ const staging = ATOMIC_STAGING_NAME_RE.exec(entry);+ if (!staging || !isPublishedLaunchFenceName(staging[1]!)) return null;+ return { kind: 'staging', writerPid: Number(staging[2]) };+}interface PiSubagentLaunchFence {version: 1;@@ -664,14 +709,13 @@ export async function clearStalePiSubagentLaunchFence(agentHome: string): Promis} catch {return;}- const fences = entries.filter((entry) => (- entry === PI_SUBAGENT_LAUNCH_FENCE_FILENAME- || (entry.startsWith(PI_SUBAGENT_LAUNCH_FENCE_PREFIX)- && entry.endsWith(PI_SUBAGENT_LAUNCH_FENCE_SUFFIX))- ));+ const fences = entries.flatMap((entry) => {+ const artifact = piSubagentLaunchFenceArtifact(entry);+ return artifact ? [{ entry, artifact }] : [];+ });// One chain per path, so the scan still runs the files concurrently: two// different fences never share a chain and cannot block each other.- await Promise.all(fences.map(async (entry) => {+ await Promise.all(fences.map(async ({ entry, artifact }) => {const file = path.join(runsRoot, entry);await queueLaunchFenceDiskWork(file, async () => {let content: string;@@ -685,10 +729,31 @@ export async function clearStalePiSubagentLaunchFence(agentHome: string): Promis// The next sweep tries again.return;}- let fence: PiSubagentLaunchFence | null;+ let fence: PiSubagentLaunchFence | null = null;+ let malformed = false;try {fence = parseLaunchFence(JSON.parse(content));} catch {+ malformed = true;+ }+ if (artifact.kind === 'staging') {+ // Only ever meaningful to the host that is about to rename it into place.+ // Between its write and that rename the file can legitimately be+ // incomplete, so an unparseable payload proves nothing on its own — the+ // writer named in the file name has to be gone before it counts as+ // debris. Once it is, the sweep is the only thing that will ever remove+ // it: no release path knows the name, and the Host's reference scan+ // treats it as an unrelated plain file rather than a session.+ //+ // A recycled writer pid keeps a half-written file alive for that+ // process's lifetime; the next sweep after it exits gets it. A payload+ // that does parse is judged like a published fence, so a recycled pid+ // with a different start time is not mistaken for the writer.+ if (fence ? launchFenceOwnerAlive(fence) : isProcessAlive(artifact.writerPid) !== false) return;+ await removeLaunchFenceFile(file);+ return;+ }+ if (malformed) {// Readable and malformed. No atomic writer publishes that, so it names no// owner — and it is the one case that must still be removed: the launch// check now treats an unparseable file as a fence, so leaving it would@@ -700,19 +765,30 @@ export async function clearStalePiSubagentLaunchFence(agentHome: string): Promis// unless the live process at that pid started at a different time than the// fence records, which means the pid was recycled and this file is a// previous life's leftover. An unreadable start time stays conservative.- if (fence && isProcessAlive(fence.hostPid) !== false) {- if (fence.hostStartTimeSec === undefined) return;- const startTimeSec = fence.hostPid === process.pid- ? ownProcessStartTimeSec()- : probeProcessStartTimeSec(fence.hostPid, Date.now());- if (startTimeSec === null) return;- if (Math.abs(startTimeSec - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC) return;- }+ if (fence && launchFenceOwnerAlive(fence)) return;await removeLaunchFenceFile(file);});}));}+/**+ * Is the incarnation that raised `fence` still running?+ *+ * Conservative in one direction only: a pid that is alive but whose start time+ * cannot be read, or a fence written before start times were recorded, counts+ * as held. A live pid with a *different* start time is a recycled pid, and the+ * fence is a previous life's leftover.+ */+function launchFenceOwnerAlive(fence: PiSubagentLaunchFence): boolean {+ if (isProcessAlive(fence.hostPid) === false) return false;+ if (fence.hostStartTimeSec === undefined) return true;+ const startTimeSec = fence.hostPid === process.pid+ ? ownProcessStartTimeSec()+ : probeProcessStartTimeSec(fence.hostPid, Date.now());+ if (startTimeSec === null) return true;+ return Math.abs(startTimeSec - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;+}+interface TranscriptCursor {version: 1;runId: string;