Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-remote-ssh,maker-core): 处理 PR #715 review 的五处竞态/收口问题
yanb6ddf0c01ff6
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.parseProxyAddr.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.parseProxyAddr.test.tsindex 6a407742ca..f0609cd89e 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.parseProxyAddr.test.ts+++ b/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.parseProxyAddr.test.ts@@ -12,9 +12,9 @@ describe('parseProxyAddrInput', () => {expect(parseProxyAddrInput('[::1]:7890')).toEqual({ localHost: '::1', localPort: 7890 });});- it('takes the last colon so bare IPv6 without brackets is rejected (ambiguous)', () => {- // ::1:7890 → lastIndexOf(':') 切出 host=': :1' 含空白? 不含 — host='::1', port=7890。- // 裸 IPv6 语义模糊, 这里的行为是接受 last-colon 切分结果; 文档推荐 bracket 形态。+ it('accepts bare IPv6 by splitting at the last colon (bracket form recommended)', () => {+ // ::1:7890 → lastIndexOf(':') 切出 host='::1', port=7890。裸 IPv6 语义+ // 模糊但有确定行为: 按 last-colon 切分接受; 文档/UI hint 推荐 bracket 形态。expect(parseProxyAddrInput('::1:7890')).toEqual({ localHost: '::1', localPort: 7890 });});diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 7cd2a7bf69..e294f14164 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -6208,6 +6208,69 @@ describe('CodexAgent turn lifecycle', () => {await handle.close();});+ it('ignores an orphan turnStarted after a failed turn/start and interrupts it server-side (greptile P1)', async () => {+ // turn/start RPC 失败 (超时/拒绝) 不代表 server 没建 turn — daemon 实际+ // 建了的 turn 迟到的 started 不得重新激活已报终态错误的会话。+ let failTurnStart = true;+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) {+ if (failTurnStart) {+ throw new Error('codex app-server turn/start timed out after 60000ms');+ }+ return { turn: { id: 'turn-2' } };+ }+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-orphan-turnstarted',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const subscribeCalls = host.subscribeThread.mock.calls as unknown as Array<[string, ThreadEventHandlers]>;+ const handlers = subscribeCalls[0]?.[1];+ const iterator = handle.events()[Symbol.asyncIterator]();++ await handle.send({ type: 'user', content: 'hello' });+ // send 开头先推 status isRunning:true, 然后才是 turn/start 失败的终态序列。+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { isRunning: true },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'error',+ data: { isTerminal: true },+ });+ expect(await nextEvent(iterator)).toMatchObject({+ type: 'status',+ data: { status: 'Done', isRunning: false },+ });++ // daemon 实际建了 turn → 迟到 started: 立墓碑 + 补 interrupt, 不重新激活。+ handlers.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'orphan-turn-id' },+ });+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(handle.getCurrentTurnId?.()).toBeNull();+ await vi.waitFor(() => {+ expect(host.request).toHaveBeenCalledWith(+ Method.TurnInterrupt,+ expect.objectContaining({ turnId: 'orphan-turn-id' }),+ );+ });+ // 孤儿事件不再产生任何 UI 事件。+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');++ // 守卫不挡后续正常发送: 下一次 turn/start 成功后 turn 正常激活+ // (handleTurnStartResp 清守卫标记并置 currentTurnId)。+ failTurnStart = false;+ await handle.send({ type: 'user', content: 'again' });+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(handle.getCurrentTurnId?.()).toBe('turn-2');+ await handle.close();+ });+it('clears running state and emits done status after terminal error notification', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent);diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex bb749b7c99..65752abeaf 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2087,6 +2087,9 @@ export class CodexAgent extends BaseAgent {let currentTurnId: string | null = null;let isTurnInFlight = false;let isTurnStartPending = false;+ // turn/start RPC 失败(超时/拒绝)后置位: server 可能实际已建 turn,+ // 迟到的孤儿 turnStarted 由 turnStarted handler 拦下并补 interrupt。+ let turnStartFailedWithoutTurnId = false;type TurnCompletedParams = Parameters<NonNullable<ThreadEventHandlers['turnCompleted']>>[0];// 正常完成的 turn 也必须保留墓碑:app-server 允许 turn/completed 早于仍在// 后台收尾的 item 事件到达。没有这层墓碑时,currentTurnId 已清空,迟到 item@@ -4122,6 +4125,28 @@ export class CodexAgent extends BaseAgent {if (shouldIgnoreStaleTurnEvent(params.turn.id)) return;// 终态已先到的 turn (墓碑) 不得被乱序晚到的 started 重新置活。if (turnsCompletedBeforeStartResp.has(params.turn.id)) return;+ // turn/start RPC 已失败(超时/拒绝)但 daemon 实际已建 turn — 迟到的孤儿+ // turnStarted 不得重新激活已报终态错误的会话 (greptile P1): 立墓碑 ++ // 补 interrupt 让 daemon 停掉这个没人消费的 turn。仅在没有新 turn/start+ // 在飞时判定 — 在飞期间到达的 started 按正常路径处理 (与成功路径的+ // started-先于-resp 乱序共存; 该固有歧义不由本守卫承担)。+ if (turnStartFailedWithoutTurnId && !isTurnStartPending && currentTurnId === null) {+ terminalErroredTurnIds.add(params.turn.id);+ log.warn('ignoring orphan turnStarted from a failed turn/start — interrupting server-side turn', {+ turnId: params.turn.id,+ threadId,+ });+ if (threadId) {+ host.request(Method.TurnInterrupt, { threadId, turnId: params.turn.id })+ .catch((e: unknown) => {+ log.warn('orphan turn interrupt failed (best-effort)', {+ turnId: params.turn.id,+ error: e instanceof Error ? e.message : String(e),+ });+ });+ }+ return;+ }threadMayHaveRollout = true;const wasSameTurn = currentTurnId === params.turn.id;currentTurnId = params.turn.id;@@ -4553,6 +4578,9 @@ export class CodexAgent extends BaseAgent {// 普通 LLM 错误 / 超时 / auth 失败照原路径报错。const handleTurnStartResp = (resp: TurnStartResponse): void => {if (resp.turn?.id) {+ // turn/start 成功 → 孤儿守卫解除 (上次失败的 RPC 若也有迟到 started,+ // 那是一次新的语义重叠, 由 turn id 匹配路径处理)。+ turnStartFailedWithoutTurnId = false;// 墓碑: 该 turn 的终态已抢在本响应之前到达 (典型: 收紧补中断后// turnCompleted(interrupted) 先回), 不得重新置活, 否则会话卡 running。const alreadyCompleted = turnsCompletedBeforeStartResp.has(resp.turn.id);@@ -4690,6 +4718,10 @@ export class CodexAgent extends BaseAgent {// failed 分支同语义), 否则 planCycleActive 泄漏, 下一条常规消息仍会// 携带 collaborationMode plan(勾选与 chip 早已熄灭, 行为与 UI 脱节)。endPlanCycleAfterPreStartFailure('turn/start failed');+ // RPC 级失败(超时/拒绝)不代表 server 没建 turn — daemon 可能已接受+ // turn/start 只是响应没回来。立孤儿守卫: 之后迟到的 turnStarted 不得+ // 重新激活会话 (greptile P1: 已报终态错误的会话又回到 generating)。+ turnStartFailedWithoutTurnId = true;log.error('turn/start failed', { error: String(finalErr) });eventQueue.push({type: 'error',diff --git a/packages/maker-remote-ssh/src/RemoteHost.ts b/packages/maker-remote-ssh/src/RemoteHost.tsindex ef0528154e..28e5be8787 100644--- a/packages/maker-remote-ssh/src/RemoteHost.ts+++ b/packages/maker-remote-ssh/src/RemoteHost.ts@@ -589,19 +589,27 @@ export class RemoteHost {* 在当前 client 上注册 forwardIn。端口冲突 / sshd 拒绝时按候选序列重试,* 全部失败抛错 (调用方决定是登记愿望待重试还是直接失败)。*- * 每次 forwardIn 带 10s 看门狗: 连接在请求在飞时断开的话, ssh2 对- * outstanding global request 的回调不保证触发, 裸 await 会永久挂起。+ * 候选顺序: 先试上次实际绑定的端口 (record.remotePort) — 重连后隧道口+ * 尽量不变, 远端进程 env (HTTPS_PROXY=http://127.0.0.1:<port>) 不用跟着+ * 重写; 再按首选基数顺延。每次 forwardIn 带 10s 看门狗: 连接在请求在飞+ * 时断开的话, ssh2 对 outstanding global request 的回调不保证触发,+ * 裸 await 会永久挂起。*/private async armForward(record: ForwardRecord): Promise<void> {const client = this.requireReady();this.attachForwardListener(client);const base = record.spec.preferredRemotePort ?? DEFAULT_REMOTE_FORWARD_PORT_BASE;- const errors: string[] = [];+ const candidates = [record.remotePort];for (let i = 0; i < REMOTE_FORWARD_PORT_SCAN_SPAN; i++) {- const port = base + i;+ if (!candidates.includes(base + i)) candidates.push(base + i);+ }+ const errors: string[] = [];+ for (const port of candidates) {const bound = await new Promise<number | null>((resolve) => {+ let settled = false;const timer = setTimeout(() => {+ settled = true;errors.push(`${port}: forwardIn timed out after 10s`);resolve(null);}, 10_000);@@ -609,6 +617,21 @@ export class RemoteHost {try {client.forwardIn('127.0.0.1', port, (err, boundPort) => {clearTimeout(timer);+ if (settled) {+ // 看门狗已判失败, 迟到的成功会在服务端留下没有 record 的野+ // 监听 (端口被占 + 连接被默默转走) — 立刻拆除。+ if (!err) {+ this.log.warn('late forwardIn success after watchdog timeout — unbinding', {+ id: this.id,+ port: boundPort || port,+ });+ try {+ client.unforwardIn('127.0.0.1', boundPort || port, () => { /* best-effort */ });+ } catch { /* client may be dead */ }+ }+ return;+ }+ settled = true;if (err) {errors.push(`${port}: ${err.message}`);resolve(null);@@ -618,11 +641,30 @@ export class RemoteHost {});} catch (err) {clearTimeout(timer);+ if (settled) return;+ settled = true;errors.push(`${port}: ${(err as Error).message}`);resolve(null);}});if (bound == null) continue;+ // close() 可能发生在 arm 在飞期间: record 已被摘除的话, 刚绑上的+ // 端口同样是野监听 — 立即 unforward, 以失败收尾 (armForwardDeduped+ // 的调用方都已 catch)。+ if (this.forwards.get(forwardKey(record.spec)) !== record) {+ this.log.warn('forward closed while arming — unbinding just-bound port', {+ id: this.id,+ port: bound,+ });+ await new Promise<void>((resolve) => {+ try {+ client.unforwardIn('127.0.0.1', bound, () => resolve());+ } catch {+ resolve();+ }+ });+ throw new Error(`remote forward to ${forwardKey(record.spec)} was closed while arming`);+ }record.remotePort = bound;record.armed = true;this.log.info('ssh remote forward armed', {@@ -633,7 +675,7 @@ export class RemoteHost {return;}throw new Error(- `remote port forwarding failed on ${this.id} (tried 127.0.0.1:${base}–${base + REMOTE_FORWARD_PORT_SCAN_SPAN - 1}). ` ++ `remote port forwarding failed on ${this.id} (tried 127.0.0.1:${candidates.join(',')}). ` +`The remote sshd may disallow remote forwarding (AllowTcpForwarding) or the ports are busy. ` +errors.slice(0, 3).join('; '),);diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.tsindex 75855c748c..9222b59836 100644--- a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts@@ -10,7 +10,7 @@* - 断线重连 re-arm: 愿望保留、端口变化触发 onRearmed*/-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import { EventEmitter } from 'node:events';import { Duplex, PassThrough } from 'node:stream';import net from 'node:net';@@ -36,6 +36,8 @@ const noopLogger = {interface ForwardInCall { addr: string; port: number }+type ForwardInCallback = (err: Error | undefined, port: number) => void;+/** 可按端口决定成败的 fake ssh2 Client。 */class FakeClient extends EventEmitter {forwardInCalls: ForwardInCall[] = [];@@ -44,7 +46,7 @@ class FakeClient extends EventEmitter {constructor(private readonly allowPort: (port: number) => boolean = () => true) {super();}- forwardIn(addr: string, port: number, cb: (err: Error | undefined, port: number) => void): void {+ forwardIn(addr: string, port: number, cb: ForwardInCallback): void {this.forwardInCalls.push({ addr, port });queueMicrotask(() => {if (this.allowPort(port)) cb(undefined, port);@@ -57,6 +59,24 @@ class FakeClient extends EventEmitter {}}+/** forwardIn 回调完全手动驱动的 fake — 用来造在飞 / 迟到回调的竞态场景。 */+class ManualForwardClient extends EventEmitter {+ pending = new Map<number, ForwardInCallback>();+ unforwardInCalls: ForwardInCall[] = [];+ forwardIn(_addr: string, port: number, cb: ForwardInCallback): void {+ this.pending.set(port, cb);+ }+ unforwardIn(addr: string, port: number, cb: () => void): void {+ this.unforwardInCalls.push({ addr, port });+ queueMicrotask(() => cb());+ }+ succeed(port: number): void {+ const cb = this.pending.get(port);+ this.pending.delete(port);+ cb?.(undefined, port);+ }+}+interface FakeChannelBundle {channel: Duplex & { close: () => void };/** test 写入 → channel readable → 本地 sock (模拟远端发来的字节)。 */@@ -89,7 +109,13 @@ function makeFakeChannel(): FakeChannelBundle {return { channel, fromRemote, toRemote, closed: () => closed };}-function makeReadyHost(client: FakeClient): RemoteHost {+/** makeReadyHost 接受的最小 fake client 面 (FakeClient / ManualForwardClient 共用)。 */+interface FakeSshClient extends EventEmitter {+ forwardIn(addr: string, port: number, cb: ForwardInCallback): void;+ unforwardIn(addr: string, port: number, cb: () => void): void;+}++function makeReadyHost(client: FakeSshClient): RemoteHost {const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });(host as unknown as { status: string }).status = 'ready';(host as unknown as { client: unknown }).client = client;@@ -267,6 +293,70 @@ describe('RemoteHost remote forwarding', () => {expect(host.listRemoteForwards()[0]?.armed).toBe(true);});+ it('re-arm prefers the last bound port (no churn / no onRearmed when it is still free)', async () => {+ // 首轮 base 被占 → 绑到 base+1; 重连后 base 已空闲, 仍应留在 base+1+ // (远端 daemon env / marker 指向它, 端口 churn 会触发无谓的 env 重写)。+ const client1 = new FakeClient((port) => port !== DEFAULT_REMOTE_FORWARD_PORT_BASE);+ const host = makeReadyHost(client1);+ let rearmed: number | null = null;+ const fwd = await host.ensureRemoteForward({+ localHost: '127.0.0.1',+ localPort: 7890,+ onRearmed: (port) => { rearmed = port; },+ });+ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);++ (host as unknown as { markForwardsDisarmed(): void }).markForwardsDisarmed();+ const client2 = new FakeClient(() => true); // 全部空闲+ (host as unknown as { client: unknown }).client = client2;+ await (host as unknown as { rearmForwards(): Promise<void> }).rearmForwards();++ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);+ expect(rearmed).toBeNull();+ expect(client2.forwardInCalls.map((c) => c.port)).toEqual([DEFAULT_REMOTE_FORWARD_PORT_BASE + 1]);+ });++ it('unbinds a late forwardIn success that races the 10s watchdog', async () => {+ vi.useFakeTimers();+ try {+ const client = new ManualForwardClient();+ const host = makeReadyHost(client);+ const pending = host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });+ // 第一个候选卡在在飞状态; 看门狗 10s 后判失败, 转下一候选。+ await vi.advanceTimersByTimeAsync(10_100);+ expect(client.pending.has(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1)).toBe(true);+ // 迟到的成功: 必须立刻 unbind, 不能在服务端留下野监听。+ client.succeed(DEFAULT_REMOTE_FORWARD_PORT_BASE);+ expect(client.unforwardInCalls).toContainEqual({+ addr: '127.0.0.1',+ port: DEFAULT_REMOTE_FORWARD_PORT_BASE,+ });+ client.succeed(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);+ const fwd = await pending;+ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('unbinds the just-bound port when close() races an in-flight arm', async () => {+ const client = new ManualForwardClient();+ const host = makeReadyHost(client);+ const pending = host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });+ pending.catch(() => { /* assertion below via rejects */ });+ // arm 在飞 (forwardIn 未回调) 时关掉 forward。+ await host.closeAllRemoteForwards();+ expect(host.listRemoteForwards()).toEqual([]);+ // 迟到的绑定成功: record 已摘除, 必须 unbind 而不是留野监听。+ client.succeed(DEFAULT_REMOTE_FORWARD_PORT_BASE);+ await expect(pending).rejects.toThrow(/closed while arming/);+ await flush();+ expect(client.unforwardInCalls).toContainEqual({+ addr: '127.0.0.1',+ port: DEFAULT_REMOTE_FORWARD_PORT_BASE,+ });+ });+it('keeps the wish when re-arm fails, without throwing (logged only)', async () => {const client1 = new FakeClient();const host = makeReadyHost(client1);