Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 修复远程切换模型参数错误 (#1527)
Dasha0e52f32cf2f
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex fe38763582..690664ea7f 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -36,7 +36,12 @@ import {type ActiveController,} from '../device-link/dispatch';import { __testing as registry, dispatchLocalInvoke } from '../device-link/invoke-registry';-import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../device-link/invoke-context';+import {+ deviceLinkInvokeControllerSupports,+ getDeviceLinkInvokeContext,+ isDeviceLinkInvoke,+} from '../device-link/invoke-context';+import * as subscriptions from '../device-link/subscriptions';beforeEach(() => {remoteControlEnabled = true;@@ -100,6 +105,30 @@ describe('runInvoke 双层校验', () => {expect(isDeviceLinkInvoke()).toBe(false);});+ it('能力查询只信任当前 device-link controller context,未知控制端 fail closed', async () => {+ subscriptions.subscribe(+ 'ctrl-cap',+ ['sessions'],+ 'Desktop',+ [CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1],+ );+ subscriptions.subscribe('ctrl-legacy', ['sessions'], 'Legacy');+ registry.register('maker:list-active', () => ({+ explicitProviderNull: deviceLinkInvokeControllerSupports(+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ ),+ }));++ await expect(runInvoke('ctrl-cap', { channel: 'maker:list-active', args: [] })).resolves.toEqual({+ ok: true,+ result: { explicitProviderNull: true },+ });+ await expect(runInvoke('ctrl-legacy', { channel: 'maker:list-active', args: [] })).resolves.toEqual({+ ok: true,+ result: { explicitProviderNull: false },+ });+ });+it('本机 handler 抛 throwIpcError → IPC_ERROR 透传 [CODE] message', async () => {registry.register('maker:send', () => {const e = new Error('[SESSION_RUNNING] busy');@@ -388,6 +417,7 @@ import {} from '../device-link/dispatch';import { hasBroadcastTapListener, tapWindowBroadcast } from '../device-link/broadcast-tap';import {+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,DeviceLinkError,SESSION_ACTIVITY_CHANNEL,type Envelope,diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 9a481f670f..63b346cd02 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -466,6 +466,22 @@ describe('sendToSession ordering', () => {expectOrder(directSendSwitchBlock, 'applyPendingAgentSwitchIfIdle(', 'return release;');});+ it('仅 Device Link 归一化 SET_MODEL 的 JSON null 可选占位,本地仍走严格校验', () => {+ const setModelBlock = extractBetween(+ source,+ 'ipcMain.handle(MAKER_INVOKE.SET_MODEL',+ 'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',+ );+ expect(setModelBlock).toContain('normalizeDeviceLinkSetModelWireArgs(');+ expect(setModelBlock).toContain('isDeviceLinkInvoke(),');+ expect(setModelBlock).toContain(+ 'expectedAgentSwitchRevision = normalizedWireArgs.expectedAgentSwitchRevision;',+ );+ expect(setModelBlock).toContain('selection = normalizedWireArgs.selection;');+ expect(setModelBlock).toContain('expectedAgentSwitchRevision must be a non-negative integer');+ expect(setModelBlock).toContain('selection must contain effort + fastMode');+ });+it('publishes Agent Island prompt preview from send intent and wires commit rollback', () => {const makerSendCreateDbMessageBlock = extractBetween(source,diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex 1634a4f565..3eb33cf2dc 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -11,6 +11,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import {DeviceLinkError,+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,DL_SUBSCRIBE_CHANNEL,MAX_FRAME_BYTES,PROTOCOL_VERSION,@@ -550,7 +551,12 @@ describe('[13] forwardPush — 转发失败 best-effort,不冒泡', () => {it('remembered modern link-open waits for an explicit subscribe frame', () => {const client = mkClient();__testing.setActiveClient(client as never);- subscriptions.subscribe('ctrl-modern', ['session:s1']);+ subscriptions.subscribe(+ 'ctrl-modern',+ ['session:s1'],+ 'Desktop',+ [CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1],+ );subscriptions.clearController('ctrl-modern');__testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });@@ -558,12 +564,16 @@ describe('[13] forwardPush — 转发失败 best-effort,不冒泡', () => {controllerName: 'Mobile',protocolVersion: 1,appVersion: '1.0.0',- capabilities: [],+ capabilities: [CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1],});expect(client.sendLinkAccept).toHaveBeenCalledTimes(1);expect(client.sendPush).not.toHaveBeenCalled();expect(subscriptions.__testing.topicsOf('ctrl-modern')).toEqual([]);+ expect(subscriptions.controllerSupports(+ 'ctrl-modern',+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ )).toBe(true);const result = __testing.handleSubscriptionFrame('ctrl-modern', {channel: DL_SUBSCRIBE_CHANNEL,diff --git a/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts b/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.tsindex d6bbdf48a1..088c7700c7 100644--- a/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts@@ -34,12 +34,18 @@ describe('subscriptions topic lifecycle listeners', () => {expect(subscribed).toHaveBeenCalledTimes(2);});- it('keeps negotiated controller capabilities until the controller is cleared', () => {+ it('keeps negotiated controller capabilities across disconnect, then clears on revocation', () => {subscriptions.subscribe('c1', ['sessions'], 'Phone', ['provider-logo-kinds-v2']);expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(true);subscriptions.subscribe('c1', ['session:s1'], 'Phone');expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(true);subscriptions.clearController('c1');+ expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(true);+ subscriptions.updateControllerMetadata('c1', 'Phone', []);+ expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(false);+ subscriptions.subscribe('c1', ['sessions'], 'Phone', ['provider-logo-kinds-v2']);+ subscriptions.clearController('c1');+ subscriptions.forgetKnownController('c1');expect(subscriptions.controllerSupports('c1', 'provider-logo-kinds-v2')).toBe(false);});diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 2b39681a4c..1a8353f0ed 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -16,6 +16,7 @@ import WebSocket from 'ws';import {DeviceLinkClient,CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,DL_CONTACTS_SYNC_CHANNEL,DL_SUBSCRIBE_CHANNEL,DL_UNSUBSCRIBE_CHANNEL,@@ -1159,7 +1160,10 @@ export async function openRemoteLink(deviceId: string): Promise<LinkAcceptPayloacontrollerName: deviceName(),protocolVersion: 1,appVersion: app.getVersion(),- capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],+ capabilities: [+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ ],});openLinkInFlight.set(deviceId, request);const cleanup = (): void => {@@ -1249,7 +1253,10 @@ export async function remoteSubscribe({topics,controllerName: deviceName(),- capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],+ capabilities: [+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ ],},],});diff --git a/apps/desktop/src/main/device-link/invoke-context.ts b/apps/desktop/src/main/device-link/invoke-context.tsindex 5f5b8950ae..f22ab44f8e 100644--- a/apps/desktop/src/main/device-link/invoke-context.ts+++ b/apps/desktop/src/main/device-link/invoke-context.ts@@ -9,6 +9,7 @@import { AsyncLocalStorage } from 'node:async_hooks';import { isMobilePlatform } from './controllerPlatform';+import * as subscriptions from './subscriptions.js';export interface DeviceLinkInvokeContext {controllerDeviceId: string;@@ -64,3 +65,15 @@ export function isDeviceLinkInvoke(): boolean {export function isMobileControllerInvoke(): boolean {return isMobilePlatform(storage.getStore()?.controllerPlatform);}++/**+ * 查询当前可信 device-link 控制端在 link-open / subscribe 中声明的能力。+ * 本地 IPC、缺少上下文或未知控制端均 fail closed。+ */+export function deviceLinkInvokeControllerSupports(capability: string): boolean {+ const context = storage.getStore();+ return (+ context !== undefined &&+ subscriptions.controllerSupports(context.controllerDeviceId, capability)+ );+}diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.tsindex 7cb435a91d..99afbaca6d 100644--- a/apps/desktop/src/main/device-link/subscriptions.ts+++ b/apps/desktop/src/main/device-link/subscriptions.ts@@ -42,6 +42,12 @@ const knownControllerIds = new Set<string>();* session push 被错误地补发给只订阅 sessions 或其它 session 的控制端。*/const rememberedTopicsByController = new Map<string, Set<StoredTopic>>();+/**+ * link-open/subscribe 协商出的能力也要跨普通断线保留。link-open 会先恢复+ * controller metadata、再等现代控制端 replay subscribe;这段窗口内不能把+ * 新控制端误判成 legacy,否则 set-model 的显式 provider null 会被当成占位。+ */+const rememberedCapabilitiesByController = new Map<string, Set<string>>();/*** topic 生命周期监听(fs-watch 档消费:订阅驱动被控端文件 watch 启停)。@@ -103,6 +109,10 @@ function getOrCreate(deviceId: string, name?: string): ControllerEntry {return e;}+function normalizeCapabilities(capabilities: readonly string[]): Set<string> {+ return new Set(capabilities.filter((value) => typeof value === 'string'));+}+/** 订阅:把 topics 并入该控制端(name 可选,subscribe/link-open 携带时更新)。 */export function subscribe(deviceId: string,@@ -115,7 +125,8 @@ export function subscribe(knownControllerIds.add(deviceId);const e = getOrCreate(deviceId, name);if (capabilities) {- e.capabilities = new Set(capabilities.filter((value) => typeof value === 'string'));+ e.capabilities = normalizeCapabilities(capabilities);+ rememberedCapabilitiesByController.set(deviceId, new Set(e.capabilities));}for (const t of topics) e.topics.add(t as StoredTopic);// Remember the topic contract across ordinary disconnects, but not across explicit revocation.@@ -133,11 +144,14 @@ export function updateControllerMetadata(capabilities?: readonly string[],): void {const e = registry.get(deviceId);- if (!e) return;- e.name = name;if (capabilities) {- e.capabilities = new Set(capabilities.filter((value) => typeof value === 'string'));+ const normalized = normalizeCapabilities(capabilities);+ rememberedCapabilitiesByController.set(deviceId, new Set(normalized));+ if (e) e.capabilities = normalized;}+ // Do not recreate a topic entry during link-open; modern controllers must still+ // replay subscribe before their remembered topics become active.+ if (e) e.name = name;}export function controllerHasTopic(deviceId: string, topic: string): boolean {@@ -178,6 +192,7 @@ export function forgetKnownController(deviceId: string): void {clearController(deviceId);knownControllerIds.delete(deviceId);rememberedTopicsByController.delete(deviceId);+ rememberedCapabilitiesByController.delete(deviceId);}/** 清空所有订阅(登出 / 关被控 / 退出)。 */@@ -187,6 +202,7 @@ export function clearAll(): void {registry.clear();knownControllerIds.clear();rememberedTopicsByController.clear();+ rememberedCapabilitiesByController.clear();held.delete(LEGACY_TOPIC);notifyReleased([...held]);}@@ -236,7 +252,8 @@ export function getControllersForTopic(topic: Topic): string[] {/** 查询 link-open 协商出的控制端能力;未知/已断链控制端一律 false。 */export function controllerSupports(deviceId: string, capability: string): boolean {- return registry.get(deviceId)?.capabilities.has(capability) === true;+ return registry.get(deviceId)?.capabilities.has(capability) === true+ || rememberedCapabilitiesByController.get(deviceId)?.has(capability) === true;}function isControlTopic(t: StoredTopic): boolean {@@ -274,6 +291,7 @@ export const __testing = {registry.clear();knownControllerIds.clear();rememberedTopicsByController.clear();+ rememberedCapabilitiesByController.clear();},/** 测试用:查某控制端当前订阅的 topic 集合。 */topicsOf(deviceId: string): string[] {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/setModelWireArgs.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/setModelWireArgs.test.tsnew file mode 100644index 0000000000..51574b1f6e--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/setModelWireArgs.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { normalizeDeviceLinkSetModelWireArgs } from '../setModelWireArgs.js';++describe('normalizeDeviceLinkSetModelWireArgs', () => {+ it('将旧控制端完整 5 槽位的 JSON optional null 还原成未提供', () => {+ expect(normalizeDeviceLinkSetModelWireArgs(true, false, null, null, null)).toEqual({+ providerId: undefined,+ expectedAgentSwitchRevision: undefined,+ selection: undefined,+ });+ });++ it('新 capability 允许短参数调用中的 providerId null 表示明确清除', () => {+ expect(normalizeDeviceLinkSetModelWireArgs(true, true, null, undefined, undefined)).toEqual({+ providerId: null,+ expectedAgentSwitchRevision: undefined,+ selection: undefined,+ });+ });++ it('旧控制端带原子 selection 也把 provider null 视为占位', () => {+ const selection = { effort: 'high', fastMode: false };+ expect(normalizeDeviceLinkSetModelWireArgs(true, false, null, null, selection)).toEqual({+ providerId: undefined,+ expectedAgentSwitchRevision: undefined,+ selection,+ });+ });++ it('新 capability 带原子 selection 时保留显式 provider null', () => {+ const selection = { effort: 'high', fastMode: false };+ expect(normalizeDeviceLinkSetModelWireArgs(true, true, null, null, selection)).toEqual({+ providerId: null,+ expectedAgentSwitchRevision: undefined,+ selection,+ });+ });++ it('本地 IPC 不放宽 null 校验', () => {+ expect(normalizeDeviceLinkSetModelWireArgs(false, false, null, null, null)).toEqual({+ providerId: null,+ expectedAgentSwitchRevision: null,+ selection: null,+ });+ });++ it('保留有效的远程 revision / selection 值', () => {+ const selection = { effort: 'high', fastMode: false };+ expect(normalizeDeviceLinkSetModelWireArgs(true, false, 'provider-a', 3, selection)).toEqual({+ providerId: 'provider-a',+ expectedAgentSwitchRevision: 3,+ selection,+ });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 85abaddad5..a97328c74b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -30,7 +30,10 @@ import type {import { createId } from '@paralleldrive/cuid2';import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';-import { DL_SESSION_REFERENCE_CAPABILITY_CHANNEL } from '@cindy/device-link';+import {+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,+} from '@cindy/device-link';import { and, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';import { getActiveAppSession } from '../appSessionState.js';@@ -545,6 +548,7 @@ import {} from '../maker-host/codex-credential-switch.js';import { applyRuntimeSetModelChange } from './runtimeSetModel.js';import { applyRuntimeEffortWithRecovery } from './runtimeSetEffort.js';+import { normalizeDeviceLinkSetModelWireArgs } from './setModelWireArgs.js';import { PendingCredentialSwitchService } from './pendingCredentialSwitch.js';import {DeferredCodexRestartService,@@ -565,7 +569,11 @@ import {setRemoteWorkingDirGuard as setDeviceLinkRemoteWorkingDirGuard,setRemoteSettingsPersist as setDeviceLinkRemoteSettingsPersist,} from '../device-link/dispatch.js';-import { isDeviceLinkInvoke, isMobileControllerInvoke } from '../device-link/invoke-context.js';+import {+ deviceLinkInvokeControllerSupports,+ isDeviceLinkInvoke,+ isMobileControllerInvoke,+} from '../device-link/invoke-context.js';import {buildMobileClientPromptNote,stampMobileClientOrigin,@@ -9415,6 +9423,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (typeof sessionId !== 'string' || typeof model !== 'string') {throwIpcError('INVALID_PARAMS', 'sessionId + model required');}+ const normalizedWireArgs = normalizeDeviceLinkSetModelWireArgs(+ isDeviceLinkInvoke(),+ deviceLinkInvokeControllerSupports(+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ ),+ providerId,+ expectedAgentSwitchRevision,+ selection,+ );+ providerId = normalizedWireArgs.providerId;+ expectedAgentSwitchRevision = normalizedWireArgs.expectedAgentSwitchRevision;+ selection = normalizedWireArgs.selection;if (providerId !== undefined &&providerId !== null &&diff --git a/apps/desktop/src/main/maker-ipc/setModelWireArgs.ts b/apps/desktop/src/main/maker-ipc/setModelWireArgs.tsnew file mode 100644index 0000000000..e2baf6b505--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/setModelWireArgs.ts@@ -0,0 +1,36 @@+/**+ * Device Link 的 maker:set-model 参数兼容。+ *+ * JSON 数组无法保留 undefined:中间的可选参数会变成 null,尾部的可选参数+ * 也会留下一个多余的 null。这里把 Device Link wire 层的可选占位归一化回+ * 本地 IPC handler 期望的 undefined;本地 IPC 不应调用此 helper。+ *+ * `providerId: null` 的语义由控制端 capability 决定:旧控制端没有能力声明时,+ * 它一律是 JSON positional 占位并还原成 undefined;新控制端明确声明能力后,+ * null 才表示清除 provider。revision / selection 的 null 在 Device Link 中始终+ * 是 optional 占位。+ */+export function normalizeDeviceLinkSetModelWireArgs(+ isDeviceLink: boolean,+ controllerSupportsExplicitProviderNull: boolean,+ providerId: unknown,+ expectedAgentSwitchRevision: unknown,+ selection: unknown,+): {+ providerId: unknown;+ expectedAgentSwitchRevision: unknown;+ selection: unknown;+} {+ if (!isDeviceLink) {+ return { providerId, expectedAgentSwitchRevision, selection };+ }+ return {+ providerId:+ providerId === null && !controllerSupportsExplicitProviderNull+ ? undefined+ : providerId,+ expectedAgentSwitchRevision:+ expectedAgentSwitchRevision === null ? undefined : expectedAgentSwitchRevision,+ selection: selection === null ? undefined : selection,+ };+}diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.tsindex e57734bd8e..c2160c14b1 100644--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts@@ -115,6 +115,61 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {expect(makerSpies.setEffort).not.toHaveBeenCalled();});+ it('远程 setModel 压缩 JSON 可选参数,保留中间占位且裁掉尾部 null', async () => {+ const { invoke } = stubElectron();+ const { makerApiForDevice } = await import('@/lib/makerTransport');+ const api = makerApiForDevice('dev-wire');+ const selection = { effort: 'high', fastMode: true };++ await api.setModel('rs', 'model-only');+ await api.setModel('rs', 'with-provider', 'provider-a');+ await api.setModel('rs', 'with-revision', null, 7);+ await api.setModel('rs', 'with-selection', 'provider-b', undefined, selection);++ expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', [+ 'rs',+ 'model-only',+ ]);+ expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', [+ 'rs',+ 'with-provider',+ 'provider-a',+ ]);+ expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', [+ 'rs',+ 'with-revision',+ null,+ 7,+ ]);+ expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', [+ 'rs',+ 'with-selection',+ 'provider-b',+ null,+ selection,+ ]);+ const lastArgs = invoke.mock.calls.at(-1)?.[2] as unknown[];+ expect(lastArgs).toHaveLength(5);+ expect(lastArgs.at(-1)).toBe(selection);+ });++ it('远程 setModel 拒绝省略 provider 但携带 revision 或 selection 的歧义调用', async () => {+ const { invoke } = stubElectron();+ const { makerApiForDevice } = await import('@/lib/makerTransport');+ const api = makerApiForDevice('dev-ambiguous');++ await expect(api.setModel('rs', 'with-revision', undefined, 7)).rejects.toThrow(+ /providerId is required/,+ );+ await expect(+ api.setModel('rs', 'with-selection', undefined, undefined, {+ effort: 'high',+ fastMode: true,+ }),+ ).rejects.toThrow(/providerId is required/);+ expect(invoke).not.toHaveBeenCalled();+ });+it('远程会话 patchMeta(删/归档/改名/置顶)经隧道 local-db:sessions:patch-meta', async () => {const { invoke } = stubElectron();const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.tsindex eb4eb4820b..f081badf83 100644--- a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts@@ -881,6 +881,15 @@ describe('ChatInput 的入口门控与调用路由', () => {expect(source).toContain(': makerApiFor(sourceSessionId);');});+ it('远程只切模型沿用当前 provider,避免 JSON optional 占位清除来源', () => {+ const start = source.indexOf('const performModelChange = useCallback(');+ const end = source.indexOf('const handleModelChange = useCallback(', start);+ const body = source.slice(start, end);+ expect(body).toMatch(+ /remoteMaker\.setModel\(\s*sessionId,\s*newModelId,\s*selectedProviderId,\s*expectedAgentSwitchRevision,/,+ );+ });+it('await 返回后做会话作用域校验:旧会话响应不得借最新 ref 写进当前会话', () => {expect(source).toContain('if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return;',diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 34ca6f3018..0b04a21991 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -4469,7 +4469,7 @@ export function ChatInput({const remoteSetModelResult = await remoteMaker.setModel(sessionId,newModelId,- undefined,+ selectedProviderId,expectedAgentSwitchRevision,useAtomicSelection? { effort: newEffort, fastMode: restoredFast }diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 2196c93320..8e5a604e07 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,5 +1,6 @@{"ipcError": {+ "INVALID_PARAMS": "Invalid input. Please check and try again.","SESSION_RUNNING": "This session is currently running a task. Please try again shortly.","PI_IMAGE_INPUT_UNSUPPORTED": "Image input is not enabled for the current Pi model. Switch to a model that supports images. For a custom model, enable “Supports image input” in provider settings, then start a new Pi task.","CREDENTIAL_SWITCH_BUSY": "Another Codex task is still running, so this provider switch was not applied (the session keeps its previous provider). Try again after those tasks finish.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex da5669ccb6..2fb9e697b9 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,5 +1,6 @@{"ipcError": {+ "INVALID_PARAMS": "パラメータが無効です。確認して再試行してください。","SESSION_RUNNING": "このセッションは現在タスクを実行中です。しばらくしてからもう一度お試しください。","PI_IMAGE_INPUT_UNSUPPORTED": "現在の Pi モデルでは画像入力が有効になっていません。画像に対応するモデルへ切り替えてください。カスタムモデルの場合は、プロバイダー設定で「画像入力に対応」を有効にしてから、新しい Pi タスクを開始してください。","CREDENTIAL_SWITCH_BUSY": "他の Codex タスクが実行中のため、今回のプロバイダー切り替えは適用されませんでした(セッションは元のプロバイダーのままです)。他のタスクが終わってからもう一度お試しください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6f8e007738..4e706fe378 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,5 +1,6 @@{"ipcError": {+ "INVALID_PARAMS": "매개변수가 잘못되었습니다. 확인 후 다시 시도하세요.","SESSION_RUNNING": "이 세션은 현재 작업을 실행 중입니다. 잠시 후 다시 시도해 주세요.","PI_IMAGE_INPUT_UNSUPPORTED": "현재 Pi 모델에는 이미지 입력이 활성화되어 있지 않습니다. 이미지를 지원하는 모델로 전환하세요. 사용자 지정 모델이라면 제공자 설정에서 ‘이미지 입력 지원’을 켠 다음 새 Pi 작업을 시작하세요.","CREDENTIAL_SWITCH_BUSY": "다른 Codex 작업이 실행 중이어서 이번 제공자 전환은 적용되지 않았습니다(세션은 기존 제공자를 유지합니다). 다른 작업이 끝난 후 다시 시도해 주세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e08642851f..96c60a3ba1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,5 +1,6 @@{"ipcError": {+ "INVALID_PARAMS": "参数无效,请检查后重试。","SESSION_RUNNING": "当前任务正在运行,请稍后再试。","PI_IMAGE_INPUT_UNSUPPORTED": "当前 Pi 模型未启用图片输入。请切换到支持图片的模型;如果这是自定义模型,请在供应商设置中开启“支持图片输入”,然后新建 Pi 任务。","CREDENTIAL_SWITCH_BUSY": "Codex 正在其它任务中运行,本次来源切换未生效(本任务仍使用原来源)。等它结束后再试。",diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.tsindex dcc735b910..d63be1f622 100644--- a/apps/desktop/src/renderer/lib/makerTransport.ts+++ b/apps/desktop/src/renderer/lib/makerTransport.ts@@ -89,16 +89,51 @@ function invokeRemote(deviceId: string, channel: string, args: unknown[]): Promireturn window.electronAPI.deviceLink.invoke(deviceId, channel, args);}-/** 远程被控设备的 maker 操作适配器:每个方法把入参原样隧道到对应 channel。 */+type SetModelArgs = Parameters<FullMaker['setModel']>;++/**+ * maker:set-model 的 wire 参数不能直接原样转发:Device Link 通过 JSON 传数组,+ * undefined 会变成 null。保留中间参数的 null 占位,但裁掉尾部多余的 undefined,+ * 使被控端能区分 providerId / revision / selection 的位置而不收到假的尾参。+ */+function buildRemoteSetModelArgs(args: SetModelArgs): unknown[] {+ const [sessionId, model, providerId, expectedAgentSwitchRevision, selection] = args;+ if (+ providerId === undefined &&+ (expectedAgentSwitchRevision !== undefined || selection !== undefined)+ ) {+ throw new Error(+ '[INVALID_PARAMS] providerId is required when expectedAgentSwitchRevision or selection is provided',+ );+ }+ const wireArgs: unknown[] = [sessionId, model];+ if (+ providerId !== undefined ||+ expectedAgentSwitchRevision !== undefined ||+ selection !== undefined+ ) {+ wireArgs.push(providerId === undefined ? null : providerId);+ }+ if (expectedAgentSwitchRevision !== undefined || selection !== undefined) {+ wireArgs.push(+ expectedAgentSwitchRevision === undefined ? null : expectedAgentSwitchRevision,+ );+ }+ if (selection !== undefined) wireArgs.push(selection);+ return wireArgs;+}++/** 远程被控设备的 maker 操作适配器:每个方法把入参隧道到对应 channel。 */function remoteMakerApi(deviceId: string): RoutableMaker {- // 入参顺序与 window.electronAPI.maker.* / maker:* handler 完全一致,原样转发即可。+ // 除 setModel 外,入参顺序与 window.electronAPI.maker.* / maker:* handler 完全一致。const t =(channel: string) =>(...args: unknown[]): Promise<unknown> =>invokeRemote(deviceId, channel, args);return {send: t('maker:send') as FullMaker['send'],- setModel: t('maker:set-model') as FullMaker['setModel'],+ setModel: (async (...args: SetModelArgs) =>+ invokeRemote(deviceId, 'maker:set-model', buildRemoteSetModelArgs(args))) as FullMaker['setModel'],switchSessionAgent: t('maker:switch-session-agent') as FullMaker['switchSessionAgent'],getSessionAgentSwitchIntent: t('maker:get-session-agent-switch-intent',diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.tsindex b9e4983d91..328f5414d8 100644--- a/packages/device-link/src/protocol.ts+++ b/packages/device-link/src/protocol.ts@@ -114,6 +114,10 @@ export interface LinkOpenPayload {/** 控制端能安全消费完整 ProviderLogoKind(含 #527 新增品牌)的 maker:provider:list 投影。 */export const CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 = 'provider-logo-kinds-v2';+/** 控制端能区分 set-model 中显式 providerId:null 与 JSON optional 占位。 */+export const CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1 =+ 'set-model-explicit-provider-null-v1';+export interface LinkAcceptPayload {appVersion: string;/** 被控端 allowlist 的指纹,便于控制端探测版本差异 */