Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 回收闲置的本机 pi 会话运行时
Zhang Yunjin6e334da84874
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 3d8bf7beed..576b1f21cd 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -794,6 +794,7 @@ import {isSessionTurnPendingCompletion,isSessionInTurn,stopOrcaIdleWatcher,+ stopPiIdleReleaseWatcher,setGoalClearObserver,setGoalDeferredResumeCancelObserver,setGoalIdleObserver,@@ -10246,6 +10247,7 @@ onQuit('review-artifact-snapshots', cleanupActiveReviewArtifactSnapshots, 'async// LSP 不占用 Agent 正常保存和退出的时间窗口。onQuit('lsp-pool', shutdownLspServerPool, 'async');onQuit('orca-idle-watcher', () => stopOrcaIdleWatcher(), 'sync');+onQuit('pi-idle-release-watcher', () => stopPiIdleReleaseWatcher(), 'sync');onQuit('im', () => stopImConnection('quit'), 'async');// 轮 27 MEDIUM-3:pi-env 挪到 post-async —— 若与 shutdown-maker 同 async 并发,// bridge 可能在 session close 的 disposeSessionRegistrations(unregisterSessionCtx/diff --git a/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.tsnew file mode 100644index 0000000000..4c2dc719ba--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts@@ -0,0 +1,206 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ createPiIdleReleaseWatcher,+ type PiIdleReleaseCandidate,+ type PiIdleReleaseWatcherDeps,+} from '../piIdleReleaseWatcher';++function createCandidate(overrides: Partial<PiIdleReleaseCandidate> = {}): PiIdleReleaseCandidate {+ return {+ id: 'session-1',+ idleSinceMs: 0,+ ...overrides,+ };+}++function createDeps(overrides: Partial<PiIdleReleaseWatcherDeps> = {}) {+ const session = {+ isTurnRunning: vi.fn<() => boolean>(() => false),+ listBackgroundTasks: vi.fn<() => readonly unknown[]>(() => []),+ countPendingWakeContinuations: vi.fn<() => number>(() => 0),+ closeIfIdle: vi.fn<() => Promise<boolean>>(async () => true),+ };+ const deps: PiIdleReleaseWatcherDeps = {+ readIdleReleaseMinutes: vi.fn(() => 1),+ listCandidates: vi.fn(async () => [createCandidate()]),+ getSession: vi.fn(() => session),+ withSessionLock: vi.fn(async (_sessionId, task) => task()),+ hasPendingInput: vi.fn(async () => false),+ hasScheduledAutoResume: vi.fn(() => false),+ now: vi.fn(() => 120_000),+ timer: { setInterval, clearInterval },+ log: {+ info: vi.fn(),+ warn: vi.fn(),+ },+ ...overrides,+ };+ return { deps, session, watcher: createPiIdleReleaseWatcher(deps, 25) };+}++afterEach(() => {+ vi.useRealTimers();+});++describe('createPiIdleReleaseWatcher', () => {+ it('does not scan when idle release is disabled', async () => {+ const { deps, watcher } = createDeps({+ readIdleReleaseMinutes: vi.fn(() => 0),+ });++ await watcher.scanNow();++ expect(deps.listCandidates).not.toHaveBeenCalled();+ expect(deps.getSession).not.toHaveBeenCalled();+ });++ it('releases an idle session and reports the idle duration', async () => {+ const { deps, session, watcher } = createDeps();++ await watcher.scanNow();++ expect(deps.listCandidates).toHaveBeenCalledWith(60_000);+ expect(deps.withSessionLock).toHaveBeenCalledWith('session-1', expect.any(Function));+ expect(session.closeIfIdle).toHaveBeenCalledOnce();+ expect(deps.log.info).toHaveBeenCalledWith(+ 'piIdleWatcher: released idle session',+ expect.objectContaining({ sessionId: 'session-1', idleMs: 120_000, idleThresholdMin: 1 }),+ );+ });++ it('keeps a session with a live turn', async () => {+ const { session, watcher } = createDeps();+ session.isTurnRunning.mockReturnValue(true);++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ });++ it('keeps a session with background tasks', async () => {+ const { session, watcher } = createDeps();+ session.listBackgroundTasks.mockReturnValue([{ taskId: 'task-1' }]);++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ });++ it('keeps a session with a pending wake continuation', async () => {+ const { session, watcher } = createDeps();+ session.countPendingWakeContinuations.mockReturnValue(1);++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ });++ it('keeps a session with a scheduled automatic resume', async () => {+ const { session, watcher } = createDeps({+ hasScheduledAutoResume: vi.fn(() => true),+ });++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ });++ it('keeps a session with queued input', async () => {+ const { deps, session, watcher } = createDeps({+ hasPendingInput: vi.fn(async () => true),+ });++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ expect(deps.log.info).not.toHaveBeenCalled();+ });++ it('leaves a session untouched when this process does not own its runtime', async () => {+ const { deps, watcher } = createDeps({+ getSession: vi.fn(() => null),+ });++ await watcher.scanNow();++ expect(deps.withSessionLock).toHaveBeenCalledWith('session-1', expect.any(Function));+ expect(deps.log.info).not.toHaveBeenCalled();+ });++ it('rechecks live state after waiting for the session lock', async () => {+ const { deps, session, watcher } = createDeps();+ deps.withSessionLock = vi.fn(async (_sessionId, task) => {+ session.isTurnRunning.mockReturnValue(true);+ return task();+ });++ await watcher.scanNow();++ expect(session.closeIfIdle).not.toHaveBeenCalled();+ expect(deps.log.info).not.toHaveBeenCalled();+ });++ it('does not report a release when the session refused to close', async () => {+ const { deps, session, watcher } = createDeps();+ session.closeIfIdle.mockResolvedValue(false);++ await watcher.scanNow();++ expect(session.closeIfIdle).toHaveBeenCalledOnce();+ expect(deps.log.info).not.toHaveBeenCalled();+ });++ it('keeps scanning after one candidate fails', async () => {+ const failing = createCandidate({ id: 'session-fail' });+ const { deps, session, watcher } = createDeps({+ listCandidates: vi.fn(async () => [failing, createCandidate()]),+ });+ session.closeIfIdle.mockRejectedValueOnce(new Error('close failed'));++ await watcher.scanNow();++ expect(deps.log.warn).toHaveBeenCalledWith(+ 'piIdleWatcher: release session failed',+ expect.objectContaining({ sessionId: 'session-fail', err: 'close failed' }),+ );+ expect(session.closeIfIdle).toHaveBeenCalledTimes(2);+ expect(deps.log.info).toHaveBeenCalledWith(+ 'piIdleWatcher: released idle session',+ expect.objectContaining({ sessionId: 'session-1' }),+ );+ });++ it('runs one scan at a time', async () => {+ let releaseScan!: () => void;+ const gate = new Promise<void>((resolve) => {+ releaseScan = resolve;+ });+ const listCandidates = vi.fn(async () => {+ await gate;+ return [];+ });+ const { watcher } = createDeps({ listCandidates });++ const first = watcher.scanNow();+ const second = watcher.scanNow();+ releaseScan();+ await Promise.all([first, second]);++ expect(listCandidates).toHaveBeenCalledOnce();+ });++ it('uses the injected interval and stops future scans', async () => {+ vi.useFakeTimers();+ const listCandidates = vi.fn(async () => []);+ const { watcher } = createDeps({ listCandidates });++ watcher.start();+ await vi.advanceTimersByTimeAsync(25);+ expect(listCandidates).toHaveBeenCalledOnce();++ watcher.stop();+ await vi.advanceTimersByTimeAsync(50);+ expect(listCandidates).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts b/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.tsnew file mode 100644index 0000000000..e624e4c99b--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts@@ -0,0 +1,149 @@+/**+ * piIdleReleaseWatcher —— 桌面普通 pi 会话的空闲运行时回收。+ *+ * 背景(2026-10 实测 + upstream #5830):`pi --mode rpc` 子进程每个约 150~300MB,+ * 普通会话此前没有任何 Idle TTL/LRU —— 只有退出应用、切换 Agent 或 Orca 工人+ * 走各自路径才会回收,长时间使用后进程数与内存持续累积、整机变卡、重启才恢复。+ * 这里为「本机、桌面来源、非 Orca/bot」的 pi 会话补一个与+ * `orcaIdleReleaseWatcher` 同构的 watcher。+ *+ * 候选由 SQL 给出(闲置起点取 max(updated_at, last_turn_ended_at, user_send_at)),+ * 但真正的闸门在**拿到发送锁之后**重读活会话:回合在跑、有排队输入、有后台任务+ * (pi 子代理)、有 silent-stop 续跑认领、有已排定的自动续跑时一律跳过。+ * 最后由 `closeIfIdle()` 做一次同步的「检查 + 关闭预约」,与并发发送互斥;+ * 关闭失败或竞态只会让本轮跳过,下轮重试,不需要额外的持久标记。+ *+ * 释放后下一次发送走既有 lazy create-session 透明重建(resume 自 sdk_session_id),+ * 与冷启动语义一致,见 docs/dev-rules/pi-harness.md。+ */++/** 普通 pi 会话进入空闲回收前的闲置时长(分钟)。与远端 pi daemon 的 30min 口径一致。 */+export const DEFAULT_PI_IDLE_RELEASE_MINUTES = 30;++/** 扫描周期:比 TTL 小一个量级即可,单个扫描只查一次本地 sessions 表(数百行)。 */+export const DEFAULT_PI_IDLE_SCAN_INTERVAL_MS = 5 * 60_000;++/** SQL 侧选出的候选:只带回收决策需要的字段。 */+export interface PiIdleReleaseCandidate {+ /** 业务会话 id(Session.id)。 */+ id: string;+ /** 闲置起点:max(updated_at, last_turn_ended_at, user_send_at),用于日志归因。 */+ idleSinceMs: number;+}++/** 运行时会话面:只暴露回收决策需要读的状态。 */+export interface PiIdleReleaseSession {+ isTurnRunning(): boolean;+ listBackgroundTasks(): readonly unknown[];+ countPendingWakeContinuations(): number;+ closeIfIdle(): Promise<boolean>;+}++/** Timer handle abstraction keeps the watcher deterministic under fake timers. */+export interface PiIdleReleaseTimer {+ setInterval(callback: () => void, intervalMs: number): ReturnType<typeof setInterval>;+ clearInterval(handle: ReturnType<typeof setInterval>): void;+}++export interface PiIdleReleaseWatcherDeps {+ /** `<= 0` 关闭回收(与 Orca 的 workerIdleReleaseMinutes 同语义)。 */+ readIdleReleaseMinutes(): number;+ listCandidates(idleBeforeMs: number): Promise<readonly PiIdleReleaseCandidate[]>;+ getSession(sessionId: string): PiIdleReleaseSession | null;+ withSessionLock<T>(sessionId: string, task: () => Promise<T>): Promise<T>;+ hasPendingInput(sessionId: string): Promise<boolean>;+ /** 已排定/在途的自动续跑(stall / idle / reconnect 等)未收口时不得释放。 */+ hasScheduledAutoResume(sessionId: string): boolean;+ now(): number;+ timer: PiIdleReleaseTimer;+ log: {+ info(message: string, details?: Record<string, unknown>): void;+ warn(message: string, details?: Record<string, unknown>): void;+ };+}++export interface PiIdleReleaseWatcher {+ start(): void;+ stop(): void;+ scanNow(): Promise<void>;+}++/**+ * 扫描是单飞的:一次扫描串行处理候选,单个候选失败只记 warn 并继续,+ * 好让下轮重试而不阻塞其它会话的回收。+ */+export function createPiIdleReleaseWatcher(+ deps: PiIdleReleaseWatcherDeps,+ scanIntervalMs = DEFAULT_PI_IDLE_SCAN_INTERVAL_MS,+): PiIdleReleaseWatcher {+ let timerHandle: ReturnType<typeof setInterval> | null = null;+ let scanInFlight = false;++ const scanNow = async (): Promise<void> => {+ if (scanInFlight) return;+ scanInFlight = true;+ try {+ const idleReleaseMinutes = deps.readIdleReleaseMinutes();+ if (idleReleaseMinutes <= 0) return;++ const idleBeforeMs = deps.now() - idleReleaseMinutes * 60_000;+ const candidates = await deps.listCandidates(idleBeforeMs);+ for (const candidate of candidates) {+ try {+ await deps.withSessionLock(candidate.id, async () => {+ // Maker 会话是进程内的:查不到说明本进程不持有该运行时+ // (共享 userData 的另一个实例在跑),只有本进程的 owner 才能释放。+ const session = deps.getSession(candidate.id);+ if (!session) return;++ // 发送与回收共用这把锁,所以拿到锁之后再读活状态:+ // 刚被接受的 turn / 排队输入不会被这次扫描关掉。+ if (session.isTurnRunning()) return;+ if (session.listBackgroundTasks().length > 0) return;+ if (session.countPendingWakeContinuations() > 0) return;+ if (deps.hasScheduledAutoResume(candidate.id)) return;+ if (await deps.hasPendingInput(candidate.id)) 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),+ idleThresholdMin: idleReleaseMinutes,+ });+ });+ } catch (err) {+ deps.log.warn('piIdleWatcher: release session failed', {+ sessionId: candidate.id,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ }+ } catch (err) {+ deps.log.warn('piIdleWatcher: scan failed', {+ err: err instanceof Error ? err.message : String(err),+ });+ } finally {+ scanInFlight = false;+ }+ };++ return {+ start() {+ if (timerHandle !== null) deps.timer.clearInterval(timerHandle);+ timerHandle = deps.timer.setInterval(() => {+ void scanNow();+ }, scanIntervalMs);+ deps.log.info('piIdleWatcher started');+ },+ stop() {+ if (timerHandle === null) return;+ deps.timer.clearInterval(timerHandle);+ timerHandle = null;+ deps.log.info('piIdleWatcher stopped');+ },+ scanNow,+ };+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4649040908..81a7213463 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -736,6 +736,11 @@ import {type OrcaIdleReleaseWatcher,} from './orcaIdleReleaseWatcher.js';import { createOrcaWorkerResumeScheduler } from './orcaWorkerResumeScheduler.js';+import {+ createPiIdleReleaseWatcher,+ DEFAULT_PI_IDLE_RELEASE_MINUTES,+ type PiIdleReleaseWatcher,+} from './piIdleReleaseWatcher.js';import {ackSessionTurnEndedDurable,hasAssistantProgressAfterMessage,@@ -3109,6 +3114,9 @@ export async function dispatchInterAgentMessage(/** 模块级 idle watcher;停止后不再持有可能已经失效的 maker 引用。 */let idleReleaseWatcher: OrcaIdleReleaseWatcher | null = null;+/** 模块级 pi 普通会话 idle watcher;与 Orca watcher 同一生命周期。 */+let piIdleReleaseWatcher: PiIdleReleaseWatcher | null = null;+/*** 取 Orca collab service, ready 前返 null。registerMakerIpc 执行完成后 holder* 被赋值, 之前调本函数会拿到 null —— 调用方 (典型: mcp-providers.ts 的 control@@ -3152,6 +3160,12 @@ export function stopOrcaIdleWatcher(): void {idleReleaseWatcher = null;}+/** 停止 pi 普通会话 idle watcher (app quit 时调, maker 可能已 shutdown)。 */+export function stopPiIdleReleaseWatcher(): void {+ piIdleReleaseWatcher?.stop();+ piIdleReleaseWatcher = null;+}+function requireAgentKind(value: unknown): AgentKind {if (value === 'claude-code' || value === 'codex' || value === 'pi') return value;throwIpcError('INVALID_PARAMS', 'agentKind required');@@ -15862,6 +15876,52 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});idleReleaseWatcher.start();+ // ─── pi 普通会话 idle watcher ────────────────────────────────────────────+ // 只回收本机桌面来源的普通 pi 会话:Orca 角色/远程/插件隐藏任务/bot 与 IM+ // 来源都有各自的生命周期。归档会话也纳入(归档不关运行时),其余安全闸门见+ // piIdleReleaseWatcher;释放后下一次发送走 lazy create-session 透明重建。+ const PI_IDLE_RELEASE_SESSION_STATUSES = ['active', 'archived'] as const;+ 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 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}`,+ ),+ );+ return rows.map((row) => ({ id: row.id, idleSinceMs: Number(row.idleSinceMs) }));+ },+ getSession: (sessionId) => maker.getSession(sessionId) ?? null,+ withSessionLock: withSendToSessionLock,+ hasPendingInput: hasPendingIdleReleaseInput,+ hasScheduledAutoResume: (sessionId) => {+ const coordinator = agentInputCoordinatorHolder;+ if (!coordinator) return false;+ return (+ coordinator.isAutoResumePending(sessionId) ||+ coordinator.getAutoResumeAttemptToken(sessionId) !== null ||+ coordinator.hasQueuedAutoResume(sessionId)+ );+ },+ now: Date.now,+ timer: { setInterval, clearInterval },+ log,+ });+ piIdleReleaseWatcher.start();+type InternalRuntimeSelectionOptions = {source: 'user' | SessionRuntimeMutationSource;runtimeSource?: 'agent';diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 210f940e20..0d41afe945 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -432,6 +432,19 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见与 CC/Codex 对齐);版本差 + daemon 活着时 defer 并显示 UpgradeBanner, 用户确认后才 kill + 重装(daemon 已死则静默升级磁盘 bundle)。+### 本机普通会话空闲回收(2026-10)++- **动机**:`pi --mode rpc` 每个约 150~300MB,普通会话此前只有退出应用/切换 Agent+ 才回收(Orca 工人另有 `workerIdleReleaseMinutes`,默认关闭),长时间使用进程与内存+ 持续累积(upstream #5830)。+- **实现**:`apps/desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts`(30min TTL /+ 5min 扫描)。候选只取本机桌面来源、无 Orca 角色、非远程、未隐藏的 pi 会话+ (归档也纳入——归档不会关运行时);释放前在发送锁内复查回合/后台任务/silent-stop+ 续跑/自动续跑/排队输入,最后由 `closeIfIdle()` 做同步的检查+关闭预约。+- **重建语义**:释放不影响会话数据;下一次发送走既有 lazy create-session,resume 自+ `sdk_session_id`,与冷启动一致。闲置后首次发送因此可能多等一次冷启动。+- **回归**:`apps/desktop/src/main/maker-ipc/__tests__/piIdleReleaseWatcher.test.ts`。+## 6. 上线门禁- [x] **平台分发**:pin 已升级到 Pi `v0.84.3`,darwin arm64/x64、linux arm64/x64、