Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote-agent): 连回后补发设置失败时当作连回失败,不在缺设置的 Agent 上发消息

fmfsaisai00cd3ea0517e
diff --git a/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts b/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts
index d589dde83f..e25cb74ff6 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/connectionPool.test.ts
@@ -325,6 +325,8 @@ interface Scenario {
pendingWake: number;
/** send 'hold' 时卡住,直到调用它。 */
releaseHold: (() => void) | null;
+ /** 接下来这么多次 setExtraDirs 报错。 */
+ failSetExtraDirs: number;
}
let scenario: Scenario;
@@ -434,6 +436,10 @@ function fakeAgent(input: HostedStartInput): AgentSessionHandle {
},
async setExtraDirs(dirs, libraryRoot) {
record('setExtraDirs', [dirs, libraryRoot]);
+ if (scenario.failSetExtraDirs > 0) {
+ scenario.failSetExtraDirs -= 1;
+ throw new Error('extra dirs rejected');
+ }
},
async requiresModelSwitchRebuild() {
record('requiresModelSwitchRebuild', []);
@@ -547,7 +553,7 @@ beforeEach(() => {
project = path.join(root, 'project');
hostRoot = path.join(root, 'host');
fs.mkdirSync(project);
- scenario = { started: [], calls: [], closes: 0, failResume: null, backgroundTasks: [], pendingWake: 0, releaseHold: null };
+ scenario = { started: [], calls: [], closes: 0, failResume: null, backgroundTasks: [], pendingWake: 0, releaseHold: null, failSetExtraDirs: 0 };
limits = { perDevice: 1, total: 64 };
intercept = null;
opens = 0;
@@ -901,6 +907,28 @@ describe('remote connection pool with a real host', () => {
await vi.waitFor(() => expect(host.limitUsage().total).toBe(1));
});
+ // PR #6483 review:连回后补发设置失败只记日志,消息照样在缺设置的 Agent 上执行。
+ it('fails the reconnect when restoring settings fails: nothing is sent, the run is closed, and the next send restores them', async () => {
+ limits = { perDevice: 16, total: 64 };
+ const pool = newPool();
+ const a = await start(pool);
+ const events = watch(a);
+ await ask(a, events, 'hello');
+ await a.setExtraDirs!([], path.join(root, 'library'));
+ await sleep(5);
+ expect(await pool.releaseForRetry(member('other', 0, false))).toBe(true);
+ expect(host.limitUsage().total).toBe(0);
+ scenario.failSetExtraDirs = 1;
+ const before = scenario.calls.length;
+ await expect(a.send({ type: 'user', content: 'one' })).rejects.toThrow('[REMOTE_AGENT_UNAVAILABLE]');
+ expect(scenario.calls.slice(before).map((call) => call.method)).toEqual(['setExtraDirs']);
+ // 这次开的进程关掉、名额还回去。
+ await vi.waitFor(() => expect(host.limitUsage().total).toBe(0));
+ expect(await ask(a, events, 'two')).toBe('ok:two');
+ expect(scenario.calls.slice(before).map((call) => call.method)).toEqual(['setExtraDirs', 'setExtraDirs', 'send']);
+ expect(scenario.started).toHaveLength(3);
+ });
+
it('gives up a release once a send has started', async () => {
const pool = newPool();
const a = await start(pool);
diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
index a6d1e1fbf8..65b41d5efd 100644
--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts
+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
@@ -395,25 +395,28 @@ export async function startRemoteAgentSession(
&& resumableAfterRelease();
/** 连接池让出名额:只结束对方的 Agent 进程,本机部分与对话记录都留着。 */
+ /** 结束对方的这个 Agent 进程,本机部分留着,状态回到已让出(调用前已置为 releasing)。 */
+ async function closeRun(client: RemoteAgentRunClient): Promise<void> {
+ try {
+ // 用 close 而不是 detach:detach 不结束对方的进程,名额让不出来。
+ await client.close('close', 'navigation');
+ } catch (error) {
+ deps.log?.warn('remote agent: closing a released connection failed', { runId: client.runId, error: String(error) });
+ // 没送到:对方可能还占着名额,连接池继续给它占位并再试一次 close。
+ deps.pool?.holdAfterFailedClose(member, () => poller.invoke([{ op: 'close', runId: client.runId, mode: 'close', reason: 'navigation' }]));
+ } finally {
+ // 对方的 Codex 已退出:本机为它起的 exec-server 一并关掉,连回来的 Agent 会重新连。
+ relay?.reset();
+ if (active === client) active = null;
+ if (linkState === 'releasing') linkState = 'released';
+ }
+ }
+
async function release(): Promise<boolean> {
if (!isIdle() || !active) return false;
const client = active;
linkState = 'releasing';
- const done = (async () => {
- try {
- // 用 close 而不是 detach:detach 不结束对方的进程,名额让不出来。
- await client.close('close', 'navigation');
- } catch (error) {
- deps.log?.warn('remote agent: closing a released connection failed', { runId: client.runId, error: String(error) });
- // 没送到:对方可能还占着名额,连接池继续给它占位并再试一次 close。
- deps.pool?.holdAfterFailedClose(member, () => poller.invoke([{ op: 'close', runId: client.runId, mode: 'close', reason: 'navigation' }]));
- } finally {
- // 对方的 Codex 已退出:本机为它起的 exec-server 一并关掉,连回来的 Agent 会重新连。
- relay?.reset();
- if (active === client) active = null;
- if (linkState === 'releasing') linkState = 'released';
- }
- })();
+ const done = closeRun(client);
releasing = done;
try {
await done;
@@ -674,7 +677,8 @@ export async function startRemoteAgentSession(
}
/**
- * 连回后补上对方进程里的状态(不在启动选项里的)。失败只记日志:不影响接着干活。
+ * 连回后补上对方进程里的状态(不在启动选项里的)。任一步失败就抛错:不能让消息在缺设置的 Agent 上执行
+ * (目录没给到,消息里的虚拟路径就落空;自动审查兜底没恢复则少了一道安全设置)。
* 目录:打开时给的是第一次的列表,之后的增减在这里按运行中改目录的方式补发,与一直连着时的效果一致。
*/
async function reapply(client: RemoteAgentRunClient): Promise<void> {
@@ -694,6 +698,8 @@ export async function startRemoteAgentSession(
await client.call(method, args);
} catch (error) {
deps.log?.warn('remote agent: restoring state after reconnect failed', { method, error: String(error) });
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new Error(`[REMOTE_AGENT_UNAVAILABLE] Reconnected to the other computer but could not restore this task's settings (${method}): ${detail}`);
}
}
}
@@ -719,7 +725,16 @@ export async function startRemoteAgentSession(
});
touch();
deps.log?.info('remote agent reconnected', { kind, runId: client.runId });
- await reapply(client);
+ try {
+ await reapply(client);
+ } catch (error) {
+ // 补发失败:关掉这次开的进程、还回名额,保持已让出;待补发的内容都还在,下次调用重新连回再补。
+ if (stateNow() === 'connected' && activeNow() === client) {
+ linkState = 'releasing';
+ await closeRun(client);
+ }
+ throw error;
+ }
if (stateNow() !== 'connected' || activeNow() !== client) throw new Error('[REMOTE_AGENT_EXPIRED] The task has ended on this computer.');
return client;
} catch (error) {
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 19c7d9761a..338b2e7411 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1361,7 +1361,9 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加
已让出时只记在 A,`abort` / `requestGracefulStop` / `stopBackgroundTask` 已让出时什么也不做。会话里还没有对话(不是接回的旧会话、
也没跑完过一轮)时连回直接开新会话,不带 id。连回带当前原生会话 id 与最新的
模型、来源、推理强度、快速模式、思考开关、权限档、计划模式;回退 / 分叉用的一次性 `resumeSessionAt` /
- `forkSession` 只在第一轮跑完前带(之后再带会再截断一次);`setVendorOptions` 改过的内容、`libraryRoot`、`useCindyAutoReviewFallback` 连回后再告诉 B 一次。
+ `forkSession` 只在第一轮跑完前带(之后再带会再截断一次);`setVendorOptions` 改过的内容、`libraryRoot`、`useCindyAutoReviewFallback` 连回后再告诉 B 一次;
+ 补发的任一步失败就当这次连回失败(fail closed):关掉刚开的 run 还回名额、回到已让出,待补发的内容保留,调用以
+ `[REMOTE_AGENT_UNAVAILABLE]` 报错,下次调用重新连回再补发,不会在缺设置的 Agent 上执行消息。
**目录映射保证**:对话里出现过的每个虚拟路径,连回后仍指向同一个本机目录,绝不会指向另一个目录。B 按 open 里
附加 / 可写目录的顺序起名(`additional/dir-<序号>`),所以连回时原样给第一次打开时的列表与顺序;A 已有的映射
(含运行中新增目录分配的 `additional/runtime-<n>`)只补不换。打开之后的增减(连着时或让出期间)在连回后按运行中