Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 远端 MCP 代际失效补全 R21 五案
yan4f061b37625a
diff --git a/apps/desktop/help-knowledge/collaboration.md b/apps/desktop/help-knowledge/collaboration.mdindex 52ba894b81..cd843badce 100644--- a/apps/desktop/help-knowledge/collaboration.md+++ b/apps/desktop/help-knowledge/collaboration.md@@ -7,7 +7,7 @@ Collaboration ("协同" / Collab) lets one session — the **lead** — bring in**Turning it on:**-- In a local project session, click the **Collab** pill in the composer toolbar. Both Claude Code and Codex sessions can be the lead.+- In a project session — local or SSH remote — click the **Collab** pill in the composer toolbar. Both Claude Code and Codex sessions can be the lead, on either side.- Pick the first worker's agent (Claude Code or Codex), and optionally its role / model / effort / an initial task.- Start. This creates the team plus that first worker.@@ -28,5 +28,5 @@ Collaboration ("协同" / Collab) lets one session — the **lead** — bring in**Notes:**-- The lead must be a **local** Claude Code / Codex **project** session — remote sessions can't be the lead yet, and a worker can't start its own sub-collab (no nesting).+- The lead must be a Claude Code / Codex **project** session — local **or SSH remote**. On a remote lead, workers are spawned on the **same remote host**, and the collaboration MCP reaches the remote side over an SSH remote-forward to the local bridge (with a persistent bearer token). A worker can't start its own sub-collab (no nesting).- A lead can have only **one active collaboration workflow** at a time. If you have two clients open on the same account (e.g. dev + release) and start collab on the same session in both, the second fails with "开启协同失败" because a workflow is already active — close one client or end the existing collab.diff --git a/apps/desktop/help-knowledge/remote.md b/apps/desktop/help-knowledge/remote.mdindex 43f4f282ff..210e61368d 100644--- a/apps/desktop/help-knowledge/remote.md+++ b/apps/desktop/help-knowledge/remote.md@@ -27,5 +27,5 @@ Settings > **Remote & device control** has two parts: **SSH remote workspaces****Notes:**-- Remote sessions can't be the lead in a collaboration workflow yet (see the Collaboration topic).+- Remote project sessions **can** be the lead in a collaboration workflow — workers then run on the same remote host (see the Collaboration topic).- Device control works only between devices on the **same account**; the relay just routes between them — your session data isn't stored on it.diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 092fc2a36d..d030a69b7a 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -332,6 +332,7 @@ import {broadcastXaiAuthStateChanged,refreshProviderAccessAfterAuthChange,restartCodexAfterAuthModeChange,+ handleCodexEnvironmentShutdownForRemote,waitForInitialCustomMcpRefresh,} from './maker-host/index.js';import { createDynamicMaker } from './maker-host/dynamic-maker.js';@@ -5576,6 +5577,9 @@ app.on('ready', async () => {if (codexRestarted) {try {await shutdownCodexEnvironment();+ // 账号切换后旧 bridge 已停 — 远端 session 立刻失效 (CC detach ++ // codex strip), 不等 lazy 重建 (codex-connector R21 P1)。+ handleCodexEnvironmentShutdownForRemote();} catch (err) {accountSwitchLog.warn('shutdownCodexEnvironment on account switch failed', {error: err instanceof Error ? err.message : String(err),diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex a192930f8d..753454b947 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -21,7 +21,7 @@ import { isModelVisible, visibleModelUnion } from '@cindy/model-providers';import { BRAND_NAME } from '@cindy/maker-shared/branding';import { createLogger } from '../logger.js';-import { getMaker, restartCodexAfterAuthModeChange } from '../maker-host/index.js';+import { getMaker, handleCodexEnvironmentShutdownForRemote, restartCodexAfterAuthModeChange } from '../maker-host/index.js';import { shutdownCodexEnvironment } from '../mcp-integrations/codexEnvironment.js';import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';import { getModelVisibilityOverride } from '../maker-host/model-visibility-mirror.js';@@ -150,6 +150,9 @@ async function drainCodexMcpRefreshForSlackAvailability(): Promise<void> {try {await restartCodexAfterAuthModeChange();await shutdownCodexEnvironment();+ // 远端 session 的 MCP URL / session id 已指向停掉的 bridge — 立刻+ // 失效 (CC detach + codex strip), 不等 lazy 重建 (codex-connector R21 P1)。+ handleCodexEnvironmentShutdownForRemote();log.info('Codex MCP environment refreshed after Slack provider availability changed', {enabled: latestSlackToolProviderEnabled,});diff --git a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.tsindex aa77214109..29666701f5 100644--- a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts@@ -71,6 +71,43 @@ describe('buildCcRemoteHttpMcpServers', () => {expect(() => cleanup()).not.toThrow();});+ it('flags needsFreshStart when the bridge token is unavailable (R21 P2)', async () => {+ // token 失效但本要注入:调用方必须 forceFresh — 否则 attach 回带旧+ // Authorization header 的 alive query, 协同 MCP 持续 401。+ const { bridge } = fakeBridge();+ const { servers, needsFreshStart } = await buildCcRemoteHttpMcpServers(+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo' },+ {+ ensureBridgeStarted: async () => ({+ port: 38080,+ serverNames: ['cindy_orca', 'orca_worker_bridge'],+ bridge,+ }),+ ensureForward: vi.fn(async () => 47921),+ getBridgeToken: async () => null,+ },+ );+ expect(servers).toEqual({});+ expect(needsFreshStart).toBe(true);+ });++ it('does not flag needsFreshStart when the token is available', async () => {+ const { bridge } = fakeBridge();+ const { needsFreshStart } = await buildCcRemoteHttpMcpServers(+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo' },+ {+ ensureBridgeStarted: async () => ({+ port: 38080,+ serverNames: ['cindy_orca', 'orca_worker_bridge'],+ bridge,+ }),+ ensureForward: vi.fn(async () => 47921),+ getBridgeToken: async () => 'persistent-test-token',+ },+ );+ expect(needsFreshStart).toBeFalsy();+ });+it('injects only whitelisted servers with the persistent token and ?session= routing', async () => {const { bridge, registered } = fakeBridge();const { servers } = await buildCcRemoteHttpMcpServers(diff --git a/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.tsindex 21c2884bfa..8dad321908 100644--- a/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts@@ -31,6 +31,7 @@ function makeDeps(overrides?: Partial<Parameters<typeof refreshRemoteCodexMcpAftgetReadyHost: (id: string) => host(id),ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_orca'], bridgeInstanceId: 'bridge-2' }),getLiveTurnChecker: () => checker,+ isCollabEnabled: () => true,log: { warn },...overrides,};@@ -51,6 +52,8 @@ describe('refreshRemoteCodexMcpAfterBridgeRecreate', () => {expect(['host-a', 'host-b']).toContain(callHost.id);expect(callDeps.ensureBridgeStarted).toBe(deps.ensureBridgeStarted);expect(callDeps.hasLiveTurnOnHost).toBe(checker);+ // R21 P1: 恢复路径必须透传 Collab 闸门 — 禁用时 ensure 走清理而非重注入。+ expect(callDeps.isCollabEnabled).toBe(deps.isCollabEnabled);}});diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.tsindex db4ac49092..b183acff9b 100644--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts@@ -109,8 +109,21 @@ export async function buildCcRemoteHttpMcpServers(vendorOptions?: Record<string, unknown>;},deps: CcRemoteHttpMcpDeps,-): Promise<{ servers: Record<string, CcRemoteHttpMcpServerConfig>; cleanup: () => void }> {- const empty = { servers: {}, cleanup: () => {} };+): Promise<{+ servers: Record<string, CcRemoteHttpMcpServerConfig>;+ cleanup: () => void;+ /**+ * true = 调用方应对已有 alive query 走 forceFresh (kill + fresh start):+ * 本要注入但 token 不可用时, attach 回带旧 Authorization header 的旧+ * query 会让协同 MCP 持续 401 — 重建为「无协同」的干净 query 才是+ * fail-closed (codex-connector R21 P2)。+ */+ needsFreshStart?: boolean;+}> {+ const empty: { servers: Record<string, CcRemoteHttpMcpServerConfig>; cleanup: () => void; needsFreshStart?: boolean } = {+ servers: {},+ cleanup: () => {},+ };const started = await deps.ensureBridgeStarted();if (!started) return empty;// collab 全局禁用时 bridge 名单不反映开关 (keepOrcaProviderStable) —@@ -124,7 +137,12 @@ export async function buildCcRemoteHttpMcpServers(// token 可用性必须在 register 之前确认:null 时下发出 "Bearer null" 还// 保留已注册 ctx (注册后失败无任何 cleanup 可达, 见 race review P1)。const bridgeToken = await (deps.getBridgeToken ?? getRemoteMcpBridgeToken)();- if (!bridgeToken) return empty;+ if (!bridgeToken) {+ // token 失效但本要注入 (names 非空):标记 needsFreshStart — 否则调用方+ // 按 injectedServerCount===0 不 forceFresh, attach 回带旧 token header+ // 的 alive query, 协同 MCP 持续 401 (codex-connector R21 P2)。+ return { ...empty, needsFreshStart: names.length > 0 };+ }const synthesize = deps.synthesizeVendorOptions ?? synthesizeCcRemoteVendorOptions;const ctx = {agentKind: 'claude-code' as const,diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 75e2e60bd5..a71fa63edc 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -117,7 +117,7 @@ import {unregisterCodexMcpThreadContext,} from '../mcp-integrations/codexEnvironment.js';import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';-import { ensureRemoteMcpForward, setRemoteMcpForwardRearmedHook } from '../remote-ssh/codex-remote-mcp.js';+import { ensureRemoteMcpForward, setRemoteMcpForwardRearmedHook, stripRemoteCodexMcpConfig } from '../remote-ssh/codex-remote-mcp.js';import { buildCcRemoteHttpMcpServers } from './cc-remote-mcp.js';import { getRemoteSessionStartEnsure, getRemoteCodexLiveTurnChecker, setRemoteCcTurnSettledHandler } from './remote-session-start-ensure.js';import {@@ -294,6 +294,33 @@ function invalidateActiveRemoteCcQueries(opts: { hostId?: string; reason: string);}+/**+ * bridge shutdown 时的远端即时失效 (codex-connector R21 P1):插件/全局+ * 设置变更触发 shutdownCodexEnvironment 后, 远端 session 的 MCP URL /+ * session id 都指向已停 bridge — 等 lazy 重建会让窗口期内 send 持续+ * 404 / connection-refused。这里立刻:+ * - 远端 CC:fresh 失效 + 无 turn query detach (下次 send 触发 lazy+ * 重建并重注入, 全链路自愈);+ * - 远端 codex:逐 host strip 受管段 + 清 daemon env (404 MCP 当场降级+ * 为无 MCP);lazy 重建后恢复遍历重新注入。+ * 挂在 shutdownCodexEnvironment 的各调用点 (hook-control / 账号切换)。+ */+export function handleCodexEnvironmentShutdownForRemote(): void {+ invalidateActiveRemoteCcQueries({ reason: 'bridge-shutdown' });+ const hostIds = new Set<string>();+ for (const s of _maker?.listActiveSessions() ?? []) {+ if (s.remoteHostId && s.agentKind === 'codex') hostIds.add(s.remoteHostId);+ }+ const liveTurnChecker = getRemoteCodexLiveTurnChecker();+ for (const hostId of hostIds) {+ const host = getRemoteSshPool().get(hostId);+ if (host?.getStatus() !== 'ready') continue;+ void stripRemoteCodexMcpConfig(host, {+ hasLiveTurnOnHost: liveTurnChecker ?? undefined,+ });+ }+}+/*** 远端 codex daemon / cc query 经 SSH remote-forward 直连本机 MCP bridge 的* 注入链路 (remote-ssh/codex-remote-mcp.ts、cc-remote-mcp 调用) 调用:确保@@ -343,6 +370,9 @@ export async function ensureCodexMcpBridgeStartedForRemote(): Promise<{},ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,getLiveTurnChecker: getRemoteCodexLiveTurnChecker,+ // 恢复路径同闸门 (codex-connector R21 P1):collab 全局禁用时+ // ensure 走清理而非重注入。+ isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),log: desktopMakerLogger,});// 远端 CC 侧同源恢复 (codex-connector R19 P2):活跃 query 持旧@@ -615,6 +645,7 @@ export function getMaker(): Maker {// 注入失败降级为"远端无协同 MCP"(历史行为),不阻塞 session 建立。let mcpCleanup: () => void = () => {};let injectedServerCount = 0;+ let mcpNeedsFreshStart = false;try {const injected = await buildCcRemoteHttpMcpServers({@@ -632,6 +663,7 @@ export function getMaker(): Maker {},);mcpCleanup = injected.cleanup;+ mcpNeedsFreshStart = injected.needsFreshStart === true;if (Object.keys(injected.servers).length > 0) {injectedServerCount = Object.keys(injected.servers).length;const mutableParams = startParams as { mcpServers?: Record<string, unknown> };@@ -653,8 +685,11 @@ export function getMaker(): Maker {// bridge 内存表还在) 不触发 — 本 Set 随进程生命周期。// 状态只在 open 成功后提交:open 失败 (daemon 未起等) 时下次重试// 仍要 forceFresh, 否则 attach 到旧 query 上协同 MCP 永久 404。+ // token 失效 (mcpNeedsFreshStart) 同样强制 fresh:attach 回带旧+ // token header 的 alive query 会持续 401 (codex-connector R21 P2)。const forceFreshQuery =- injectedServerCount > 0 && !forcedFreshCcBridgeSessions.has(sessionId);+ (injectedServerCount > 0 || mcpNeedsFreshStart) &&+ !forcedFreshCcBridgeSessions.has(sessionId);// 协同 MCP 已 mutate 进 startParams.mcpServers;这里再把 proxy env 合入// 得到最终 startParams (mcpServers 与 env 都带上)。diff --git a/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts b/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.tsindex ddfd482555..458a9735c8 100644--- a/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts+++ b/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts@@ -29,6 +29,12 @@ export interface RemoteCodexMcpRecoveryDeps {ensureBridgeStarted: () => Promise<RemoteMcpBridgeEndpoint | null>;/** live-turn 判定缺失时 (checker 未装配) 返回 null → 整体不触发 (宁可不补刀, 不误杀 turn)。 */getLiveTurnChecker: () => ((hostId: string) => boolean) | null;+ /**+ * Collab 全局开关 (plugin registry Tier 4)。恢复路径的 ensure 必须透传 —+ * 缺省视为开启的话, 用户禁用 Collab 后 bridge 重建会把刚清理的受管段+ * 重新注入回去 (codex-connector R21 P1)。+ */+ isCollabEnabled: () => boolean;log: { warn: (msg: string, meta?: Record<string, unknown>) => void };}@@ -41,6 +47,7 @@ export function refreshRemoteCodexMcpAfterBridgeRecreate(deps: RemoteCodexMcpRecvoid ensureRemoteCodexMcpBridge(host, {ensureBridgeStarted: deps.ensureBridgeStarted,hasLiveTurnOnHost: liveTurnChecker,+ isCollabEnabled: deps.isCollabEnabled,}).then((result) => {if (!result.ok) {deps.log.warn('remote MCP recovery after bridge recreate failed', {diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex d52457548c..b5816669a5 100644--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts@@ -28,7 +28,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [id: "collaboration",title: "Collaboration mode (lead + workers)",summary: "Turn on Collab to bring one or more worker agents in beside your session and delegate tasks to them.",- content: "Collaboration (\"协同\" / Collab) lets one session — the **lead** — bring in one or more **worker** agents to run alongside it (a \"team\"). The lead delegates tasks to workers through a built-in MCP, and you can watch and steer each worker.\n\n**Turning it on:**\n\n- In a local project session, click the **Collab** pill in the composer toolbar. Both Claude Code and Codex sessions can be the lead.\n- Pick the first worker's agent (Claude Code or Codex), and optionally its role / model / effort / an initial task.\n- Start. This creates the team plus that first worker.\n\n**Adding more workers:**\n\n- From the collaboration tab's worker list, use **Create new worker** (+) to add more.\n- Default limits are a **soft cap of 5** and a **hard cap of 8** workers per lead — you'll see a warning past the soft cap, and creation is blocked at the hard cap. Both are adjustable (1–20) in the Collaboration section under **Settings > General**.\n\n**While collaborating:**\n\n- Each worker is a full session with its own history, tools, working directory, and model, and runs with permissions bypassed so it doesn't stop to ask. It inherits the lead's working directory by default (or shares the worktree when the lead uses one).\n- A worker's model defaults to your last \"New Maker\" choice for that vendor, falling back to the lead's model.\n- Only one worker is **focused** (shown) at a time — switch between them with the worker tabs / dropdown. You can intervene in any worker directly, and archive workers individually.\n\n**Turning it off:**\n\n- Closing collab **confirms with you first** (in-progress work is lost), then ends the workflow and archives **all** the team's workers. The conversation history stays searchable.\n\n**Notes:**\n\n- The lead must be a **local** Claude Code / Codex **project** session — remote sessions can't be the lead yet, and a worker can't start its own sub-collab (no nesting).\n- A lead can have only **one active collaboration workflow** at a time. If you have two clients open on the same account (e.g. dev + release) and start collab on the same session in both, the second fails with \"开启协同失败\" because a workflow is already active — close one client or end the existing collab.",+ content: "Collaboration (\"协同\" / Collab) lets one session — the **lead** — bring in one or more **worker** agents to run alongside it (a \"team\"). The lead delegates tasks to workers through a built-in MCP, and you can watch and steer each worker.\n\n**Turning it on:**\n\n- In a project session — local or SSH remote — click the **Collab** pill in the composer toolbar. Both Claude Code and Codex sessions can be the lead, on either side.\n- Pick the first worker's agent (Claude Code or Codex), and optionally its role / model / effort / an initial task.\n- Start. This creates the team plus that first worker.\n\n**Adding more workers:**\n\n- From the collaboration tab's worker list, use **Create new worker** (+) to add more.\n- Default limits are a **soft cap of 5** and a **hard cap of 8** workers per lead — you'll see a warning past the soft cap, and creation is blocked at the hard cap. Both are adjustable (1–20) in the Collaboration section under **Settings > General**.\n\n**While collaborating:**\n\n- Each worker is a full session with its own history, tools, working directory, and model, and runs with permissions bypassed so it doesn't stop to ask. It inherits the lead's working directory by default (or shares the worktree when the lead uses one).\n- A worker's model defaults to your last \"New Maker\" choice for that vendor, falling back to the lead's model.\n- Only one worker is **focused** (shown) at a time — switch between them with the worker tabs / dropdown. You can intervene in any worker directly, and archive workers individually.\n\n**Turning it off:**\n\n- Closing collab **confirms with you first** (in-progress work is lost), then ends the workflow and archives **all** the team's workers. The conversation history stays searchable.\n\n**Notes:**\n\n- The lead must be a Claude Code / Codex **project** session — local **or SSH remote**. On a remote lead, workers are spawned on the **same remote host**, and the collaboration MCP reaches the remote side over an SSH remote-forward to the local bridge (with a persistent bearer token). A worker can't start its own sub-collab (no nesting).\n- A lead can have only **one active collaboration workflow** at a time. If you have two clients open on the same account (e.g. dev + release) and start collab on the same session in both, the second fails with \"开启协同失败\" because a workflow is already active — close one client or end the existing collab.",},{id: "commands",@@ -114,7 +114,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [title: "Remote workspaces and device control",summary: "Run agents on a remote machine over SSH, and let another signed-in device (e.g. your phone) control this desktop — both in Settings > Remote & device control.",tab: "remote-control",- content: "Settings > **Remote & device control** has two parts: **SSH remote workspaces** (run an agent on another machine) and **My Devices** (let other devices you're signed into control this one).\n\n**SSH remote workspaces:**\n\n- **Add a host** with the **+** button: give it an alias, hostname (IP or domain), user, port (default 22), and an auth method (SSH agent or a key file). Hosts from your `~/.ssh/config` also show up automatically; you can re-read that file at any time.\n- Once a host connects (status dot turns green), expand it to:\n - **Install the agents** (Claude Code / Codex) on the remote machine, and run a quick test prompt against them.\n - **Start a remote session** — enter a working directory on the remote (defaults to `~`); the app creates the directory if needed and opens a normal session whose agent runs **on the remote machine** with that remote working directory. It appears in your sidebar like any other session.\n- The agent-facing SSH tools (via the `cindy-ssh` plugin) reuse these **same** configured hosts — if a tool reports the host isn't found, add it here first.\n\n**My Devices (controlling this desktop from another device):**\n\n- **No manual pairing** — any device signed into the **same Cindy account** is discovered automatically and appears in the list (this is how the phone app connects to your desktop).\n- The **top card is this machine**: rename it, see its relay-connection status, and toggle the master switch **\"allow other devices to control this machine\"**.\n- Each **other device** has two independent switches: **you control it** (outbound) and **allow it to control this machine** (inbound). You can rename devices, and delete ones that are offline.\n\n**What a controlling device can and can't do:**\n\n- A controlling device (like the phone app, which is control-only — it has no local agent or database of its own) can drive sessions: create / close / fork them, send and steer input, approve interaction prompts, switch model / effort / permission mode, rewind, manage collaboration workers and scheduled tasks, and read session / message lists.\n- It can **not** touch auth or API keys, change global settings, write the database directly, trigger updates, or run local shell / file dialogs on the controlled machine. A new remote session's working directory must be currently accessible on the controlled desktop; disconnected network drives are rejected.\n\n**Notes:**\n\n- Remote sessions can't be the lead in a collaboration workflow yet (see the Collaboration topic).\n- Device control works only between devices on the **same account**; the relay just routes between them — your session data isn't stored on it.",+ content: "Settings > **Remote & device control** has two parts: **SSH remote workspaces** (run an agent on another machine) and **My Devices** (let other devices you're signed into control this one).\n\n**SSH remote workspaces:**\n\n- **Add a host** with the **+** button: give it an alias, hostname (IP or domain), user, port (default 22), and an auth method (SSH agent or a key file). Hosts from your `~/.ssh/config` also show up automatically; you can re-read that file at any time.\n- Once a host connects (status dot turns green), expand it to:\n - **Install the agents** (Claude Code / Codex) on the remote machine, and run a quick test prompt against them.\n - **Start a remote session** — enter a working directory on the remote (defaults to `~`); the app creates the directory if needed and opens a normal session whose agent runs **on the remote machine** with that remote working directory. It appears in your sidebar like any other session.\n- The agent-facing SSH tools (via the `cindy-ssh` plugin) reuse these **same** configured hosts — if a tool reports the host isn't found, add it here first.\n\n**My Devices (controlling this desktop from another device):**\n\n- **No manual pairing** — any device signed into the **same Cindy account** is discovered automatically and appears in the list (this is how the phone app connects to your desktop).\n- The **top card is this machine**: rename it, see its relay-connection status, and toggle the master switch **\"allow other devices to control this machine\"**.\n- Each **other device** has two independent switches: **you control it** (outbound) and **allow it to control this machine** (inbound). You can rename devices, and delete ones that are offline.\n\n**What a controlling device can and can't do:**\n\n- A controlling device (like the phone app, which is control-only — it has no local agent or database of its own) can drive sessions: create / close / fork them, send and steer input, approve interaction prompts, switch model / effort / permission mode, rewind, manage collaboration workers and scheduled tasks, and read session / message lists.\n- It can **not** touch auth or API keys, change global settings, write the database directly, trigger updates, or run local shell / file dialogs on the controlled machine. A new remote session's working directory must be currently accessible on the controlled desktop; disconnected network drives are rejected.\n\n**Notes:**\n\n- Remote project sessions **can** be the lead in a collaboration workflow — workers then run on the same remote host (see the Collaboration topic).\n- Device control works only between devices on the **same account**; the relay just routes between them — your session data isn't stored on it.",},{id: "reviewing-changes",diff --git a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.tsindex 4a45cf00cb..0e983513e2 100644--- a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts+++ b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts@@ -15,6 +15,7 @@ import {renderManagedMcpBlock,mergeManagedMcpBlock,ensureRemoteCodexMcpBridge,+ stripRemoteCodexMcpConfig,} from '../codex-remote-mcp.js';// safeStorage 在测试 stub 里 isEncryptionAvailable=false → token 真源恒 null;@@ -1012,3 +1013,114 @@ describe('codex-connector R20 regressions', () => {expect(configContent).toContain('model = "gpt-5.5"'); // 用户配置保留});});++describe('codex-connector R21 regressions', () => {+ it('does not release the forward while a live turn defers cleanup; releases after the turn settles (R21 P2)', async () => {+ // R20-1 把拆 forward 放进清理路径, 但拆在 live-turn defer 判定之前 —+ // turn 中 daemon 内存 config 仍指该端口, 早拆 = connection refused。+ // 修正:bootstrap (清理真正生效) 时才拆。+ const stale = renderManagedMcpBlock({ remotePort: 47921, serverNames: SERVERS, tokenFingerprint: 'fp-old' });+ let configContent = `model = "gpt-5.5"\n\n${stale}\n`;+ const closeCalls: Array<{ addr: string; port: number }> = [];+ const host = {+ id: 'host-defer-norelease',+ exec: async (cmd: string, opts?: { input?: string }) => {+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {+ return { exitCode: 0, stdout: configContent, stderr: '' };+ }+ if (cmd.includes('base64 -d')) {+ const written = decodeWrittenConfig(opts?.input ? [opts.input] : []);+ if (written !== null) configContent = written;+ }+ return { exitCode: 0, stdout: 'ok', stderr: '' };+ },+ ensureRemoteForward: async (spec: { localHost: string; localPort: number; preferredRemotePort?: number }) => ({+ remotePort: spec.preferredRemotePort ?? 47921,+ close: async () => {},+ }),+ closeRemoteForward: async (addr: string, port: number) => {+ closeCalls.push({ addr, port });+ },+ } as unknown as RemoteHost;+ const deps = (live: boolean) => ({+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'], bridgeInstanceId: 'bridge-1' }),+ hasLiveTurnOnHost: () => live,+ });++ // 先注入 (留下 bridgeLocalPort)。+ const hostForInject = {+ ...host,+ exec: async (cmd: string, opts?: { input?: string }) => {+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {+ return { exitCode: 0, stdout: configContent, stderr: '' };+ }+ if (cmd.includes('base64 -d')) {+ const written = decodeWrittenConfig(opts?.input ? [opts.input] : []);+ if (written !== null) configContent = written;+ }+ return { exitCode: 0, stdout: 'ok', stderr: '' };+ },+ } as unknown as RemoteHost;+ expect((await ensureRemoteCodexMcpBridge(hostForInject, {+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),+ hasLiveTurnOnHost: () => false,+ })).ok).toBe(true);++ // live turn 中的清理:config 剥除但不 bootstrap、不拆 forward。+ const first = await ensureRemoteCodexMcpBridge(host, deps(true));+ expect(first.ok).toBe(true);+ expect(closeCalls).toHaveLength(0);++ // turn 结束后:bootstrap 生效 + forward 拆除。+ const second = await ensureRemoteCodexMcpBridge(host, deps(false));+ expect(second.ok).toBe(true);+ expect(closeCalls).toEqual([{ addr: '127.0.0.1', port: 38080 }]);+ });++ it('stripRemoteCodexMcpConfig strips the block, clears env, and skips entirely during a live turn (R21 P1)', async () => {+ const stale = renderManagedMcpBlock({ remotePort: 47921, serverNames: SERVERS, tokenFingerprint: 'fp-old' });+ let configContent = `model = "gpt-5.5"\n\n${stale}\n`;+ const execCmds: string[] = [];+ const host = {+ id: 'host-strip-shutdown',+ exec: async (cmd: string, opts?: { input?: string }) => {+ execCmds.push(cmd);+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {+ return { exitCode: 0, stdout: configContent, stderr: '' };+ }+ if (cmd.includes('base64 -d')) {+ const written = decodeWrittenConfig(opts?.input ? [opts.input] : []);+ if (written !== null) configContent = written;+ }+ return { exitCode: 0, stdout: 'ok', stderr: '' };+ },+ ensureRemoteForward: async (spec: { localHost: string; localPort: number; preferredRemotePort?: number }) => ({+ remotePort: spec.preferredRemotePort ?? 47921,+ close: async () => {},+ }),+ closeRemoteForward: async () => {},+ } as unknown as RemoteHost;++ // 先注入成功。+ expect((await ensureRemoteCodexMcpBridge(host, {+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),+ hasLiveTurnOnHost: () => false,+ })).ok).toBe(true);+ expect(prefsOf('host-strip-shutdown')?.appliedFingerprint).toBeTruthy();+ execCmds.length = 0;++ // live turn 中 strip:整体跳过 (不写不重启)。+ await stripRemoteCodexMcpConfig(host, { hasLiveTurnOnHost: () => true });+ expect(execCmds.join('\n')).not.toContain('base64 -d');+ expect(execCmds.join('\n')).not.toContain('bootstrap');++ // idle 后 strip:剥段 + bootstrap 清 env + applied 摘除。+ await stripRemoteCodexMcpConfig(host, { hasLiveTurnOnHost: () => false });+ const joined = execCmds.join('\n');+ expect(joined).toContain('base64 -d');+ expect(joined).toContain('bootstrap');+ expect(configContent).not.toContain('cindy-remote-mcp');+ expect(configContent).toContain('model = "gpt-5.5"');+ expect(prefsOf('host-strip-shutdown')?.appliedFingerprint).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.tsindex d625d0de97..df7ffd2fc0 100644--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts@@ -557,6 +557,52 @@ export function ensureRemoteMcpForward(// ── 主入口 ──────────────────────────────────────────────────────────────────+/**+ * bridge shutdown 时的立即清理 (无 bridge 变体, codex-connector R21 P1):+ * 插件 / 全局设置变更触发 shutdownCodexEnvironment 后, 远端 daemon config+ * 仍指向已停 bridge — 立刻剥受管段 + 清 daemon env, 让「指向死 bridge 的+ * 404 / connection-refused MCP」当场降级为「无 MCP」;lazy 重建后恢复遍历+ * (remote-codex-mcp-recovery) 会按常规漂移路径重新注入。+ *+ * live turn 时整体跳过:旧 config 在 turn 中仍可用 (daemon 内存态),+ * turn-done 的 ensure 会兜底。失败只记 warn 不抛 (shutdown 路径不因此被+ * 阻断)。与 ensure 共用 per-host 串行锁。+ */+export function stripRemoteCodexMcpConfig(+ host: RemoteHost,+ deps?: { hasLiveTurnOnHost?: (hostId: string) => boolean },+): Promise<void> {+ return withHostSerial(host.id, async () => {+ try {+ if (deps?.hasLiveTurnOnHost?.(host.id)) return;+ const existing = await readRemoteConfig(host);+ const { next, changed } = mergeManagedMcpBlock(existing, '', { serverNames: [] });+ if (changed) {+ await writeRemoteConfig(host, next);+ log.info('remote codex config.toml managed block stripped on bridge shutdown', {+ host: host.id,+ });+ }+ const applied = readPortPrefs()[host.id]?.appliedFingerprint;+ const daemonRunning = await isDaemonRunning(host);+ if (daemonRunning && (changed || applied)) {+ await bootstrapDaemon(host, '');+ log.info('remote codex daemon rebootstrapped with empty MCP env on bridge shutdown', {+ host: host.id,+ });+ }+ if (changed || applied) clearHostAppliedFingerprint(host.id);+ // 清理生效后拆 MCP forward (R21 P2 语义:live turn 已在上面整体跳过)。+ await releaseRemoteMcpForwardIfAny(host);+ } catch (err) {+ log.warn('strip remote codex MCP config on bridge shutdown failed', {+ host: host.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ });+}+/*** 确保远端 codex daemon 能用上本机 MCP bridge。幂等,挂在 remote codex* session 的 start/resume 前置 (ensureRemoteReadyForSessionStart)。@@ -646,12 +692,11 @@ async function doEnsureRemoteCodexMcpBridge(// 只有确实要下发 server 时才 arm forward:清理路径 (serverNames 空)// 剥 config / 清 env 都不经隧道 — forward 被拒或扫描窗口耗尽不该// 阻断清理, 否则旧受管段与 daemon env 残留成「持续暴露死 MCP」- // (codex-connector R20 P2)。清理路径下 MCP forward 本身也是清理对象:- // 有 bridgeLocalPort 记录就拆掉。+ // (codex-connector R20 P2)。拆除旧 forward 则推迟到清理真正生效+ // (bootstrap) 时:live turn 期间 defer 不拆 — daemon 内存里的旧+ // config 还指着这个端口, 早拆会让进行中的协同调用 connection+ // refused, 与「不打断 live turn」自相矛盾 (codex-connector R21 P2)。const remotePort = serverNames.length > 0 ? await ensureRemotePort(host, bridge.port) : 0;- if (serverNames.length === 0) {- await releaseRemoteMcpForwardIfAny(host);- }// token 与 bridge 代际一起进指纹:token 轮换 (账号切换) 与 bridge 重建// (旧 mcp-session-id 全失效, codex-connector P2) 都构成 config 漂移,@@ -738,6 +783,11 @@ async function doEnsureRemoteCodexMcpBridge(// driftUnapplied 仍成立, 强制重试 (跨 app 重启同样成立)。if (desiredFingerprint) writeHostAppliedFingerprint(host.id, desiredFingerprint);else clearHostAppliedFingerprint(host.id);+ if (serverNames.length === 0) {+ // 清理真正生效 (daemon 已持空 env 重启) 才拆 MCP forward — 见+ // ensureRemotePort 调用点注释 (R21 P2: live turn defer 期间不拆)。+ await releaseRemoteMcpForwardIfAny(host);+ }log.info('remote codex daemon (re)bootstrapped with MCP bridge env', {host: host.id,daemonWasRunning: daemonRunning,