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,orca-workflow): 远端 MCP 失效补全 R22 三案

yanf542e05c1305
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index d030a69b7a..092fc2a36d 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -332,7 +332,6 @@ import {
broadcastXaiAuthStateChanged,
refreshProviderAccessAfterAuthChange,
restartCodexAfterAuthModeChange,
- handleCodexEnvironmentShutdownForRemote,
waitForInitialCustomMcpRefresh,
} from './maker-host/index.js';
import { createDynamicMaker } from './maker-host/dynamic-maker.js';
@@ -5577,9 +5576,6 @@ 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.ts
index 753454b947..a192930f8d 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, handleCodexEnvironmentShutdownForRemote, restartCodexAfterAuthModeChange } from '../maker-host/index.js';
+import { getMaker, 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,9 +150,6 @@ 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__/remoteCcQueryFactory.test.ts b/apps/desktop/src/main/maker-host/__tests__/remoteCcQueryFactory.test.ts
index 0413e8f734..a4a3c3fc1a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/remoteCcQueryFactory.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/remoteCcQueryFactory.test.ts
@@ -103,3 +103,19 @@ describe('remoteCcQueryFactory cleanup wiring', () => {
expect(returnIdx).toBeGreaterThan(clearIdx);
});
});
+
+describe('remoteCcQueryFactory stale-invalidation freshness (R22 P2)', () => {
+ it('forces fresh for invalidated sessions even when nothing is injected this round', () => {
+ // collab 禁用等场景:invalidate 过的 session 重建时无 server 可注
+ // (injectedServerCount===0 且 needsFreshStart=false), 不 forceFresh 会
+ // attach 回带旧 collab URL 的 query — stale 集合必须进入 forceFresh 判定。
+ expect(source).toContain('staleInvalidatedCcSessions.has(sessionId)');
+ // invalidate 的 clearFreshMark 必须同时记 stale。
+ expect(source).toContain('staleInvalidatedCcSessions.add(sessionId)');
+ // open 成功后提交 fresh 的同时必须清掉 stale 标记。
+ const addFresh = source.indexOf('forcedFreshCcBridgeSessions.add(sessionId)');
+ const delStale = source.indexOf('staleInvalidatedCcSessions.delete(sessionId)');
+ expect(addFresh).toBeGreaterThan(-1);
+ expect(delStale).toBeGreaterThan(addFresh);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index a71fa63edc..4c21f7877d 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -114,6 +114,7 @@ import { createPluginRegistry, resetPluginRegistry } from './plugins/index.js';
import {
getCodexExtraSpawnConfig,
registerCodexMcpThreadContext,
+ setCodexEnvironmentShutdownHook,
unregisterCodexMcpThreadContext,
} from '../mcp-integrations/codexEnvironment.js';
import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';
@@ -254,6 +255,13 @@ let _codexMcpProviders: McpProvider[] | null = null;
* 重连 (bridge 表还在) 不重复 kill。见 remoteCcQueryFactory 注释。
*/
const forcedFreshCcBridgeSessions = new Set<string>();
+/**
+ * 被 invalidate 判定为「MCP 代际已过期」的远端 CC session (bridge 重建 /
+ * 端口重绑 / bridge shutdown / collab 禁用)。下次 lazy-resume 重建时无论
+ * 本次能否注入都必须 forceFresh kill 旧 query — 否则 attach 回带旧 URL
+ * 的 query (codex-connector R22 P2)。open 成功后从集合移除。
+ */
+const staleInvalidatedCcSessions = new Set<string>();
/**
* 本进程见过的 bridge 实例 — ensureCodexMcpBridgeStartedForRemote 据此检测
* bridge 重建并清空 forcedFreshCcBridgeSessions (旧 bridge 的
@@ -287,7 +295,14 @@ function invalidateActiveRemoteCcQueries(opts: { hostId?: string; reason: string
{
listRemoteCcSessions: () =>
(_maker?.listActiveSessions() ?? []).filter((s) => s.agentKind === 'claude-code'),
- clearFreshMark: (sessionId) => forcedFreshCcBridgeSessions.delete(sessionId),
+ // invalidate 的语义是「该 query 的 MCP 代际已过期」— 除清 fresh 标记
+ // 外记入 stale 集合:下次重建 (lazy-resume) 无论本次是否注入 (例如
+ // collab 已禁用 → 无 server 可注) 都必须 forceFresh kill 旧 query,
+ // 否则 attach 回带旧 collab URL 的 query (codex-connector R22 P2)。
+ clearFreshMark: (sessionId) => {
+ forcedFreshCcBridgeSessions.delete(sessionId);
+ staleInvalidatedCcSessions.add(sessionId);
+ },
log: desktopMakerLogger,
},
opts,
@@ -491,6 +506,10 @@ export function getMaker(): Maker {
broadcastOrcaWorkerChanged,
logger: desktopMakerLogger,
});
+ // bridge shutdown 后的远端失效统一折进 shutdownCodexEnvironment 内部
+ // (codex-connector R22 P1):插件开关 / custom MCP CRUD / contacts /
+ // Slack provider / 账号切换等所有 shutdown 路径自动覆盖, 不靠逐点调用。
+ setCodexEnvironmentShutdownHook(handleCodexEnvironmentShutdownForRemote);
// forward 端口重绑 (SSH 重连 onRearmed) 时, 该 host 上活跃远端 CC
// query 的 mcpServers URL 还指旧端口 — fresh 失效 + detach 促重建
// (codex-connector R19 P2)。
@@ -687,8 +706,11 @@ export function getMaker(): Maker {
// 仍要 forceFresh, 否则 attach 到旧 query 上协同 MCP 永久 404。
// token 失效 (mcpNeedsFreshStart) 同样强制 fresh:attach 回带旧
// token header 的 alive query 会持续 401 (codex-connector R21 P2)。
+ // 被 invalidate 过 (staleInvalidatedCcSessions) 也一样:collab 禁用
+ // 等场景重建时无 server 可注, 不 forceFresh 会 attach 回带旧 collab
+ // URL 的 query (codex-connector R22 P2)。
const forceFreshQuery =
- (injectedServerCount > 0 || mcpNeedsFreshStart) &&
+ (injectedServerCount > 0 || mcpNeedsFreshStart || staleInvalidatedCcSessions.has(sessionId)) &&
!forcedFreshCcBridgeSessions.has(sessionId);
// 协同 MCP 已 mutate 进 startParams.mcpServers;这里再把 proxy env 合入
@@ -724,6 +746,7 @@ export function getMaker(): Maker {
})();
if (forceFreshQuery) {
forcedFreshCcBridgeSessions.add(sessionId);
+ staleInvalidatedCcSessions.delete(sessionId);
}
// 把 ssh transport disposer 串进 remoteQuery.close — maker-core 不知道
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
index 4cc8073760..c68c7a5fe4 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
@@ -5,6 +5,7 @@ import type { Logger, McpProvider } from '@cindy/maker-core';
import {
getCodexExtraSpawnConfig,
registerCodexMcpThreadContext,
+ setCodexEnvironmentShutdownHook,
shutdownCodexEnvironment,
unregisterCodexMcpThreadContext,
} from '../codexEnvironment.js';
@@ -78,6 +79,7 @@ function extractUrl(args: string[]): URL {
describe('codexEnvironment', () => {
afterEach(async () => {
+ setCodexEnvironmentShutdownHook(null);
await shutdownCodexEnvironment();
});
@@ -187,4 +189,20 @@ describe('codexEnvironment', () => {
expect(cfg.extraArgs).toContain('mcp_servers.themis.url="https://themis.example/mcp"');
expect(Object.getPrototypeOf({} as Record<string, unknown>)).toBe(Object.prototype);
});
+
+ it('invokes the shutdown hook after the bridge stops, on every shutdown path (R22 P1)', async () => {
+ // 远端失效钩子折进 shutdownCodexEnvironment 内部:任何调用点 (插件开关 /
+ // custom MCP CRUD / contacts / 账号切换) 都自动覆盖, 不靠逐点挂接。
+ const hook = vi.fn();
+ setCodexEnvironmentShutdownHook(hook);
+ await getCodexExtraSpawnConfig({ mcpProviders: [testProvider()], logger: noopLogger() });
+ expect(hook).not.toHaveBeenCalled(); // 未 shutdown 不调
+
+ await shutdownCodexEnvironment();
+ expect(hook).toHaveBeenCalledTimes(1);
+
+ // 未启动过时 (cached 为空) shutdown 是 no-op, 不调 hook。
+ await shutdownCodexEnvironment();
+ expect(hook).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
index 3909f0a285..43009d3ea5 100644
--- a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
@@ -73,6 +73,20 @@ export function getCodexExtraSpawnConfig(
}
/** before-quit 调一次。**先**等 codexAgent.dispose() 杀完子进程**再**调这个 (见 plan)。 */
+/**
+ * bridge 成功 shutdown 后的失效钩子 (maker-host 注入):远端 session 的 MCP
+ * URL / session id 已指向停掉的 bridge, 需要立刻失效 (CC detach + codex
+ * strip), 不能等 lazy 重建 (codex-connector R21/R22 P1)。放本模块内部而
+ * 非各调用点, 让所有 shutdown 路径 (插件开关 / custom MCP CRUD /
+ * contacts / Slack provider / 账号切换 / 未来新增) 自动覆盖。
+ * mcp-integrations 不反向依赖 maker-host, 经 setter 注入解耦。
+ */
+let shutdownHook: (() => void) | null = null;
+
+export function setCodexEnvironmentShutdownHook(fn: (() => void) | null): void {
+ shutdownHook = fn;
+}
+
export async function shutdownCodexEnvironment(): Promise<void> {
const cur = cached;
if (!cur) return;
@@ -87,6 +101,14 @@ export async function shutdownCodexEnvironment(): Promise<void> {
} finally {
if (!bridge || activeBridge === bridge) activeBridge = null;
}
+ // bridge 实际 shutdown 后失效远端 (URL/session id 必然指向已停实例)。
+ // cached 为空 (从未启动) 时 early return 不调 — 彼时本就不存在指向
+ // bridge 的注入, 无需失效。
+ try {
+ shutdownHook?.();
+ } catch {
+ /* 失效失败不阻断 shutdown 主流程 */
+ }
}
export function registerCodexMcpThreadContext(
diff --git a/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts b/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
index 781dc72cc0..04e4a0fc67 100644
--- a/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
+++ b/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
@@ -485,6 +485,9 @@ describe('orca_worker_bridge MCP helpers', () => {
expect(parseToolJson(result)).toMatchObject({ ok: true, lead_session_id: 'lead-1' });
expect(createSessionCalls).toHaveLength(1);
expect(createSessionCalls[0]).toMatchObject({ id: 'lead-1', remoteHostId: 'host-remote-1' });
+ // R22 P2:远端 rehydrate 必须带 makerMemoryEnabled=false (与 IPC create/send
+ // 的 remote ensure 归一化对齐), 不注入本地 Maker Memory 上下文。
+ expect(createSessionCalls[0]).toMatchObject({ makerMemoryEnabled: false });
});
it('runs the injected remote preflight before rehydrating an inactive remote lead', async () => {
diff --git a/packages/orca-workflow/src/orca-bridge-mcp.ts b/packages/orca-workflow/src/orca-bridge-mcp.ts
index e1806ce18b..f77940d2f2 100644
--- a/packages/orca-workflow/src/orca-bridge-mcp.ts
+++ b/packages/orca-workflow/src/orca-bridge-mcp.ts
@@ -453,7 +453,12 @@ async function ensureSessionFromMeta(
...(meta.sdkSessionId ? { resumeSessionId: meta.sdkSessionId } : {}),
// 远端 lead 在同一台 SSH 主机上重建 (host 侧 createSession 会先做
// remote ensure); 本地 lead 无此字段。
- ...(meta.remoteHostId ? { remoteHostId: meta.remoteHostId } : {}),
+ // 远端 lead 在同一台 SSH 主机上重建 (host 侧 createSession 会先做
+ // remote ensure); 本地 lead 无此字段。makerMemoryEnabled=false 与 IPC
+ // create/send 路径的 remote ensure 归一化对齐 (ensure 里对 createOpts
+ // 的同款 mutate) — 远端 workdir 不得注入本地 Cindy Memory 上下文
+ // (codex-connector R22 P2;preflight 用临时 opts, mutation 到不了这里)。
+ ...(meta.remoteHostId ? { remoteHostId: meta.remoteHostId, makerMemoryEnabled: false } : {}),
});
deps.wireSession(session);
return session;