Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 远程控制会话补齐 Claude Code ↔ Codex 引擎切换 (#1298)
Chris Zhangcb04e2e003ae
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex 1ac820e252..7783dce078 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -27,6 +27,7 @@ vi.mock('../voice-input/index.js', () => ({}));import {+ markRemoteSettingPersistedInsideHandler,runInvoke,setRemoteWorkingDirGuard,setRemoteSettingsPersist,@@ -2091,6 +2092,36 @@ describe('远程 set-* 持久化回流', () => {});});+ it('set-model handler 返回 superseded 时不持久化过期 model/provider', async () => {+ const persist = vi.fn();+ setRemoteSettingsPersist(persist);+ registry.register('maker:set-model', () => ({ deferred: false, superseded: true }));++ const r = await runInvoke('ctrl-a', {+ channel: 'maker:set-model',+ args: ['sess-1', 'stale-model', 'stale-provider', 7],+ });++ expect(r).toEqual({ ok: true, result: { deferred: false, superseded: true } });+ expect(persist).not.toHaveBeenCalled();+ });++ it('set-model handler 已在 session 锁内持久化时 dispatch 不重复回流', async () => {+ const persist = vi.fn();+ setRemoteSettingsPersist(persist);+ const handlerResult = { deferred: false, superseded: false };+ markRemoteSettingPersistedInsideHandler(handlerResult);+ registry.register('maker:set-model', () => handlerResult);++ const r = await runInvoke('ctrl-a', {+ channel: 'maker:set-model',+ args: ['sess-1', 'claude-x', 'anthropic'],+ });++ expect(r).toEqual({ ok: true, result: handlerResult });+ expect(persist).not.toHaveBeenCalled();+ });+it('set-fast-mode → {fastMode}', async () => {const persist = vi.fn();setRemoteSettingsPersist(persist);diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 19b011bd39..a9fd0018cb 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -388,11 +388,53 @@ describe('sendToSession ordering', () => {expect(setModelBlock).toContain('return withSendToSessionLock(sessionId, async () => {',);+ expect(setModelBlock).toContain(+ 'agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',+ );+ expect(setModelBlock).toContain('return { deferred: false, superseded: true };');expectOrder(setModelBlock,'return withSendToSessionLock(sessionId, async () => {',+ 'agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',+ );+ expectOrder(+ setModelBlock,+ 'agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',+ 'applySetModelThenCancelAgentSwitchIntent(',+ );+ expect(setModelBlock).toContain('if (isDeviceLinkInvoke()) {');+ expect(setModelBlock).toContain('if (atomicSelection) {');+ expect(setModelBlock).toContain('setSessionEffort(sessionId, atomicSelection.effort);');+ expect(setModelBlock).toContain('setSessionFastMode(sessionId, atomicSelection.fastMode);');+ expect(setModelBlock).toContain('await sess.setEffort(');+ expect(setModelBlock).toContain('await sess.setFastMode(atomicSelection.fastMode);');+ expect(setModelBlock).toContain('if (isDeviceLinkInvoke() || atomicSelection) {');+ expect(setModelBlock).toContain('patch.effort = atomicSelection.effort;');+ expect(setModelBlock).toContain('patch.fastMode = atomicSelection.fastMode;');+ expect(setModelBlock).toContain('await persistSessionFields(sessionId, patch);');+ expect(setModelBlock).toContain('markRemoteSettingPersistedInsideHandler(response);');+ expectOrder(+ setModelBlock,'applySetModelThenCancelAgentSwitchIntent(',+ 'setSessionEffort(sessionId, atomicSelection.effort);',+ );+ expectOrder(+ setModelBlock,+ 'setSessionFastMode(sessionId, atomicSelection.fastMode);',+ 'await persistSessionFields(sessionId, patch);',+ );+ expectOrder(+ setModelBlock,+ 'await persistSessionFields(sessionId, patch);',+ 'return response;',+ );+ expect(preloadSource).toContain('selection?: { effort: string; fastMode: boolean },');+ expectOrder(+ preloadSource,+ 'expectedAgentSwitchRevision,',+ 'selection,',);+ expect(source).toContain('withSessionLock: withSendToSessionLock,');expect(directSendSwitchBlock).toContain('const release = await acquireSendToSessionLock(sessionId);');expectOrder(directSendSwitchBlock,diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex db5c29afe6..f86b26fd76 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -220,10 +220,11 @@ function extractGuardedPath(args: unknown[], field: 'workingDir' | 'baseRepo'):}/**- * 远程 set-* 成功后回流持久化(register.ts 在 maker 就绪后注入)。被控端 set-* 是- * runtime-only,这里补一次写被控端 DB + 广播 sessions:patched,使控制端镜像收敛到被控端真相- * (取代控制端乐观覆盖)。调用方会等待注入函数完成后才回 invoke-result,让控制端只在被控端- * DB 已确认持久化后继续同步新聊天草稿默认值。+ * 远程 set-* 成功后回流持久化(register.ts 在 maker 就绪后注入)。被控端大多数+ * set-* 是 runtime-only,这里补一次写被控端 DB + 广播 sessions:patched。SET_MODEL+ * 生产 handler 为了与队列 drain 原子化,会在 session 锁内先持久化并标记结果,+ * 这里只保留给最小/旧 handler 的兼容回流。调用方会等待持久化完成后才回+ * invoke-result,让控制端只在被控端 DB 已确认后同步新聊天草稿默认值。*/type RemoteSettingsPersist = (sessionId: string,@@ -232,6 +233,15 @@ type RemoteSettingsPersist = (let settingsPersist: RemoteSettingsPersist | null = null;+// SET_MODEL 需要把 runtime + DB 持久化放在同一把 session 锁内。handler 会在锁内+// 完成持久化后标记返回对象;dispatch 仍保留通用回流逻辑给其它 set-* 和+// 最小/旧 handler,但不得对已原子持久化的结果再写一次。WeakSet 标记不进 wire。+const settingsPersistedInsideHandler = new WeakSet<object>();++export function markRemoteSettingPersistedInsideHandler(result: object): void {+ settingsPersistedInsideHandler.add(result);+}+export function setRemoteSettingsPersist(fn: RemoteSettingsPersist | null): void {settingsPersist = fn;}@@ -249,6 +259,13 @@ const SET_CHANNEL_FIELD: Record<string, 'model' | 'effort' | 'permissionMode' |async function persistRemoteSetting(channel: string, args: unknown[], result: unknown): Promise<void> {const field = SET_CHANNEL_FIELD[channel];if (!field || !settingsPersist) return;+ if (+ result !== null &&+ typeof result === 'object' &&+ settingsPersistedInsideHandler.has(result)+ ) {+ return;+ }const sessionId = args[0];if (typeof sessionId !== 'string') return;// extraDirs 特例:set-extra-dirs handler 会按被控端 workingDir 校验、只应用 validation.valid,@@ -265,6 +282,17 @@ async function persistRemoteSetting(channel: string, args: unknown[], result: un// (G2)。与被控端 handler 同语义:args[2]===undefined(老 2 参调用)不动 provider_id;string→写;// null/''→清除(回落默认路由)。写进 DB 后 mapper 自动带进 sessions:patched → 回流控制端镜像。if (channel === 'maker:set-model') {+ // 同引擎重选的第二段带 host revision CAS。handler 返回 superseded 表示+ // 另一控制端已在两段之间更新过意图:runtime 未应用,DB 也必须同样不落+ // 这次请求参数,否则 sessions:patched 会把过期选择反向盖回控制端。+ if (+ result !== null &&+ typeof result === 'object' &&+ !Array.isArray(result) &&+ (result as { superseded?: unknown }).superseded === true+ ) {+ return;+ }const patch: Record<string, unknown> = { model: args[1] };if (args.length > 2) {patch.providerId = normalizeSessionProviderId(typeof args[2] === 'string' ? args[2] : null);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex a3acae4b14..98f21c4697 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';import {applyPendingAgentSwitchIfIdle,applySetModelThenCancelAgentSwitchIntent,+ createPendingAgentSwitchRegistry,performSessionAgentSwitch,registerMakerSessionAgentSwitchHandler,type AgentSwitchSessionRow,@@ -182,6 +183,79 @@ describe('performSessionAgentSwitch', () => {expect(calls).toEqual([]);});+ it('同引擎 no-op 通过真实 registry CAS 清意图并返回因果修订号', async () => {+ const pendingSwitches = createPendingAgentSwitchRegistry();+ pendingSwitches.set('s1', {+ targetAgentKind: 'codex',+ model: 'gpt-5.5',+ providerId: null,+ });+ const onPendingSwitchChanged = vi.fn();+ const { deps } = makeDeps({ pendingSwitches, onPendingSwitchChanged });++ const result = await performSessionAgentSwitch(deps, {+ ...validParams,+ targetAgentKind: 'claude-code',+ model: 'claude-sonnet-5',+ });++ expect(result).toMatchObject({+ switched: false,+ sameEngineRevision: 2,+ });+ expect(pendingSwitches.get('s1')).toBeUndefined();+ expect(pendingSwitches.revision?.('s1')).toBe(2);+ expect(onPendingSwitchChanged).toHaveBeenCalledWith('s1', null);+ });++ it('回归:同引擎 no-op 在 await 期间被外部 set→clear ABA 超车时不再应用旧选择', async () => {+ const pendingSwitches = createPendingAgentSwitchRegistry();+ pendingSwitches.set('s1', {+ targetAgentKind: 'codex',+ model: 'gpt-5.5',+ providerId: null,+ });+ let releaseRouteCheck!: () => void;+ let routeCheckStarted!: () => void;+ const routeCheckGate = new Promise<void>((resolve) => {+ releaseRouteCheck = resolve;+ });+ const routeCheckEntered = new Promise<void>((resolve) => {+ routeCheckStarted = resolve;+ });+ const onPendingSwitchChanged = vi.fn();+ const { deps } = makeDeps({+ pendingSwitches,+ onPendingSwitchChanged,+ assertModelRouteUsable: vi.fn(async () => {+ routeCheckStarted();+ await routeCheckGate;+ return undefined;+ }),+ });++ const request = performSessionAgentSwitch(deps, {+ ...validParams,+ targetAgentKind: 'claude-code',+ model: 'claude-sonnet-5',+ });+ await routeCheckEntered;+ pendingSwitches.set('s1', {+ targetAgentKind: 'codex',+ model: 'gpt-5.5-codex',+ providerId: 'openai',+ });+ pendingSwitches.clear('s1');+ releaseRouteCheck();++ await expect(request).resolves.toMatchObject({+ switched: false,+ sameEngineSuperseded: true,+ });+ expect(pendingSwitches.revision?.('s1')).toBe(3);+ expect(onPendingSwitchChanged).not.toHaveBeenCalled();+ });+it('turn 进行中抛 SESSION_RUNNING,不触碰任何状态', async () => {const { deps, calls } = makeDeps({getLiveSession: vi.fn(() => ({ isTurnRunning: () => true })),@@ -404,6 +478,31 @@ describe('deferred switch (turn running)', () => {await expect(ipc.invoke(MAKER_INVOKE.GET_SESSION_AGENT_SWITCH_INTENT, '')).rejects.toThrow(/INVALID_PARAMS/);});+ it('IPC 切换与 send / SET_MODEL 共用 session 锁', async () => {+ const withSessionLockSpy = vi.fn();+ const withSessionLock: NonNullable<MakerSessionAgentSwitchHandlerDeps['withSessionLock']> =+ async <T>(sessionId: string, task: () => Promise<T>): Promise<T> => {+ withSessionLockSpy(sessionId, task);+ return task();+ };+ const { deps } = makeDeps({ withSessionLock });+ const ipc = new IpcHarness();+ registerMakerSessionAgentSwitchHandler(ipc, deps);++ await ipc.invoke(+ MAKER_INVOKE.SWITCH_SESSION_AGENT,+ 's1',+ 'claude-code',+ 'claude-sonnet-5',+ null,+ undefined,+ undefined,+ );++ expect(withSessionLockSpy).toHaveBeenCalledTimes(1);+ expect(withSessionLockSpy).toHaveBeenCalledWith('s1', expect.any(Function));+ });+it('applyPendingAgentSwitchIfIdle:直发路径可要求切换后同步 bootstrap', async () => {const { deps, store } = makeDepsWithPending();store.set('s1', {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 7707e46a48..7117c4c217 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -442,6 +442,7 @@ import {import {getSessionProvider,hydrateSessionProvider,+ normalizeSessionProviderId,setSessionProvider,} from '../maker-host/session-provider-store.js';import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';@@ -533,6 +534,7 @@ import { resolveClearSessionBoundary } from './clearSessionBoundary.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import { setBusyProbe as setDeviceLinkBusyProbe } from '../device-link/index.js';import {+ markRemoteSettingPersistedInsideHandler,setRemoteWorkingDirGuard as setDeviceLinkRemoteWorkingDirGuard,setRemoteSettingsPersist as setDeviceLinkRemoteSettingsPersist,} from '../device-link/dispatch.js';@@ -3927,10 +3929,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 必须是本机当前可访问的目录,挡掉控制端用任意路径越权起进程或执行 git。setDeviceLinkRemoteWorkingDirGuard(checkRemoteWorkingDir);- // device-link 远程 set-* 持久化回流:控制端远程切 model/effort/permission/fastMode/extraDirs- // 时,被控端 set-* 只改运行时不落库;这里注入「写被控端 DB + 广播 patched」,让控制端镜像- // 收敛到被控端真相(取代控制端乐观覆盖)。必须 await DB 写入后才回 invoke-result,否则控制端会- // 过早同步新聊天草稿默认值,与被控端未来 resume 的真实 row 脱节。+ // device-link 远程 set-* 持久化回流:effort/permission/fastMode/extraDirs 等+ // runtime-only handler 经这个注入写被控端 DB + 广播 patched。SET_MODEL 是例外:+ // 它必须在自己的 session 锁内直接调 persistSessionFields,防队列 drain 夹在+ // runtime 切换与 DB 落盘之间。两条路径都必须 await 持久化后才回 invoke-result。setDeviceLinkRemoteSettingsPersist(async (sessionId, patch) => {try {await persistSessionFields(sessionId, patch);@@ -4102,6 +4104,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// host 级 optional 能力;旧 desktop 缺省为 false。两个 agent 查询都带回,// 手机读取当前 agent 快照即可决定是否展示切换入口。supportsSessionAgentSwitch: true,+ // v2 因果能力:同引擎 no-op 返回 revision,后续 SET_MODEL 在 session 锁内 CAS。+ // 新 desktop 控制端据此与只有基础切换能力的旧 host 做安全兼容门控。+ supportsSessionAgentSwitchCas: true,};});@@ -5314,6 +5319,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)model: sessions.model,sdkSessionId: sessions.sdkSessionId,providerId: sessions.providerId,+ effort: sessions.effort,+ fastMode: sessions.fastMode,}).from(sessions).where(eq(sessions.id, sessionId))@@ -5328,19 +5335,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});co.agentKind = dbMakerKind;}- // 意图制切换下,renderer 的 createOpts 快照构建于 send 事务内 apply 之前- // (乐观翻转后 agentKind 可能已一致,但 model/resume/providerId 仍是旧值,+ // 意图制切换 / 凭证形态切换下,renderer 与排队项的 createOpts 快照构建于 send+ // 事务内 apply 之前。agentKind 可能已一致,但 model/resume/providerId/effort/fast+ // 仍是旧值;// 尤其 resumeSessionId 可能是**旧引擎**的原生会话 id——resume 会以错误引擎- // 解释它)。lazy-create 时刻 DB 行是唯一真源,三个字段无条件对齐。+ // 解释它)。lazy-create 时刻 DB 行是唯一真源,执行字段无条件对齐。co.model = row.model ?? undefined;co.resumeSessionId = row.sdkSessionId ?? undefined;co.providerId = row.providerId ?? undefined;+ co.effort = (row.effort ?? undefined) as CreateOpts['effort'];+ co.fastMode = !!row.fastMode;} catch {// 校正读库失败按原 opts 继续(与切换功能上线前行为一致)。}}const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = {+ withSessionLock: withSendToSessionLock,// 停用轴边界裁决:目标路由被停用 → 抛错;隐式默认落点被停用 → 返回启用替代来源。assertModelRouteUsable: (agent, model, providerId) =>assertModelRouteUsable(agent, model, providerId),@@ -8915,7 +8926,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// session 不存在(被 close / 还没 send 创建出来)就 no-op 不报错, 让 renderer// 可以乐观调用 (UI 更新先行, IPC 失败也不会回滚 UI, 老 agentManager 同语义)。- ipcMain.handle(MAKER_INVOKE.SET_MODEL, async (_e, sessionId: unknown, model: unknown, providerId?: unknown) => {+ ipcMain.handle(MAKER_INVOKE.SET_MODEL, async (+ _e,+ sessionId: unknown,+ model: unknown,+ providerId?: unknown,+ expectedAgentSwitchRevision?: unknown,+ selection?: unknown,+ ) => {if (typeof sessionId !== 'string' || typeof model !== 'string') {throwIpcError('INVALID_PARAMS', 'sessionId + model required');}@@ -8926,10 +8944,41 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)) {throwIpcError('INVALID_PARAMS', 'providerId must be string, null, or undefined');}+ if (+ expectedAgentSwitchRevision !== undefined &&+ (typeof expectedAgentSwitchRevision !== 'number' ||+ !Number.isSafeInteger(expectedAgentSwitchRevision) ||+ expectedAgentSwitchRevision < 0)+ ) {+ throwIpcError('INVALID_PARAMS', 'expectedAgentSwitchRevision must be a non-negative integer');+ }+ if (+ selection !== undefined &&+ (+ selection === null ||+ typeof selection !== 'object' ||+ Array.isArray(selection) ||+ typeof (selection as { effort?: unknown }).effort !== 'string' ||+ typeof (selection as { fastMode?: unknown }).fastMode !== 'boolean'+ )+ ) {+ throwIpcError('INVALID_PARAMS', 'selection must contain effort + fastMode');+ }+ const atomicSelection = selection as+ | { effort: string; fastMode: boolean }+ | undefined;// 与 send 事务共用 session 锁:发送时刻执行的跨引擎切换必须先落定,// 后到的 SET_MODEL 才能写 route。否则切换 DB await 恢复后会用旧 provider// 覆盖用户刚选的新 route,形成 DB 与进程内路由分叉。return withSendToSessionLock(sessionId, async () => {+ // 同引擎重选是 switch ack 后的第二段写入。另一控制端若在两段之间更新(含+ // set→clear ABA),修订号已变化:旧 SET_MODEL 必须在任何 route/DB 副作用前让位。+ if (+ typeof expectedAgentSwitchRevision === 'number' &&+ agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision+ ) {+ return { deferred: false, superseded: true };+ }// 停用轴准入(PR #744 review;第十二轮移入锁内):切换模型是一次新的路由选择,// 不得切到用户停用的模型 / 来源(本机选择器已过滤,但本 channel 在 device-link// allowlist 内,老控制端可直接点名)。裁决必须在拿到会话锁**之后**执行 ——@@ -8976,7 +9025,56 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions));// deferred = 会话自己在跑,选择已登记、turn 结束自动生效。renderer 据此提示// "任务结束后生效"而不是当成已即时切换。- return { deferred: result.status === 'deferred' };+ const response = { deferred: result.status === 'deferred', superseded: false };+ if (atomicSelection) {+ // model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。+ // applyRuntimeSetModelChange 可能 close + wake;若 effort/fast 留给 renderer+ // 后续独立调用,queue drain 会用新 model + 旧偏好重建,跨控制端时还会发生+ // 旧请求尾写覆盖新选择。+ setSessionEffort(sessionId, atomicSelection.effort);+ setSessionFastMode(sessionId, atomicSelection.fastMode);+ const sess = maker.getSession(sessionId);+ if (+ sess &&+ result.status !== 'deferred' &&+ !pendingCredentialSwitchHolder?.has(sessionId)+ ) {+ await sess.setEffort(+ atomicSelection.effort as+ | 'minimal'+ | 'low'+ | 'medium'+ | 'high'+ | 'xhigh'+ | 'max'+ | 'ultra',+ );+ if (sess.agentKind === 'codex') {+ await sess.setFastMode(atomicSelection.fastMode);+ }+ }+ }+ if (isDeviceLinkInvoke() || atomicSelection) {+ // device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;+ // 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的+ // 新调用都由 host 在解锁前一次落定全部字段。+ const patch: Record<string, unknown> = { model };+ if (effectiveProviderId !== undefined) {+ patch.providerId = normalizeSessionProviderId(+ typeof effectiveProviderId === 'string' ? effectiveProviderId : null,+ );+ }+ if (atomicSelection) {+ patch.effort = atomicSelection.effort;+ patch.fastMode = atomicSelection.fastMode;+ }+ await persistSessionFields(sessionId, patch);+ if (isDeviceLinkInvoke()) {+ // dispatch 继续兼容最小/旧 handler 的锁外回流;标记本结果避免重复写。+ markRemoteSettingPersistedInsideHandler(response);+ }+ }+ return response;} catch (err) {if (err instanceof CredentialModeSwitchBusyError) {// 兜底(正常路径 busy 已转 deferred):切模型撞上凭证切换忙,独立 code,diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex bee4b7eacf..87a8400c88 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -99,6 +99,8 @@ export interface AgentSwitchSessionRow {}export interface MakerSessionAgentSwitchHandlerDeps {+ /** 与 send / SET_MODEL 共用的 session 锁;生产注入,最小测试 harness 可省略。 */+ withSessionLock?<T>(sessionId: string, task: () => Promise<T>): Promise<T>;/*** 停用轴的边界裁决(生产 = register.ts 的 assertModelRouteUsable,内核纯逻辑在* model-route-guard.ts)。跨引擎切换是新的路由选择,目标 (agent, model, 来源) 被@@ -212,6 +214,13 @@ export interface SessionAgentSwitchResult {deferred?: boolean;/** resume 回落的原子事务失败,保留切换意图供下一条消息重试恢复尾段。 */retryPending?: boolean;+ /**+ * 同引擎 no-op 成功清除意图后的 host 修订号。renderer 后续 SET_MODEL 必须带回+ * 该值做 CAS,防止另一控制端的更新在 ack 往返期间被旧选择覆盖。+ */+ sameEngineRevision?: number;+ /** 同引擎请求已被更晚的意图写入/撤销超车,renderer 必须丢弃旧选择。 */+ sameEngineSuperseded?: boolean;}/** 登记的切换意图(下一条消息发送时刻执行;effort/fastMode 由 renderer 按目标引擎解析好带入)。 */@@ -253,6 +262,10 @@ export interface PendingAgentSwitchRegistry {set(sessionId: string, intent: PendingAgentSwitchIntent): void;get(sessionId: string): PendingAgentSwitchIntent | undefined;clear(sessionId: string): void;+ /** session 级单调修订号;set / clear(含 ABA)都会推进。 */+ revision?(sessionId: string): number;+ /** 修订号仍匹配才清除,成功返回清除后的新修订号,否则返回 null。 */+ clearIfRevision?(sessionId: string, expectedRevision: number): number | null;}/** 将 main 内部 intent 收窄成可跨 IPC / device-link 暴露的只读投影。 */@@ -271,10 +284,28 @@ export function projectPendingAgentSwitchIntent(export function createPendingAgentSwitchRegistry(): PendingAgentSwitchRegistry {const pending = new Map<string, PendingAgentSwitchIntent>();+ const revisions = new Map<string, number>();+ const bump = (sessionId: string): number => {+ const next = (revisions.get(sessionId) ?? 0) + 1;+ revisions.set(sessionId, next);+ return next;+ };return {- set: (sessionId, intent) => void pending.set(sessionId, intent),+ set: (sessionId, intent) => {+ pending.set(sessionId, intent);+ bump(sessionId);+ },get: (sessionId) => pending.get(sessionId),- clear: (sessionId) => void pending.delete(sessionId),+ clear: (sessionId) => {+ pending.delete(sessionId);+ bump(sessionId);+ },+ revision: (sessionId) => revisions.get(sessionId) ?? 0,+ clearIfRevision: (sessionId, expectedRevision) => {+ if ((revisions.get(sessionId) ?? 0) !== expectedRevision) return null;+ pending.delete(sessionId);+ return bump(sessionId);+ },};}@@ -333,6 +364,8 @@ export async function performSessionAgentSwitch(if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {throwIpcError('INVALID_PARAMS', 'providerId must be string | null');}+ // 必须在第一个 await 前快照:跨窗口 / 跨设备写入即使 set→clear 回到同值,修订号也会变化。+ const pendingRevisionAtStart = deps.pendingSwitches?.revision?.(sessionId);let normalizedProviderId =typeof providerId === 'string' ? providerId.trim() || null : providerId;@@ -367,9 +400,34 @@ export async function performSessionAgentSwitch(if (fromDbKind === toDbKind) {// 同引擎 = 纯模型切换,调用方应走 SET_MODEL;这里按 no-op 成功返回。// 顺带清 pending:用户先登记了跨引擎切换、又选回当前引擎 = 改主意取消。- deps.pendingSwitches?.clear(sessionId);+ let sameEngineRevision: number | undefined;+ if (deps.pendingSwitches?.clearIfRevision && pendingRevisionAtStart !== undefined) {+ const clearedRevision = deps.pendingSwitches.clearIfRevision(+ sessionId,+ pendingRevisionAtStart,+ );+ if (clearedRevision === null) {+ return {+ switched: false,+ agentKind: targetAgentKind,+ model,+ engineReady: true,+ sameEngineSuperseded: true,+ };+ }+ sameEngineRevision = clearedRevision;+ } else {+ // 最小测试 harness / 旧内嵌调用方没有修订能力时维持原 no-op 清除语义。+ deps.pendingSwitches?.clear(sessionId);+ }deps.onPendingSwitchChanged?.(sessionId, null);- return { switched: false, agentKind: targetAgentKind, model, engineReady: true };+ return {+ switched: false,+ agentKind: targetAgentKind,+ model,+ engineReady: true,+ ...(sameEngineRevision !== undefined ? { sameEngineRevision } : {}),+ };}// 跨引擎选择比此前登记的凭证切换更新;即使旧切换已在 await close,清掉登记后@@ -727,15 +785,19 @@ export function registerMakerSessionAgentSwitchHandler(providerId: unknown,effort: unknown,fastMode: unknown,- ) =>- performSessionAgentSwitch(deps, {+ ) => {+ const run = () => performSessionAgentSwitch(deps, {sessionId,targetAgentKind,model,providerId,effort,fastMode,- }),+ });+ return typeof sessionId === 'string' && sessionId && deps.withSessionLock+ ? deps.withSessionLock(sessionId, run)+ : run();+ },);registry.handle(MAKER_INVOKE.GET_SESSION_AGENT_SWITCH_INTENT,diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 06f6ed6c37..2d8fa98e4a 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4677,8 +4677,17 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string,model: string,providerId?: string | null,- ): Promise<{ deferred: boolean } | undefined> =>- ipcRenderer.invoke('maker:set-model', sessionId, model, providerId),+ expectedAgentSwitchRevision?: number,+ selection?: { effort: string; fastMode: boolean },+ ): Promise<{ deferred: boolean; superseded?: boolean } | undefined> =>+ ipcRenderer.invoke(+ 'maker:set-model',+ sessionId,+ model,+ providerId,+ expectedAgentSwitchRevision,+ selection,+ ),// session-agent-switch:同一会话切换 agent 引擎(claude-code ↔ codex)。// 与 setModel 的边界:同引擎换模型走 setModel,跨引擎必须走本方法。// 意图制:本调用只登记切换意图(deferred=true 为常态返回),真正的交接与@@ -4692,8 +4701,19 @@ contextBridge.exposeInMainWorld('electronAPI', {providerId?: string | null,effort?: string,fastMode?: boolean,- ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean }> =>+ ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }> =>ipcRenderer.invoke('maker:switch-session-agent', sessionId, targetAgentKind, model, providerId, effort, fastMode),+ // 读 main 权威的 pending 切换意图(内存态,不落库)。重开视图 / 远程会话重连后+ // 用它恢复乐观显示——否则用户登记的意图在 UI 上凭空消失,下一条消息却按意图切换。+ getSessionAgentSwitchIntent: (+ sessionId: string,+ ): Promise<{+ targetAgentKind: 'claude-code' | 'codex';+ model: string;+ providerId: string | null;+ effort?: string;+ fastMode?: boolean;+ } | null> => ipcRenderer.invoke('maker:get-session-agent-switch-intent', sessionId),// effort/mode 透传 string —— 合法值由 maker capabilities 在运行时校验,// preload 不重复枚举 (避免 capabilities 加新值时这里也要改)。setEffort: (sessionId: string, effort: string): Promise<void> =>diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex d36cfb2d4b..0cfb573fad 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -857,18 +857,18 @@ describe('远程交互接线不变式', () => {expect(body.slice(activeBranch, elseBranch)).not.toContain('modelMemory?.setFast');});- it('ChatInput 远程切模型先尝试静默恢复 Fast,失败仍同步已落盘 model/effort', () => {+ it('ChatInput 远程切模型优先原子提交 model/effort/fast,旧 host 才走兼容链', () => {const src = read('components/new-chat/ChatInput.tsx');const start = src.indexOf('if (sourceRemoteDeviceId) {');expect(start).toBeGreaterThan(-1);const body = src.slice(start, start + 2800);- const persist = body.indexOf(- 'const fastPersisted = await persistFastModeChange(restoredFast, {',- );+ const atomic = body.indexOf('? { effort: newEffort, fastMode: restoredFast }');+ const fallback = body.indexOf('if (!useAtomicSelection) {');+ const persist = body.indexOf('fastPersisted = await persistFastModeChange(restoredFast, {');const sync = body.indexOf('syncSessionDraftModelPrefs(');- expect(persist).toBeGreaterThan(- body.indexOf('await remoteMaker.setEffort(sessionId, newEffort);'),- );+ expect(atomic).toBeGreaterThan(-1);+ expect(fallback).toBeGreaterThan(atomic);+ expect(persist).toBeGreaterThan(body.indexOf('await remoteMaker.setEffort(sessionId, newEffort);'));expect(persist).toBeGreaterThan(-1);expect(sync).toBeGreaterThan(-1);expect(persist).toBeLessThan(sync);@@ -877,21 +877,21 @@ describe('远程交互接线不变式', () => {expect(body.slice(sync, sync + 300)).toContain('fast: fastPersisted ? restoredFast : fastMode');});- it('ChatInput 远程切来源先尝试静默恢复 Fast,失败仍同步已落盘 model/effort/provider', () => {+ it('ChatInput 远程切来源优先原子提交选择快照,旧 host 才走兼容链', () => {const src = read('components/new-chat/ChatInput.tsx');const start = src.indexOf('if (sessionId && sourceRemoteDeviceId)');const end = src.indexOf('// 把这次切换后落定的 (model, effort)', start);expect(start).toBeGreaterThan(-1);expect(end).toBeGreaterThan(start);const body = src.slice(start, end);- const persist = body.indexOf(- 'const fastPersisted = await persistFastModeChange(restoredFast, {',- );+ const atomic = body.indexOf('? { effort: targetEffort, fastMode: restoredFast }');+ const fallback = body.indexOf('if (!useAtomicSelection) {');+ const persist = body.indexOf('fastPersisted = await persistFastModeChange(restoredFast, {');const sync = body.indexOf('syncSessionDraftModelPrefs(');const finalize = body.indexOf('onModelDidChange?.(targetModel);');- expect(persist).toBeGreaterThan(- body.indexOf('await remoteMaker.setEffort(sessionId, targetEffort);'),- );+ expect(atomic).toBeGreaterThan(-1);+ expect(fallback).toBeGreaterThan(atomic);+ expect(persist).toBeGreaterThan(body.indexOf('await remoteMaker.setEffort(sessionId, targetEffort);'));expect(persist).toBeGreaterThan(-1);expect(sync).toBeGreaterThan(-1);expect(body.slice(persist, sync)).not.toContain('return;');@@ -1085,12 +1085,11 @@ describe('远程交互接线不变式', () => {const applyStart = src.indexOf('const applyModelAndEffort = async');expect(applyStart).toBeGreaterThan(-1);const applyBody = src.slice(applyStart, applyStart + 3200);- expect(applyBody).toContain(- 'handleFastModeChange(restoredFast, modelId, eff, false, newProviderId)',- );+ expect(applyBody).toContain('modelMemory?.setFast(');+ expect(applyBody).toContain('newProviderId,\n modelId,\n restoredFast,');});- it('ChatInput 本地切来源先过 main credential gate,再写 DB / UI', () => {+ it('ChatInput 本地切来源把完整选择交给 main 原子落定后再更新 UI', () => {const src = read('components/new-chat/ChatInput.tsx');const start = src.indexOf('const applyModelAndEffort = async (modelId: string, eff: Effort)');expect(start).toBeGreaterThan(-1);@@ -1100,16 +1099,16 @@ describe('远程交互接线不变式', () => {const runtimeGate = body.indexOf('const setModelResult = await window.electronAPI.maker.setModel(',);- const persist = body.indexOf('await sessionService.update(sessionId, {');+ const atomicSelection = body.indexOf('{ effort: eff, fastMode: restoredFast }');const applyUi = body.indexOf('applyProviderSelection();');expect(runtimeGate).toBeGreaterThan(-1);- expect(persist).toBeGreaterThan(-1);+ expect(atomicSelection).toBeGreaterThan(runtimeGate);expect(applyUi).toBeGreaterThan(-1);- expect(runtimeGate).toBeLessThan(persist);- expect(persist).toBeLessThan(applyUi);+ expect(atomicSelection).toBeLessThan(applyUi);+ expect(body).not.toContain('await sessionService.update(sessionId, {');});- it('ChatInput 本地只切模型先过 main credential gate,再写 DB / UI', () => {+ it('ChatInput 本地只切模型把完整选择交给 main 原子落定后再更新 UI', () => {const src = read('components/new-chat/ChatInput.tsx');const start = src.indexOf('const performModelChange = useCallback(');const end = src.indexOf('const handleModelChange = useCallback(', start);@@ -1117,15 +1116,18 @@ describe('远程交互接线不变式', () => {expect(end).toBeGreaterThan(start);const body = src.slice(start, end);const runtimeGate = body.indexOf(- 'const setModelResult = await window.electronAPI.maker.setModel(sessionId, newModelId)',+ 'const setModelResult = await window.electronAPI.maker.setModel(',+ );+ const atomicSelection = body.indexOf(+ '{ effort: newEffort, fastMode: restoredFast }',+ runtimeGate,);- const persist = body.indexOf('await sessionService.update(sessionId, {');const applyUi = body.indexOf('onModelDidChange?.(newModelId)');expect(runtimeGate).toBeGreaterThan(-1);- expect(persist).toBeGreaterThan(-1);+ expect(atomicSelection).toBeGreaterThan(runtimeGate);expect(applyUi).toBeGreaterThan(-1);- expect(runtimeGate).toBeLessThan(persist);- expect(persist).toBeLessThan(applyUi);+ expect(atomicSelection).toBeLessThan(applyUi);+ expect(body).not.toContain('await sessionService.update(sessionId, {');});// 多端收敛核心:resolve interaction 必须广播 INTERACTION_DISMISSED,否则其它 rendererdiff --git a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts b/apps/desktop/src/renderer/__tests__/makerQueueState.test.tsindex 0f3a494f75..c4b5541e37 100644--- a/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerQueueState.test.ts@@ -66,6 +66,7 @@ const userMessage = (id: string, text = id): ChatMessage => ({const state = (overrides: Partial<SessionChatState> = {}): SessionChatState => ({agentKind: 'claude-code',agentSwitchIntent: null,+ agentSwitchIntentRev: 0,remoteHostId: null,messages: [],isStreaming: false,diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.tsindex a07108d17f..c6a4a19e04 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts@@ -2035,8 +2035,9 @@ describe('ModelSelector trigger variants', () => {await act(async () => {await Promise.resolve();});- // 第一笔事务仍在途时,后一次配置只入队,不能并发覆盖。- expect(onSwitch).toHaveBeenCalledTimes(1);+ // 第一笔事务仍在途时,后一次配置也立即交给调用方;调用方会同步登记目标+ // session 的 pending token,再由 session 级协调器保证同会话顺序。+ expect(onSwitch).toHaveBeenCalledTimes(2);expect(setEffort).toHaveBeenNthCalledWith(2,'codex',@@ -2049,7 +2050,6 @@ describe('ModelSelector trigger variants', () => {releaseFirstSwitch();await firstSwitch;});- await waitFor(() => expect(onSwitch).toHaveBeenCalledTimes(2));expect(observedSwitchEfforts).toEqual(['low', 'high']);fireEvent.click(screen.getByRole('tab', { name: /Claude/ }));diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.tsnew file mode 100644index 0000000000..eb4eb4820b--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts@@ -0,0 +1,893 @@+/**+ * session-agent-switch 的 device-link 远程会话接线回归。+ *+ * 背景:同会话跨引擎切换(Claude Code ↔ Codex)的 channel 早已在 device-link allowlist 里+ * (手机版控制端在用),但桌面控制端一度把入口按 v1 限制关掉、切换 IPC 也硬打本机 maker —— 远程+ * 会话在被控端才有,打本机必失败。这里锁住三件事:+ * 1. 传输层按 session 来源路由(远程隧道 / 本机直连,args 与 preload 对齐);+ * 2. 意图镜像的归一化与幂等(权威态在会话所在端,控制端只做镜像);+ * 3. ChatInput 的入口门控不再排除 device-link,且切换走传输层。+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { Session } from '@/lib/ccAgent.types';++const sess = (id: string): Session => ({ id }) as unknown as Session;++describe('makerApiFor 的 agent 切换路由', () => {+ beforeEach(() => {+ vi.resetModules();+ });++ function stubElectron() {+ const maker = {+ switchSessionAgent: vi.fn().mockResolvedValue({ deferred: true }),+ getSessionAgentSwitchIntent: vi.fn().mockResolvedValue(null),+ };+ const invoke = vi.fn().mockResolvedValue(null);+ vi.stubGlobal('window', { electronAPI: { maker, deviceLink: { invoke } } });+ return { maker, invoke };+ }++ it('远程会话:登记 / 读回都命中被控端 channel(入参顺序与 preload 一致)', async () => {+ const { maker, invoke } = stubElectron();+ const { makerApiFor } = await import('@/lib/makerTransport');+ const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');+ remoteProjectsStore.setDeviceSessions('dev-1', 'Mac', [sess('remote-1')]);++ const api = makerApiFor('remote-1');+ await api.switchSessionAgent('remote-1', 'codex', 'gpt-5.5', 'openai', 'high', true);+ await api.getSessionAgentSwitchIntent('remote-1');++ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:switch-session-agent', [+ 'remote-1',+ 'codex',+ 'gpt-5.5',+ 'openai',+ 'high',+ true,+ ]);+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:get-session-agent-switch-intent', [+ 'remote-1',+ ]);+ // 远程会话在控制端本机不存在,绝不能打本机 maker。+ expect(maker.switchSessionAgent).not.toHaveBeenCalled();+ expect(maker.getSessionAgentSwitchIntent).not.toHaveBeenCalled();+ });++ it('本机会话:直连本机 maker,不经隧道(零回归)', async () => {+ const { maker, invoke } = stubElectron();+ const { makerApiFor } = await import('@/lib/makerTransport');++ const api = makerApiFor('local-1'); // 未注册进 remoteProjectsStore → 本机+ await api.switchSessionAgent('local-1', 'codex', 'gpt-5.5', 'openai', 'high', false);+ await api.getSessionAgentSwitchIntent('local-1');++ expect(maker.switchSessionAgent).toHaveBeenCalledWith(+ 'local-1',+ 'codex',+ 'gpt-5.5',+ 'openai',+ 'high',+ false,+ );+ expect(maker.getSessionAgentSwitchIntent).toHaveBeenCalledWith('local-1');+ expect(invoke).not.toHaveBeenCalled();+ });+});++describe('makerChatStore.mirrorAgentSwitchIntent', () => {+ // 模块级 sessions Map 跨用例持久 → 每个用例用唯一 sessionId 隔离。+ let n = 0;+ const sid = () => `agent-switch-mirror-${n++}`;++ it('wire 投影(targetAgentKind)收窄成展示记录(target),providerId 缺失按 null', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'codex',+ model: 'gpt-5.5',+ effort: 'high',+ fastMode: true,+ });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toEqual({+ target: 'codex',+ model: 'gpt-5.5',+ providerId: null,+ effort: 'high',+ fastMode: true,+ });+ // 展示槽独立:真实 reducer 路由不受影响。+ expect(makerChatStore.getSnapshot(s).agentKind).toBe('claude-code');+ });++ it('幂等:同值回声不重建快照(不与本端乐观登记打架)', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ makerChatStore.noteAgentSwitchIntent(s, 'codex', { model: 'gpt-5.5', providerId: 'openai' });+ const snap = makerChatStore.getSnapshot(s);+ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'codex',+ model: 'gpt-5.5',+ providerId: 'openai',+ });+ expect(makerChatStore.getSnapshot(s)).toBe(snap); // 引用不变 = 未触发更新+ });++ it('null / 非法值 = 无意图 → 清除', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ makerChatStore.noteAgentSwitchIntent(s, 'codex', { model: 'gpt-5.5', providerId: null });+ makerChatStore.mirrorAgentSwitchIntent(s, null);+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toBeNull();++ makerChatStore.noteAgentSwitchIntent(s, 'codex', { model: 'gpt-5.5', providerId: null });+ makerChatStore.mirrorAgentSwitchIntent(s, { targetAgentKind: 'gemini', model: 'x' });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toBeNull();+ });++ it('sessions:patched 带 agentSwitchIntent 才镜像;不带该字段的普通 patch 不得清掉意图', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ // 被控端 / 另一窗口登记 → 回流镜像进控制端展示槽。+ makerChatStore.mirrorSessionFields(s, {+ agentSwitchIntent: { targetAgentKind: 'codex', model: 'gpt-5.5', providerId: 'openai' },+ });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent?.target).toBe('codex');++ // 标题 / preview 之类的无关广播不带该字段:意图必须原样保留。+ makerChatStore.mirrorSessionFields(s, { title: 'x' } as { fastMode?: unknown });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent?.target).toBe('codex');++ // 被控端清除意图(apply 完成 / 用户撤销)→ 显式 null 才清。+ makerChatStore.mirrorSessionFields(s, { agentSwitchIntent: null });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toBeNull();+ });+});++describe('isAgentSwitchResponseFresh(远程意图读回的新鲜度守卫)', () => {+ const base = {+ cancelled: false,+ writeSeqAtStart: 3,+ writeSeqNow: 3,+ intentRevAtStart: 7,+ intentRevNow: 7,+ };++ it('在途期间无人改动 → 应用读回结果', async () => {+ const { isAgentSwitchResponseFresh } = await import('@/components/new-chat/agentSwitchConfirmation');+ expect(isAgentSwitchResponseFresh(base)).toBe(true);+ });++ it('effect 已清理(切走会话)→ 丢弃', async () => {+ const { isAgentSwitchResponseFresh } = await import('@/components/new-chat/agentSwitchConfirmation');+ expect(isAgentSwitchResponseFresh({ ...base, cancelled: true })).toBe(false);+ });++ it('本端 ABA:点选登记后又撤销 → 写序号已变,丢弃', async () => {+ const { isAgentSwitchResponseFresh } = await import('@/components/new-chat/agentSwitchConfirmation');+ expect(isAgentSwitchResponseFresh({ ...base, writeSeqNow: 5 })).toBe(false);+ });++ it('外部 ABA:另一窗口 / 被控端把意图改成非空又清回 null → 修订号已变,丢弃', async () => {+ const { isAgentSwitchResponseFresh } = await import('@/components/new-chat/agentSwitchConfirmation');+ // 外部回流不经本端点选,writeSeq 不动;值也回到发起时的 null —— 只有修订号能识别。+ expect(+ isAgentSwitchResponseFresh({ ...base, writeSeqNow: 3, intentRevNow: 9 }),+ ).toBe(false);+ });+});++describe('resolveAgentSwitchAckAction(ack 分派:两类守卫作用域不同)', () => {+ const fresh = {+ cancelled: false,+ writeSeqAtStart: 3,+ writeSeqNow: 3,+ intentRevAtStart: 7,+ intentRevNow: 7,+ };+ const load = () => import('@/components/new-chat/agentSwitchConfirmation');++ it('deferred 常态 → 登记乐观意图', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ expect(+ resolveAgentSwitchAckAction({+ deferred: true,+ switched: false,+ freshness: fresh,+ }),+ ).toBe('apply-intent');+ });++ it('回归:已有跨引擎意图 → 选回当前引擎模型 → 清除回流先到,仍须走同引擎重选', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ // 被控端处理同引擎 no-op 时会清 pending 意图并广播,回流推进修订号 —— 那是本次调用+ // 自己引起的,不是被外部超车。误判成 stale 会让用户刚选的模型不生效。+ expect(+ resolveAgentSwitchAckAction({+ deferred: false,+ switched: false,+ sameEngineRevision: 8,+ freshness: { ...fresh, intentRevNow: 9 },+ }),+ ).toBe('same-engine-reselect');+ });++ it('回归:同引擎 no-op 的 ack 先于清除回流到达 → 旧镜像仍非空也须继续重选', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ // 修订号未变证明当前非空仍是发起前的旧 intent,不是外部新登记;不能依赖 null push+ // 必须抢在 ack 前到达,否则 device-link 的响应/事件调度顺序会随机吞掉用户重选。+ expect(+ resolveAgentSwitchAckAction({+ deferred: false,+ switched: false,+ sameEngineRevision: 8,+ freshness: fresh,+ }),+ ).toBe('same-engine-reselect');+ });++ it('旧 host 无 CAS token:仅修订号未变时兼容执行,任何回流变化都 fail-closed', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ expect(+ resolveAgentSwitchAckAction({ deferred: false, switched: false, freshness: fresh }),+ ).toBe('same-engine-reselect');+ expect(+ resolveAgentSwitchAckAction({+ deferred: false,+ switched: false,+ freshness: { ...fresh, intentRevNow: 9 },+ }),+ ).toBe('discard');+ });++ it('回归:同引擎重选在途时外部登记或 ABA → host CAS 标成 superseded,一律丢弃', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ // 修订号同样变了,但回流后的内容是「有意图」——只可能来自更新的登记。继续收尾会把它+ // 抹掉,选择器退回旧引擎,而被控端下一条消息仍按新意图切换。+ expect(+ resolveAgentSwitchAckAction({+ deferred: false,+ switched: false,+ sameEngineSuperseded: true,+ freshness: { ...fresh, intentRevNow: 10 },+ }),+ ).toBe('discard');+ });++ it('用户又点了一次(写序号变)→ 所有分支一律作废,包括同引擎重选', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ for (const branch of [+ { deferred: true, switched: false },+ { deferred: false, switched: false },+ { deferred: false, switched: true },+ ]) {+ expect(+ resolveAgentSwitchAckAction({+ ...branch,+ freshness: { ...fresh, writeSeqNow: 4 },+ }),+ ).toBe('discard');+ }+ });++ it('外部权威更新抢先 → 写意图值的分支仍然丢弃(不回退 stale-ack 防护)', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ const superseded = { ...fresh, intentRevNow: 9 };+ expect(+ resolveAgentSwitchAckAction({+ deferred: true,+ switched: false,+ freshness: superseded,+ }),+ ).toBe('discard');+ expect(+ resolveAgentSwitchAckAction({+ deferred: false,+ switched: true,+ freshness: superseded,+ }),+ ).toBe('discard');+ });++ it('立即切换路径无人超车 → 收敛真实引擎', async () => {+ const { resolveAgentSwitchAckAction } = await load();+ expect(+ resolveAgentSwitchAckAction({+ deferred: false,+ switched: true,+ freshness: fresh,+ }),+ ).toBe('apply-switched');+ });+});++describe('agentSwitchCoordinator(串行链与写序号按 session,跨组件实例存活)', () => {+ const load = async () => {+ const mod = await import('@/lib/agentSwitchCoordinator');+ mod.__resetAgentSwitchCoordinatorForTests();+ return mod;+ };+ const deferred = <T,>() => {+ let resolve!: (v: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+ };++ it('同 session 串行:后一次点选必须等前一次往返结束才发出', async () => {+ const { runAgentSwitchExclusive } = await load();+ const first = deferred<string>();+ const started: string[] = [];++ const a = runAgentSwitchExclusive('s1', () => {+ started.push('a');+ return first.promise;+ });+ const b = runAgentSwitchExclusive('s1', () => {+ started.push('b');+ return Promise.resolve('b');+ });++ await Promise.resolve();+ expect(started).toEqual(['a']); // b 尚未发出+ first.resolve('a');+ await Promise.all([a, b]);+ expect(started).toEqual(['a', 'b']); // 发送顺序 = 点选顺序+ });++ it('复合操作预占整条串行位置:release 前后续点选不能插进 ack 后收尾', async () => {+ const { reserveAgentSwitchExclusive, runAgentSwitchExclusive } = await load();+ const turn = reserveAgentSwitchExclusive('s1');+ const started: string[] = [];+ await turn.ready;+ const next = runAgentSwitchExclusive('s1', () => {+ started.push('next');+ return Promise.resolve();+ });++ await Promise.resolve();+ expect(started).toEqual([]);+ turn.release();+ await next;+ expect(started).toEqual(['next']);+ turn.release(); // release 幂等。+ });++ it('不同 session 各自独立:A 的慢请求不拖住 B', async () => {+ const { runAgentSwitchExclusive } = await load();+ const slow = deferred<string>();+ const started: string[] = [];++ void runAgentSwitchExclusive('s1', () => {+ started.push('s1');+ return slow.promise;+ });+ await runAgentSwitchExclusive('s2', () => {+ started.push('s2');+ return Promise.resolve('s2');+ });++ expect(started).toEqual(['s1', 's2']);+ slow.resolve('done');+ });++ it('前一个任务失败不掐断链:后一个仍会发出', async () => {+ const { runAgentSwitchExclusive } = await load();+ const started: string[] = [];+ const failed = runAgentSwitchExclusive('s1', () => {+ started.push('a');+ return Promise.reject(new Error('tunnel down'));+ });+ await expect(failed).rejects.toThrow('tunnel down');+ await runAgentSwitchExclusive('s1', () => {+ started.push('b');+ return Promise.resolve('b');+ });+ expect(started).toEqual(['a', 'b']);+ });++ it('回归:写序号按 session 存在模块级,组件卸载重挂后不归零', async () => {+ const { nextAgentSwitchWriteSeq, getAgentSwitchWriteSeq } = await load();+ expect(nextAgentSwitchWriteSeq('s1')).toBe(1);+ expect(nextAgentSwitchWriteSeq('s1')).toBe(2);+ // 组件重挂 = 重新读取,而不是从 0 开始 —— 否则在途 ack 会被误判成新鲜。+ expect(getAgentSwitchWriteSeq('s1')).toBe(2);+ expect(getAgentSwitchWriteSeq('s2')).toBe(0); // 每个 session 独立计数+ });++ it('回归:同一 session 的队列跨「组件实例」共享,切走再切回不会分叉出并发', async () => {+ const { runAgentSwitchExclusive } = await load();+ const inFlight = deferred<string>();+ const started: string[] = [];++ // 旧组件发出请求后卸载(invoke 仍在飞)。+ void runAgentSwitchExclusive('s1', () => {+ started.push('old-mount');+ return inFlight.promise;+ });+ await Promise.resolve();+ // 新组件挂载后立即点选:必须排在在途请求之后,而不是另起一条空队列并发发送。+ const next = runAgentSwitchExclusive('s1', () => {+ started.push('new-mount');+ return Promise.resolve('ok');+ });+ await Promise.resolve();+ expect(started).toEqual(['old-mount']);+ inFlight.resolve('done');+ await next;+ expect(started).toEqual(['old-mount', 'new-mount']);+ });++ it('dispose 释放该 session 的协调状态', async () => {+ const {+ beginAgentSendDispatch,+ beginAgentSwitchOperation,+ nextAgentSwitchWriteSeq,+ getAgentSwitchWriteSeq,+ hasPendingAgentSendDispatch,+ hasPendingAgentSwitchOperation,+ disposeAgentSwitchSession,+ } = await load();+ nextAgentSwitchWriteSeq('s1');+ beginAgentSwitchOperation('s1');+ beginAgentSendDispatch('s1');+ disposeAgentSwitchSession('s1');+ expect(getAgentSwitchWriteSeq('s1')).toBe(0);+ expect(hasPendingAgentSwitchOperation('s1')).toBe(false);+ expect(hasPendingAgentSendDispatch('s1')).toBe(false);+ });++ it('完整切换 pending 按 session 计数并通知,最后一个操作完成后才放开发送', async () => {+ const {+ beginAgentSwitchOperation,+ hasPendingAgentSwitchOperation,+ subscribeAgentSwitchPending,+ } = await load();+ const notifications: boolean[] = [];+ const unsubscribe = subscribeAgentSwitchPending(() => {+ notifications.push(hasPendingAgentSwitchOperation('s1'));+ });+ const finishA = beginAgentSwitchOperation('s1');+ const finishB = beginAgentSwitchOperation('s1');+ beginAgentSwitchOperation('s2');++ expect(hasPendingAgentSwitchOperation('s1')).toBe(true);+ finishA();+ expect(hasPendingAgentSwitchOperation('s1')).toBe(true);+ finishA(); // 完成函数幂等,不误减另一个操作。+ expect(hasPendingAgentSwitchOperation('s1')).toBe(true);+ finishB();+ expect(hasPendingAgentSwitchOperation('s1')).toBe(false);+ expect(hasPendingAgentSwitchOperation('s2')).toBe(true);+ expect(notifications).toEqual([true, true, true, true, false]);+ unsubscribe();+ });++ it('完整发送 pending 按 session 计数,跨组件重挂可见且完成函数幂等', async () => {+ const { beginAgentSendDispatch, hasPendingAgentSendDispatch } = await load();+ const finishA = beginAgentSendDispatch('s1');+ const finishB = beginAgentSendDispatch('s1');++ // 新组件从同一模块级 registry 读取,不依赖旧组件实例的 ref/state。+ expect(hasPendingAgentSendDispatch('s1')).toBe(true);+ expect(hasPendingAgentSendDispatch('s2')).toBe(false);+ finishA();+ finishA();+ expect(hasPendingAgentSendDispatch('s1')).toBe(true);+ finishB();+ expect(hasPendingAgentSendDispatch('s1')).toBe(false);+ });++ it('发送检查与登记原子化:切换在途时拒绝,外层准备 token 与共享发送边界可嵌套', async () => {+ const {+ beginAgentSwitchOperation,+ hasPendingAgentSendDispatch,+ tryBeginAgentSendDispatch,+ } = await load();+ const finishSwitch = beginAgentSwitchOperation('s1');+ expect(tryBeginAgentSendDispatch('s1')).toBeNull();+ expect(hasPendingAgentSendDispatch('s1')).toBe(false);++ finishSwitch();+ const finishPreparation = tryBeginAgentSendDispatch('s1');+ const finishSharedBoundary = tryBeginAgentSendDispatch('s1');+ expect(finishPreparation).not.toBeNull();+ expect(finishSharedBoundary).not.toBeNull();+ expect(hasPendingAgentSendDispatch('s1')).toBe(true);+ finishPreparation?.();+ expect(hasPendingAgentSendDispatch('s1')).toBe(true);+ finishSharedBoundary?.();+ expect(hasPendingAgentSendDispatch('s1')).toBe(false);+ });+});++describe('makerChatStore 意图修订号(ABA 识别的真源)', () => {+ let n = 0;+ const sid = () => `agent-switch-rev-${n++}`;++ it('任何来源的实际变更都推进修订号:本端登记 / 撤销 / 外部回流镜像', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ expect(makerChatStore.getAgentSwitchIntentRev(s)).toBe(0);++ makerChatStore.noteAgentSwitchIntent(s, 'codex', { model: 'gpt-5.5', providerId: null });+ const afterNote = makerChatStore.getAgentSwitchIntentRev(s);+ expect(afterNote).toBeGreaterThan(0);++ makerChatStore.clearAgentSwitchIntent(s);+ const afterClear = makerChatStore.getAgentSwitchIntentRev(s);+ // 值回到 null(与登记前相同),修订号必须继续前进 —— 这正是 ABA 能被识别的原因。+ expect(makerChatStore.getAgentSwitchIntent(s)).toBeNull();+ expect(afterClear).toBeGreaterThan(afterNote);++ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'codex',+ model: 'gpt-5.5',+ providerId: null,+ });+ expect(makerChatStore.getAgentSwitchIntentRev(s)).toBeGreaterThan(afterClear);+ });++ it('no-op(同值镜像 / 重复清空)不推进修订号,不误伤在途读回', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ makerChatStore.noteAgentSwitchIntent(s, 'codex', { model: 'gpt-5.5', providerId: 'openai' });+ const rev = makerChatStore.getAgentSwitchIntentRev(s);+ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'codex',+ model: 'gpt-5.5',+ providerId: 'openai',+ });+ expect(makerChatStore.getAgentSwitchIntentRev(s)).toBe(rev);++ makerChatStore.clearAgentSwitchIntent(s);+ const cleared = makerChatStore.getAgentSwitchIntentRev(s);+ makerChatStore.clearAgentSwitchIntent(s);+ expect(makerChatStore.getAgentSwitchIntentRev(s)).toBe(cleared);+ });+});++describe('makerChatStore 共享发送边界', () => {+ it('切换在途时消息、UI 续跑、错误重试与压缩都 fail-closed', async () => {+ const coordinator = await import('@/lib/agentSwitchCoordinator');+ coordinator.__resetAgentSwitchCoordinatorForTests();+ const finishSwitch = coordinator.beginAgentSwitchOperation('guarded-send');+ const { makerChatStore } = await import('@/lib/makerChatStore');++ await expect(+ makerChatStore.sendMessage(+ 'guarded-send',+ 'hello',+ 'claude-sonnet-4-6',+ 'medium',+ 'default',+ '/tmp/workdir',+ ),+ ).resolves.toBe(false);+ await expect(+ makerChatStore.sendUiTrigger('guarded-send', '[UI_ACTION_TRIGGER] continue'),+ ).rejects.toThrow('Agent switch is still in progress');+ await expect(makerChatStore.retryLastError('guarded-send')).rejects.toThrow(+ 'Agent switch is still in progress',+ );+ await expect(+ makerChatStore.compactSession(+ 'guarded-send',+ 'claude-sonnet-4-6',+ 'medium',+ 'default',+ '/tmp/workdir',+ ),+ ).resolves.toBe(false);+ expect(coordinator.hasPendingAgentSendDispatch('guarded-send')).toBe(false);+ finishSwitch();+ });++ it('错误重试先发时从历史查询开始占住发送 token,settle 后才允许切换', async () => {+ const coordinator = await import('@/lib/agentSwitchCoordinator');+ coordinator.__resetAgentSwitchCoordinatorForTests();+ let rejectRetry!: (reason: Error) => void;+ const retryLastError = vi.fn(() => new Promise<never>((_resolve, reject) => {+ rejectRetry = reject;+ }));+ vi.stubGlobal('window', {+ electronAPI: { maker: { input: { retryLastError } } },+ });+ const { makerChatStore } = await import('@/lib/makerChatStore');++ const retry = makerChatStore.retryLastError('retry-first');+ expect(retryLastError).toHaveBeenCalledWith('retry-first');+ expect(coordinator.hasPendingAgentSendDispatch('retry-first')).toBe(true);+ // ChatInput 的切换入口同步检查这个 registry;重试 main RPC 尚未入队也不能被越过。+ expect(coordinator.hasPendingAgentSwitchOperation('retry-first')).toBe(false);++ rejectRetry(new Error('retry failed'));+ await expect(retry).rejects.toThrow('retry failed');+ expect(coordinator.hasPendingAgentSendDispatch('retry-first')).toBe(false);+ });++ it('上下文压缩先发时从队列恢复开始占住发送 token,settle 后才允许切换', async () => {+ const coordinator = await import('@/lib/agentSwitchCoordinator');+ coordinator.__resetAgentSwitchCoordinatorForTests();+ let rejectCompact!: (reason: Error) => void;+ const compact = vi.fn(() => new Promise<never>((_resolve, reject) => {+ rejectCompact = reject;+ }));+ vi.stubGlobal('window', { electronAPI: { maker: { input: { compact } } } });+ const { makerChatStore } = await import('@/lib/makerChatStore');++ const request = makerChatStore.compactSession(+ 'compact-first',+ 'claude-sonnet-4-6',+ 'medium',+ 'default',+ '/tmp/workdir',+ );+ expect(compact).toHaveBeenCalledOnce();+ expect(coordinator.hasPendingAgentSendDispatch('compact-first')).toBe(true);++ rejectCompact(new Error('compact failed'));+ await expect(request).resolves.toBe(false);+ expect(coordinator.hasPendingAgentSendDispatch('compact-first')).toBe(false);+ });+});++describe('ChatInput 的入口门控与调用路由', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const storeSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/lib/makerChatStore.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('切换 IPC 走传输层(远程会话隧道到被控端),不再硬打本机 maker', () => {+ expect(source).toContain('switchApi.switchSessionAgent(');+ expect(source).toContain(': makerApiFor(sourceSessionId);');+ expect(source).not.toContain('window.electronAPI.maker.switchSessionAgent(');+ });++ it('入口按被控端能力位门控:device-link 不再被排除,SSH 远程仍排除', () => {+ expect(source).toContain(+ 'sessionId && vendorKey && !remoteHostId && sessionAgentSwitchSupported',+ );+ expect(source).toContain('ccCaps.capabilities?.supportsSessionAgentSwitch === true');+ expect(source).toContain('ccCaps.capabilities.supportsSessionAgentSwitchCas === true');+ expect(source).toContain('codexCaps.capabilities?.supportsSessionAgentSwitch === true');+ expect(source).toContain('codexCaps.capabilities.supportsSessionAgentSwitchCas === true');+ const hostSource = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),+ 'utf8',+ );+ expect(hostSource).toContain('supportsSessionAgentSwitchCas: true');+ });++ it('lazy-create 从 DB 对齐原子模型选择的 effort 与 Fast,不复用旧排队快照', () => {+ const hostSource = readFileSync(+ resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),+ 'utf8',+ );+ const start = hostSource.indexOf('async function reconcileCreateOptsAgainstDb(');+ const end = hostSource.indexOf('const agentSwitchDeps:', start);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ const body = hostSource.slice(start, end);+ expect(body).toContain('effort: sessions.effort,');+ expect(body).toContain('fastMode: sessions.fastMode,');+ expect(body).toContain("co.effort = (row.effort ?? undefined) as CreateOpts['effort'];");+ expect(body).toContain('co.fastMode = !!row.fastMode;');+ });++ it('Orca 与角色未加载会话都 fail-closed:只有完整元数据确认非协同后开放入口', () => {+ expect(source).toContain('sessionOrcaRole === null &&');+ // 会话视图必须保留 undefined 未知态,不能在完整 session 回流前冒充「非协同」。+ const viewSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),+ 'utf8',+ );+ expect(viewSource).toContain(+ 'sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}',+ );+ });++ it('本地与远程会话打开时都读回 main 权威意图,并经新鲜度守卫过滤过期响应', () => {+ expect(source).toContain('if (!sessionId || remoteHostId) return;');+ expect(source).toContain('const switchApi = deviceLinkDeviceId');+ expect(source).toContain('? makerApiForDevice(deviceLinkDeviceId)');+ expect(source).toContain(': makerApiFor(sessionId);');+ expect(source).toContain('.getSessionAgentSwitchIntent(sessionId)');+ expect(source).toContain('isAgentSwitchResponseFresh({');+ expect(source).toContain(+ 'makerChatStore.mirrorAgentSwitchIntent(sessionId, authoritativeIntent)',+ );+ // 每次点选都要推进写序号,外部变更靠 store 修订号 —— 少任一个 ABA 守卫都失效。+ expect(source).toContain('nextAgentSwitchWriteSeq(sourceSessionId)');+ expect(source).toContain('makerChatStore.getAgentSwitchIntentRev(sessionId)');+ // deviceId 跨重连不变,不把重连代际放进依赖就永远不会重试(断链期间的读回失败+ // 与错过的 sessions:patched 都靠这一跳补回)。+ expect(source).toContain(+ '}, [sessionId, deviceLinkDeviceId, remoteHostId, remoteReconnectEpoch]);',+ );+ expect(source).toContain("remoteConnStatus === 'connected'");+ });++ it('切换 ack 走分派决策:发起时捕获写序号与修订号,按分支判定而非一刀切 return', () => {+ expect(source).toContain('const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);');+ expect(source).toContain(+ 'const intentRevAtSend = makerChatStore.getAgentSwitchIntentRev(sourceSessionId);',+ );+ expect(source).toContain('const ackAction = resolveAgentSwitchAckAction({');+ expect(source).toContain("if (ackAction === 'discard') return;");+ expect(source).toContain("if (ackAction === 'same-engine-reselect') {");+ expect(source).toContain('sameEngineRevision: result.sameEngineRevision,');+ expect(source).toContain('sameEngineSuperseded: result.sameEngineSuperseded,');+ });++ it('切换写入走模块级协调层(串行链与写序号按 session,不随组件卸载归零)', () => {+ expect(source).toContain('const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);');+ expect(source).toContain('await exclusiveTurn.ready;');+ expect(source).toContain('exclusiveTurn.release();');+ expect(source).toContain('const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);');+ expect(source).toContain('writeSeqNow: getAgentSwitchWriteSeq(sourceSessionId),');+ // 组件内不得再持有队列/序号 ref,否则重挂后又会分叉出第二条空队列。+ expect(source).not.toContain('agentSwitchWriteSeqRef');+ expect(source).not.toContain('agentSwitchQueueRef');++ const selectorSource = readFileSync(+ resolve(process.cwd(), 'src/renderer/components/new-chat/ModelSelector.tsx'),+ 'utf8',+ );+ expect(selectorSource).not.toContain('agentSwitchQueueRef');+ expect(selectorSource).toContain(+ 'void agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);',+ );+ });++ it('同引擎重选与前置 invoke 共占一个串行位置,并在用最新 ref 前校验会话', () => {+ const reservation = source.indexOf(+ 'const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);',+ );+ const invoke = source.indexOf(+ 'const result = await switchApi.switchSessionAgent(',+ reservation,+ );+ const scopeGuard = source.indexOf(+ 'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return;',+ invoke,+ );+ const reselect = source.indexOf('const applied = providerId', scopeGuard);+ const staleGuard = source.indexOf('if (applied === false) return;', reselect);+ const release = source.indexOf('exclusiveTurn.release();', reselect);+ expect(reservation).toBeGreaterThanOrEqual(0);+ expect(invoke).toBeGreaterThan(reservation);+ expect(scopeGuard).toBeGreaterThan(invoke);+ expect(reselect).toBeGreaterThan(scopeGuard);+ expect(staleGuard).toBeGreaterThan(reselect);+ expect(release).toBeGreaterThan(reselect);+ });++ it('同引擎重选把 host 因果 token 带回 SET_MODEL,且遇到 superseded 不落后续状态', () => {+ expect(source).toContain('expectedAgentSwitchRevision?: number');+ expect(source).toContain('expectedAgentSwitchRevision === undefined &&');+ expect(source.split('expectedAgentSwitchRevision === undefined &&')).toHaveLength(3);+ expect(source).toContain('remoteAtomicModelSelectionSupported');+ expect(source).toContain(+ 'expectedAgentSwitchRevision !== undefined || remoteAtomicModelSelectionSupported',+ );+ expect(source).toContain('? { effort: newEffort, fastMode: restoredFast }');+ expect(source).toContain('? { effort: targetEffort, fastMode: restoredFast }');+ expect(source).toContain('if (!useAtomicSelection) {');+ expect(source).toContain('if (remoteSetModelResult?.superseded) {');+ expect(source).toContain('if (setModelResult?.superseded) {');+ expect(source).toContain('result.sameEngineRevision,');+ });++ it('切换意图登记完成前所有发送入口都被同步门禁,组件重挂后 pending 仍可见', () => {+ expect(source).toContain('const agentSwitchInFlight = useSyncExternalStore(');+ expect(source).toContain('const finishAgentSwitchOperation = beginAgentSwitchOperation(');+ expect(source).toContain('finishAgentSwitchOperation();');+ expect(source).toContain('? tryBeginAgentSendDispatch(sourceSessionId)');+ expect(source).toContain('agentSwitchInFlight ||');++ // composer 之外的继续 / 编辑重发等入口最终都经过共享 store 边界,不能要求每个+ // UI 调用点记得手工登记 token。+ const sendMessage = storeSource.indexOf('function sendMessage(');+ const sendMessageBegin = storeSource.indexOf('return withAgentSendDispatch(', sendMessage);+ const sendUiTrigger = storeSource.indexOf('function sendUiTrigger(');+ const uiTriggerBegin = storeSource.indexOf('return withAgentSendDispatch(', sendUiTrigger);+ const retryLastError = storeSource.indexOf('function retryLastError(');+ const retryBegin = storeSource.indexOf(+ 'return runAgentDispatchProjectionOperation(',+ retryLastError,+ );+ const compactSession = storeSource.indexOf('function compactSession(');+ const compactBegin = storeSource.indexOf(+ 'return runAgentDispatchProjectionOperation(',+ compactSession,+ );+ const resumeQueue = storeSource.indexOf('function resumeQueue(');+ const resumeBegin = storeSource.indexOf(+ 'runAgentDispatchProjectionOperation(',+ resumeQueue,+ );+ const steerMessage = storeSource.indexOf('function steerMessage(');+ const steerBegin = storeSource.indexOf('return withAgentSendDispatch(', steerMessage);+ const steerQueuedMessage = storeSource.indexOf('function steerQueuedMessage(');+ const queuedSteerBegin = storeSource.indexOf(+ 'return withAgentSendDispatch(',+ steerQueuedMessage,+ );+ const resendBlockedMessage = storeSource.indexOf('async function resendBlockedMessage(');+ const blockedResendBegin = storeSource.indexOf(+ 'const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);',+ resendBlockedMessage,+ );+ const sharedBegin = storeSource.indexOf(+ 'const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);',+ );+ const sharedFinish = storeSource.indexOf(+ 'return task().finally(finishAgentSendDispatch);',+ sharedBegin,+ );+ expect(sendMessageBegin).toBeGreaterThan(sendMessage);+ expect(uiTriggerBegin).toBeGreaterThan(sendUiTrigger);+ expect(retryBegin).toBeGreaterThan(retryLastError);+ expect(compactBegin).toBeGreaterThan(compactSession);+ expect(resumeBegin).toBeGreaterThan(resumeQueue);+ expect(steerBegin).toBeGreaterThan(steerMessage);+ expect(queuedSteerBegin).toBeGreaterThan(steerQueuedMessage);+ expect(blockedResendBegin).toBeGreaterThan(resendBlockedMessage);+ expect(sharedBegin).toBeGreaterThanOrEqual(0);+ expect(sharedFinish).toBeGreaterThan(sharedBegin);+ });++ it('引用水合期间发送与切换双向互斥,并在真正发送前复核切换状态', () => {+ const sendBegin = source.indexOf('tryBeginAgentSendDispatch(sourceSessionId)');+ const hydrate = source.indexOf('await resolveSessionMessageReferencesForSend(editor);');+ const sendRecheck = source.indexOf(+ 'if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;',+ hydrate,+ );+ const onSend = source.indexOf('result = await onSend(', sendRecheck);+ const sendFinish = source.indexOf('finishAgentSendDispatch();', onSend);+ const sendSelfGuard = source.indexOf(+ 'if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;',+ );+ const switchGuard = source.indexOf(+ 'if (hasPendingAgentSendDispatch(sessionId)) return;',+ sendFinish,+ );++ expect(sendSelfGuard).toBeGreaterThanOrEqual(0);+ expect(sendBegin).toBeGreaterThan(sendSelfGuard);+ expect(hydrate).toBeGreaterThan(sendBegin);+ expect(sendRecheck).toBeGreaterThan(hydrate);+ expect(onSend).toBeGreaterThan(sendRecheck);+ expect(sendFinish).toBeGreaterThan(onSend);+ expect(switchGuard).toBeGreaterThan(sendFinish);+ expect(source).toContain(+ 'disabled={disabled || agentSendDispatchInFlight || agentSwitchInFlight}',+ );+ });++ it('远程分支用稳定 deviceId 直连隧道:relay 瞬时重连会清空 sessionId→deviceId 索引', () => {+ expect(source).toContain('const switchApi = deviceLinkDeviceId');+ expect(source).toContain('? makerApiForDevice(deviceLinkDeviceId)');+ expect(source).toContain(': makerApiFor(sourceSessionId);');+ });++ it('await 返回后做会话作用域校验:旧会话响应不得借最新 ref 写进当前会话', () => {+ expect(source).toContain(+ 'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return;',+ );+ // 读回同理:往返期间被切走就丢弃。+ expect(source).toContain(+ 'cancelled: cancelled || !isSessionScopeCurrent(sessionId, currentSessionIdRef.current),',+ );+ });+});diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex d1103459f2..b6e4ed3e05 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -4,6 +4,7 @@ import {useMemo,useRef,useState,+ useSyncExternalStore,useLayoutEffect,type DragEvent as ReactDragEvent,type PointerEvent as ReactPointerEvent,@@ -98,7 +99,23 @@ import {enqueueEffortChange,isSessionScopeCurrent,} from './effortChangeQueue';-import { confirmAgentSwitchRisk } from './agentSwitchConfirmation';+import { useRemoteSessionConnection } from '@/features/cc-agent/hooks/useRemoteSessionConnection';++import {+ confirmAgentSwitchRisk,+ isAgentSwitchResponseFresh,+ resolveAgentSwitchAckAction,+} from './agentSwitchConfirmation';+import {+ beginAgentSwitchOperation,+ getAgentSwitchWriteSeq,+ hasPendingAgentSendDispatch,+ hasPendingAgentSwitchOperation,+ nextAgentSwitchWriteSeq,+ reserveAgentSwitchExclusive,+ subscribeAgentSwitchPending,+ tryBeginAgentSendDispatch,+} from '@/lib/agentSwitchCoordinator';import {isSelectedSourceDisconnected,resolveEffort,@@ -316,6 +333,14 @@ interface ChatInputProps {* 不能用 vendorKey 的 Claude Code 默认回退冒充真实身份。*/runtimeAgentKind?: AgentKind | null;+ /**+ * 会话的 Orca 角色(lead / worker;null = 已确认非协同;undefined = 元数据未加载)。+ * 协同运行时对 agent 形态有独立+ * 契约(docs/dev-rules/orca-team-architecture.md),被控端的 session-agent-switch handler+ * 对任何带 orcaRole 的会话一律拒 UNSUPPORTED_CAPABILITY —— 入口据此隐藏,不给用户+ * 一个点了必失败的控件(与手机端 supportsMobileSessionAgentSwitch 同口径)。+ */+ sessionOrcaRole?: string | null;/** Initial workingDir from session data. */initialWorkingDir?: string | null;/**@@ -816,6 +841,7 @@ export function ChatInput({onSend,sessionId,runtimeAgentKind,+ sessionOrcaRole,initialWorkingDir,remoteHostId,deviceLinkDeviceId,@@ -1135,6 +1161,17 @@ export function ChatInput({// 只镜像 fastMode),若把禁用绑到 pendingRemoteSwitch 的三元 settle 上,跨来源切换(如 GPT→Opus 必换来源)// 会一直 settle 不了、selector 置灰吃满 5s 兜底。乐观显示(chip 不回落默认)仍由 pendingRemoteSwitch 承接。const [remoteSwitchInFlight, setRemoteSwitchInFlight] = useState(false);+ // 跨引擎切换的 pending 真源在模块级协调器:切走再切回 / 组件重挂时仍保持发送门禁。+ const agentSwitchInFlight = useSyncExternalStore(+ subscribeAgentSwitchPending,+ () => !!sessionId && hasPendingAgentSwitchOperation(sessionId),+ () => false,+ );+ const agentSendDispatchInFlight = useSyncExternalStore(+ subscribeAgentSwitchPending,+ () => !!sessionId && hasPendingAgentSendDispatch(sessionId),+ () => false,+ );useEffect(() => {setPendingRemoteSwitch(null);@@ -1149,11 +1186,10 @@ export function ChatInput({// (model/effort/provider/fast),props(镜像 DB)仍是旧引擎值——真切换在下一条// 消息发送时刻 apply,patched 回流后意图清除、显示交回 props。意图存放在// SessionChatState 独立槽位,登记/撤销通过 setState 驱动重渲染,不会改真实- // agentKind reducer 路由。+ // agentKind reducer 路由。device-link 远程会话同样适用:意图的权威态在被控端+ // main,控制端 store 里这份是它的镜像(登记时乐观写、重连时读回、push 回流覆盖)。const agentSwitchIntent =- sessionId && !deviceLinkDeviceId && !remoteHostId- ? makerChatStore.getAgentSwitchIntent(sessionId)- : null;+ sessionId && !remoteHostId ? makerChatStore.getAgentSwitchIntent(sessionId) : null;const activeModel =agentSwitchIntent?.model ??pendingRemoteSwitch?.model ??@@ -1207,6 +1243,81 @@ export function ChatInput({const ccCaps = useAgentCapabilities('claude-code', deviceLinkDeviceId);const codexCaps = useAgentCapabilities('codex', deviceLinkDeviceId);+ // session-agent-switch 入口门控。device-link 远程会话读**被控端**的值;除了基础+ // supportsSessionAgentSwitch,还必须有 v2 CAS 能力。同引擎 no-op 的安全收尾依赖 host+ // 返回修订号,只有基础位的旧 host 无法把自己的 clear push 与外部 ABA 关联,不能开放+ // 一个会随机吞掉模型重选的入口。本机会话恒可用——main 与 renderer 同版本,不能因+ // capabilities 还没加载完而闪掉入口。+ // SSH 远程(remoteHostId)是另一套引擎生命周期,继续不支持,由调用点单独排除。+ // Orca 会话(lead / worker)同样排除:被控端 handler 对带 orcaRole 的会话一律拒+ // UNSUPPORTED_CAPABILITY。角色未加载(undefined)也 fail-closed,避免冷启动短暂露出入口。+ const ccSupportsSessionAgentSwitch =+ ccCaps.capabilities?.supportsSessionAgentSwitch === true &&+ ccCaps.capabilities.supportsSessionAgentSwitchCas === true;+ const codexSupportsSessionAgentSwitch =+ codexCaps.capabilities?.supportsSessionAgentSwitch === true &&+ codexCaps.capabilities.supportsSessionAgentSwitchCas === true;+ // 此能力与原子 model-selection payload 同版发布。旧被控端会忽略 SET_MODEL 第 5 参,+ // 因此缺能力位时保留原来的 SET_MODEL → SET_EFFORT → SET_FAST 兼容链;同引擎+ // reselect 入口本就要求 CAS=true,不会退回这条非原子路径。+ const remoteAtomicModelSelectionSupported =+ ccCaps.capabilities?.supportsSessionAgentSwitchCas === true ||+ codexCaps.capabilities?.supportsSessionAgentSwitchCas === true;+ const sessionAgentSwitchSupported =+ sessionOrcaRole === null &&+ (!deviceLinkDeviceId || ccSupportsSessionAgentSwitch || codexSupportsSessionAgentSwitch);++ // 切换写入的串行链与写序号都按 session 存在**模块级**协调层(agentSwitchCoordinator),+ // 不放组件 ref:用户切走再切回时旧组件已卸载但 invoke 仍在飞,新组件若另起空队列 /+ // 归零序号,两个请求会重新并发、旧 ack 会被误判成新鲜。理由与取舍见该模块头注释。+ // 链路重连代际:deviceId 在断链重连期间保持不变,只靠它当依赖的话读回永远不会重试。+ // 断链期间发出的读回会失败(catch 吞掉),断链期间被控端 / 另一控制端改的意图其+ // sessions:patched 推送也收不到 —— 恢复连接后必须重读一次,否则 composer 会一直+ // 停在过期引擎上。非 connected → connected 的每次跃迁 +1,驱动下方 effect 重跑。+ const remoteConnStatus = useRemoteSessionConnection(deviceLinkDeviceId);+ const [remoteReconnectEpoch, setRemoteReconnectEpoch] = useState(0);+ const remoteWasConnectedRef = useRef(false);+ useEffect(() => {+ const connected = remoteConnStatus === 'connected';+ if (connected && !remoteWasConnectedRef.current) setRemoteReconnectEpoch((n) => n + 1);+ remoteWasConnectedRef.current = connected;+ }, [remoteConnStatus]);++ // 会话打开时读回 main 的权威 pending 意图。意图是 main 的内存态、不落库,+ // renderer 换窗口 / 重开视图 / LRU 驱逐后本地镜像为空,不读回就会出现「UI 显示旧引擎、+ // 下一条消息却按意图切换」的错位。device-link 会话直连稳定 deviceId;本地会话走+ // 本机 maker。SSH 是另一套引擎生命周期,继续排除。+ useEffect(() => {+ if (!sessionId || remoteHostId) return;+ let cancelled = false;+ const writeSeq = getAgentSwitchWriteSeq(sessionId);+ const intentRev = makerChatStore.getAgentSwitchIntentRev(sessionId);+ const switchApi = deviceLinkDeviceId+ ? makerApiForDevice(deviceLinkDeviceId)+ : makerApiFor(sessionId);+ void switchApi+ .getSessionAgentSwitchIntent(sessionId)+ .then((authoritativeIntent) => {+ const fresh = isAgentSwitchResponseFresh({+ // 会话在往返期间被切走 → 这次响应不属于当前视图,丢弃。+ cancelled: cancelled || !isSessionScopeCurrent(sessionId, currentSessionIdRef.current),+ writeSeqAtStart: writeSeq,+ writeSeqNow: getAgentSwitchWriteSeq(sessionId),+ intentRevAtStart: intentRev,+ intentRevNow: makerChatStore.getAgentSwitchIntentRev(sessionId),+ });+ if (!fresh) return;+ makerChatStore.mirrorAgentSwitchIntent(sessionId, authoritativeIntent);+ })+ .catch(() => {+ // 老被控端未收录该 channel(CHANNEL_NOT_ALLOWED)、断链或本地读取失败:保留已有镜像,+ // 不擦用户已登记的选择(入口本身已按 capabilities 隐藏)。+ });+ return () => {+ cancelled = true;+ };+ }, [sessionId, deviceLinkDeviceId, remoteHostId, remoteReconnectEpoch]);+// cycle-permission-mode 快捷键 (默认 Shift+Tab) 的轮切候选 —— 与// PermissionSelector 用同一份 capabilities.permissionModes 列表, 键盘轮切// 与下拉菜单看到的顺序一致。vendorKey 未锁定时按 PermissionSelector 的@@ -3417,7 +3528,8 @@ export function ChatInput({// ── Send / Stop wiring ─────────────────────────────────────────────const dispatchSendInFlightRef = useRef(false);- const [sendDispatchInFlight, setSendDispatchInFlight] = useState(false);+ const [localSendDispatchInFlight, setSendDispatchInFlight] = useState(false);+ const sendDispatchInFlight = localSendDispatchInFlight || agentSendDispatchInFlight;const dispatchSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(() => {},);@@ -3425,164 +3537,177 @@ export function ChatInput({async (deliveryMode: MessageDeliveryMode = 'queue') => {if (!editor) return;if (disabled) return;+ // React 的 disabled 状态可能尚未完成下一帧渲染;同步读协调器兜住点击、快捷键、+ // 语音发送等所有入口,确保 host 已登记切换意图后才允许 maker:send。+ if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;if (dispatchSendInFlightRef.current) return;+ const sourceSessionId = sessionId;+ const finishAgentSendDispatch = sourceSessionId+ ? tryBeginAgentSendDispatch(sourceSessionId)+ : () => {};+ if (!finishAgentSendDispatch) return;draftSaveSchedulerRef.current?.flush();dispatchSendInFlightRef.current = true;setSendDispatchInFlight(true);try {await resolveSessionMessageReferencesForSend(editor);- } finally {- dispatchSendInFlightRef.current = false;- setSendDispatchInFlight(false);- }- if (editor.isDestroyed) return;- const {- text: editorText,- mentions,- hasQuotes,- agentReferences,- pastedTextRanges,- slashCommandRanges,- } = serializeEditorContent(editor);- // composerQuote 在其正文位置序列化成 markdown blockquote,支持引用与回复交错。- // browser-comment-chip:页面评论序列化为 `# Browser comments:` 段拼在正文后- // (截图在下方并入 filesToSend,与文本块里的 "attached as a labeled image"- // caption 对应)。- const text = formatBrowserCommentsForSend(browserCommentsRef.current, editorText);- // Allow send if there is text OR attachments(纯引用 / 纯评论无输入也可发送)- if (!text && !hasAttachments) return;-- // 预检:会话显式选中的来源已断开 → 发送前拦截。main 侧懒创建会从 DB 水合 providerId- // 直接 LAZY_CREATE_FAILED(renderer 的 sendProviderId=null 救不了已建会话),所以这里- // 弹窗给出明确原因 + 去设置入口,而不是让请求出去撞一个原始错误码。- // Send 按钮已被 selectedSourceDisconnected 禁用,此 guard 兜底覆盖间接派发路径。- if (selectedSourceDisconnected) {- const goConnect = await confirmDialog({- title: t('newChat.sourceDisconnected.title'),- description: t('newChat.sourceDisconnected.description'),- confirmText: t('newChat.sourceDisconnected.connect'),- cancelText: t('logic.confirm.cancel'),- autoFocusConfirm: true,- });- if (goConnect) navigate('/settings?tab=providers');- return;- }-- // 预检(通用、provider-aware): 当前模型在当前 agent 下「一个已连接来源都没有」- // 时,不把请求扔给 SDK 等 401,改弹确认框引导用户去「设置 → 模型供应商」连接。- // 取代过去仅 cc + 仅 api_key 的写法 —— 现在 OAuth / XD 网关 / 未来自定义供应商- // 都按 ProviderView.connected 统一计入(chatEligibleSourcesForModel onlyConnected),- // 未来加新供应商无需改这里。判定数据来自本地 IPC(useProviders),无网络往返、- // ~ms 级。只有「确实零已连接来源」才拦截;≥1 个直接放行(无弹窗)。- // currentModelAgentKind 解析不出(罕见:capabilities 未就绪)时不拦,交给下游- // 处理,不误伤。用 chatEligibleSourcesForModel 而非裸 sourcesForModel:- // 非聊天来源不该被当成"可以发"放行(issue #882 第 3 点,2026-07 review)。- if (currentModelAgentKind) {- // 已建会话按实际路由口径判(includeDisabled,与上方 hasConnectedSendSource- // 同则):运行中会话不因停用打断,最终 preflight 若按准入 rail 判会在全停时- // 弹「去连接来源」把继续发送挡死(PR #744 review 第十八轮)。草稿保持准入口径。- const connectedSources = chatEligibleSourcesForModel(providers, activeModel, currentModelAgentKind, {- onlyConnected: true,- includeDisabled: !!sessionId,- });- if (connectedSources.length === 0) {+ // 引用 chip 水合会跨 device-link await;等待期间若旧客户端 / 其他入口登记了切换,+ // 必须在真正 onSend 前再查一次,不能让准备阶段前的一次性检查代表发送时刻。+ if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;+ if (editor.isDestroyed) return;+ const {+ text: editorText,+ mentions,+ hasQuotes,+ agentReferences,+ pastedTextRanges,+ slashCommandRanges,+ } = serializeEditorContent(editor);+ // composerQuote 在其正文位置序列化成 markdown blockquote,支持引用与回复交错。+ // browser-comment-chip:页面评论序列化为 `# Browser comments:` 段拼在正文后+ // (截图在下方并入 filesToSend,与文本块里的 "attached as a labeled image"+ // caption 对应)。+ const text = formatBrowserCommentsForSend(browserCommentsRef.current, editorText);+ // Allow send if there is text OR attachments(纯引用 / 纯评论无输入也可发送)+ if (!text && !hasAttachments) return;++ // 预检:会话显式选中的来源已断开 → 发送前拦截。main 侧懒创建会从 DB 水合 providerId+ // 直接 LAZY_CREATE_FAILED(renderer 的 sendProviderId=null 救不了已建会话),所以这里+ // 弹窗给出明确原因 + 去设置入口,而不是让请求出去撞一个原始错误码。+ // Send 按钮已被 selectedSourceDisconnected 禁用,此 guard 兜底覆盖间接派发路径。+ if (selectedSourceDisconnected) {const goConnect = await confirmDialog({- title: t('newChat.noProvider.title'),- description: t('newChat.noProvider.description'),- confirmText: t('newChat.noProvider.connect'),+ title: t('newChat.sourceDisconnected.title'),+ description: t('newChat.sourceDisconnected.description'),+ confirmText: t('newChat.sourceDisconnected.connect'),cancelText: t('logic.confirm.cancel'),autoFocusConfirm: true,});if (goConnect) navigate('/settings?tab=providers');return;}- }- // 评论截图并入发送附件(item.screenshot 即 AttachedFile,顺序在用户附件后,- // 与评论块的编号 caption 对应)。- const commentScreenshots = browserCommentsRef.current.map((c) => c.screenshot);- const filesToSend =- hasAttachments || commentScreenshots.length > 0- ? [...attachments, ...commentScreenshots]- : undefined;- const mentionsToSend = mentions.length > 0 ? mentions : undefined;- // 意识 $指令展开(C3d 双触发):`$画图 ...` 开头且命中已唤醒意识时,- // 追加"必须走 cindy 总机"的机器指令;未命中原样发送。- // 读取 useInstalledGhosts 的最新窗口级快照。ghosts:changed 会原子更新- // 该快照;发送路径无需同步 IPC,仍按当前工作目录执行同一禁用判定。+ // 预检(通用、provider-aware): 当前模型在当前 agent 下「一个已连接来源都没有」+ // 时,不把请求扔给 SDK 等 401,改弹确认框引导用户去「设置 → 模型供应商」连接。+ // 取代过去仅 cc + 仅 api_key 的写法 —— 现在 OAuth / XD 网关 / 未来自定义供应商+ // 都按 ProviderView.connected 统一计入(chatEligibleSourcesForModel onlyConnected),+ // 未来加新供应商无需改这里。判定数据来自本地 IPC(useProviders),无网络往返、+ // ~ms 级。只有「确实零已连接来源」才拦截;≥1 个直接放行(无弹窗)。+ // currentModelAgentKind 解析不出(罕见:capabilities 未就绪)时不拦,交给下游+ // 处理,不误伤。用 chatEligibleSourcesForModel 而非裸 sourcesForModel:+ // 非聊天来源不该被当成"可以发"放行(issue #882 第 3 点,2026-07 review)。+ if (currentModelAgentKind) {+ // 已建会话按实际路由口径判(includeDisabled,与上方 hasConnectedSendSource+ // 同则):运行中会话不因停用打断,最终 preflight 若按准入 rail 判会在全停时+ // 弹「去连接来源」把继续发送挡死(PR #744 review 第十八轮)。草稿保持准入口径。+ const connectedSources = chatEligibleSourcesForModel(providers, activeModel, currentModelAgentKind, {+ onlyConnected: true,+ includeDisabled: !!sessionId,+ });+ if (connectedSources.length === 0) {+ const goConnect = await confirmDialog({+ title: t('newChat.noProvider.title'),+ description: t('newChat.noProvider.description'),+ confirmText: t('newChat.noProvider.connect'),+ cancelText: t('logic.confirm.cancel'),+ autoFocusConfirm: true,+ });+ if (goConnect) navigate('/settings?tab=providers');+ return;+ }+ }++ // 评论截图并入发送附件(item.screenshot 即 AttachedFile,顺序在用户附件后,+ // 与评论块的编号 caption 对应)。+ const commentScreenshots = browserCommentsRef.current.map((c) => c.screenshot);+ const filesToSend =+ hasAttachments || commentScreenshots.length > 0+ ? [...attachments, ...commentScreenshots]+ : undefined;+ const mentionsToSend = mentions.length > 0 ? mentions : undefined;+ // 意识 $指令展开(C3d 双触发):`$画图 ...` 开头且命中已唤醒意识时,+ // 追加"必须走 cindy 总机"的机器指令;未命中原样发送。+ // 读取 useInstalledGhosts 的最新窗口级快照。ghosts:changed 会原子更新+ // 该快照;发送路径无需同步 IPC,仍按当前工作目录执行同一禁用判定。const eligibleGhosts = filterGhostsForWorkdir(installedGhostsRef.current,workingDirRef.current,);- const ghostCommandWord = parseGhostCommandWord(text);- const usedGhost = ghostCommandWord- ? findGhostByCommand(eligibleGhosts, ghostCommandWord)- : null;- const textToSend = expandGhostCommand(text, eligibleGhosts);- let recentUsageMarked = false;- const markRecentPluginUsage = () => {- if (!usedGhost || recentUsageMarked) return;- recentUsageMarked = true;- void window.electronAPI.ghosts.markUsed(usedGhost.manifest.id).catch((error) => {- log.warn(- 'failed to persist recent Plugin usage:',- error instanceof Error ? error.message : String(error),+ const ghostCommandWord = parseGhostCommandWord(text);+ const usedGhost = ghostCommandWord+ ? findGhostByCommand(eligibleGhosts, ghostCommandWord)+ : null;+ const textToSend = expandGhostCommand(text, eligibleGhosts);+ let recentUsageMarked = false;+ const markRecentPluginUsage = () => {+ if (!usedGhost || recentUsageMarked) return;+ recentUsageMarked = true;+ void window.electronAPI.ghosts.markUsed(usedGhost.manifest.id).catch((error) => {+ log.warn(+ 'failed to persist recent Plugin usage:',+ error instanceof Error ? error.message : String(error),+ );+ });+ };+ dispatchSendInFlightRef.current = true;+ setSendDispatchInFlight(true);+ let result: boolean | void;+ try {+ result = await onSend(+ textToSend,+ activeModel,+ activeEffort,+ activePermissionMode,+ filesToSend,+ mentionsToSend,+ {+ deliveryMode,+ providerId: sendProviderId,+ ...(hasQuotes ? { quotesEncoded: true } : {}),+ ...(agentReferences.length > 0 ? { agentReferences } : {}),+ ...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),+ slashCommandRanges,+ ...(usedGhost ? { onAccepted: markRecentPluginUsage } : {}),+ },);- });- };- dispatchSendInFlightRef.current = true;- setSendDispatchInFlight(true);- let result: boolean | void;- try {- result = await onSend(- textToSend,- activeModel,- activeEffort,- activePermissionMode,- filesToSend,- mentionsToSend,- {- deliveryMode,- providerId: sendProviderId,- ...(hasQuotes ? { quotesEncoded: true } : {}),- ...(agentReferences.length > 0 ? { agentReferences } : {}),- ...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),- slashCommandRanges,- ...(usedGhost ? { onAccepted: markRecentPluginUsage } : {}),- },- );- } catch (error) {- log.warn('send rejected:', error instanceof Error ? error.message : String(error));- return;+ } catch (error) {+ log.warn('send rejected:', error instanceof Error ? error.message : String(error));+ return;+ } finally {+ dispatchSendInFlightRef.current = false;+ setSendDispatchInFlight(false);+ }+ if (result === false) return;+ markRecentPluginUsage();+ // Suppress onUpdate's draft-save during the post-send clearContent so+ // we don't write a transient empty-doc entry that we're about to drop.+ isRestoringRef.current = true;+ try {+ editor.commands.clearContent(true);+ } finally {+ isRestoringRef.current = false;+ }+ clearFiles();+ setBrowserComments([]);+ historyIndexRef.current = -1;+ hydratedHistoryDocumentRef.current = null;+ draftRef.current = null;+ // composer-draft-per-session: drop the saved draft now that this+ // session's content has been sent. Without this, switching away then+ // back would re-restore the just-sent text/files into the composer.+ if (storageKey) {+ clearComposerDraft(storageKey);+ }} finally {dispatchSendInFlightRef.current = false;setSendDispatchInFlight(false);- }- if (result === false) return;- markRecentPluginUsage();- // Suppress onUpdate's draft-save during the post-send clearContent so- // we don't write a transient empty-doc entry that we're about to drop.- isRestoringRef.current = true;- try {- editor.commands.clearContent(true);- } finally {- isRestoringRef.current = false;- }- clearFiles();- setBrowserComments([]);- historyIndexRef.current = -1;- hydratedHistoryDocumentRef.current = null;- draftRef.current = null;- // composer-draft-per-session: drop the saved draft now that this- // session's content has been sent. Without this, switching away then- // back would re-restore the just-sent text/files into the composer.- if (storageKey) {- clearComposerDraft(storageKey);+ finishAgentSendDispatch();}},[editor,disabled,+ sessionId,onSend,activeModel,activeEffort,@@ -3950,8 +4075,12 @@ export function ChatInput({// handleModelChange / handleProviderChange 声明在本回调之后,经 ref 引用避免// TDZ(仅在"选回当前引擎"分支的调用时刻解引用)。const sameEngineReselectRef = useRef<{- byProvider: (providerId: string, modelId: string) => void | Promise<void>;- byModel: (modelId: string) => void | Promise<void>;+ byProvider: (+ providerId: string,+ modelId: string,+ expectedRevision?: number,+ ) => void | boolean | Promise<void | boolean>;+ byModel: (modelId: string, expectedRevision?: number) => void | boolean | Promise<void | boolean>;}>({ byProvider: () => {}, byModel: () => {} });const confirmAgentBrowseSwitch = useCallback(() =>@@ -3981,7 +4110,18 @@ export function ChatInput({},) => {if (!sessionId) return;+ // 发送的引用水合 / 预检也可能 await。以同步登记的 session 级发送 token 为准,+ // 防止「先点发送、后选引擎」被异步准备反转成先登记切换再 maker:send。+ if (hasPendingAgentSendDispatch(sessionId)) return;+ // 本次点选无论落到哪个分支(登记意图 / 撤销意图 / 立即切换),都算一次本端写入:+ // 在途的远程意图读回据此作废,不会用旧快照盖掉用户刚做的选择。+ const sourceSessionId = sessionId;+ const writeSeq = nextAgentSwitchWriteSeq(sourceSessionId);+ const intentRevAtSend = makerChatStore.getAgentSwitchIntentRev(sourceSessionId);+ const finishAgentSwitchOperation = beginAgentSwitchOperation(sourceSessionId);+ const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);try {+ await exclusiveTurn.ready;// effort 档按**目标引擎**目录解析(resolveModelEfforts 锚定当前引擎,// 同 id 模型两家档位可不同、目标独占模型在当前目录里查不到);浏览态// 悬浮面板写下的 per-(目标引擎,来源,模型) 预设在此恢复。@@ -4024,25 +4164,58 @@ export function ChatInput({}) &&(modelMemory.getFast(targetAgentKind, providerId, newModelId) ?? false);- const result = await window.electronAPI.maker.switchSessionAgent(- sessionId,+ // 会话级操作按来源路由:device-link 远程会话隧道到被控端(意图注册表与引擎+ // 交接都在那边),本机会话零变化直连本机 maker。+ // 远程分支用**稳定的** deviceLinkDeviceId 直连隧道,不走 makerApiFor 的+ // sessionId→deviceId 索引解析:该索引在 relay 瞬时重连窗口会被清空(见+ // stickySessionOrigin),此时远程会话会被误判成本机 → 打到控制端本机 maker,+ // 轻则「无此 session」,极小概率命中本机同 id 会话写错 pending intent。+ const switchApi = deviceLinkDeviceId+ ? makerApiForDevice(deviceLinkDeviceId)+ : makerApiFor(sourceSessionId);+ const result = await switchApi.switchSessionAgent(+ sourceSessionId,targetAgentKind,newModelId,providerId,newEffort,targetFast,);- if (result.deferred) {+ // device-link 往返期间可以切到另一个任务:同一路由下 ChatInput 会带着新+ // sessionId 继续渲染,sameEngineReselectRef 等闭包也已指向新会话。旧会话的+ // 响应绝不能借最新的 ref 把模型/来源写进当前会话。+ if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return;+ // 远程往返期间状态可能已被更新的选择超车:用户又点了一次(写序号变),或另一个+ // 控制端 / 被控端的权威 sessions:patched 先到(修订号变)。此时这次 ack 携带的是+ // **旧**选择,落下去会让选择器显示过期引擎,而被控端按新意图执行下一条消息。+ // 丢弃即可——被控端每次意图变更都会广播,权威值随 push 收敛。+ // 注意两类守卫作用域不同(见 resolveAgentSwitchAckAction):同引擎 no-op 的清除+ // 回流本就由本次调用引起,不能拿修订号变化把自己判成 stale。+ const ackAction = resolveAgentSwitchAckAction({+ deferred: result.deferred === true,+ switched: result.switched,+ sameEngineRevision: result.sameEngineRevision,+ sameEngineSuperseded: result.sameEngineSuperseded,+ freshness: {+ cancelled: false,+ writeSeqAtStart: writeSeq,+ writeSeqNow: getAgentSwitchWriteSeq(sourceSessionId),+ intentRevAtStart: intentRevAtSend,+ intentRevNow: makerChatStore.getAgentSwitchIntentRev(sourceSessionId),+ },+ });+ if (ackAction === 'discard') return;+ if (ackAction === 'apply-intent') {// 意图已登记:乐观呈现目标引擎/模型/档位(独立 intent 覆盖// model/effort/provider/fast 显示,不改真实 reducer agentKind)。真切换// 在下一条消息发送时刻执行;turn 运行中额外提示旧 turn 不受影响。- makerChatStore.noteAgentSwitchIntent(sessionId, targetAgentKind, {+ makerChatStore.noteAgentSwitchIntent(sourceSessionId, targetAgentKind, {model: newModelId,providerId,effort: newEffort,fastMode: targetFast,});- if (makerChatStore.getSnapshot(sessionId).agentStatus.isRunning) {+ if (makerChatStore.getSnapshot(sourceSessionId).agentStatus.isRunning) {toast.success(t('newChat.chatInput.agentSwitch.deferred', {agent: targetAgentKind === 'codex' ? 'Codex' : 'Claude Code',@@ -4053,16 +4226,31 @@ export function ChatInput({}return;}- if (!result.switched) {- // 同引擎 no-op = 用户选回当前引擎:撤销展示意图,再把这次- // 点选当作普通的模型/来源切换应用到当前引擎。- makerChatStore.clearAgentSwitchIntent(sessionId);- if (providerId) void sameEngineReselectRef.current.byProvider(providerId, newModelId);- else void sameEngineReselectRef.current.byModel(newModelId);+ if (ackAction === 'same-engine-reselect') {+ // 同引擎 no-op = 用户选回当前引擎:撤销展示意图(幂等,被控端可能已清并回流),+ // 再把这次点选当作普通的模型/来源切换应用到当前引擎。+ //+ // 这次 SET_MODEL 在被控端会走 applySetModelThenCancelAgentSwitchIntent —— 它+ // **无条件**清掉 pending intent 并广播 agentSwitchIntent:null。fire-and-forget+ // 的话,它可能在用户随后登记的新跨引擎意图之后才落地,把那次选择清掉(下一条+ // 消息就不切引擎了)。因此把完整异步调用也排进同一条会话串行链:后续的引擎切换+ // 必须等它发完才发出,顺序由链保证。+ const applied = providerId+ ? await sameEngineReselectRef.current.byProvider(+ providerId,+ newModelId,+ result.sameEngineRevision,+ )+ : await sameEngineReselectRef.current.byModel(+ newModelId,+ result.sameEngineRevision,+ );+ if (applied === false) return;+ makerChatStore.clearAgentSwitchIntent(sourceSessionId);return;}// 立即切换路径(harness / registry 缺省兜底,生产不走):维持旧收敛语义。- makerChatStore.noteAgentSwitched(sessionId, targetAgentKind);+ makerChatStore.noteAgentSwitched(sourceSessionId, targetAgentKind);if (!result.engineReady) {toast.error(t('newChat.chatInput.agentSwitch.engineNotReady'), { duration: 4000 });}@@ -4070,6 +4258,9 @@ export function ChatInput({toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'newChat.chatInput.agentSwitch.failed' })),);+ } finally {+ exclusiveTurn.release();+ finishAgentSwitchOperation();}},[@@ -4093,7 +4284,7 @@ export function ChatInput({performAgentSwitchRef.current = performAgentSwitch;const performModelChange = useCallback(- async (newModelId: string) => {+ async (newModelId: string, expectedAgentSwitchRevision?: number) => {const sourceSessionId = sessionId;const sourceRemoteDeviceId = sourceSessionId? (deviceLinkDeviceId ?? getSessionDeviceId(sourceSessionId))@@ -4104,12 +4295,18 @@ export function ChatInput({// 容量护栏最先跑: 用户取消时直接 return, 不留任何副作用(effort 快照都不动)。if (sessionId && newModelId !== activeModel) {const proceed = await confirmModelSwitchContextGuard(newModelId, sourceRemoteDeviceId);- if (!proceed || (sourceIsRemoteSession && !isSourceSessionCurrent())) return;+ if (!proceed || (sourceIsRemoteSession && !isSourceSessionCurrent())) return false;}// 切换意图期:此时列表展示的是目标引擎(乐观翻转),改选模型 = 更新意图,// 绝不能走普通 SET_MODEL 链路(main 会清意图、renderer 乐观态失配)。// flat 路径无来源信息,交默认路由(null)。- if (sessionId && makerChatStore.getAgentSwitchIntent(sessionId)) {+ // 带 host CAS token = 同引擎 no-op 的第二段收尾。此时 clear push 可能尚未回流,+ // store 里仍是发起前的旧跨引擎意图;不能把它误当成一次新的意图编辑重新登记。+ if (+ sessionId &&+ expectedAgentSwitchRevision === undefined &&+ makerChatStore.getAgentSwitchIntent(sessionId)+ ) {const intent = makerChatStore.getAgentSwitchIntent(sessionId)!;void performAgentSwitch(intent.target, newModelId, null);return;@@ -4145,14 +4342,9 @@ export function ChatInput({// 已创建会话会在成功切换后同步 New Maker 草稿默认,使下一次新建聊天复用本次选择。const restoredFast = resolveFast(newModelId, effectiveSourceId);if (sourceRemoteDeviceId) {- // device-link 远程会话:控制端纯镜像 —— **await** 运行时隧道 setX,被控端持久化(Phase 5)后- // 广播 sessions:patched 回流到分片(display 经回流更新);send/resume 由被控端 DB(已 persist- // 新 model/effort)保证正确。Fast 恢复成功后再写穿被控端草稿默认;控制端本地默认仍不被污染。- // New-K:await 而非 fire-and-forget —— relay 重连中 / 已被撤销 / effort 那半失败时,被控端- // 运行时/DB 根本没变(或只变一半),不能照报成功、污染 controller 默认偏好。失败 → toast 提示- // 并 return,不跑下方 onModelDidChange/onEffortDidChange 成功收尾。- // Fast 恢复失败只代表 restoredFast 未落盘:不回滚已经成功的 model/effort 切换,也不向- // 用户展示「远程切换失败」。草稿默认仍同步已落盘的 model/effort,Fast 保留当前真实值。+ // device-link 远程会话:控制端纯镜像。把 model/effort/fast 作为一个选择快照交给+ // 被控端 SET_MODEL;host 会在同一 session 锁内完成 runtime + DB 后才回 ack,避免+ // close/wake 的 queue drain 在独立 SET_EFFORT/SET_FAST 之前抢锁。// 乐观显示目标 (model, effort) + 置灰 selector,等被控端 echo 回流;失败回滚。setPendingRemoteSwitch({model: newModelId,@@ -4164,10 +4356,31 @@ export function ChatInput({// 老被控端返回 undefined = 立即生效。deferred 时给控制端同款提示,消除"切没切成"疑惑。let remoteDeferred = false;const remoteMaker = makerApiForDevice(sourceRemoteDeviceId);+ let fastPersisted = true;+ const useAtomicSelection =+ expectedAgentSwitchRevision !== undefined || remoteAtomicModelSelectionSupported;try {- const remoteSetModelResult = await remoteMaker.setModel(sessionId, newModelId);+ const remoteSetModelResult = await remoteMaker.setModel(+ sessionId,+ newModelId,+ undefined,+ expectedAgentSwitchRevision,+ useAtomicSelection+ ? { effort: newEffort, fastMode: restoredFast }+ : undefined,+ );+ if (remoteSetModelResult?.superseded) {+ if (isSourceSessionCurrent()) setPendingRemoteSwitch(null);+ return false;+ }remoteDeferred = remoteSetModelResult?.deferred === true;- await remoteMaker.setEffort(sessionId, newEffort);+ if (!useAtomicSelection) {+ await remoteMaker.setEffort(sessionId, newEffort);+ fastPersisted = await persistFastModeChange(restoredFast, {+ silent: true,+ remoteDeviceId: sourceRemoteDeviceId,+ });+ }} catch (err) {if (isSourceSessionCurrent()) {setPendingRemoteSwitch(null);@@ -4177,21 +4390,14 @@ export function ChatInput({),);}- return;+ return false;} finally {// 被控端 ack(成功)/ 失败 return 都解除禁用,不等 mirror 三元回流。if (isSourceSessionCurrent()) setRemoteSwitchInFlight(false);}- const fastPersisted = await persistFastModeChange(restoredFast, {- silent: true,- remoteDeviceId: sourceRemoteDeviceId,- });syncSessionDraftModelPrefs(newModelId,- {- effort: newEffort,- fast: fastPersisted ? restoredFast : fastMode,- },+ { effort: newEffort, fast: fastPersisted ? restoredFast : fastMode },{ remoteDeviceId: sourceRemoteDeviceId },);if (remoteDeferred && isSourceSessionCurrent()) {@@ -4205,46 +4411,43 @@ export function ChatInput({const switchSeqBySession = localRuntimeSwitchSeqBySessionRef.current;const rollbackSeq = (switchSeqBySession.get(sessionId) ?? 0) + 1;switchSeqBySession.set(sessionId, rollbackSeq);- const setModelResult = await window.electronAPI.maker.setModel(sessionId, newModelId);- const deferredUntilTurnEnd = setModelResult?.deferred === true;rollbackModelAfterPersistFailure = { model: activeModel, seq: rollbackSeq };- await sessionService.update(sessionId, {- model: newModelId,- effort: newEffort,- fastMode: restoredFast,- });+ const setModelResult = await window.electronAPI.maker.setModel(+ sessionId,+ newModelId,+ undefined,+ expectedAgentSwitchRevision,+ { effort: newEffort, fastMode: restoredFast },+ );+ if (setModelResult?.superseded) {+ rollbackModelAfterPersistFailure = null;+ return false;+ }+ const deferredUntilTurnEnd = setModelResult?.deferred === true;rollbackModelAfterPersistFailure = null;const effortCoordinator = effortChangeCoordinatorRef.current;effortCoordinator.setCommittedEffort(sessionId, newEffort);- // model-switch-effort-runtime-sync (2026-05-09): MAKER_INVOKE.SEND 在 session- // 已 spawn 时不使用 createOpts.effort, runtime 沿用上次 setEffort 设的值。- // runtime promise 不阻塞 commit lane;旧调用晚完成时 coordinator 会重放最新 effort。- if (!deferredUntilTurnEnd) {- effortCoordinator.publishRuntimeEffort(- sessionId,- newEffort,- (targetSessionId, effort) =>- window.electronAPI.maker.setEffort(targetSessionId, effort),- );- // fast 同理:切模型后把恢复的 fast 同步进 runtime。无条件下发 —— codex 走 agent fast- // runtime;claude-code 由 main 记 bridge 会话态(chatgpt/ 模型经订阅 handler prefs 生效,- // 不下发会让 main 内存态滞留旧值);其余在 main 侧安全 no-op。- window.electronAPI.maker.setFastMode(sessionId, restoredFast).catch(() => {});- } else {+ if (deferredUntilTurnEnd) {effortCoordinator.suppressRuntimeEffort(sessionId);// 默认 success 1200ms 读不完这句;拉长到 4s。toast.success(t('newChat.chatInput.credentialSwitchDeferred'), { duration: 4000 });}syncSessionDraftModelPrefs(newModelId, { effort: newEffort, fast: restoredFast });- // fast live 同步:DB 已写 restoredFast,但驱动 chip ⚡ 的 makerChatStore 快照不会被- // sessionService.update 更新(它只写会话行)。目标模型支持 fast 时把恢复值推进快照,否则切到+ if (currentModelAgentKind && effectiveSourceId) {+ modelMemory?.setFast(+ currentModelAgentKind,+ effectiveSourceId,+ newModelId,+ restoredFast,+ );+ }+ // fast live 同步:host 已原子落 DB/runtime,这里只更新驱动 chip ⚡ 的 renderer 快照。+ // 目标模型支持 fast 时把恢复值推进快照,否则切到// 「该来源记过 fast=on」的模型 chip 读不到、⚡ 掉档(本次修的 bug)。不支持 fast 的模型不在// 此动 —— 交给下方 onModelDidChange → handleModelDidChange 的关闭路径(保留「模型不支持已关闭- // Fast」toast)。onFastModeChange = makerChatStore.setFastMode:乐观 setState(同步进快照)+ 落盘。- // deferred 时跳过:它会经 maker:set-fast-mode 推给仍在跑的旧 turn(与上面跳过- // setEffort/setFastMode 同因);DB 已持久化 restoredFast,会话重建时生效。+ // Fast」toast)。deferred 时由 sessions:patched 回流,避免提前改当前 turn 的展示。if (!deferredUntilTurnEnd && modelFastSupported(newModelId, effectiveSourceId)) {- void handleFastModeChange(restoredFast, newModelId, newEffort, false);+ makerChatStore.mirrorSessionFields(sessionId, { fastMode: restoredFast });}}// SSoT: server persisted → ask parent to refresh `session` so the@@ -4273,13 +4476,20 @@ export function ChatInput({!getSessionDeviceId(sessionId)) {await window.electronAPI.maker- .setModel(sessionId, rollbackModelAfterPersistFailure.model)+ .setModel(+ sessionId,+ rollbackModelAfterPersistFailure.model,+ undefined,+ undefined,+ { effort: activeEffort, fastMode },+ ).catch((rollbackErr) => {log.warn('model change rollback failed:', rollbackErr);});}log.warn('model change failed:', err);toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'newChat.chatInput.switchFailed' })));+ return false;}},[@@ -4306,20 +4516,21 @@ export function ChatInput({fastMode,confirmModelSwitchContextGuard,performAgentSwitch,+ remoteAtomicModelSelectionSupported,],);const handleModelChange = useCallback(- (newModelId: string): Promise<void> => {+ (newModelId: string, expectedAgentSwitchRevision?: number): Promise<void | boolean> => {const remoteDeviceId = sessionId? (deviceLinkDeviceId ?? getSessionDeviceId(sessionId)): undefined;if (sessionId && !remoteDeviceId) {return effortChangeCoordinatorRef.current.enqueue(sessionId, () =>- performModelChange(newModelId),+ performModelChange(newModelId, expectedAgentSwitchRevision),);}- return performModelChange(newModelId);+ return performModelChange(newModelId, expectedAgentSwitchRevision);},[deviceLinkDeviceId, performModelChange, sessionId],);@@ -4468,7 +4679,12 @@ export function ChatInput({);const performProviderChange = useCallback(- async (newProviderId: string | null, reconciledModelId?: string, reconciledEffort?: Effort) => {+ async (+ newProviderId: string | null,+ reconciledModelId?: string,+ reconciledEffort?: Effort,+ expectedAgentSwitchRevision?: number,+ ) => {const sourceSessionId = sessionId;const sourceRemoteDeviceId = sourceSessionId? (deviceLinkDeviceId ?? getSessionDeviceId(sourceSessionId))@@ -4486,11 +4702,17 @@ export function ChatInput({reconciledModelId,sourceRemoteDeviceId,);- if (!proceed || (sourceIsRemoteSession && !isSourceSessionCurrent())) return;+ if (!proceed || (sourceIsRemoteSession && !isSourceSessionCurrent())) return false;}// 切换意图期:列表展示的是目标引擎(乐观翻转),(来源,模型) 改选 = 更新意图,// 不走普通 set-model 链路(main 会清意图、renderer 乐观态失配)。- if (sessionId && makerChatStore.getAgentSwitchIntent(sessionId)) {+ // 同 performModelChange:因果 token 存在时必须直达 SET_MODEL,绕过尚未回流+ // 的旧 intent 镜像;最终是否仍新鲜由 host 在 session 锁内用 revision 裁决。+ if (+ sessionId &&+ expectedAgentSwitchRevision === undefined &&+ makerChatStore.getAgentSwitchIntent(sessionId)+ ) {const intent = makerChatStore.getAgentSwitchIntent(sessionId)!;void performAgentSwitch(intent.target, reconciledModelId ?? intent.model, newProviderId);return;@@ -4534,14 +4756,34 @@ export function ChatInput({// deferred 语义同 handleModelChange 远程分支(被控端会话在跑 → pending、turn 结束生效)。let remoteDeferred = false;const remoteMaker = makerApiForDevice(sourceRemoteDeviceId);+ let fastPersisted = true;+ const useAtomicSelection =+ expectedAgentSwitchRevision !== undefined || remoteAtomicModelSelectionSupported;try {const remoteSetModelResult = await remoteMaker.setModel(sessionId,targetModel,newProviderId,+ expectedAgentSwitchRevision,+ useAtomicSelection+ ? { effort: targetEffort, fastMode: restoredFast }+ : undefined,);+ if (remoteSetModelResult?.superseded) {+ if (isSourceSessionCurrent()) {+ setPendingRemoteSwitch(null);+ setSelectedProviderId(initialProviderId ?? null);+ }+ return false;+ }remoteDeferred = remoteSetModelResult?.deferred === true;- await remoteMaker.setEffort(sessionId, targetEffort);+ if (!useAtomicSelection) {+ await remoteMaker.setEffort(sessionId, targetEffort);+ fastPersisted = await persistFastModeChange(restoredFast, {+ silent: true,+ remoteDeviceId: sourceRemoteDeviceId,+ });+ }} catch (err) {if (isSourceSessionCurrent()) {setPendingRemoteSwitch(null);@@ -4550,20 +4792,10 @@ export function ChatInput({t(mapIpcErrorToI18nKey(err, { fallback: 'newChat.chatInput.remoteSwitchFailed' })),);}- return;+ return false;} finally {if (isSourceSessionCurrent()) setRemoteSwitchInFlight(false);}- // 把恢复的 fast 经隧道推给被控端 —— onFastModeChange = makerChatStore.setFastMode,远程会话内部- // 走「乐观 setState(同步)+ maker:set-fast-mode 隧道 + echo 回流」,被控端 set-fast-mode 仅 codex- // 生效、其余 no-op。放在 onModelDidChange 前:setFastMode 的乐观 setState 同步先行,使随后- // handleModelDidChange 据已恢复的 fast 判断,避免误触发「模型已切、Fast 关闭」重置 toast + 多一次隧道。- // Fast 恢复失败只代表 restoredFast 未落盘;model/effort/provider 已在被控端成功落盘,- // 仍正常收尾并同步草稿默认,Fast 保留当前真实值。- const fastPersisted = await persistFastModeChange(restoredFast, {- silent: true,- remoteDeviceId: sourceRemoteDeviceId,- });syncSessionDraftModelPrefs(targetModel,{ effort: targetEffort, fast: fastPersisted ? restoredFast : fastMode },@@ -4597,6 +4829,11 @@ export function ChatInput({const switchSeqBySession = localRuntimeSwitchSeqBySessionRef.current;const rollbackSeq = (switchSeqBySession.get(sessionId) ?? 0) + 1;switchSeqBySession.set(sessionId, rollbackSeq);+ rollbackProviderAfterPersistFailure = {+ model: activeModel,+ providerId: selectedProviderId ?? null,+ seq: rollbackSeq,+ };// deferred = 会话自己在跑,main 已登记 pending、turn 结束自动生效(选择不丢);// DB 照常落盘(重启也生效),但跳过 runtime setEffort/setFastMode —— 会话// turn 结束会被关闭重建,别去动还在跑的旧 turn。@@ -4604,31 +4841,18 @@ export function ChatInput({sessionId,modelId,newProviderId,+ expectedAgentSwitchRevision,+ { effort: eff, fastMode: restoredFast },);+ if (setModelResult?.superseded) {+ rollbackProviderAfterPersistFailure = null;+ return false;+ }const deferredUntilTurnEnd = setModelResult?.deferred === true;- rollbackProviderAfterPersistFailure = {- model: activeModel,- providerId: selectedProviderId ?? null,- seq: rollbackSeq,- };- await sessionService.update(sessionId, {- model: modelId,- effort: eff,- providerId: newProviderId,- fastMode: restoredFast,- });rollbackProviderAfterPersistFailure = null;const effortCoordinator = effortChangeCoordinatorRef.current;effortCoordinator.setCommittedEffort(sessionId, eff);- if (!deferredUntilTurnEnd) {- effortCoordinator.publishRuntimeEffort(sessionId, eff, (targetSessionId, effort) =>- window.electronAPI.maker.setEffort(targetSessionId, effort),- );- // fast 无条件下发,与 handleModelChange 本地分支同口径 —— codex 走 agent fast runtime;- // claude-code 由 main 记 bridge 会话态(切到 chatgpt/ 模型时恢复的 fast 经订阅 handler- // prefs 生效,只在 codex 下发会让 main 内存态滞留旧值);其余在 main 侧安全 no-op。- window.electronAPI.maker.setFastMode(sessionId, restoredFast).catch(() => {});- } else {+ if (deferredUntilTurnEnd) {effortCoordinator.suppressRuntimeEffort(sessionId);toast.success(t('newChat.chatInput.credentialSwitchDeferred'), { duration: 4000 });}@@ -4638,28 +4862,36 @@ export function ChatInput({{ effort: eff, fast: restoredFast },{ activeProviderId: newProviderId, memoryProviderId: newProviderId },);- // fast live 同步:同 handleModelChange —— sessionService.update 写了 DB 但不更新驱动 chip 的- // makerChatStore 快照。目标模型支持 fast 时把恢复值推进快照(切来源 / 同来源换模型都覆盖);+ if (currentModelAgentKind && newProviderId) {+ modelMemory?.setFast(+ currentModelAgentKind,+ newProviderId,+ modelId,+ restoredFast,+ );+ }+ // fast live 同步:host 已原子落 DB/runtime,这里只更新 renderer 快照。+ // 目标模型支持 fast 时把恢复值推进快照(切来源 / 同来源换模型都覆盖);// 不支持 fast 的模型交给 onModelDidChange 的关闭路径(保留 toast)。- // deferred 时跳过:runtime 推送会打到仍在跑的旧 turn;DB 已持久化,重建时生效。+ // deferred 时由 sessions:patched 回流。if (!deferredUntilTurnEnd && modelFastSupported(modelId, newProviderId)) {- void handleFastModeChange(restoredFast, modelId, eff, false, newProviderId);+ makerChatStore.mirrorSessionFields(sessionId, { fastMode: restoredFast });}}onModelDidChange?.(modelId);onEffortDidChange?.(eff, sessionId);remember(modelId, eff);+ return true;};try {// 选源 reconcile:picker 传来新来源下应落到的模型(优先恢复该来源记忆的模型,其次当前// 模型不被 offer 时落到首个可用)。原子应用 model+effort+providerId(避免「先改 model// 再改 provider」的闭包 stale)。effort 优先用记忆带回的 reconciledEffort(resolveSwitchEffort 内校验)。if (reconciledModelId && reconciledModelId !== activeModel) {- await applyModelAndEffort(+ return await applyModelAndEffort(reconciledModelId,resolveSwitchEffort(reconciledModelId, newProviderId, reconciledEffort),);- return;}// 同模型只切来源:effort/fast 采用同一份 (agent,model) 全局预设,但仍按新来源 capability// 校验;不支持的档位回落模型默认。reconciledEffort(来源切换 hint,当前 picker 不传)@@ -4683,7 +4915,7 @@ export function ChatInput({});// applyModelAndEffort 同时按新来源 capability 校验 fast,并把 (activeModel, targetEffort)// 写回模型级全局预设。模型不变,model 字段照写 activeModel(幂等)。- await applyModelAndEffort(activeModel, targetEffort);+ return await applyModelAndEffort(activeModel, targetEffort);} catch (err) {const rollbackProvider = rollbackProviderAfterPersistFailure as {model: string;@@ -4697,13 +4929,20 @@ export function ChatInput({!isRemoteSession) {await window.electronAPI.maker- .setModel(sessionId, rollbackProvider.model, rollbackProvider.providerId)+ .setModel(+ sessionId,+ rollbackProvider.model,+ rollbackProvider.providerId,+ undefined,+ { effort: activeEffort, fastMode },+ ).catch((rollbackErr) => {log.warn('provider change rollback failed:', rollbackErr);});}log.warn('provider change failed:', err);toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'newChat.chatInput.switchFailed' })));+ return false;}},[@@ -4729,6 +4968,7 @@ export function ChatInput({t,confirmModelSwitchContextGuard,performAgentSwitch,+ remoteAtomicModelSelectionSupported,],);@@ -4737,24 +4977,36 @@ export function ChatInput({newProviderId: string | null,reconciledModelId?: string,reconciledEffort?: Effort,- ): Promise<void> => {+ expectedAgentSwitchRevision?: number,+ ): Promise<void | boolean> => {const remoteDeviceId = sessionId? (deviceLinkDeviceId ?? getSessionDeviceId(sessionId)): undefined;if (sessionId && !remoteDeviceId) {return effortChangeCoordinatorRef.current.enqueue(sessionId, () =>- performProviderChange(newProviderId, reconciledModelId, reconciledEffort),+ performProviderChange(+ newProviderId,+ reconciledModelId,+ reconciledEffort,+ expectedAgentSwitchRevision,+ ),);}- return performProviderChange(newProviderId, reconciledModelId, reconciledEffort);+ return performProviderChange(+ newProviderId,+ reconciledModelId,+ reconciledEffort,+ expectedAgentSwitchRevision,+ );},[deviceLinkDeviceId, performProviderChange, sessionId],);// performAgentSwitch 的"选回当前引擎"分支经 ref 调用(两 handler 声明在其后,TDZ)。sameEngineReselectRef.current = {- byProvider: (providerId, modelId) => handleProviderChange(providerId, modelId),- byModel: (modelId) => handleModelChange(modelId),+ byProvider: (providerId, modelId, expectedRevision) =>+ handleProviderChange(providerId, modelId, undefined, expectedRevision),+ byModel: (modelId, expectedRevision) => handleModelChange(modelId, expectedRevision),};const handleNavigateToProviders = useCallback(() => {@@ -4835,6 +5087,8 @@ export function ChatInput({noConnectedSource ||// 会话显式选中的来源已断开 → Send 禁用(trigger 同步显示「已断开」错误态说明原因)。selectedSourceDisconnected ||+ // host 尚未完成切换意图登记时不能发送,否则 maker:send 可能先被旧引擎消费。+ agentSwitchInFlight ||sendDispatchInFlight ||(!voiceInput.isListening && !canSend && !hasVoiceDraftText) ||voiceInput.state === 'submitting' ||@@ -5423,11 +5677,12 @@ export function ChatInput({): undefined}- // session-agent-switch:本机已建会话提供显式两步引擎切换(列表顶部- // Claude/Codex 分段,先选 Agent 再选模型)。草稿(无 sessionId)与- // device-link / SSH 远程会话不传(v1 不支持切换)。+ // session-agent-switch:已建会话提供显式两步引擎切换(列表顶部+ // Claude/Codex 分段,先选 Agent 再选模型)。device-link 远程会话同样+ // 支持(隧道到被控端执行,与手机端同一套 channel),入口按被控端能力位+ // 门控。草稿(无 sessionId)与 SSH 远程会话仍不传。agentSwitch={- sessionId && vendorKey && !deviceLinkDeviceId && !remoteHostId+ sessionId && vendorKey && !remoteHostId && sessionAgentSwitchSupported? {currentVendor: vendorKey,confirmBrowseSwitch: confirmAgentBrowseSwitch,@@ -5452,7 +5707,7 @@ export function ChatInput({onProviderChange={handleProviderChange}onNavigateToProviders={handleNavigateToProviders}switching={remoteSwitchInFlight}- disabled={disabled}+ disabled={disabled || agentSendDispatchInFlight || agentSwitchInFlight}visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}compactToolbar={useNarrowToolbar}ultraCompactToolbar={useUltraCompactToolbar}diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex cc63924785..8320d8d7e8 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -558,7 +558,6 @@ function ModelSelectorContentView({agentSwitch?.currentVendor ?? vendorKey ?? 'cc',);const browseSwitchPendingRef = useRef(false);- const agentSwitchQueueRef = useRef<Promise<void>>(Promise.resolve());const handleBrowseVendorChange = async (next: 'cc' | 'codex') => {if (interactionDisabled || next === browseVendor || browseSwitchPendingRef.current) return;// 返回当前引擎(含已有意图时浏览原引擎准备撤销)不需要确认;只有从@@ -588,15 +587,10 @@ function ModelSelectorContentView({targetProviderId: string | null,) => {if (!agentSwitch) return;- const run = () => agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);- // 配置面板保持可连续操作,但切换事务必须按点击顺序执行:否则较早的请求可能- // 较晚完成并覆盖用户最后一次选择。失败也不能阻断后续已排队的意图。- agentSwitchQueueRef.current = agentSwitchQueueRef.current- .then(run, run)- .then(- () => undefined,- () => undefined,- );+ // 立即交给调用方同步登记目标 session 的 pending token。真正的顺序由+ // agentSwitchCoordinator 按 session 串行;组件级 Promise 队列会把不同 session+ // 错误地串在一起,并在回调尚未启动时留下可发送窗口。+ void agentSwitch.onSwitch(targetAgentKind, targetModelId, targetProviderId);};// 同时拉两个 agent —— vendorKey 不传时把两边模型一起展示。hooks 必须按固定顺序调用。const cc = useAgentCapabilities('claude-code', deviceId);diff --git a/apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts b/apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.tsindex a8422ff874..9741aa9bb5 100644--- a/apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts+++ b/apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts@@ -46,3 +46,77 @@ export async function confirmAgentSwitchRisk({dontShowAgainLabel: copy.dontShowAgainLabel,});}++export interface AgentSwitchResponseFreshness {+ /** 发起方已放弃(effect 清理:切走会话 / 换设备)。同步调用点传 false。 */+ cancelled: boolean;+ /** 发起时的本端写序号 vs 响应到达时的当前值(覆盖「已点选但尚未落 store」的窗口)。 */+ writeSeqAtStart: number;+ writeSeqNow: number;+ /** 发起时的意图修订号 vs 响应到达时的当前值(覆盖任何来源的实际变更)。 */+ intentRevAtStart: number;+ intentRevNow: number;+}++/**+ * device-link 远程会话的异步意图响应是否仍然新鲜(可以落到展示态)。两个调用点同构:+ * 打开 / 重连时的**权威意图读回**,以及切换 IPC 的**登记 ack**——两者都在 await 期间+ * 可能被更新的状态超车,落下去就会让选择器显示过期引擎,与被控端实际要执行的不一致。+ *+ * 判定必须基于**单调计数**,不能比较意图值本身:意图在途期间从 null 变成非空又清回+ * null(本端登记后撤销,或另一窗口 / 被控端经 sessions:patched 来回改)时,值与引用都会+ * 回到相等,过期响应就会被误判为新鲜。+ *+ * 两个计数各管一段:store 修订号覆盖**任何来源**的实际变更(含外部权威回流);本端写序号+ * 覆盖「用户已点选、切换 IPC 还在途、尚未落 store」的空窗。+ */+export function isAgentSwitchResponseFresh(args: AgentSwitchResponseFreshness): boolean {+ if (args.cancelled) return false;+ if (args.writeSeqNow !== args.writeSeqAtStart) return false;+ return args.intentRevNow === args.intentRevAtStart;+}++/** 切换 ack 到达后该做什么。 */+export type AgentSwitchAckAction =+ /** 登记乐观意图(deferred 常态路径)。 */+ | 'apply-intent'+ /** 同引擎 no-op:清掉展示意图,把这次点选当普通模型/来源切换应用到当前引擎。 */+ | 'same-engine-reselect'+ /** 立即切换已完成(harness / registry 缺省兜底),收敛真实引擎。 */+ | 'apply-switched'+ /** 已被更新的状态超车,本次 ack 作废。 */+ | 'discard';++/**+ * 切换 ack 的分派决策。三类判据作用域**不同**,不能一刀切:+ *+ * - **写序号**(本端点选)对所有分支生效:用户又点了一次,本次 ack 整体作废。+ * - **意图修订号**保护「要把本次选择写成乐观意图值」的分支(apply-intent /+ * apply-switched):外部权威值更新,就不能用旧选择盖回去。+ * - 同引擎 no-op 不能从 renderer 的「修订号 + 最终值」猜因果:外部 set→clear ABA 与+ * 本次 clear 都会得到「修订号已变 + 当前为空」。新 host 因此返回 CAS 成功后的+ * `sameEngineRevision`,后续 SET_MODEL 带回该 token 再做一次 CAS;若请求已在 host+ * 内被超车则返回 `sameEngineSuperseded` 直接丢弃。远程入口另由+ * `supportsSessionAgentSwitchCas` 门控,不会向缺 token 的旧 host 开放;这里的无 token+ * 分支只作本地 harness / 防御性兼容,修订号变化时仍 fail-closed。+ */+export function resolveAgentSwitchAckAction(args: {+ deferred: boolean;+ switched: boolean;+ sameEngineRevision?: number;+ sameEngineSuperseded?: boolean;+ freshness: AgentSwitchResponseFreshness;+}): AgentSwitchAckAction {+ const { freshness } = args;+ if (freshness.cancelled) return 'discard';+ if (freshness.writeSeqNow !== freshness.writeSeqAtStart) return 'discard';+ if (args.deferred) return isAgentSwitchResponseFresh(freshness) ? 'apply-intent' : 'discard';+ if (!args.switched) {+ if (args.sameEngineSuperseded) return 'discard';+ if (args.sameEngineRevision !== undefined) return 'same-engine-reselect';+ return freshness.intentRevNow === freshness.intentRevAtStart+ ? 'same-engine-reselect'+ : 'discard';+ }+ return isAgentSwitchResponseFresh(freshness) ? 'apply-switched' : 'discard';+}diff --git a/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts b/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.tsindex 9f1b5fcf20..209d0b26fd 100644--- a/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts+++ b/apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts@@ -16,7 +16,7 @@ export function isSessionScopeCurrent(* 晚完成时会重放当前 revision 的目标 effort,修复 Claude Code runtime 的迟到覆盖。*/export interface EffortChangeCoordinator {- enqueue(sessionId: string, task: () => Promise<void>): Promise<void>;+ enqueue<T>(sessionId: string, task: () => Promise<T>): Promise<T>;getCommittedEffort(sessionId: string): Effort | undefined;setCommittedEffort(sessionId: string, effort: Effort): void;adoptExternalEffort(sessionId: string, effort: Effort, applyRuntime: ApplyRuntimeEffort): void;@@ -88,7 +88,10 @@ export function createEffortChangeCoordinator(): EffortChangeCoordinator {enqueue(sessionId, task) {const lane = getLane(sessionId);const result = lane.commitTail.then(task, task);- lane.commitTail = result.catch(() => undefined);+ lane.commitTail = result.then(+ () => undefined,+ () => undefined,+ );return result;},getCommittedEffort(sessionId) {diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 8ab95604ac..01c49d612d 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -3570,6 +3570,9 @@ export function CCAgentSessionView({: 'claude-code': null}+ // 协同会话不参与跨引擎切换;session 未加载时保留 undefined 未知态,+ // 仅在完整元数据确认非 Orca 后传 null 开放入口。+ sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}initialWorkingDir={session?.workingDir}remoteHostId={session?.remoteHostId ?? null}deviceLinkDeviceId={remoteDeviceId}diff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.tsindex 6bacd7b696..fb0cec7ba6 100644--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts@@ -87,6 +87,18 @@ export interface AgentCapabilities {fork?: CapabilityStatus;/** Session rewind — UserMessage 下方 Rewind icon 据此显示 / 隐藏。 */rewind?: CapabilityStatus;+ /**+ * 同会话跨引擎切换(Claude Code ↔ Codex)。host 级能力,两个 agent 的 capabilities+ * 都带回同一个值;device-link 老被控端无此字段 → undefined = 不支持,控制端隐藏+ * 模型选择器顶部的 Agent 分段(它同时也没收录切换 channel,点了必失败)。+ */+ supportsSessionAgentSwitch?: boolean;+ /**+ * 同引擎重选是否返回可供 SET_MODEL 二次校验的 CAS 修订号。首版切换 host 只有上面的+ * 基础能力位;远程控制端必须同时看到本位才开放入口,避免旧 host 的清除回流先于 ack+ * 到达时无法安全关联后续模型写入。+ */+ supportsSessionAgentSwitchCas?: boolean;}interface MakerApiShape {diff --git a/apps/desktop/src/renderer/lib/agentSwitchCoordinator.ts b/apps/desktop/src/renderer/lib/agentSwitchCoordinator.tsnew file mode 100644index 0000000000..15ec2e4793--- /dev/null+++ b/apps/desktop/src/renderer/lib/agentSwitchCoordinator.ts@@ -0,0 +1,186 @@+/**+ * session-agent-switch 与消息发送的异步协调层(按 session,模块级)。+ * ---------------------------------------------------------------------------+ * 跨引擎切换的每一次点选都会产生一个**跨越 await 的写入**:发 IPC → 等被控端 ack →+ * 落展示态。这条链上有三个归属问题,组件内的 ref 都兜不住:+ *+ * 1. **串行**:被控端 device-link dispatch 对每个 invoke 独立起协程,而+ * sessionAgentSwitchHandler 写 pendingSwitches 前还要 await 路由校验与 DB 读——+ * 并发时较旧的请求可能后落库,覆盖较新的选择。队列必须存在于 **session 生命周期**+ * 而不是组件实例:用户切走再切回时旧组件已卸载但 invoke 仍在飞,新组件若另起一条+ * 空队列就会立刻发出第二次选择,两个请求重新并发。+ * 2. **写序号**(判定「在途期间用户是否又点过」)同理:挂在组件 ref 上会随重挂归零,+ * 旧 ack 就会被误判成新鲜。+ * 3. **会话作用域**:同一路由下 ChatInput 可以换 sessionId 继续渲染,await 返回后必须+ * 确认「当前仍是发起时那个会话」,否则旧会话的响应会写进新会话。+ *+ * 因此这些状态按 sessionId 键控放在模块级,与组件挂载无关;会话被清理时调用+ * `disposeAgentSwitchSession` 释放(不释放也只是留下一个已 settle 的 promise 与一个整数)。+ */++/** 每个 session 一条串行链;值恒为已 catch 的 promise,不会向外抛。 */+const switchQueues = new Map<string, Promise<void>>();+/** 每个 session 的本端写次数(登记 / 撤销 / 选回当前引擎都算一次),单调递增。 */+const writeSeqs = new Map<string, number>();+/** 完整切换操作的在途 token;Set 避免并发点选或 dispose 后旧 finally 误清新操作。 */+const pendingOperations = new Map<string, Set<symbol>>();+/** 发送准备至 maker:send 完成的在途 token;与切换操作互斥,避免动作顺序被 await 反转。 */+const pendingSendDispatches = new Map<string, Set<symbol>>();+const pendingListeners = new Set<() => void>();++function emitPendingChange(): void {+ for (const listener of pendingListeners) listener();+}++/**+ * 推进并返回本次点选的写序号。响应到达时与 `getAgentSwitchWriteSeq` 比对即可判断+ * 「在途期间用户是否又点过」——单调递增,不受 ABA 影响(登记后又撤销时值都回到 null,+ * 序号已 +2)。+ */+export function nextAgentSwitchWriteSeq(sessionId: string): number {+ const next = (writeSeqs.get(sessionId) ?? 0) + 1;+ writeSeqs.set(sessionId, next);+ return next;+}++export function getAgentSwitchWriteSeq(sessionId: string): number {+ return writeSeqs.get(sessionId) ?? 0;+}++/**+ * 把一次切换写入排进该 session 的串行链,保证「发送顺序 = 被控端处理顺序」。+ * 前一个任务的成败都不影响后一个继续(链上只串顺序,不串结果)。+ */+export function runAgentSwitchExclusive<T>(+ sessionId: string,+ task: () => Promise<T>,+): Promise<T> {+ const base = switchQueues.get(sessionId) ?? Promise.resolve();+ const run = base.then(task, task);+ switchQueues.set(+ sessionId,+ run.then(+ () => undefined,+ () => undefined,+ ),+ );+ return run;+}++/**+ * 预占该 session 的串行位置,直到 release 才允许后续任务开始。+ * 用于 host ack 后仍需继续执行 renderer 异步收尾的复合操作,避免后续点选插进两段之间。+ */+export function reserveAgentSwitchExclusive(sessionId: string): {+ ready: Promise<void>;+ release: () => void;+} {+ const base = switchQueues.get(sessionId) ?? Promise.resolve();+ const ready = base.then(() => undefined);+ let releaseGate!: () => void;+ const gate = new Promise<void>((resolve) => {+ releaseGate = resolve;+ });+ switchQueues.set(+ sessionId,+ ready.then(() => gate),+ );++ let released = false;+ return {+ ready,+ release: () => {+ if (released) return;+ released = true;+ releaseGate();+ },+ };+}++/**+ * 登记一次完整的切换操作(含 host ack 后的 renderer 收敛),返回幂等完成函数。+ * pending 状态独立于组件实例,切走再切回或重挂 ChatInput 时发送门禁仍然可靠。+ */+export function beginAgentSwitchOperation(sessionId: string): () => void {+ const token = Symbol(sessionId);+ const tokens = pendingOperations.get(sessionId) ?? new Set<symbol>();+ tokens.add(token);+ pendingOperations.set(sessionId, tokens);+ emitPendingChange();++ let finished = false;+ return () => {+ if (finished) return;+ finished = true;+ const current = pendingOperations.get(sessionId);+ if (!current?.delete(token)) return;+ if (current.size === 0) pendingOperations.delete(sessionId);+ emitPendingChange();+ };+}++export function hasPendingAgentSwitchOperation(sessionId: string): boolean {+ return (pendingOperations.get(sessionId)?.size ?? 0) > 0;+}++/**+ * 登记一次完整发送派发(引用水合、预检、maker:send 与发送后清理),返回幂等完成函数。+ * 状态放在模块级,ChatInput 重挂后新的切换入口仍能看到旧实例尚未完成的发送。+ */+export function beginAgentSendDispatch(sessionId: string): () => void {+ const token = Symbol(sessionId);+ const tokens = pendingSendDispatches.get(sessionId) ?? new Set<symbol>();+ tokens.add(token);+ pendingSendDispatches.set(sessionId, tokens);+ emitPendingChange();++ let finished = false;+ return () => {+ if (finished) return;+ finished = true;+ const current = pendingSendDispatches.get(sessionId);+ if (!current?.delete(token)) return;+ if (current.size === 0) pendingSendDispatches.delete(sessionId);+ emitPendingChange();+ };+}++/**+ * 在没有完整切换操作占用该 session 时同步登记发送。+ *+ * 检查与登记必须收在同一个无 await 的原语里:调用方若先查再跨异步准备,切换可能在+ * 中间插入;反过来,登记成功后切换入口会立刻看见 token 并拒绝,从而保持用户动作顺序。+ * 已有发送 token 不构成拒绝条件——共享 store 发送边界可能嵌套在 ChatInput 从引用水合+ * 阶段持有的外层 token 中,两层各自在自己的 finally 释放。+ */+export function tryBeginAgentSendDispatch(sessionId: string): (() => void) | null {+ if (hasPendingAgentSwitchOperation(sessionId)) return null;+ return beginAgentSendDispatch(sessionId);+}++export function hasPendingAgentSendDispatch(sessionId: string): boolean {+ return (pendingSendDispatches.get(sessionId)?.size ?? 0) > 0;+}++export function subscribeAgentSwitchPending(listener: () => void): () => void {+ pendingListeners.add(listener);+ return () => pendingListeners.delete(listener);+}++/** 会话销毁(purge / 关闭)时释放协调状态。 */+export function disposeAgentSwitchSession(sessionId: string): void {+ switchQueues.delete(sessionId);+ writeSeqs.delete(sessionId);+ const hadPendingSwitch = pendingOperations.delete(sessionId);+ const hadPendingSend = pendingSendDispatches.delete(sessionId);+ const pendingChanged = hadPendingSwitch || hadPendingSend;+ if (pendingChanged) emitPendingChange();+}++/** 仅供测试:清空全部协调状态。 */+export function __resetAgentSwitchCoordinatorForTests(): void {+ switchQueues.clear();+ writeSeqs.clear();+ pendingOperations.clear();+ pendingSendDispatches.clear();+}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 3269e8357b..ce0100571a 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -104,6 +104,7 @@ import {emitPatch,} from '@/lib/sessionsBus';import { createLogger } from '@/lib/logger';+import { tryBeginAgentSendDispatch } from '@/lib/agentSwitchCoordinator';import { getUserPrompt } from '@/lib/userPromptStore';import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';import { buildUserMessageAttachmentPayload } from '@/lib/messageAttachmentPayload';@@ -750,6 +751,13 @@ export interface SessionChatState {agentKind: 'claude-code' | 'codex';/** 下一条消息发送时才由 main 应用的跨引擎切换意图。 */agentSwitchIntent: AgentSwitchIntentRecord | null;+ /**+ * 意图的单调修订号:**任何来源**(本端登记/撤销、被控端 push 回流、另一窗口)真正改变+ * 意图时 +1,只增不减。异步读回的新鲜度判定必须用它,不能比较意图值本身——外部把意图+ * 从 null 改成非空又清回 null 时,值与引用都会回到相等,过期响应会被误判为新鲜而复活+ * 已取消的意图(ABA)。+ */+ agentSwitchIntentRev: number;/*** Remote codex target (P2): SSH host alias from `@cindy/maker-remote-ssh`* pool。null/undefined = 本地 session。ensureInitialMessages 从 DB@@ -1062,6 +1070,7 @@ function createInitialState(): SessionChatState {return {agentKind: 'claude-code',agentSwitchIntent: null,+ agentSwitchIntentRev: 0,remoteHostId: null,messages: [],taskUpdates: EMPTY_TASK_UPDATES,@@ -1128,6 +1137,7 @@ function createInitialState(): SessionChatState {export const EMPTY_SESSION_STATE: SessionChatState = Object.freeze({agentKind: 'claude-code',agentSwitchIntent: null,+ agentSwitchIntentRev: 0,remoteHostId: null,messages: [],taskUpdates: EMPTY_TASK_UPDATES,@@ -5473,6 +5483,22 @@ function runInputProjectionOperation(}));}+/**+ * 会直接触发 Agent 工作的 input 操作统一入口。与纯投影操作分开,避免 setExpanded / 清锁+ * 等内部收尾在切换期间被拒后残留状态;compact / retry / resume 这类用户派发则从 RPC+ * 发起前直到 settle 全程占住发送 token,保持点击顺序。+ */+function runAgentDispatchProjectionOperation(+ sessionId: string,+ invoke: (input: RoutableMaker['input']) => Promise<AgentInputProjection>,+): Promise<{ applied: boolean; projection: AgentInputProjection }> {+ return withAgentSendDispatch(+ sessionId,+ () => Promise.reject(new Error('Agent switch is still in progress')),+ () => runInputProjectionOperation(sessionId, invoke),+ );+}+/*** 会话消息切片的代际号:整体重置切片的路径递增——reloadMessages(rewind / origin* 漂移重载)、clearSessionAfterGuard(/clear)、_purgeSession(删除 / 归档 / LRU 驱逐)、@@ -7188,7 +7214,7 @@ function setQueueExpanded(sessionId: string, expanded: boolean): void {function resumeQueue(sessionId: string): void {if (!sessionId) return;- runInputProjectionOperation(sessionId, (input) => input.resume(sessionId))+ runAgentDispatchProjectionOperation(sessionId, (input) => input.resume(sessionId)).catch((err) => log.warn('resumeQueue failed:', err));}@@ -7440,6 +7466,26 @@ function isRemoteMediaSession(sessionId: string): boolean {);}+/**+ * 共享发送边界:同步完成「无切换在途」检查与发送 token 登记,并保证同步抛错和+ * Promise settle 两条路径都会释放。`task` 仍在当前调用栈内启动,保留 sendMessage+ * 对 planMode 等点击时语义的同步定格。+ */+function withAgentSendDispatch<T>(+ sessionId: string,+ onSwitchPending: () => Promise<T>,+ task: () => Promise<T>,+): Promise<T> {+ const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);+ if (!finishAgentSendDispatch) return onSwitchPending();+ try {+ return task().finally(finishAgentSendDispatch);+ } catch (err) {+ finishAgentSendDispatch();+ return Promise.reject(err instanceof Error ? err : new Error(String(err)));+ }+}+function sendMessage(sessionId: string,text: string,@@ -7456,37 +7502,46 @@ function sendMessage(if ((!text.trim() && (!files || files.length === 0)) || !workingDir)return Promise.resolve(false);- // 非破坏性标注:发送时刻才把矢量笔迹烧录成位图(模型只认位图)。仅在真的- // 存在待烧录附件时才走 async 物化——其余消息保持**全同步**发送路径,守住- // "planMode 点击即消耗 / enqueue 在点击同步栈内发生"的既有语义- // (planReviewDoneRace 测试守护;CI 曾因无条件 await 让步一拍而红)。- if (!needsAnnotationMaterialize(files)) {- return sendMessageCore(- sessionId,- text,- model,- effort,- permissionMode,- workingDir,- files,- mentions,- opts,- );- }- return materializeAnnotatedAttachmentsForSend(files, sessionId, {- stripAnnotationMeta: isRemoteMediaSession(sessionId),- }).then((prepared) =>- sendMessageCore(- sessionId,- text,- model,- effort,- permissionMode,- workingDir,- prepared,- mentions,- opts,- ),+ // 共享发送边界兜住 composer 之外的入口(编辑重发、恢复等)。ChatInput 会从引用+ // 水合阶段先持有一层 token;这里允许嵌套登记,确保未来新增调用方也不会绕过+ // session-agent-switch 的双向互斥。检查与登记同步完成,不给切换插入空窗。+ return withAgentSendDispatch(+ sessionId,+ () => Promise.resolve(false),+ () => {+ // 非破坏性标注:发送时刻才把矢量笔迹烧录成位图(模型只认位图)。仅在真的+ // 存在待烧录附件时才走 async 物化——其余消息保持**全同步**发送路径,守住+ // "planMode 点击即消耗 / enqueue 在点击同步栈内发生"的既有语义+ // (planReviewDoneRace 测试守护;CI 曾因无条件 await 让步一拍而红)。+ if (!needsAnnotationMaterialize(files)) {+ return sendMessageCore(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ files,+ mentions,+ opts,+ );+ }+ return materializeAnnotatedAttachmentsForSend(files, sessionId, {+ stripAnnotationMeta: isRemoteMediaSession(sessionId),+ }).then((prepared) =>+ sendMessageCore(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ prepared,+ mentions,+ opts,+ ),+ );+ },);}@@ -7630,7 +7685,7 @@ function compactSession(// /compact 是控制 turn(上下文压缩), 与 sendUiTrigger 同口径: 显式普通执行,// 不进计划模式、不消耗用户的一次性勾选(false 语义见 SendOptions.planMode)。createOpts.planMode = false;- return runInputProjectionOperation(sessionId, (input) =>+ return runAgentDispatchProjectionOperation(sessionId, (input) =>input.compact(sessionId, createOpts, { userName: currentUserName }),)// RPC 已执行成功时保留既有返回语义;origin 漂移只丢控制端镜像回写。@@ -7680,34 +7735,40 @@ function steerMessage(requestInputProjection(sessionId);return Promise.resolve(false);}- // 同 sendMessage:无待烧录附件走全同步路径;有则物化后进同一核心。- if (!needsAnnotationMaterialize(files)) {- return steerMessageCore(- sessionId,- text,- model,- effort,- permissionMode,- workingDir,- files,- mentions,- opts,- );- }- return materializeAnnotatedAttachmentsForSend(files, sessionId, {- stripAnnotationMeta: isRemoteMediaSession(sessionId),- }).then((prepared) =>- steerMessageCore(- sessionId,- text,- model,- effort,- permissionMode,- workingDir,- prepared,- mentions,- opts,- ),+ return withAgentSendDispatch(+ sessionId,+ () => Promise.resolve(false),+ () => {+ // 同 sendMessage:无待烧录附件走全同步路径;有则物化后进同一核心。+ if (!needsAnnotationMaterialize(files)) {+ return steerMessageCore(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ files,+ mentions,+ opts,+ );+ }+ return materializeAnnotatedAttachmentsForSend(files, sessionId, {+ stripAnnotationMeta: isRemoteMediaSession(sessionId),+ }).then((prepared) =>+ steerMessageCore(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ prepared,+ mentions,+ opts,+ ),+ );+ },);}@@ -7821,6 +7882,9 @@ async function resendBlockedMessage(const state = getOrCreateState(sessionId);const msg = state.messages.find((m) => m.clientId === clientId && m.blockedByGhost);if (!msg) throw new Error('resendBlockedMessage: message not found');+ // 会话行读取也是本次用户重发的一部分;token 必须在第一个 await 前登记。+ const finishAgentSendDispatch = tryBeginAgentSendDispatch(sessionId);+ if (!finishAgentSendDispatch) throw new Error('Agent switch is still in progress');resendBlockedInFlight.add(clientId);try {const row = await sessionService.get(sessionId);@@ -7871,6 +7935,7 @@ async function resendBlockedMessage(}} finally {resendBlockedInFlight.delete(clientId);+ finishAgentSendDispatch();}}@@ -7898,25 +7963,29 @@ function steerQueuedMessage(sessionId: string, clientId: string): Promise<boolearequestInputProjection(sessionId);return Promise.resolve(false);}- return makerApiFor(sessionId)- .input.steer(sessionId, queued, { removeFromQueue: true })- .then((ok) => {- requestInputProjection(sessionId);- return ok;- })- .catch((err) => {- // 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里- // (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。- const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));- setState(sessionId, (s) => ({- ...s,- error: message,- usageLimitRecovery: null,- recoverableError: null,- errorRetryText: null,- }));- return false;- });+ return withAgentSendDispatch(+ sessionId,+ () => Promise.resolve(false),+ () => makerApiFor(sessionId)+ .input.steer(sessionId, queued, { removeFromQueue: true })+ .then((ok) => {+ requestInputProjection(sessionId);+ return ok;+ })+ .catch((err) => {+ // 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里+ // (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。+ const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));+ setState(sessionId, (s) => ({+ ...s,+ error: message,+ usageLimitRecovery: null,+ recoverableError: null,+ errorRetryText: null,+ }));+ return false;+ }),+ );}/**@@ -8080,8 +8149,12 @@ function retryLastError(sessionId: string): Promise<void> {// 续跑语义在 main:coordinator 判定失败 turn 已有 assistant 产出时,用共享英文// 常量 CONTINUE_AFTER_ERROR_PROMPT 替代重发原文(shared/interruptedTurn.ts),// renderer 不传文案、不做判定。- return runInputProjectionOperation(sessionId, (input) => input.retryLastError(sessionId))- .then(() => undefined);+ // retryLastError 在 main 内会先 await 历史查询再入队,必须从点击时刻起占住与+ // Agent 切换共享的发送 token;否则后点的切换能越过这段查询,让重试改由新 Agent 执行。+ return runAgentDispatchProjectionOperation(+ sessionId,+ (input) => input.retryLastError(sessionId),+ ).then(() => undefined);}/**@@ -9149,8 +9222,7 @@ export { UI_ACTION_TRIGGER_PREFIX };* error-tail banner) toasts or恢复红条。*/-function sendUiTrigger(sessionId: string, prompt: string): Promise<void> {- if (!sessionId) return Promise.reject(new Error('sendUiTrigger: empty sessionId'));+function sendUiTriggerCore(sessionId: string, prompt: string): Promise<void> {const state = getOrCreateState(sessionId);const originalTail = state.messages[state.messages.length - 1];// Freeze the row the user acted on before session lookup / dispatch. A fast@@ -9232,6 +9304,15 @@ function sendUiTrigger(sessionId: string, prompt: string): Promise<void> {});}+function sendUiTrigger(sessionId: string, prompt: string): Promise<void> {+ if (!sessionId) return Promise.reject(new Error('sendUiTrigger: empty sessionId'));+ return withAgentSendDispatch(+ sessionId,+ () => Promise.reject(new Error('Agent switch is still in progress')),+ () => sendUiTriggerCore(sessionId, prompt),+ );+}+/*** session-agent-switch:切换 IPC 成功后由 ChatInput 调用。翻转 in-memory* agentKind(事件 reducer 路由 + createOpts 派生都读它)并清掉旧引擎的@@ -9243,7 +9324,16 @@ function noteAgentSwitched(sessionId: string, agentKind: 'claude-code' | 'codex'setState(sessionId, (s) =>s.agentKind === agentKind && s.sdkSessionId === null && s.agentSwitchIntent === null? s- : { ...s, agentKind, sdkSessionId: null, agentSwitchIntent: null },+ : {+ ...s,+ agentKind,+ sdkSessionId: null,+ agentSwitchIntent: null,+ // 意图被真实切换消费掉也是一次变更,在途读回据此作废。+ ...(s.agentSwitchIntent === null+ ? {}+ : { agentSwitchIntentRev: s.agentSwitchIntentRev + 1 }),+ },);}@@ -9268,6 +9358,7 @@ function noteAgentSwitchIntent(effort: opts.effort,fastMode: opts.fastMode,},+ agentSwitchIntentRev: s.agentSwitchIntentRev + 1,}));}@@ -9275,7 +9366,9 @@ function noteAgentSwitchIntent(function clearAgentSwitchIntent(sessionId: string): void {if (!sessionId) return;setState(sessionId, (s) =>- s.agentSwitchIntent === null ? s : { ...s, agentSwitchIntent: null },+ s.agentSwitchIntent === null+ ? s+ : { ...s, agentSwitchIntent: null, agentSwitchIntentRev: s.agentSwitchIntentRev + 1 },);}@@ -9283,6 +9376,75 @@ function getAgentSwitchIntent(sessionId: string): AgentSwitchIntentRecord | nullreturn sessions.get(sessionId)?.agentSwitchIntent ?? null;}+/**+ * 意图的单调修订号(不存在的会话按 0)。异步读回的新鲜度判定读它——值比较会被 ABA+ * (null → 已登记 → null)骗过,修订号不会。+ */+function getAgentSwitchIntentRev(sessionId: string): number {+ return sessions.get(sessionId)?.agentSwitchIntentRev ?? 0;+}++/**+ * main 的 pending 意图投影(PublicAgentSwitchIntent,字段名 targetAgentKind)收窄成+ * store 记录(target)。形状不合法 / 非意图 → null,按「无意图」处理。+ */+function normalizeAgentSwitchIntent(value: unknown): AgentSwitchIntentRecord | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const item = value as Record<string, unknown>;+ if (item.targetAgentKind !== 'claude-code' && item.targetAgentKind !== 'codex') return null;+ if (typeof item.model !== 'string' || item.model.length === 0) return null;+ // providerId 缺失按 null(与 main projectPendingAgentSwitchIntent 的 `?? null` 对齐);+ // 只有出现非 string / 非空值的脏值才判非法,避免协议演进时静默丢掉合法意图。+ if (item.providerId != null && typeof item.providerId !== 'string') return null;+ if (item.effort !== undefined && typeof item.effort !== 'string') return null;+ if (item.fastMode !== undefined && typeof item.fastMode !== 'boolean') return null;+ return {+ target: item.targetAgentKind,+ model: item.model,+ providerId: typeof item.providerId === 'string' ? item.providerId : null,+ ...(typeof item.effort === 'string' && item.effort.length > 0 ? { effort: item.effort } : {}),+ ...(typeof item.fastMode === 'boolean' ? { fastMode: item.fastMode } : {}),+ };+}++function agentSwitchIntentEquals(+ a: AgentSwitchIntentRecord | null,+ b: AgentSwitchIntentRecord | null,+): boolean {+ if (a === b) return true;+ if (!a || !b) return false;+ return (+ a.target === b.target &&+ a.model === b.model &&+ a.providerId === b.providerId &&+ a.effort === b.effort &&+ a.fastMode === b.fastMode+ );+}++/**+ * 「意图的权威态在会话所在端」:被控端(或本机另一个窗口)登记 / 清除 pending 意图后,+ * main 经 sessions:patched 广播 agentSwitchIntent 字段;device-link 远程会话打开时+ * 控制端还会主动读回一次。两条 sink 都汇到这里。+ *+ * 幂等:值等价即 no-op —— 本端乐观登记后收到自己的回声不会重建对象、不触发多余重渲染,+ * 也不会与用户正在进行的选择打架。null / 非法值 = 无意图 → 清除。+ */+function mirrorAgentSwitchIntent(sessionId: string, value: unknown): void {+ if (!sessionId) return;+ const next = normalizeAgentSwitchIntent(value);+ if (agentSwitchIntentEquals(sessions.get(sessionId)?.agentSwitchIntent ?? null, next)) return;+ if (!next) {+ clearAgentSwitchIntent(sessionId);+ return;+ }+ setState(sessionId, (s) => ({+ ...s,+ agentSwitchIntent: next,+ agentSwitchIntentRev: s.agentSwitchIntentRev + 1,+ }));+}+function setSessionRuntime(sessionId: string,opts: { agentKind?: 'claude-code' | 'codex'; fastMode?: boolean; planModeEnabled?: boolean },@@ -9345,6 +9507,7 @@ function mirrorSessionFields(fastMode?: unknown;planModeEnabled?: unknown;agentKind?: unknown;+ agentSwitchIntent?: unknown;agentSwitchIntentCanceled?: unknown;}| null@@ -9352,6 +9515,10 @@ function mirrorSessionFields(): void {if (!sessionId || !patch) return;if (patch.agentSwitchIntentCanceled === true) clearAgentSwitchIntent(sessionId);+ // 意图登记 / 覆盖 / 清除的回流(main onPendingSwitchChanged)。必须判字段存在性:+ // 不带该字段的普通 patch(标题、preview、token 计数…)不能被当成「意图已清空」,+ // 否则任何无关广播都会擦掉用户已登记的切换意图。+ if ('agentSwitchIntent' in patch) mirrorAgentSwitchIntent(sessionId, patch.agentSwitchIntent);// session-agent-switch:引擎翻转必须镜像进 chat in-memory——maker:event 的// reducer 按 state.agentKind 分流(Claude / Codex 两套),非发起窗口若停在旧值,// 新引擎的事件会被旧引擎 reducer 错误处理(2026-07-20 审计实锤)。随引擎翻转@@ -9366,7 +9533,10 @@ function mirrorSessionFields(...s,agentKind: nextKind,sdkSessionId: null,- ...(intentApplied ? { agentSwitchIntent: null } : {}),+ // 意图被真实切换消费 = 一次意图变更,推进修订号让在途读回作废。+ ...(intentApplied+ ? { agentSwitchIntent: null, agentSwitchIntentRev: s.agentSwitchIntentRev + 1 }+ : {}),};});}@@ -9467,6 +9637,10 @@ export const makerChatStore = {noteAgentSwitchIntent,clearAgentSwitchIntent,getAgentSwitchIntent,+ /** 意图的单调修订号;异步读回的新鲜度判定用它,值比较会被 ABA 骗过。 */+ getAgentSwitchIntentRev,+ /** 会话所在端(被控端 / 另一窗口)的权威 pending 意图回流镜像;幂等,值等价即 no-op。 */+ mirrorAgentSwitchIntent,/** Update the displayed context window immediately after local model switches. */setContextWindow,/** MEM-OPT-2: Mark a session view mounted; returns a disposer for unmount. */diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.tsindex 73d19446b3..510a986f3e 100644--- a/apps/desktop/src/renderer/lib/makerTransport.ts+++ b/apps/desktop/src/renderer/lib/makerTransport.ts@@ -39,6 +39,11 @@ type FullMaker = typeof window.electronAPI.maker;export interface RoutableMaker {send: FullMaker['send'];setModel: FullMaker['setModel'];+ // session-agent-switch:跨引擎切换是**会话级**操作,数据真相(pending 意图注册表 ++ // 引擎交接)都在会话所在端。远程会话必须隧道到被控端,否则打到控制端本机 maker 上+ // 会因本机无此 session 直接失败。只读入口供重连 / 重开视图后恢复 main 权威意图。+ switchSessionAgent: FullMaker['switchSessionAgent'];+ getSessionAgentSwitchIntent: FullMaker['getSessionAgentSwitchIntent'];setEffort: FullMaker['setEffort'];setPermissionMode: FullMaker['setPermissionMode'];setFastMode: FullMaker['setFastMode'];@@ -92,6 +97,10 @@ function remoteMakerApi(deviceId: string): RoutableMaker {return {send: t('maker:send') as FullMaker['send'],setModel: t('maker:set-model') as FullMaker['setModel'],+ switchSessionAgent: t('maker:switch-session-agent') as FullMaker['switchSessionAgent'],+ getSessionAgentSwitchIntent: t(+ 'maker:get-session-agent-switch-intent',+ ) as FullMaker['getSessionAgentSwitchIntent'],setEffort: t('maker:set-effort') as FullMaker['setEffort'],setPermissionMode: t('maker:set-permission-mode') as FullMaker['setPermissionMode'],setFastMode: t('maker:set-fast-mode') as FullMaker['setFastMode'],diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex f626aad69a..59c21cd3ee 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4436,7 +4436,9 @@ interface ElectronAPI {sessionId: string,model: string,providerId?: string | null,- ) => Promise<{ deferred: boolean } | undefined>;+ expectedAgentSwitchRevision?: number,+ selection?: { effort: string; fastMode: boolean },+ ) => Promise<{ deferred: boolean; superseded?: boolean } | undefined>;/*** session-agent-switch:同一会话切换 agent 引擎(claude-code ↔ codex)。* 同引擎换模型走 setModel;跨引擎必须走本方法。意图制:本调用只登记切换@@ -4451,7 +4453,20 @@ interface ElectronAPI {providerId?: string | null,effort?: string,fastMode?: boolean,- ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean }>;+ ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }>;+ /**+ * 读 main 权威的 pending 切换意图(内存态,不落库;无意图 → null)。+ * 重开视图 / device-link 远程会话重连后恢复乐观显示用。+ */+ getSessionAgentSwitchIntent: (+ sessionId: string,+ ) => Promise<{+ targetAgentKind: 'claude-code' | 'codex';+ model: string;+ providerId: string | null;+ effort?: string;+ fastMode?: boolean;+ } | null>;// effort/mode 透传 string —— 合法值由 maker capabilities 决定, vite-env 不重复枚举setEffort: (sessionId: string, effort: string) => Promise<void>;setPermissionMode: (sessionId: string, mode: string) => Promise<void>;