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): 远端协同补全 R23 四案

yan5009f420460d
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.ts
index 29666701f5..b063ee5cca 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
@@ -108,6 +108,58 @@ describe('buildCcRemoteHttpMcpServers', () => {
expect(needsFreshStart).toBeFalsy();
});
+ it('returns a generation fingerprint on successful injection, and the disabled constant when gated off (R23 P2)', async () => {
+ const { bridge } = fakeBridge();
+ const injected = 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(typeof injected.fingerprint).toBe('string');
+ expect(injected.fingerprint!.length).toBeGreaterThan(0);
+
+ const gated = await buildCcRemoteHttpMcpServers(
+ { host: HOST, sessionId: 's2', workingDir: '/remote/repo' },
+ {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'orca_worker_bridge'],
+ bridge,
+ }),
+ ensureForward: vi.fn(async () => 47921),
+ getBridgeToken: async () => 'persistent-test-token',
+ isCollabEnabled: () => false,
+ },
+ );
+ expect(gated.servers).toEqual({});
+ expect(gated.fingerprint).toBe('disabled');
+ });
+
+ it('returns no fingerprint when the bridge token is unavailable (drift stays idle)', async () => {
+ const { bridge } = fakeBridge();
+ const { fingerprint, 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(fingerprint).toBeUndefined();
+ expect(needsFreshStart).toBe(true);
+ });
+
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.ts
index 8dad321908..783d9324bf 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
@@ -133,33 +133,33 @@ describe('invalidateRemoteCcQueriesForMcpGenerationChange', () => {
});
describe('maybeDetachStaleRemoteCcQuery', () => {
- it('detaches when the fresh mark is gone and no turn is running', () => {
+ it('detaches only when the session was explicitly invalidated (stale mark) and no turn is running', () => {
const s = { id: 'cc-1', remoteHostId: 'host-a', isTurnRunning: () => false, detach: vi.fn(async () => {}) };
maybeDetachStaleRemoteCcQuery(
- { getSession: () => s, hasFreshMark: () => false, log: { warn: vi.fn() } },
+ { getSession: () => s, hasStaleMark: () => true, log: { warn: vi.fn() } },
'cc-1',
);
expect(s.detach).toHaveBeenCalledTimes(1);
});
- it('is a no-op when the fresh mark is still valid or the session is local or a turn is running', () => {
+ it('is a no-op for healthy sessions without a stale mark (never-fresh is not stale), local sessions, and running turns', () => {
const fresh = { id: 'cc-1', remoteHostId: 'host-a', isTurnRunning: () => false, detach: vi.fn(async () => {}) };
maybeDetachStaleRemoteCcQuery(
- { getSession: () => fresh, hasFreshMark: () => true, log: { warn: vi.fn() } },
+ { getSession: () => fresh, hasStaleMark: () => false, log: { warn: vi.fn() } },
'cc-1',
);
expect(fresh.detach).not.toHaveBeenCalled();
const local = { id: 'cc-2', remoteHostId: null, isTurnRunning: () => false, detach: vi.fn(async () => {}) };
maybeDetachStaleRemoteCcQuery(
- { getSession: () => local, hasFreshMark: () => false, log: { warn: vi.fn() } },
+ { getSession: () => local, hasStaleMark: () => true, log: { warn: vi.fn() } },
'cc-2',
);
expect(local.detach).not.toHaveBeenCalled();
const running = { id: 'cc-3', remoteHostId: 'host-a', isTurnRunning: () => true, detach: vi.fn(async () => {}) };
maybeDetachStaleRemoteCcQuery(
- { getSession: () => running, hasFreshMark: () => false, log: { warn: vi.fn() } },
+ { getSession: () => running, hasStaleMark: () => true, log: { warn: vi.fn() } },
'cc-3',
);
expect(running.detach).not.toHaveBeenCalled();
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 2da0aec6e9..0cdf5dae33 100644
--- a/apps/desktop/src/main/maker-host/__tests__/remoteCcQueryFactory.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/remoteCcQueryFactory.test.ts
@@ -134,3 +134,17 @@ describe('cc-manager-client forced-fresh kill settle (Greptile R22/R23 P1)', ()
expect(client).toContain('restart the remote');
});
});
+
+describe('remoteCcQueryFactory persistent generation drift (R23 P2)', () => {
+ it('drives forceFresh from the persisted cc generation fingerprint and writes it after open', () => {
+ // collab 开→关 / token 轮换 / bridge 代际跨 app 重启:进程内集合清空
+ // 也要靠 applied 指纹判出旧代际 query。
+ expect(source).toContain('readCcAppliedFingerprint(sessionId)');
+ expect(source).toContain('ccGenerationDrift');
+ expect(source).toContain('mcpInjectFingerprint !== ccAppliedFingerprint');
+ // drift 必须进入 forceFreshQuery 判定。
+ expect(source).toContain('|| ccGenerationDrift)');
+ // open 成功后 (含 attach) 必须落盘 applied 指纹。
+ expect(source).toContain('writeCcAppliedFingerprint(sessionId, mcpInjectFingerprint)');
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
index b183acff9b..7c9a956cda 100644
--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
@@ -13,6 +13,11 @@
* 端口, 与 codex daemon 共用同一条) 与 codex 路径完全一致。
*/
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { app } from 'electron';
import type { RemoteHost } from '@cindy/maker-remote-ssh';
import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';
@@ -119,6 +124,14 @@ export async function buildCcRemoteHttpMcpServers(
* fail-closed (codex-connector R21 P2)。
*/
needsFreshStart?: boolean;
+ /**
+ * 本次注入 (或禁用) 的代际指纹 — 调用方在 open 成功后经
+ * writeCcAppliedFingerprint 落盘;下次 open 前与 readCcAppliedFingerprint
+ * 比对, 不一致说明存活 query 的 MCP 配置属旧代际, 应 forceFresh
+ * (codex-connector R23 P2)。bridge 不在 / token 缺失时为 undefined
+ * (不驱动 drift)。
+ */
+ fingerprint?: string;
}> {
const empty: { servers: Record<string, CcRemoteHttpMcpServerConfig>; cleanup: () => void; needsFreshStart?: boolean } = {
servers: {},
@@ -132,7 +145,12 @@ export async function buildCcRemoteHttpMcpServers(
const names = collabEnabled
? started.serverNames.filter((n) => CC_REMOTE_HTTP_MCP_SERVER_NAMES.has(n))
: [];
- if (names.length === 0) return empty;
+ if (names.length === 0) {
+ // 无注入也是一代 (collab 禁用 / 白名单空):指纹常量 'disabled',
+ // 开→关的重启后 drift 判定成立 (R23 P2);不含 instanceId, 一直禁用
+ // 的健康 query 不被误判。
+ return { ...empty, fingerprint: CC_MCP_DISABLED_FINGERPRINT };
+ }
const remotePort = await deps.ensureForward(args.host, started.port);
// token 可用性必须在 register 之前确认:null 时下发出 "Bearer null" 还
// 保留已注册 ctx (注册后失败无任何 cleanup 可达, 见 race review P1)。
@@ -167,6 +185,11 @@ export async function buildCcRemoteHttpMcpServers(
return {
servers,
cleanup: () => started.bridge.unregisterSessionCtx(args.sessionId, ctx),
+ fingerprint: computeCcRemoteMcpFingerprint({
+ token: bridgeToken,
+ bridgeInstanceId: started.bridge.instanceId,
+ remotePort,
+ }),
};
} catch (err) {
// 注册后失败必须回滚,否则调用方拿不到 cleanup,ctx 永久残留。
@@ -174,3 +197,79 @@ export async function buildCcRemoteHttpMcpServers(
throw err;
}
}
+
+// ── per-session 注入代际指纹持久化 (R23 P2:跨 app 重启的 stale 判定) ─────────
+
+/**
+ * 远端 CC query 的注入代际指纹。与 codex daemon 的 appliedFingerprint 同
+ * 思想 (daemon env/config 一致性必须是持久事实, 不能靠进程内存集合):
+ * cc 的注入虽是 per-query startParams, 但「这条 query 是用哪一代 MCP 配置
+ * 建的」同样是跨重启必须可判的事实 — collab 开→关 + app 重启后, 进程内
+ * stale 集合清空, 没有它 factory 会 attach 回带旧 collab URL 的 query
+ * (codex-connector R23 P2)。
+ *
+ * 成分:token|bridgeInstanceId|remotePort (注入代际);无注入代际用常量
+ * 'disabled' (collab 禁用 / 白名单为空) — 不含 instanceId, 避免「collab
+ * 一直禁用」的健康 query 在每次 bridge 重建后被误判 drift 白杀。
+ * bridge 不在 (shutdown) 时不产指纹 — 判定方跳过 (forceFresh 也无 bridge
+ * 可用, 恢复由 lazy 重建路径负责)。
+ */
+
+const CC_DISABLED_GENERATION = 'disabled';
+
+export function computeCcRemoteMcpFingerprint(opts: {
+ token: string;
+ bridgeInstanceId: string;
+ remotePort: number;
+}): string {
+ return createHash('sha256')
+ .update(`${opts.token}|${opts.bridgeInstanceId}|${opts.remotePort}`, 'utf8')
+ .digest('hex')
+ .slice(0, 12);
+}
+
+export const CC_MCP_DISABLED_FINGERPRINT = CC_DISABLED_GENERATION;
+
+type CcFreshPrefs = Record<string, string>;
+
+function ccFreshPrefsPath(): string {
+ return path.join(app.getPath('userData'), 'remote-cc-mcp-fresh.json');
+}
+
+let ccFreshPrefsCache: CcFreshPrefs | null = null;
+
+function readCcFreshPrefs(): CcFreshPrefs {
+ if (ccFreshPrefsCache) return ccFreshPrefsCache;
+ const file = ccFreshPrefsPath();
+ try {
+ if (fs.existsSync(file)) {
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown;
+ const out: CcFreshPrefs = {};
+ if (raw && typeof raw === 'object') {
+ for (const [sessionId, fp] of Object.entries(raw as Record<string, unknown>)) {
+ if (typeof fp === 'string' && fp.length > 0) out[sessionId] = fp;
+ }
+ }
+ ccFreshPrefsCache = out;
+ return out;
+ }
+ } catch {
+ // 读失败按空处理 (下次写入覆盖)。
+ }
+ ccFreshPrefsCache = {};
+ return ccFreshPrefsCache;
+}
+
+export function readCcAppliedFingerprint(sessionId: string): string | null {
+ return readCcFreshPrefs()[sessionId] ?? null;
+}
+
+export function writeCcAppliedFingerprint(sessionId: string, fingerprint: string): void {
+ const next = { ...readCcFreshPrefs(), [sessionId]: fingerprint };
+ const file = ccFreshPrefsPath();
+ 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);
+ ccFreshPrefsCache = next;
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 4c21f7877d..794e6ba720 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -119,8 +119,8 @@ import {
} from '../mcp-integrations/codexEnvironment.js';
import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.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 { buildCcRemoteHttpMcpServers, readCcAppliedFingerprint, writeCcAppliedFingerprint } from './cc-remote-mcp.js';
+import { getRemoteSessionStartEnsure, getRemoteCodexLiveTurnChecker, setRemoteCcTurnSettledHandler, setRemoteCcStaleQuery } from './remote-session-start-ensure.js';
import {
refreshRemoteCodexMcpAfterBridgeRecreate,
invalidateRemoteCcQueriesForMcpGenerationChange,
@@ -522,6 +522,7 @@ export function getMaker(): Maker {
});
// register.ts 的 turn 收口经 holder 回调:远端 CC 的 fresh 已失效且
// 无 turn 时 detach 旧 query (bridge 重建 / 端口重绑的补刀路径)。
+ setRemoteCcStaleQuery((sessionId) => staleInvalidatedCcSessions.has(sessionId));
setRemoteCcTurnSettledHandler((sessionId) => {
maybeDetachStaleRemoteCcQuery(
{
@@ -529,7 +530,7 @@ export function getMaker(): Maker {
const s = _maker?.getSession(id);
return s && s.agentKind === 'claude-code' ? s : null;
},
- hasFreshMark: (id) => forcedFreshCcBridgeSessions.has(id),
+ hasStaleMark: (id) => staleInvalidatedCcSessions.has(id),
log: desktopMakerLogger,
},
sessionId,
@@ -665,6 +666,7 @@ export function getMaker(): Maker {
let mcpCleanup: () => void = () => {};
let injectedServerCount = 0;
let mcpNeedsFreshStart = false;
+ let mcpInjectFingerprint: string | undefined;
try {
const injected = await buildCcRemoteHttpMcpServers(
{
@@ -683,6 +685,7 @@ export function getMaker(): Maker {
);
mcpCleanup = injected.cleanup;
mcpNeedsFreshStart = injected.needsFreshStart === true;
+ mcpInjectFingerprint = injected.fingerprint;
if (Object.keys(injected.servers).length > 0) {
injectedServerCount = Object.keys(injected.servers).length;
const mutableParams = startParams as { mcpServers?: Record<string, unknown> };
@@ -709,8 +712,16 @@ export function getMaker(): Maker {
// 被 invalidate 过 (staleInvalidatedCcSessions) 也一样:collab 禁用
// 等场景重建时无 server 可注, 不 forceFresh 会 attach 回带旧 collab
// URL 的 query (codex-connector R22 P2)。
+ // 持久代际指纹 drift (codex-connector R23 P2):collab 开→关 /
+ // token 轮换 / bridge 代际 / 端口重绑后跨 app 重启, 进程内集合
+ // 清空也能判出存活 query 的 MCP 配置属旧代际。
+ const ccAppliedFingerprint = readCcAppliedFingerprint(sessionId);
+ const ccGenerationDrift =
+ mcpInjectFingerprint !== undefined &&
+ ccAppliedFingerprint !== null &&
+ mcpInjectFingerprint !== ccAppliedFingerprint;
const forceFreshQuery =
- (injectedServerCount > 0 || mcpNeedsFreshStart || staleInvalidatedCcSessions.has(sessionId)) &&
+ (injectedServerCount > 0 || mcpNeedsFreshStart || staleInvalidatedCcSessions.has(sessionId) || ccGenerationDrift) &&
!forcedFreshCcBridgeSessions.has(sessionId);
// 协同 MCP 已 mutate 进 startParams.mcpServers;这里再把 proxy env 合入
@@ -748,6 +759,11 @@ export function getMaker(): Maker {
forcedFreshCcBridgeSessions.add(sessionId);
staleInvalidatedCcSessions.delete(sessionId);
}
+ // 注入/禁用代际随 open 成功落盘 (attach 也算 — 它确认了该 query
+ // 的 MCP 代际);下次 open 前据此判 drift。
+ if (mcpInjectFingerprint) {
+ writeCcAppliedFingerprint(sessionId, mcpInjectFingerprint);
+ }
// 把 ssh transport disposer 串进 remoteQuery.close — maker-core 不知道
// ssh / RpcClient / nc 这层 transport, 只会调它认得的 Query.close()。
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.ts
index 458a9735c8..a2600b025c 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
@@ -103,20 +103,23 @@ export function invalidateRemoteCcQueriesForMcpGenerationChange(
export interface RemoteCcTurnSettledDeps {
getSession: (sessionId: string) => RemoteCcSessionLike | null;
- /** 该 session 的 fresh 标记是否仍有效 (无效 = 代际已变 / 本进程未 fresh)。 */
- hasFreshMark: (sessionId: string) => boolean;
+ /** 该 session 是否被显式 invalidate 过 (staleInvalidatedCcSessions 成员)。 */
+ hasStaleMark: (sessionId: string) => boolean;
log: { warn: (msg: string, meta?: Record<string, unknown>) => void };
}
/**
- * turn 收口时对远端 CC session 的补偿判定:fresh 标记已失效 (bridge 重建 /
- * 端口重绑时已删) 且当前无 turn → detach,让下次 send 走 factory 重新注入
- * 并 forceFresh (kill 已 idle 的旧 query);标记有效则 no-op。
+ * turn 收口时对远端 CC session 的补偿判定:仅当被显式 invalidate 过
+ * (bridge 重建 / 端口重绑 / bridge shutdown 时记 stale) 且当前无 turn 才
+ * detach,让下次 send 走 factory 重新注入并 forceFresh。
+ * 不得按「无 fresh 标记」判定 (codex-connector R23 P2):collab 禁用 /
+ * bridge 不可用的健康 session 从未 fresh 过, 每个 turn 结束都拆它们的
+ * idle query 会制造无谓的 lazy-resume 竞态。
*/
export function maybeDetachStaleRemoteCcQuery(deps: RemoteCcTurnSettledDeps, sessionId: string): void {
const s = deps.getSession(sessionId);
if (!s || !s.remoteHostId) return;
- if (deps.hasFreshMark(sessionId)) return;
+ if (!deps.hasStaleMark(sessionId)) return;
if (s.isTurnRunning()) return;
void s.detach().catch((err) => {
deps.log.warn('remote CC stale query detach on turn settled failed', {
diff --git a/apps/desktop/src/main/maker-host/remote-session-start-ensure.ts b/apps/desktop/src/main/maker-host/remote-session-start-ensure.ts
index 52c91acee9..4c403e9e5d 100644
--- a/apps/desktop/src/main/maker-host/remote-session-start-ensure.ts
+++ b/apps/desktop/src/main/maker-host/remote-session-start-ensure.ts
@@ -61,3 +61,22 @@ export function setRemoteCcTurnSettledHandler(fn: RemoteCcTurnSettledHandler): v
export function getRemoteCcTurnSettledHandler(): RemoteCcTurnSettledHandler | null {
return ccTurnSettledHandler;
}
+
+/**
+ * 远端 CC session 是否被显式 invalidate (staleInvalidatedCcSessions 成员,
+ * maker-host 装配)。live SEND 路径在直发前查询:命中必须先 detach 走
+ * lazy-resume (forceFresh), 否则 invalidate 的 fire-and-forget detach 与
+ * 用户立即发送形成竞态 — 消息会进带旧 MCP URL 的活跃 query
+ * (codex-connector R23 P2)。
+ */
+export type RemoteCcStaleQuery = (sessionId: string) => boolean;
+
+let ccStaleQuery: RemoteCcStaleQuery | null = null;
+
+export function setRemoteCcStaleQuery(fn: RemoteCcStaleQuery): void {
+ ccStaleQuery = fn;
+}
+
+export function getRemoteCcStaleQuery(): RemoteCcStaleQuery | null {
+ return ccStaleQuery;
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 6c2894e04a..acc3a237db 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -1721,3 +1721,43 @@ describe('SSH remote worker model/provider compatibility gate (R23 P2)', () => {
).resolves.toMatchObject({ ok: true });
});
});
+
+ it('rejects chat-bridged providers resolved through the default route (no explicit providerId)', async () => {
+ // R23 P2 回归:resolved.providerId 为 null (默认路由) 时, 兼容闸必须
+ // 仍按 budgetRouteProviderId 解析出的实际落点判定 — 只查显式选择会漏。
+ const { service } = createDeps({
+ getLeadSessionRow: vi.fn(async () => ({
+ id: 'lead-1',
+ agentKind: 'codex' as const,
+ workingDir: '/srv/repo',
+ model: 'gpt-5.5',
+ effort: 'medium',
+ permissionMode: 'default',
+ fastMode: false,
+ providerId: 'deepseek',
+ remoteHostId: 'remote-host-1',
+ })),
+ getAvailableModels: vi.fn(() => [
+ { id: 'deepseek-v4', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high', supportsFastMode: true },
+ ]),
+ getProviderRoutingContext: vi.fn(async () => providerRoutingContext({
+ 'claude-code': [],
+ codex: [{ id: 'deepseek', name: 'DeepSeek', models: ['deepseek-v4'], chatBridgedCodex: true }],
+ })),
+ });
+
+ await expect(
+ service.createWorker({
+ leadSessionId: 'lead-1',
+ role: 'reviewer',
+ agent: 'codex',
+ label: 'reviewer',
+ model: 'deepseek-v4',
+ // 不传 providerId — 走默认路由解析到 deepseek (chatBridged)。
+ }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_PARAMS',
+ message: expect.stringContaining('not available for SSH remote workers'),
+ });
+ });
diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index cd1788e656..ad8f1c0842 100644
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@ -653,8 +653,12 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
'subscription-direct models require the local proxy path — pick an SSH-compatible model',
};
}
- const remoteRouteProvider = resolved.providerId !== null
- ? agentProviders.find((candidate) => candidate.id === resolved.providerId)
+ // 默认路由 (resolved.providerId=null) 同样要闸:budgetRouteProviderId
+ // 已按显式来源 → 模型默认路由 → 缓存兜底顺序解析出实际落点
+ // (codex-connector R23 P2), 不能只查显式选择。
+ const remoteRouteProviderId = resolved.providerId ?? budgetRouteProviderId;
+ const remoteRouteProvider = remoteRouteProviderId !== null
+ ? agentProviders.find((candidate) => candidate.id === remoteRouteProviderId)
: undefined;
if (remoteRouteProvider?.chatBridgedCodex === true) {
return {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2b4c499372..e643f50b08 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -167,7 +167,7 @@ import { t } from '../i18n.js';
import { createLogger } from '../logger.js';
import { desktopClaudeAuthAdapter, desktopCodexAuthAdapter, readClaudeApiKey } from '../maker-host/auth-adapters.js';
import { prepareSharedProjectSkillLinks } from '../maker-host/shared-global-skills.js';
-import { setRemoteCodexLiveTurnChecker, setRemoteSessionStartEnsure, getRemoteCcTurnSettledHandler } from '../maker-host/remote-session-start-ensure.js';
+import { setRemoteCodexLiveTurnChecker, setRemoteSessionStartEnsure, getRemoteCcTurnSettledHandler, getRemoteCcStaleQuery } from '../maker-host/remote-session-start-ensure.js';
import { syncExternalCodexSessionFromDesktop } from '../maker-host/codex-local-sessions.js';
import { getCodexProxyAuthInjection, getCodexProxyAuthInjectionState } from '../maker-host/codex-proxy-host.js';
import {
@@ -5156,7 +5156,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await runAcceptedCallback(onAccepted, targetSessionId, clientId);
};
- const live = maker.getSession(targetSessionId);
+ let live = maker.getSession(targetSessionId);
if (live) {
if (live.isTurnRunning?.()) {
await enqueueSendToSessionMessage({
@@ -5197,6 +5197,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
) {
await ensureRemoteReadyForSessionStart({ session: live });
}
+ // 远端 CC 的 invalidate 竞态 (codex-connector R23 P2):invalidate
+ // (bridge 重建 / 端口重绑 / shutdown) 的 detach 是 fire-and-forget,
+ // session 在 detach 完成前仍 active — 此时直发会进带旧 MCP URL 的
+ // query。stale 命中时先同步 detach 再落 lazy-resume (forceFresh)。
+ if (
+ live.remoteHostId &&
+ live.agentKind === 'claude-code' &&
+ getRemoteCcStaleQuery()?.(live.id) === true
+ ) {
+ try {
+ await live.detach();
+ } catch (err) {
+ log.warn('sendToSession: detach stale remote CC session failed, falling through to lazy-resume', {
+ targetSessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ }
+ // detach 后不得继续 live 直发 (session 已 closed) — 置空落入
+ // 下方 lazy-resume (bootstrap 重建 → factory forceFresh)。
+ live = undefined;
+ }
+ }
+ if (live) {
try {
const sendResult = await sendUserMessageWithAwaitedGitBaseline(
live,