Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 远端 MCP 漂移自愈改持久指纹驱动 + turn-done 补刀

yanebabf07701c4
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 283e8d94c6..b831b7ecac 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1644,6 +1644,11 @@ const rewindInputSessions = new Set<string>();
const SESSION_REWIND_INPUT_LOCK_ID = 'session-rewind';
const SESSION_REWIND_STOP_TIMEOUT_MS = 15_000;
let pendingCredentialSwitchHolder: PendingCredentialSwitchService | null = null;
+// turn 收口时对远端 codex MCP 做一次 best-effort ensure 的钩子 (live turn
+// 期间被推迟的 daemon bootstrap 在 idle 时点补刀)。真实现定义在
+// registerMakerIpcs 闭包内 (依赖 maker / ensure 函数), 模块级 turn 收口
+// 路径经 holder 调用; 未注入时 no-op。
+let refreshRemoteCodexMcpOnTurnSettledHolder: ((sessionId: string) => void) | null = null;
let deferredCodexRestartHolder: DeferredCodexRestartService | null = null;
let pendingAgentSwitchApplyHolder:
((sessionId: string, signal?: AbortSignal) => Promise<() => void>) | null = null;
@@ -2316,6 +2321,7 @@ function settleSilentStopDone(sessionId: string, reason: 'exhausted' | 'skip' |
void pendingCredentialSwitchHolder?.onTurnSettled(sessionId);
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);
fireSilentStopSettled(sessionId, reason);
}
@@ -2715,6 +2721,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
void pendingCredentialSwitchHolder?.onTurnSettled(session.id);
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
} else if (shouldMarkTurnStatusIdleAfterBroadcast) {
sessionTurnActivityTracker.scheduleIdleAfterStatusBroadcast(session.id);
// status:isRunning=false 即逻辑 turn 结束(可重试 error 不发这个信号)。
@@ -3241,6 +3248,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
pendingCredentialSwitchHolder?.onSessionClosed(session.id);
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
gitSnapshotCoordinator?.onSessionClosed(session.id);
wiredSessionsById.delete(session.id);
for (const dispose of registration.disposers) dispose();
@@ -4374,14 +4382,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await ensureRemoteCodexMcpBridge(host, {
ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
// config 漂移生效要重启 daemon, 重启会断同 host 的 live turn:
- // 有 turn 在跑时本次降级 (config 留旧值, 下次 ensure 重试)。
- hasLiveTurnOnHost: (hostId) =>
- maker.listActiveSessions().some(
- (s) =>
- s.remoteHostId === hostId &&
- s.agentKind === 'codex' &&
- (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),
- ),
+ // 有 turn 在跑时 config 照写但 bootstrap 推迟 (driftUnapplied 持久,
+ // turn-done 挂钩补刀)。
+ hasLiveTurnOnHost: codexRemoteHasLiveTurn,
});
}
}
@@ -4392,6 +4395,33 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// (review: PR #778 codex-connector R17 P1)。
setRemoteSessionStartEnsure(ensureRemoteReadyForSessionStart);
+ // codex 远端 daemon 的 live-turn 判定 (ensure 与 turn-done 挂钩共用):
+ // bootstrap 重启会断同 host 的 live turn, defer/补刀都以此为据。
+ const codexRemoteHasLiveTurn = (hostId: string): boolean =>
+ maker.listActiveSessions().some(
+ (s) =>
+ s.remoteHostId === hostId &&
+ s.agentKind === 'codex' &&
+ (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),
+ );
+
+ // turn 结束后补一次远端 MCP ensure (best-effort):live turn 期间被推迟的
+ // daemon bootstrap (driftUnapplied 持久指纹, 见 codex-remote-mcp.ts) 在
+ // idle 时点必然补刀 — 不等用户下次操作 (Greptile: defer 需要可靠自愈
+ // 路径)。ensure 幂等, 无漂移时仅一次 config 读 + daemon 探活。经模块级
+ // holder 供各 turn 收口路径调用。
+ refreshRemoteCodexMcpOnTurnSettledHolder = (sessionId: string): void => {
+ const session = maker.getSession(sessionId);
+ const remoteHostId = session?.remoteHostId;
+ if (!remoteHostId || session?.agentKind !== 'codex') return;
+ const host = getRemoteSshPool().get(remoteHostId);
+ if (host?.getStatus() !== 'ready') return;
+ void ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
+ hasLiveTurnOnHost: codexRemoteHasLiveTurn,
+ });
+ };
+
const makerSessionRegistry = createElectronIpcHandlerRegistry();
registerMakerSessionCreateHandler(
makerSessionRegistry,
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.ts
index 406d7932ee..dac9d91b17 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
@@ -4,8 +4,11 @@
* 追加语义(漂移检测是"内容一致则不重写、不重启 daemon"的前提)。
*/
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it, vi, beforeAll } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import { app } from 'electron';
import type { RemoteHost } from '@cindy/maker-remote-ssh';
import {
@@ -22,6 +25,13 @@ vi.mock('../../mcp-integrations/remoteMcpBridgeToken.js', () => ({
const SERVERS = ['cindy_orca', 'orca_worker_bridge'];
+// remote-mcp-forwards.json 在真实 userData stub 目录跨 vitest 运行残留
+// (appliedFingerprint 持久化后会影响 driftUnapplied 判定) — 每次运行起始
+// 清掉;模块级 portPrefsCache 是懒加载, 此刻必然未读, 首读即空文件。
+beforeAll(() => {
+ fs.rmSync(path.join(app.getPath('userData'), 'remote-mcp-forwards.json'), { force: true });
+});
+
/** 走完整 ensure 流程的 fake host:读 config 返回给定内容, 其余命令一律成功。 */
function fakeHost(hostId: string, configContent: string) {
const execCmds: string[] = [];
@@ -355,9 +365,10 @@ describe('ensureRemoteCodexMcpBridge live-turn defer', () => {
ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
};
- it('defers config write and daemon restart while a live turn exists on the host', async () => {
+ it('writes config but defers daemon restart while a live turn exists on the host', async () => {
// P1 回归:config 漂移生效必须重启 daemon, 重启会断同 host 的 live turn —
- // 有 turn 时跳过写入与重启 (config 留旧值, 下次 ensure 重试)。
+ // 有 turn 时 config 照写 (daemon 运行中不读 config, 落盘无害) 但 bootstrap
+ // 推迟;driftUnapplied 是持久指纹事实, turn 结束后的 ensure 必然补刀。
const { host, execCmds } = fakeHost('host-defer-live', '');
const result = await ensureRemoteCodexMcpBridge(host, {
...bridgeDeps,
@@ -366,8 +377,8 @@ describe('ensureRemoteCodexMcpBridge live-turn defer', () => {
expect(result.ok).toBe(true);
const joined = execCmds.join('\n');
expect(joined).toContain('config.toml'); // 仍读了 config (漂移检测)
- expect(joined).not.toContain('base64 -d'); // 不写 config
- expect(joined).not.toContain('bootstrap'); // 不重启 daemon
+ expect(joined).toContain('base64 -d'); // config 照写 (落盘等新指纹)
+ expect(joined).not.toContain('bootstrap'); // 但不重启 daemon
});
it('writes config and rebootstraps once the host has no live turn', async () => {
@@ -585,3 +596,136 @@ describe('ensureRemoteCodexMcpBridge server whitelist', () => {
expect(joined3).not.toContain('bootstrap');
});
});
+
+describe('ensureRemoteCodexMcpBridge drift self-heal (appliedFingerprint)', () => {
+ function prefsOf(hostId: string): { remotePort?: number; appliedFingerprint?: string } | null {
+ const file = path.join(app.getPath('userData'), 'remote-mcp-forwards.json');
+ if (!fs.existsSync(file)) return null;
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as Record<string, { remotePort?: number; appliedFingerprint?: string }>;
+ return raw[hostId] ?? null;
+ }
+
+ it('bootstraps on the next ensure once the live turn settles (deferred drift stays persistent)', async () => {
+ // defer 语义回归:live turn 期间 config 照写但 bootstrap 推迟;漂移未生效
+ // 是持久指纹事实 — turn 结束 (hasLiveTurn=false) 后的 ensure 即使
+ // changed=false 也必然补刀 (turn-done 挂钩 / 下次 session start)。
+ let configContent = '';
+ const execCmds: string[] = [];
+ const host = {
+ id: 'host-defer-heal',
+ 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 ?? 47923,
+ close: async () => {},
+ }),
+ } as unknown as RemoteHost;
+ const deps = (live: boolean) => ({
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => live,
+ });
+
+ const first = await ensureRemoteCodexMcpBridge(host, deps(true));
+ expect(first.ok).toBe(true);
+ expect(execCmds.join('\n')).not.toContain('bootstrap'); // live: 推迟重启
+ expect(prefsOf('host-defer-heal')?.appliedFingerprint).toBeUndefined(); // 未生效不落盘
+
+ const second = await ensureRemoteCodexMcpBridge(host, deps(false));
+ expect(second.ok).toBe(true);
+ expect(execCmds.join('\n')).toContain('bootstrap'); // idle: 持久漂移驱动补刀
+ expect(prefsOf('host-defer-heal')?.appliedFingerprint).toBeTruthy(); // 生效后落盘
+ });
+
+ it('retries bootstrap after an app restart even when config is unchanged (Greptile P1)', async () => {
+ // Greptile P1 回归:config 已写入 + bootstrap 失败 + app 重启 → 进程内
+ // pending 全丢, 但 appliedFingerprint 持久缺失 ⇒ driftUnapplied 仍成立,
+ // 下次 ensure (changed=false + 旧 daemon 在跑) 强制重试 bootstrap,
+ // daemon 不会永远持旧 token 401。
+ let bootstrapAttempts = 0;
+ let configContent = '';
+ const makeHost = () =>
+ ({
+ id: 'host-restart-heal',
+ exec: async (cmd: string, opts?: { input?: string }) => {
+ if (cmd.includes('cat "$CODEX_HOME/config.toml"')) {
+ return { exitCode: 0, stdout: configContent, stderr: '' };
+ }
+ if (cmd.includes('bootstrap')) {
+ bootstrapAttempts += 1;
+ if (bootstrapAttempts === 1) {
+ return { exitCode: 1, stdout: '', stderr: 'timed out' }; // 首轮失败
+ }
+ return { exitCode: 0, stdout: 'ok', 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 ?? 47924,
+ close: async () => {},
+ }),
+ }) as unknown as RemoteHost;
+ const deps = {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ };
+
+ const first = await ensureRemoteCodexMcpBridge(makeHost(), deps);
+ expect(first.ok).toBe(false); // bootstrap 失败折叠
+ expect(bootstrapAttempts).toBe(1);
+
+ // 模拟 app 重启:模块状态 (串行锁 / prefs cache) 全清, prefs 文件保留。
+ vi.resetModules();
+ const fresh = await import('../codex-remote-mcp.js');
+ const second = await fresh.ensureRemoteCodexMcpBridge(makeHost(), deps);
+ expect(second.ok).toBe(true);
+ expect(bootstrapAttempts).toBe(2); // appliedFingerprint 缺失 ⇒ 强制重试
+ });
+
+ it('clears appliedFingerprint after the cleanup-path bootstrap so later ensures stay quiet', async () => {
+ // 清理路径:受管段剥除 + bootstrap (清 daemon env) 后 applied 记录摘除 —
+ // 否则 desiredFingerprint=null 与残留 applied 恒不等, 之后每次 ensure
+ // 都会无谓重启 daemon。
+ const stale = renderManagedMcpBlock({ remotePort: 47925, serverNames: SERVERS, tokenFingerprint: 'fp-old' });
+ const { host, execCmds } = fakeHost('host-cleanup-quiet', `model = "gpt-5.5"\n\n${stale}\n`);
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'], bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ });
+ expect(result.ok).toBe(true);
+ expect(execCmds.join('\n')).toContain('bootstrap');
+ expect(prefsOf('host-cleanup-quiet')?.appliedFingerprint).toBeUndefined();
+
+ // 下轮 ensure:无受管段、无 applied、desired=null → 静默, 不再 bootstrap。
+ const execCmds2: string[] = [];
+ const host2 = {
+ id: 'host-cleanup-quiet',
+ exec: async (cmd: string) => {
+ execCmds2.push(cmd);
+ return { exitCode: 0, stdout: 'model = "gpt-5.5"\n', stderr: '' };
+ },
+ ensureRemoteForward: async (spec: { localHost: string; localPort: number; preferredRemotePort?: number }) => ({
+ remotePort: spec.preferredRemotePort ?? 47925,
+ close: async () => {},
+ }),
+ } as unknown as RemoteHost;
+ const second = await ensureRemoteCodexMcpBridge(host2, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_memory'], bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ });
+ expect(second.ok).toBe(true);
+ expect(execCmds2.join('\n')).not.toContain('bootstrap');
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
index b8cf60577f..93b6176275 100644
--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
@@ -73,9 +73,9 @@ export interface EnsureRemoteCodexMcpResult {
reason?: string;
}
-// ── per-host 固定 remotePort 持久化 ─────────────────────────────────────────
+// ── per-host 固定 remotePort 与已生效指纹持久化 ─────────────────────────────
-type PortPrefs = Record<string, { remotePort: number }>;
+type PortPrefs = Record<string, { remotePort: number; appliedFingerprint?: string }>;
function portPrefsPath(): string {
return path.join(app.getPath('userData'), 'remote-mcp-forwards.json');
@@ -95,6 +95,10 @@ function readPortPrefs(): PortPrefs {
const port = (v as { remotePort?: unknown })?.remotePort;
if (typeof port === 'number' && Number.isInteger(port) && port > 0 && port < 65536) {
out[hostId] = { remotePort: port };
+ const fp = (v as { appliedFingerprint?: unknown })?.appliedFingerprint;
+ if (typeof fp === 'string' && fp.length > 0) {
+ out[hostId].appliedFingerprint = fp;
+ }
}
}
}
@@ -110,8 +114,7 @@ function readPortPrefs(): PortPrefs {
return portPrefsCache;
}
-function writeHostRemotePort(hostId: string, remotePort: number): void {
- const next = { ...readPortPrefs(), [hostId]: { remotePort } };
+function writePortPrefs(next: PortPrefs): void {
const file = portPrefsPath();
const tmp = `${file}.tmp`;
// userData 在真实 app 里由 electron 保证存在; 测试 stub 只拼路径不建
@@ -123,18 +126,39 @@ function writeHostRemotePort(hostId: string, remotePort: number): void {
portPrefsCache = next;
}
+function writeHostRemotePort(hostId: string, remotePort: number): void {
+ writePortPrefs({ ...readPortPrefs(), [hostId]: { ...readPortPrefs()[hostId], remotePort } });
+}
+
+/**
+ * bootstrap 确认成功后落「已生效指纹」。这是 daemon env 与 config 一致性
+ * 的唯一持久事实:config 已写入 (changed=false) 但 bootstrap 失败/中断 +
+ * app 重启的组合下,进程内 pending 标记会丢,而本记录不会 — 下次 ensure
+ * 比较「应有指纹 ≠ 已生效指纹」仍会强制 bootstrap,daemon 不会永远持旧
+ * env 401 (Greptile P1: 重启丢失令牌更新状态)。
+ */
+function writeHostAppliedFingerprint(hostId: string, fingerprint: string): void {
+ const current = readPortPrefs()[hostId];
+ if (!current) return; // 无端口记录 = 未曾注入, 不写孤儿行
+ writePortPrefs({ ...readPortPrefs(), [hostId]: { ...current, appliedFingerprint: fingerprint } });
+}
+
+/** 清理路径 (白名单为空) bootstrap 后调用:daemon env 已清, 摘除生效记录。 */
+function clearHostAppliedFingerprint(hostId: string): void {
+ const current = readPortPrefs()[hostId];
+ if (!current?.appliedFingerprint) return;
+ const next = { ...readPortPrefs() };
+ delete next[hostId].appliedFingerprint;
+ writePortPrefs(next);
+}
+
/** host 被删时清理端口记录 (registerRemoteSshIpc 的 remove 路径调用)。 */
export function removeRemoteMcpForwardPref(hostId: string): void {
const current = readPortPrefs();
if (!(hostId in current)) return;
const next = { ...current };
delete next[hostId];
- const file = portPrefsPath();
- const tmp = `${file}.tmp`;
- fs.mkdirSync(path.dirname(file), { recursive: true });
- fs.writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf-8');
- fs.renameSync(tmp, file);
- portPrefsCache = next;
+ writePortPrefs(next);
}
// ── 远端 config.toml 管理段 (纯函数, 便于单测) ──────────────────────────────
@@ -413,17 +437,6 @@ async function ensureRemotePort(host: RemoteHost, localBridgePort: number): Prom
// ── per-host 串行锁与共用 forward 入口 ───────────────────────────────────────
-/**
- * bootstrap 未确认完成的 host 集合 (进程内存态)。config 写入成功但
- * bootstrap 超时/中断 (旧 daemon 还活着) 时, 下次 ensure 会看到
- * changed=false && daemonRunning=true → 永远跳过 bootstrap, daemon 一直
- * 持旧 env (无 token) → 远端请求 401 且不自愈 (review P2 回归)。进入
- * bootstrap 分支前悲观标记, 全部成功后清除; 失败保留, 下次 ensure 强制
- * 重试 bootstrap。已知边界:进程重启后标记丢失, 跨进程残留需 daemon 自行
- * 重启或 token 轮换 (指纹漂移) 触发, 接受为该罕见组合下的限制。
- */
-const pendingBootstrapHosts = new Set<string>();
-
/**
* per-host 串行链:同一 host 的 forward 端口分配 / config.toml 读写 / daemon
* bootstrap 必须串行——并发时两个 ensure 会互相交错 arm 与 config 写入,
@@ -542,14 +555,6 @@ async function doEnsureRemoteCodexMcpBridge(
servers: strippedUserServers,
});
}
- if (changed && deps.hasLiveTurnOnHost?.(host.id)) {
- // 漂移生效要重启 daemon, 重启会断 live turn:本次跳过写入与重启,
- // config 保持旧值 (下次 ensure 仍 changed=true 会重试), 远端降级无 MCP。
- log.warn('remote MCP config drift deferred: live turn in progress on host', {
- host: host.id,
- });
- return { ok: true };
- }
if (changed) {
await writeRemoteConfig(host, next);
log.info('remote codex config.toml mcp_servers updated', {
@@ -559,12 +564,29 @@ async function doEnsureRemoteCodexMcpBridge(
});
}
+ // 「daemon env 是否已生效」的唯一持久事实:应有指纹 (清理路径为 null —
+ // 目标是 daemon 不持 token) vs bootstrap 确认时落盘的已生效指纹。
+ // 不一致 ⇒ 必须 (重) bootstrap;bootstrap 失败/中断 + app 重启后它依然
+ // 成立, 自愈不依赖任何进程内存态 (Greptile P1: 重启丢失令牌更新状态)。
+ // changed 是并列的独立触发:指纹只含 token|bridge 代际, 端口 / server
+ // 列表变化不进指纹, 只能靠 changed 驱动重启生效。
+ const desiredFingerprint = serverNames.length > 0 ? tokenFingerprint : null;
+ const appliedFingerprint = readPortPrefs()[host.id]?.appliedFingerprint ?? null;
+ const driftUnapplied = desiredFingerprint !== appliedFingerprint;
+ const needApply = changed || driftUnapplied;
+
const daemonRunning = await isDaemonRunning(host);
- if (!daemonRunning || changed || pendingBootstrapHosts.has(host.id)) {
- // 悲观标记:bootstrap 任何一步失败都保留标记, 下次 ensure 强制重试 —
- // 否则 config 已写入 (changed=false) + 旧 daemon 存活 (daemonRunning)
- // 的组合会让 daemon 永远持旧 env, 远端请求 401 且不自愈。
- pendingBootstrapHosts.add(host.id);
+ if (needApply && deps.hasLiveTurnOnHost?.(host.id)) {
+ // bootstrap 重启会断 live turn:config 已就绪 (changed 时已写入, daemon
+ // 运行中不读 config), 本次只推迟重启 — driftUnapplied 是持久事实,
+ // turn 结束后的 ensure (turn-done 挂钩 / 下次 session start) 必然补刀,
+ // 宽限期内 daemon 持旧 env (协同降级) 但 turn 本身不被打断。
+ log.warn('remote MCP daemon bootstrap deferred: live turn in progress on host', {
+ host: host.id,
+ });
+ return { ok: true };
+ }
+ if (!daemonRunning || needApply) {
await bootstrapDaemon(host, effectiveToken);
// 防御:bootstrap 若覆盖了 config.toml (managed_install 行为未文档化),
// 管理段丢失时补写一次并再次 bootstrap。最多两轮,避免无限循环。
@@ -576,7 +598,10 @@ async function doEnsureRemoteCodexMcpBridge(
await writeRemoteConfig(host, next);
await bootstrapDaemon(host, effectiveToken);
}
- pendingBootstrapHosts.delete(host.id);
+ // bootstrap 确认完成才落已生效指纹;失败/中断不落 → 下次 ensure
+ // driftUnapplied 仍成立, 强制重试 (跨 app 重启同样成立)。
+ if (desiredFingerprint) writeHostAppliedFingerprint(host.id, desiredFingerprint);
+ else clearHostAppliedFingerprint(host.id);
log.info('remote codex daemon (re)bootstrapped with MCP bridge env', {
host: host.id,
daemonWasRunning: daemonRunning,