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。

feat(desktop): Agent Proxy 三态化——固定端口独立隧道 + 自备代理注入 (#992)

yan341c972c6846
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 98275c417b..6e70fb843f 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1066,6 +1066,9 @@ export function getMaker(): Maker {
// 继续 probe 会 attach 到 stale daemon, UI 报 tunnel active 而
// codex 流量走旧路由 (codex R10 P1): 按 bootstrap 失败抛出, 让
// session start 显式报错, 而不是静默复用。
+ // deferredForLiveTurn (host 上有别的 turn 在跑) 则放行 attach:
+ // 这正是「不 mid-turn 杀 daemon」的代价 — 新 session 暂用旧
+ // env, turn-done 挂钩补刀后自愈。
const reconciled = await reconcileCodexAgentProxyEnv(remoteHost);
if (reconciled.markerChanged && !reconciled.daemonRestarted) {
throw new Error(
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b29182d96c..a7ca5e0e47 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -259,7 +259,11 @@ import {
} from '../messagePersistBroadcaster.js';
import { ensureCcManagerInstalledOrInstall } from '../remote-ssh/cc-manager-install.js';
import { ensureRemoteCodexMcpBridge, hasPendingRemoteMcpDrift } from '../remote-ssh/codex-remote-mcp.js';
-import { reconcileCodexAgentProxyEnv } from '../remote-ssh/agent-proxy.js';
+import {
+ hasPendingAgentProxyReconcile,
+ reconcileCodexAgentProxyEnv,
+ setAgentProxyLiveTurnChecker,
+} from '../remote-ssh/agent-proxy.js';
import { ensureRemoteAgentInstalledOrInstall, ensureRemoteHostReady, getRemoteSshPool, isCcMgrUpgradeInFlight } from '../remote-ssh/index.js';
import {
recordSessionContextSnapshot,
@@ -4523,6 +4527,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
setRemoteCodexLiveTurnChecker(codexRemoteHasLiveTurn);
+ // agent-proxy 的漂移应用 (重启 daemon / 迁移拆除隧道) 会打断该 host 上
+ // **任一** agent 的在途流量 — 隧道是 codex 与 CC 共用的网络通路, gate
+ // 必须两个通道都看 (R3 review P1), 不能沿用 MCP ensure 的 codex-only
+ // 判定 (那边 daemon 重启只影响 codex, 语义不同)。
+ function remoteAgentHasLiveTurn(hostId: string): boolean {
+ return maker.listActiveSessions().some(
+ (s) =>
+ s.remoteHostId === hostId &&
+ (s.agentKind === 'codex' || s.agentKind === 'claude-code') &&
+ (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),
+ );
+ }
+ setAgentProxyLiveTurnChecker(remoteAgentHasLiveTurn);
async function detachIdleRemoteCodexSessionsOnHost(hostId: string, reason: string): Promise<void> {
const detachTasks: Array<Promise<void>> = [];
@@ -4553,22 +4570,43 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const session = maker.getSession(sessionId);
const remoteHostId = session?.remoteHostId;
if (!remoteHostId) return;
+ const host = getRemoteSshPool().get(remoteHostId);
+ const hostReady = host?.getStatus() === 'ready';
+ // agent-proxy 的 live-turn defer 在这里补刀 — codex 与 CC 的 turn 收口
+ // 都算 (隧道是两个 agent 共用的通路, gate 也共用, R3 review P1)。只有
+ // 确有 pending (defer / 失败) 时才跑, 稳态下不为每次 turn 结束白付一次
+ // 远端 cat RTT。失败不阻断后续 (自身已重新记 pending)。
+ const reconcileIfPending =
+ hostReady && host && hasPendingAgentProxyReconcile(remoteHostId)
+ ? reconcileCodexAgentProxyEnv(host).catch((err) => {
+ log.warn('agent-proxy reconcile on turn settled failed', {
+ sessionId,
+ hostId: remoteHostId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ })
+ : Promise.resolve();
if (session.agentKind === 'codex') {
- const host = getRemoteSshPool().get(remoteHostId);
- if (host?.getStatus() !== 'ready') return;
- void ensureRemoteCodexMcpBridge(host, {
- ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
- hasLiveTurnOnHost: codexRemoteHasLiveTurn,
- isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
- isMakerMemoryEnabled: () => maker.makerMemory?.isEnabled() ?? false,
- }).then(async (result) => {
- if (result.ok && result.daemonRebootstrapped && !codexRemoteHasLiveTurn(remoteHostId)) {
- await detachIdleRemoteCodexSessionsOnHost(remoteHostId, 'codex-mcp-turn-settled-rebootstrap');
- }
- });
+ if (!hostReady || !host) return;
+ // 与 session-start 路径同序: 先 reconcile 再 MCP ensure (codex R20 P1)。
+ void reconcileIfPending
+ .then(() =>
+ ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
+ hasLiveTurnOnHost: codexRemoteHasLiveTurn,
+ isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
+ isMakerMemoryEnabled: () => maker.makerMemory?.isEnabled() ?? false,
+ }),
+ )
+ .then(async (result) => {
+ if (result?.ok && result.daemonRebootstrapped && !codexRemoteHasLiveTurn(remoteHostId)) {
+ await detachIdleRemoteCodexSessionsOnHost(remoteHostId, 'codex-mcp-turn-settled-rebootstrap');
+ }
+ });
return;
}
if (session.agentKind === 'claude-code') {
+ void reconcileIfPending;
getRemoteCcTurnSettledHandler()?.(sessionId);
}
};
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
index 4de2a85626..5adaba4b4d 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
@@ -1,15 +1,18 @@
/**
- * agent-proxy 策略层单测。
+ * agent-proxy 策略层单测 (固定端口 + 双模式版)。
*
* 覆盖:
* - buildAgentProxyEnv / buildAgentProxyEnvUppercase / buildAgentProxyMarkerContent
- * 的内容契约 (env 键集、URL 形态、NO_PROXY)
+ * 的内容契约 (env 键集、URL 透传、NO_PROXY)
* - reconcileCodexAgentProxyEnv 的对账状态机:
- * marker 一致 → 零副作用; 漂移 → 重写 + pkill; 关闭 → 删除 + pkill
- * - ensureAgentProxyTunnel 的 pref gate (关 → null, 开 → 建隧道)
+ * marker 一致 → 零副作用; 漂移 → 重写 + pkill; 关闭 → 删除 + pkill;
+ * live turn → 推迟 (不写不杀); env 模式 marker 用用户 URL
+ * - applyAgentProxyForHost 的失败上报与 per-host 串行化
+ * - prefs store 的双模式 round-trip 与旧数据迁移
*
* prefs store 依赖 electron app.getPath, 用 vi.mock 替换; RemoteHost 用
- * 最小 fake (exec 脚本断言 + ensureRemoteForward stub)。
+ * 最小 fake (exec 脚本断言)。代建隧道的保活器在 agent-proxy-tunnel.test.ts
+ * 单独测 — 本文件不 initAgentProxy, keeper 未装配时相关入口是 no-op。
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -47,16 +50,22 @@ import {
buildAgentProxyEnv,
buildAgentProxyEnvUppercase,
buildAgentProxyMarkerContent,
- ensureAgentProxyTunnel,
+ clearAgentProxyTunnelState,
getAgentProxyTunnelState,
+ getRemoteAgentProxyEnv,
+ hasPendingAgentProxyReconcile,
+ initAgentProxy,
killRemoteCodexDaemon,
reconcileCodexAgentProxyEnv,
+ resolveAgentProxyUrl,
+ setAgentProxyLiveTurnChecker,
} from '../agent-proxy';
import {
getSshHostAgentProxy,
getSshHostAutoConnect,
setSshHostAgentProxy,
setSshHostAutoConnect,
+ type SshHostAgentProxyPref,
} from '../ssh-host-prefs-store';
interface ExecCall {
@@ -65,15 +74,23 @@ interface ExecCall {
}
/** 最小 RemoteHost fake: 记录 exec, cat/rm marker + pkill 走脚本内容断言。 */
-function makeFakeHost(opts: { marker?: string | null; remotePort?: number } = {}) {
+function makeFakeHost(opts: { marker?: string | null } = {}) {
const state = {
marker: opts.marker ?? null,
execCalls: [] as ExecCall[],
pkillCount: 0,
- forwards: [] as Array<{ localHost: string; localPort: number; remotePort: number }>,
};
const host = {
id: 'test-host',
+ config: {
+ id: 'test-host',
+ hostname: '10.0.0.1',
+ port: 22,
+ user: 'deploy',
+ authMethod: 'agent',
+ source: 'manual',
+ },
+ getStatus: () => 'ready',
async exec(cmd: string, execOpts?: { input?: string }) {
state.execCalls.push({ cmd, input: execOpts?.input });
if (cmd.includes('cat "') && cmd.includes('agent-proxy.env')) {
@@ -93,36 +110,43 @@ function makeFakeHost(opts: { marker?: string | null; remotePort?: number } = {}
}
return { stdout: '', stderr: '', exitCode: 0, signal: null };
},
- async ensureRemoteForward(spec: { localHost: string; localPort: number }) {
- const remotePort = opts.remotePort ?? 17893;
- state.forwards.push({ ...spec, remotePort });
- return { remotePort, close: async () => {} };
- },
- async closeAllRemoteForwards() {
- state.forwards = [];
- },
- async closeRemoteForward(localHost: string, localPort: number) {
- state.forwards = state.forwards.filter(
- (f) => !(f.localHost === localHost && f.localPort === localPort),
- );
- },
- listRemoteForwards() {
- return state.forwards.map((f) => ({ ...f, armed: true }));
- },
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { host: host as any, state };
}
-const PREF = { enabled: true, localHost: '127.0.0.1', localPort: 7890 };
+const TUNNEL_PREF: SshHostAgentProxyPref = {
+ enabled: true,
+ mode: 'tunnel',
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ remotePort: 17893,
+};
+
+const ENV_PREF: SshHostAgentProxyPref = {
+ enabled: true,
+ mode: 'env',
+ proxyUrl: 'http://127.0.0.1:7890',
+};
beforeEach(() => {
prefsFileContent = null;
+ // prefs cache / tunnel state 都是模块级 — 显式清空, 防跨用例串味。
+ setSshHostAgentProxy('test-host', null);
+ clearAgentProxyTunnelState('test-host');
+ setAgentProxyLiveTurnChecker(() => false);
+});
+
+describe('resolveAgentProxyUrl', () => {
+ it('tunnel mode pins the fixed remote port; env mode passes the URL through', () => {
+ expect(resolveAgentProxyUrl(TUNNEL_PREF)).toBe('http://127.0.0.1:17893');
+ expect(resolveAgentProxyUrl(ENV_PREF)).toBe('http://127.0.0.1:7890');
+ });
});
describe('buildAgentProxyEnv', () => {
- it('builds dual-case proxy env pointing at the tunnel port', () => {
- const env = buildAgentProxyEnv(17893);
+ it('builds dual-case proxy env pointing at the proxy URL', () => {
+ const env = buildAgentProxyEnv('http://127.0.0.1:17893');
expect(env.HTTPS_PROXY).toBe('http://127.0.0.1:17893');
expect(env.HTTP_PROXY).toBe('http://127.0.0.1:17893');
expect(env.https_proxy).toBe('http://127.0.0.1:17893');
@@ -132,17 +156,18 @@ describe('buildAgentProxyEnv', () => {
});
it('uppercase-only variant satisfies the env-block gatekeeper', () => {
- const env = buildAgentProxyEnvUppercase(17893);
+ const env = buildAgentProxyEnvUppercase('socks5://10.0.0.5:1080');
for (const key of Object.keys(env)) {
expect(key).toMatch(/^[A-Z_][A-Z0-9_]*$/);
}
expect(Object.keys(env)).toEqual(['HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY']);
+ expect(env.HTTPS_PROXY).toBe('socks5://10.0.0.5:1080');
});
});
describe('buildAgentProxyMarkerContent', () => {
- it('is a sourceable shell snippet with the tunnel URL', () => {
- const content = buildAgentProxyMarkerContent(18000);
+ it('is a sourceable shell snippet with the proxy URL', () => {
+ const content = buildAgentProxyMarkerContent('http://127.0.0.1:18000');
expect(content).toContain("export HTTPS_PROXY='http://127.0.0.1:18000'");
expect(content).toContain("export https_proxy='http://127.0.0.1:18000'");
expect(content).toContain("export NO_PROXY='localhost,127.0.0.1,::1'");
@@ -150,44 +175,32 @@ describe('buildAgentProxyMarkerContent', () => {
});
});
-describe('ensureAgentProxyTunnel', () => {
+describe('getRemoteAgentProxyEnv', () => {
it('returns null when the pref is off', async () => {
- const { host, state } = makeFakeHost();
- const result = await ensureAgentProxyTunnel(host);
- expect(result).toBeNull();
- expect(state.forwards).toHaveLength(0);
+ const { host } = makeFakeHost();
+ expect(await getRemoteAgentProxyEnv(host)).toBeNull();
});
- it('opens the forward to the pref target when enabled', async () => {
- setSshHostAgentProxy('test-host', PREF);
+ it('env mode returns the user URL without touching any tunnel', async () => {
+ setSshHostAgentProxy('test-host', ENV_PREF);
const { host, state } = makeFakeHost();
- const result = await ensureAgentProxyTunnel(host);
- expect(result).toEqual({ remotePort: 17893, staleForwards: [] });
- expect(state.forwards).toEqual([{ localHost: '127.0.0.1', localPort: 7890, remotePort: 17893 }]);
+ const env = await getRemoteAgentProxyEnv(host);
+ expect(env?.HTTPS_PROXY).toBe('http://127.0.0.1:7890');
+ expect(state.execCalls).toHaveLength(0);
});
- it('closes stale forwards whose target no longer matches the pref (review R5)', async () => {
- // pref 目标被编辑 (7890 → 1080): 旧目标的 forward 必须拆掉, 否则残留并
- // 随重连 re-arm, 远端多暴露一个隧道口。
- setSshHostAgentProxy('test-host', PREF);
- const { host, state } = makeFakeHost();
- await ensureAgentProxyTunnel(host);
- expect(state.forwards).toHaveLength(1);
-
- setSshHostAgentProxy('test-host', { ...PREF, localPort: 1080 });
- const result = await ensureAgentProxyTunnel(host);
- expect(result).toMatchObject({ remotePort: 17893 });
- expect(result?.staleForwards).toHaveLength(1);
- expect(result?.staleForwards[0]).toMatchObject({ localHost: '127.0.0.1', localPort: 7890 });
- // 旧 7890 已拆 (默认 closeStale 立即拆), 只剩新 1080。
- expect(state.forwards).toEqual([{ localHost: '127.0.0.1', localPort: 1080, remotePort: 17893 }]);
+ it('tunnel mode rejects when the keeper is not armed (fail-closed, no silent direct)', async () => {
+ // 本测试文件不 initAgentProxy — keeper 未装配, ensureTunnelUp 立即拒绝。
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const { host } = makeFakeHost();
+ await expect(getRemoteAgentProxyEnv(host)).rejects.toThrow();
});
});
describe('reconcileCodexAgentProxyEnv', () => {
- it('no-ops when the marker already matches the desired content', async () => {
- setSshHostAgentProxy('test-host', PREF);
- const desired = buildAgentProxyMarkerContent(17893).trim();
+ it('no-ops when the marker already matches the desired content (tunnel mode)', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
const { host, state } = makeFakeHost({ marker: desired });
const result = await reconcileCodexAgentProxyEnv(host);
expect(result).toEqual({ markerChanged: false, daemonRestarted: false });
@@ -195,16 +208,51 @@ describe('reconcileCodexAgentProxyEnv', () => {
});
it('writes the marker and kills the daemon when drifted', async () => {
- setSshHostAgentProxy('test-host', PREF);
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
const { host, state } = makeFakeHost({ marker: null });
const result = await reconcileCodexAgentProxyEnv(host);
expect(result).toEqual({ markerChanged: true, daemonRestarted: true });
- expect(state.marker).toBe(buildAgentProxyMarkerContent(17893).trim());
+ expect(state.marker).toBe(buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim());
+ expect(state.pkillCount).toBe(1);
+ });
+
+ it('env mode writes the user URL verbatim into the marker', async () => {
+ setSshHostAgentProxy('test-host', { ...ENV_PREF, proxyUrl: 'socks5://10.0.0.5:1080' });
+ const { host, state } = makeFakeHost({ marker: null });
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: true, daemonRestarted: true });
+ expect(state.marker).toContain("export HTTPS_PROXY='socks5://10.0.0.5:1080'");
+ });
+
+ it('defers (no write, no kill) when a live turn is running on the host', async () => {
+ // 漂移生效要重启 daemon → 会断 live turn: 必须推迟, 漂移持久,
+ // turn-done / 下次 session start 补刀。
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ setAgentProxyLiveTurnChecker((hostId) => hostId === 'test-host');
+ const { host, state } = makeFakeHost({ marker: null });
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: false, daemonRestarted: false, deferredForLiveTurn: true });
+ expect(state.marker).toBeNull();
+ expect(state.pkillCount).toBe(0);
+
+ // turn 结束后同一调用点重试 → 正常收敛。
+ setAgentProxyLiveTurnChecker(() => false);
+ const retry = await reconcileCodexAgentProxyEnv(host);
+ expect(retry).toEqual({ markerChanged: true, daemonRestarted: true });
expect(state.pkillCount).toBe(1);
});
+ it('live turn does not defer the fast path (marker already consistent)', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ setAgentProxyLiveTurnChecker(() => true);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host, state } = makeFakeHost({ marker: desired });
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: false, daemonRestarted: false });
+ expect(state.pkillCount).toBe(0);
+ });
+
it('deletes the marker and kills the daemon when the pref is off', async () => {
- // 模块级 prefs cache 跨用例共享 — 显式清除, 模拟 "pref 关闭" 场景。
setSshHostAgentProxy('test-host', null);
const { host, state } = makeFakeHost({ marker: "export HTTPS_PROXY='http://127.0.0.1:17893'" });
const result = await reconcileCodexAgentProxyEnv(host);
@@ -222,9 +270,7 @@ describe('reconcileCodexAgentProxyEnv', () => {
});
it('fails closed when the marker write fails: throws and does not kill the daemon (codex R7 P1)', async () => {
- // exec 对非零退出码 resolve 不 throw — 写失败必须显式挡, 否则 reconcile
- // 继续 pkill, daemon 起来没 marker 直连, fail-closed 破。
- setSshHostAgentProxy('test-host', PREF);
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
const { host, state } = makeFakeHost({ marker: null });
const baseExec = host.exec.bind(host);
host.exec = async (cmd: string, execOpts?: { input?: string }) => {
@@ -252,9 +298,6 @@ describe('reconcileCodexAgentProxyEnv', () => {
});
it('rolls the marker back when pkill fails so the next reconcile retries the kill (codex R10 P2)', async () => {
- // disable 场景 (desired=null, current=旧 proxy marker): pkill 失败时若让
- // marker 停在 null, 下次 reconcile 命中 fast path (null===null) 永不重试
- // kill — 存活 daemon 握着指向已拆隧道的 proxy env 一直跑到手动重启。
setSshHostAgentProxy('test-host', null);
const staleMarker = "export HTTPS_PROXY='http://127.0.0.1:17893'";
const { host, state } = makeFakeHost({ marker: staleMarker });
@@ -284,78 +327,27 @@ describe('reconcileCodexAgentProxyEnv', () => {
const second = await reconcileCodexAgentProxyEnv(host);
expect(second).toEqual({ markerChanged: true, daemonRestarted: true });
expect(state.marker).toBeNull();
- // 两次 reconcile 各发了一次 pkill: 第一次失败 (mock 拦截), 第二次重试成功。
expect(failedPkillCount).toBe(1);
expect(state.pkillCount).toBe(1);
});
- it('closes the old forward only after the daemon restart succeeds during a rebind (codex R17 P2)', async () => {
- // rebind (7890 → 1080): reconcile 先建后拆 — daemon 重启成功后才拆旧。
- setSshHostAgentProxy('test-host', PREF);
+ it('reconnect does not create drift: marker content is static per pref (fixed port)', async () => {
+ // 旧方案的回归靶: 动态端口重连重绑 → marker 漂移 → pkill 正在跑的
+ // daemon。固定端口下同一 pref 的 desired 恒定, 重复 reconcile 恒 fast path。
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
const { host, state } = makeFakeHost({ marker: null });
- // 端口递增分配, 让 rebind 后 desired marker 与旧 marker 不同 (fake 默认
- // 恒 17893 时 marker 内容不变会走 fast path, 测不到拆旧时机)。
- let nextPort = 17893;
- host.ensureRemoteForward = async (spec: { localHost: string; localPort: number }) => {
- const remotePort = nextPort;
- nextPort += 1;
- state.forwards.push({ ...spec, remotePort });
- return { remotePort, close: async () => {} };
- };
- // 先 enable 成功 (旧目标 7890: forward + marker 都就位)。
await reconcileCodexAgentProxyEnv(host);
- expect(state.forwards).toEqual([{ localHost: '127.0.0.1', localPort: 7890, remotePort: 17893 }]);
-
- setSshHostAgentProxy('test-host', { ...PREF, localPort: 1080 });
- const result = await reconcileCodexAgentProxyEnv(host);
- expect(result).toEqual({ markerChanged: true, daemonRestarted: true });
- // daemon 重启成功 → 旧 7890 已拆, 只剩新 1080。
- expect(state.forwards).toEqual([{ localHost: '127.0.0.1', localPort: 1080, remotePort: 17894 }]);
- });
-
- it('keeps the old forward when the daemon survives pkill during a rebind (codex R17 P2)', async () => {
- // rebind + pkill 失败: marker 回滚 (R10), 旧 7890 forward 保留 (存活
- // daemon 流量不断), 新 1080 forward 闲置待下轮 reconcile 复用。
- setSshHostAgentProxy('test-host', PREF);
- const { host, state } = makeFakeHost({ marker: null });
- let nextPort = 17893;
- host.ensureRemoteForward = async (spec: { localHost: string; localPort: number }) => {
- const remotePort = nextPort;
- nextPort += 1;
- state.forwards.push({ ...spec, remotePort });
- return { remotePort, close: async () => {} };
- };
- await reconcileCodexAgentProxyEnv(host);
- const oldMarker = state.marker;
-
- setSshHostAgentProxy('test-host', { ...PREF, localPort: 1080 });
- const baseExec = host.exec.bind(host);
- host.exec = async (cmd: string, execOpts?: { input?: string }) => {
- if (cmd.includes('pkill')) {
- return {
- stdout: '',
- stderr: 'daemon still alive after TERM(5s)+KILL(2s)',
- exitCode: 3,
- signal: null,
- };
- }
- return baseExec(cmd, execOpts);
- };
- const result = await reconcileCodexAgentProxyEnv(host);
- expect(result).toEqual({ markerChanged: true, daemonRestarted: false });
- // marker 回滚到旧值; 旧 7890 保留; 新 1080 闲置 (不拆任何 forward)。
- expect(state.marker).toBe(oldMarker);
- expect(state.forwards).toEqual([
- { localHost: '127.0.0.1', localPort: 7890, remotePort: 17893 },
- { localHost: '127.0.0.1', localPort: 1080, remotePort: 17894 },
- ]);
+ expect(state.pkillCount).toBe(1);
+ for (let i = 0; i < 3; i++) {
+ const again = await reconcileCodexAgentProxyEnv(host);
+ expect(again).toEqual({ markerChanged: false, daemonRestarted: false });
+ }
+ expect(state.pkillCount).toBe(1);
});
});
describe('killRemoteCodexDaemon', () => {
it('waits for the daemon to actually exit after TERM before returning (greptile R6 P2)', async () => {
- // pkill 只保证信号送达 — 脚本必须 TERM 后轮询等进程消失, 没死透再 KILL,
- // 防旧 daemon 在 dying 窗口里响应探活被复用 (旧 env, marker 变更静默落空)。
const { host, state } = makeFakeHost();
const result = await killRemoteCodexDaemon(host);
expect(result).toEqual({ ok: true });
@@ -384,17 +376,20 @@ describe('killRemoteCodexDaemon', () => {
});
});
-describe('applyAgentProxyForHost disable path', () => {
- it('reports apply error when the daemon survives pkill during proxy disable (codex R9 P2)', async () => {
- // 先 enable 建隧道 (marker 已就位)。
- setSshHostAgentProxy('test-host', PREF);
- const { host } = makeFakeHost({ marker: "export HTTPS_PROXY='http://127.0.0.1:17893'" });
+describe('applyAgentProxyForHost', () => {
+ it('env mode: reconcile succeeds and records applied evidence (phase=active)', async () => {
+ // UI 只在确有应用证据时显示「已注入」(R1 review P2) — apply 成功落
+ // phase='active', 未应用/推迟中无状态则渲染等待态。
+ setSshHostAgentProxy('test-host', ENV_PREF);
+ const { host, state } = makeFakeHost({ marker: null });
await applyAgentProxyForHost(host);
- expect(getAgentProxyTunnelState('test-host')?.active).toBe(true);
+ expect(state.marker).toContain("export HTTPS_PROXY='http://127.0.0.1:7890'");
+ expect(getAgentProxyTunnelState('test-host')).toEqual({ phase: 'active' });
+ });
- // disable: 隧道拆 + marker 清, 但 daemon 没死透 — 旧 daemon 还握着指向
- // 已关闭端口的 proxy env, 卡片必须落错误而不是谎称「已关闭」。
+ it('reports apply error when the daemon survives pkill during proxy disable (codex R9 P2)', async () => {
setSshHostAgentProxy('test-host', null);
+ const { host } = makeFakeHost({ marker: "export HTTPS_PROXY='http://127.0.0.1:17893'" });
const baseExec = host.exec.bind(host);
host.exec = async (cmd: string, execOpts?: { input?: string }) => {
if (cmd.includes('pkill')) {
@@ -409,26 +404,30 @@ describe('applyAgentProxyForHost disable path', () => {
};
await applyAgentProxyForHost(host);
const state = getAgentProxyTunnelState('test-host');
- expect(state?.active).toBe(false);
+ expect(state?.phase).toBe('error');
expect(state?.lastError).toMatch(/survived pkill/);
});
+ it('live-turn defer is not an apply error (state untouched, retried at turn-done)', async () => {
+ setSshHostAgentProxy('test-host', ENV_PREF);
+ setAgentProxyLiveTurnChecker(() => true);
+ const { host, state } = makeFakeHost({ marker: null });
+ await applyAgentProxyForHost(host);
+ expect(state.marker).toBeNull();
+ expect(state.pkillCount).toBe(0);
+ // defer 不是失败 — 不落 error 状态。
+ expect(getAgentProxyTunnelState('test-host')?.lastError).toBeUndefined();
+ });
+
it('serializes concurrent reconciles per host so a fast-path caller never probes mid-restart (codex R9 P2)', async () => {
- // 并发 reconcile (两个 transport 的 beforeDaemonProbe 同时触发): 第一个
- // 还在等 killRemoteCodexDaemon 时, 第二个必须排队, 不得走 marker-match
- // fast path 直接去 probe 旧 daemon。
- setSshHostAgentProxy('test-host', PREF);
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
const { host, state } = makeFakeHost({ marker: null });
let killStarted = false;
- // 对象持有 release: TS 不对属性做 closure 收窄 (let 声明会被 narrow 成
- // undefined → CI typecheck TS2349 "Type 'never' has no call signatures")。
const killGate: { release?: () => void } = {};
const baseExec = host.exec.bind(host);
host.exec = async (cmd: string, execOpts?: { input?: string }) => {
if (cmd.includes('pkill')) {
- // 进入 kill-and-wait 即翻牌 (baseExec 的记录要等释放后才有,
- // 不能拿 execCalls 当等待信号)。
killStarted = true;
await new Promise<void>((resolve) => {
killGate.release = resolve;
@@ -442,7 +441,6 @@ describe('applyAgentProxyForHost disable path', () => {
order.push('first-done');
return r;
});
- // 等第一个写完 marker 并卡在 kill-and-wait 阶段。
await vi.waitFor(() => {
expect(killStarted).toBe(true);
});
@@ -450,7 +448,6 @@ describe('applyAgentProxyForHost disable path', () => {
order.push('second-done');
return r;
});
- // 第二个已入队但不得开工: 给它一拍机会, 确认没有第二个 cat/pkill 发生。
await Promise.resolve();
const execCountWhileFirstBlocked = state.execCalls.length;
await Promise.resolve();
@@ -460,69 +457,40 @@ describe('applyAgentProxyForHost disable path', () => {
const [r1, r2] = await Promise.all([first, second]);
expect(r1.markerChanged).toBe(true);
expect(r1.daemonRestarted).toBe(true);
- // 第二个在第一个完成后才走对账: 此时 marker 已一致 → fast path 零副作用。
expect(r2).toEqual({ markerChanged: false, daemonRestarted: false });
expect(order).toEqual(['first-done', 'second-done']);
expect(state.pkillCount).toBe(1);
});
});
-describe('applyAgentProxyForHost enable path', () => {
- it('reports apply error and rolls the marker back when the daemon survives pkill (codex R10 P1)', async () => {
- // marker 漂移 (null → 新 proxy marker) 但 pkill 失败: 旧 daemon 还活着跑
- // 旧 env — 不得按成功落 active, 卡片显示错误; marker 回滚到 null 供下次
- // reconcile 重试。
- setSshHostAgentProxy('test-host', PREF);
- const { host, state } = makeFakeHost({ marker: null });
- const baseExec = host.exec.bind(host);
- host.exec = async (cmd: string, execOpts?: { input?: string }) => {
- if (cmd.includes('pkill')) {
- return {
- stdout: '',
- stderr: 'daemon still alive after TERM(5s)+KILL(2s)',
- exitCode: 3,
- signal: null,
- };
- }
- return baseExec(cmd, execOpts);
- };
- await applyAgentProxyForHost(host);
- const tunnelState = getAgentProxyTunnelState('test-host');
- expect(tunnelState?.active).toBe(false);
- expect(tunnelState?.lastError).toMatch(/survived pkill/);
- // 原 marker 为 null → 回滚即删除。
- expect(state.marker).toBeNull();
+describe('ssh-host-prefs-store agentProxy', () => {
+ it('round-trips a tunnel-mode pref', () => {
+ setSshHostAgentProxy('h1', TUNNEL_PREF);
+ expect(getSshHostAgentProxy('h1')).toEqual(TUNNEL_PREF);
});
-});
-describe('ssh-host-prefs-store agentProxy', () => {
- it('round-trips an enabled pref', () => {
- setSshHostAgentProxy('h1', PREF);
- expect(getSshHostAgentProxy('h1')).toEqual(PREF);
+ it('round-trips an env-mode pref', () => {
+ setSshHostAgentProxy('h1', ENV_PREF);
+ expect(getSshHostAgentProxy('h1')).toEqual(ENV_PREF);
});
it('returns null for disabled / cleared / unknown hosts', () => {
- setSshHostAgentProxy('h1', { ...PREF, enabled: false });
+ setSshHostAgentProxy('h1', { ...TUNNEL_PREF, enabled: false });
expect(getSshHostAgentProxy('h1')).toBeNull();
- setSshHostAgentProxy('h2', PREF);
+ setSshHostAgentProxy('h2', TUNNEL_PREF);
setSshHostAgentProxy('h2', null);
expect(getSshHostAgentProxy('h2')).toBeNull();
expect(getSshHostAgentProxy('never-set')).toBeNull();
});
it('keeps autoConnect when writing agentProxy and vice versa', () => {
- // 双向共存回归 (review: PR #715 五轮审核 P2 — 原测试只写了两次 agentProxy,
- // 没真正交叉 autoConnect): prefs 是同一 JSON 文件里的 sibling 字段,
- // 任一侧写入不得把另一侧冲掉。
setSshHostAutoConnect('h1', true);
- setSshHostAgentProxy('h1', PREF);
+ setSshHostAgentProxy('h1', TUNNEL_PREF);
expect(getSshHostAutoConnect('h1')).toBe(true);
- expect(getSshHostAgentProxy('h1')).toEqual(PREF);
- // 反向: 先写 agentProxy 再改 autoConnect, agentProxy 不丢。
+ expect(getSshHostAgentProxy('h1')).toEqual(TUNNEL_PREF);
setSshHostAutoConnect('h1', false);
- expect(getSshHostAgentProxy('h1')).toEqual(PREF);
+ expect(getSshHostAgentProxy('h1')).toEqual(TUNNEL_PREF);
expect(getSshHostAutoConnect('h1')).toBe(false);
- // 清 agentProxy 不影响 autoConnect。
setSshHostAutoConnect('h1', true);
setSshHostAgentProxy('h1', null);
expect(getSshHostAgentProxy('h1')).toBeNull();
@@ -531,20 +499,252 @@ describe('ssh-host-prefs-store agentProxy', () => {
it('rejects malformed prefs at write time', () => {
expect(() =>
- setSshHostAgentProxy('h1', { enabled: true, localHost: 'bad host', localPort: 7890 }),
+ setSshHostAgentProxy('h1', { ...TUNNEL_PREF, localHost: 'bad host' }),
).toThrow(/invalid agentProxy/);
expect(() =>
- setSshHostAgentProxy('h1', { enabled: true, localPort: 7890, localHost: '127.0.0.1' }),
- ).not.toThrow();
+ setSshHostAgentProxy('h1', { ...TUNNEL_PREF, localPort: 0 }),
+ ).toThrow(/invalid agentProxy/);
+ expect(() =>
+ setSshHostAgentProxy('h1', { ...TUNNEL_PREF, localHost: `12'7.0.0.1` }),
+ ).toThrow(/invalid agentProxy/);
+ // env 模式: 非法 URL / 带引号 / 不支持的 scheme 都拒。
expect(() =>
- setSshHostAgentProxy('h1', { enabled: true, localHost: '127.0.0.1', localPort: 0 }),
+ setSshHostAgentProxy('h1', { ...ENV_PREF, proxyUrl: 'not a url' }),
).toThrow(/invalid agentProxy/);
- // 引号同样拒 (与 IPC / renderer 校验对齐, review: PR #715 copilot R8)。
expect(() =>
- setSshHostAgentProxy('h1', { enabled: true, localHost: `12'7.0.0.1`, localPort: 7890 }),
+ setSshHostAgentProxy('h1', { ...ENV_PREF, proxyUrl: "http://x'y:1" }),
).toThrow(/invalid agentProxy/);
expect(() =>
- setSshHostAgentProxy('h1', { enabled: true, localHost: '12"7.0.0.1', localPort: 7890 }),
+ setSshHostAgentProxy('h1', { ...ENV_PREF, proxyUrl: 'ftp://127.0.0.1:21' }),
).toThrow(/invalid agentProxy/);
+ expect(() =>
+ setSshHostAgentProxy('h1', { ...ENV_PREF, proxyUrl: 'socks5://127.0.0.1:1080' }),
+ ).not.toThrow();
+ });
+});
+
+describe('reconcile × tunnel keeper 集成 (事务边界, R2 review P1/P3)', () => {
+ class FakeTunnelConn {
+ status = 'disconnected';
+ armCalls: Array<Record<string, unknown>> = [];
+ disconnectCount = 0;
+ constructor(public id: string) {}
+ getStatus() {
+ return this.status;
+ }
+ onStatus() {
+ return () => {};
+ }
+ async connect() {
+ this.status = 'ready';
+ }
+ async ensureRemoteForward(spec: Record<string, unknown>) {
+ this.armCalls.push(spec);
+ return { remotePort: spec.preferredRemotePort as number, close: async () => {} };
+ }
+ async exec() {
+ return { stdout: '', stderr: '', exitCode: 10, signal: null };
+ }
+ async disconnect() {
+ this.disconnectCount += 1;
+ this.status = 'disconnected';
+ }
+ }
+
+ let conns: FakeTunnelConn[] = [];
+
+ beforeEach(() => {
+ conns = [];
+ });
+
+ function initKeeperWith(host: { id: string }) {
+ initAgentProxy({
+ broadcast: () => {},
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ createTunnelHost: (cfg) => {
+ const c = new FakeTunnelConn(cfg.id);
+ conns.push(c);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return c as any;
+ },
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ getMainHost: () => host as any,
+ });
+ }
+
+ it('local target 变更 (remotePort 不变) 经 reconcile 迁移隧道, 不重启 daemon', async () => {
+ // marker 只编码远端端口 — 该场景 marker 无漂移, 旧实现会永远沿用旧隧道
+ // (R2 review P1)。
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host, state } = makeFakeHost({ marker: desired });
+ initKeeperWith(host);
+ await reconcileCodexAgentProxyEnv(host);
+ expect(conns).toHaveLength(1);
+ expect(conns[0]!.armCalls[0]).toMatchObject({ localPort: 7890 });
+
+ setSshHostAgentProxy('test-host', { ...TUNNEL_PREF, localPort: 1080 });
+ const result = await reconcileCodexAgentProxyEnv(host);
+ // tunnel-only 迁移: 不写 marker、不杀 daemon。
+ expect(result).toEqual({ markerChanged: false, daemonRestarted: false });
+ expect(state.pkillCount).toBe(0);
+ expect(conns).toHaveLength(2);
+ expect(conns[0]!.disconnectCount).toBe(1);
+ expect(conns[1]!.armCalls[0]).toMatchObject({ localPort: 1080, preferredRemotePort: 17893 });
+ expect(hasPendingAgentProxyReconcile('test-host')).toBe(false);
+ });
+
+ it('tunnel 漂移 (含 local target 变更) 同样受 live-turn gate 保护', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host } = makeFakeHost({ marker: desired });
+ initKeeperWith(host);
+ await reconcileCodexAgentProxyEnv(host);
+ expect(conns).toHaveLength(1);
+
+ setSshHostAgentProxy('test-host', { ...TUNNEL_PREF, localPort: 1080 });
+ setAgentProxyLiveTurnChecker(() => true);
+ const deferred = await reconcileCodexAgentProxyEnv(host);
+ expect(deferred).toMatchObject({ deferredForLiveTurn: true });
+ // 隧道原样不动, pending 记账等 turn-done 补刀。
+ expect(conns).toHaveLength(1);
+ expect(conns[0]!.disconnectCount).toBe(0);
+ expect(hasPendingAgentProxyReconcile('test-host')).toBe(true);
+
+ setAgentProxyLiveTurnChecker(() => false);
+ await reconcileCodexAgentProxyEnv(host);
+ expect(conns).toHaveLength(2);
+ expect(hasPendingAgentProxyReconcile('test-host')).toBe(false);
+ });
+
+ it('marker 写失败时旧隧道原样保留 (迁移在 write/kill 之后)', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host } = makeFakeHost({ marker: desired });
+ initKeeperWith(host);
+ await reconcileCodexAgentProxyEnv(host);
+ expect(conns).toHaveLength(1);
+
+ // 远端端口迁移 17893 → 18000, 但 marker 写失败。
+ setSshHostAgentProxy('test-host', { ...TUNNEL_PREF, remotePort: 18000 });
+ const baseExec = host.exec.bind(host);
+ host.exec = async (cmd: string, execOpts?: { input?: string }) => {
+ if (cmd.includes('cat > "') && cmd.includes('agent-proxy.env')) {
+ return { stdout: '', stderr: 'Read-only file system', exitCode: 1, signal: null };
+ }
+ return baseExec(cmd, execOpts);
+ };
+ await expect(reconcileCodexAgentProxyEnv(host)).rejects.toThrow(/write agent-proxy marker failed/);
+ // 旧隧道未被拆 (R2 review P1), 失败已记 pending (R2 review P2)。
+ expect(conns).toHaveLength(1);
+ expect(conns[0]!.disconnectCount).toBe(0);
+ expect(hasPendingAgentProxyReconcile('test-host')).toBe(true);
+ });
+
+ it('pkill 失败回滚时旧隧道原样保留', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host, state } = makeFakeHost({ marker: desired });
+ initKeeperWith(host);
+ await reconcileCodexAgentProxyEnv(host);
+ expect(conns).toHaveLength(1);
+
+ setSshHostAgentProxy('test-host', { ...TUNNEL_PREF, remotePort: 18000 });
+ const baseExec = host.exec.bind(host);
+ host.exec = async (cmd: string, execOpts?: { input?: string }) => {
+ if (cmd.includes('pkill')) {
+ return {
+ stdout: '',
+ stderr: 'daemon still alive after TERM(5s)+KILL(2s)',
+ exitCode: 3,
+ signal: null,
+ };
+ }
+ return baseExec(cmd, execOpts);
+ };
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: true, daemonRestarted: false });
+ // marker 已回滚, 存活 daemon 仍指旧端口 — 旧隧道保留兜底。
+ expect(state.marker).toBe(desired);
+ expect(conns).toHaveLength(1);
+ expect(conns[0]!.disconnectCount).toBe(0);
+ expect(hasPendingAgentProxyReconcile('test-host')).toBe(true);
+ });
+
+ it('远端端口迁移成功: marker → kill → 隧道迁移的完整事务', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host, state } = makeFakeHost({ marker: desired });
+ initKeeperWith(host);
+ await reconcileCodexAgentProxyEnv(host);
+
+ setSshHostAgentProxy('test-host', { ...TUNNEL_PREF, remotePort: 18000 });
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: true, daemonRestarted: true });
+ expect(state.marker).toBe(buildAgentProxyMarkerContent('http://127.0.0.1:18000').trim());
+ expect(state.pkillCount).toBe(1);
+ expect(conns).toHaveLength(2);
+ expect(conns[0]!.disconnectCount).toBe(1);
+ expect(conns[1]!.armCalls[0]).toMatchObject({ preferredRemotePort: 18000 });
+ expect(hasPendingAgentProxyReconcile('test-host')).toBe(false);
+ });
+
+ it('pref 关闭: daemon 以空 env 重启成功后才拆隧道', async () => {
+ setSshHostAgentProxy('test-host', TUNNEL_PREF);
+ const desired = buildAgentProxyMarkerContent('http://127.0.0.1:17893').trim();
+ const { host, state } = makeFakeHost({ marker: desired });
+ initKeeperWith(host);
+ await reconcileCodexAgentProxyEnv(host);
+ expect(conns).toHaveLength(1);
+
+ setSshHostAgentProxy('test-host', null);
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: true, daemonRestarted: true });
+ expect(state.marker).toBeNull();
+ expect(conns[0]!.disconnectCount).toBe(1);
+ });
+});
+
+describe('ssh-host-prefs-store legacy migration', () => {
+ it('migrates a pre-mode pref ({enabled,localHost,localPort}) to tunnel mode with the legacy fixed port', async () => {
+ // 旧 PR #715 数据形态直接落盘 → 重新加载模块 (绕过内存 cache) 读回。
+ prefsFileContent = JSON.stringify({
+ 'legacy-host': {
+ autoConnect: true,
+ agentProxy: { enabled: true, localHost: '127.0.0.1', localPort: 7890 },
+ },
+ });
+ vi.resetModules();
+ const fresh = await import('../ssh-host-prefs-store');
+ expect(fresh.getSshHostAgentProxy('legacy-host')).toEqual({
+ enabled: true,
+ mode: 'tunnel',
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ remotePort: fresh.LEGACY_AGENT_PROXY_REMOTE_PORT,
+ });
+ expect(fresh.getSshHostAutoConnect('legacy-host')).toBe(true);
+ });
+
+ it('rejects hand-edited invalid agentProxy values instead of silently resurrecting them', async () => {
+ // 用户手编 prefs 写了非法值 (端口 0 / 带引号 host): 迁移时被丢弃为
+ // 「未配置」而不是恢复成可用 pref (review: 迁移边界 — 否则功能看似
+ // 开着实际已静默失效, 连警告都没有)。
+ prefsFileContent = JSON.stringify({
+ 'bad-port-host': {
+ autoConnect: true,
+ agentProxy: { enabled: true, localHost: '127.0.0.1', localPort: 0 },
+ },
+ 'bad-quote-host': {
+ autoConnect: false,
+ agentProxy: { enabled: true, localHost: `12'7.0.0.1`, localPort: 7890 },
+ },
+ });
+ vi.resetModules();
+ const fresh = await import('../ssh-host-prefs-store');
+ expect(fresh.getSshHostAgentProxy('bad-port-host')).toBeNull();
+ expect(fresh.getSshHostAgentProxy('bad-quote-host')).toBeNull();
+ // autoConnect 等兄弟字段不受 agentProxy 非法影响。
+ expect(fresh.getSshHostAutoConnect('bad-port-host')).toBe(true);
});
});
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts
new file mode 100644
index 0000000000..760f5907c7
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts
@@ -0,0 +1,405 @@
+/**
+ * agent-proxy-tunnel 保活器单测。
+ *
+ * 覆盖:
+ * - ensureTunnelUp: 独立连接 connect + 固定端口 arm (exactRemotePort) → active
+ * - 固定端口被占: 连续失败后触发残留监听清理 (protect pid 校验), 清理成功
+ * 立即重试; 清理被拒继续退避
+ * - 主连接不 ready: 保活挂起 (paused), 不空转
+ * - stopTunnelForHost: 拆连接 + 状态清空
+ * - pref 目标变更: 旧连接拆除, 新连接重建
+ *
+ * RemoteHost 用最小 fake; prefs 经 deps.getPref 注入 (不 mock electron)。
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+import {
+ disposeAllTunnels,
+ ensureTunnelForHost,
+ ensureTunnelUp,
+ getTunnelKeeperState,
+ initAgentProxyTunnelKeeper,
+ pauseTunnelForHost,
+ stopTunnelForHost,
+ type TunnelKeeperState,
+} from '../agent-proxy-tunnel';
+import type { SshHostAgentProxyPref } from '../ssh-host-prefs-store';
+
+interface StatusSnap {
+ config: { id: string };
+ status: string;
+ lastError?: string;
+ statusChangedAt: number;
+}
+
+class FakeTunnelConn {
+ status = 'disconnected';
+ listeners = new Set<(snap: StatusSnap) => void>();
+ armCalls: Array<Record<string, unknown>> = [];
+ execCalls: string[] = [];
+ armFailuresRemaining = 0;
+ cleanupExitCode = 10; // no-holder
+ disconnectCount = 0;
+ constructor(public id: string) {}
+ getStatus() {
+ return this.status;
+ }
+ onStatus(cb: (snap: StatusSnap) => void) {
+ this.listeners.add(cb);
+ return () => this.listeners.delete(cb);
+ }
+ emitStatus(status: string, lastError?: string) {
+ this.status = status;
+ for (const cb of [...this.listeners]) {
+ cb({ config: { id: this.id }, status, lastError, statusChangedAt: 0 });
+ }
+ }
+ async connect() {
+ this.status = 'ready';
+ }
+ async ensureRemoteForward(spec: Record<string, unknown>) {
+ this.armCalls.push(spec);
+ if (this.armFailuresRemaining > 0) {
+ this.armFailuresRemaining -= 1;
+ throw new Error('remote port forwarding failed on test-host (tried 127.0.0.1:45000)');
+ }
+ return { remotePort: spec.preferredRemotePort as number, close: async () => {} };
+ }
+ async exec(cmd: string) {
+ this.execCalls.push(cmd);
+ return { stdout: '', stderr: 'declined', exitCode: this.cleanupExitCode, signal: null };
+ }
+ async disconnect() {
+ this.disconnectCount += 1;
+ this.status = 'disconnected';
+ }
+}
+
+const HOST_CFG = {
+ id: 'test-host',
+ hostname: '10.0.0.1',
+ port: 22,
+ user: 'deploy',
+ authMethod: 'agent' as const,
+ source: 'manual' as const,
+};
+
+const TUNNEL_PREF: SshHostAgentProxyPref = {
+ enabled: true,
+ mode: 'tunnel',
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ remotePort: 45000,
+};
+
+function makeHarness(opts: { pref?: SshHostAgentProxyPref | null; mainReady?: boolean } = {}) {
+ const conns: FakeTunnelConn[] = [];
+ const states: Array<TunnelKeeperState | null> = [];
+ const harness = {
+ pref: opts.pref === undefined ? TUNNEL_PREF : opts.pref,
+ mainReady: opts.mainReady ?? true,
+ mainExecResult: { stdout: '4242', stderr: '', exitCode: 0, signal: null },
+ /** 新建隧道连接时的预设钩子 (在首次 arm 前生效)。 */
+ setupConn: (_conn: FakeTunnelConn) => {},
+ conns,
+ states,
+ mainHost: {
+ id: 'test-host',
+ config: HOST_CFG,
+ getStatus: () => (harness.mainReady ? 'ready' : 'disconnected'),
+ exec: async () => harness.mainExecResult,
+ },
+ };
+ initAgentProxyTunnelKeeper({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ createTunnelHost: (cfg) => {
+ const conn = new FakeTunnelConn(cfg.id);
+ harness.setupConn(conn);
+ conns.push(conn);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return conn as any;
+ },
+ getPref: () => harness.pref,
+ isMainHostReady: () => harness.mainReady,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ getMainHost: () => (harness.mainReady ? (harness.mainHost as any) : null),
+ onState: (_hostId, state) => {
+ states.push(state);
+ },
+ logger: { info: () => {}, warn: () => {} },
+ });
+ return harness;
+}
+
+beforeEach(async () => {
+ await disposeAllTunnels();
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ await disposeAllTunnels();
+});
+
+describe('agent-proxy tunnel keeper', () => {
+ it('connects the dedicated conn, arms the fixed port and reports active', async () => {
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const result = await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(result).toEqual({ remotePort: 45000 });
+ expect(h.conns).toHaveLength(1);
+ expect(h.conns[0]!.armCalls[0]).toMatchObject({
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ preferredRemotePort: 45000,
+ exactRemotePort: true,
+ });
+ expect(getTunnelKeeperState('test-host')).toMatchObject({ phase: 'active', remotePort: 45000 });
+ });
+
+ it('does nothing when the pref is off or env-mode', async () => {
+ const h = makeHarness({ pref: null });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any);
+ expect(h.conns).toHaveLength(0);
+ h.pref = { enabled: true, mode: 'env', proxyUrl: 'http://127.0.0.1:7890' };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any);
+ expect(h.conns).toHaveLength(0);
+ });
+
+ it('pauses (no connect attempts) while the main connection is down, resumes on ensure', async () => {
+ const h = makeHarness({ mainReady: false });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any);
+ await vi.waitFor(() => {
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('paused');
+ });
+ expect(h.conns[0]!.armCalls).toHaveLength(0);
+
+ // 主连接恢复 → ready 钩子重新 ensure → 正常建立。
+ h.mainReady = true;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('active');
+ });
+
+ it('retries the busy fixed port, runs stale-listener cleanup after 2 failures, then re-arms', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness();
+ // 前两次 arm 失败 (残留监听占着固定端口); 清理脚本 exit 0 = 已 kill。
+ h.setupConn = (conn) => {
+ conn.armFailuresRemaining = 2;
+ conn.cleanupExitCode = 0;
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const upPromise = ensureTunnelUp(h.mainHost as any, 60_000);
+ upPromise.catch(() => {});
+ // 第一次 arm 失败 (streak 1): 退避等待, 未触发清理。
+ await vi.waitFor(() => {
+ expect(h.conns[0]!.armCalls.length).toBe(1);
+ });
+ expect(h.conns[0]!.execCalls).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(3_000); // 第一档退避
+ // 第二次失败 (streak=2) → 清理触发: 先查主连接 sshd pid, 再在隧道连接
+ // 上跑清理脚本; exit 0 = 已 kill → 立即补跑 (kickPending), 第三次成功。
+ await vi.waitFor(() => {
+ expect(h.conns[0]!.execCalls.length).toBeGreaterThanOrEqual(1);
+ });
+ await vi.advanceTimersByTimeAsync(10);
+ await vi.waitFor(() => {
+ expect(h.conns[0]!.armCalls.length).toBe(3);
+ });
+ await expect(upPromise).resolves.toEqual({ remotePort: 45000 });
+ const cleanupScript = h.conns[0]!.execCalls.join('\n');
+ expect(cleanupScript).toContain('PORT=45000');
+ expect(cleanupScript).toContain('PROTECT=4242');
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('active');
+ });
+
+ it('declined cleanup keeps waiting with backoff instead of killing anything', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness();
+ // 持续失败 + 清理被拒 (exit 11: holder 是控制连接自身 — 比如用户把固定
+ // 端口配成了 MCP 转发口)。
+ h.setupConn = (conn) => {
+ conn.armFailuresRemaining = 99;
+ conn.cleanupExitCode = 11;
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any);
+ await vi.waitFor(() => {
+ expect(h.conns).toHaveLength(1);
+ });
+ const conn = h.conns[0]!;
+ // 走过前两次失败 (0s + 3s) 触发清理, 清理被拒 → 继续退避。
+ await vi.waitFor(() => {
+ expect(conn.armCalls.length).toBeGreaterThanOrEqual(1);
+ });
+ await vi.advanceTimersByTimeAsync(3_000);
+ await vi.waitFor(() => {
+ expect(conn.armCalls.length).toBeGreaterThanOrEqual(2);
+ });
+ await vi.waitFor(() => {
+ expect(conn.execCalls.length).toBeGreaterThanOrEqual(1);
+ });
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('port-busy');
+ // 清理只试一次 (per busy-streak), 不反复 kill。
+ expect(conn.execCalls).toHaveLength(1);
+ });
+
+ it('takes over reconnection with unbounded backoff after the conn reaches failed', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ const conn = h.conns[0]!;
+ const connectSpy = vi.spyOn(conn, 'connect');
+ // RemoteHost 自己的 5 次重连耗尽 → failed; keeper 接管退避重连。
+ conn.emitStatus('failed', 'keepalive timeout');
+ expect(getTunnelKeeperState('test-host')).toMatchObject({ phase: 'error', lastError: 'keepalive timeout' });
+ await vi.advanceTimersByTimeAsync(3_000);
+ await vi.waitFor(() => {
+ expect(connectSpy).toHaveBeenCalled();
+ });
+ await vi.waitFor(() => {
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('active');
+ });
+ });
+
+ it('keeps a live tunnel serving while the main connection is down (pause ≠ teardown)', async () => {
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ h.mainReady = false;
+ pauseTunnelForHost('test-host');
+ // 隧道连接仍 ready + armed: 不拆, 状态保持 active。
+ expect(h.conns[0]!.disconnectCount).toBe(0);
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('active');
+ });
+
+ it('stopTunnelForHost tears down the conn and clears state', async () => {
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ await stopTunnelForHost('test-host');
+ expect(h.conns[0]!.disconnectCount).toBe(1);
+ expect(getTunnelKeeperState('test-host')).toBeNull();
+ expect(h.states[h.states.length - 1]).toBeNull();
+ });
+
+ it('keeps serving the old tunnel when the pref changes without rebuild permission', async () => {
+ // pref 编辑后旧隧道可能还在服务存活 daemon 的流量 — 未获准迁移
+ // (allowRebuild 缺省 false) 时沿用旧隧道, 返回现役真实端口
+ // (R1 review P1: 拆/换隧道与杀 daemon 同级, 只能在 reconcile 的
+ // live-turn gate 后发生)。
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(h.conns).toHaveLength(1);
+ h.pref = { ...TUNNEL_PREF, remotePort: 45001 };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const result = await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(result).toEqual({ remotePort: 45000 });
+ expect(h.conns).toHaveLength(1);
+ expect(h.conns[0]!.disconnectCount).toBe(0);
+ });
+
+ it('rebuilds when the main host connection config changes with the same pref (R3 review P1)', async () => {
+ // hostname/user/port 等连接字段变更后, 旧 entry 的独立连接还连着旧
+ // 机器 — key 含连接指纹, reconcile 的 allowRebuild 迁移必须换新连接。
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(h.conns).toHaveLength(1);
+ h.mainHost.config = { ...HOST_CFG, hostname: '10.0.0.2' };
+ // 未获准迁移时沿用旧连接 (与 pref 变更同语义)。
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(h.conns).toHaveLength(1);
+ // reconcile 路径 (allowRebuild) 迁移到新机器。
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any, { allowRebuild: true });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(h.conns).toHaveLength(2);
+ await vi.waitFor(() => {
+ expect(h.conns[0]!.disconnectCount).toBe(1);
+ });
+ });
+
+ it('late teardown of a replaced entry does not clobber the new active state (R3 review P2)', async () => {
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ const old = h.conns[0]!;
+ // 旧连接 disconnect 拖慢 — 新隧道先 armed, 旧 teardown 后完成。
+ let releaseDisconnect: (() => void) | null = null;
+ old.disconnect = async () => {
+ await new Promise<void>((resolve) => {
+ releaseDisconnect = resolve;
+ });
+ old.disconnectCount += 1;
+ old.status = 'disconnected';
+ };
+ h.pref = { ...TUNNEL_PREF, remotePort: 45001 };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any, { allowRebuild: true });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('active');
+ releaseDisconnect!();
+ await new Promise((r) => setTimeout(r, 20));
+ // 迟到的旧 teardown 不得把新隧道的 active 状态清成 null。
+ expect(h.states[h.states.length - 1]).toMatchObject({ phase: 'active', remotePort: 45001 });
+ expect(getTunnelKeeperState('test-host')?.phase).toBe('active');
+ });
+
+ it('rebuilds the tunnel when the pref target changes and rebuild is allowed (reconcile path)', async () => {
+ const h = makeHarness();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(h.conns).toHaveLength(1);
+ h.pref = { ...TUNNEL_PREF, remotePort: 45001 };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any, { allowRebuild: true });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const result = await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(result).toEqual({ remotePort: 45001 });
+ expect(h.conns).toHaveLength(2);
+ await vi.waitFor(() => {
+ expect(h.conns[0]!.disconnectCount).toBe(1);
+ });
+ expect(h.conns[1]!.armCalls[0]).toMatchObject({ preferredRemotePort: 45001 });
+ });
+
+ it('late in-flight cycle of a stopped entry does not pollute the reported state', async () => {
+ // stop/rebuild 后迟到的旧 cycle 回写会把「已拆除/新 entry」的状态覆盖
+ // 成旧端口 active (R1 review P1) — setState 的 isCurrent 守卫拦截。
+ const h = makeHarness();
+ let releaseArm: (() => void) | null = null;
+ h.setupConn = (conn) => {
+ const baseArm = conn.ensureRemoteForward.bind(conn);
+ conn.ensureRemoteForward = async (spec: Record<string, unknown>) => {
+ // arm 挂起, 等测试显式放行 — 模拟 stop 发生在 arm 在飞期间。
+ await new Promise<void>((resolve) => {
+ releaseArm = resolve;
+ });
+ return baseArm(spec);
+ };
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any);
+ await vi.waitFor(() => {
+ expect(releaseArm).not.toBeNull();
+ });
+ await stopTunnelForHost('test-host');
+ expect(h.states[h.states.length - 1]).toBeNull();
+ releaseArm!();
+ // 给迟到的 cycle 一点时间收尾 — 不得再推任何状态帧。
+ await new Promise((r) => setTimeout(r, 20));
+ expect(h.states[h.states.length - 1]).toBeNull();
+ expect(getTunnelKeeperState('test-host')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts b/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts
new file mode 100644
index 0000000000..1cc3bedcbc
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts
@@ -0,0 +1,560 @@
+/**
+ * agent-proxy-tunnel — 「Cindy 代建隧道」模式的独立 SSH 连接保活器。
+ *
+ * 为什么独立连接而不复用控制面 (ConnectionPool 里的那条):
+ * Agent 的 LLM 流量是持续的大流量 (prompt 上传 + 流式响应, 协同时多
+ * worker 并发), 与 MCP forward / codex ws transport 同连接时会互相拖累 —
+ * 一次拥塞/断链让协同工具与会话控制流陪葬 (用户实测: 同网络下不承载
+ * bulk 流量的连接稳定得多)。隧道断了只影响 LLM 请求 (agent 自己重试),
+ * 控制面毫发无损; 反之亦然。
+ *
+ * 生命周期与保活:
+ * - 只在「主连接 ready + pref 开启 (mode=tunnel)」时保活 — 主连接断开时
+ * 挂起重试 (不空转), 主连接恢复 ready 由 applyAgentProxyForHost 重新
+ * ensure。存活的隧道不因主连接断开而被拆 (它还在服务 LLM 流量)。
+ * - RemoteHost 自带 5 次退避重连; 耗尽进 'failed' 后由本模块以无上限
+ * 退避 (3s→60s cap) 继续拉起, 用户无需任何手动操作。
+ *
+ * 固定端口 (exactRemotePort):
+ * 远端 daemon env 写死 http://127.0.0.1:<remotePort>, 端口漂移 = env 失效
+ * + 必须重启 daemon (断 live turn), 所以被占时**原地等**而不是顺延。
+ * 非干净断链后旧 sshd 会话可能残留占着端口 (远端 sshd 默认无 ClientAlive
+ * 检测): 连续 arm 失败 2 次后尝试定点清理 — 经隧道连接找到监听该端口的
+ * sshd 会话进程, 校验它既不是本连接也不是主控制连接的 sshd 后 kill。
+ * 校验不过 / 工具缺失时退回等待 (远端 TCP 超时后 sshd 自行释放)。
+ * 设计取舍 (产品裁决): 固定端口由用户显式指定, 该端口上「非本连接的
+ * sshd 监听」按残留处理并清理 — 若用户把别的活跃隧道 (另一实例 / 自建
+ * ssh -R) 配在同一端口上, 被清理属预期行为, 端口归属由用户自己保证。
+ *
+ * 生命周期归属 (R1 review P1): 拆除/重建隧道会打断存活 daemon 经它跑的
+ * 流量, 与「不 mid-turn 杀 daemon」同级 — 所以 stop/rebuild 的触发点收敛
+ * 在 agent-proxy 的 reconcile (live-turn gate 之后), 本模块的 ensure 默认
+ * **不** rebuild (allowRebuild=false 时 pref 变化只沿用旧隧道)。
+ */
+
+import type { HostConfig, RemoteHost } from '@cindy/maker-remote-ssh';
+
+import type { AgentProxyTunnelState } from '../../shared/agentProxyConfig.js';
+import type { SshHostAgentProxyPref } from './ssh-host-prefs-store.js';
+
+/** 保活器汇报的状态就是 UI 状态本身 (类型真源在 shared)。 */
+export type TunnelKeeperState = AgentProxyTunnelState;
+
+interface TunnelKeeperLogger {
+ info(msg: string, meta?: Record<string, unknown>): void;
+ warn(msg: string, meta?: Record<string, unknown>): void;
+}
+
+export interface TunnelKeeperDeps {
+ /** 用主 host 的 config 起一条隧道专用 RemoteHost (共享 host key store)。 */
+ createTunnelHost: (cfg: HostConfig) => RemoteHost;
+ getPref: (hostId: string) => SshHostAgentProxyPref | null;
+ /** 主控制连接是否 ready — 保活的前提 (不 ready 时挂起重试)。 */
+ isMainHostReady: (hostId: string) => boolean;
+ /** 主控制连接实例 (残留监听清理需要在它上面查自己的 sshd pid)。 */
+ getMainHost: (hostId: string) => RemoteHost | null;
+ /** 状态推送 (UI 卡片); null = 已拆除。 */
+ onState: (hostId: string, state: TunnelKeeperState | null) => void;
+ logger: TunnelKeeperLogger;
+}
+
+/** 重试退避表 (ms); 超出取末位。无上限次数 — 保活到 pref 关闭/主连接断开。 */
+const RETRY_BACKOFF_MS = [3_000, 5_000, 10_000, 20_000, 30_000, 60_000];
+/** 连续 arm 失败达到该次数后尝试一次残留监听清理。 */
+const STALE_CLEANUP_AFTER_FAILURES = 2;
+/** ensureTunnelUp 缺省等待上限。 */
+const DEFAULT_ENSURE_UP_TIMEOUT_MS = 20_000;
+
+interface Waiter {
+ resolve: (v: { remotePort: number }) => void;
+ reject: (e: Error) => void;
+ timer: NodeJS.Timeout;
+}
+
+interface Entry {
+ hostId: string;
+ /** pref 快照键 — 变化时整条隧道重建。 */
+ key: string;
+ localHost: string;
+ localPort: number;
+ remotePort: number;
+ conn: RemoteHost;
+ offStatus: () => void;
+ desired: boolean;
+ paused: boolean;
+ cycleRunning: boolean;
+ /** cycle 进行中收到的 kick — 收尾后立即补跑一轮, 不丢事件。 */
+ kickPending: boolean;
+ retryTimer: NodeJS.Timeout | null;
+ backoffIdx: number;
+ armFailStreak: number;
+ /** 本轮 busy-streak 内是否已尝试过残留清理 (成功 arm 后复位)。 */
+ staleCleanupTried: boolean;
+ waiters: Waiter[];
+ state: TunnelKeeperState;
+}
+
+let deps: TunnelKeeperDeps | null = null;
+const entries = new Map<string, Entry>();
+
+export function initAgentProxyTunnelKeeper(d: TunnelKeeperDeps): void {
+ deps = d;
+}
+
+/**
+ * keeper 是否已装配 (app 启动期 registerRemoteSshIpc 完成 initAgentProxy
+ * 之后恒为 true)。reconcile 的 fail-closed 隧道校验以此为闸 — 未装配时
+ * (单测 / 极早期启动) 跳过, 不把「keeper 还没 init」误报成隧道故障。
+ */
+export function isAgentProxyTunnelKeeperInitialized(): boolean {
+ return deps != null;
+}
+
+/**
+ * entry 身份键 = 主机连接指纹 + 隧道目标。主机连接字段 (hostname/port/
+ * user/auth/identityFile) 变更后, 旧 entry 的独立连接还连着**旧机器** —
+ * 不进 key 的话 reconcile 会认为无漂移而继续复用, 新机器上的 agent env
+ * 指着一个不存在的 listener, fail-closed 校验也校验错了主机
+ * (R3 review P1)。
+ */
+function entryKey(
+ cfg: HostConfig,
+ pref: Extract<SshHostAgentProxyPref, { mode: 'tunnel' }>,
+): string {
+ return [
+ cfg.hostname,
+ cfg.port,
+ cfg.user,
+ cfg.authMethod,
+ cfg.identityFile ?? '',
+ pref.localHost,
+ pref.localPort,
+ pref.remotePort,
+ ].join('|');
+}
+
+/**
+ * 现役隧道与「pref 目标 + 主机连接配置」是否已脱节 (需要迁移)。marker 只
+ * 编码远端端口 — localHost/localPort 或主机连接字段变更都不产生 marker
+ * 漂移, reconcile 用本判定把「隧道漂移」纳入同一个 live-turn gate
+ * (R2/R3 review P1)。无现役 entry 时返回 false (ensureTunnelUp 会按当前
+ * pref 直接新建, 无迁移语义)。
+ */
+export function tunnelNeedsRebuild(
+ mainHost: RemoteHost,
+ pref: SshHostAgentProxyPref | null,
+): boolean {
+ if (!pref?.enabled || pref.mode !== 'tunnel') return false;
+ const entry = entries.get(mainHost.id);
+ return entry != null && entry.key !== entryKey(mainHost.config, pref);
+}
+
+function setState(entry: Entry, state: TunnelKeeperState): void {
+ entry.state = state;
+ // stop/rebuild 后迟到的 in-flight cycle 回写不得污染「已拆除」或新 entry
+ // 的对外状态 (R1 review P1): 只有仍在登记表里的 entry 才对外汇报。
+ if (entries.get(entry.hostId) !== entry) return;
+ try {
+ deps?.onState(entry.hostId, state);
+ } catch {
+ /* state push must not break the keeper */
+ }
+}
+
+/** entry 是否仍是该 host 的现役登记 (stop/rebuild 后为 false)。 */
+function isCurrent(entry: Entry): boolean {
+ return entries.get(entry.hostId) === entry;
+}
+
+function settleWaiters(entry: Entry, err: Error | null): void {
+ const ws = entry.waiters.splice(0);
+ for (const w of ws) {
+ clearTimeout(w.timer);
+ if (err) w.reject(err);
+ else w.resolve({ remotePort: entry.remotePort });
+ }
+}
+
+/**
+ * 主入口 (幂等): pref=tunnel 且开启 → 确保隧道在保活; pref 关/env 模式则
+ * 不动现有隧道 (拆除是 reconcile 在 live-turn gate 后的职责)。
+ *
+ * allowRebuild: pref 目标变化时是否拆旧建新。**默认 false** — 旧隧道可能
+ * 还在服务存活 daemon 的流量, 只有 reconcile 确认无 live turn 并要重启
+ * daemon 时才允许迁移 (R1 review P1); 其余调用方 (ready 钩子 resume /
+ * CC env 注入 / one-shot) 沿用现役隧道。
+ */
+export function ensureTunnelForHost(
+ mainHost: RemoteHost,
+ opts?: { allowRebuild?: boolean },
+): void {
+ if (!deps) return;
+ const pref = deps.getPref(mainHost.id);
+ if (!pref?.enabled || pref.mode !== 'tunnel') return;
+ const key = entryKey(mainHost.config, pref);
+ let entry = entries.get(mainHost.id);
+ if (entry && entry.key !== key) {
+ if (!opts?.allowRebuild) {
+ // pref 已变但未获准迁移: 沿用旧隧道 (env/marker 仍指旧端口, 语义
+ // 自洽), reconcile 会在安全时机完成迁移。
+ entry.desired = true;
+ entry.paused = false;
+ kick(entry);
+ return;
+ }
+ void stopTunnelForHost(mainHost.id);
+ entry = undefined;
+ }
+ if (!entry) {
+ const conn = deps.createTunnelHost(mainHost.config);
+ const created: Entry = {
+ hostId: mainHost.id,
+ key,
+ localHost: pref.localHost,
+ localPort: pref.localPort,
+ remotePort: pref.remotePort,
+ conn,
+ offStatus: () => {},
+ desired: true,
+ paused: false,
+ cycleRunning: false,
+ kickPending: false,
+ retryTimer: null,
+ backoffIdx: 0,
+ armFailStreak: 0,
+ staleCleanupTried: false,
+ waiters: [],
+ state: { phase: 'connecting', remotePort: pref.remotePort },
+ };
+ created.offStatus = conn.onStatus((snap) => handleConnStatus(created, snap.status, snap.lastError));
+ entries.set(mainHost.id, created);
+ entry = created;
+ }
+ entry.desired = true;
+ entry.paused = false;
+ kick(entry);
+}
+
+/** 主连接断开: 挂起重试 (存活隧道不拆 — 它可能还在正常服务)。 */
+export function pauseTunnelForHost(hostId: string): void {
+ const entry = entries.get(hostId);
+ if (!entry) return;
+ entry.paused = true;
+ clearRetry(entry);
+ // phase==='active' 蕴含「forward 已 arm 且隧道连接 ready」— 存活隧道保持
+ // active 展示, 其余翻 paused。
+ if (entry.state.phase !== 'active') {
+ setState(entry, { phase: 'paused', remotePort: entry.remotePort, lastError: entry.state.lastError });
+ }
+}
+
+/** 彻底拆除 (pref 关闭 / mode 切换 / host 删除 / app 退出)。幂等。 */
+export async function stopTunnelForHost(hostId: string): Promise<void> {
+ const entry = entries.get(hostId);
+ if (!entry) return;
+ entries.delete(hostId);
+ entry.desired = false;
+ clearRetry(entry);
+ entry.offStatus();
+ settleWaiters(entry, new Error('agent-proxy tunnel torn down'));
+ // 状态清空在 disconnect **之前**同步推送: rebuild 场景新 entry 随后创建
+ // 并推 connecting/active, 若把 null 推迟到 disconnect 完成后, 迟到的
+ // null 会把新隧道的 active 状态清掉 (R3 review P2)。
+ try {
+ deps?.onState(hostId, null);
+ } catch {
+ /* ignore */
+ }
+ try {
+ await entry.conn.disconnect();
+ } catch {
+ /* already dead */
+ }
+}
+
+export async function disposeAllTunnels(): Promise<void> {
+ await Promise.all(Array.from(entries.keys()).map((id) => stopTunnelForHost(id)));
+}
+
+/** 当前保活态 (诊断/测试)。 */
+export function getTunnelKeeperState(hostId: string): TunnelKeeperState | null {
+ return entries.get(hostId)?.state ?? null;
+}
+
+/**
+ * 等待隧道就绪 (session 路径: CC env 注入 / one-shot quick test)。
+ * 不在保活中会先 ensure; 超时/拆除时 reject。
+ */
+export function ensureTunnelUp(
+ mainHost: RemoteHost,
+ timeoutMs = DEFAULT_ENSURE_UP_TIMEOUT_MS,
+): Promise<{ remotePort: number }> {
+ ensureTunnelForHost(mainHost);
+ const entry = entries.get(mainHost.id);
+ if (!entry) {
+ return Promise.reject(new Error('agent-proxy tunnel pref is not enabled (mode=tunnel)'));
+ }
+ if (entry.state.phase === 'active') {
+ return Promise.resolve({ remotePort: entry.remotePort });
+ }
+ return new Promise<{ remotePort: number }>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ const idx = entry.waiters.findIndex((w) => w.timer === timer);
+ if (idx >= 0) entry.waiters.splice(idx, 1);
+ reject(
+ new Error(
+ `agent-proxy tunnel not ready within ${timeoutMs}ms (${entry.state.phase}${entry.state.lastError ? `: ${entry.state.lastError}` : ''})`,
+ ),
+ );
+ }, timeoutMs);
+ timer.unref?.();
+ entry.waiters.push({ resolve, reject, timer });
+ });
+}
+
+// ── 保活循环 ────────────────────────────────────────────────────────────────
+
+function clearRetry(entry: Entry): void {
+ if (entry.retryTimer) {
+ clearTimeout(entry.retryTimer);
+ entry.retryTimer = null;
+ }
+}
+
+function scheduleRetry(entry: Entry): void {
+ if (!isCurrent(entry) || !entry.desired || entry.paused) return;
+ clearRetry(entry);
+ const delay = RETRY_BACKOFF_MS[Math.min(entry.backoffIdx, RETRY_BACKOFF_MS.length - 1)];
+ entry.backoffIdx += 1;
+ entry.retryTimer = setTimeout(() => {
+ entry.retryTimer = null;
+ kick(entry);
+ }, delay);
+ entry.retryTimer.unref?.();
+}
+
+function handleConnStatus(entry: Entry, status: string, lastError?: string): void {
+ if (!entry.desired) return;
+ if (status === 'ready') {
+ // RemoteHost 自己的 rearmForwards 会尝试重挂; kick 里的 ensure 幂等对齐。
+ clearRetry(entry);
+ kick(entry);
+ return;
+ }
+ if (status === 'failed') {
+ // RemoteHost 内部 5 次重连耗尽 — 本模块接管无上限退避。
+ setState(entry, { phase: 'error', remotePort: entry.remotePort, lastError });
+ scheduleRetry(entry);
+ return;
+ }
+ if (status === 'connecting' || status === 'reconnecting') {
+ setState(entry, { phase: 'connecting', remotePort: entry.remotePort });
+ }
+}
+
+function kick(entry: Entry): void {
+ if (!isCurrent(entry) || !entry.desired || entry.paused) return;
+ if (entry.cycleRunning) {
+ // cycle 正在跑 (或在收尾的微任务窗口里): 不能丢 kick — resume/ready
+ // 事件撞上收尾窗口被静默吞掉的话, 隧道会停在旧状态等下一个事件才动。
+ // 记 pending, finally 里补跑。
+ entry.kickPending = true;
+ return;
+ }
+ entry.cycleRunning = true;
+ void runCycle(entry)
+ .catch(() => {
+ /* runCycle 自己收口所有错误 — 这里只兜底 */
+ })
+ .finally(() => {
+ entry.cycleRunning = false;
+ if (entry.kickPending) {
+ entry.kickPending = false;
+ kick(entry);
+ }
+ });
+}
+
+async function runCycle(entry: Entry): Promise<void> {
+ if (!deps) return;
+ if (!deps.isMainHostReady(entry.hostId)) {
+ // 主连接不在 — 挂起, 主连接 ready 钩子会重新 ensure。存活隧道
+ // (phase==='active') 保持展示, 不翻 paused。
+ entry.paused = true;
+ if (entry.state.phase !== 'active') {
+ setState(entry, { phase: 'paused', remotePort: entry.remotePort });
+ }
+ return;
+ }
+ if (entry.conn.getStatus() !== 'ready') {
+ setState(entry, { phase: 'connecting', remotePort: entry.remotePort });
+ try {
+ await entry.conn.connect();
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ setState(entry, { phase: 'error', remotePort: entry.remotePort, lastError: msg });
+ scheduleRetry(entry);
+ return;
+ }
+ // stop/rebuild 可能发生在 connect 在飞期间 — 孤儿 entry 不再继续
+ // (setState/scheduleRetry 也有各自的 isCurrent 守卫兜底)。
+ if (!isCurrent(entry) || !entry.desired || entry.paused) return;
+ }
+ try {
+ await entry.conn.ensureRemoteForward({
+ localHost: entry.localHost,
+ localPort: entry.localPort,
+ preferredRemotePort: entry.remotePort,
+ exactRemotePort: true,
+ });
+ } catch (err) {
+ // stop/rebuild 后的孤儿 cycle 不得继续 — 尤其不能再跑残留监听清理
+ // (远端 kill 副作用): 用户可能已关闭 proxy / 切走端口, 授权已收回
+ // (R2 review P2)。
+ if (!isCurrent(entry) || !entry.desired) return;
+ const msg = err instanceof Error ? err.message : String(err);
+ entry.armFailStreak += 1;
+ deps.logger.warn('agent-proxy tunnel arm failed', {
+ hostId: entry.hostId,
+ remotePort: entry.remotePort,
+ streak: entry.armFailStreak,
+ error: msg,
+ });
+ setState(entry, { phase: 'port-busy', remotePort: entry.remotePort, lastError: msg });
+ if (entry.armFailStreak >= STALE_CLEANUP_AFTER_FAILURES && !entry.staleCleanupTried) {
+ entry.staleCleanupTried = true;
+ const cleaned = await tryCleanupStaleListener(entry).catch(() => false);
+ if (cleaned) {
+ // 立即重试一次, 不吃退避 (cycle 内 kick 记 pending, finally 补跑)。
+ setState(entry, { phase: 'connecting', remotePort: entry.remotePort });
+ entry.backoffIdx = 0;
+ kick(entry);
+ return;
+ }
+ }
+ scheduleRetry(entry);
+ return;
+ }
+ if (!isCurrent(entry) || !entry.desired) return; // arm 在飞期间被 stop/rebuild
+ entry.backoffIdx = 0;
+ entry.armFailStreak = 0;
+ entry.staleCleanupTried = false;
+ setState(entry, { phase: 'active', remotePort: entry.remotePort });
+ settleWaiters(entry, null);
+ deps.logger.info('agent-proxy tunnel armed', {
+ hostId: entry.hostId,
+ remotePort: entry.remotePort,
+ localTarget: `${entry.localHost}:${entry.localPort}`,
+ });
+}
+
+// ── 残留监听清理 ────────────────────────────────────────────────────────────
+
+/**
+ * 在主控制连接上查出它自己的会话 sshd pid (清理脚本的保护名单):
+ * 隧道端口若被主连接上的其他 forward (如用户把固定端口配成了 MCP 转发口)
+ * 占用, kill 那个 sshd 等于杀掉整个控制连接 — 必须排除。
+ * 查不出来 (工具缺失等) 返回 null, 调用方放弃清理 (保守优先)。
+ */
+async function lookupSessionSshdPid(host: RemoteHost): Promise<string | null> {
+ const script = `
+P=$$
+i=0
+while [ $i -lt 8 ]; do
+ PP=$(awk '{print $4}' "/proc/$P/stat" 2>/dev/null) || exit 1
+ [ -z "$PP" ] && exit 1
+ C=$(ps -o comm= -p "$PP" 2>/dev/null | tr -d ' ')
+ case "$C" in sshd|sshd-session) printf '%s' "$PP"; exit 0;; esac
+ [ "$PP" = "1" ] && exit 1
+ P=$PP
+ i=$((i+1))
+done
+exit 1
+`;
+ try {
+ const result = await host.exec(`bash -c ${shellQuote(script)}`, {
+ timeoutMs: 10_000,
+ label: 'agent-proxy-lookup-sshd-pid',
+ });
+ const pid = result.stdout.trim();
+ return result.exitCode === 0 && /^[0-9]+$/.test(pid) ? pid : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * 定点清理占着固定端口的残留 sshd 会话。全部校验通过才 kill:
+ * - 端口确有监听者且能解析出 pid (ss 可用);
+ * - 监听者进程是 sshd / sshd-session (非 root 本来也只能杀自己用户的);
+ * - 监听者不在本连接自身的进程链上, 也不是主控制连接的会话 sshd。
+ * 返回 true = 已 kill (调用方立即重试 arm); false = 未清理 (继续退避等待,
+ * 远端 TCP 超时后 sshd 会自行释放)。
+ */
+async function tryCleanupStaleListener(entry: Entry): Promise<boolean> {
+ if (!deps) return false;
+ const mainHost = deps.getMainHost(entry.hostId);
+ if (!mainHost || mainHost.getStatus() !== 'ready') return false;
+ const protectPid = await lookupSessionSshdPid(mainHost);
+ if (!protectPid) {
+ deps.logger.warn('agent-proxy stale-listener cleanup skipped: cannot resolve control-connection sshd pid', {
+ hostId: entry.hostId,
+ remotePort: entry.remotePort,
+ });
+ return false;
+ }
+ // PORT/PROTECT 都是内部产生的纯数字, 直接内插安全 (双保险再校验一次)。
+ if (!/^[0-9]+$/.test(protectPid) || !Number.isInteger(entry.remotePort)) return false;
+ const script = `
+PORT=${entry.remotePort}
+PROTECT=${protectPid}
+HOLDER=$(ss -H -tlnp "sport = :$PORT" 2>/dev/null | grep -o 'pid=[0-9]*' | head -n1 | cut -d= -f2)
+if [ -z "$HOLDER" ]; then echo "no-holder" >&2; exit 10; fi
+if [ "$HOLDER" = "$PROTECT" ]; then echo "holder-is-control-connection" >&2; exit 11; fi
+C=$(ps -o comm= -p "$HOLDER" 2>/dev/null | tr -d ' ')
+case "$C" in sshd|sshd-session) ;; *) echo "holder-not-sshd:$C" >&2; exit 12;; esac
+P=$$
+i=0
+while [ $i -lt 8 ]; do
+ PP=$(awk '{print $4}' "/proc/$P/stat" 2>/dev/null) || break
+ [ -z "$PP" ] && break
+ if [ "$PP" = "$HOLDER" ]; then echo "holder-is-self-chain" >&2; exit 13; fi
+ [ "$PP" = "1" ] && break
+ P=$PP
+ i=$((i+1))
+done
+kill "$HOLDER" 2>/dev/null || { echo "kill-failed" >&2; exit 14; }
+exit 0
+`;
+ try {
+ const result = await entry.conn.exec(`bash -c ${shellQuote(script)}`, {
+ timeoutMs: 10_000,
+ label: 'agent-proxy-cleanup-stale-listener',
+ });
+ if (result.exitCode === 0) {
+ deps.logger.info('agent-proxy stale listener killed, retrying fixed-port bind', {
+ hostId: entry.hostId,
+ remotePort: entry.remotePort,
+ });
+ return true;
+ }
+ deps.logger.warn('agent-proxy stale-listener cleanup declined', {
+ hostId: entry.hostId,
+ remotePort: entry.remotePort,
+ exitCode: result.exitCode,
+ reason: result.stderr.trim().slice(0, 120),
+ });
+ return false;
+ } catch (err) {
+ deps.logger.warn('agent-proxy stale-listener cleanup failed', {
+ hostId: entry.hostId,
+ remotePort: entry.remotePort,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return false;
+ }
+}
+
+function shellQuote(s: string): string {
+ return `'${s.replace(/'/g, `'\\''`)}'`;
+}
diff --git a/apps/desktop/src/main/remote-ssh/agent-proxy.ts b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
index 5f187b720b..ef00d4db5c 100644
--- a/apps/desktop/src/main/remote-ssh/agent-proxy.ts
+++ b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
@@ -1,18 +1,27 @@
/**
- * agent-proxy —— 「Agent 流量经 SSH 隧道走本地 Proxy」的策略层。
+ * agent-proxy —— 「Agent 流量走 Proxy」的策略层。两种模式 (pref.mode):
*
- * 链路与职责切分:
+ * mode='tunnel' (Cindy 代建隧道, 固定端口):
+ * 远端 codex daemon / claude CLI
+ * │ HTTPS_PROXY=http://127.0.0.1:<remotePort> (env 注入, remotePort 固定)
+ * ▼
+ * 远端 127.0.0.1:<remotePort> (sshd remote forwarding, ssh -R)
+ * │ **独立的** SSH 隧道连接 (agent-proxy-tunnel.ts 保活)
+ * ▼
+ * 本机 pipe → 用户自己的本地 Proxy (如 127.0.0.1:7890)
*
- * 远端 codex daemon / claude CLI
- * │ HTTPS_PROXY=http://127.0.0.1:<remotePort> (env 注入)
- * ▼
- * 远端 127.0.0.1:<remotePort> (sshd remote forwarding, ssh -R)
- * │ SSH 连接内多路复用 channel (RemoteHost.ensureRemoteForward)
- * ▼
- * 本机 pipe → 用户自己的本地 Proxy (如 127.0.0.1:7890)
+ * mode='env' (仅注入环境变量):
+ * 远端 agent env 直接指向用户给的 proxyUrl (远端可达: 远端本机代理 /
+ * 局域网代理 / 用户自建 autossh 隧道)。Cindy 不建任何隧道。
*
- * Cindy 不提供 Proxy, 只提供隧道。域名解析发生在用户 Proxy 那一端
- * (HTTP CONNECT 语义), 远端完全不需要能解 chatgpt.com / api.anthropic.com。
+ * 与旧方案 (PR #715, 动态端口 + 控制面连接承载) 的两个关键差异:
+ * 1. env 是**静态**的 — 只随用户改设置而变, SSH 重连不再触发 marker
+ * 漂移 / daemon 重启 (旧方案重连端口重绑会 pkill 正在跑的 daemon)。
+ * 2. bulk 流量走独立连接 — 控制面 (MCP forward / codex ws transport)
+ * 不再与 LLM 大流量同命。
+ *
+ * Cindy 不提供 Proxy, 只提供通路。域名解析发生在用户 Proxy 那一端
+ * (HTTP CONNECT 语义), 远端不需要能解 chatgpt.com / api.anthropic.com。
*
* 两个 agent 的 env 注入方式不同:
* - claude-code: cc-mgr daemon 按 session spawn SDK, startParams.env 每
@@ -21,26 +30,32 @@
* 生效。所以写一个 marker 文件 ($INSTALL_ROOT/agent-proxy.env),
* daemon wrapper 启动前 source 它; marker 漂移时 pkill daemon
* (daemon version 探活失败 → 下次 transport bootstrap 重新拉起,
- * 与 auth sync 的 daemonRestart 同套路)。
+ * 与 auth sync 的 daemonRestart 同套路)。marker 漂移只会由用户改
+ * 设置触发; 若此刻 host 上有 live turn, 对账推迟 (turn-done 与下次
+ * session start 的 reconcile 都会补刀), 不 mid-turn 杀 daemon。
*/
-import {
- REMOTE_AGENT_PROXY_ENV_PATH,
- REMOTE_INSTALL_ROOT,
- type RemoteHost,
-} from '@cindy/maker-remote-ssh';
+import type { HostConfig, RemoteHost } from '@cindy/maker-remote-ssh';
+import { REMOTE_AGENT_PROXY_ENV_PATH, REMOTE_INSTALL_ROOT } from '@cindy/maker-remote-ssh';
+import type { AgentProxyTunnelState } from '../../shared/agentProxyConfig.js';
import { createLogger } from '../logger.js';
-import { getSshHostAgentProxy } from './ssh-host-prefs-store.js';
+import {
+ ensureTunnelForHost,
+ ensureTunnelUp,
+ initAgentProxyTunnelKeeper,
+ isAgentProxyTunnelKeeperInitialized,
+ pauseTunnelForHost,
+ stopTunnelForHost,
+ tunnelNeedsRebuild,
+} from './agent-proxy-tunnel.js';
+import { getSshHostAgentProxy, type SshHostAgentProxyPref } from './ssh-host-prefs-store.js';
const log = createLogger('remote-ssh/agent-proxy');
-/** UI 展示用的隧道实时状态 (内存态, 不持久化)。 */
-export interface AgentProxyTunnelState {
- active: boolean;
- remotePort?: number;
- lastError?: string;
-}
+// UI 展示用的实时状态 (内存态, 不持久化)。类型真源在 shared (preload /
+// renderer 共用), 这里 re-export 保持既有引用点不变。
+export type { AgentProxyTunnelState };
const tunnelStates = new Map<string, AgentProxyTunnelState>();
@@ -48,53 +63,111 @@ export function getAgentProxyTunnelState(hostId: string): AgentProxyTunnelState
return tunnelStates.get(hostId) ?? null;
}
-/** host 删除时同步清掉内存态。 */
+/** host 删除时同步清掉内存态 + 拆隧道。 */
export function clearAgentProxyTunnelState(hostId: string): void {
tunnelStates.delete(hostId);
+ void stopTunnelForHost(hostId);
+}
+
+/**
+ * 主控制连接断开时的处理: 隧道保活挂起 (不空转重试), 但**存活的隧道不拆**
+ * — 独立连接可能还在正常服务 LLM 流量, 主连接的断链不该牵连它。主连接
+ * 恢复 ready 后 applyAgentProxyForHost 会恢复保活。
+ */
+export function handleAgentProxyMainHostDown(hostId: string): void {
+ pauseTunnelForHost(hostId);
}
/**
- * 断连时把隧道标记为非活跃 (review: PR #715 copilot R3): 状态只在内存,
- * 断连后 forward 已 disarm, UI 不应继续显示「已建立」。愿望仍在 —
- * reconnect ready 时 applyAgentProxyForHost 会重建并重新标活跃。
- * 仅在确实有 active 记录时动作 (避免无意义 broadcast 刷屏)。
+ * 用户**显式**断开 (Settings → Disconnect) 时拆除隧道: 该动作的语义是
+ * 「切断这台机器的全部 SSH 连通」, 独立隧道连接也算 (review: PR #992
+ * codex-connector P1)。与断线/重连的 pause 路径区分 — 那种是网络抖动,
+ * 存活隧道值得保留; 用户点断开则是明确授权终结。
*/
-export function markAgentProxyTunnelInactive(hostId: string): void {
- const cur = tunnelStates.get(hostId);
- if (!cur?.active) return;
- tunnelStates.set(hostId, { active: false });
- emitState(hostId);
+export async function teardownAgentProxyOnUserDisconnect(hostId: string): Promise<void> {
+ await stopTunnelForHost(hostId);
}
-// broadcast 由 index.ts 注入 (避免循环依赖): 隧道状态变化后推一版
-// status snapshot 给 renderer, HostSnapshotWithPrefs 会带上最新 tunnel state。
+// broadcast 由 index.ts 注入 (避免循环依赖): 状态变化后推一版 status
+// snapshot 给 renderer, HostSnapshotWithPrefs 会带上最新 tunnel state。
let broadcaster: ((hostId: string) => void) | null = null;
-export function initAgentProxy(deps: { broadcast: (hostId: string) => void }): void {
+
+export function initAgentProxy(deps: {
+ broadcast: (hostId: string) => void;
+ /** 用主 host 的 config 起隧道专用 RemoteHost (共享 host key store)。 */
+ createTunnelHost: (cfg: HostConfig) => RemoteHost;
+ getMainHost: (hostId: string) => RemoteHost | null;
+}): void {
broadcaster = deps.broadcast;
+ const { getMainHost } = deps;
+ initAgentProxyTunnelKeeper({
+ createTunnelHost: deps.createTunnelHost,
+ getPref: (hostId) => getSshHostAgentProxy(hostId),
+ isMainHostReady: (hostId) => getMainHost(hostId)?.getStatus() === 'ready',
+ getMainHost,
+ onState: (hostId, state) => {
+ if (!state) tunnelStates.delete(hostId);
+ else tunnelStates.set(hostId, state);
+ emitState(hostId);
+ },
+ logger: log,
+ });
}
+
function emitState(hostId: string): void {
try {
broadcaster?.(hostId);
} catch { /* broadcast must not throw into ssh paths */ }
}
+// ── live-turn 守卫 (marker 对账不 mid-turn 杀 daemon) ───────────────────────
+
+/**
+ * codex 远端 live-turn 判定 — maker-ipc/register.ts 装配 (真源是 agent
+ * input coordinator)。未装配时视为无 live turn (与历史行为一致; 装配点
+ * 在 IPC 注册期, 早于任何 session 路径)。
+ */
+let liveTurnChecker: ((hostId: string) => boolean) | null = null;
+
+export function setAgentProxyLiveTurnChecker(fn: (hostId: string) => boolean): void {
+ liveTurnChecker = fn;
+}
+
+/**
+ * 对账被推迟/未完成的 host 集合 — turn-done 挂钩据此决定要不要补刀,
+ * 避免每次 turn 结束都白付一次远端 marker cat RTT (稳态下 marker 不漂移)。
+ * 成员在 reconcile 的 defer / pkill 失败路径加入, 收敛成功后移除。
+ */
+const pendingReconcileHosts = new Set<string>();
+
+export function hasPendingAgentProxyReconcile(hostId: string): boolean {
+ return pendingReconcileHosts.has(hostId);
+}
+
/* ============================== env 构造 ============================== */
+/** pref → 远端 agent 应使用的代理 URL (env 模式原样; tunnel 模式固定端口)。 */
+export function resolveAgentProxyUrl(pref: SshHostAgentProxyPref): string {
+ return pref.mode === 'env' ? pref.proxyUrl : `http://127.0.0.1:${pref.remotePort}`;
+}
+
/**
* 注入远端 agent 进程的代理 env。大小写两份: Rust (reqwest) / Node /
* Go / curl 对 HTTPS_PROXY vs https_proxy 的读取习惯不一致, 全给最稳。
* NO_PROXY 只排除 loopback — 用户自己的 Proxy 规则决定内网域名直连与否,
* 那是 Proxy 软件的职责, 不是我们的。
+ *
+ * 本函数是 env 键集与取值的唯一真源: uppercase 子集与 marker 序列化都从
+ * 它派生, 加键/改 NO_PROXY 只动这里。
*/
-export function buildAgentProxyEnv(remotePort: number): Record<string, string> {
- const url = `http://127.0.0.1:${remotePort}`;
+export function buildAgentProxyEnv(proxyUrl: string): Record<string, string> {
const noProxy = 'localhost,127.0.0.1,::1';
return {
- HTTPS_PROXY: url,
- HTTP_PROXY: url,
+ HTTPS_PROXY: proxyUrl,
+ HTTP_PROXY: proxyUrl,
NO_PROXY: noProxy,
- https_proxy: url,
- http_proxy: url,
+ https_proxy: proxyUrl,
+ http_proxy: proxyUrl,
no_proxy: noProxy,
};
}
@@ -103,126 +176,64 @@ export function buildAgentProxyEnv(remotePort: number): Record<string, string> {
* 仅大写版本 — env-block.ts 的 gatekeeper 拒小写 key (防 stdin 协议注入),
* one-shot 的 envBlock 路径只能拿大写; claude/codex 都认大写。
*/
-export function buildAgentProxyEnvUppercase(remotePort: number): Record<string, string> {
- const url = `http://127.0.0.1:${remotePort}`;
- return {
- HTTPS_PROXY: url,
- HTTP_PROXY: url,
- NO_PROXY: 'localhost,127.0.0.1,::1',
- };
+export function buildAgentProxyEnvUppercase(proxyUrl: string): Record<string, string> {
+ const { HTTPS_PROXY, HTTP_PROXY, NO_PROXY } = buildAgentProxyEnv(proxyUrl);
+ return { HTTPS_PROXY, HTTP_PROXY, NO_PROXY };
}
-/** codex daemon wrapper source 的 marker 文件内容。 */
-export function buildAgentProxyMarkerContent(remotePort: number): string {
- const url = `http://127.0.0.1:${remotePort}`;
- return [
- '# Written by Cindy — agent proxy tunnel env. Sourced by the codex daemon wrapper.',
- `export HTTPS_PROXY='${url}'`,
- `export HTTP_PROXY='${url}'`,
- `export NO_PROXY='localhost,127.0.0.1,::1'`,
- `export https_proxy='${url}'`,
- `export http_proxy='${url}'`,
- `export no_proxy='localhost,127.0.0.1,::1'`,
- '',
- ].join('\n');
+/**
+ * codex daemon wrapper source 的 marker 文件内容 (buildAgentProxyEnv 的
+ * shell 序列化)。首行注释沿用 #715 的原文 — tunnel 模式迁移后 URL 不变时
+ * marker 逐字节一致, 升级不触发无谓的 daemon 重启。
+ */
+export function buildAgentProxyMarkerContent(proxyUrl: string): string {
+ const lines = ['# Written by Cindy — agent proxy tunnel env. Sourced by the codex daemon wrapper.'];
+ for (const [key, value] of Object.entries(buildAgentProxyEnv(proxyUrl))) {
+ lines.push(`export ${key}='${value}'`);
+ }
+ lines.push('');
+ return lines.join('\n');
}
-/* ============================== 隧道管理 ============================== */
-
-export interface AgentProxyTunnelInfo {
- remotePort: number;
- /** 与新 pref 不匹配的旧 forward (rebind 场景), 由调用方决定拆除时机。 */
- staleForwards: Array<{ localHost: string; localPort: number }>;
-}
+/* ============================== session 路径 ============================== */
/**
- * pref 开启时确保隧道在跑, 返回远端端口; pref 关闭返回 null。
- * host 必须 ready (调用方保证); arm 失败抛错并记录到 tunnel state。
- *
- * rebind (目标被编辑) 场景**先建后拆** (codex R17 P2): 新 forward 建立
- * 失败时旧 forward 原样保留, 存活 daemon 流量不断。closeStale !== false
- * (默认) 建成功后立即拆旧 (R5 语义: 不拆会残留并随重连 re-arm, 远端
- * 多暴露一个隧道口); reconcile 传 closeStale: false, 把拆旧推迟到
- * daemon 重启成功之后 (pkill 失败时旧隧道保留兜底)。
+ * session 路径的代理就绪确保: 返回远端应使用的代理 URL。
+ * - pref 关闭 → null;
+ * - env 模式 → 直接返回 (远端可达性由用户保证);
+ * - tunnel 模式 → 等隧道 armed (保活器起隧道; 超时抛错, fail-closed —
+ * 不静默回落直连, 与旧行为一致)。
*/
-export async function ensureAgentProxyTunnel(
- host: RemoteHost,
- opts?: { closeStale?: boolean },
-): Promise<AgentProxyTunnelInfo | null> {
+export async function ensureAgentProxyReady(host: RemoteHost): Promise<string | null> {
const pref = getSshHostAgentProxy(host.id);
- if (!pref) return null;
- try {
- const fwd = await host.ensureRemoteForward({
- localHost: pref.localHost,
- localPort: pref.localPort,
- });
- const staleForwards = host
- .listRemoteForwards()
- .filter((f) => f.localHost !== pref.localHost || f.localPort !== pref.localPort);
- if (opts?.closeStale !== false) {
- for (const f of staleForwards) {
- try {
- await host.closeRemoteForward(f.localHost, f.localPort);
- } catch (err) {
- log.warn('close stale remote forward failed (best-effort)', {
- hostId: host.id,
- staleTarget: `${f.localHost}:${f.localPort}`,
- error: String((err as Error)?.message ?? err),
- });
- }
- }
- }
- tunnelStates.set(host.id, { active: true, remotePort: fwd.remotePort });
- emitState(host.id);
- return { remotePort: fwd.remotePort, staleForwards };
- } catch (err) {
- const msg = String((err as Error)?.message ?? err);
- tunnelStates.set(host.id, { active: false, lastError: msg });
- emitState(host.id);
- throw err;
- }
-}
-
-/** 拆旧 forward (rebind 残留) — best-effort, 单个失败不阻塞其余。 */
-async function closeStaleForwards(
- host: RemoteHost,
- staleForwards: Array<{ localHost: string; localPort: number }>,
-): Promise<void> {
- for (const f of staleForwards) {
- try {
- await host.closeRemoteForward(f.localHost, f.localPort);
- } catch (err) {
- log.warn('close stale remote forward failed (best-effort)', {
- hostId: host.id,
- staleTarget: `${f.localHost}:${f.localPort}`,
- error: String((err as Error)?.message ?? err),
- });
- }
- }
+ if (!pref?.enabled) return null;
+ if (pref.mode === 'env') return pref.proxyUrl;
+ // 用 armed 隧道的实际端口而非 pref: pref 刚被编辑而迁移尚未获准 (live
+ // turn 挡着 reconcile) 时, 现役隧道还在旧端口上 — 按现役真值注入才可用,
+ // 迁移由 reconcile 在安全时机完成 (R1 review P1)。
+ const { remotePort } = await ensureTunnelUp(host);
+ return `http://127.0.0.1:${remotePort}`;
}
/**
- * claude-code session 路径: pref 开启 → 确保隧道 + 返回要 merge 进
- * startParams.env 的代理 env; 关闭 → null (调用方原样透传 startParams)。
+ * claude-code session 路径: pref 开启 → 返回要 merge 进 startParams.env 的
+ * 代理 env; 关闭 → null (调用方原样透传 startParams)。
*/
export async function getRemoteAgentProxyEnv(
host: RemoteHost,
): Promise<Record<string, string> | null> {
- const tunnel = await ensureAgentProxyTunnel(host);
- if (!tunnel) return null;
- return buildAgentProxyEnv(tunnel.remotePort);
+ const proxyUrl = await ensureAgentProxyReady(host);
+ if (!proxyUrl) return null;
+ return buildAgentProxyEnv(proxyUrl);
}
-/** 拆除本 host 的所有 forward (pref 关闭时调用)。 */
-async function closeAllForwards(host: RemoteHost): Promise<void> {
- try {
- await host.closeAllRemoteForwards();
- } catch (err) {
- log.warn('close remote forwards failed (best-effort)', {
- hostId: host.id,
- error: String((err as Error)?.message ?? err),
- });
- }
+/** one-shot quick test 路径 (envBlock 只收大写)。 */
+export async function getRemoteAgentProxyEnvUppercase(
+ host: RemoteHost,
+): Promise<Record<string, string> | null> {
+ const proxyUrl = await ensureAgentProxyReady(host);
+ if (!proxyUrl) return null;
+ return buildAgentProxyEnvUppercase(proxyUrl);
}
/* ============================== codex daemon env marker ============================== */
@@ -346,16 +357,32 @@ exit 3
}
}
+export interface ReconcileCodexAgentProxyResult {
+ markerChanged: boolean;
+ daemonRestarted: boolean;
+ /**
+ * true = marker 已漂移但 host 上有 live turn, 本次不写不杀 (重启 daemon
+ * 会断 turn)。漂移是持久事实 — turn-done 挂钩与下次 session start 的
+ * reconcile 都会重试, 不依赖本次。
+ */
+ deferredForLiveTurn?: boolean;
+}
+
/**
- * codex 路径的 env 对账: 比较远端 marker 与期望值, 漂移则重写 marker +
- * pkill daemon (下次 transport bootstrap 时 daemon version 探活失败 →
- * 重新 bootstrap, wrapper source 新 marker, env 生效)。
+ * codex 路径的 env 对账: 比较远端 marker 与期望值 (由 pref 静态派生),
+ * 漂移则重写 marker + pkill daemon (下次 transport bootstrap 时 daemon
+ * version 探活失败 → 重新 bootstrap, wrapper source 新 marker, env 生效)。
+ *
+ * 期望值只随用户改设置而变 — SSH 重连不再制造漂移 (固定端口), 所以命中
+ * 慢路径的时机基本只有「用户刚改完设置」与「首次开启」。此时若 host 上
+ * 有 live turn, 推迟对账 (deferredForLiveTurn), 不 mid-turn 杀 daemon。
*
* 调用点:
* 1. codex-remote-transport bootstrap 的 beforeDaemonProbe (每个新
- * app-server host 建立前) — 兜底所有路径 (app 重启 / 端口变化 /
- * 远端被别的客户端动过)。
+ * app-server host 建立前) — 兜底所有路径 (app 重启 / 远端被别的
+ * 客户端动过)。
* 2. pref 变更 / host ready 的 applyAgentProxyForHost — 即时生效。
+ * 3. turn-done 挂钩 (register.ts) — live-turn defer 的补刀点。
*
* marker 一致时零副作用 (1 次 cat RTT)。pkill 失败不抛错 — marker 回滚到
* 原值 (与存活 daemon 的 env 保持一致, 否则下次 reconcile 命中 fast path
@@ -364,7 +391,7 @@ exit 3
*/
export async function reconcileCodexAgentProxyEnv(
host: RemoteHost,
-): Promise<{ markerChanged: boolean; daemonRestarted: boolean }> {
+): Promise<ReconcileCodexAgentProxyResult> {
// per-host 串行链 (codex R9 P2): 并发 reconcile (两个 transport 的
// beforeDaemonProbe 与 ready-hook 同时触发) 时, 若第一个还在等
// killRemoteCodexDaemon 而第二个走 marker-match fast path, 第二个会直接去
@@ -389,101 +416,165 @@ const reconcileChains = new Map<string, Promise<void>>();
async function reconcileCodexAgentProxyEnvSerialized(
host: RemoteHost,
-): Promise<{ markerChanged: boolean; daemonRestarted: boolean }> {
- const pref = getSshHostAgentProxy(host.id);
- let desired: string | null = null;
- let staleForwards: Array<{ localHost: string; localPort: number }> = [];
- if (pref) {
- // 拆旧推迟到 daemon 重启成功后 (codex R17 P2): pkill 失败时旧隧道保留,
- // 存活 daemon 仍指旧端口, 流量不断; 新 forward 闲置在 pref 目标上
- // (语义正确, 下次 reconcile 直接用)。
- const tunnel = await ensureAgentProxyTunnel(host, { closeStale: false });
- if (!tunnel) throw new Error('agentProxy pref enabled but tunnel refused to start');
- desired = buildAgentProxyMarkerContent(tunnel.remotePort);
- staleForwards = tunnel.staleForwards;
+): Promise<ReconcileCodexAgentProxyResult> {
+ try {
+ return await doReconcileCodexAgentProxyEnv(host);
+ } catch (err) {
+ // 任何失败 (marker 读写 / 隧道 armed 超时 / …) 都记 pending — turn-done
+ // 补刀是最近的自愈时机, 不能只靠下一次 session start (R2 review P2)。
+ pendingReconcileHosts.add(host.id);
+ throw err;
}
+}
+
+async function doReconcileCodexAgentProxyEnv(
+ host: RemoteHost,
+): Promise<ReconcileCodexAgentProxyResult> {
+ const pref = getSshHostAgentProxy(host.id);
+ const desired = pref?.enabled ? buildAgentProxyMarkerContent(resolveAgentProxyUrl(pref)) : null;
+ const keeperReady = isAgentProxyTunnelKeeperInitialized();
+ const wantsTunnel = pref?.enabled === true && pref.mode === 'tunnel';
const current = await readRemoteMarker(host);
- if (current === (desired ? desired.trim() : null)) {
- // marker 一致 (fast path): daemon env 已是新目标, rebind 残留的旧
- // forward 可以安全拆 (R5 语义; pref 关路径由 closeAllForwards 统一拆)。
- if (staleForwards.length > 0) await closeStaleForwards(host, staleForwards);
+ const markerDrift = current !== (desired ? desired.trim() : null);
+ // marker 只编码远端固定端口 — localHost/localPort 或主机连接配置变更都
+ // 不产生 marker 漂移, 必须单独纳入判定, 且与 marker 漂移共用同一个
+ // live-turn gate (R2/R3 review P1: 否则本地代理目标 / 主机变更永远不会
+ // 被应用到隧道上)。
+ const tunnelDrift = wantsTunnel && keeperReady && tunnelNeedsRebuild(host, pref);
+
+ if (!markerDrift && !tunnelDrift) {
+ if (keeperReady) {
+ if (wantsTunnel) {
+ // fail-closed (R1 review P1): marker 一致也必须隧道真的 armed —
+ // 否则 daemon 拿着正确 env 却打不通端口, 表现为 agent 内部网络
+ // 静默失败。armed 不上抛错 (外层记 pending), 调用方按各自路径
+ // 收口 (probe 中断 / apply 落 error 状态 / quick test 报错),
+ // keeper 继续自愈。
+ await ensureTunnelUp(host);
+ } else {
+ // pref 关 / env 模式的残留隧道兜底拆除 (幂等, 常态 no-op):
+ // 覆盖「离线期间关了 proxy, 上线时 marker 本就是空」这类路径。
+ void stopTunnelForHost(host.id);
+ }
+ }
+ // pending 只在一切收敛 (含隧道 armed) 之后才摘除 (R2 review P2)。
+ pendingReconcileHosts.delete(host.id);
return { markerChanged: false, daemonRestarted: false };
}
- log.info('codex agent-proxy env marker drifted, rewriting + restarting daemon', {
- hostId: host.id,
- enabled: pref != null,
- });
- await writeRemoteMarker(host, desired);
- const kill = await killRemoteCodexDaemon(host);
- if (!kill.ok) {
- // daemon 没死透 → marker 回滚到原值 (codex R10 P1/P2): 存活 daemon 的
- // env 仍来自原 marker; 若让 marker 停在新值, 下次 reconcile 命中
- // marker-match fast path 永不重试 kill — disable 后旧 daemon 握着指向
- // 已拆隧道的 proxy env 跑到手动重启, enable 后旧 daemon 一直跑旧 env。
- // 回滚后 marker 与存活 daemon env 一致, 下次 reconcile 仍 drift →
- // 重写 + 重试 kill, 可自愈。回滚失败仅 warn: 调用方已按失败上报。
- // 不拆任何 forward (codex R17 P2): 旧 forward 保留兜底, 存活 daemon
- // 仍指旧端口, 流量不断。
- try {
- await writeRemoteMarker(host, current);
- } catch (rollbackErr) {
- log.warn('agent-proxy marker rollback after pkill failure failed', {
- hostId: host.id,
- error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- });
+ if (liveTurnChecker?.(host.id)) {
+ // 漂移生效要重启 daemon / 迁移隧道, 两者都会打断 live turn — 推迟,
+ // 漂移持久 (marker 与隧道都未动), turn-done / 下次 session start 必然
+ // 补刀 (R1 review P1)。
+ pendingReconcileHosts.add(host.id);
+ log.warn('agent-proxy drift deferred: live turn in progress on host', {
+ hostId: host.id,
+ enabled: pref != null,
+ markerDrift,
+ tunnelDrift,
+ });
+ return { markerChanged: false, daemonRestarted: false, deferredForLiveTurn: true };
+ }
+
+ if (markerDrift) {
+ log.info('codex agent-proxy env marker drifted, rewriting + restarting daemon', {
+ hostId: host.id,
+ enabled: pref != null,
+ });
+ await writeRemoteMarker(host, desired);
+ const kill = await killRemoteCodexDaemon(host);
+ if (!kill.ok) {
+ // daemon 没死透 → marker 回滚到原值 (codex R10 P1/P2): 存活 daemon 的
+ // env 仍来自原 marker; 若让 marker 停在新值, 下次 reconcile 命中
+ // marker-match fast path 永不重试 kill — disable 后旧 daemon 握着旧
+ // proxy env 跑到手动重启, enable 后旧 daemon 一直跑旧 env。
+ // 回滚后 marker 与存活 daemon env 一致, 下次 reconcile 仍 drift →
+ // 重写 + 重试 kill, 可自愈。回滚失败仅 warn: 调用方已按失败上报。
+ // 隧道不动 (R2 review P1): 存活 daemon 还指着旧端口, 旧隧道保留兜底。
+ try {
+ await writeRemoteMarker(host, current);
+ } catch (rollbackErr) {
+ log.warn('agent-proxy marker rollback after pkill failure failed', {
+ hostId: host.id,
+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
+ });
+ }
+ pendingReconcileHosts.add(host.id);
+ return { markerChanged: true, daemonRestarted: false };
+ }
+ }
+
+ // 隧道迁移/拆除放在 marker 写入 + daemon 重启**成功之后** (R2 review P1):
+ // write/kill 任一失败时旧隧道原样保留, 存活 daemon 的流量不断。此刻旧
+ // daemon 已死 (或本来就是 tunnel-only 迁移、daemon env 无需变), 迁移不再
+ // 打断任何在途消费者; 新隧道 armed 不上则抛错 (外层记 pending), 下次
+ // reconcile 的 fast path 恒校验 armed, probe 始终 fail-closed。
+ if (keeperReady) {
+ if (wantsTunnel) {
+ ensureTunnelForHost(host, { allowRebuild: true });
+ await ensureTunnelUp(host);
+ } else {
+ await stopTunnelForHost(host.id);
}
- return { markerChanged: true, daemonRestarted: false };
}
- // daemon 重启成功: 拆旧 (R5 语义, 时机后移到重启成功后, codex R17 P2)。
- if (staleForwards.length > 0) await closeStaleForwards(host, staleForwards);
- return { markerChanged: true, daemonRestarted: true };
+ pendingReconcileHosts.delete(host.id);
+ return { markerChanged: markerDrift, daemonRestarted: markerDrift };
}
/**
- * host ready / pref 变更后的统一应用入口 (幂等):
- * - pref 开 → 建隧道 + codex marker 对账
- * - pref 关 → 拆隧道 + 清 marker (有残留 daemon 时重启之)
+ * host ready / pref 变更后的统一应用入口 (幂等)。隧道的建/拆/迁移与 marker
+ * 一并由 reconcile 在 live-turn gate 内统一执行 (R1 review P1) — 这里只
+ * 负责调用 reconcile、收敛 UI 状态与失败上报:
+ * - deferred (live turn) → 一切原样, turn-done 补刀 (pendingReconcile 集合)
+ * - pkill 失败 → 按 apply 失败上报 (卡片显示错误而不是说谎的「已开/关」)
+ * - env 模式成功 → 落 phase='active' (UI 只在确有应用证据时显示「已注入」)
* 失败不抛 — 状态落 tunnelStates 给 UI, session 路径会再显式重试并拿到错误。
*/
export async function applyAgentProxyForHost(host: RemoteHost): Promise<void> {
const pref = getSshHostAgentProxy(host.id);
try {
- if (!pref) {
- await closeAllForwards(host);
- const reconciled = await reconcileCodexAgentProxyEnv(host);
- // 隧道已拆但旧 daemon 没死透 = 它还握着指向已关闭端口的 proxy env,
- // 后续 codex turn 全部 proxy-connect 失败, 而 marker/隧道状态已清、
- // UI 显示 proxy 已关 (codex R9 P2) — 按 apply 失败上报, 让用户在
- // 卡片上看到错误而不是一个说谎的「已关闭」。
- if (reconciled.markerChanged && !reconciled.daemonRestarted) {
- throw new Error(
- 'codex daemon survived pkill after proxy disable; it still holds the old proxy env (retry disable or restart the host)',
- );
+ const reconciled = await reconcileCodexAgentProxyEnv(host);
+ if (reconciled.deferredForLiveTurn) {
+ // 配置已变但因 live turn 推迟 — 旧 phase='active' 状态不得继续展示
+ // (review: PR #992 codex P2): env 模式会把新 URL 显示成已注入, disable
+ // 会连卡片都不显示, 而旧 marker/隧道其实还在服役。改落 pending 态
+ // (无 lastError, UI 显示等待), turn-done 补刀后收敛。
+ const existing = tunnelStates.get(host.id);
+ if (existing?.phase === 'active') {
+ tunnelStates.set(host.id, { phase: 'paused', remotePort: existing.remotePort });
+ emitState(host.id);
}
- tunnelStates.delete(host.id);
- emitState(host.id);
return;
}
- await ensureAgentProxyTunnel(host);
- const reconciled = await reconcileCodexAgentProxyEnv(host);
- // 隧道建好但旧 daemon 没死透 = 它还跑着旧 env (无 proxy / 旧端口), 不得
- // 按成功落 active 状态 (codex R10 P1) — 与 disable 分支同款按失败上报,
- // 让卡片显示错误而不是说谎的「已开启」。
+ // 旧 daemon 没死透 = 它还跑着旧 env, 而 marker 已回滚待重试 — 不得按
+ // 成功收口 (codex R9/R10 P1/P2), 让卡片显示错误。
if (reconciled.markerChanged && !reconciled.daemonRestarted) {
throw new Error(
- 'codex daemon survived pkill after proxy enable/rebind; it still runs with the previous env (retry or restart the host)',
+ 'codex daemon survived pkill after agent-proxy change; it still runs with the previous env (retry or restart the host)',
);
}
+ if (!pref) {
+ tunnelStates.delete(host.id);
+ emitState(host.id);
+ } else if (pref.mode === 'env') {
+ // env 模式无隧道 — 以 phase='active' 记录「已应用」证据, UI 才显示
+ // 「已注入」(R1 review P2: 没证据不说谎)。
+ tunnelStates.set(host.id, { phase: 'active' });
+ emitState(host.id);
+ }
+ // tunnel 模式: 状态由 keeper 经 onState 持续汇报, 这里不写。
} catch (err) {
const msg = String((err as Error)?.message ?? err);
log.warn('apply agent-proxy failed (will retry on next session)', { hostId: host.id, error: msg });
- tunnelStates.set(host.id, { active: false, lastError: msg });
+ tunnelStates.set(host.id, { phase: 'error', lastError: msg });
emitState(host.id);
}
}
+/** app 退出清理 (index.ts onQuit 调用)。 */
+export { disposeAllTunnels } from './agent-proxy-tunnel.js';
+
function shellQuote(s: string): string {
return `'${s.replace(/'/g, `'\\''`)}'`;
}
diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.ts
index 218a6d3a26..f3e9671c00 100644
--- a/apps/desktop/src/main/remote-ssh/index.ts
+++ b/apps/desktop/src/main/remote-ssh/index.ts
@@ -33,13 +33,14 @@ import {
uninstallRemoteAgent,
checkRemoteCodexAuth,
pushRemoteCodexAuth,
+ FileHostKeyStore,
+ RemoteHost,
type AddHostInput,
type CodexAuthState,
type HostConfig,
type HostSnapshot,
type InstallProgressEvent,
type RemoteAgentKind,
- type RemoteHost,
} from '@cindy/maker-remote-ssh';
import { createLogger } from '../logger.js';
@@ -57,6 +58,9 @@ import {
getSshHostAgentProxy,
getSshHostAutoConnect,
hasAnyAutoConnectHost,
+ isAllowedAgentProxyRemotePort,
+ LEGACY_AGENT_PROXY_REMOTE_PORT,
+ normalizeAgentProxyUrl,
readSshHostPrefs,
removeSshHostPref,
setSshHostAgentProxy,
@@ -65,14 +69,15 @@ import {
} from './ssh-host-prefs-store.js';
import {
applyAgentProxyForHost,
- buildAgentProxyEnvUppercase,
clearAgentProxyTunnelState,
- ensureAgentProxyTunnel,
+ disposeAllTunnels,
getAgentProxyTunnelState,
+ getRemoteAgentProxyEnvUppercase,
+ handleAgentProxyMainHostDown,
initAgentProxy,
killRemoteCodexDaemon,
- markAgentProxyTunnelInactive,
reconcileCodexAgentProxyEnv,
+ teardownAgentProxyOnUserDisconnect,
type AgentProxyTunnelState,
} from './agent-proxy.js';
import {
@@ -191,19 +196,32 @@ const VALID_AGENT_KINDS: ReadonlyArray<RemoteAgentKind> = ['claude-code', 'codex
let pool: ConnectionPool | null = null;
let initPromise: Promise<void> | null = null;
let registered = false;
+/** 与 pool 共享的 host-key store — agent-proxy 隧道专用连接也用它做 TOFU 校验。 */
+let sharedHostKeyStore: FileHostKeyStore | null = null;
+
+function getSharedHostKeyStore(): FileHostKeyStore {
+ if (!sharedHostKeyStore) {
+ // Maker-owned host-key TOFU store. Kept out of the user's real
+ // ~/.ssh/known_hosts so we never mutate their OpenSSH state.
+ sharedHostKeyStore = new FileHostKeyStore(
+ path.join(app.getPath('userData'), 'remote-ssh', 'known-hosts.json'),
+ );
+ }
+ return sharedHostKeyStore;
+}
+
+const poolLogger = {
+ debug: (msg: string, ctx?: Record<string, unknown>) => log.debug(msg, ctx),
+ info: (msg: string, ctx?: Record<string, unknown>) => log.info(msg, ctx),
+ warn: (msg: string, ctx?: Record<string, unknown>) => log.warn(msg, ctx),
+ error: (msg: string, ctx?: Record<string, unknown>) => log.error(msg, ctx),
+};
function getPool(): ConnectionPool {
if (!pool) {
pool = new ConnectionPool({
- logger: {
- debug: (msg, ctx) => log.debug(msg, ctx),
- info: (msg, ctx) => log.info(msg, ctx),
- warn: (msg, ctx) => log.warn(msg, ctx),
- error: (msg, ctx) => log.error(msg, ctx),
- },
- // Maker-owned host-key TOFU store. Kept out of the user's real
- // ~/.ssh/known_hosts so we never mutate their OpenSSH state.
- knownHostsPath: path.join(app.getPath('userData'), 'remote-ssh', 'known-hosts.json'),
+ logger: poolLogger,
+ hostKeys: getSharedHostKeyStore(),
});
}
return pool;
@@ -507,6 +525,17 @@ function normalizeAgentProxyInput(raw: unknown): SshHostAgentProxyPref | null |
const obj = requireObject(raw, 'agentProxy');
const enabled = obj.enabled === true;
if (!enabled) return null;
+ const mode = obj.mode === 'env' ? 'env' : 'tunnel'; // 缺省 tunnel (旧 renderer 兼容)
+ if (mode === 'env') {
+ const proxyUrl = normalizeAgentProxyUrl(obj.proxyUrl);
+ if (!proxyUrl) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'agentProxy.proxyUrl must be a remote-reachable http(s)/socks5 URL without whitespace/quotes, e.g. http://127.0.0.1:7890',
+ );
+ }
+ return { enabled: true, mode: 'env', proxyUrl };
+ }
const localHost = requireString(obj.localHost, 'agentProxy.localHost').trim();
// localHost 是本机隧道转发目标 (net.connect 的目的地; 远端 env 永远指向
// 127.0.0.1:<隧道口>, 不含这个值)。空白/引号在这里虽无注入面, 但必然是
@@ -521,7 +550,12 @@ function normalizeAgentProxyInput(raw: unknown): SshHostAgentProxyPref | null |
if (!Number.isInteger(localPort)) {
throwIpcError('INVALID_PARAMS', 'agentProxy.localPort must be an integer in 1..65535');
}
- return { enabled: true, localHost, localPort };
+ // 固定远端端口 — env 静态化的关键; 旧 renderer 不传时沿用迁移缺省。
+ const remotePortRaw = obj.remotePort === undefined ? LEGACY_AGENT_PROXY_REMOTE_PORT : obj.remotePort;
+ if (!isAllowedAgentProxyRemotePort(remotePortRaw)) {
+ throwIpcError('INVALID_PARAMS', 'agentProxy.remotePort must be an integer in 1024..65535 (privileged/service ports are rejected)');
+ }
+ return { enabled: true, mode: 'tunnel', localHost, localPort, remotePort: remotePortRaw };
}
function normalizeAddInput(raw: unknown): AddHostInput & { agentProxy?: SshHostAgentProxyPref | null } {
@@ -565,24 +599,25 @@ export function registerRemoteSshIpc(): void {
const host = getPool().get(snap.config.id);
if (host) void applyAgentProxyForHost(host);
} else {
- // 断连 / 重连中: 隧道已 disarm, 状态标非活跃, detail 面板不显示
- // 过期的「已建立」(review: PR #715 copilot R3)。reconnect ready 时
- // 上面的 apply 会重建并重新标活跃。
- // 先标非活跃再广播 (mark 自带一次 emitState 推送): 事件流里不出现
- // status≠ready 但 tunnel.active=true 的 stale 帧, renderer 不会
- // 闪一帧「已建立」再翻「等待连接」(review: PR #715 收官审查 P2)。
- markAgentProxyTunnelInactive(snap.config.id);
+ // 主连接断连 / 重连中: 隧道保活挂起 (存活的独立隧道连接不拆 — 它
+ // 可能还在正常服务 LLM 流量); 主连接恢复 ready 时上面的 apply 恢复
+ // 保活。状态帧由 keeper 经 onState 汇报, 不在这里手工翻转。
+ handleAgentProxyMainHostDown(snap.config.id);
const host = getPool().get(snap.config.id);
broadcastStatus(host ? host.snapshot() : snap);
}
});
// agent-proxy 内部状态 (隧道成败 / 端口) 变化 → 推一版最新 snapshot,
- // 让 detail 面板的隧道状态行即时刷新。
+ // 让 detail 面板的隧道状态行即时刷新。隧道走独立 SSH 连接 (与控制面
+ // 隔离, 大流量不拖累 MCP/transport), 共享同一个 host-key store。
initAgentProxy({
broadcast: (hostId) => {
const host = getPool().get(hostId);
if (host) broadcastStatus(host.snapshot());
},
+ createTunnelHost: (cfg) =>
+ new RemoteHost(cfg, { logger: poolLogger, hostKeys: getSharedHostKeyStore() }),
+ getMainHost: (hostId) => getPool().get(hostId) ?? null,
});
ipcMain.handle(REMOTE_SSH_INVOKE.LIST, async () => {
@@ -746,6 +781,14 @@ export function registerRemoteSshIpc(): void {
ipcMain.handle(REMOTE_SSH_INVOKE.DISCONNECT, async (_event, args: unknown) => {
const obj = requireObject(args);
const id = requireString(obj.id, 'id');
+ // 显式断开 = 切断这台机器的全部 SSH 连通 — 独立隧道连接一并拆
+ // (与断线/重连的 pause 语义区分, review: PR #992 codex-connector P1)。
+ await teardownAgentProxyOnUserDisconnect(id).catch((err) => {
+ log.warn('agent-proxy tunnel teardown on user disconnect failed', {
+ hostId: id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
await getPool().disconnect(id);
return { host: getPool().get(id)?.snapshot() ?? null };
});
@@ -840,7 +883,7 @@ export function registerRemoteSshIpc(): void {
// ~/.codex/auth.json on the remote (synced via "Sync auth").
//
// agentProxy pref 开启时把代理 env 一并注入 (quick test 因此同时验证
- // 隧道链路是否可用): claude 走 envBlock (gatekeeper 只收大写), codex
+ // 代理链路是否可用): claude 走 envBlock (gatekeeper 只收大写), codex
// 的 wrapper 统一 source agent-proxy.env marker, 与 daemon 行为一致。
let envBlock: string | null = null;
if (agentKind === 'claude-code') {
@@ -851,18 +894,26 @@ export function registerRemoteSshIpc(): void {
'Cindy AI is not connected in Cindy; connect it in Settings → Model Providers first',
);
}
- const proxyTunnel = await ensureAgentProxyTunnel(host);
- const envWithProxy = proxyTunnel
- ? { ...env, ...buildAgentProxyEnvUppercase(proxyTunnel.remotePort) }
- : env;
+ // tunnel 模式内部会等隧道 armed (超时抛错, fail-closed 不静默直连);
+ // env 模式直接注入用户给的 URL。
+ const proxyEnv = await getRemoteAgentProxyEnvUppercase(host);
+ const envWithProxy = proxyEnv ? { ...env, ...proxyEnv } : env;
envBlock = serializeEnvBlock(envWithProxy);
} else {
// codex one-shot: wrapper 读的是 marker 文件而非直接 env — 先跑
- // reconcile (隧道 + marker 对账), 保证 quick test 与真实 daemon 链路一致。
+ // reconcile (marker 对账), 保证 quick test 与真实 daemon 链路一致。
// markerChanged && !daemonRestarted = 旧 daemon 活着跑旧 env, marker 已
// 回滚 — one-shot 若继续会 source 不到新 proxy marker 而直连, 与
// daemon-probe 路径的 fail-closed 不一致 (codex R12 P1): 显式失败。
+ // deferredForLiveTurn = 有远端任务在跑, 对账推迟 — quick test 会以
+ // 旧 env 运行, 提示用户稍后再试而不是 mid-turn 杀 daemon。
const reconciled = await reconcileCodexAgentProxyEnv(host);
+ if (reconciled.deferredForLiveTurn) {
+ throwIpcError(
+ 'INTERNAL',
+ 'agent-proxy settings changed while a remote turn is running; quick test deferred — retry after the current task finishes',
+ );
+ }
if (reconciled.markerChanged && !reconciled.daemonRestarted) {
throwIpcError(
'INTERNAL',
@@ -1566,8 +1617,9 @@ function shellQuoteSh(s: string): string {
return `'${s.replace(/'/g, `'\\''`)}'`;
}
-/** Tear down all live connections. Hook into onQuit. */
+/** Tear down all live connections (含 agent-proxy 隧道专用连接). Hook into onQuit. */
export async function disposeRemoteSshPool(): Promise<void> {
+ await disposeAllTunnels().catch(() => undefined);
if (!pool) return;
await pool.dispose();
pool = null;
diff --git a/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts b/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts
index 7e12ad9098..c155b94ee2 100644
--- a/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts
+++ b/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts
@@ -26,15 +26,31 @@ import { createLogger } from '../logger.js';
const log = createLogger('ssh-host-prefs-store');
+// pref 联合类型 / URL 校验 / 迁移缺省端口的真源在 shared (preload 与
+// renderer 表单共用同一份, 消除手写镜像的结构漂移) — 这里 re-export 保持
+// main 侧既有引用点不变。旧数据 ({enabled, localHost, localPort} 无 mode,
+// PR #715 动态端口方案) 迁移为 mode='tunnel' + LEGACY_AGENT_PROXY_REMOTE_PORT。
+import {
+ LEGACY_AGENT_PROXY_REMOTE_PORT,
+ normalizeAgentProxyUrl,
+ type SshHostAgentProxyPref,
+} from '../../shared/agentProxyConfig.js';
+
+export { LEGACY_AGENT_PROXY_REMOTE_PORT, normalizeAgentProxyUrl };
+export type { SshHostAgentProxyPref };
+
+function isValidPort(v: unknown): v is number {
+ return typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 65535;
+}
+
/**
- * Agent 流量经 SSH 隧道走本地 Proxy 的 per-host 配置。
- * Cindy 不提供 Proxy, 只建隧道: 远端 127.0.0.1:<forwardPort> → 本地
- * localHost:localPort (用户自己的 Proxy, 如 Clash 的 7890 混合端口)。
+ * 固定远端端口拒收特权/知名服务端口 (<1024): 隧道保活的残留清理会定点
+ * kill 占着固定端口的 sshd 会话, 若用户把端口配成 22 (SSH 服务) 等, 清理
+ * 路径可能误杀系统 sshd 主服务 (review: PR #992 codex-connector P1)。
+ * 高端口 (>=1024) 由用户显式指定、归属自担; 低端口一刀切拒收。
*/
-export interface SshHostAgentProxyPref {
- enabled: boolean;
- localHost: string;
- localPort: number;
+export function isAllowedAgentProxyRemotePort(v: unknown): v is number {
+ return isValidPort(v) && (v as number) >= 1024;
}
export interface SshHostPref {
@@ -51,16 +67,42 @@ function settingsFilePath(): string {
function normalizeAgentProxy(raw: unknown): SshHostAgentProxyPref | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const v = raw as Record<string, unknown>;
+ if (v.mode === 'env') {
+ const proxyUrl = normalizeAgentProxyUrl(v.proxyUrl);
+ if (!proxyUrl) {
+ log.warn('invalid agentProxy.proxyUrl in prefs — dropping (was it hand-edited?)', {
+ proxyUrl: typeof v.proxyUrl === 'string' ? v.proxyUrl.slice(0, 80) : v.proxyUrl,
+ });
+ return undefined;
+ }
+ return { enabled: v.enabled === true, mode: 'env', proxyUrl };
+ }
+ // mode='tunnel' 或缺省 (旧数据迁移路径)。
const localHost = typeof v.localHost === 'string' ? v.localHost.trim() : '';
const localPort = typeof v.localPort === 'number' ? v.localPort : NaN;
// 引号与空白同样拒 (与 IPC normalizeAgentProxyInput / renderer 校验对齐,
// review: PR #715 copilot R8): 手编 prefs 的脏值不应在启动时被恢复成
// 可用 pref, 然后晚到 net.connect 才以难懂的方式失败。
if (!localHost || /\s/.test(localHost) || localHost.includes("'") || localHost.includes('"')) {
+ log.warn('invalid agentProxy.localHost in prefs — dropping (was it hand-edited?)', {
+ localHost: typeof v.localHost === 'string' ? v.localHost.slice(0, 80) : v.localHost,
+ });
+ return undefined;
+ }
+ if (!isValidPort(localPort)) {
+ log.warn('invalid agentProxy.localPort in prefs — dropping (was it hand-edited?)', {
+ localPort: v.localPort,
+ });
return undefined;
}
- if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) return undefined;
- return { enabled: v.enabled === true, localHost, localPort };
+ if (!isAllowedAgentProxyRemotePort(v.remotePort ?? LEGACY_AGENT_PROXY_REMOTE_PORT)) {
+ log.warn('agentProxy.remotePort in privileged/service range — dropping (must be >=1024)', {
+ remotePort: v.remotePort,
+ });
+ return undefined;
+ }
+ const remotePort = isValidPort(v.remotePort) ? v.remotePort : LEGACY_AGENT_PROXY_REMOTE_PORT;
+ return { enabled: v.enabled === true, mode: 'tunnel', localHost, localPort, remotePort };
}
function normalize(raw: unknown): SshHostPrefs {
@@ -128,13 +170,31 @@ export function setSshHostAgentProxy(hostId: string, agentProxy: SshHostAgentPro
}
current[hostId] = next;
writePrefs(current);
+ const ap = next.agentProxy;
log.info('ssh host agentProxy written', {
hostId,
- enabled: next.agentProxy?.enabled === true,
- localTarget: next.agentProxy ? `${next.agentProxy.localHost}:${next.agentProxy.localPort}` : null,
+ enabled: ap?.enabled === true,
+ mode: ap?.mode ?? null,
+ // 脱敏: proxyUrl 即使将来校验放宽也不原样进日志 (review: PR #992
+ // copilot — URL 可能带 userinfo), 只记录 scheme://host:port。
+ target: ap
+ ? ap.mode === 'tunnel'
+ ? `remote:${ap.remotePort} -> ${ap.localHost}:${ap.localPort}`
+ : redactProxyUrlForLog(ap.proxyUrl)
+ : null,
});
}
+/** 日志安全的 proxy URL 形态: scheme://host:port (剥 userinfo / path / query)。 */
+function redactProxyUrlForLog(url: string): string {
+ try {
+ const u = new URL(url);
+ return `${u.protocol}//${u.host}`;
+ } catch {
+ return '(unparseable)';
+ }
+}
+
function writePrefs(prefs: SshHostPrefs): void {
const file = settingsFilePath();
const tmp = `${file}.tmp`;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 9f06c78d15..37c08c456a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -17,6 +17,7 @@ import {
type AgentIslandSoundChoice,
type AgentIslandSoundSettings,
} from '../shared/agentIsland';
+import type { AgentProxyTunnelState, SshHostAgentProxyPref } from '../shared/agentProxyConfig';
import {
WINDOW_BEHAVIOR_GET_WINDOWS_CLOSE_BEHAVIOR_CHANNEL,
WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL,
@@ -2977,9 +2978,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** Phase D — 启动时是否自动连接 (本地 prefs, 不写入 ~/.ssh/config). */
autoConnect: boolean;
/** Agent 流量经 SSH 隧道走本地 Proxy (本地 prefs); 未开启 → null. */
- agentProxy: { enabled: boolean; localHost: string; localPort: number } | null;
+ agentProxy: SshHostAgentProxyPref | null;
/** 隧道实时状态 (内存态); 无记录 → null. */
- agentProxyTunnel: { active: boolean; remotePort?: number; lastError?: string } | null;
+ agentProxyTunnel: AgentProxyTunnelState | null;
}>;
}> => ipcRenderer.invoke('maker:remote-ssh:list'),
reloadConfig: (): Promise<{ hosts: unknown[] }> =>
@@ -2991,7 +2992,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
- agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
+ agentProxy?: SshHostAgentProxyPref | null;
}): Promise<{ host: unknown }> => ipcRenderer.invoke('maker:remote-ssh:add', host),
update: (host: {
id: string;
@@ -3000,7 +3001,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
- agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
+ agentProxy?: SshHostAgentProxyPref | null;
}): Promise<{ host: unknown }> => ipcRenderer.invoke('maker:remote-ssh:update', host),
remove: (id: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('maker:remote-ssh:remove', { id }),
diff --git a/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx b/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx
index ffc3e5adef..1f9dd23e98 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx
@@ -273,9 +273,9 @@ function AgentProxyTunnelCard({ hostId }: { hostId: string }) {
const tunnel = snap?.agentProxyTunnel ?? null;
// pref 已关但 disable 失败 (daemon 没死透, 错误已落 lastError) 时仍渲染
// 错误卡片 (codex R17 P2) — 否则 Settings 看起来像成功关闭, 存活 daemon
- // 还握着指向已拆端口的 proxy env, 用户毫无察觉。
+ // 还握着旧 proxy env, 用户毫无察觉。
if (!pref && !tunnel?.lastError) return null;
- const localTarget = pref ? `${pref.localHost}:${pref.localPort}` : '';
+ const localTarget = pref?.mode === 'tunnel' ? `${pref.localHost}:${pref.localPort}` : '';
let icon;
let text: string;
@@ -285,21 +285,38 @@ function AgentProxyTunnelCard({ hostId }: { hostId: string }) {
icon = <AlertCircle size={14} />;
text = t('settings.remote.detail.agentProxyError', { message: tunnel?.lastError ?? '' });
isError = true;
- } else if (snap?.status !== 'ready') {
- // 主机断连/重连中: 隧道已 disarm 或正在拆除 — 即使隧道状态快照还没翻到
- // 非活跃 (断连帧先于 mark-inactive 帧到达), 也优先显示「等待连接」,
- // 不渲染过期的「已建立」(review: PR #715 收官审查 P2)。断连时
- // markAgentProxyTunnelInactive 会清掉 lastError, 错误分支只在 ready
- // 状态 (连接正常但建隧道失败) 下有语义。
- icon = <AlertCircle size={14} />;
- text = t('settings.remote.detail.agentProxyWaiting', { target: localTarget });
- } else if (tunnel?.active && tunnel.remotePort != null) {
+ } else if (pref.mode === 'env') {
+ // env 模式无隧道 — 只有 apply 成功 (phase='active' 由 main 侧落下) 才
+ // 显示「已注入」; 未连接 / 尚未应用 / live-turn 推迟中都显示等待态,
+ // 不凭 pref 存在就谎报已生效。
+ if (tunnel?.phase === 'error' && tunnel.lastError) {
+ icon = <AlertCircle size={14} />;
+ text = t('settings.remote.detail.agentProxyError', { message: tunnel.lastError });
+ isError = true;
+ } else if (snap?.status === 'ready' && tunnel?.phase === 'active') {
+ icon = <CheckCircle2 size={14} />;
+ text = t('settings.remote.detail.agentProxyEnvInfo', { url: pref.proxyUrl });
+ } else {
+ icon = <Spinner size={12} />;
+ text = t('settings.remote.detail.agentProxyEnvPending', { url: pref.proxyUrl });
+ }
+ } else if (tunnel?.phase === 'active' && tunnel.remotePort != null) {
+ // 隧道走独立 SSH 连接 — 主连接断开期间它可能仍在服务, active 优先展示。
icon = <CheckCircle2 size={14} />;
text = t('settings.remote.detail.agentProxyActive', {
port: tunnel.remotePort,
target: localTarget,
});
- } else if (tunnel?.lastError) {
+ } else if (snap?.status !== 'ready' || tunnel?.phase === 'paused') {
+ // 主机断连/重连中: 隧道保活挂起, 主连接恢复后自动重建。
+ icon = <AlertCircle size={14} />;
+ text = t('settings.remote.detail.agentProxyWaiting', { target: localTarget });
+ } else if (tunnel?.phase === 'port-busy') {
+ icon = <Spinner size={12} />;
+ text = t('settings.remote.detail.agentProxyPortBusy', {
+ port: tunnel.remotePort ?? pref.remotePort,
+ });
+ } else if (tunnel?.lastError && tunnel.phase === 'error') {
icon = <AlertCircle size={14} />;
text = t('settings.remote.detail.agentProxyError', { message: tunnel.lastError });
isError = true;
diff --git a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
index d279783bae..0b3a611524 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
@@ -17,6 +17,7 @@ import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
import { remoteSshHostsStore } from '@/lib/remoteSshHostsStore';
import { extractIpcError, mapIpcErrorToI18nKey } from '@/utils/ipcError';
+import { LEGACY_AGENT_PROXY_REMOTE_PORT, normalizeAgentProxyUrl } from '../../../shared/agentProxyConfig';
import { RemoteHostDetail } from './RemoteHostDetail';
import { SshKeySetupDialog } from './SshKeySetupDialog';
@@ -270,11 +271,20 @@ interface AddFormState {
port: string;
authMethod: 'agent' | 'key';
identityFile: string;
- /** 「Agent 流量走本地 Proxy」隧道开关 + 本地 Proxy 地址 (host:port)。 */
+ /** 「Agent 流量走 Proxy」开关。 */
agentProxyEnabled: boolean;
+ /** tunnel = Cindy 代建隧道; env = 自备代理 (仅注入环境变量)。 */
+ agentProxyMode: 'tunnel' | 'env';
+ /** tunnel 模式: 本地 Proxy 地址 (host:port)。 */
agentProxyAddr: string;
+ /** tunnel 模式: 远端固定监听端口 (文本输入, 提交时转数字)。 */
+ agentProxyRemotePort: string;
+ /** env 模式: 远端可达的代理 URL。 */
+ agentProxyUrl: string;
}
+const DEFAULT_AGENT_PROXY_REMOTE_PORT = String(LEGACY_AGENT_PROXY_REMOTE_PORT);
+
const EMPTY_FORM: AddFormState = {
id: '',
hostname: '',
@@ -283,7 +293,10 @@ const EMPTY_FORM: AddFormState = {
authMethod: 'agent',
identityFile: '',
agentProxyEnabled: false,
+ agentProxyMode: 'tunnel',
agentProxyAddr: '127.0.0.1:7890',
+ agentProxyRemotePort: DEFAULT_AGENT_PROXY_REMOTE_PORT,
+ agentProxyUrl: 'http://127.0.0.1:7890',
};
/**
@@ -320,6 +333,44 @@ export function parseProxyAddrInput(input: string): { localHost: string; localPo
return { localHost, localPort };
}
+/** 远端固定端口输入 — 严格整数, 且拒特权/知名服务端口 (与 main 侧
+ * isAllowedAgentProxyRemotePort 同口径, 防清理路径误杀系统 sshd)。 */
+export function parseRemotePortInput(input: string): number | null {
+ const s = input.trim();
+ if (!/^\d+$/.test(s)) return null;
+ const port = Number(s);
+ return Number.isInteger(port) && port >= 1024 && port <= 65535 ? port : null;
+}
+
+type AgentProxyPayload =
+ | { enabled: boolean; mode: 'tunnel'; localHost: string; localPort: number; remotePort: number }
+ | { enabled: boolean; mode: 'env'; proxyUrl: string };
+
+/** 表单 → IPC agentProxy 载荷; 校验失败返回错误文案 key (toast 用)。 */
+function buildAgentProxyPayload(
+ form: AddFormState,
+): { ok: true; agentProxy: AgentProxyPayload | null } | { ok: false; errorKey: string } {
+ if (!form.agentProxyEnabled) return { ok: true, agentProxy: null };
+ if (form.agentProxyMode === 'tunnel') {
+ const addr = parseProxyAddrInput(form.agentProxyAddr);
+ if (!addr) return { ok: false, errorKey: 'settings.remote.add.agentProxyAddrInvalid' };
+ const remotePort = parseRemotePortInput(form.agentProxyRemotePort);
+ if (!remotePort) return { ok: false, errorKey: 'settings.remote.add.agentProxyRemotePortInvalid' };
+ return { ok: true, agentProxy: { enabled: true, mode: 'tunnel', ...addr, remotePort } };
+ }
+ const proxyUrl = parseProxyUrlInput(form.agentProxyUrl);
+ if (!proxyUrl) return { ok: false, errorKey: 'settings.remote.add.agentProxyUrlInvalid' };
+ return { ok: true, agentProxy: { enabled: true, mode: 'env', proxyUrl } };
+}
+
+/**
+ * env 模式代理 URL 校验 — 直接复用 shared 的 normalizeAgentProxyUrl,
+ * 与 main 侧 prefs/IPC 恒同口径 (两套标准会让用户填了合法表象被 IPC 打回)。
+ */
+export function parseProxyUrlInput(input: string): string | null {
+ return normalizeAgentProxyUrl(input);
+}
+
interface HostFormProps {
/**
* 'add' → blank form, alias editable, submit creates a new host.
@@ -354,7 +405,14 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
if (!form.hostname.trim()) return false;
if (!form.user.trim()) return false;
if (form.authMethod === 'key' && !form.identityFile.trim()) return false;
- if (form.agentProxyEnabled && !parseProxyAddrInput(form.agentProxyAddr)) return false;
+ if (form.agentProxyEnabled) {
+ if (form.agentProxyMode === 'tunnel') {
+ if (!parseProxyAddrInput(form.agentProxyAddr)) return false;
+ if (!parseRemotePortInput(form.agentProxyRemotePort)) return false;
+ } else if (!parseProxyUrlInput(form.agentProxyUrl)) {
+ return false;
+ }
+ }
return true;
}, [form]);
@@ -547,9 +605,10 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
)}
</div>
- {/* ── Agent Proxy 隧道 ──
- 开关 + 本地 Proxy 地址。pref 落 desktop 本地 ssh-host-prefs.json
- (不写 ~/.ssh/config); 生效路径: 远端 127.0.0.1:<port> → 本机 Proxy,
+ {/* ── Agent Proxy ──
+ 开关 + 双模式。pref 落 desktop 本地 ssh-host-prefs.json (不写
+ ~/.ssh/config)。tunnel 模式: 远端 127.0.0.1:<固定端口> → 独立 SSH
+ 隧道 → 本机 Proxy; env 模式: 只注入用户给的远端可达 URL。
codex daemon 经 env marker (重启生效), claude 按 session env (即时)。 */}
<div className="flex flex-col gap-2">
<label
@@ -570,23 +629,89 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
</span>
</label>
{form.agentProxyEnabled && (
- <div className="flex flex-col gap-1">
- <LabeledInput
- label={t('settings.remote.add.agentProxyAddr')}
- placeholder="127.0.0.1:7890"
- value={form.agentProxyAddr}
- onChange={(v) => setForm({ ...form, agentProxyAddr: v })}
- />
- <span
- className="text-11"
- style={{ color: 'var(--settings-integration-subtitle)' }}
- >
- {t('settings.remote.add.agentProxyHint')}
- </span>
- {form.agentProxyAddr.trim() && !parseProxyAddrInput(form.agentProxyAddr) && (
- <span className="text-11" style={{ color: 'var(--error-fg)' }}>
- {t('settings.remote.add.agentProxyAddrInvalid')}
- </span>
+ <div className="flex flex-col gap-2 pl-6">
+ <div className="flex flex-col gap-1">
+ {(['tunnel', 'env'] as const).map((mode) => (
+ <label key={mode} className="flex items-start gap-2 cursor-pointer select-none">
+ <input
+ type="radio"
+ name="agent-proxy-mode"
+ checked={form.agentProxyMode === mode}
+ onChange={() => setForm({ ...form, agentProxyMode: mode })}
+ className="mt-[3px] cursor-pointer accent-[var(--settings-menu-text-selected)]"
+ />
+ <span className="flex flex-col">
+ <span
+ className="text-12 font-medium"
+ style={{ color: 'var(--settings-section-sublabel)' }}
+ >
+ {t(mode === 'tunnel'
+ ? 'settings.remote.add.agentProxyModeTunnel'
+ : 'settings.remote.add.agentProxyModeEnv')}
+ </span>
+ <span
+ className="text-11"
+ style={{ color: 'var(--settings-integration-subtitle)' }}
+ >
+ {t(mode === 'tunnel'
+ ? 'settings.remote.add.agentProxyModeTunnelDesc'
+ : 'settings.remote.add.agentProxyModeEnvDesc')}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ {form.agentProxyMode === 'tunnel' ? (
+ <div className="flex flex-col gap-1">
+ <LabeledInput
+ label={t('settings.remote.add.agentProxyAddr')}
+ placeholder="127.0.0.1:7890"
+ value={form.agentProxyAddr}
+ onChange={(v) => setForm({ ...form, agentProxyAddr: v })}
+ />
+ {form.agentProxyAddr.trim() && !parseProxyAddrInput(form.agentProxyAddr) && (
+ <span className="text-11" style={{ color: 'var(--error-fg)' }}>
+ {t('settings.remote.add.agentProxyAddrInvalid')}
+ </span>
+ )}
+ <LabeledInput
+ label={t('settings.remote.add.agentProxyRemotePort')}
+ placeholder={DEFAULT_AGENT_PROXY_REMOTE_PORT}
+ value={form.agentProxyRemotePort}
+ onChange={(v) => setForm({ ...form, agentProxyRemotePort: v })}
+ />
+ {form.agentProxyRemotePort.trim() && !parseRemotePortInput(form.agentProxyRemotePort) && (
+ <span className="text-11" style={{ color: 'var(--error-fg)' }}>
+ {t('settings.remote.add.agentProxyRemotePortInvalid')}
+ </span>
+ )}
+ <span
+ className="text-11"
+ style={{ color: 'var(--settings-integration-subtitle)' }}
+ >
+ {t('settings.remote.add.agentProxyHint')}
+ </span>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1">
+ <LabeledInput
+ label={t('settings.remote.add.agentProxyUrl')}
+ placeholder="http://127.0.0.1:7890"
+ value={form.agentProxyUrl}
+ onChange={(v) => setForm({ ...form, agentProxyUrl: v })}
+ />
+ {form.agentProxyUrl.trim() && !parseProxyUrlInput(form.agentProxyUrl) && (
+ <span className="text-11" style={{ color: 'var(--error-fg)' }}>
+ {t('settings.remote.add.agentProxyUrlInvalid')}
+ </span>
+ )}
+ <span
+ className="text-11"
+ style={{ color: 'var(--settings-integration-subtitle)' }}
+ >
+ {t('settings.remote.add.agentProxyUrlHint')}
+ </span>
+ </div>
)}
</div>
)}
@@ -882,9 +1007,9 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
// agent → optional pin (FilteredAgent only offers this one key)
// Empty string from the input = unset, send undefined.
const trimmedIdentityFile = form.identityFile.trim();
- const proxyAddr = form.agentProxyEnabled ? parseProxyAddrInput(form.agentProxyAddr) : null;
- if (form.agentProxyEnabled && !proxyAddr) {
- toast.error(t('settings.remote.add.agentProxyAddrInvalid'));
+ const proxyPayload = buildAgentProxyPayload(form);
+ if (!proxyPayload.ok) {
+ toast.error(t(proxyPayload.errorKey));
return;
}
await window.electronAPI.remoteSsh.update({
@@ -894,7 +1019,7 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
port: Number.isFinite(port) && port > 0 ? port : 22,
authMethod: form.authMethod,
identityFile: trimmedIdentityFile || undefined,
- agentProxy: proxyAddr ? { enabled: true, ...proxyAddr } : null,
+ agentProxy: proxyPayload.agentProxy,
});
// refresh() pulls the latest snapshot; updateConfig already fired a
// status event, but a full refresh is the safest way to also reflect
@@ -915,9 +1040,9 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
const port = parseInt(form.port, 10);
// identityFile is meaningful in BOTH auth modes (see handleEdit).
const trimmedIdentityFile = form.identityFile.trim();
- const proxyAddr = form.agentProxyEnabled ? parseProxyAddrInput(form.agentProxyAddr) : null;
- if (form.agentProxyEnabled && !proxyAddr) {
- toast.error(t('settings.remote.add.agentProxyAddrInvalid'));
+ const proxyPayload = buildAgentProxyPayload(form);
+ if (!proxyPayload.ok) {
+ toast.error(t(proxyPayload.errorKey));
return;
}
await window.electronAPI.remoteSsh.add({
@@ -927,7 +1052,7 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
port: Number.isFinite(port) && port > 0 ? port : 22,
authMethod: form.authMethod,
identityFile: trimmedIdentityFile || undefined,
- agentProxy: proxyAddr ? { enabled: true, ...proxyAddr } : null,
+ agentProxy: proxyPayload.agentProxy,
});
await refresh();
setAdding(false);
@@ -1053,9 +1178,16 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
authMethod: snap.config.authMethod === 'key' ? 'key' : 'agent',
identityFile: snap.config.identityFile ?? '',
agentProxyEnabled: snap.agentProxy?.enabled === true,
- agentProxyAddr: snap.agentProxy
+ agentProxyMode: snap.agentProxy?.mode === 'env' ? 'env' : 'tunnel',
+ agentProxyAddr: snap.agentProxy?.mode === 'tunnel'
? `${snap.agentProxy.localHost}:${snap.agentProxy.localPort}`
: '127.0.0.1:7890',
+ agentProxyRemotePort: snap.agentProxy?.mode === 'tunnel'
+ ? String(snap.agentProxy.remotePort)
+ : DEFAULT_AGENT_PROXY_REMOTE_PORT,
+ agentProxyUrl: snap.agentProxy?.mode === 'env'
+ ? snap.agentProxy.proxyUrl
+ : 'http://127.0.0.1:7890',
}}
onSubmit={handleEdit}
onCancel={() => setEditingId(null)}
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.ts
index 57cffc51c3..86cd066a73 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
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { parseProxyAddrInput } from '../RemoteSection';
+import { parseProxyAddrInput, parseProxyUrlInput, parseRemotePortInput } from '../RemoteSection';
describe('parseProxyAddrInput', () => {
it('parses host:port', () => {
@@ -39,3 +39,45 @@ describe('parseProxyAddrInput', () => {
expect(parseProxyAddrInput('host:7890 ')).toEqual({ localHost: 'host', localPort: 7890 }); // 整串 trim 后合法
});
});
+
+describe('parseRemotePortInput', () => {
+ it('accepts strict integer ports in range', () => {
+ expect(parseRemotePortInput('17893')).toBe(17893);
+ expect(parseRemotePortInput(' 45000 ')).toBe(45000);
+ });
+
+ it('rejects non-integers, out-of-range, privileged and suffixed values', () => {
+ expect(parseRemotePortInput('')).toBeNull();
+ expect(parseRemotePortInput('0')).toBeNull();
+ expect(parseRemotePortInput('65536')).toBeNull();
+ expect(parseRemotePortInput('7890abc')).toBeNull();
+ expect(parseRemotePortInput('-1')).toBeNull();
+ expect(parseRemotePortInput('78.9')).toBeNull();
+ // 特权/知名服务端口拒收 (防残留清理误杀系统 sshd, PR #992 review)。
+ expect(parseRemotePortInput('22')).toBeNull();
+ expect(parseRemotePortInput('1023')).toBeNull();
+ expect(parseRemotePortInput('1024')).toBe(1024);
+ });
+});
+
+describe('parseProxyUrlInput', () => {
+ it('accepts http/https/socks5 URLs (与 main 侧 normalizeAgentProxyUrl 同口径)', () => {
+ expect(parseProxyUrlInput('http://127.0.0.1:7890')).toBe('http://127.0.0.1:7890');
+ expect(parseProxyUrlInput(' https://proxy.lan:3128 ')).toBe('https://proxy.lan:3128');
+ expect(parseProxyUrlInput('socks5://10.0.0.5:1080')).toBe('socks5://10.0.0.5:1080');
+ expect(parseProxyUrlInput('socks5h://10.0.0.5:1080')).toBe('socks5h://10.0.0.5:1080');
+ });
+
+ it('rejects unsupported schemes, whitespace, quotes, userinfo and non-URLs', () => {
+ expect(parseProxyUrlInput('')).toBeNull();
+ expect(parseProxyUrlInput('127.0.0.1:7890')).toBeNull(); // 缺 scheme
+ expect(parseProxyUrlInput('ftp://127.0.0.1:21')).toBeNull();
+ expect(parseProxyUrlInput('http://a b:1')).toBeNull();
+ expect(parseProxyUrlInput("http://x'y:1")).toBeNull();
+ expect(parseProxyUrlInput('http://x"y:1')).toBeNull();
+ expect(parseProxyUrlInput('http://')).toBeNull();
+ // userinfo 内嵌凭证拒收 (会持久化 + 写远端 marker, PR #992 greptile P1)。
+ expect(parseProxyUrlInput('http://user:[email protected]:7890')).toBeNull();
+ expect(parseProxyUrlInput('socks5://[email protected]:1080')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 94bbf48cb4..5e0a152e46 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -272,13 +272,22 @@
"keyHint": "Read a private key file directly. We don't store passphrases, so encrypted keys aren't supported — use this only when ssh-agent isn't available."
},
"identityFile": "Identity file path",
- "agentProxy": "Route agent traffic via local proxy",
- "agentProxyTip": "Open a 127.0.0.1 port on the remote that tunnels back over SSH to a proxy on this machine; remote codex / Claude Code traffic flows out through it",
+ "cancel": "Cancel",
+ "submit": "Add machine",
+ "agentProxy": "Route agent traffic via proxy",
+ "agentProxyTip": "Send remote codex / Claude Code model traffic through a proxy: either a Cindy-managed SSH tunnel back to your local proxy, or a remote-reachable proxy URL you provide",
+ "agentProxyModeTunnel": "Cindy-managed tunnel",
+ "agentProxyModeTunnelDesc": "Dedicated SSH tunnel back to your local proxy, fixed remote port, auto-reconnects",
+ "agentProxyModeEnv": "Bring your own proxy (env vars only)",
+ "agentProxyModeEnvDesc": "Provide a proxy URL reachable from the remote; you maintain the tunnel/reachability",
"agentProxyAddr": "Local proxy address",
- "agentProxyHint": "Opens a 127.0.0.1 port on the remote, tunneled over SSH back to your local proxy (e.g. Clash on 7890). {{appName}} does not provide a proxy — only the tunnel; the remote agent's HTTPS_PROXY points at the tunnel and domains are resolved by your proxy. Toggling restarts the remote codex daemon once to take effect.",
+ "agentProxyHint": "A fixed port on the remote 127.0.0.1 is tunneled over a dedicated, Cindy-managed SSH connection back to your local proxy (e.g. Clash on 7890). {{appName}} does not provide a proxy — only the tunnel; the remote agent's HTTPS_PROXY is pinned to the fixed port and never drifts on reconnect. Changing this restarts the remote codex daemon once.",
"agentProxyAddrInvalid": "Expected host:port, e.g. 127.0.0.1:7890",
- "cancel": "Cancel",
- "submit": "Add machine"
+ "agentProxyRemotePort": "Fixed remote port",
+ "agentProxyRemotePortInvalid": "Port must be an integer between 1 and 65535",
+ "agentProxyUrl": "Remote-reachable proxy URL",
+ "agentProxyUrlHint": "Resolved on the remote host: a proxy on the remote itself (e.g. your own autossh -R tunnel), a LAN proxy, etc. Supports http / https / socks5.",
+ "agentProxyUrlInvalid": "Must be an http(s):// or socks5:// URL without spaces or quotes"
},
"detail": {
"agentSetupTitle": "Agent setup",
@@ -292,11 +301,6 @@
"statusInstalled": "Installed",
"statusNotInstalled": "Not installed",
"claudeCodeName": "Claude Code",
- "agentProxyTitle": "Agent proxy tunnel",
- "agentProxyActive": "Remote 127.0.0.1:{{port}} → local {{target}} · established",
- "agentProxyPending": "Establishing tunnel → local {{target}}",
- "agentProxyWaiting": "Host not connected; tunnel will be established on reconnect → local {{target}}",
- "agentProxyError": "Tunnel failed: {{message}}",
"button": {
"install": "Install",
"reinstall": "Reinstall",
@@ -305,7 +309,15 @@
"run": "Run",
"syncAuth": "Sync auth",
"syncAuthTip": "Copy your local Codex credentials to this remote so you don't need to log in again there"
- }
+ },
+ "agentProxyTitle": "Agent proxy",
+ "agentProxyActive": "Remote 127.0.0.1:{{port}} → local {{target}} · established",
+ "agentProxyPending": "Establishing tunnel → local {{target}}",
+ "agentProxyWaiting": "Host not connected; resumes automatically on reconnect → local {{target}}",
+ "agentProxyError": "Proxy setup failed: {{message}}",
+ "agentProxyPortBusy": "Remote port {{port}} is busy; waiting for release and retrying… (change the port in settings if it stays busy)",
+ "agentProxyEnvInfo": "Env vars injected → {{url}} (you maintain the route)",
+ "agentProxyEnvPending": "Waiting to apply env vars → {{url}} (takes effect automatically once the host connects)"
},
"startSession": {
"title": "Start a remote Codex session",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 67f1e2c0d5..a19bd85925 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -272,13 +272,22 @@
"keyHint": "秘密鍵ファイルを直接読み込みます。パスフレーズは保存しないため、暗号化された鍵には非対応 — ssh-agent が使えない場合のみご使用ください。"
},
"identityFile": "秘密鍵ファイルのパス",
- "agentProxy": "Agent トラフィックをローカルプロキシ経由にする",
- "agentProxyTip": "リモートに 127.0.0.1 ポートを開き、SSH トンネルでこのマシンのプロキシに中継します。リモートの codex / Claude Code の通信がそこから出ます",
+ "cancel": "キャンセル",
+ "submit": "マシンを追加",
+ "agentProxy": "Agent トラフィックをプロキシ経由にする",
+ "agentProxyTip": "リモートの codex / Claude Code のモデル通信をプロキシ経由にします。Cindy が管理する SSH トンネルでローカルプロキシへ戻すか、リモートから到達可能なプロキシ URL を指定します",
+ "agentProxyModeTunnel": "Cindy 管理トンネル",
+ "agentProxyModeTunnelDesc": "専用 SSH トンネルでローカルプロキシへ中継。リモートポート固定、切断時は自動再接続",
+ "agentProxyModeEnv": "自前プロキシ(環境変数の注入のみ)",
+ "agentProxyModeEnvDesc": "リモートから到達可能なプロキシ URL を指定。トンネルや到達性はご自身で管理",
"agentProxyAddr": "ローカルプロキシのアドレス",
- "agentProxyHint": "リモートの 127.0.0.1 にポートを開き、SSH トンネルでローカルプロキシ(例: Clash の 7890)に中継します。{{appName}} はプロキシを提供せず、トンネルのみを張ります。リモート Agent の HTTPS_PROXY がトンネル口を指し、ドメインはお使いのプロキシ側で解決されます。切り替え後、リモートの codex daemon が一度再起動します。",
+ "agentProxyHint": "リモート 127.0.0.1 の固定ポートを、Cindy が管理する専用 SSH 接続でローカルプロキシ(例: Clash の 7890)へ中継します。{{appName}} はプロキシを提供せず、トンネルのみを張ります。リモート Agent の HTTPS_PROXY は固定ポートに固定され、再接続でずれません。設定変更後、リモートの codex daemon が一度再起動します。",
"agentProxyAddrInvalid": "host:port 形式で入力してください(例: 127.0.0.1:7890)",
- "cancel": "キャンセル",
- "submit": "マシンを追加"
+ "agentProxyRemotePort": "リモート固定ポート",
+ "agentProxyRemotePortInvalid": "ポートは 1〜65535 の整数で入力してください",
+ "agentProxyUrl": "リモートから到達可能なプロキシ URL",
+ "agentProxyUrlHint": "リモート側で解決されます。リモート上のプロキシ(例: autossh -R で自作したトンネル口)や LAN 内プロキシなど。http / https / socks5 に対応。",
+ "agentProxyUrlInvalid": "http(s):// または socks5:// で始まる URL を、空白や引用符なしで入力してください"
},
"detail": {
"agentSetupTitle": "エージェント設定",
@@ -292,11 +301,6 @@
"statusInstalled": "インストール済み",
"statusNotInstalled": "未インストール",
"claudeCodeName": "Claude Code",
- "agentProxyTitle": "Agent プロキシトンネル",
- "agentProxyActive": "リモート 127.0.0.1:{{port}} → ローカル {{target}} · 確立済み",
- "agentProxyPending": "トンネル確立中 → ローカル {{target}}",
- "agentProxyWaiting": "ホスト未接続 — 再接続後に自動確立 → ローカル {{target}}",
- "agentProxyError": "トンネルの確立に失敗: {{message}}",
"button": {
"install": "インストール",
"reinstall": "再インストール",
@@ -305,7 +309,15 @@
"run": "実行",
"syncAuth": "認証情報を同期",
"syncAuthTip": "ローカルの Codex 認証情報をこのリモートにコピーして、再ログインを省きます"
- }
+ },
+ "agentProxyTitle": "Agent プロキシ",
+ "agentProxyActive": "リモート 127.0.0.1:{{port}} → ローカル {{target}} · 確立済み",
+ "agentProxyPending": "トンネル確立中 → ローカル {{target}}",
+ "agentProxyWaiting": "ホスト未接続 — 再接続後に自動復旧 → ローカル {{target}}",
+ "agentProxyError": "プロキシ設定に失敗: {{message}}",
+ "agentProxyPortBusy": "リモートポート {{port}} が使用中です。解放を待って自動再試行します…(長く続く場合は設定でポートを変更してください)",
+ "agentProxyEnvInfo": "環境変数を注入済み → {{url}}(経路はご自身で管理)",
+ "agentProxyEnvPending": "環境変数の適用待ち → {{url}}(ホスト接続後に自動で反映)"
},
"startSession": {
"title": "このリモートで Codex セッションを開始",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index aa647ed5c5..a343d68534 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -272,13 +272,22 @@
"keyHint": "개인 키 파일을 직접 읽습니다. 암호를 저장하지 않으므로 암호화된 키는 지원되지 않습니다 — ssh-agent 를 사용할 수 없을 때만 사용하세요."
},
"identityFile": "개인 키 파일 경로",
- "agentProxy": "Agent 트래픽을 로컬 프록시로 우회",
- "agentProxyTip": "원격에 127.0.0.1 포트를 열고 SSH 터널로 이 컴퓨터의 프록시로 중계합니다. 원격 codex / Claude Code 트래픽이 그 경로로 나갑니다",
+ "cancel": "취소",
+ "submit": "머신 추가",
+ "agentProxy": "Agent 트래픽을 프록시로 우회",
+ "agentProxyTip": "원격 codex / Claude Code 모델 트래픽을 프록시로 내보냅니다. Cindy가 관리하는 SSH 터널로 로컬 프록시에 연결하거나, 원격에서 접근 가능한 프록시 URL을 직접 지정합니다",
+ "agentProxyModeTunnel": "Cindy 관리 터널",
+ "agentProxyModeTunnelDesc": "전용 SSH 터널로 로컬 프록시에 중계. 원격 포트 고정, 끊기면 자동 재연결",
+ "agentProxyModeEnv": "직접 준비한 프록시(환경 변수만 주입)",
+ "agentProxyModeEnvDesc": "원격에서 접근 가능한 프록시 주소를 입력하세요. 터널/도달성은 직접 관리합니다",
"agentProxyAddr": "로컬 프록시 주소",
- "agentProxyHint": "원격 127.0.0.1에 포트를 열고 SSH 터널로 로컬 프록시(예: Clash 7890)로 중계합니다. {{appName}}은(는) 프록시를 제공하지 않고 터널만 만듭니다. 원격 Agent의 HTTPS_PROXY가 터널 포트를 가리키고, 도메인은 프록시에서 해석됩니다. 전환 후 원격 codex daemon이 한 번 재시작됩니다.",
+ "agentProxyHint": "원격 127.0.0.1의 고정 포트를 Cindy가 관리하는 전용 SSH 연결로 로컬 프록시(예: Clash 7890)에 중계합니다. {{appName}}은(는) 프록시를 제공하지 않고 터널만 만듭니다. 원격 Agent의 HTTPS_PROXY는 고정 포트로 고정되어 재연결 시 변하지 않습니다. 설정을 바꾸면 원격 codex daemon이 한 번 재시작됩니다.",
"agentProxyAddrInvalid": "host:port 형식이어야 합니다(예: 127.0.0.1:7890)",
- "cancel": "취소",
- "submit": "머신 추가"
+ "agentProxyRemotePort": "원격 고정 포트",
+ "agentProxyRemotePortInvalid": "포트는 1~65535 사이의 정수여야 합니다",
+ "agentProxyUrl": "원격에서 접근 가능한 프록시 주소",
+ "agentProxyUrlHint": "원격 호스트에서 해석됩니다. 원격 자체의 프록시(예: autossh -R로 직접 만든 터널 포트), LAN 프록시 등. http / https / socks5 지원.",
+ "agentProxyUrlInvalid": "공백/따옴표 없이 http(s):// 또는 socks5:// URL이어야 합니다"
},
"detail": {
"agentSetupTitle": "에이전트 설정",
@@ -292,11 +301,6 @@
"statusInstalled": "설치됨",
"statusNotInstalled": "설치되지 않음",
"claudeCodeName": "Claude Code",
- "agentProxyTitle": "Agent 프록시 터널",
- "agentProxyActive": "원격 127.0.0.1:{{port}} → 로컬 {{target}} · 설정됨",
- "agentProxyPending": "터널 설정 중 → 로컬 {{target}}",
- "agentProxyWaiting": "호스트 미연결 — 재연결 후 자동 설정 → 로컬 {{target}}",
- "agentProxyError": "터널 설정 실패: {{message}}",
"button": {
"install": "설치",
"reinstall": "재설치",
@@ -305,7 +309,15 @@
"run": "실행",
"syncAuth": "인증 동기화",
"syncAuthTip": "로컬 Codex 자격 증명을 이 원격에 복사해서 다시 로그인하지 않도록 합니다"
- }
+ },
+ "agentProxyTitle": "Agent 프록시",
+ "agentProxyActive": "원격 127.0.0.1:{{port}} → 로컬 {{target}} · 설정됨",
+ "agentProxyPending": "터널 설정 중 → 로컬 {{target}}",
+ "agentProxyWaiting": "호스트 미연결 — 재연결 후 자동 복구 → 로컬 {{target}}",
+ "agentProxyError": "프록시 설정 실패: {{message}}",
+ "agentProxyPortBusy": "원격 포트 {{port}}이(가) 사용 중입니다. 해제를 기다려 자동 재시도합니다… (계속 사용 중이면 설정에서 포트를 변경하세요)",
+ "agentProxyEnvInfo": "환경 변수 주입됨 → {{url}} (경로는 직접 관리)",
+ "agentProxyEnvPending": "환경 변수 적용 대기 중 → {{url}} (호스트 연결 후 자동 적용)"
},
"startSession": {
"title": "이 원격에서 Codex 세션 시작",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 811bc6441a..727e0b75a6 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -272,13 +272,22 @@
"keyHint": "直接读私钥文件。为了不存密码,不支持加密的密钥 —— 仅在 ssh-agent 不可用时使用。"
},
"identityFile": "私钥文件路径",
- "agentProxy": "Agent 流量走本地 Proxy",
- "agentProxyTip": "在远端开一个 127.0.0.1 端口,经 SSH 隧道转回本机 Proxy,远端 codex / Claude Code 的流量由此流出",
+ "cancel": "取消",
+ "submit": "添加机器",
+ "agentProxy": "Agent 流量走 Proxy",
+ "agentProxyTip": "让远端 codex / Claude Code 的模型流量经 Proxy 流出:由 Cindy 代建 SSH 隧道回本机 Proxy,或直接注入你自备的远端可达 Proxy 地址",
+ "agentProxyModeTunnel": "Cindy 代建隧道",
+ "agentProxyModeTunnelDesc": "独立 SSH 隧道转回本机 Proxy,固定远端端口,断线自动重连保活",
+ "agentProxyModeEnv": "自备 Proxy(仅注入环境变量)",
+ "agentProxyModeEnvDesc": "填一个在远端可达的 Proxy 地址,隧道与可达性由你自行维护",
"agentProxyAddr": "本地 Proxy 地址",
- "agentProxyHint": "在远端 127.0.0.1 开端口,经 SSH 隧道转回本机 Proxy(如 Clash 的 7890)。{{appName}} 不提供 Proxy,只建隧道;远端 agent 的 HTTPS_PROXY 会指向隧道口,域名由你的 Proxy 解析。切换后远端 codex daemon 会重启一次以生效。",
+ "agentProxyHint": "远端 127.0.0.1 的固定端口经 Cindy 维护的独立 SSH 隧道转回本机 Proxy(如 Clash 的 7890)。{{appName}} 不提供 Proxy,只建隧道;远端 agent 的 HTTPS_PROXY 写死这个固定端口,重连不漂移。修改配置后远端 codex daemon 会重启一次以生效。",
"agentProxyAddrInvalid": "格式应为 host:port,例如 127.0.0.1:7890",
- "cancel": "取消",
- "submit": "添加机器"
+ "agentProxyRemotePort": "远端固定端口",
+ "agentProxyRemotePortInvalid": "端口应为 1-65535 的整数",
+ "agentProxyUrl": "远端可达的 Proxy 地址",
+ "agentProxyUrlHint": "该地址在远端解析:可以是远端本机 Proxy(如你用 autossh -R 自建的隧道口)、局域网 Proxy 等。支持 http / https / socks5。",
+ "agentProxyUrlInvalid": "应为 http:// 、https:// 或 socks5:// 开头的 URL,不含空格与引号"
},
"detail": {
"agentSetupTitle": "Agent 设置",
@@ -292,11 +301,6 @@
"statusInstalled": "已安装",
"statusNotInstalled": "未安装",
"claudeCodeName": "Claude Code",
- "agentProxyTitle": "Agent Proxy 隧道",
- "agentProxyActive": "远端 127.0.0.1 端口 {{port}} → 本机 {{target}} · 已建立",
- "agentProxyPending": "隧道建立中 → 本机 {{target}}",
- "agentProxyWaiting": "主机未连接,重连后自动建立 → 本机 {{target}}",
- "agentProxyError": "隧道建立失败:{{message}}",
"button": {
"install": "安装",
"reinstall": "重新安装",
@@ -305,7 +309,15 @@
"run": "运行",
"syncAuth": "同步登录态",
"syncAuthTip": "把本机的 Codex 凭证复制到这台远端,免去在远端重新登录"
- }
+ },
+ "agentProxyTitle": "Agent Proxy",
+ "agentProxyActive": "远端 127.0.0.1 端口 {{port}} → 本机 {{target}} · 已建立",
+ "agentProxyPending": "隧道建立中 → 本机 {{target}}",
+ "agentProxyWaiting": "主机未连接,重连后自动恢复 → 本机 {{target}}",
+ "agentProxyError": "Proxy 配置失败:{{message}}",
+ "agentProxyPortBusy": "远端端口 {{port}} 被占用,正在等待释放并自动重试…(长时间占用可在设置中更换端口)",
+ "agentProxyEnvInfo": "已注入环境变量 → {{url}}(通路由你自行维护)",
+ "agentProxyEnvPending": "等待应用环境变量 → {{url}}(主机连接后自动生效)"
},
"startSession": {
"title": "在这台远端开新 Codex 对话",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6242f060ea..f539f9bce5 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -12,6 +12,8 @@ interface ImportMeta {
readonly env: ImportMetaEnv;
}
+type AgentProxyPrefPayload = import('../shared/agentProxyConfig').SshHostAgentProxyPref;
+type AgentProxyTunnelStatePayload = import('../shared/agentProxyConfig').AgentProxyTunnelState;
type ModelAccessStatusPayload = import('../shared/modelAccess').ModelAccessStatus;
type AnalyticsSettingsPayload = import('../shared/analyticsSettings').AnalyticsSettingsPayload;
type RsbWindowCommand = import('../shared/rightSidebarWindow').RsbWindowCommand;
@@ -51,9 +53,9 @@ interface EnvCheckResult {
type RemoteHostSnapshot = import('@cindy/maker-remote-ssh').HostSnapshot & {
autoConnect: boolean;
/** Agent 流量经 SSH 隧道走本地 Proxy 的 per-host 配置; 未开启 → null。 */
- agentProxy: { enabled: boolean; localHost: string; localPort: number } | null;
+ agentProxy: AgentProxyPrefPayload | null;
/** 隧道实时状态 (main 进程内存态); 无记录 → null。 */
- agentProxyTunnel: { active: boolean; remotePort?: number; lastError?: string } | null;
+ agentProxyTunnel: AgentProxyTunnelStatePayload | null;
};
/** 设备互联:REST 设备视图(同 shared/deviceLinkIpc.ts DeviceLinkDeviceView) */
interface DeviceLinkDeviceInfo {
@@ -2839,7 +2841,7 @@ interface ElectronAPI {
authMethod?: 'agent' | 'key';
identityFile?: string;
/** 「Agent 流量走本地 Proxy」pref; null = 关闭, 缺省 = 不动。 */
- agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
+ agentProxy?: AgentProxyPrefPayload | null;
}) => Promise<{ host: RemoteHostSnapshot }>;
update: (host: {
id: string;
@@ -2848,7 +2850,7 @@ interface ElectronAPI {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
- agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
+ agentProxy?: AgentProxyPrefPayload | null;
}) => Promise<{ host: RemoteHostSnapshot }>;
remove: (id: string) => Promise<{ ok: true }>;
connect: (id: string) => Promise<{ host: RemoteHostSnapshot | null }>;
diff --git a/apps/desktop/src/shared/agentProxyConfig.ts b/apps/desktop/src/shared/agentProxyConfig.ts
new file mode 100644
index 0000000000..96c4dc8a8b
--- /dev/null
+++ b/apps/desktop/src/shared/agentProxyConfig.ts
@@ -0,0 +1,76 @@
+/**
+ * agentProxyConfig — 「Agent 流量走 Proxy」的跨进程共享类型与校验。
+ *
+ * main (ssh-host-prefs-store / agent-proxy) / preload / renderer 三端共用,
+ * 消除手写镜像类型的结构漂移风险 (变体字段不同, 漏同步时结构化类型会让
+ * renderer 静默吞掉新字段)。纯类型 + 纯函数, 不依赖 electron / node API。
+ */
+
+/**
+ * Agent 流量走 Proxy 的 per-host 配置, 两种模式:
+ * - mode='tunnel' (Cindy 代建隧道): 独立 SSH 连接维护
+ * `ssh -R <remotePort>:<localHost>:<localPort>`, 远端 agent env 指向
+ * http://127.0.0.1:<remotePort> (remotePort 为用户指定的固定端口)。
+ * - mode='env' (仅注入环境变量): 用户自己保证 proxyUrl 在远端可达,
+ * Cindy 只注入 env, 不建隧道。
+ */
+export type SshHostAgentProxyPref =
+ | {
+ enabled: boolean;
+ mode: 'tunnel';
+ localHost: string;
+ localPort: number;
+ /** 远端 127.0.0.1 固定绑定端口 (被占时等待/清理, 不顺延漂移)。 */
+ remotePort: number;
+ }
+ | {
+ enabled: boolean;
+ mode: 'env';
+ /** 远端可达的代理 URL, 如 http://127.0.0.1:7890 (在远端解析)。 */
+ proxyUrl: string;
+ };
+
+/**
+ * 隧道/应用的实时状态 (内存态, UI 卡片展示):
+ * connecting/active/port-busy/paused 来自代建隧道保活器;
+ * error 也可能来自 marker 对账失败 (env 模式同样会落)。
+ */
+export interface AgentProxyTunnelState {
+ phase: 'connecting' | 'active' | 'port-busy' | 'error' | 'paused';
+ remotePort?: number;
+ lastError?: string;
+}
+
+/**
+ * 旧 pref ({enabled,localHost,localPort} 无 mode, PR #715 动态端口方案)
+ * 迁移用的固定远端端口缺省值 — 旧动态分配的首选基数, 多数存量 daemon 的
+ * marker 本来就指向它, 迁移后通常无需重启 daemon。
+ */
+export const LEGACY_AGENT_PROXY_REMOTE_PORT = 17893;
+
+/** env 模式允许的代理 URL scheme (reqwest / node / curl 的公约数)。 */
+const PROXY_URL_SCHEMES = new Set(['http:', 'https:', 'socks5:', 'socks5h:']);
+
+/**
+ * 校验 env 模式的 proxyUrl; 非法返回 null。main 的 prefs/IPC 与 renderer
+ * 表单共用同一口径 — 两套标准会让用户填了合法表象却被 IPC 打回。
+ */
+export function normalizeAgentProxyUrl(raw: unknown): string | null {
+ if (typeof raw !== 'string') return null;
+ const trimmed = raw.trim();
+ // 引号/空白拒收: 值会进远端 shell marker 文件 (单引号包裹), 脏值晚到
+ // 远端才失败, 难排查。
+ if (!trimmed || /\s/.test(trimmed) || trimmed.includes("'") || trimmed.includes('"')) return null;
+ try {
+ const url = new URL(trimmed);
+ if (!PROXY_URL_SCHEMES.has(url.protocol)) return null;
+ if (!url.hostname) return null;
+ // 拒 userinfo (http://user:pass@host): 该值会持久化 + 写远端 marker 文件,
+ // 内嵌凭证会被当成非机密落盘/进日志 (review: PR #992 greptile P1)。
+ // 需要认证的代理让用户改用本机代理转发, 不接受凭证内嵌。
+ if (url.username || url.password) return null;
+ return trimmed;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/maker-remote-ssh/src/RemoteHost.ts b/packages/maker-remote-ssh/src/RemoteHost.ts
index 7e1403ec9a..75ea890973 100644
--- a/packages/maker-remote-ssh/src/RemoteHost.ts
+++ b/packages/maker-remote-ssh/src/RemoteHost.ts
@@ -112,6 +112,13 @@ export interface RemoteForwardSpec {
localPort: number;
/** 远端 127.0.0.1 首选绑定端口; 缺省 DEFAULT_REMOTE_FORWARD_PORT_BASE。 */
preferredRemotePort?: number;
+ /**
+ * true = 只绑 preferredRemotePort, 被占时**不**向后顺延探测 — 用于
+ * 「远端 env 写死固定端口」的隧道 (agent-proxy 固定端口模式): 端口漂移
+ * 意味着远端 daemon env 失效 + 必须重启 daemon, 比「暂时绑不上等重试」
+ * 代价大得多。被占时 armForward 抛错, 由调用方决定重试/清理残留监听。
+ */
+ exactRemotePort?: boolean;
/** 断线重连后端口被重绑到不同值时回调一次 (首次绑定不回调)。 */
onRearmed?: (remotePort: number) => void;
}
@@ -544,6 +551,9 @@ export class RemoteHost {
) {
throw new Error(`ensureRemoteForward: invalid preferredRemotePort ${spec.preferredRemotePort}`);
}
+ if (spec.exactRemotePort && spec.preferredRemotePort === undefined) {
+ throw new Error('ensureRemoteForward: exactRemotePort requires preferredRemotePort');
+ }
const key = forwardKey(spec);
const existing = this.forwards.get(key);
if (existing) {
@@ -674,9 +684,14 @@ export class RemoteHost {
this.attachForwardListener(client);
const base = record.spec.preferredRemotePort ?? DEFAULT_REMOTE_FORWARD_PORT_BASE;
- const candidates = [record.remotePort];
- for (let i = 0; i < REMOTE_FORWARD_PORT_SCAN_SPAN; i++) {
- if (!candidates.includes(base + i)) candidates.push(base + i);
+ // exact 模式恒试 preferred 而非 record.remotePort (review: PR #992
+ // copilot): 同 key 的 record 可能是在非 exact 阶段顺延漂到别的端口的,
+ // 以漂移值为种子会把「固定端口」语义吃回去。
+ const candidates = record.spec.exactRemotePort ? [base] : [record.remotePort];
+ if (!record.spec.exactRemotePort) {
+ for (let i = 0; i < REMOTE_FORWARD_PORT_SCAN_SPAN; i++) {
+ if (!candidates.includes(base + i)) candidates.push(base + i);
+ }
}
const errors: string[] = [];
for (const port of candidates) {
diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts
index 1a658b61ea..e890dfa426 100644
--- a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts
@@ -464,3 +464,76 @@ describe('RemoteHost remote forwarding', () => {
expect(client.forwardInCalls).toHaveLength(1);
});
});
+
+describe('RemoteHost remote forwarding — exactRemotePort (固定端口)', () => {
+ it('binds only the fixed port and succeeds when it is free', async () => {
+ const client = new FakeClient();
+ const host = makeReadyHost(client);
+ const fwd = await host.ensureRemoteForward({
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ preferredRemotePort: 45000,
+ exactRemotePort: true,
+ });
+ expect(fwd.remotePort).toBe(45000);
+ expect(client.forwardInCalls).toEqual([{ addr: '127.0.0.1', port: 45000 }]);
+ });
+
+ it('fails without falling back to other candidates when the fixed port is busy', async () => {
+ // 固定端口语义: 远端 env 写死该端口, 顺延 = env 失效 + 必须重启 daemon,
+ // 宁可失败让调用方 (agent-proxy 保活器) 重试/清理残留监听。
+ const client = new FakeClient((port) => port !== 45000);
+ const host = makeReadyHost(client);
+ await expect(
+ host.ensureRemoteForward({
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ preferredRemotePort: 45000,
+ exactRemotePort: true,
+ }),
+ ).rejects.toThrow(/remote port forwarding failed/);
+ expect(client.forwardInCalls).toEqual([{ addr: '127.0.0.1', port: 45000 }]);
+ });
+
+ it('rejects exactRemotePort without preferredRemotePort at the entrance', async () => {
+ const client = new FakeClient();
+ const host = makeReadyHost(client);
+ await expect(
+ host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890, exactRemotePort: true }),
+ ).rejects.toThrow(/exactRemotePort requires preferredRemotePort/);
+ expect(client.forwardInCalls).toHaveLength(0);
+ });
+
+ it('exact mode seeds the fixed port even when the record previously drifted (PR #992 copilot)', async () => {
+ // 同 key 的 record 先在非 exact 阶段顺延漂到别的端口; 之后同 key 改
+ // exactRemotePort=true 重绑时, 候选必须回到 preferred 固定端口, 不得以
+ // 漂移值为种子把「固定端口」语义吃回去。
+ const client = new FakeClient((port) => port !== 45000 && port !== 45001);
+ const host = makeReadyHost(client);
+ // 非 exact: 45000、45001 都被占 → 顺延到 45002 (record 漂到 45002)。
+ const fwd = await host.ensureRemoteForward({
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ preferredRemotePort: 45000,
+ });
+ expect(fwd.remotePort).toBe(45002);
+ expect(client.forwardInCalls).toEqual([
+ { addr: '127.0.0.1', port: 45000 },
+ { addr: '127.0.0.1', port: 45001 },
+ { addr: '127.0.0.1', port: 45002 },
+ ]);
+ // 模拟同 record 在 exact 语义下重绑 (断开愿望, 以 exact 重新登记)。
+ await host.closeRemoteForward('127.0.0.1', 7890);
+ const client2 = new FakeClient((port) => port === 45000); // 45000 现在可用
+ (host as unknown as { client: unknown }).client = client2;
+ const exact = await host.ensureRemoteForward({
+ localHost: '127.0.0.1',
+ localPort: 7890,
+ preferredRemotePort: 45000,
+ exactRemotePort: true,
+ });
+ expect(exact.remotePort).toBe(45000);
+ // 只试了固定端口 45000 — 没有从漂移的 45002 开始。
+ expect(client2.forwardInCalls).toEqual([{ addr: '127.0.0.1', port: 45000 }]);
+ });
+});