Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-agent): 按最新提供方设置释放已闲置任务
MagicLizicc541af92908
diff --git a/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts b/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.tsindex bdf317b118..be4c4e09d9 100644--- a/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts@@ -157,6 +157,32 @@ describe('remote connection pool', () => {expect(a.released).toBe(1);});+ // provider-sharing.md §3:提供方关闭或延长闲置收回后,不能按打开时缓存的旧时长继续让出;+ // 读不到当前设置也不能用旧值关进程。原来的用例只在打开前手动更新 caps,未覆盖定时 trim。+ it.each([0, 120, undefined, 'offline'] as const)('refreshes the provider policy before releasing when it becomes %s', async policy => {+ let offline = policy === 'offline';+ let minutes: number | undefined = typeof policy === 'number' ? policy : undefined;+ const pool = new RemoteConnectionPool({+ now: () => now, checkMs: 3_600_000,+ readCaps: async () => {+ if (offline) throw new Error('DEVICE_OFFLINE');+ return { maxRuns: 5, idleReclaimMinutes: minutes };+ },+ });+ pool.noteMaxRuns(5);+ pool.noteIdleReclaimMinutes(1);+ const members = Array.from({ length: 4 }, (_, index) => member(`m${index}`, now - 10 * MINUTE));+ const remove = members.map(item => pool.add(item));+ try {+ await pool.trim();+ expect(members.every(item => item.released === 0)).toBe(true);+ offline = false;+ minutes = 1;+ await pool.trim();+ expect(members.reduce((sum, item) => sum + item.released, 0)).toBe(1);+ } finally { remove.forEach(unregister => unregister()); }+ });+it('after a capacity rejection releases one eligible connection, none when nothing qualifies', async () => {const { pool } = poolWith(10, now);pool.noteMaxRuns(16);diff --git a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.tsindex bf1b4ea369..41f70c32c7 100644--- a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts@@ -216,7 +216,7 @@ describe('idle reclaim by the provider', () => {return handle;}- async function openBusy(minutes: number, busy: Busy) {+ async function openBusy(minutes: number, busy: Busy, kind: 'claude-code' | 'codex' | 'pi' = 'claude-code') {vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });let handle!: ReturnType<typeof busyHandle>;const started = whenStarted();@@ -227,7 +227,7 @@ describe('idle reclaim by the provider', () => {isControllerAuthorized: () => true, captureOwner: () => 'owner', isOwnerCurrent: () => true, runsRoot,now: () => clock,});- await host.handle('controller-1', { op: 'open', runId: RUN_1, agentKind: 'claude-code', payload: { json: openPayload('task-1') } });+ await host.handle('controller-1', { op: 'open', runId: RUN_1, agentKind: kind, payload: { json: openPayload('task-1') } });await started.promise;await settle();let cursor = 0;@@ -295,6 +295,21 @@ describe('idle reclaim by the provider', () => {} finally { host.dispose(); }});+ // Codex / Pi 在 commitRewindFiles 返回前已经完成原生回退,不需要等待下一次发送保存。+ // 只有 Claude Code 的 pendingRewindTo 要保留进程;否则这两个引擎回退后再也不会被闲置收回。+ it.each(['codex', 'pi'] as const)('reclaims an idle %s run after its rewind has already completed', async kind => {+ const { host, pass } = await openBusy(1, { turn: false, background: 0, wake: 0 }, kind);+ try {+ await host.handle('controller-1', { op: 'call', runId: RUN_1, callId: RUN_2, method: 'commitRewindFiles', payload: { json: ['user-1', 'assistant-1'] } });+ await settle();+ await pass(50_000);+ expect(host.runCount()).toBe(1);+ await pass(20_000);+ await pass(0);+ expect(host.runCount()).toBe(0);+ } finally { host.dispose(); }+ });+it('never reclaims with 0 minutes and declares the setting in caps', async () => {const { host, pass } = await openBusy(0, { turn: false, background: 0, wake: 0 });try {diff --git a/apps/desktop/src/main/remote-agent/controller/connectionPool.ts b/apps/desktop/src/main/remote-agent/controller/connectionPool.tsindex 3f41b61a98..9dc8770cfe 100644--- a/apps/desktop/src/main/remote-agent/controller/connectionPool.ts+++ b/apps/desktop/src/main/remote-agent/controller/connectionPool.ts@@ -56,6 +56,8 @@ export interface RemoteConnectionPoolOptions {* 闲置收回时长(noteIdleReclaimMinutes)。*/idleMinutes?(): number;+ /** 主动让出前读取提供方的当前设置;读取失败时不沿用缓存关闭进程。 */+ readCaps?(): Promise<{ maxRuns: number; idleReclaimMinutes?: number }>;now?: () => number;checkMs?: number;closeRetryMs?: number;@@ -191,6 +193,19 @@ export class RemoteConnectionPool {return next;}+ private async refreshPolicy(): Promise<boolean> {+ if (!this.options.readCaps) return true;+ try {+ const caps = await this.options.readCaps();+ this.noteMaxRuns(caps.maxRuns);+ this.noteIdleReclaimMinutes(caps.idleReclaimMinutes);+ return true;+ } catch (error) {+ this.options.log?.warn('remote agent pool: current reclaim policy unavailable; skipping release', { error: String(error) });+ return false;+ }+ }+/** 按顺序试着让一个(候选在等待期间可能变忙,release 会放弃)。 */private async releaseNext(except?: PooledRemoteConnection): Promise<boolean> {for (const member of this.eligible(except)) {@@ -211,6 +226,9 @@ export class RemoteConnectionPool {for (;;) {const watermark = this.watermark();if (watermark === null || this.occupied() < watermark) return;+ if (!await this.refreshPolicy()) return;+ const currentWatermark = this.watermark();+ if (currentWatermark === null || this.occupied() < currentWatermark) return;if (!await this.releaseNext()) return;this.options.log?.info('remote agent pool: released an idle connection', { occupied: this.occupied(), maxRuns: this.maxRuns });}@@ -226,6 +244,7 @@ export class RemoteConnectionPool {// 自己让出时没关掉的旧 run:先关掉它再看名额。await this.closeHeld(self);if (this.maxRuns === null || this.occupied(self) < this.maxRuns) return;+ if (!await this.refreshPolicy() || this.maxRuns === null || this.occupied(self) < this.maxRuns) return;if (await this.releaseNext(self)) {this.options.log?.info('remote agent pool: made room before opening', { maxRuns: this.maxRuns });}@@ -236,7 +255,7 @@ export class RemoteConnectionPool {/** 对方以名额已满拒绝了打开:先试着关掉自己没关掉的旧 run,否则让一个;腾出了就由调用方重试一次。 */releaseForRetry(self: PooledRemoteConnection): Promise<boolean> {return this.serial(async () => {- const released = await this.closeHeld(self) || await this.releaseNext(self);+ const released = await this.closeHeld(self) || (await this.refreshPolicy() && await this.releaseNext(self));this.options.log?.info('remote agent pool: open rejected for capacity', { released, maxRuns: this.maxRuns });return released;});diff --git a/apps/desktop/src/main/remote-agent/controller/service.ts b/apps/desktop/src/main/remote-agent/controller/service.tsindex ad6f25c18f..29ca105440 100644--- a/apps/desktop/src/main/remote-agent/controller/service.ts+++ b/apps/desktop/src/main/remote-agent/controller/service.ts@@ -37,7 +37,7 @@ import {collectProjectInstructionFiles,} from './projectFiles';import type { LocalMcpTarget } from './router';-import { RemoteAgentPoller, remoteAgentInvoker } from './runClient';+import { RemoteAgentPoller, RemoteAgentRunClient, remoteAgentInvoker } from './runClient';import { startRemoteAgentSession, type PreparedRemoteMcp } from './startRemote';export interface DeviceAgentServiceDeps {@@ -155,12 +155,13 @@ export function createDeviceAgentStarter(deps: DeviceAgentServiceDeps) {const log = deps.logger.child('remote-agent');const pollerFor = (deviceId: string): RemoteAgentPoller => remoteAgentPollerFor(deviceId, deps.remoteInvoke, log);// 每台运行 Agent 的电脑一个连接池:对方按这台设备计名额,池里算的是本机在那台上开着的连接;- // 闲置多久可以让出按那台主人设置的闲置收回时长(每次打开前从 caps 读)。+ // 闲置多久可以让出按那台主人设置的闲置收回时长(打开前与主动让出前从 caps 读)。const pools = new Map<string, RemoteConnectionPool>();const poolFor = (deviceId: string): RemoteConnectionPool => {let pool = pools.get(deviceId);if (!pool) {- pool = new RemoteConnectionPool({ log });+ const invoke = remoteAgentInvoker(deviceId, deps.remoteInvoke);+ pool = new RemoteConnectionPool({ log, readCaps: () => RemoteAgentRunClient.caps(invoke) });pools.set(deviceId, pool);}return pool;diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex a28357a58e..f3410e6437 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -1866,7 +1866,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {}const value = await relay.client.callWithId(callId, method, callArgs);if (method === 'setModel' && typeof args[0] === 'string') run.authorizedModel = args[0];- if (method === 'commitRewindFiles') run.rewindPending = true;+ if (method === 'commitRewindFiles' && run.kind === 'claude-code') run.rewindPending = true;append(run, { t: 'result', callId, ok: true, ...(value !== undefined ? { value: JSON.parse(JSON.stringify(value)) } : {}) });} catch (error) {append(run, { t: 'result', callId, ok: false, error: relayErrorInfoFrom(error) });@@ -2054,7 +2054,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {}if (nextProviderId && !run.closing) run.providerId = nextProviderId;if (method === 'setModel' && typeof args[0] === 'string' && !run.closing) run.authorizedModel = args[0];- if (method === 'commitRewindFiles') run.rewindPending = true;+ if (method === 'commitRewindFiles' && run.kind === 'claude-code') run.rewindPending = true;append(run, { t: 'result', callId, ok: true, ...(value !== undefined ? { value: JSON.parse(JSON.stringify(value)) } : {}) });} catch (error) {append(run, { t: 'result', callId, ok: false, error: remoteAgentErrorInfo(error) });diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 388f92cdcf..b0784ed4f3 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1453,7 +1453,7 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加「闲置收回(分钟)」(`RemoteAgentLimits.idleMinutes`,0~1440,默认 30,0 = 不收回),对全部控制端统一生效。仍用`maker:remote-agent:v1`,不改 relay、服务器、数据库或协议版本;新增的都是可选字段:- **B 收回**:巡检(每 5 秒)看到任务不忙且闲置满这个时长,就结束它的 Agent 进程。「忙」= 有等 A 回包的反向请求、- 执行中的调用、待生效的回退(`commitRewindFiles` 成功后到下一个 `done`)、还没启动好,或 Agent 状态里有在跑 / 在准备的+ 执行中的调用、Claude Code 待生效的回退(`commitRewindFiles` 成功后到下一个 `done`;Codex / Pi 返回时已完成回退)、还没启动好,或 Agent 状态里有在跑 / 在准备的回合、后台任务、待唤醒续跑(中转任务看组内电脑报来的同一组字段);巡检时忙就把闲置起点移到此刻。活动 = 打开、`call` / `reply` / `push`、写进事件流的非 `state` 行;只被 `poll` 不算(闲着的任务 A 也一直在拉)。- **收尾**:`closed` 行写 `reason: 'ended'` 并带可选 `idleReclaimed: true`。旧 A 不认识这个字段,按 `ended` 静默收起,@@ -1478,7 +1478,8 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加A 上开着的任务即使闲着也占名额。A 对每台 B 一个连接池(`controller/connectionPool.ts`,计数口径与 B 的 `limitDeviceOf`一致:这台设备),**只在名额紧张时**让出「不忙且闲置满 N 分钟」的连接;N 是 B 在 `caps.idleReclaimMinutes` 里声明的闲置收回时长(A 原来的本机设置已删除;B 没声明或为 0 时从不让出,满了直接报错)。闲置满 N 分钟的任务 B 本来也会自己收回,- 连接池只是名额紧张时不必等它那一轮巡检。三条路径都只让有资格的:+ 连接池只是名额紧张时不必等它那一轮巡检。主动让出前重新读取 B 的 caps,读取失败不按缓存值关进程,+ 主人改为 0 或延长时长不必等 A 再打开连接才生效。三条路径都只让有资格的:A 在这台 B 上开着的连接数到了水位线 `ceil(maxRuns×80%)`(只在水位线低于上限、即 maxRuns ≥ 5 时;每次 open 前与每分钟查一次)按最久没活动的顺序让,直到降到水位线以下;open 前已满先同步让一个;open 被拒且是名额类 `REMOTE_AGENT_BUSY`(`[DEVICE_LIMIT]` / `[TOTAL_LIMIT]`,旧 B 是 `too many tasks are running from this computer`;`too much staged data` 不算)