Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 收紧 pi 空闲回收的两处竞态
Zhang Yunjin756c52df6bbd
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.tsindex 4c2dc719ba..08164fb14c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts@@ -27,6 +27,7 @@ function createDeps(overrides: Partial<PiIdleReleaseWatcherDeps> = {}) {getSession: vi.fn(() => session),withSessionLock: vi.fn(async (_sessionId, task) => task()),hasPendingInput: vi.fn(async () => false),+ readIdleSinceMs: vi.fn(async () => 0),hasScheduledAutoResume: vi.fn(() => false),now: vi.fn(() => 120_000),timer: { setInterval, clearInterval },@@ -117,6 +118,28 @@ describe('createPiIdleReleaseWatcher', () => {expect(deps.log.info).not.toHaveBeenCalled();});+ it('rechecks the idle clock after waiting for the session lock', async () => {+ // now=120_000、TTL=1min:候选快照已过期,锁内复核发现 30s 前刚有活动。+ const { deps, session, watcher } = createDeps({+ readIdleSinceMs: vi.fn(async () => 90_000),+ });++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ expect(deps.log.info).not.toHaveBeenCalled();+ });++ it('skips a session that no longer matches the candidate filter', async () => {+ const { session, watcher } = createDeps({+ readIdleSinceMs: vi.fn(async () => null),+ });++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ });+it('leaves a session untouched when this process does not own its runtime', async () => {const { deps, watcher } = createDeps({getSession: vi.fn(() => null),diff --git a/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts b/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.tsindex e624e4c99b..dddd5cd04a 100644--- a/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts+++ b/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts@@ -9,9 +9,10 @@** 候选由 SQL 给出(闲置起点取 max(updated_at, last_turn_ended_at, user_send_at)),* 但真正的闸门在**拿到发送锁之后**重读活会话:回合在跑、有排队输入、有后台任务- * (pi 子代理)、有 silent-stop 续跑认领、有已排定的自动续跑时一律跳过。- * 最后由 `closeIfIdle()` 做一次同步的「检查 + 关闭预约」,与并发发送互斥;- * 关闭失败或竞态只会让本轮跳过,下轮重试,不需要额外的持久标记。+ * (pi 子代理)、有 silent-stop 续跑认领、有已排定的自动续跑时一律跳过;锁内再用+ * 最新活动时间复核一次闲置阈值(扫描快照可能已经过期)。最后由 `closeIfIdle()`+ * 做一次同步的「检查 + 关闭预约」——它同时覆盖宿主发起的独占 RPC 操作+ * (手动压缩 / rewind / 切模)与并发发送;关闭失败或竞态只会让本轮跳过,下轮重试。** 释放后下一次发送走既有 lazy create-session 透明重建(resume 自 sdk_session_id),* 与冷启动语义一致,见 docs/dev-rules/pi-harness.md。@@ -52,6 +53,8 @@ export interface PiIdleReleaseWatcherDeps {getSession(sessionId: string): PiIdleReleaseSession | null;withSessionLock<T>(sessionId: string, task: () => Promise<T>): Promise<T>;hasPendingInput(sessionId: string): Promise<boolean>;+ /** 锁内复核用:重读该会话的最新活动时间;`null` = 已不再符合候选条件。 */+ readIdleSinceMs(sessionId: string): Promise<number | null>;/** 已排定/在途的自动续跑(stall / idle / reconnect 等)未收口时不得释放。 */hasScheduledAutoResume(sessionId: string): boolean;now(): number;@@ -104,13 +107,19 @@ export function createPiIdleReleaseWatcher(if (deps.hasScheduledAutoResume(candidate.id)) return;if (await deps.hasPendingInput(candidate.id)) return;+ // 候选是扫描开始时的快照:等锁期间用户可能已经发过消息、跑完一轮。+ // 用锁内的最新活动时间复核阈值,避免把刚用过的会话提前回收。+ const idleSinceMs = await deps.readIdleSinceMs(candidate.id);+ if (idleSinceMs === null) return;+ if (deps.now() - idleSinceMs < idleReleaseMinutes * 60_000) return;+// 同步复查 + 关闭预约:并发发送要么先赢,要么看到 closePromise 被拒。const released = await session.closeIfIdle();if (!released) return;deps.log.info('piIdleWatcher: released idle session', {sessionId: candidate.id,- idleMs: Math.max(0, deps.now() - candidate.idleSinceMs),+ idleMs: Math.max(0, deps.now() - idleSinceMs),idleThresholdMin: idleReleaseMinutes,});});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 81a7213463..5904b0eefb 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -15881,29 +15881,39 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 来源都有各自的生命周期。归档会话也纳入(归档不关运行时),其余安全闸门见// piIdleReleaseWatcher;释放后下一次发送走 lazy create-session 透明重建。const PI_IDLE_RELEASE_SESSION_STATUSES = ['active', 'archived'] as const;+ const piIdleReleaseIdleSince = () =>+ sql<number>`max(${sessions.updatedAt}, coalesce(${sessions.lastTurnEndedAt}, 0), coalesce(${sessions.userSendAt}, 0))`;+ const piIdleReleaseCandidateWhere = () =>+ and(+ eq(sessions.agentKind, 'pi'),+ inArray(sessions.status, PI_IDLE_RELEASE_SESSION_STATUSES),+ eq(sessions.source, 'desktop'),+ isNull(sessions.orcaRole),+ isNull(sessions.hiddenAt),+ isNull(sessions.remoteHostId),+ isNull(sessions.agentDeviceId),+ );piIdleReleaseWatcher?.stop();piIdleReleaseWatcher = createPiIdleReleaseWatcher({readIdleReleaseMinutes: () => DEFAULT_PI_IDLE_RELEASE_MINUTES,listCandidates: async (idleBeforeMs) => {- const idleSince = sql<number>`max(${sessions.updatedAt}, coalesce(${sessions.lastTurnEndedAt}, 0), coalesce(${sessions.userSendAt}, 0))`;+ const idleSince = piIdleReleaseIdleSince();const rows = await getDbClient().drizzle.select({ id: sessions.id, idleSinceMs: idleSince }).from(sessions)- .where(- and(- eq(sessions.agentKind, 'pi'),- inArray(sessions.status, PI_IDLE_RELEASE_SESSION_STATUSES),- eq(sessions.source, 'desktop'),- isNull(sessions.orcaRole),- isNull(sessions.hiddenAt),- isNull(sessions.remoteHostId),- isNull(sessions.agentDeviceId),- sql`${idleSince} < ${idleBeforeMs}`,- ),- );+ .where(and(piIdleReleaseCandidateWhere(), sql`${idleSince} < ${idleBeforeMs}`));return rows.map((row) => ({ id: row.id, idleSinceMs: Number(row.idleSinceMs) }));},+ readIdleSinceMs: async (sessionId) => {+ const [row] = await getDbClient()+ .drizzle+ .select({ idleSinceMs: piIdleReleaseIdleSince() })+ .from(sessions)+ .where(and(eq(sessions.id, sessionId), piIdleReleaseCandidateWhere()))+ .limit(1);+ return row ? Number(row.idleSinceMs) : null;+ },getSession: (sessionId) => maker.getSession(sessionId) ?? null,withSessionLock: withSendToSessionLock,hasPendingInput: hasPendingIdleReleaseInput,diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 0d41afe945..0baa183a0b 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -440,7 +440,10 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见- **实现**:`apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts`(30min TTL /5min 扫描)。候选只取本机桌面来源、无 Orca 角色、非远程、未隐藏的 pi 会话(归档也纳入——归档不会关运行时);释放前在发送锁内复查回合/后台任务/silent-stop- 续跑/自动续跑/排队输入,最后由 `closeIfIdle()` 做同步的检查+关闭预约。+ 续跑/自动续跑/排队输入,并重读最新活动时间复核阈值;最后由+ `Session.closeIfIdle()` 做同步的检查+关闭预约——它同时拒绝关闭宿主独占 RPC 操作+ (手动压缩 / rewind / 切模)在途的会话(pi 侧由 `runExclusivePiRpc` 计数,+ 见 `hasPendingHostOperation`)。- **重建语义**:释放不影响会话数据;下一次发送走既有 lazy create-session,resume 自`sdk_session_id`,与冷启动一致。闲置后首次发送因此可能多等一次冷启动。- **回归**:`apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts`。diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 28b0be7cbb..477250f02e 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -2472,6 +2472,13 @@ export interface AgentSessionHandle {*/countPendingWakeContinuations?(): number;+ /**+ * 宿主发起的独占 RPC 操作(手动压缩 / rewind fork / 切模等)是否在途。+ * 这类操作不预约 turn、也不置 isStreaming;运行时回收必须能看见它们,+ * 不能把进程关在操作中间。不支持的 agent 留空(Session 层回退 false)。+ */+ hasPendingHostOperation?(): boolean;+/*** Resolve the provider claim attached atomically to a specific `done` event.* Returns null when that event has no matching continuation boundary.diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 4021ffee9d..226a2a707d 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -5124,10 +5124,17 @@ export class PiAgent extends BaseAgent {const waitForSessionRpcIdle = async (): Promise<void> => {await sessionRpcChain.catch(() => undefined);};+ /**+ * 宿主发起的独占 RPC 操作(手动压缩 / rewind / 切模等)不预约 turn、也不置+ * `ctx.isStreaming`;用计数器把它们暴露给 `hasPendingHostOperation()`,+ * 空闲回收据此拒绝关闭正在执行这类操作的会话。+ */+ let hostOperationsInFlight = 0;const runExclusivePiRpc = <T>(fn: () => Promise<T>): Promise<T> => {+ hostOperationsInFlight += 1;const run = sessionRpcChain.then(fn);sessionRpcChain = run.then(() => undefined, () => undefined);- return run;+ return run.finally(() => { hostOperationsInFlight -= 1; });};const requestPiCompact = async (instructions?: string): Promise<ManualCompactResult> => {const command: Record<string, unknown> = { type: 'compact' };@@ -8041,6 +8048,10 @@ export class PiAgent extends BaseAgent {}));},+ hasPendingHostOperation() {+ return hostOperationsInFlight > 0;+ },+async requestGracefulStop(): Promise<void> {if (closed || piProcessExited || rpcDisconnected) throw new Error('No active Pi turn to stop');const hostAbortToken = markPiHostAbortRequested(ctx);diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.tsindex 88ef93df5b..fb09ef114e 100644--- a/packages/maker-core/src/session.close.test.ts+++ b/packages/maker-core/src/session.close.test.ts@@ -198,6 +198,19 @@ describe('Session close lifecycle', () => {expect(seen.at(-1)?.data).toMatchObject({ result: 'delivered' });});+ it('keeps the executor open while a host-initiated RPC operation is in flight', async () => {+ const { session, handle } = liveTurn();+ let hostOperationInFlight = true;+ handle.hasPendingHostOperation = () => hostOperationInFlight;++ await expect(session.closeIfIdle()).resolves.toBe(false);+ expect(handle.close).not.toHaveBeenCalled();++ hostOperationInFlight = false;+ await expect(session.closeIfIdle()).resolves.toBe(true);+ expect(handle.close).toHaveBeenCalledOnce();+ });+it('rejects a non-Host send while a retiring silent-stop claim is live', async () => {const { session, handle, queue, seen, idle } = liveTurn();await session.send('work');diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 92b53d40e8..400e9f59ae 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -1437,6 +1437,15 @@ export class Session {return this.handle.listBackgroundTasks?.() ?? [];}+ /**+ * 宿主发起的独占 RPC 操作(手动压缩 / rewind / 切模等)在途。这类操作不预约+ * turn,关闭会把它们拦腰截断;空闲回收据此拒绝关闭。会话已关闭 → false。+ */+ hasPendingHostOperation(): boolean {+ if (this.status === 'closed' || this.status === 'error') return false;+ return this.handle.hasPendingHostOperation?.() ?? false;+ }+/*** 「任务已终态、wake turn 尚未启动或仍在跑」的 continuation claim 数。* 会话已关闭 / agent 不支持 → 0(此时不会再有 wake turn,0 即事实)。@@ -1569,7 +1578,8 @@ export class Session {*/closeIfIdle(): Promise<boolean> {if (this.status !== 'active' || this.closePromise || this.isTurnRunning() || this.hasUnsettledTurn()- || this.retirementContinuationGeneration === this.turnGeneration) {+ || this.retirementContinuationGeneration === this.turnGeneration+ || this.hasPendingHostOperation()) {return Promise.resolve(false);}return this.close().then(() => true);