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): 随进程回包及时保护本机后台工作
MagicLizi3b769976a3b5
diff --git a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.tsindex a3cc4a20e7..a6423382fa 100644--- a/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/groupRelay.test.ts@@ -20,7 +20,7 @@ import { decideProviderGroupFailure } from '../../provider-group/failurePolicy';import { RemoteAgentPoller } from '../controller/poller';import { RemoteAgentRunClient } from '../controller/runClient';-import { relayKeyFor, reshareKeyFor, type RelayRunFailure } from '../host/groupRelay';+import { relayConnId, relayKeyFor, reshareKeyFor, type RelayRunFailure } from '../host/groupRelay';import { createGuestProviderRouteBinder } from '../host/providerAccess';import { guestProviderRouteForToken } from '../../maker-host/guest-provider-route-store';import {@@ -312,6 +312,32 @@ function switchTokenIn(stream: Awaited<ReturnType<typeof openAsGuest>>['stream']}describe('provider group relay for shared users', () => {+ // Unit regression for provider-sharing.md §3: first local work must reach the member with its push,+ // before either poll batch can report hold. Existing relay cases did not carry this busy-state field.+ // Real guest -> owner Host.handle -> member RunClient.push with JSON serialization on both hops.+ it('forwards the first local hold with the process startup reply to the group member', async () => {+ let forwarded: Record<string, unknown> | undefined;+ const env = setup({ intercept: async (_device, request, forward) => {+ if (request.op === 'push') forwarded = request;+ return forward();+ } });+ const { client } = await openAsGuest(env, GUEST_A, openPayload(SESSION));+ try {+ await env.owner.handle(GUEST_A, {+ op: 'push', runId: client.runId, seq: 1, hold: true,+ frames: [{ connId: relayConnId(1, 'exec-1'), kind: 'message', data: '{"id":1,"result":{}}' }],+ });+ await vi.waitFor(() => expect(forwarded).toBeDefined());+ expect(forwarded).toMatchObject({+ hold: true,+ frames: [{ connId: 'exec-1', kind: 'message', data: '{"id":1,"result":{}}' }],+ });+ } finally {+ await client.close('close', 'navigation');+ for (const host of [env.owner, ...Object.values(env.members)]) { await host.abortAll(); host.dispose(); }+ }+ });+// Review 4328897446, unit: the old three-host harness never exercised the// original member's model restrictions at the executing computer. A allows// only opus, while the executor offers opus and sonnet; revoke opus mid-run.diff --git a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.tsindex 00375c8fea..4233d76238 100644--- a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts@@ -12,6 +12,8 @@ import path from 'node:path';import type { AgentEvent, AgentSessionHandle } from '@cindy/maker-core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { RemoteAgentPoller } from '../controller/poller';+import { RemoteAgentRunClient } from '../controller/runClient';import { createRemoteAgentHost, hostSessionIdFor, type HostedStartInput } from '../host/runHost';/** 协议层 id 是 36 位 UUID 形态。 */@@ -246,7 +248,7 @@ describe('idle reclaim by the provider', () => {await vi.advanceTimersByTimeAsync(5_000);await settle();};- return { host, handle: () => handle, pass, rows };+ return { host, handle: () => handle, pass, rows, cursor: () => cursor };}it.each(['turn', 'background', 'wake', 'hold', 'rewind'] as const)('keeps a run while it is busy (%s) and reclaims it after a full idle period', async (reason) => {@@ -295,6 +297,53 @@ describe('idle reclaim by the provider', () => {} finally { host.dispose(); }});+ // Unit regression: a Codex process starts just after this run's poll batch. Its push must protect the+ // first 70-second gap before another poll can report hold; a previously waiting poll must not clear it.+ // Real RunClient.push -> Host.handle entry points; the existing held-run test begins after the first hold.+ it.each([false, true])('keeps new local work before its first held poll (older poll waiting: %s)', async (waiting) => {+ const { host, handle, pass, rows, cursor } = await openBusy(1, { turn: false, background: 0, wake: 0 }, 'codex');+ let localBusy = true;+ const client = new RemoteAgentRunClient(RUN_1, new RemoteAgentPoller(args => host.handle('controller-1', args[0])), {+ onEvent() {}, onState() {}, onWs() {}, onClosed() {},+ onRequest: async () => ({ type: 'callback', value: undefined }),+ holdsRemote: () => localBusy,+ }, () => RUN_2);+ const abort = new AbortController();+ let previousPoll: Promise<unknown> | undefined;+ try {+ await pass(0);+ if (waiting) {+ let returned = false;+ previousPoll = host.handle('controller-1', {+ op: 'poll', runs: [{ runId: RUN_1, cursor: cursor() }], waitMs: 10_000,+ }, abort.signal).then(result => { returned = true; return result; });+ await settle();+ expect(returned).toBe(false);+ }+ await client.push([{ connId: 'exec-1', kind: 'message', data: '{"id":1,"result":{}}' }]);+ handle().emit({ type: 'done', data: {}, source: 'codex' } as AgentEvent);+ await previousPoll;+ await settle();+ clock += 70_000;+ await vi.advanceTimersByTimeAsync(5_000);+ await settle();+ expect(host.runCount()).toBe(1);+ localBusy = false;+ await pass(0);+ await pass(50_000);+ expect(host.runCount()).toBe(1);+ await pass(20_000);+ await pass(0);+ expect(host.runCount()).toBe(0);+ expect(rows.at(-1)).toEqual({ t: 'closed', reason: 'ended', idleReclaimed: true });+ } finally {+ abort.abort();+ await previousPoll?.catch(() => undefined);+ client.abandon('test-finished');+ 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 => {diff --git a/apps/desktop/src/main/remote-agent/controller/runClient.ts b/apps/desktop/src/main/remote-agent/controller/runClient.tsindex a772a6a03f..2a72439399 100644--- a/apps/desktop/src/main/remote-agent/controller/runClient.ts+++ b/apps/desktop/src/main/remote-agent/controller/runClient.ts@@ -180,7 +180,7 @@ export class RemoteAgentRunClient implements PolledRun {for (let attempt = 1; ; attempt += 1) {if (this.closed) return;try {- await this.invoke([{ op: 'push', runId: this.runId, seq, frames }]);+ await this.invoke([{ op: 'push', runId: this.runId, seq, frames, ...(this.holdsRemote() ? { hold: true } : {}) }]);return;} catch (error) {const retryable = isRetryableLinkError(error) && attempt < MAX_PUSH_DELIVER_ATTEMPTS;diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex 1b281a6639..d5a62bf627 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -2081,12 +2081,15 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {waitMs: number,signal?: AbortSignal,): Promise<RemoteAgentPollResult> {- const touch = () => {+ const touch = (updateHold: boolean) => {const t = now();for (const { runId, hold } of wanted) {const run = runs.get(key(controller, runId));if (!run) continue;run.lastReadAt = t;+ // Only apply the snapshot when this request arrives; an older long poll returning later must+ // not clear a newer hold received with a process startup reply.+ if (!updateHold) continue;// 控制端那边还有这个任务的工作在进行:按有活动算,不按闲置收回。if (hold) run.activeAt = run.heldAt = t;else run.heldAt = undefined;@@ -2096,11 +2099,11 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {const run = runs.get(key(controller, runId));return run && run.log.isValidCursor(cursor) ? [{ run, cursor }] : [];});- touch();+ touch(true);const initial = live();const anyReady = initial.length < wanted.length || initial.some(({ run, cursor }) => run.log.isReady(cursor));if (!anyReady && waitMs > 0) await waitForAny(initial.map(({ run }) => run.log), waitMs, signal);- touch();+ touch(false);const out: RemoteAgentPollResult = { runs: [] };let budget = REMOTE_AGENT_POLL_MAX_BYTES;const start = wanted.length ? pollRotation++ % wanted.length : 0;@@ -2627,6 +2630,9 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {}case 'push': {const run = requireRun(controller, request.runId);+ // The first local process may start between poll batches. Its startup reply carries the hold+ // immediately; retries refresh the lease without delivering the frames again.+ if (request.hold) run.activeAt = run.heldAt = now();if (run.pushSeq.has(request.seq)) return {};run.pushSeq.add(request.seq);// Codex 执行环境在控制端的输出与回包:控制端那边还在干活。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 541de48459..e74f5cc24c 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1461,10 +1461,12 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加Maker 把事件流结束当成句柄已死、自动关闭任务,下次发送照常重建并带原生会话 id 接回(本机后台命令随句柄结束);新 A 不关句柄,与连接池让出名额同一状态(released),本机部分保留,下次要 B 干活时连回。中转时组所在电脑把这个字段原样转给受邀者(`relayClosed`),`ended` 本来就在正常收尾的原因里,不触发换电脑。- - **A 报 hold**:`poll` 的每个任务项可选 `hold: true`,表示 A 这边还有 B 看不到的工作(当前只有 Codex 经执行环境在 A 上起的、- 仍在运行的进程,`ExecServerRelay.busy()`)。B 收到后在控制端的 3 分钟存活窗口内按忙处理,后续 poll 未带 hold 就解除,+ - **A 报 hold**:`poll` 的每个任务项和 `push` 请求可选 `hold: true`,表示 A 这边还有 B 看不到的工作(当前只有 Codex 经执行环境在 A 上起的、+ 仍在运行的进程,`ExecServerRelay.busy()`)。本机进程的启动回包随 `push` 立即报 hold,不必等下一批 poll;组所在电脑逐跳接着报。+ B 收到后在控制端的 3 分钟存活窗口内按忙处理,后续 poll 未带 hold 就解除,再从忙完后计算闲置时长;组所在电脑在同一窗口内接着给组内电脑报 hold。大量任务按批轮询可能超过最短的 1 分钟- 闲置设置,不能只把收到 hold 的那一刻算作活动。旧 B 解析 poll 时丢弃不认识的字段。+ 闲置设置,不能只把收到 hold 的那一刻算作活动。poll 的 hold 只在请求抵达时应用,等待结束后仅刷新存活时间,避免旧快照清掉新 hold。+ 旧 B 解析 poll / push 时丢弃不认识的字段。- **caps**:B 声明 `idleReclaimMinutes`(不合法时当作没声明,不让整个 caps 作废)。A 的连接池按它判定「闲置满」,旧 B 不声明 = 0,不让出。- **四种组合**:A 新 × B 新 按上面;A 新 × B 旧 不收回、不让出;A 旧 × B 新 被收回后静默重建;A 旧 × B 旧 不变。diff --git a/packages/device-link/src/__tests__/remoteAgent.test.ts b/packages/device-link/src/__tests__/remoteAgent.test.tsindex 314e8450bc..8fe7065b6a 100644--- a/packages/device-link/src/__tests__/remoteAgent.test.ts+++ b/packages/device-link/src/__tests__/remoteAgent.test.ts@@ -194,6 +194,11 @@ describe('remote agent channel', () => {.toEqual({ op: 'reply', runId, requestId: otherId, payload: { uploadId: otherId, chunks: 2, bytes: 10 } });expect(parseRemoteAgentRequest({ op: 'push', runId, seq: 3, frames: [{ connId: 'c1', kind: 'message', data: '{}' }] })).toEqual({ op: 'push', runId, seq: 3, frames: [{ connId: 'c1', kind: 'message', data: '{}' }] });+ // Optional busy-state addition to v1: retain only true; legacy senders omit it.+ for (const hold of [true, false, 'true']) {+ expect(parseRemoteAgentRequest({ op: 'push', runId, seq: 3, hold, frames: [{ connId: 'c1', kind: 'message', data: '{}' }] }))+ .toEqual({ op: 'push', runId, seq: 3, ...(hold === true ? { hold: true } : {}), frames: [{ connId: 'c1', kind: 'message', data: '{}' }] });+ }expect(parseRemoteAgentRequest({ op: 'close', runId, mode: 'detach', reason: 'navigation' })).toEqual({ op: 'close', runId, mode: 'detach', reason: 'navigation' });expect(parseRemoteAgentRequest({ op: 'upload', uploadId: otherId, index: 0, data: 'AAAA' })).toEqual({ op: 'upload', uploadId: otherId, index: 0, data: 'AAAA' });diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.tsindex f3d7cd29f6..cd8aeca899 100644--- a/packages/device-link/src/remoteAgent.ts+++ b/packages/device-link/src/remoteAgent.ts@@ -166,7 +166,8 @@ export type RemoteAgentRequest =*/| { op: 'poll'; runs: Array<{ runId: string; cursor: number; hold?: true }>; waitMs?: number }| { op: 'reply'; runId: string; requestId: string; payload: RemoteAgentPayload }- | { op: 'push'; runId: string; seq: number; frames: RemoteAgentPushFrame[] }+ /** hold: local work has started; protect it with the startup reply before the next poll batch. */+ | { op: 'push'; runId: string; seq: number; frames: RemoteAgentPushFrame[]; hold?: true }| { op: 'close'; runId: string; mode: 'close' | 'detach'; reason: RemoteAgentTeardownReason }/*** 供应商组(组所在电脑 → 组内电脑):组所在电脑删掉某个受邀者后,请组内电脑清掉替这个受邀者@@ -511,7 +512,10 @@ export function parseRemoteAgentRequest(value: unknown): RemoteAgentRequest {case 'reply':return { op: 'reply', runId: id(v.runId), requestId: id(v.requestId), payload: payload(v.payload) };case 'push':- return { op: 'push', runId: id(v.runId), seq: count(v.seq, Number.MAX_SAFE_INTEGER), frames: pushFrames(v.frames) };+ return {+ op: 'push', runId: id(v.runId), seq: count(v.seq, Number.MAX_SAFE_INTEGER), frames: pushFrames(v.frames),+ ...(v.hold === true ? { hold: true as const } : {}),+ };case 'close':return {op: 'close',