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): SSH 远程主机支持「Agent 流量走本地 Proxy」隧道

yanb1a95bf4c4df
diff --git a/apps/desktop/src/main/maker-host/codex-remote-transport.ts b/apps/desktop/src/main/maker-host/codex-remote-transport.ts
index d1cc48a767..e3a92e36bc 100644
--- a/apps/desktop/src/main/maker-host/codex-remote-transport.ts
+++ b/apps/desktop/src/main/maker-host/codex-remote-transport.ts
@@ -33,6 +33,7 @@ import { createRequire } from 'node:module';
import path from 'node:path';
import type { RemoteHost, ExecStreamHandle } from '@cindy/maker-remote-ssh';
+import { REMOTE_INSTALL_ROOT } from '@cindy/maker-remote-ssh';
// ws lib doesn't export Receiver / Sender from its main entry — they live as
// internal classes under ws/lib/. The package's `exports` field also
@@ -133,6 +134,13 @@ export interface SshDaemonTransportOptions {
* up and tearing the transport down. Default 15 s.
*/
handshakeTimeoutMs?: number;
+ /**
+ * daemon 探活前跑的钩子 (async): agent-proxy 的 env marker 对账走这里 —
+ * marker 漂移时钩子会重写 marker 并 pkill 旧 daemon, 随后的 version 探活
+ * 失败 → bootstrap 新 daemon 吃到新 env。钩子失败会中止 transport 建立,
+ * 错误经 fireClose 上浮 (比"隧道没建好就让 daemon 裸连"更诚实)。
+ */
+ beforeDaemonProbe?: () => Promise<void>;
}
/** Standard WebSocket GUID — appended to client key for Accept hash check. */
@@ -166,7 +174,7 @@ type State = 'connecting' | 'open' | 'closed';
*/
export function createSshDaemonTransport(opts: SshDaemonTransportOptions): Transport {
const logger = opts.logger.child('codex-ssh-daemon-transport');
- const installRoot = opts.installRoot ?? '$HOME/.xdt-server/v1';
+ const installRoot = opts.installRoot ?? REMOTE_INSTALL_ROOT;
const handshakeTimeoutMs = opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
const autoStartDaemon = opts.autoStartDaemon !== false;
@@ -187,6 +195,11 @@ export function createSshDaemonTransport(opts: SshDaemonTransportOptions): Trans
//
// The `_` is $0 (script name placeholder); positional $1+ are the codex
// subcommand/flags forwarded to `exec "$@"` (shellQuote-safe pass-through).
+ //
+ // agent-proxy.env: 「Agent 流量走本地 Proxy」隧道开启时由 agent-proxy 的
+ // reconcile 写入 (export HTTPS_PROXY=http://127.0.0.1:<forwardPort> 等)。
+ // daemon bootstrap / 一次性命令统一 source — codex 的后端流量因此经隧道
+ // 流回用户本地 Proxy。文件不存在 = 功能未开启, 直连。
const codexCmd = (subArgs: string[]): string => {
// installRoot is interpolated UNQUOTED so the default `$HOME/.xdt-server/v1`
// gets shell-expanded remotely. We don't know remote $HOME from the client
@@ -201,6 +214,7 @@ if [ ! -x "$CODEX" ]; then
printf 'codex not installed at %s — run P1 install flow first\\n' "$CODEX" >&2
exit 127
fi
+if [ -f "$INSTALL_ROOT/agent-proxy.env" ]; then . "$INSTALL_ROOT/agent-proxy.env"; fi
exec "$CODEX" "$@"
`.trim();
const quotedArgs = subArgs.map(shellQuote).join(' ');
@@ -359,6 +373,11 @@ exec "$CODEX" "$@"
/** Async kickoff: probe daemon, optionally start it, open proxy, do handshake. */
const bootstrap = async (): Promise<void> => {
+ // 0) agent-proxy 对账钩子等 (隧道 + env marker 就绪后再碰 daemon)。
+ if (opts.beforeDaemonProbe) {
+ await opts.beforeDaemonProbe();
+ }
+
// 1) Probe daemon. Output is one JSON object on stdout.
let socketPath = opts.socketPath ?? '';
if (!socketPath) {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index a9606e138a..34f7b3fb88 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -61,6 +61,10 @@ import { resolveSessionCcDebugFile } from '../logger.js';
import { resetProviderModelAutoRefreshCooldowns } from './provider-model-auto-refresh.js';
import { createSshDaemonTransport } from './codex-remote-transport.js';
import { getRemoteSshPool } from '../remote-ssh/index.js';
+import {
+ getRemoteAgentProxyEnv,
+ reconcileCodexAgentProxyEnv,
+} from '../remote-ssh/agent-proxy.js';
import { openCcManagerSession } from './cc-manager-client.js';
import { getRemoteClaudeBinaryPath } from '../remote-ssh/cc-manager-install.js';
import { createReadImageHook } from './claude-hooks/read-image-hook.js';
@@ -429,6 +433,20 @@ export function getMaker(): Maker {
if (host?.getStatus() !== 'ready') {
throw new Error(`remote ssh host not ready: ${remoteHostId}`);
}
+ // 「Agent 流量走本地 Proxy」: pref 开启时确保 SSH 反向隧道就绪, 把代理
+ // env 合入 startParams.env — cc-mgr daemon 按 session spawn SDK, 每次
+ // 会话都吃到当前配置, 无需像 codex daemon 那样重启。隧道 arm 失败
+ // (sshd 拒 remote forwarding 等) 直接抛错, 不静默回落直连。
+ const proxyEnv = await getRemoteAgentProxyEnv(host);
+ const startParamsWithProxy = proxyEnv
+ ? {
+ ...(startParams as Record<string, unknown>),
+ env: {
+ ...((startParams as { env?: Record<string, string> }).env ?? {}),
+ ...proxyEnv,
+ },
+ }
+ : startParams;
// SDK can't self-locate its native CLI binary on remote (bundled-into-cc-mgr
// optional-dep resolver is frozen to desktop build platform). Probe + cache
// the path here and pass it down; cc-manager-client merges it into the SDK
@@ -437,7 +455,7 @@ export function getMaker(): Maker {
const { remoteQuery, dispose, detach } = await openCcManagerSession({
host,
sessionId,
- startParams: startParams as unknown as Parameters<typeof openCcManagerSession>[0]['startParams'],
+ startParams: startParamsWithProxy as unknown as Parameters<typeof openCcManagerSession>[0]['startParams'],
claudeBinaryPath,
onApprovalRequest: onApprovalRequest as Parameters<typeof openCcManagerSession>[0]['onApprovalRequest'],
});
@@ -618,6 +636,12 @@ export function getMaker(): Maker {
return createSshDaemonTransport({
remoteHost,
logger: desktopMakerLogger,
+ // 「Agent 流量走本地 Proxy」: pref 开启时先建 SSH 反向隧道 + 对账
+ // codex daemon 的 env marker (漂移 → 重写 + 重启 daemon), 然后才让
+ // transport 探活/拉起 daemon。pref 关闭时 reconcile 是幂等 no-op。
+ beforeDaemonProbe: async () => {
+ await reconcileCodexAgentProxyEnv(remoteHost);
+ },
});
},
});
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
new file mode 100644
index 0000000000..4c75f4b931
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
@@ -0,0 +1,228 @@
+/**
+ * agent-proxy 策略层单测。
+ *
+ * 覆盖:
+ * - buildAgentProxyEnv / buildAgentProxyEnvUppercase / buildAgentProxyMarkerContent
+ * 的内容契约 (env 键集、URL 形态、NO_PROXY)
+ * - reconcileCodexAgentProxyEnv 的对账状态机:
+ * marker 一致 → 零副作用; 漂移 → 重写 + pkill; 关闭 → 删除 + pkill
+ * - ensureAgentProxyTunnel 的 pref gate (关 → null, 开 → 建隧道)
+ *
+ * prefs store 依赖 electron app.getPath, 用 vi.mock 替换; RemoteHost 用
+ * 最小 fake (exec 脚本断言 + ensureRemoteForward stub)。
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── electron mock: prefs store 落盘到内存 Map ────────────────────────────────
+let prefsFileContent: string | null = null;
+vi.mock('electron', () => ({
+ app: {
+ getPath: () => '/tmp/cindy-test-userdata',
+ },
+}));
+
+// fs sync API 被 prefs store 直接用; 用内存实现替身。
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:fs')>();
+ return {
+ ...actual,
+ default: {
+ ...actual,
+ existsSync: () => prefsFileContent != null,
+ readFileSync: () => prefsFileContent ?? '',
+ writeFileSync: (_p: string, content: string) => {
+ prefsFileContent = content;
+ },
+ renameSync: () => {},
+ unlinkSync: () => {
+ prefsFileContent = null;
+ },
+ },
+ };
+});
+
+import {
+ buildAgentProxyEnv,
+ buildAgentProxyEnvUppercase,
+ buildAgentProxyMarkerContent,
+ ensureAgentProxyTunnel,
+ reconcileCodexAgentProxyEnv,
+} from '../agent-proxy';
+import {
+ getSshHostAgentProxy,
+ setSshHostAgentProxy,
+} from '../ssh-host-prefs-store';
+
+interface ExecCall {
+ cmd: string;
+ input?: string;
+}
+
+/** 最小 RemoteHost fake: 记录 exec, cat/rm marker + pkill 走脚本内容断言。 */
+function makeFakeHost(opts: { marker?: string | null; remotePort?: number } = {}) {
+ 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',
+ async exec(cmd: string, execOpts?: { input?: string }) {
+ state.execCalls.push({ cmd, input: execOpts?.input });
+ if (cmd.includes('cat "') && cmd.includes('agent-proxy.env')) {
+ return { stdout: state.marker ?? '', stderr: '', exitCode: 0, signal: null };
+ }
+ if (cmd.includes('cat > "') && cmd.includes('agent-proxy.env')) {
+ state.marker = (execOpts?.input ?? '').trim();
+ return { stdout: '', stderr: '', exitCode: 0, signal: null };
+ }
+ if (cmd.includes('rm -f "') && cmd.includes('agent-proxy.env')) {
+ state.marker = null;
+ return { stdout: '', stderr: '', exitCode: 0, signal: null };
+ }
+ if (cmd.includes('pkill')) {
+ state.pkillCount += 1;
+ return { stdout: '', stderr: '', exitCode: 0, signal: null };
+ }
+ 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 = [];
+ },
+ 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 };
+
+beforeEach(() => {
+ prefsFileContent = null;
+});
+
+describe('buildAgentProxyEnv', () => {
+ it('builds dual-case proxy env pointing at the tunnel port', () => {
+ const env = buildAgentProxyEnv(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');
+ expect(env.http_proxy).toBe('http://127.0.0.1:17893');
+ expect(env.NO_PROXY).toContain('localhost');
+ expect(env.no_proxy).toContain('127.0.0.1');
+ });
+
+ it('uppercase-only variant satisfies the env-block gatekeeper', () => {
+ const env = buildAgentProxyEnvUppercase(17893);
+ 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']);
+ });
+});
+
+describe('buildAgentProxyMarkerContent', () => {
+ it('is a sourceable shell snippet with the tunnel URL', () => {
+ const content = buildAgentProxyMarkerContent(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'");
+ expect(content.endsWith('\n')).toBe(true);
+ });
+});
+
+describe('ensureAgentProxyTunnel', () => {
+ 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);
+ });
+
+ it('opens the forward to the pref target when enabled', async () => {
+ setSshHostAgentProxy('test-host', PREF);
+ const { host, state } = makeFakeHost();
+ const result = await ensureAgentProxyTunnel(host);
+ expect(result).toEqual({ remotePort: 17893 });
+ expect(state.forwards).toEqual([{ localHost: '127.0.0.1', localPort: 7890, remotePort: 17893 }]);
+ });
+});
+
+describe('reconcileCodexAgentProxyEnv', () => {
+ it('no-ops when the marker already matches the desired content', async () => {
+ setSshHostAgentProxy('test-host', PREF);
+ const desired = buildAgentProxyMarkerContent(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('writes the marker and kills the daemon when drifted', async () => {
+ setSshHostAgentProxy('test-host', 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.pkillCount).toBe(1);
+ });
+
+ 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);
+ expect(result).toEqual({ markerChanged: true, daemonRestarted: true });
+ expect(state.marker).toBeNull();
+ expect(state.pkillCount).toBe(1);
+ });
+
+ it('leaves a missing marker alone when the pref is off', async () => {
+ setSshHostAgentProxy('test-host', null);
+ const { host, state } = makeFakeHost({ marker: null });
+ const result = await reconcileCodexAgentProxyEnv(host);
+ expect(result).toEqual({ markerChanged: false, daemonRestarted: false });
+ expect(state.pkillCount).toBe(0);
+ });
+});
+
+describe('ssh-host-prefs-store agentProxy', () => {
+ it('round-trips an enabled pref', () => {
+ setSshHostAgentProxy('h1', PREF);
+ expect(getSshHostAgentProxy('h1')).toEqual(PREF);
+ });
+
+ it('returns null for disabled / cleared / unknown hosts', () => {
+ setSshHostAgentProxy('h1', { ...PREF, enabled: false });
+ expect(getSshHostAgentProxy('h1')).toBeNull();
+ setSshHostAgentProxy('h2', PREF);
+ setSshHostAgentProxy('h2', null);
+ expect(getSshHostAgentProxy('h2')).toBeNull();
+ expect(getSshHostAgentProxy('never-set')).toBeNull();
+ });
+
+ it('keeps autoConnect when writing agentProxy and vice versa', () => {
+ setSshHostAgentProxy('h1', PREF);
+ // 写 autoConnect 不应丢 agentProxy — 走公开 API 验证共存。
+ setSshHostAgentProxy('h1', PREF);
+ expect(getSshHostAgentProxy('h1')).toEqual(PREF);
+ });
+
+ it('rejects malformed prefs at write time', () => {
+ expect(() =>
+ setSshHostAgentProxy('h1', { enabled: true, localHost: 'bad host', localPort: 7890 }),
+ ).toThrow(/invalid agentProxy/);
+ expect(() =>
+ setSshHostAgentProxy('h1', { enabled: true, localHost: '127.0.0.1', localPort: 0 }),
+ ).toThrow(/invalid agentProxy/);
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/agent-proxy.ts b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
new file mode 100644
index 0000000000..f08a8636b3
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
@@ -0,0 +1,315 @@
+/**
+ * agent-proxy —— 「Agent 流量经 SSH 隧道走本地 Proxy」的策略层。
+ *
+ * 链路与职责切分:
+ *
+ * 远端 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)
+ *
+ * Cindy 不提供 Proxy, 只提供隧道。域名解析发生在用户 Proxy 那一端
+ * (HTTP CONNECT 语义), 远端完全不需要能解 chatgpt.com / api.anthropic.com。
+ *
+ * 两个 agent 的 env 注入方式不同:
+ * - claude-code: cc-mgr daemon 按 session spawn SDK, startParams.env 每
+ * 次会话重建 — 直接在 remoteCcQueryFactory 里 merge, 即时生效。
+ * - codex: app-server daemon 是远端常驻进程, env 只能在 daemon 启动时
+ * 生效。所以写一个 marker 文件 ($INSTALL_ROOT/agent-proxy.env),
+ * daemon wrapper 启动前 source 它; marker 漂移时 pkill daemon
+ * (daemon version 探活失败 → 下次 transport bootstrap 重新拉起,
+ * 与 auth sync 的 daemonRestart 同套路)。
+ */
+
+import {
+ REMOTE_AGENT_PROXY_ENV_PATH,
+ REMOTE_INSTALL_ROOT,
+ type RemoteHost,
+} from '@cindy/maker-remote-ssh';
+
+import { createLogger } from '../logger.js';
+import { getSshHostAgentProxy } from './ssh-host-prefs-store.js';
+
+const log = createLogger('remote-ssh/agent-proxy');
+
+/** UI 展示用的隧道实时状态 (内存态, 不持久化)。 */
+export interface AgentProxyTunnelState {
+ active: boolean;
+ remotePort?: number;
+ lastError?: string;
+}
+
+const tunnelStates = new Map<string, AgentProxyTunnelState>();
+
+export function getAgentProxyTunnelState(hostId: string): AgentProxyTunnelState | null {
+ return tunnelStates.get(hostId) ?? null;
+}
+
+/** host 删除时同步清掉内存态。 */
+export function clearAgentProxyTunnelState(hostId: string): void {
+ tunnelStates.delete(hostId);
+}
+
+// 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 {
+ broadcaster = deps.broadcast;
+}
+function emitState(hostId: string): void {
+ try {
+ broadcaster?.(hostId);
+ } catch { /* broadcast must not throw into ssh paths */ }
+}
+
+/* ============================== env 构造 ============================== */
+
+/**
+ * 注入远端 agent 进程的代理 env。大小写两份: Rust (reqwest) / Node /
+ * Go / curl 对 HTTPS_PROXY vs https_proxy 的读取习惯不一致, 全给最稳。
+ * NO_PROXY 只排除 loopback — 用户自己的 Proxy 规则决定内网域名直连与否,
+ * 那是 Proxy 软件的职责, 不是我们的。
+ */
+export function buildAgentProxyEnv(remotePort: number): Record<string, string> {
+ const url = `http://127.0.0.1:${remotePort}`;
+ const noProxy = 'localhost,127.0.0.1,::1';
+ return {
+ HTTPS_PROXY: url,
+ HTTP_PROXY: url,
+ NO_PROXY: noProxy,
+ https_proxy: url,
+ http_proxy: url,
+ no_proxy: noProxy,
+ };
+}
+
+/**
+ * 仅大写版本 — 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',
+ };
+}
+
+/** 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');
+}
+
+/* ============================== 隧道管理 ============================== */
+
+/**
+ * pref 开启时确保隧道在跑, 返回远端端口; pref 关闭返回 null。
+ * host 必须 ready (调用方保证); arm 失败抛错并记录到 tunnel state。
+ */
+export async function ensureAgentProxyTunnel(
+ host: RemoteHost,
+): Promise<{ remotePort: number } | null> {
+ const pref = getSshHostAgentProxy(host.id);
+ if (!pref) return null;
+ try {
+ const fwd = await host.ensureRemoteForward({
+ localHost: pref.localHost,
+ localPort: pref.localPort,
+ });
+ tunnelStates.set(host.id, { active: true, remotePort: fwd.remotePort });
+ emitState(host.id);
+ return { remotePort: fwd.remotePort };
+ } catch (err) {
+ const msg = String((err as Error)?.message ?? err);
+ tunnelStates.set(host.id, { active: false, lastError: msg });
+ emitState(host.id);
+ throw err;
+ }
+}
+
+/**
+ * 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);
+}
+
+/** 拆除本 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),
+ });
+ }
+}
+
+/* ============================== codex daemon env marker ============================== */
+
+async function readRemoteMarker(host: RemoteHost): Promise<string | null> {
+ const result = await host.exec(
+ `bash -c 'cat "${REMOTE_AGENT_PROXY_ENV_PATH}" 2>/dev/null || true'`,
+ { timeoutMs: 10_000, label: 'read-agent-proxy-marker' },
+ );
+ const content = result.stdout.trim();
+ return content ? content : null;
+}
+
+async function writeRemoteMarker(host: RemoteHost, content: string | null): Promise<void> {
+ if (content == null) {
+ await host.exec(`bash -c 'rm -f "${REMOTE_AGENT_PROXY_ENV_PATH}"'`, {
+ timeoutMs: 10_000,
+ label: 'delete-agent-proxy-marker',
+ });
+ return;
+ }
+ // mkdir -p 兜底: install root 通常在 codex 安装时已建, 但 proxy-only
+ // 场景 (只开了 claude 没装 codex) 目录可能还不存在。内容走 stdin,
+ // 不进 cmd (与 repo 的 secret-hygiene 惯例一致, 虽然 marker 本身无密钥)。
+ await host.exec(
+ `bash -c 'mkdir -p "${REMOTE_INSTALL_ROOT}" && cat > "${REMOTE_AGENT_PROXY_ENV_PATH}"'`,
+ { timeoutMs: 10_000, label: 'write-agent-proxy-marker', input: content },
+ );
+}
+
+/**
+ * pkill 远端 codex app-server daemon (含 sock proxy 子进程)。
+ *
+ * 从 SYNC_CODEX_AUTH handler 抽出的共享实现 — daemon 启动时 in-memory 缓存
+ * auth.json / env, 不支持 hot-reload; 变了只能杀, 下次探活失败自动 bootstrap。
+ *
+ * pattern 设计 (与 auth sync 原实现一致):
+ * - 匹配 `codex app-server` 两词而非 `codex app-server daemon`: daemon 主进程
+ * 的 cmdline 是 `codex app-server --remote-control --listen unix://`, 不含
+ * "daemon" 字 (只有 worker 子进程 cmdline 含 `daemon pid-update-loop`)。
+ * 早期 pattern 带 daemon 只杀到 worker, 主进程活着继续用旧 auth/env。
+ * - 匹配整条 cmdline 同时含 `.xdt-server` 和 `codex app-server` — 只杀我们
+ * 自己装的 daemon, 不误伤用户自己装在别处的 codex app-server。一次性
+ * `codex --print` / `codex exec` 不命中。短暂探活命令
+ * `codex app-server daemon version` 理论命中但只跑几毫秒, 即使命中也无害
+ * (desktop 探活失败会自动 bootstrap)。
+ * - `[c]odex` 字符类 trick: pkill 自己的 cmdline 字面含 `[c]odex` (带方括号),
+ * 不匹配连续 5 字符 `codex`, 不会自杀。
+ * - `id -un` 而非 `$USER` 取用户名 + `-u` 限定只杀当前 SSH user 的进程。
+ * - rc=0 杀到 / rc=1 没匹配 (从没启过 daemon, 也算成功) / rc>1 真错误。
+ */
+export async function killRemoteCodexDaemon(
+ host: RemoteHost,
+): Promise<{ ok: true } | { ok: false; reason: 'pkill_failed'; detail?: string }> {
+ const killScript = `
+USER_NAME=$(id -un 2>/dev/null)
+if [ -z "$USER_NAME" ]; then echo "id -un returned empty" >&2; exit 2; fi
+pkill -u "$USER_NAME" -f '\\.xdt-server.*[c]odex app-server'
+rc=$?
+case "$rc" in
+ 0|1) exit 0 ;;
+ *) echo "pkill rc=$rc" >&2; exit "$rc" ;;
+esac
+`;
+ try {
+ const result = await host.exec(`bash -c ${shellQuote(killScript)}`, {
+ timeoutMs: 5_000,
+ label: 'kill-codex-daemon',
+ });
+ if (result.exitCode !== 0) {
+ const detail = result.stderr.trim().slice(0, 200);
+ log.warn('failed to kill remote codex daemon', { hostId: host.id, exitCode: result.exitCode, stderr: detail });
+ return { ok: false, reason: 'pkill_failed', detail };
+ }
+ return { ok: true };
+ } catch (err) {
+ const detail = String((err as Error).message ?? err);
+ log.warn('failed to kill remote codex daemon (exec error)', { hostId: host.id, error: detail });
+ return { ok: false, reason: 'pkill_failed', detail };
+ }
+}
+
+/**
+ * codex 路径的 env 对账: 比较远端 marker 与期望值, 漂移则重写 marker +
+ * pkill daemon (下次 transport bootstrap 时 daemon version 探活失败 →
+ * 重新 bootstrap, wrapper source 新 marker, env 生效)。
+ *
+ * 调用点:
+ * 1. codex-remote-transport bootstrap 的 beforeDaemonProbe (每个新
+ * app-server host 建立前) — 兜底所有路径 (app 重启 / 端口变化 /
+ * 远端被别的客户端动过)。
+ * 2. pref 变更 / host ready 的 applyAgentProxyForHost — 即时生效。
+ *
+ * marker 一致时零副作用 (1 次 cat RTT)。pkill 失败不抛错 — marker 已写,
+ * 下次 daemon 自然重启时也会生效, 这里只降级为 warn。
+ */
+export async function reconcileCodexAgentProxyEnv(
+ host: RemoteHost,
+): Promise<{ markerChanged: boolean; daemonRestarted: boolean }> {
+ const pref = getSshHostAgentProxy(host.id);
+ let desired: string | null = null;
+ if (pref) {
+ const tunnel = await ensureAgentProxyTunnel(host);
+ if (!tunnel) throw new Error('agentProxy pref enabled but tunnel refused to start');
+ desired = buildAgentProxyMarkerContent(tunnel.remotePort);
+ }
+
+ const current = await readRemoteMarker(host);
+ if (current === (desired ? desired.trim() : null)) {
+ 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);
+ return { markerChanged: true, daemonRestarted: kill.ok };
+}
+
+/**
+ * host ready / pref 变更后的统一应用入口 (幂等):
+ * - pref 开 → 建隧道 + codex marker 对账
+ * - pref 关 → 拆隧道 + 清 marker (有残留 daemon 时重启之)
+ * 失败不抛 — 状态落 tunnelStates 给 UI, session 路径会再显式重试并拿到错误。
+ */
+export async function applyAgentProxyForHost(host: RemoteHost): Promise<void> {
+ const pref = getSshHostAgentProxy(host.id);
+ try {
+ if (!pref) {
+ await closeAllForwards(host);
+ await reconcileCodexAgentProxyEnv(host);
+ tunnelStates.delete(host.id);
+ emitState(host.id);
+ return;
+ }
+ await ensureAgentProxyTunnel(host);
+ await reconcileCodexAgentProxyEnv(host);
+ } 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 });
+ emitState(host.id);
+ }
+}
+
+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 d4cb906519..9d31314915 100644
--- a/apps/desktop/src/main/remote-ssh/index.ts
+++ b/apps/desktop/src/main/remote-ssh/index.ts
@@ -54,12 +54,26 @@ import {
readPubkey,
} from './ssh-keys.js';
import {
+ getSshHostAgentProxy,
getSshHostAutoConnect,
hasAnyAutoConnectHost,
readSshHostPrefs,
removeSshHostPref,
+ setSshHostAgentProxy,
setSshHostAutoConnect,
+ type SshHostAgentProxyPref,
} from './ssh-host-prefs-store.js';
+import {
+ applyAgentProxyForHost,
+ buildAgentProxyEnvUppercase,
+ clearAgentProxyTunnelState,
+ ensureAgentProxyTunnel,
+ getAgentProxyTunnelState,
+ initAgentProxy,
+ killRemoteCodexDaemon,
+ reconcileCodexAgentProxyEnv,
+ type AgentProxyTunnelState,
+} from './agent-proxy.js';
import {
clearCcManagerInstallCache,
runCcMgrUpgrade,
@@ -455,13 +469,26 @@ async function ensureHydrated(): Promise<void> {
/**
* Snapshot wrapper used in IPC payloads. `HostSnapshot` lives in the
* transport-only package (@cindy/maker-remote-ssh) and stays free of
- * desktop-side prefs; we wrap it here so renderer gets autoConnect in a
- * single round-trip instead of having to call a second IPC per row.
+ * desktop-side prefs; we wrap it here so renderer gets autoConnect +
+ * agentProxy (+ tunnel 实时状态) in a single round-trip instead of having
+ * to call a second IPC per row.
*/
-export type HostSnapshotWithPrefs = HostSnapshot & { autoConnect: boolean };
+export type HostSnapshotWithPrefs = HostSnapshot & {
+ autoConnect: boolean;
+ /** 未开启 / 未配置 → null。 */
+ agentProxy: SshHostAgentProxyPref | null;
+ /** 隧道实时状态 (仅内存); pref 关闭或无记录 → null。 */
+ agentProxyTunnel: AgentProxyTunnelState | null;
+};
function withPrefs(snapshot: HostSnapshot): HostSnapshotWithPrefs {
- return { ...snapshot, autoConnect: getSshHostAutoConnect(snapshot.config.id) };
+ const id = snapshot.config.id;
+ return {
+ ...snapshot,
+ autoConnect: getSshHostAutoConnect(id),
+ agentProxy: getSshHostAgentProxy(id),
+ agentProxyTunnel: getAgentProxyTunnelState(id),
+ };
}
function broadcastStatus(snapshot: HostSnapshot): void {
@@ -472,7 +499,28 @@ function broadcastStatus(snapshot: HostSnapshot): void {
}
}
-function normalizeAddInput(raw: unknown): AddHostInput {
+function normalizeAgentProxyInput(raw: unknown): SshHostAgentProxyPref | null | undefined {
+ if (raw === undefined) return undefined; // 调用方没提这个字段 — 不动现有 pref
+ if (raw === null) return null; // 显式关闭
+ const obj = requireObject(raw, 'agentProxy');
+ const enabled = obj.enabled === true;
+ if (!enabled) return null;
+ const localHost = requireString(obj.localHost, 'agentProxy.localHost').trim();
+ // localHost 会进远端 env (HTTPS_PROXY=http://<host>:<port>) — 空白和引号
+ // 都会破坏 marker shell 片段, 直接拒。host:port 里的 port 单独给。
+ if (!localHost || /\s/.test(localHost) || localHost.includes("'") || localHost.includes('"')) {
+ throwIpcError('INVALID_PARAMS', 'agentProxy.localHost must be a plain host (no whitespace/quotes), e.g. 127.0.0.1');
+ }
+ const localPort = typeof obj.localPort === 'number' && Number.isInteger(obj.localPort) && obj.localPort > 0 && obj.localPort < 65536
+ ? obj.localPort
+ : NaN;
+ if (!Number.isInteger(localPort)) {
+ throwIpcError('INVALID_PARAMS', 'agentProxy.localPort must be an integer in 1..65535');
+ }
+ return { enabled: true, localHost, localPort };
+}
+
+function normalizeAddInput(raw: unknown): AddHostInput & { agentProxy?: SshHostAgentProxyPref | null } {
const obj = requireObject(raw, 'host');
const id = requireString(obj.id, 'id').trim();
// Alias must be safe to drop into ~/.ssh/config Host directive.
@@ -495,7 +543,8 @@ function normalizeAddInput(raw: unknown): AddHostInput {
if (authMethod === 'key' && !identityFile) {
throwIpcError('INVALID_PARAMS', 'identityFile required when authMethod is "key"');
}
- return { id, hostname, port, user, authMethod, identityFile };
+ const agentProxy = normalizeAgentProxyInput(obj.agentProxy);
+ return { id, hostname, port, user, authMethod, identityFile, ...(agentProxy !== undefined ? { agentProxy } : {}) };
}
export function registerRemoteSshIpc(): void {
@@ -503,7 +552,24 @@ export function registerRemoteSshIpc(): void {
registered = true;
// Wire pool status → renderer broadcast (once, at registration time).
- getPool().onAnyStatus(broadcastStatus);
+ // ready 转换时顺带应用 agent-proxy 愿望 (建隧道 + codex env 对账): 这是
+ // 所有路径 (手动 connect / autoConnect / 断线重连) 的统一点, 失败只落
+ // tunnel state 不阻断连接, session 路径会显式重试。
+ getPool().onAnyStatus((snap) => {
+ broadcastStatus(snap);
+ if (snap.status === 'ready') {
+ const host = getPool().get(snap.config.id);
+ if (host) void applyAgentProxyForHost(host);
+ }
+ });
+ // agent-proxy 内部状态 (隧道成败 / 端口) 变化 → 推一版最新 snapshot,
+ // 让 detail 面板的隧道状态行即时刷新。
+ initAgentProxy({
+ broadcast: (hostId) => {
+ const host = getPool().get(hostId);
+ if (host) broadcastStatus(host.snapshot());
+ },
+ });
ipcMain.handle(REMOTE_SSH_INVOKE.LIST, async () => {
await ensureHydrated();
@@ -544,6 +610,9 @@ export function registerRemoteSshIpc(): void {
}
const host = getPool().add(cfg);
+ if (input.agentProxy !== undefined) {
+ setSshHostAgentProxy(cfg.id, input.agentProxy);
+ }
return { host: withPrefs(host.snapshot()) };
});
@@ -571,9 +640,16 @@ export function registerRemoteSshIpc(): void {
source: existing.config.source,
};
- // Disconnect first if active — changing hostname / user / auth method
- // invalidates the open channel. User will reconnect when ready.
- if (existing.getStatus() !== 'disconnected') {
+ // 仅当连接字段真的变了才断开 — 只改 agentProxy 偏好不该打断正在用的
+ // SSH 连接 (隧道/会话都在上面)。
+ const prev = existing.config;
+ const connectionFieldsChanged =
+ prev.hostname !== cfg.hostname ||
+ prev.user !== cfg.user ||
+ prev.port !== cfg.port ||
+ prev.authMethod !== cfg.authMethod ||
+ prev.identityFile !== cfg.identityFile;
+ if (connectionFieldsChanged && existing.getStatus() !== 'disconnected') {
await existing.disconnect();
}
@@ -583,6 +659,15 @@ export function registerRemoteSshIpc(): void {
throwIpcError('SSH_CONFIG_IO_FAILED', `update ~/.ssh/config failed: ${String(err)}`);
}
existing.updateConfig(cfg);
+
+ // agentProxy 偏好: 写盘 + host 活着就立即应用 (建/拆隧道 + codex daemon
+ // env 对账)。host 未连时只落 pref, 下次 ready 时由 ready hook 应用。
+ if (input.agentProxy !== undefined) {
+ setSshHostAgentProxy(cfg.id, input.agentProxy);
+ if (existing.getStatus() === 'ready') {
+ await applyAgentProxyForHost(existing);
+ }
+ }
return { host: withPrefs(existing.snapshot()) };
});
@@ -610,6 +695,7 @@ export function registerRemoteSshIpc(): void {
// 同步清掉 prefs 里的孤儿 autoConnect 标志, 避免后续重新 add 同名 host 时
// 拿到旧偏好造成"莫名其妙又自动连了"。同步清 agent install cache。
removeSshHostPref(id);
+ clearAgentProxyTunnelState(id);
remoteAgentInstalledCache.delete(id);
clearCcManagerInstallCache(id);
return { ok: true as const };
@@ -736,6 +822,10 @@ export function registerRemoteSshIpc(): void {
// Claude: inject local API key + upstream endpoint via STDIN (not cmd
// args) — see claude-env.ts header for security model. Codex relies on
// ~/.codex/auth.json on the remote (synced via "Sync auth").
+ //
+ // agentProxy pref 开启时把代理 env 一并注入 (quick test 因此同时验证
+ // 隧道链路是否可用): claude 走 envBlock (gatekeeper 只收大写), codex
+ // 的 wrapper 统一 source agent-proxy.env marker, 与 daemon 行为一致。
let envBlock: string | null = null;
if (agentKind === 'claude-code') {
const env = getRemoteClaudeEnv();
@@ -745,7 +835,15 @@ export function registerRemoteSshIpc(): void {
'Cindy AI is not connected in Cindy; connect it in Settings → Model Providers first',
);
}
- envBlock = serializeEnvBlock(env);
+ const proxyTunnel = await ensureAgentProxyTunnel(host);
+ const envWithProxy = proxyTunnel
+ ? { ...env, ...buildAgentProxyEnvUppercase(proxyTunnel.remotePort) }
+ : env;
+ envBlock = serializeEnvBlock(envWithProxy);
+ } else {
+ // codex one-shot: wrapper 读的是 marker 文件而非直接 env — 先跑
+ // reconcile (隧道 + marker 对账), 保证 quick test 与真实 daemon 链路一致。
+ await reconcileCodexAgentProxyEnv(host);
}
const cmd = oneShotCommand(agentKind, probe.binaryPath, envBlock != null);
@@ -831,74 +929,20 @@ export function registerRemoteSshIpc(): void {
// Retry 还是撞同一个 401。pkill 杀掉后, desktop 端下次 send 走 ensureStarted →
// `daemon version` 探活失败 → bootstrap 新 daemon → 读到新 auth.json → 成功。
//
- // pattern 设计:
- // - 匹配 `codex app-server` 两词 literal —— 覆盖 daemon 主进程 + sock proxy
- // 子进程 + 任何 `codex app-server <subcommand>` 长跑进程。**注意**: daemon
- // 主进程的 cmdline 是 `codex app-server --remote-control --listen unix://`,
- // **不包含 "daemon" 字**; 只有 worker 子进程 cmdline 含 `daemon pid-update-loop`。
- // 早期 pattern 写 `codex app-server daemon` 只杀 worker 不杀主进程, 导致
- // sync 后 daemon 还在跑用旧 auth, 复现 401。
- // - 第一个字母套字符类 `[c]odex` —— 经典 ps/grep 自排除 trick: regex `[c]odex`
- // 等价于 `codex`, 匹配真 daemon 的 cmdline; 但 pkill 命令自身的 cmdline 里
- // 出现的是字面 `[c]odex` (有方括号), regex 找不到 5 连续字符 `codex`, 所以
- // pkill 不会把自己 kill 掉。
- // - 用 `id -un` 而非 `$USER` 取当前用户名 + `-u "$USER_NAME"` 限制只杀当前
- // SSH user 的进程, 防误伤别人。某些非交互 ssh shell ($USER 未设) 会让
- // `pkill -u ""` 默默匹配 0 进程, 用 `id -un` 兜底; 取到空再 exit 2。
- // - 误杀风险评估: 短暂的 `codex app-server daemon version` 探活命令也会被命中,
- // 但它本身只跑几毫秒, 命中窗口极小; desktop 端探活失败会自动重试 bootstrap,
- // 即使命中也无害。一次性的 `codex --print` / `codex exec` 不命中此 pattern。
- // - exit code: pkill rc=0 杀到, rc=1 没匹配 (全新机器从没启过 daemon, 也算成功),
- // rc>1 真错误 (pattern 不合法 / 权限 / pkill 缺失) → script 透传 rc, 上层
- // log.warn 但不抛 IPC error, 因为 auth.json 已经推到远端是已经完成的事,
- // 失败时用户至少能从日志看到 daemon 重启失败。
+ // pkill 实现抽成了共享 helper (agent-proxy.ts:killRemoteCodexDaemon) —
+ // agent-proxy 的 env marker 漂移时也要走同一条 daemon 重启路径。pattern 的
+ // 设计考量 ([c]odex 自排除 / .xdt-server 路径限定 / id -un 取用户) 见 helper 注释。
+ //
// pkill 失败时不再 silently swallow — propagate 给 renderer 显示软提示 "auth
// 已推上去, 但 daemon 没重启成功, 要 reconnect / 手动重启 daemon 后才能用新
// auth"。auth.json 已成功落盘所以 ok=true; daemonRestart 字段告诉 renderer
// 是否需要降级显示。
- let daemonRestart: { ok: true } | { ok: false; reason: 'pkill_failed'; detail?: string } = {
- ok: true as const,
- };
- // pkill pattern: 加 .xdt-server 路径限定 — 远端 transport 把 xdt 自家 daemon
- // 装在 $HOME/.xdt-server/v1/codex-home + 通过 $HOME/.xdt-server/v1/<bin> 启动,
- // 进程 cmdline 必然含 ".xdt-server" 子串。旧 pattern `'[c]odex app-server'`
- // 在共享 SSH 账号场景误杀用户**自己装在别处的** codex app-server。
- // - `[c]odex` 自排除 trick 保留: pkill 自己的 cmdline 字面包含 `[c]odex`, 不
- // 匹配 5 连续字符 `codex`, 所以不杀 pkill 自己。
- // - `.*` 跨段匹配 — 用户进程 cmdline 形如 `node .../xdt-server/.../codex
- // app-server --remote-control ...`, 我们要求整条 cmdline 同时含 .xdt-server
- // AND `codex app-server`。
- try {
- const killScript = `
-USER_NAME=$(id -un 2>/dev/null)
-if [ -z "$USER_NAME" ]; then echo "id -un returned empty" >&2; exit 2; fi
-pkill -u "$USER_NAME" -f '\\.xdt-server.*[c]odex app-server'
-rc=$?
-case "$rc" in
- 0|1) exit 0 ;;
- *) echo "pkill rc=$rc" >&2; exit "$rc" ;;
-esac
-`;
- const result = await host.exec(`bash -c ${shellQuoteSh(killScript)}`, {
- timeoutMs: 5_000,
- label: 'kill-codex-daemon-post-sync',
- });
- if (result.exitCode !== 0) {
- const detail = result.stderr.trim().slice(0, 200);
- log.warn('failed to kill remote codex daemon after auth sync (auth.json pushed ok, but daemon may still use old auth)', {
- hostId: id,
- exitCode: result.exitCode,
- stderr: detail,
- });
- daemonRestart = { ok: false, reason: 'pkill_failed', detail };
- }
- } catch (err) {
- const detail = String((err as Error).message ?? err);
- log.warn('failed to kill remote codex daemon after auth sync (will reload on next reconnect)', {
+ const daemonRestart = await killRemoteCodexDaemon(host);
+ if (!daemonRestart.ok) {
+ log.warn('failed to kill remote codex daemon after auth sync (auth.json pushed ok, but daemon may still use old auth)', {
hostId: id,
- error: detail,
+ detail: daemonRestart.detail,
});
- daemonRestart = { ok: false, reason: 'pkill_failed', detail };
}
return { ok: true as const, daemonRestart };
@@ -1448,7 +1492,14 @@ function oneShotCommand(
let envSetup: string;
if (agentKind === 'codex') {
const codexHome = binaryPath.replace(/\/packages\/standalone\/current\/codex$/, '');
- envSetup = `export CODEX_HOME=${shellQuoteSh(codexHome)}`;
+ const installRoot = codexHome.replace(/\/codex-home$/, '');
+ const markerPath = `${installRoot}/agent-proxy.env`;
+ // source agent-proxy marker (agentProxy pref 开启时由 reconcile 写入) —
+ // 与 daemon wrapper 同源, quick test 走的就是真实会话的代理链路。
+ envSetup = [
+ `export CODEX_HOME=${shellQuoteSh(codexHome)}`,
+ `if [ -f ${shellQuoteSh(markerPath)} ]; then . ${shellQuoteSh(markerPath)}; fi`,
+ ].join('\n');
} else {
const installDir = binaryPath.replace(/\/node_modules\/\.bin\/[^/]+$/, '');
const nodeBinDir = `${installDir}/node/bin`;
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 d949982f2b..1a8d8dbd9b 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
@@ -1,5 +1,5 @@
/**
- * ssh-host-prefs-store —— 每台 SSH 远端机器的本地偏好(目前只有 autoConnect)。
+ * ssh-host-prefs-store —— 每台 SSH 远端机器的本地偏好(autoConnect + agentProxy)。
*
* 设计上跟 ~/.ssh/config 解耦: 不污染用户的 ssh config (那是 ssh 客户端通用配置),
* 用一个独立 JSON 落 <userData>/ssh-host-prefs.json. 数据极小, 同步 R/W + 内存
@@ -7,12 +7,15 @@
*
* Schema:
* {
- * "<hostId>": { "autoConnect": true },
+ * "<hostId>": {
+ * "autoConnect": true,
+ * "agentProxy": { "enabled": true, "localHost": "127.0.0.1", "localPort": 7890 }
+ * },
* ...
* }
*
- * 缺失 host 默认 autoConnect=false (启动不自动连, 新建对话不显远程项目入口)。
- * 这样老用户升级零破坏 —— 没有 prefs 文件就当所有 host 都没勾。
+ * 缺失 host 默认 autoConnect=false (启动不自动连, 新建对话不显远程项目入口)、
+ * agentProxy=未开启。这样老用户升级零破坏 —— 没有 prefs 文件就当所有 host 都没勾。
*/
import { app } from 'electron';
@@ -23,8 +26,20 @@ import { createLogger } from '../logger.js';
const log = createLogger('ssh-host-prefs-store');
+/**
+ * Agent 流量经 SSH 隧道走本地 Proxy 的 per-host 配置。
+ * Cindy 不提供 Proxy, 只建隧道: 远端 127.0.0.1:<forwardPort> → 本地
+ * localHost:localPort (用户自己的 Proxy, 如 Clash 的 7890 混合端口)。
+ */
+export interface SshHostAgentProxyPref {
+ enabled: boolean;
+ localHost: string;
+ localPort: number;
+}
+
export interface SshHostPref {
autoConnect: boolean;
+ agentProxy?: SshHostAgentProxyPref;
}
export type SshHostPrefs = Record<string, SshHostPref>;
@@ -33,13 +48,27 @@ function settingsFilePath(): string {
return path.join(app.getPath('userData'), 'ssh-host-prefs.json');
}
+function normalizeAgentProxy(raw: unknown): SshHostAgentProxyPref | undefined {
+ if (!raw || typeof raw !== 'object') return undefined;
+ const v = raw as Record<string, unknown>;
+ const localHost = typeof v.localHost === 'string' ? v.localHost.trim() : '';
+ const localPort = typeof v.localPort === 'number' ? v.localPort : NaN;
+ if (!localHost || /\s/.test(localHost)) return undefined;
+ if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) return undefined;
+ return { enabled: v.enabled === true, localHost, localPort };
+}
+
function normalize(raw: unknown): SshHostPrefs {
if (!raw || typeof raw !== 'object') return {};
const out: SshHostPrefs = {};
for (const [hostId, value] of Object.entries(raw as Record<string, unknown>)) {
if (!value || typeof value !== 'object') continue;
const v = value as Record<string, unknown>;
- out[hostId] = { autoConnect: v.autoConnect === true };
+ const agentProxy = normalizeAgentProxy(v.agentProxy);
+ out[hostId] = {
+ autoConnect: v.autoConnect === true,
+ ...(agentProxy ? { agentProxy } : {}),
+ };
}
return out;
}
@@ -73,15 +102,47 @@ export function getSshHostAutoConnect(hostId: string): boolean {
return readSshHostPrefs()[hostId]?.autoConnect === true;
}
-/** 写入单 host 的 autoConnect, atomic write + 更新 cache. */
-export function setSshHostAutoConnect(hostId: string, autoConnect: boolean): void {
+/** 单 host 的 agentProxy 配置; 未配置 / enabled=false / 数据非法 → null. */
+export function getSshHostAgentProxy(hostId: string): SshHostAgentProxyPref | null {
+ const pref = readSshHostPrefs()[hostId]?.agentProxy;
+ if (!pref || pref.enabled !== true) return null;
+ return pref;
+}
+
+/** 写入单 host 的 agentProxy 配置 (null = 关闭并清除), atomic write + 更新 cache. */
+export function setSshHostAgentProxy(hostId: string, agentProxy: SshHostAgentProxyPref | null): void {
const current = { ...readSshHostPrefs() };
- current[hostId] = { ...current[hostId], autoConnect };
+ // 不 spread 旧 entry — 旧 agentProxy 会借 spread 复活, null 语义就是清除。
+ const next: SshHostPref = { autoConnect: current[hostId]?.autoConnect === true };
+ if (agentProxy) {
+ const normalized = normalizeAgentProxy(agentProxy);
+ if (!normalized) {
+ throw new Error(`invalid agentProxy pref: localHost/localPort malformed`);
+ }
+ next.agentProxy = { ...normalized, enabled: agentProxy.enabled === true };
+ }
+ current[hostId] = next;
+ writePrefs(current);
+ log.info('ssh host agentProxy written', {
+ hostId,
+ enabled: next.agentProxy?.enabled === true,
+ localTarget: next.agentProxy ? `${next.agentProxy.localHost}:${next.agentProxy.localPort}` : null,
+ });
+}
+
+function writePrefs(prefs: SshHostPrefs): void {
const file = settingsFilePath();
const tmp = `${file}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(current, null, 2), 'utf-8');
+ fs.writeFileSync(tmp, JSON.stringify(prefs, null, 2), 'utf-8');
fs.renameSync(tmp, file);
- cached = current;
+ cached = prefs;
+}
+
+/** 写入单 host 的 autoConnect, atomic write + 更新 cache. */
+export function setSshHostAutoConnect(hostId: string, autoConnect: boolean): void {
+ const current = { ...readSshHostPrefs() };
+ current[hostId] = { ...current[hostId], autoConnect };
+ writePrefs(current);
log.info('ssh host autoConnect written', { hostId, autoConnect });
}
@@ -100,10 +161,6 @@ export function removeSshHostPref(hostId: string): void {
if (!(hostId in current)) return;
const next = { ...current };
delete next[hostId];
- const file = settingsFilePath();
- const tmp = `${file}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf-8');
- fs.renameSync(tmp, file);
- cached = next;
+ writePrefs(next);
log.info('ssh host pref removed', { hostId });
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b0cf90d908..1cdeeaa27c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2904,6 +2904,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
statusChangedAt: number;
/** Phase D — 启动时是否自动连接 (本地 prefs, 不写入 ~/.ssh/config). */
autoConnect: boolean;
+ /** Agent 流量经 SSH 隧道走本地 Proxy (本地 prefs); 未开启 → null. */
+ agentProxy: { enabled: boolean; localHost: string; localPort: number } | null;
+ /** 隧道实时状态 (内存态); 无记录 → null. */
+ agentProxyTunnel: { active: boolean; remotePort?: number; lastError?: string } | null;
}>;
}> => ipcRenderer.invoke('maker:remote-ssh:list'),
reloadConfig: (): Promise<{ hosts: unknown[] }> =>
@@ -2915,6 +2919,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
+ agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
}): Promise<{ host: unknown }> => ipcRenderer.invoke('maker:remote-ssh:add', host),
update: (host: {
id: string;
@@ -2923,6 +2928,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
+ agentProxy?: { enabled: boolean; localHost: string; localPort: number } | 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/__tests__/remoteProjectIdentity.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
index bec55e81e3..b0411206ec 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
@@ -23,6 +23,8 @@ function sshHost(
status: 'ready',
statusChangedAt: 0,
autoConnect: false,
+ agentProxy: null,
+ agentProxyTunnel: null,
};
}
diff --git a/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx b/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx
index 47ee23ac28..19ead9a086 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx
@@ -13,10 +13,10 @@
* that's Phase C (RemoteAgent as a BaseAgent subclass).
*/
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
-import { CheckCircle2, AlertCircle, Play, Upload, Sparkles } from 'lucide-react';
+import { CheckCircle2, AlertCircle, Play, Upload, Sparkles, Waypoints } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
@@ -25,6 +25,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { Spinner } from '@/components/ui/spinner';
import * as sessionService from '@/lib/sessionService';
import { buildCodexSyncWarning } from '@/utils/codexAuthSync';
+import { remoteSshHostsStore } from '@/lib/remoteSshHostsStore';
type AgentKind = RemoteAgentKind;
const AGENT_KINDS: ReadonlyArray<AgentKind> = ['claude-code', 'codex'];
@@ -240,6 +241,8 @@ export function RemoteHostDetail({ hostId }: Props) {
<QuickTestPanel hostId={hostId} availableKinds={installedKinds} />
)}
+ <AgentProxyTunnelCard hostId={hostId} />
+
{agents.codex.probe?.installed && (
<StartRemoteSessionPanel hostId={hostId} />
)}
@@ -247,6 +250,68 @@ export function RemoteHostDetail({ hostId }: Props) {
);
}
+// ── agent proxy tunnel status card ──────────────────────────────────────────
+//
+// 「Agent 流量走本地 Proxy」pref 开启时显示隧道实时状态。快照来自
+// remoteSshHostsStore (main 端 status push 驱动, withPrefs 携带 tunnel state)。
+
+function AgentProxyTunnelCard({ hostId }: { hostId: string }) {
+ const { t } = useTranslation();
+ const snap = useSyncExternalStore(
+ (cb) => remoteSshHostsStore.subscribe(cb),
+ () => remoteSshHostsStore.get()?.find((h) => h.config.id === hostId) ?? null,
+ );
+ // 触发一次 ensure, 保证 cold start (没开过 Settings 列表) 也有快照。
+ useEffect(() => {
+ void remoteSshHostsStore.ensure();
+ }, []);
+
+ const pref = snap?.agentProxy ?? null;
+ if (!pref) return null;
+ const tunnel = snap?.agentProxyTunnel ?? null;
+ const localTarget = `${pref.localHost}:${pref.localPort}`;
+
+ let icon;
+ let text: string;
+ let isError = false;
+ if (tunnel?.active && tunnel.remotePort != null) {
+ icon = <CheckCircle2 size={14} />;
+ text = t('settings.remote.detail.agentProxyActive', {
+ port: tunnel.remotePort,
+ target: localTarget,
+ });
+ } else if (tunnel?.lastError) {
+ icon = <AlertCircle size={14} />;
+ text = t('settings.remote.detail.agentProxyError', { message: tunnel.lastError });
+ isError = true;
+ } else {
+ icon = <Spinner size={12} />;
+ text = t('settings.remote.detail.agentProxyPending', { target: localTarget });
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <p
+ className="text-13 font-medium"
+ style={{ color: 'var(--settings-section-sublabel)' }}
+ >
+ {t('settings.remote.detail.agentProxyTitle')}
+ </p>
+ <div
+ className="flex items-center gap-2 rounded-lg p-3 text-12"
+ style={{
+ border: '1px solid var(--settings-theme-card-border)',
+ color: isError ? 'var(--error-fg, #dc2626)' : 'var(--settings-integration-subtitle)',
+ }}
+ >
+ <Waypoints size={14} className="shrink-0" />
+ {icon}
+ <span className="break-all">{text}</span>
+ </div>
+ </div>
+ );
+}
+
// ── start-remote-session panel ──────────────────────────────────────────────
//
// Create a real maker session pinned to this remote host. The session goes
diff --git a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
index 5e1b31a85f..5bef97c67b 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
@@ -270,6 +270,9 @@ interface AddFormState {
port: string;
authMethod: 'agent' | 'key';
identityFile: string;
+ /** 「Agent 流量走本地 Proxy」隧道开关 + 本地 Proxy 地址 (host:port)。 */
+ agentProxyEnabled: boolean;
+ agentProxyAddr: string;
}
const EMPTY_FORM: AddFormState = {
@@ -279,8 +282,31 @@ const EMPTY_FORM: AddFormState = {
port: '22',
authMethod: 'agent',
identityFile: '',
+ agentProxyEnabled: false,
+ agentProxyAddr: '127.0.0.1:7890',
};
+/**
+ * 解析 "host:port" 输入 — 支持 IPv6 bracket 形态 ([::1]:7890)。
+ * 返回 null = 无法解析 (表单校验据此拦截提交)。
+ */
+export function parseProxyAddrInput(input: string): { localHost: string; localPort: number } | null {
+ const s = input.trim();
+ if (!s) return null;
+ const bracket = /^\[([^\]]+)\]:(\d+)$/.exec(s);
+ if (bracket) {
+ const localPort = parseInt(bracket[2]!, 10);
+ return bracket[1] && Number.isInteger(localPort) ? { localHost: bracket[1]!, localPort } : null;
+ }
+ const idx = s.lastIndexOf(':');
+ if (idx <= 0) return null;
+ const localHost = s.slice(0, idx).trim();
+ const localPort = parseInt(s.slice(idx + 1), 10);
+ if (!localHost || /\s/.test(localHost) || !Number.isInteger(localPort)) return null;
+ if (localPort < 1 || localPort > 65535) return null;
+ return { localHost, localPort };
+}
+
interface HostFormProps {
/**
* 'add' → blank form, alias editable, submit creates a new host.
@@ -315,6 +341,7 @@ 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;
return true;
}, [form]);
@@ -507,6 +534,51 @@ 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,
+ codex daemon 经 env marker (重启生效), claude 按 session env (即时)。 */}
+ <div className="flex flex-col gap-2">
+ <label
+ className="flex items-center gap-2 cursor-pointer select-none"
+ title={t('settings.remote.add.agentProxyTip')}
+ >
+ <input
+ type="checkbox"
+ checked={form.agentProxyEnabled}
+ onChange={(e) => setForm({ ...form, agentProxyEnabled: e.target.checked })}
+ className="cursor-pointer accent-[var(--settings-menu-text-selected)]"
+ />
+ <span
+ className="text-12 font-medium"
+ style={{ color: 'var(--settings-section-sublabel)' }}
+ >
+ {t('settings.remote.add.agentProxy')}
+ </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, #dc2626)' }}>
+ {t('settings.remote.add.agentProxyAddrInvalid')}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
@@ -797,6 +869,11 @@ 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'));
+ return;
+ }
await window.electronAPI.remoteSsh.update({
id: form.id.trim(),
hostname: form.hostname.trim(),
@@ -804,6 +881,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,
});
// refresh() pulls the latest snapshot; updateConfig already fired a
// status event, but a full refresh is the safest way to also reflect
@@ -824,6 +902,11 @@ 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'));
+ return;
+ }
await window.electronAPI.remoteSsh.add({
id: form.id.trim(),
hostname: form.hostname.trim(),
@@ -831,6 +914,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,
});
await refresh();
setAdding(false);
@@ -955,6 +1039,10 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
port: String(snap.config.port ?? 22),
authMethod: snap.config.authMethod === 'key' ? 'key' : 'agent',
identityFile: snap.config.identityFile ?? '',
+ agentProxyEnabled: snap.agentProxy?.enabled === true,
+ agentProxyAddr: snap.agentProxy
+ ? `${snap.agentProxy.localHost}:${snap.agentProxy.localPort}`
+ : '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
new file mode 100644
index 0000000000..6a407742ca
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.parseProxyAddr.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseProxyAddrInput } from '../RemoteSection';
+
+describe('parseProxyAddrInput', () => {
+ it('parses host:port', () => {
+ expect(parseProxyAddrInput('127.0.0.1:7890')).toEqual({ localHost: '127.0.0.1', localPort: 7890 });
+ expect(parseProxyAddrInput(' localhost:1080 ')).toEqual({ localHost: 'localhost', localPort: 1080 });
+ });
+
+ it('parses bracketed IPv6', () => {
+ expect(parseProxyAddrInput('[::1]:7890')).toEqual({ localHost: '::1', localPort: 7890 });
+ });
+
+ it('takes the last colon so bare IPv6 without brackets is rejected (ambiguous)', () => {
+ // ::1:7890 → lastIndexOf(':') 切出 host=': :1' 含空白? 不含 — host='::1', port=7890。
+ // 裸 IPv6 语义模糊, 这里的行为是接受 last-colon 切分结果; 文档推荐 bracket 形态。
+ expect(parseProxyAddrInput('::1:7890')).toEqual({ localHost: '::1', localPort: 7890 });
+ });
+
+ it('rejects malformed input', () => {
+ expect(parseProxyAddrInput('')).toBeNull();
+ expect(parseProxyAddrInput('7890')).toBeNull();
+ expect(parseProxyAddrInput(':7890')).toBeNull();
+ expect(parseProxyAddrInput('host:')).toBeNull();
+ expect(parseProxyAddrInput('host:abc')).toBeNull();
+ expect(parseProxyAddrInput('host:0')).toBeNull();
+ expect(parseProxyAddrInput('host:70000')).toBeNull();
+ expect(parseProxyAddrInput('bad host:7890')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 1d4f98eb37..f125bf4c1e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -267,6 +267,11 @@
"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",
+ "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.",
+ "agentProxyAddrInvalid": "Expected host:port, e.g. 127.0.0.1:7890",
"cancel": "Cancel",
"submit": "Add machine"
},
@@ -282,6 +287,10 @@
"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}}",
+ "agentProxyError": "Tunnel failed: {{message}}",
"button": {
"install": "Install",
"reinstall": "Reinstall",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a801a6a4f6..5a86715737 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -267,6 +267,11 @@
"keyHint": "秘密鍵ファイルを直接読み込みます。パスフレーズは保存しないため、暗号化された鍵には非対応 — ssh-agent が使えない場合のみご使用ください。"
},
"identityFile": "秘密鍵ファイルのパス",
+ "agentProxy": "Agent トラフィックをローカルプロキシ経由にする",
+ "agentProxyTip": "リモートに 127.0.0.1 ポートを開き、SSH トンネルでこのマシンのプロキシに中継します。リモートの codex / Claude Code の通信がそこから出ます",
+ "agentProxyAddr": "ローカルプロキシのアドレス",
+ "agentProxyHint": "リモートの 127.0.0.1 にポートを開き、SSH トンネルでローカルプロキシ(例: Clash の 7890)に中継します。{{appName}} はプロキシを提供せず、トンネルのみを張ります。リモート Agent の HTTPS_PROXY がトンネル口を指し、ドメインはお使いのプロキシ側で解決されます。切り替え後、リモートの codex daemon が一度再起動します。",
+ "agentProxyAddrInvalid": "host:port 形式で入力してください(例: 127.0.0.1:7890)",
"cancel": "キャンセル",
"submit": "マシンを追加"
},
@@ -282,6 +287,10 @@
"statusInstalled": "インストール済み",
"statusNotInstalled": "未インストール",
"claudeCodeName": "Claude Code",
+ "agentProxyTitle": "Agent プロキシトンネル",
+ "agentProxyActive": "リモート 127.0.0.1:{{port}} → ローカル {{target}} · 確立済み",
+ "agentProxyPending": "トンネル確立中 → ローカル {{target}}",
+ "agentProxyError": "トンネルの確立に失敗: {{message}}",
"button": {
"install": "インストール",
"reinstall": "再インストール",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2283e1a5f0..160a3f0e03 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -267,6 +267,11 @@
"keyHint": "개인 키 파일을 직접 읽습니다. 암호를 저장하지 않으므로 암호화된 키는 지원되지 않습니다 — ssh-agent 를 사용할 수 없을 때만 사용하세요."
},
"identityFile": "개인 키 파일 경로",
+ "agentProxy": "Agent 트래픽을 로컬 프록시로 우회",
+ "agentProxyTip": "원격에 127.0.0.1 포트를 열고 SSH 터널로 이 컴퓨터의 프록시로 중계합니다. 원격 codex / Claude Code 트래픽이 그 경로로 나갑니다",
+ "agentProxyAddr": "로컬 프록시 주소",
+ "agentProxyHint": "원격 127.0.0.1에 포트를 열고 SSH 터널로 로컬 프록시(예: Clash 7890)로 중계합니다. {{appName}}은(는) 프록시를 제공하지 않고 터널만 만듭니다. 원격 Agent의 HTTPS_PROXY가 터널 포트를 가리키고, 도메인은 프록시에서 해석됩니다. 전환 후 원격 codex daemon이 한 번 재시작됩니다.",
+ "agentProxyAddrInvalid": "host:port 형식이어야 합니다(예: 127.0.0.1:7890)",
"cancel": "취소",
"submit": "머신 추가"
},
@@ -282,6 +287,10 @@
"statusInstalled": "설치됨",
"statusNotInstalled": "설치되지 않음",
"claudeCodeName": "Claude Code",
+ "agentProxyTitle": "Agent 프록시 터널",
+ "agentProxyActive": "원격 127.0.0.1:{{port}} → 로컬 {{target}} · 설정됨",
+ "agentProxyPending": "터널 설정 중 → 로컬 {{target}}",
+ "agentProxyError": "터널 설정 실패: {{message}}",
"button": {
"install": "설치",
"reinstall": "재설치",
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 2d2f7363f7..4ca12c12ec 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -267,6 +267,11 @@
"keyHint": "直接读私钥文件。为了不存密码,不支持加密的密钥 —— 仅在 ssh-agent 不可用时使用。"
},
"identityFile": "私钥文件路径",
+ "agentProxy": "Agent 流量走本地 Proxy",
+ "agentProxyTip": "在远端开一个 127.0.0.1 端口,经 SSH 隧道转回本机 Proxy,远端 codex / Claude Code 的流量由此流出",
+ "agentProxyAddr": "本地 Proxy 地址",
+ "agentProxyHint": "在远端 127.0.0.1 开端口,经 SSH 隧道转回本机 Proxy(如 Clash 的 7890)。{{appName}} 不提供 Proxy,只建隧道;远端 agent 的 HTTPS_PROXY 会指向隧道口,域名由你的 Proxy 解析。切换后远端 codex daemon 会重启一次以生效。",
+ "agentProxyAddrInvalid": "格式应为 host:port,例如 127.0.0.1:7890",
"cancel": "取消",
"submit": "添加机器"
},
@@ -282,6 +287,10 @@
"statusInstalled": "已安装",
"statusNotInstalled": "未安装",
"claudeCodeName": "Claude Code",
+ "agentProxyTitle": "Agent Proxy 隧道",
+ "agentProxyActive": "远端 127.0.0.1 端口 {{port}} → 本机 {{target}} · 已建立",
+ "agentProxyPending": "隧道建立中 → 本机 {{target}}",
+ "agentProxyError": "隧道建立失败:{{message}}",
"button": {
"install": "安装",
"reinstall": "重新安装",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 99686b4987..ea8970994f 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -44,10 +44,14 @@ interface EnvCheckResult {
// surface and the core package's contract in sync. `VoiceInputShortcut` is
// renderer-only (defined in voice-input/shortcut.ts) so it stays inline.
// HostSnapshot 来自 transport-only package; desktop main 端 wrap 时附加
-// autoConnect 偏好字段 (本地 prefs, 不写入 ~/.ssh/config), 渲染层统一用
+// autoConnect / agentProxy 偏好字段 (本地 prefs, 不写入 ~/.ssh/config), 渲染层统一用
// 这个扩展类型即可一次拿到完整信息, 不必再为单个字段单独 IPC。
type RemoteHostSnapshot = import('@cindy/maker-remote-ssh').HostSnapshot & {
autoConnect: boolean;
+ /** Agent 流量经 SSH 隧道走本地 Proxy 的 per-host 配置; 未开启 → null。 */
+ agentProxy: { enabled: boolean; localHost: string; localPort: number } | null;
+ /** 隧道实时状态 (main 进程内存态); 无记录 → null。 */
+ agentProxyTunnel: { active: boolean; remotePort?: number; lastError?: string } | null;
};
/** 设备互联:REST 设备视图(同 shared/deviceLinkIpc.ts DeviceLinkDeviceView) */
interface DeviceLinkDeviceInfo {
@@ -2765,6 +2769,8 @@ interface ElectronAPI {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
+ /** 「Agent 流量走本地 Proxy」pref; null = 关闭, 缺省 = 不动。 */
+ agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
}) => Promise<{ host: RemoteHostSnapshot }>;
update: (host: {
id: string;
@@ -2773,6 +2779,7 @@ interface ElectronAPI {
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
+ agentProxy?: { enabled: boolean; localHost: string; localPort: number } | null;
}) => Promise<{ host: RemoteHostSnapshot }>;
remove: (id: string) => Promise<{ ok: true }>;
connect: (id: string) => Promise<{ host: RemoteHostSnapshot | null }>;