Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(remote-agent): 对齐手机模型列表并支持任务中途换电脑
Liziefed9e435409
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 20bfed12ea..392d5ba165 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -644,6 +644,8 @@ export async function applyAgentSwitchToSessionRow(effort?: string;fastMode?: boolean;contextWindow?: number | null;+ /** 远程 Agent 换电脑:undefined = 不动,null = 改回任务所在电脑。 */+ agentDeviceId?: string | null;},): Promise<void> {const ownerScope = captureOwnerScope();@@ -656,6 +658,7 @@ export async function applyAgentSwitchToSessionRow(updatedAt: Date.now(),};if (patch.providerId !== undefined) setObj.providerId = patch.providerId;+ if (patch.agentDeviceId !== undefined) setObj.agentDeviceId = patch.agentDeviceId;// effort 值域由 renderer 按目标引擎 capabilities 解析(schema 列是字面量联合,// 跨层传输后此处以 string 到达;非法值与直改 DB 同级,运行时由引擎侧收敛)。// 固定 effort 模型运行时为 null;sessions.effort NOT NULL,省略该字段。@@ -682,6 +685,7 @@ export async function applyAgentSwitchToSessionRow(model: patch.model,sdkSessionId: nextSdkSessionId,...(patch.providerId !== undefined ? { providerId: patch.providerId } : {}),+ ...(patch.agentDeviceId !== undefined ? { agentDeviceId: patch.agentDeviceId } : {}),...(persistableEffort !== undefined ? { effort: persistableEffort } : {}),...(patch.fastMode !== undefined ? { fastMode: patch.fastMode } : {}),...(typeof patch.contextWindow === 'number' && patch.contextWindow > 0diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex c3bc95c808..83fb945da3 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -1203,3 +1203,142 @@ describe('landed user route selection', () => {expect(pending.get('s1')).toBeDefined();});});++describe('远程 Agent:选模型时换 Agent 所在电脑', () => {+ function relocationHarness(rowOverrides: Partial<AgentSwitchSessionRow> = {}) {+ const pending = createPendingAgentSwitchRegistry();+ const row = makeRow({ agentDeviceId: 'studio-mac', providerId: 'anthropic', ...rowOverrides });+ const selectSameAgentModel = vi.fn(async (id: string, intent: PendingAgentSwitchIntent) => {+ pending.set(id, intent);+ return { deferred: true };+ });+ const assertAgentDeviceRouteUsable = vi.fn(async () => undefined);+ const findParkedEngineSession = vi.fn(async () => ({+ sdkSessionId: 'sdk-parked',+ watermarkCreatedAt: 1,+ watermarkRowid: 1,+ }));+ const { deps, calls } = makeDeps({+ pendingSwitches: pending,+ getSessionRow: vi.fn(async () => row),+ selectSameAgentModel,+ assertAgentDeviceRouteUsable,+ findParkedEngineSession,+ describeAgentDevice: (deviceId) => (deviceId ? 'Studio Mac' : 'Office PC'),+ });+ return { deps, calls, pending, selectSameAgentModel, assertAgentDeviceRouteUsable, findParkedEngineSession };+ }++ const backToTaskComputer = {+ sessionId: 's1',+ targetAgentKind: 'claude-code',+ model: 'anthropic/claude-opus-5-5[1m]',+ providerId: 'xd',+ agentDeviceId: null,+ };++ it('同引擎改回任务所在电脑:登记带位置的完整切换意图,不走同引擎换模型', async () => {+ const h = relocationHarness();+ const result = await performSessionAgentSwitch(h.deps, backToTaskComputer);+ expect(result).toMatchObject({ deferred: true, switched: false });+ expect(h.selectSameAgentModel).not.toHaveBeenCalled();+ // 改回本机不需要问那台电脑。+ expect(h.assertAgentDeviceRouteUsable).not.toHaveBeenCalled();+ expect(h.pending.get('s1')).toMatchObject({ model: 'anthropic/claude-opus-5-5[1m]', targetAgentDeviceId: null });+ expect(h.calls).toEqual([]);+ });++ it('发送时落地:全量交接、不续接停泊会话、写入新位置并在分隔条记下两台电脑', async () => {+ const h = relocationHarness();+ await performSessionAgentSwitch(h.deps, backToTaskComputer);+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');++ expect(h.findParkedEngineSession).not.toHaveBeenCalled();+ expect(h.calls).toEqual(['close', 'db', 'provider', 'boundary', 'pending']);+ expect(h.deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({+ agentKind: 'cc',+ model: 'anthropic/claude-opus-5-5[1m]',+ providerId: 'xd',+ sdkSessionId: null,+ agentDeviceId: null,+ }));+ const boundary = vi.mocked(h.deps.insertBoundaryMessage).mock.calls[0][1];+ expect(boundary).toMatchObject({+ fromAgentKind: 'cc',+ toAgentKind: 'cc',+ fromAgentDeviceId: 'studio-mac',+ toAgentDeviceId: null,+ fromAgentDeviceName: 'Studio Mac',+ toAgentDeviceName: 'Office PC',+ resumed: false,+ });+ expect(boundary.handoff).toContain('Claude Code (on a different computer)');+ expect(h.pending.get('s1')).toBeUndefined();+ });++ it('挪到另一台电脑:登记前与落地前都按那台的目录校验', async () => {+ const h = relocationHarness({ agentDeviceId: null, providerId: 'xd' });+ await performSessionAgentSwitch(h.deps, {+ ...backToTaskComputer,+ model: 'claude-opus-5-5',+ providerId: 'anthropic',+ agentDeviceId: 'studio-mac',+ });+ expect(h.assertAgentDeviceRouteUsable).toHaveBeenCalledWith('studio-mac', 'claude-code', 'claude-opus-5-5', 'anthropic');+ expect(h.pending.get('s1')).toMatchObject({ targetAgentDeviceId: 'studio-mac' });++ await applyPendingAgentSwitchIfIdle(h.deps, 's1');+ expect(h.assertAgentDeviceRouteUsable).toHaveBeenCalledTimes(2);+ expect(h.deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ agentDeviceId: 'studio-mac' }));+ });++ it('那台电脑没有这个模型:选择时直接拒绝,不留意图', async () => {+ const h = relocationHarness({ agentDeviceId: null });+ h.assertAgentDeviceRouteUsable.mockRejectedValueOnce(new Error('not offered'));+ await expect(performSessionAgentSwitch(h.deps, {+ ...backToTaskComputer,+ agentDeviceId: 'studio-mac',+ })).rejects.toThrow('not offered');+ expect(h.pending.get('s1')).toBeUndefined();+ });++ it('不带位置(旧控制端 / 内部调用)保持原位置,同引擎仍走换模型', async () => {+ const h = relocationHarness();+ const { agentDeviceId: _omit, ...withoutLocation } = backToTaskComputer;+ await performSessionAgentSwitch(h.deps, withoutLocation);+ expect(h.selectSameAgentModel).toHaveBeenCalledTimes(1);+ expect(h.pending.get('s1')?.targetAgentDeviceId).toBeUndefined();+ });++ it('换位置在发送时失败:挡住这次发送并保留意图,不悄悄留在原来那台继续', async () => {+ const h = relocationHarness({ agentDeviceId: null });+ await performSessionAgentSwitch(h.deps, { ...backToTaskComputer, agentDeviceId: 'studio-mac' });+ h.assertAgentDeviceRouteUsable.mockRejectedValueOnce(new Error('offline'));+ await expect(applyPendingAgentSwitchIfIdle(h.deps, 's1')).rejects.toThrow('offline');+ expect(h.pending.get('s1')).toMatchObject({ targetAgentDeviceId: 'studio-mac' });+ expect(h.calls).toEqual([]);+ });++ it('非法位置参数被拒绝', async () => {+ const h = relocationHarness();+ await expect(performSessionAgentSwitch(h.deps, { ...backToTaskComputer, agentDeviceId: 'bad id!' }))+ .rejects.toThrow(/INVALID_PARAMS/);+ await expect(performSessionAgentSwitch(h.deps, { ...backToTaskComputer, agentDeviceId: 42 }))+ .rejects.toThrow(/INVALID_PARAMS/);+ });++ it('IPC 第 7 参带位置透传;意图投影带上位置', async () => {+ const h = relocationHarness();+ const ipc = new IpcHarness();+ registerMakerSessionAgentSwitchHandler(ipc, h.deps);+ await ipc.invoke(+ MAKER_INVOKE.SWITCH_SESSION_AGENT,+ 's1', 'claude-code', 'anthropic/claude-opus-5-5[1m]', 'xd', undefined, undefined,+ { agentDeviceId: null },+ );+ await expect(ipc.invoke(MAKER_INVOKE.GET_SESSION_AGENT_SWITCH_INTENT, 's1')).resolves.toMatchObject({+ model: 'anthropic/claude-opus-5-5[1m]',+ agentDeviceId: null,+ });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 122718a1ec..363252ea33 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -22,6 +22,7 @@ import { setBotRemoteMessageService } from './botRemoteMessageReceiver.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';import { getHostSourceDevice, getSelfDeviceId, remoteBackgroundInvoke, remoteInvoke as invokeBotPeer } from '../device-link/index.js';import { readDeviceProviderViews } from '../remote-agent/controller/deviceCatalog.js';+import { checkDeviceRoute } from '../remote-agent/controller/deviceRouteCheck.js';import {isRemoteProviderInvocationAllowed,setRemoteProviderInvocationEnabled,@@ -136,7 +137,7 @@ import { upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';import { isRetainableProjectSession } from '../../shared/sessionSource.js';import { initializePluginOauthCards } from '../plugin-oauth/cards.js';import { currentOauthIdentityScope, loadOauthSigningKey } from '../plugin-oauth/desktopIdentity.js';-import { readDeviceLinkSettings } from '../device-link/settings-store.js';+import { readDeviceLinkSettings, readLastKnownDeviceNames } from '../device-link/settings-store.js';import { getDeviceLinkStatus, getMobileNotifyGeneration, sendMobileBotGroupNotify } from '../device-link/index.js';import type { AgentMeta, Session as RendererSession } from '../../renderer/lib/ccAgent.types';import {@@ -7045,6 +7046,44 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}}+ /**+ * Agent 将在另一台电脑运行时的选择准入(远程 Agent):那台在线、允许被远程调用这个来源、+ * 目录里有这个模型。在选择时就拒绝,不留一个发送时在那台失败、且每次发送都重试的意图。+ */+ async function assertAgentDeviceRouteUsable(+ deviceId: string,+ agent: AgentKind,+ model: string,+ providerId: string | null,+ ): Promise<void> {+ const rejection = await checkDeviceRoute(+ () => readDeviceProviderViews(remoteBackgroundInvoke, deviceId),+ agent,+ providerId,+ model,+ );+ if (!rejection) return;+ log.warn('remote agent selection rejected', { agent, model, providerId, rejection });+ // device-link 控制端降级为 PRECONDITION_FAILED(不把新 code 变成跨版本 wire 契约)。+ const code = rejection === 'unreachable' ? 'REMOTE_AGENT_DEVICE_UNREACHABLE' : 'REMOTE_AGENT_MODEL_UNAVAILABLE';+ throwIpcError(+ isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code,+ rejection === 'unreachable'+ ? 'the computer that would run the agent is not reachable; the model was not changed'+ : 'that computer does not offer this model to other computers; the model was not changed',+ );+ }++ /** 分隔条展示用的电脑名:null = 任务所在电脑(本机),其他按设备目录最近一次的名字。 */+ function describeAgentDevice(deviceId: string | null): string | null {+ if (!deviceId) return getHostSourceDevice().name ?? null;+ try {+ return readLastKnownDeviceNames()[deviceId] ?? null;+ } catch {+ return null;+ }+ }+/*** 懒启动 / 队列恢复时,renderer 传来的 createOpts 可能没有 providerId,但 DB 里的* sessions.provider_id 才是这条会话的真实来源选择。必须在 maker.createSession 前补齐,@@ -8743,11 +8782,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerId: sessions.providerId,effort: sessions.effort,fastMode: sessions.fastMode,+ agentDeviceId: sessions.agentDeviceId,+ remoteHostId: sessions.remoteHostId,}).from(sessions).where(eq(sessions.id, sessionId)).limit(1);if (!row) return;+ // Agent 换电脑也在发送事务内落地:快照里的旧位置不能把 Agent 拉回原来那台。+ // 缺省(undefined)交给 bootstrapSession 按任务记录读取,与恢复路径同一口径。+ if (!co.remoteHostId && !row.remoteHostId) {+ co.agentDeviceId = row.agentDeviceId ?? undefined;+ }const dbMakerKind = dbToMakerAgentKind(row.agentKind);if (co.agentKind !== dbMakerKind) {log.warn('lazy-create: createOpts agentKind drifted from DB (agent switch); reconciling', {@@ -8830,11 +8876,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = {withSessionLock: withSendToSessionLock,// 停用轴边界裁决:目标路由被停用 → 抛错;隐式默认落点被停用 → 返回启用替代来源。- // Agent 在另一台电脑运行的任务:目标模型属于那台的目录,由那台的 Agent 启动时裁决。- assertModelRouteUsable: async (agent, model, providerId, sessionId) =>- (sessionId && await readSessionAgentDeviceId(sessionId))- ? undefined- : assertModelRouteUsable(agent, model, providerId),+ // Agent 在另一台电脑运行的任务:目标模型属于那台的目录,由那台的 Agent 启动时裁决(选择时另+ // 有 assertAgentDeviceRouteUsable 预检)。本次选择换了位置时按目标位置判断。+ assertModelRouteUsable: async (agent, model, providerId, sessionId, targetAgentDeviceId) => {+ const agentDeviceId = targetAgentDeviceId !== undefined+ ? targetAgentDeviceId+ : sessionId ? await readSessionAgentDeviceId(sessionId) : null;+ return agentDeviceId ? undefined : assertModelRouteUsable(agent, model, providerId);+ },+ assertAgentDeviceRouteUsable,+ describeAgentDevice,getSessionRow: async (sessionId) => {const db = getDbClient().drizzle;const [row] = await db@@ -8848,6 +8899,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)orcaRole: sessions.orcaRole,sdkSessionId: sessions.sdkSessionId,source: sessions.source,+ agentDeviceId: sessions.agentDeviceId,}).from(sessions).where(eq(sessions.id, sessionId))@@ -8861,7 +8913,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)findParkedEngineSession: (sessionId, targetDbKind) =>findParkedEngineSession(sessionId, targetDbKind),applyAgentSwitchToDb: async (sessionId, patch) => {- const verifiedWindow = lookupVerifiedContextWindow(+ // 把 Agent 挪到另一台电脑时那台的目录才算数,不拿本机目录的窗口写进去。+ const movingToOtherDevice = typeof patch.agentDeviceId === 'string';+ const verifiedWindow = movingToOtherDevice ? undefined : lookupVerifiedContextWindow((agentKind, modelId, pid) =>resolveConfiguredContextWindow(getActiveCatalog(),@@ -18014,6 +18068,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerId: string | null;effort: string | null;fastMode: boolean;+ agentDeviceId: string | null;};assertRuntimeOwnerCurrent(): void;assertSharedTaskCurrent: { admit(): void };@@ -18045,6 +18100,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)!runtimeStatus.orcaRole) {assertRuntimeOwnerCurrent();assertSharedTaskCurrent.admit();+ // 那台的目录里没有这个模型(例如控制端列的是任务所在电脑的目录):现在就拒绝,+ // 不登记一个发送时必然失败、之后每次发送都重试的意图。+ if (runtimeStatus.agentDeviceId) {+ await assertAgentDeviceRouteUsable(runtimeStatus.agentDeviceId, agentKind, model, targetProviderId);+ if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };+ assertRuntimeOwnerCurrent();+ assertSharedTaskCurrent.admit();+ }const intent = {...(internalOptions.runtimeSource ? { runtimeSource: internalOptions.runtimeSource } : {}),...(internalOptions.configStaged === true ? { configStaged: true } : {}),diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex 06f63a5967..2bfb330485 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -24,6 +24,10 @@** 边界:远程会话(remoteHostId)与 Orca 协同会话不支持切换(UNSUPPORTED_CAPABILITY);* turn 进行中登记 pending 推迟到下一条消息发送时刻执行。+ *+ * 远程 Agent 换电脑(agentDeviceId 变化,null = 任务所在电脑):原生会话记录在原来运行 Agent+ * 的那台电脑上,换位置无法续接,即使引擎相同也按跨引擎同一流程走(全量交接 + 全新原生会话);+ * 目标是另一台电脑时,登记与落地前都按那台的目录校验,不留一个发送时必然失败的意图。*/import type { AgentKind } from '@cindy/maker-core';@@ -95,6 +99,14 @@ export interface AgentSwitchBoundaryContent {* 缺失表示 v1 老行,重建时继续使用“边界后是否存在 user 行”的兼容启发式。*/consumed?: boolean;+ /**+ * 只在 Agent 换电脑时出现:离场 / 目标位置(null = 任务所在电脑)。名称在切换时快照,+ * 那台电脑之后改名或移除,分隔条仍看得懂;缺名称时界面显示「另一台电脑」。+ */+ fromAgentDeviceId?: string | null;+ toAgentDeviceId?: string | null;+ fromAgentDeviceName?: string | null;+ toAgentDeviceName?: string | null;}export interface AgentSwitchSessionRow {@@ -107,8 +119,13 @@ export interface AgentSwitchSessionRow {orcaRole: string | null;sdkSessionId: string | null;source?: string | null;+ /** Agent 在哪台电脑运行(null / 缺省 = 任务所在电脑)。 */+ agentDeviceId?: string | null;}+/** 与 create-session 的 agentDeviceId 校验同一口径。 */+const AGENT_DEVICE_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;+export interface MakerSessionAgentSwitchHandlerDeps {/** Same-engine choices use SET_MODEL validation; only the send boundary applies them. Caller owns the session lock. */selectSameAgentModel?(@@ -133,7 +150,21 @@ export interface MakerSessionAgentSwitchHandlerDeps {providerId: string | null,/** 被切换的任务;Agent 在另一台电脑运行的任务按那台的目录裁决(本机不校验)。 */sessionId?: string,+ /** 本次选择的 Agent 位置;undefined = 按任务当前位置,null = 任务所在电脑。 */+ targetAgentDeviceId?: string | null,): Promise<string | undefined>;+ /**+ * Agent 将在另一台电脑运行时的准入:那台在线、允许被远程调用该供应商、目录里有这个模型。+ * 不满足抛错。缺省 = 不校验(测试最小 harness)。+ */+ assertAgentDeviceRouteUsable?(+ deviceId: string,+ agent: 'claude-code' | 'codex' | 'pi',+ model: string,+ providerId: string | null,+ ): Promise<void>;+ /** 分隔条展示用的电脑名(null = 任务所在电脑)。缺省 = 不记名称。 */+ describeAgentDevice?(deviceId: string | null): string | null;getSessionRow(sessionId: string): Promise<AgentSwitchSessionRow | null>;getLiveSession(sessionId: string): { isTurnRunning(): boolean } | null | undefined;closeSession(sessionId: string): Promise<void>;@@ -165,6 +196,8 @@ export interface MakerSessionAgentSwitchHandlerDeps {/** 目标引擎下的 effort / fastMode(意图登记时由 renderer 解析,apply 时一并落库)。 */effort?: string;fastMode?: boolean;+ /** Agent 换电脑:undefined = 不动,null = 改回任务所在电脑。 */+ agentDeviceId?: string | null;},): Promise<void>;/**@@ -271,6 +304,8 @@ export interface PendingAgentSwitchIntent {* 那台的模型,发送时据此做「换小窗口前先交接」。本机任务不设。*/confirmedContextWindow?: number;+ /** 选择同时换 Agent 所在电脑(null = 任务所在电脑);缺省 = 位置不变。 */+ targetAgentDeviceId?: string | null;/** resume 回落事务失败后的内部恢复载荷;下一次 send 先重试这笔原子事务。 */resumeFallbackRecovery?: {boundaryClientId: string | null;@@ -292,6 +327,8 @@ export interface PublicAgentSwitchIntent {providerId: string | null;effort?: string;fastMode?: boolean;+ /** 只在换 Agent 所在电脑时出现(null = 任务所在电脑);旧控制端忽略。 */+ agentDeviceId?: string | null;}/**@@ -320,6 +357,7 @@ export function projectPendingAgentSwitchIntent(providerId: intent.providerId ?? null,...(intent.effort ? { effort: intent.effort } : {}),...(typeof intent.fastMode === 'boolean' ? { fastMode: intent.fastMode } : {}),+ ...(intent.targetAgentDeviceId !== undefined ? { agentDeviceId: intent.targetAgentDeviceId } : {}),};}@@ -374,6 +412,11 @@ export async function performSessionAgentSwitch(/** 目标引擎下应生效的 effort / fastMode(renderer 按目标目录与预设解析好带入)。 */effort?: unknown;fastMode?: unknown;+ /**+ * 选择的 Agent 位置(远程 Agent):undefined = 保持任务当前位置(内部调用与不认识该字段的+ * 旧控制端都走这里,不做推断),null = 任务所在电脑,字符串 = 同账号另一台电脑。+ */+ agentDeviceId?: unknown;/*** pending-apply 路径(send 事务派发前执行):跳过新引擎立即重建——send 随后* 的 lazy-create 会按 DB 新值 spawn(reconcileCreateOptsWithDb 校正兜底),@@ -410,6 +453,15 @@ export async function performSessionAgentSwitch(if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {throwIpcError('INVALID_PARAMS', 'providerId must be string | null');}+ const rawAgentDeviceId = params.agentDeviceId;+ if (+ rawAgentDeviceId !== undefined &&+ rawAgentDeviceId !== null &&+ (typeof rawAgentDeviceId !== 'string' || !AGENT_DEVICE_ID_PATTERN.test(rawAgentDeviceId))+ ) {+ throwIpcError('INVALID_PARAMS', 'agentDeviceId must be a device id or null');+ }+ const requestedAgentDeviceId = rawAgentDeviceId as string | null | undefined;// 必须在第一个 await 前快照:跨窗口 / 跨设备写入即使 set→clear 回到同值,修订号也会变化。const pendingRevisionAtStart = deps.pendingSwitches?.revision?.(sessionId);let normalizedProviderId =@@ -424,6 +476,7 @@ export async function performSessionAgentSwitch(model,typeof normalizedProviderId === 'string' ? normalizedProviderId : null,sessionId,+ requestedAgentDeviceId,);if (reroute && shouldApplyExclusiveProviderRerouteLive(normalizedProviderId)) {normalizedProviderId = reroute;@@ -454,7 +507,23 @@ export async function performSessionAgentSwitch(const fromDbKind: DbAgentKind = normalizeDbAgentKind(row.agentKind);const toDbKind: DbAgentKind = makerToDbAgentKind(targetAgentKind);- if (fromDbKind === toDbKind) {+ const currentAgentDeviceId = row.agentDeviceId ?? null;+ const targetAgentDeviceId =+ requestedAgentDeviceId === undefined ? currentAgentDeviceId : requestedAgentDeviceId;+ const agentDeviceChanges = targetAgentDeviceId !== currentAgentDeviceId;+ // 落到另一台电脑的完整切换(换引擎或换电脑):登记与落地前都按那台的目录裁决。同引擎同位置+ // 的模型选择走 selectSameAgentModel,在 SET_MODEL 链路里裁决。+ if (targetAgentDeviceId && (agentDeviceChanges || fromDbKind !== toDbKind)) {+ await deps.assertAgentDeviceRouteUsable?.(+ targetAgentDeviceId,+ targetAgentKind,+ model,+ typeof normalizedProviderId === 'string' ? normalizedProviderId : null,+ );+ throwIfAgentSwitchAborted(signal);+ params.assertSelectionCurrent?.();+ }+ if (fromDbKind === toDbKind && !agentDeviceChanges) {// Only picker calls stage a model choice here. Internal cross-engine apply/recovery// callers retain the existing same-engine no-op; send consumes staged choices below.if (deps.selectSameAgentModel && !params.applyNow) {@@ -525,6 +594,7 @@ export async function performSessionAgentSwitch(providerId: normalizedProviderId,...(typeof params.effort === 'string' && params.effort ? { effort: params.effort } : {}),...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),+ ...(agentDeviceChanges ? { targetAgentDeviceId } : {}),};deps.pendingSwitches.set(sessionId, intent);deps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(intent));@@ -532,6 +602,7 @@ export async function performSessionAgentSwitch(sessionId,targetAgentKind,model,+ ...(agentDeviceChanges ? { agentDeviceChange: targetAgentDeviceId ? 'other-device' : 'task-device' } : {}),});return { switched: false, agentKind: targetAgentKind, model, engineReady: true, deferred: true };}@@ -548,13 +619,17 @@ export async function performSessionAgentSwitch(// 交接素材与停泊绑定先于任何状态变更取得(失败不留半切换状态)。// Phase 2:目标引擎有停泊原生会话 → resume + 增量交接(只补离开期间的进展,// 工作状态区仍按全量历史提取);无绑定 → v1 全量交接 + 全新原生会话。- const parked = deps.findParkedEngineSession+ // 换电脑时停泊的原生会话在原来那台电脑上,目标电脑接不上,一律全量交接。+ const parked = deps.findParkedEngineSession && !agentDeviceChanges? await deps.findParkedEngineSession(sessionId, toDbKind): null;const fullSourceMessages = await deps.listMessagesForHandoff(sessionId);throwIfAgentSwitchAborted(signal);const handoffOptsBase = {- fromLabel: agentEngineLabel(fromDbKind),+ // 同引擎换电脑时两边引擎名相同,标出旧的那段跑在另一台电脑上。+ fromLabel: agentDeviceChanges+ ? `${agentEngineLabel(fromDbKind)} (on a different computer)`+ : agentEngineLabel(fromDbKind),toLabel: agentEngineLabel(toDbKind),// 附带早期原文检索指引(get_chat_history / search_chat_history 定向到本会话)。sessionId,@@ -590,6 +665,7 @@ export async function performSessionAgentSwitch(model,typeof normalizedProviderId === 'string' ? normalizedProviderId : null,sessionId,+ requestedAgentDeviceId,);if (rerouteAtCommit && typeof normalizedProviderId !== 'string') {normalizedProviderId = rerouteAtCommit;@@ -604,6 +680,7 @@ export async function performSessionAgentSwitch(sdkSessionId: parked?.sdkSessionId ?? null,...(typeof params.effort === 'string' && params.effort ? { effort: params.effort } : {}),...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),+ ...(agentDeviceChanges ? { agentDeviceId: targetAgentDeviceId } : {}),});if (normalizedProviderId !== undefined) {deps.setSessionProvider(sessionId, normalizedProviderId);@@ -621,6 +698,14 @@ export async function performSessionAgentSwitch(handoff,resumed: !!parked,consumed: false,+ ...(agentDeviceChanges+ ? {+ fromAgentDeviceId: currentAgentDeviceId,+ toAgentDeviceId: targetAgentDeviceId,+ fromAgentDeviceName: deps.describeAgentDevice?.(currentAgentDeviceId) ?? null,+ toAgentDeviceName: deps.describeAgentDevice?.(targetAgentDeviceId) ?? null,+ }+ : {}),};let boundaryClientId: string | null = null;try {@@ -755,6 +840,7 @@ export async function performSessionAgentSwitch(engineReady,resumed,handoffChars: handoff.length,+ ...(agentDeviceChanges ? { agentDeviceChange: targetAgentDeviceId ? 'other-device' : 'task-device' } : {}),});return {switched: true,@@ -916,6 +1002,7 @@ export function applyPendingAgentSwitchIfIdle(providerId: intent.providerId,effort: intent.effort,fastMode: intent.fastMode,+ agentDeviceId: intent.targetAgentDeviceId,// 普通 maker send 随后会按 DB 真源 lazy-create,无需在 apply 内多 spawn 一次;// Goal / IM / scheduler 三条直发路径没有该 lazy-create 事务,必须先把新引擎// bootstrap 好再拿 live session 发送,否则会继续持有已关闭的旧 session。@@ -952,10 +1039,12 @@ export function applyPendingAgentSwitchIfIdle(// Never send on the old model after the user's selected route failed preparation.// 墓碑写失败同理: 跨引擎的 fail-continue 也必须挡住 —— 发送继续 + 进程退出会把// 同值重选的唯一证据一起丢掉(PR #5155 review P2)。+ // 换电脑同理:用户选的是另一台电脑(或改回本机),不能悄悄留在原来那台继续发。if (err instanceof UserRouteSelectionMarkerError ||intent.sameAgentSelection ||- intent.runtimeSource === 'agent'+ intent.runtimeSource === 'agent' ||+ intent.targetAgentDeviceId !== undefined) {throw err;}@@ -983,8 +1072,19 @@ export function registerMakerSessionAgentSwitchHandler(providerId: unknown,effort: unknown,fastMode: unknown,+ // 第 7 参(可选):{ agentDeviceId } —— 同时换 Agent 所在电脑。旧被控端忽略多余参数,+ // 位置保持不变(与今天一致)。+ options?: unknown,) => {const context = getDeviceLinkInvokeContext();+ const agentDeviceId =+ options && typeof options === 'object' && !Array.isArray(options) && 'agentDeviceId' in options+ ? (options as { agentDeviceId?: unknown }).agentDeviceId+ : undefined;+ // 共享任务的访客只能在主人给的范围内改设置,不能把 Agent 挪到主人的其他电脑上。+ if (agentDeviceId !== undefined && context?.sharedTask) {+ throwIpcError('UNSUPPORTED_CAPABILITY', 'shared task guests cannot move the agent to another computer');+ }const guard = createSharedTaskSettingGuard(context?.sharedTask, String(sessionId), context?.sharedTaskSetting ?? { admitted: false });const run = () => performSessionAgentSwitch(deps, {sessionId,@@ -993,6 +1093,7 @@ export function registerMakerSessionAgentSwitchHandler(providerId,effort,fastMode,+ ...(agentDeviceId !== undefined ? { agentDeviceId } : {}),assertSelectionCurrent: guard.admit,});return typeof sessionId === 'string' && sessionId && deps.withSessionLockdiff --git a/apps/desktop/src/main/remote-agent/__tests__/deviceRouteCheck.test.ts b/apps/desktop/src/main/remote-agent/__tests__/deviceRouteCheck.test.tsnew file mode 100644index 0000000000..0125b5c19c--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/deviceRouteCheck.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';+import type { ProviderView } from '@cindy/model-providers';++import { checkDeviceRoute, deviceOffersModel } from '../controller/deviceRouteCheck';++function view(id: string, models: Record<string, string[]>): ProviderView {+ return {+ id,+ name: id,+ agents: Object.keys(models),+ connected: true,+ remoteInvocationEnabled: true,+ routing: {},+ models: Object.fromEntries(+ Object.entries(models).map(([agent, ids]) => [agent, ids.map((modelId) => ({ id: modelId, efforts: [], defaultEffort: null }))]),+ ),+ } as unknown as ProviderView;+}++describe('deviceOffersModel', () => {+ const views = [view('anthropic', { 'claude-code': ['claude-opus-5-5'] })];++ it('按来源与 Agent 匹配,长上下文写法回落到基础条目', () => {+ expect(deviceOffersModel(views, 'claude-code', 'anthropic', 'claude-opus-5-5')).toBe(true);+ expect(deviceOffersModel(views, 'claude-code', 'anthropic', 'claude-opus-5-5[1m]')).toBe(true);+ expect(deviceOffersModel(views, 'claude-code', null, 'claude-opus-5-5')).toBe(true);+ });++ it('那台没开放这个来源 / 没有这个模型 / Agent 不对时为 false', () => {+ expect(deviceOffersModel(views, 'claude-code', 'xd', 'claude-opus-5-5')).toBe(false);+ expect(deviceOffersModel(views, 'claude-code', 'anthropic', 'anthropic/claude-opus-5-5[1m]')).toBe(false);+ expect(deviceOffersModel(views, 'codex', 'anthropic', 'claude-opus-5-5')).toBe(false);+ });+});++describe('checkDeviceRoute', () => {+ it('目录读不到 = unreachable,读到但没有 = not-offered,可用 = null', async () => {+ const views = [view('anthropic', { 'claude-code': ['claude-opus-5-5'] })];+ await expect(checkDeviceRoute(async () => { throw new Error('offline'); }, 'claude-code', null, 'x'))+ .resolves.toBe('unreachable');+ await expect(checkDeviceRoute(async () => views, 'claude-code', 'xd', 'claude-opus-5-5'))+ .resolves.toBe('not-offered');+ await expect(checkDeviceRoute(async () => views, 'claude-code', 'anthropic', 'claude-opus-5-5'))+ .resolves.toBeNull();+ });+});diff --git a/apps/desktop/src/main/remote-agent/controller/deviceRouteCheck.ts b/apps/desktop/src/main/remote-agent/controller/deviceRouteCheck.tsnew file mode 100644index 0000000000..6581c2fc1b--- /dev/null+++ b/apps/desktop/src/main/remote-agent/controller/deviceRouteCheck.ts@@ -0,0 +1,47 @@+/**+ * 远程 Agent 的选择准入(本机主进程)。+ *+ * Agent 要在另一台电脑运行时,所选 (Agent, 来源, 模型) 必须出现在那台允许被远程调用的供应商+ * 目录里(readDeviceProviderViews 已只留授权供应商)。在用户选择的那一刻就拒绝,不留一个到发送时+ * 才在那台失败、且之后每次发送都会重试的意图。+ *+ * 这只是预检:真正的裁决仍由那台的 Agent 启动 / 切换时做。所以按目录元数据回查的宽松口径匹配+ * (`[1m]` 写法、桥接前缀),宁可放过也不误拒。+ */+import type { AgentKind } from '@cindy/maker-core';+import { findCatalogModel, type ProviderView } from '@cindy/model-providers';++/** 那台电脑的目录里能否按这个 (Agent, 来源, 模型) 运行;providerId 为 null = 任一授权来源。 */+export function deviceOffersModel(+ views: readonly ProviderView[],+ agent: AgentKind,+ providerId: string | null,+ modelId: string,+): boolean {+ return views.some(+ (view) =>+ (providerId === null || view.id === providerId) &&+ findCatalogModel(view, modelId, agent) !== undefined,+ );+}++export type DeviceRouteRejection = 'unreachable' | 'not-offered';++/**+ * 读那台的目录并判定。目录读不到(离线、未授权远控、旧版本) = unreachable;+ * 读到了但没有这个模型 / 来源没开放 = not-offered;可用返回 null。+ */+export async function checkDeviceRoute(+ readViews: () => Promise<ProviderView[]>,+ agent: AgentKind,+ providerId: string | null,+ modelId: string,+): Promise<DeviceRouteRejection | null> {+ let views: ProviderView[];+ try {+ views = await readViews();+ } catch {+ return 'unreachable';+ }+ return deviceOffersModel(views, agent, providerId, modelId) ? null : 'not-offered';+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 44bb06be68..d114d2d2de 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6900,6 +6900,8 @@ contextBridge.exposeInMainWorld('electronAPI', {providerId?: string | null,effort?: string,fastMode?: boolean,+ // 远程 Agent:同时换 Agent 所在电脑(null = 任务所在电脑)。不传 = 位置不变。+ options?: { agentDeviceId?: string | null },): Promise<{switched: boolean;agentKind: 'claude-code' | 'codex' | 'pi';@@ -6909,15 +6911,26 @@ contextBridge.exposeInMainWorld('electronAPI', {sameEngineRevision?: number;sameEngineSuperseded?: boolean;}> =>- ipcRenderer.invoke(- 'maker:switch-session-agent',- sessionId,- targetAgentKind,- model,- providerId,- effort,- fastMode,- ),+ options+ ? ipcRenderer.invoke(+ 'maker:switch-session-agent',+ sessionId,+ targetAgentKind,+ model,+ providerId,+ effort,+ fastMode,+ options,+ )+ : ipcRenderer.invoke(+ 'maker:switch-session-agent',+ sessionId,+ targetAgentKind,+ model,+ providerId,+ effort,+ fastMode,+ ),// 读 main 权威的 pending 切换意图(内存态,不落库)。重开视图 / 远程会话重连后// 用它恢复乐观显示——否则用户登记的意图在 UI 上凭空消失,下一条消息却按意图切换。getSessionAgentSwitchIntent: (diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.tsindex 6427b18392..4a6185eb0d 100644--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts@@ -381,7 +381,8 @@ describe('ChatInput model source switching wiring', () => {expect(chatInputSource).toContain('const unifiedModelPanelEnabled = !catalogDeviceId || !remoteProviders.unsupported;',);- expect(chatInputSource).toContain('const catalogDeviceId = deviceLinkDeviceId ?? agentDeviceId ?? undefined;');+ // 已建任务换电脑的意图期内,目录跟随意图里的电脑(effectiveAgentDeviceId)。+ expect(chatInputSource).toContain('const catalogDeviceId = deviceLinkDeviceId ?? effectiveAgentDeviceId ?? undefined;');});/**diff --git a/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts b/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.tsnew file mode 100644index 0000000000..41ed5ece7b--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts@@ -0,0 +1,79 @@+/**+ * 远程 Agent · 已建任务换电脑的渲染端接线(2026-10-07 用户裁决:选模型即可换 Agent 位置)。+ *+ * 起因:Agent 在另一台电脑运行的任务里选了本机模型,选择被转给那台电脑报 Model not found,+ * 之后每次发送都卡住。这里锁住渲染端的几条不变量:+ * 1. 面板浏览的不是 Agent 落点那台的目录时,同引擎 / 跨引擎两条会话链路都改道给 onRelocate;+ * 2. 换位置带着目标电脑进切换事务,意图期内的后续改选沿用意图里的电脑;+ * 3. 意图期内模型目录跟随意图里的电脑,选回任务当前所在电脑不带位置;+ * 4. 只有本机任务、且能走切换事务时才开放(SSH / 被控端 / 协同任务不开放)。+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++const read = (relative: string): string =>+ readFileSync(resolve(__dirname, relative), 'utf8').replace(/\r\n/g, '\n');++const selectorSource = read('../components/new-chat/ModelSelector.tsx');+const chatInputSource = read('../components/new-chat/ChatInput.tsx');++describe('ModelSelector:浏览别的电脑的目录时改道换位置', () => {+ it('只在已建任务、且浏览的不是落点目录时改道', () => {+ expect(selectorSource).toContain(+ 'remoteAgent?.onRelocate && !onUnifiedSelect && !browsingSelectedCatalog',+ );+ });++ it('行选中在同引擎会话链路之前先走 relocate', () => {+ const relocateBranch = selectorSource.indexOf('if (relocate) {');+ const sessionApply = selectorSource.indexOf('return applyUnifiedSessionSelect({', relocateBranch);+ expect(relocateBranch).toBeGreaterThan(0);+ expect(sessionApply).toBeGreaterThan(relocateBranch);+ });++ it('跨引擎行也改道:替换 onCrossEngineSelect / onCrossEngineConfigure,并把整份过滤器交给面板', () => {+ const filter = selectorSource.indexOf('const panelSessionEngineFilter =');+ expect(filter).toBeGreaterThan(0);+ expect(selectorSource.indexOf('onCrossEngineSelect: (args', filter)).toBeGreaterThan(filter);+ expect(selectorSource.indexOf('onCrossEngineConfigure: (args', filter)).toBeGreaterThan(filter);+ expect(selectorSource).toContain(+ '{...(panelSessionEngineFilter ? { sessionEngineFilter: panelSessionEngineFilter } : {})}',+ );+ });++ it('改道的行带上所属电脑', () => {+ expect(selectorSource).toContain('relocate!({ ...row, agentDevice: remoteBrowseDevice })');+ });+});++describe('ChatInput:换位置进切换事务', () => {+ it('位置来自显式选择,否则沿用意图里的电脑;与任务当前所在电脑相同就不带', () => {+ expect(chatInputSource).toContain(+ 'overrides?.agentDeviceId !== undefined ? overrides.agentDeviceId : pendingAgentDeviceId;',+ );+ expect(chatInputSource).toContain('requestedAgentDeviceId !== agentDeviceId');+ expect(chatInputSource).toContain('{ agentDeviceId: relocateTo },');+ });++ it('回声匹配把位置算进意图;登记时写入位置;换电脑不写本机新建任务记忆', () => {+ expect(chatInputSource).toContain('registeredIntent.agentDeviceId === relocateTo;');+ expect(chatInputSource).toContain(+ '...(relocateTo !== undefined ? { agentDeviceId: relocateTo } : {}),',+ );+ expect(chatInputSource).toContain('if (relocateTo === undefined) syncSessionDraftModelPrefs(');+ });++ it('意图期内目录跟随意图里的电脑', () => {+ expect(chatInputSource).toContain(+ 'const catalogDeviceId = deviceLinkDeviceId ?? effectiveAgentDeviceId ?? undefined;',+ );+ });++ it('只对本机任务、且能走切换事务时开放', () => {+ expect(chatInputSource).toContain(+ 'if (!sessionId || deviceLinkDeviceId || remoteHostId || !sessionEngineFilter) return undefined;',+ );+ expect(chatInputSource).toContain('agentDeviceId: selection.agentDevice?.deviceId ?? null,');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.tsindex 2e832b2d74..3342276d21 100644--- a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts@@ -118,6 +118,37 @@ describe('makerChatStore.mirrorAgentSwitchIntent', () => {expect(makerChatStore.getSnapshot(s)).toBe(snap); // 引用不变 = 未触发更新});+ it('远程 Agent 换电脑:位置随意图镜像(null = 任务所在电脑),脏值按位置不变处理', async () => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const s = sid();+ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'claude-code',+ model: 'anthropic/claude-opus-5-5[1m]',+ providerId: 'xd',+ agentDeviceId: null,+ });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent).toMatchObject({ agentDeviceId: null });++ // 位置不同 = 不同的意图,不能当成同一份回声吞掉。+ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'claude-code',+ model: 'anthropic/claude-opus-5-5[1m]',+ providerId: 'xd',+ agentDeviceId: 'studio-mac',+ });+ expect(makerChatStore.getSnapshot(s).agentSwitchIntent?.agentDeviceId).toBe('studio-mac');++ makerChatStore.mirrorAgentSwitchIntent(s, {+ targetAgentKind: 'claude-code',+ model: 'm',+ providerId: 'xd',+ agentDeviceId: 42,+ });+ const intent = makerChatStore.getSnapshot(s).agentSwitchIntent;+ expect(intent?.model).toBe('m');+ expect(intent && 'agentDeviceId' in intent).toBe(false);+ });+it('null / 非法值 = 无意图 → 清除', async () => {const { makerChatStore } = await import('@/lib/makerChatStore');const s = sid();@@ -937,7 +968,8 @@ describe('ChatInput 的入口门控与调用路由', () => {'const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);',);const invoke = source.indexOf(- 'const result = await switchApi.switchSessionAgent(',+ // 换电脑时多带一个位置参数,两种调用形态共用同一个 result。+ 'const result = relocateTo !== undefined',reservation,);const scopeGuard = source.indexOf(diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsxindex 07690226be..0908cd61fb 100644--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx@@ -54,6 +54,7 @@ import { MarkdownRenderer } from './MarkdownRenderer';import { CindyMakeDoctorCard } from './CindyMakeDoctorCard';import { builtInSkillDescriptionKey } from '@/features/skillhub/lib/builtInSkillPresentation';import { CindyMakeCompleteCard } from '@/components/cindy-make/CindyMakeCompleteCard';+import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';interface SystemCardProps {cardType:@@ -1097,7 +1098,28 @@ function isEnglishSourceHandoff(handoff: string): boolean {* 的上下文摘要全文)——默认不打扰,想看时可核查我们替用户做了什么交接。* 全灰度(docs/design-rules/cindy-design-system.md §4),无 chromatic 色;展开面板复用 msg-tool 系 token。*/-function AgentSwitchCard({ data }: { data?: Record<string, unknown> }) {+/**+ * 远程 Agent 换电脑的分隔条文案:只有边界行带 toAgentDeviceId 时才是换电脑。null = 任务所在电脑 ——+ * 在本机打开的任务就是「本机」;远程控制另一台电脑上的任务时那台不是本机,用切换时快照的名字。+ */+function agentRelocationLabel(+ data: Record<string, unknown> | undefined,+ sessionId: string | undefined,+ t: ReturnType<typeof useTranslation>['t'],+): string | null {+ if (!data || !('toAgentDeviceId' in data)) return null;+ const name =+ typeof data.toAgentDeviceName === 'string' && data.toAgentDeviceName ? data.toAgentDeviceName : null;+ if (data.toAgentDeviceId === null && (!sessionId || !getSessionDeviceId(sessionId))) {+ return t('chat.systemCard.agentSwitch.relocatedHere');+ }+ if (name) return t('chat.systemCard.agentSwitch.relocatedTo', { device: name });+ return data.toAgentDeviceId === null+ ? t('chat.systemCard.agentSwitch.relocatedTaskComputer')+ : t('chat.systemCard.agentSwitch.relocatedElsewhere');+}++function AgentSwitchCard({ data, sessionId }: { data?: Record<string, unknown>; sessionId?: string }) {const { t } = useTranslation();const [expanded, setExpanded] = useState(false);const engineLabel = (kind: unknown): string =>@@ -1106,7 +1128,9 @@ function AgentSwitchCard({ data }: { data?: Record<string, unknown> }) {const toLabel = engineLabel(data?.toAgentKind);const toModel = typeof data?.toModel === 'string' ? data.toModel : '';const handoff = typeof data?.handoff === 'string' ? data.handoff : '';- const label = t('chat.systemCard.agentSwitch.label', { from: fromLabel, to: toLabel });+ const label =+ agentRelocationLabel(data, sessionId, t) ??+ t('chat.systemCard.agentSwitch.label', { from: fromLabel, to: toLabel });return (<div className="w-full select-none py-2" role="separator" aria-label={label}>@@ -1375,7 +1399,7 @@ export function SystemCard({case 'auto-resume-pending':return <AutoResumeActionRow state="live" info={readAutoResumeInfo(data)} />;case 'agent-switch':- return <AgentSwitchCard data={data} />;+ return <AgentSwitchCard data={data} sessionId={sessionId} />;case 'context-rebuild':return <ContextRebuildCard data={data} />;case 'learn':diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 0de2b0ffec..8d3906d6c7 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -1229,8 +1229,19 @@ export function ChatInput({const deviceLinkDeviceId = _deviceLinkDeviceId;/** Agent 在另一台电脑运行的本机任务(只影响模型目录来源)。 */const agentDeviceId = deviceLinkDeviceId ? null : (_agentDeviceId ?? null);+ /**+ * 已建任务选了换电脑、下一条消息才生效时(意图带位置):模型目录、选中态与 trigger 都按意图里的+ * 电脑显示。undefined = 没有换位置的意图。+ */+ const intentAgentDeviceId =+ sessionId && !deviceLinkDeviceId && !remoteHostId+ ? makerChatStore.getAgentSwitchIntent(sessionId)?.agentDeviceId+ : undefined;+ /** 下一条消息时 Agent 所在的电脑(null = 本机)。 */+ const effectiveAgentDeviceId =+ intentAgentDeviceId !== undefined ? intentAgentDeviceId : agentDeviceId;/** 模型目录所在的电脑:远程任务在那台;Agent 在另一台电脑运行时也是那台。 */- const catalogDeviceId = deviceLinkDeviceId ?? agentDeviceId ?? undefined;+ const catalogDeviceId = deviceLinkDeviceId ?? effectiveAgentDeviceId ?? undefined;const sharedGuest = isSharedTaskPeer(deviceLinkDeviceId ?? '');const { t } = useTranslation();const navigate = useNavigate();@@ -6599,6 +6610,11 @@ export function ChatInput({overrides?: {effort?: Effort;fastMode?: boolean;+ /**+ * 远程 Agent:这一行属于哪台电脑的目录(null = 本机)。与任务当前所在电脑不同 = 连 Agent+ * 的运行位置一起换。不传 = 沿用已登记的换位置意图,没有就是位置不变。+ */+ agentDeviceId?: string | null;},): Promise<boolean> => {// ★ 返回值 = **本端请求的完整配置真的落到会话上了没有**(2026-08-17 review 确立@@ -6623,6 +6639,24 @@ export function ChatInput({const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);try {await exclusiveTurn.ready;+ // 远程 Agent:这次选择落在哪台电脑。左侧栏点了另一台电脑的目录就用那台;否则沿用已登记+ // 的换位置意图 —— 意图期内在同一份目录里改选,不能被当成原来那台的选择。与任务当前+ // 所在电脑相同 = 位置不变,不带给 main(旧被控端 / 内部调用同样不带)。+ const pendingAgentDeviceId =+ makerChatStore.getAgentSwitchIntent(sourceSessionId)?.agentDeviceId;+ const requestedAgentDeviceId =+ overrides?.agentDeviceId !== undefined ? overrides.agentDeviceId : pendingAgentDeviceId;+ const relocateTo =+ !deviceLinkDeviceId &&+ requestedAgentDeviceId !== undefined &&+ requestedAgentDeviceId !== agentDeviceId+ ? requestedAgentDeviceId+ : undefined;+ // 这一行来自当前没在显示的那份目录:档位与 Fast 已由面板按那份目录解析好,原样采用,+ // 不拿当前目录再解析一遍(同 id 模型两台电脑的档位 / Fast 能力可以不同)。+ const fromOtherCatalog =+ overrides?.agentDeviceId !== undefined &&+ overrides.agentDeviceId !== effectiveAgentDeviceId;// effort 档按**目标引擎 + 目标来源**目录解析(同 id 模型跨来源档位可不同);浏览态// 悬浮面板写下的 per-(目标引擎,来源,模型) 预设在此恢复。const { efforts, defaultEffort } = resolveModelEfforts(@@ -6634,14 +6668,17 @@ export function ChatInput({modelMemory && providerId? modelMemory.getEffort(targetAgentKind, providerId, newModelId): undefined;- const newEffort = resolveRequestedEffort({- requested: overrides?.effort,- efforts,- defaultEffort,- activeEffort,- providerEffort,- rememberedEffort: getRememberedEffort(newModelId),- });+ const newEffort =+ fromOtherCatalog && overrides?.effort+ ? overrides.effort+ : resolveRequestedEffort({+ requested: overrides?.effort,+ efforts,+ defaultEffort,+ activeEffort,+ providerEffort,+ rememberedEffort: getRememberedEffort(newModelId),+ });// Fast 目标值:目标 (来源,模型) 支持时按目标引擎全局预设,否则 false——// 旧引擎的 fastMode 不能原样带进新引擎。// 显式 override 也必须过目标能力门:意图期改选到不支持 Fast 的模型/来源时,@@ -6660,8 +6697,9 @@ export function ChatInput({modelId: newModelId,agentKind: targetAgentKind,});- const targetFast =- overrides?.fastMode !== undefined+ const targetFast = fromOtherCatalog+ ? overrides?.fastMode === true+ : overrides?.fastMode !== undefined? overrides.fastMode && fastCapable: fastCapable &&!!providerId &&@@ -6677,14 +6715,24 @@ export function ChatInput({const switchApi = deviceLinkDeviceId? makerApiForDevice(deviceLinkDeviceId): makerApiFor(sourceSessionId);- const result = await switchApi.switchSessionAgent(- sourceSessionId,- targetAgentKind,- newModelId,- providerId,- newEffort,- targetFast,- );+ const result = relocateTo !== undefined+ ? await switchApi.switchSessionAgent(+ sourceSessionId,+ targetAgentKind,+ newModelId,+ providerId,+ newEffort,+ targetFast,+ { agentDeviceId: relocateTo },+ )+ : await switchApi.switchSessionAgent(+ sourceSessionId,+ targetAgentKind,+ newModelId,+ providerId,+ newEffort,+ targetFast,+ );// device-link 往返期间可以切到另一个任务:同一路由下 ChatInput 会带着新// sessionId 继续渲染,sameEngineReselectRef 等闭包也已指向新会话。旧会话的// 响应绝不能借最新的 ref 把模型/来源写进当前会话。@@ -6715,7 +6763,9 @@ export function ChatInput({registeredIntent !== null &®isteredIntent.target === targetAgentKind &®isteredIntent.model === newModelId &&- (providerId === null || registeredIntent.providerId === providerId);+ (providerId === null || registeredIntent.providerId === providerId) &&+ // 位置同样是这份意图的一部分:没换位置时 main 的投影也不带该字段。+ registeredIntent.agentDeviceId === relocateTo;const ackAction = resolveAgentSwitchAckAction({deferred: result.deferred === true,switched: result.switched,@@ -6755,6 +6805,7 @@ export function ChatInput({providerId,effort: newEffort,fastMode: targetFast,+ ...(relocateTo !== undefined ? { agentDeviceId: relocateTo } : {}),});}// 跨引擎点选也是用户显式选模:记到目标 vendor,下次用该引擎新建跟随这次选择。@@ -6770,7 +6821,8 @@ export function ChatInput({const syncedEffort = authoritative ? authoritative.effort : newEffort;const syncedFast = authoritative ? authoritative.fastMode : targetFast;const syncedProviderId = authoritative ? authoritative.providerId : providerId;- syncSessionDraftModelPrefs(+ // 换电脑的选择属于目标电脑的目录,不写进本机的新建任务记忆。+ if (relocateTo === undefined) syncSessionDraftModelPrefs(newModelId,{...(syncedEffort ? { effort: syncedEffort } : {}),@@ -6838,7 +6890,7 @@ export function ChatInput({}// 立即切换路径(harness / registry 缺省兜底,生产不走):维持旧收敛语义。makerChatStore.noteAgentSwitched(sourceSessionId, targetAgentKind);- syncSessionDraftModelPrefs(+ if (relocateTo === undefined) syncSessionDraftModelPrefs(newModelId,{ effort: newEffort, fast: targetFast },{@@ -6875,6 +6927,8 @@ export function ChatInput({providers,modelMemory,deviceLinkDeviceId,+ agentDeviceId,+ effectiveAgentDeviceId,remoteProviders.providers,providers,ccCaps.capabilities,@@ -6997,6 +7051,58 @@ export function ChatInput({setSessionFavoriteAnchor,]);+ // ── 远程 Agent · 已建任务:选另一台电脑(或本机)目录里的模型 = 把 Agent 挪过去 ──────────+ // 与跨引擎同一套事务(performAgentSwitch:意图在下一条消息发送时落地,交接摘要接续)。换电脑+ // 同样续接不了原生会话,复用同一份风险确认与「不再提示」偏好,只换说明文案。选回任务当前+ // 所在电脑(撤销挂着的换位置)或已确认过的同一目标不再问。+ const confirmAgentRelocation = useCallback(+ (target: UnifiedSelectionAgentDevice) =>+ confirmAgentSwitchRisk({+ hasSwitchIntent:+ (target?.deviceId ?? null) === agentDeviceId ||+ (intentAgentDeviceId !== undefined && intentAgentDeviceId === (target?.deviceId ?? null)),+ confirm: confirmDialog,+ copy: {+ title: target+ ? t('newChat.chatInput.agentRelocation.titleOther', { device: target.name })+ : t('newChat.chatInput.agentRelocation.titleLocal'),+ description: t('newChat.chatInput.agentRelocation.description'),+ confirmText: t('newChat.chatInput.agentRelocation.confirm'),+ cancelText: t('newChat.chatInput.agentRelocation.cancel'),+ dontShowAgainLabel: t('newChat.chatInput.agentSwitch.confirmation.dontShowAgain'),+ },+ }),+ [agentDeviceId, intentAgentDeviceId, confirmDialog, t],+ );+ const sessionRemoteAgentOptions = useMemo<RemoteAgentSelectorOptions | undefined>(() => {+ // 只有本机任务、且会话内能走切换事务时才开放(SSH / 被控端任务 / 协同任务都不行)。+ if (!sessionId || deviceLinkDeviceId || remoteHostId || !sessionEngineFilter) return undefined;+ if (!remoteAgentDevices || (remoteAgentDevices.length === 0 && !effectiveAgentDeviceId)) {+ return undefined;+ }+ return {+ devices: remoteAgentDevices,+ selectedDeviceId: effectiveAgentDeviceId,+ localModelMemory: LOCAL_MODEL_MEMORY,+ onRelocate: async (selection) => {+ if (!(await confirmAgentRelocation(selection.agentDevice))) return false;+ return performAgentSwitchRef.current(selection.agent, selection.modelId, selection.providerId, {+ ...(selection.effort ? { effort: selection.effort } : {}),+ fastMode: selection.fast,+ agentDeviceId: selection.agentDevice?.deviceId ?? null,+ });+ },+ };+ }, [+ sessionId,+ deviceLinkDeviceId,+ remoteHostId,+ sessionEngineFilter,+ remoteAgentDevices,+ effectiveAgentDeviceId,+ confirmAgentRelocation,+ ]);+// composer pill 尾部引擎小标的取值(model-selector-unified §1.1,Chris 2026-08-12 裁决:// pill 不再写 harness 名字文本)。与 agentIdentity **同一口径**,不另起一套:// · 已建会话:身份由 session / runtime 确认后才画;切换意图期画目标引擎;@@ -9120,18 +9226,24 @@ export function ChatInput({: undefined}deviceId={catalogDeviceId}- // 远程 Agent(仅本机新任务草稿):面板同时列出其他电脑上的供应商,选中即换 Agent 落点。+ // 远程 Agent:面板同时列出其他电脑上的供应商。草稿选中即换 Agent 落点;已建任务+ // 选中另一台电脑的模型 = 把 Agent 挪过去(下一条消息生效)。{...(remoteAgentOptions && unifiedPanelActive && onUnifiedDraftSelect? { remoteAgent: remoteAgentOptions }- : {})}- // Agent 在另一台电脑运行(草稿或已建任务):trigger 用带信号波纹的远程 Logo。+ : sessionRemoteAgentOptions && unifiedPanelActive+ ? { remoteAgent: sessionRemoteAgentOptions }+ : {})}+ // Agent 在另一台电脑运行(草稿或已建任务;意图期按下一条消息时的位置):+ // trigger 用带信号波纹的远程 Logo。agentDevice={- agentDeviceId+ effectiveAgentDeviceId? {- deviceId: agentDeviceId,+ deviceId: effectiveAgentDeviceId,name:- remoteAgentDevices?.find((device) => device.deviceId === agentDeviceId)- ?.name ?? agentDeviceName,+ remoteAgentDevices?.find(+ (device) => device.deviceId === effectiveAgentDeviceId,+ )?.name ??+ (effectiveAgentDeviceId === agentDeviceId ? agentDeviceName : null),}: null}diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 93427da6a8..fb0c3020eb 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -637,22 +637,41 @@ export function resolveModelSelectorAgentIdentity(};}+/** 远程 Agent 草稿里一次行选中的落点电脑;null = Agent 在本机。 */+export type UnifiedSelectionAgentDevice = { deviceId: string; name: string } | null;++/** 已建任务里选中了另一台电脑(或本机)目录里的一行:连 Agent 的运行位置一起换。 */+export interface RemoteAgentRelocation {+ providerId: string;+ /** 目标引擎的 wire model id。 */+ modelId: string;+ agent: AgentKind;+ /** 该行生效档位;不可调档时为 undefined。 */+ effort?: Effort;+ fast: boolean;+ /** 这一行所属的电脑;null = 本机。 */+ agentDevice: UnifiedSelectionAgentDevice;+}+/**- * 远程 Agent 的选择入口(只有本机新任务草稿传)。模型面板的左侧栏在本机供应商之后列出- * 这些电脑上的供应商;选中那台电脑上的模型 = Agent 在那台电脑运行,任务和文件仍在本机。+ * 远程 Agent 的选择入口(本机新任务草稿与本机已建任务传)。模型面板的左侧栏在本机供应商之后+ * 列出这些电脑上的供应商;选中那台电脑上的模型 = Agent 在那台电脑运行,任务和文件仍在本机。*/export interface RemoteAgentSelectorOptions {/** 可以运行 Agent 的其他电脑(已配对、在线)。 */devices: readonly { deviceId: string; name: string }[];- /** 草稿当前的 Agent 所在电脑;null = 本机。 */+ /** 当前的 Agent 所在电脑(已建任务按下一条消息时的位置);null = 本机。 */selectedDeviceId: string | null;/** 本机目录的模型记忆。Agent 当前在其他电脑时,浏览本机目录用它显示各行的档位。 */localModelMemory?: ModelMemoryAccessors;+ /**+ * 已建任务传:选中的行不在 Agent 落点那台电脑的目录里 = 把 Agent 挪过去(与跨引擎同一套意图,+ * 下一条消息发送时生效)。返回 false = 没有执行(确认被取消 / 登记失败),面板留在原地。+ * 草稿不传(草稿走 onUnifiedSelect,行带 agentDevice)。+ */+ onRelocate?: (selection: RemoteAgentRelocation) => Promise<boolean>;}-/** 远程 Agent 草稿里一次行选中的落点电脑;null = Agent 在本机。 */-export type UnifiedSelectionAgentDevice = { deviceId: string; name: string } | null;-interface ModelSelectorProps {/** Authoritative surface-specific allowlist (e.g. one-shot or vision routes). */providersOverride?: ProviderView[];@@ -3034,6 +3053,51 @@ function ModelSelectorContentView({const panelSelection = browsingSelectedCatalog? { providerId: activeSourceId, modelId }: { providerId: null, modelId: '' };+ // 已建任务浏览的不是 Agent 落点那台的目录:选中的行要连运行位置一起换,同引擎 / 跨引擎+ // 两条会话链路都按当前落点的目录工作,这里一律改道给 onRelocate。+ const relocate =+ remoteAgent?.onRelocate && !onUnifiedSelect && !browsingSelectedCatalog+ ? remoteAgent.onRelocate+ : undefined;+ const relocateRow = (+ row: { providerId: string; modelId: string; agent: AgentKind; effort?: Effort; fast: boolean },+ dismiss: boolean,+ ): Promise<boolean> =>+ runLiveWrite(() => relocate!({ ...row, agentDevice: remoteBrowseDevice })).then((applied) => {+ if (applied && dismiss) {+ closeOptionsPanel();+ onDismiss?.();+ }+ return applied;+ });+ const panelSessionEngineFilter =+ sessionEngineFilter && relocate+ ? {+ ...sessionEngineFilter,+ onCrossEngineSelect: (args: Parameters<NonNullable<typeof sessionEngineFilter>['onCrossEngineSelect']>[0]) =>+ relocateRow(+ {+ providerId: args.providerId,+ modelId: args.modelId,+ agent: args.targetAgent,+ ...(args.effort ? { effort: args.effort } : {}),+ fast: args.fast === true,+ },+ true,+ ),+ onCrossEngineConfigure: (args: Parameters<NonNullable<typeof sessionEngineFilter>['onCrossEngineSelect']>[0]) =>+ relocateRow(+ {+ providerId: args.providerId,+ modelId: args.modelId,+ agent: args.targetAgent,+ ...(args.effort ? { effort: args.effort } : {}),+ fast: args.fast === true,+ },+ false,+ ),+ }+ : sessionEngineFilter;return (// 外层多包一层「百分比钳制」:面板列自身的 max-h 公式(560px/100vh)不知道宿主// popover 实际给了多少纵向空间 —— morph 弹层按锚点位置算出的可用高度可能更小,@@ -3168,7 +3232,7 @@ function ModelSelectorContentView({configurationEnabled={configurationEnabled}selectionPolicy={unifiedSelectionPolicy}isRouteDisabled={(providerId, id, rowAgent) => providersOverride ? false : modelDisabledOf(providers.find((provider) => provider.id === providerId) ?? null, id, rowAgent)}- {...(sessionEngineFilter ? { sessionEngineFilter } : {})}+ {...(panelSessionEngineFilter ? { sessionEngineFilter: panelSessionEngineFilter } : {})}{...(followSession ? { followSession: {...followSession,onFollow: async () => {@@ -3204,6 +3268,20 @@ function ModelSelectorContentView({return applied;});}+ if (relocate) {+ const agent = vendorKeyToAgentKind(rowConfig.engine);+ if (!agent) return false;+ return relocateRow(+ {+ providerId,+ modelId: id,+ agent,+ ...(rowEffortValue ? { effort: rowEffortValue } : {}),+ fast: rowConfig.fast,+ },+ true,+ );+ }// 已建会话(M6):同引擎行照旧走 onProviderChange 直切;跨引擎行在 selectRow// 里就已经改道 sessionEngineFilter.onCrossEngineSelect,到不了这里。// 「同模型不同配置的收藏」与「锚点只在真的应用后才记」两件事收在@@ -3229,6 +3307,20 @@ function ModelSelectorContentView({...withAgentDevice,});}+ if (relocate) {+ const agent = vendorKeyToAgentKind(rowConfig.engine);+ if (!agent) return false;+ return relocateRow(+ {+ providerId,+ modelId: id,+ agent,+ ...(nextEffort ? { effort: nextEffort } : {}),+ fast: rowConfig.fast,+ },+ false,+ );+ }return applyUnifiedSessionSelect({providerId,wireModelId: id,@@ -3255,6 +3347,8 @@ function ModelSelectorContentView({...withAgentDevice,});}+ // 浏览别的电脑的目录时没有「正在用的那一行」,也就没有锚点可清。+ if (relocate) return;onSessionFavoriteAnchorChange?.(null);}}{...(onEffortChangediff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex f593ed46cc..32fce95901 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -165,6 +165,7 @@ import {import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { canAccessBillingSettings } from '@/components/settings/billingVisibility';import { useDeviceProviders } from '@/hooks/useDeviceProviders';+import { useSelectableDevices } from '@/hooks/useControllableDevices';import {canExposeWritableDirsChange,resolveManualCompactChannel,@@ -2091,6 +2092,27 @@ export function CCAgentSessionView({const { mode: authMode, user: authUser, dataOwnerId } = useAuth();// Agent 在另一台电脑运行的任务:模型目录同样以那台为准(任务本身在本机)。const agentDeviceId = remoteDeviceId ? undefined : (session?.agentDeviceId ?? undefined);+ // 远程 Agent:本机任务的模型面板也列出其他电脑的供应商(选中 = 把 Agent 挪过去,下一条消息+ // 生效)。Agent 当前所在电脑与挂着的换位置目标即使掉线也保留,让用户看得到、换得回来。+ const { devices: selectableDevices } = useSelectableDevices();+ const pendingAgentDeviceId = agentSwitchIntent?.agentDeviceId;+ const remoteAgentDevices = useMemo(+ () =>+ remoteDeviceId || session?.remoteHostId+ ? undefined+ : selectableDevices+ .filter(+ (device) =>+ device.online ||+ device.deviceId === agentDeviceId ||+ device.deviceId === pendingAgentDeviceId,+ )+ .map(({ deviceId, name }) => ({ deviceId, name })),+ [selectableDevices, remoteDeviceId, session?.remoteHostId, agentDeviceId, pendingAgentDeviceId],+ );+ const agentDeviceName = agentDeviceId+ ? (selectableDevices.find((device) => device.deviceId === agentDeviceId)?.name ?? null)+ : null;const catalogDeviceId = remoteDeviceId ?? agentDeviceId;const { providers: deviceProviders } = useDeviceProviders(catalogDeviceId);const providers = catalogDeviceId ? deviceProviders : localProviders;@@ -5520,6 +5542,8 @@ export function CCAgentSessionView({remoteHostId={session?.remoteHostId ?? null}deviceLinkDeviceId={rightSidebarDeviceLinkDeviceId}agentDeviceId={session?.agentDeviceId ?? null}+ agentDeviceName={agentDeviceName}+ {...(remoteAgentDevices ? { remoteAgentDevices } : {})}modelMemoryOverride={remoteModelMemoryOverride}initialModel={session?.model}initialProviderId={session?.providerId ?? null}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 13580077a0..a2a415197f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -404,7 +404,9 @@"SSH_HOST_PREFS_WRITE_FAILED": "The host is still saved, but its display name or Agent Proxy settings could not be saved. Check local storage permissions and try again.","RIGHT_SIDEBAR_TOO_MANY_TABS": "This task has reached its tab limit. Close some tabs first","RIGHT_SIDEBAR_STATE_TOO_LARGE": "Tab content is too large to add",- "RIGHT_SIDEBAR_UNKNOWN_KIND": "This tab type is unavailable"+ "RIGHT_SIDEBAR_UNKNOWN_KIND": "This tab type is unavailable",+ "REMOTE_AGENT_DEVICE_UNREACHABLE": "Model not changed: the computer that would run the Agent can’t be reached. Make sure it’s online and allows remote control, then try again.",+ "REMOTE_AGENT_MODEL_UNAVAILABLE": "Model not changed: that computer doesn’t have this model, or hasn’t turned on “Allow remote use” for this provider. Pick another model."},"providerError": {"AUTH_INVALID": "Invalid or expired API key (401). Check the key and try again",@@ -9298,6 +9300,13 @@"cancel": "Keep Current Agent","dontShowAgain": "Don’t remind me again"}+ },+ "agentRelocation": {+ "titleLocal": "Run the Agent on this computer again?",+ "titleOther": "Run the Agent on “{{device}}”?",+ "description": "The conversation record on the other computer can’t be moved over, so it continues from a handoff summary. Thinking and similar details may not carry over completely. Takes effect when you send the next message.",+ "confirm": "Switch computer",+ "cancel": "Keep as is"}},"agentSelect": {@@ -10135,7 +10144,11 @@"toggleHint": "View handoff context","handoffTitle": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)","handoffTitleEnglishSource": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)",- "resumedBadge": "session resumed"+ "resumedBadge": "session resumed",+ "relocatedHere": "Agent now runs on this computer",+ "relocatedTo": "Agent now runs on {{device}}",+ "relocatedTaskComputer": "Agent now runs on the task’s computer",+ "relocatedElsewhere": "Agent now runs on another computer"},"contextRebuild": {"labelOverflow": "Context reorganized, continuing",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 1c4a3f0a08..98c14f6e46 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -404,7 +404,9 @@"SSH_HOST_PREFS_WRITE_FAILED": "ホストは保存されていますが、表示名または Agent Proxy の設定を保存できませんでした。ローカルストレージの権限を確認して再試行してください。","RIGHT_SIDEBAR_TOO_MANY_TABS": "このタスクのタブ数の上限に達しました。いくつかのタブを閉じてください","RIGHT_SIDEBAR_STATE_TOO_LARGE": "タブの内容が大きすぎるため、追加できません",- "RIGHT_SIDEBAR_UNKNOWN_KIND": "このタブの種類は現在使用できません"+ "RIGHT_SIDEBAR_UNKNOWN_KIND": "このタブの種類は現在使用できません",+ "REMOTE_AGENT_DEVICE_UNREACHABLE": "モデルは切り替わっていません:Agent を実行するパソコンに接続できません。オンラインでリモート操作を許可していることを確認してから、もう一度お試しください。",+ "REMOTE_AGENT_MODEL_UNAVAILABLE": "モデルは切り替わっていません:そのパソコンにこのモデルがないか、このプロバイダーの「リモート利用を許可」がオンになっていません。別のモデルを選んでください。"},"providerError": {"AUTH_INVALID": "API キーが無効か期限切れです(401)。キーを確認して再試行してください",@@ -9285,6 +9287,13 @@"cancel": "現在の Agent を維持","dontShowAgain": "次回から表示しない"}+ },+ "agentRelocation": {+ "titleLocal": "Agent をこのパソコンで実行し直しますか?",+ "titleOther": "Agent を「{{device}}」で実行しますか?",+ "description": "元のパソコンにある会話の記録は移せないため、引き継ぎの要約から続けます。思考内容などは完全には引き継がれない場合があります。次のメッセージを送信したときに反映されます。",+ "confirm": "パソコンを切り替える",+ "cancel": "このままにする"}},"agentSelect": {@@ -10118,7 +10127,11 @@"toggleHint": "引き継ぎ内容を表示","handoffTitle": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)","handoffTitleEnglishSource": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",- "resumedBadge": "セッション再開"+ "resumedBadge": "セッション再開",+ "relocatedHere": "Agent をこのパソコンで実行するようにしました",+ "relocatedTo": "Agent を {{device}} で実行するようにしました",+ "relocatedTaskComputer": "Agent をタスクのあるパソコンで実行するようにしました",+ "relocatedElsewhere": "Agent を別のパソコンで実行するようにしました"},"contextRebuild": {"labelOverflow": "コンテキストを整理して続行しました",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 962c2237c1..efdf4f96b6 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -404,7 +404,9 @@"SSH_HOST_PREFS_WRITE_FAILED": "호스트는 저장되었지만 표시 이름 또는 Agent Proxy 설정을 저장하지 못했습니다. 로컬 저장소 권한을 확인한 후 다시 시도하세요.","RIGHT_SIDEBAR_TOO_MANY_TABS": "이 작업의 탭 한도에 도달했습니다. 일부 탭을 닫아 주세요","RIGHT_SIDEBAR_STATE_TOO_LARGE": "탭 내용이 너무 커서 추가할 수 없습니다",- "RIGHT_SIDEBAR_UNKNOWN_KIND": "이 탭 유형은 현재 사용할 수 없습니다"+ "RIGHT_SIDEBAR_UNKNOWN_KIND": "이 탭 유형은 현재 사용할 수 없습니다",+ "REMOTE_AGENT_DEVICE_UNREACHABLE": "모델이 바뀌지 않았습니다: Agent를 실행할 컴퓨터에 연결할 수 없습니다. 온라인 상태이고 원격 제어를 허용하는지 확인한 뒤 다시 시도하세요.",+ "REMOTE_AGENT_MODEL_UNAVAILABLE": "모델이 바뀌지 않았습니다: 그 컴퓨터에 이 모델이 없거나, 이 제공자의 “원격 사용 허용”이 켜져 있지 않습니다. 다른 모델을 선택하세요."},"providerError": {"AUTH_INVALID": "API 키가 유효하지 않거나 만료되었습니다(401). 키를 확인한 후 다시 시도하세요",@@ -9285,6 +9287,13 @@"cancel": "현재 Agent 유지","dontShowAgain": "다음부터 표시하지 않기"}+ },+ "agentRelocation": {+ "titleLocal": "Agent를 다시 이 컴퓨터에서 실행할까요?",+ "titleOther": "Agent를 “{{device}}”에서 실행할까요?",+ "description": "원래 컴퓨터에 있는 대화 기록은 옮길 수 없어 인수인계 요약으로 이어집니다. 사고 내용 등은 완전히 이어지지 않을 수 있습니다. 다음 메시지를 보낼 때 적용됩니다.",+ "confirm": "컴퓨터 전환",+ "cancel": "그대로 두기"}},"agentSelect": {@@ -10118,7 +10127,11 @@"toggleHint": "인계 내용 보기","handoffTitle": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)","handoffTitleEnglishSource": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",- "resumedBadge": "세션 재개됨"+ "resumedBadge": "세션 재개됨",+ "relocatedHere": "이제 Agent가 이 컴퓨터에서 실행됩니다",+ "relocatedTo": "이제 Agent가 {{device}}에서 실행됩니다",+ "relocatedTaskComputer": "이제 Agent가 작업이 있는 컴퓨터에서 실행됩니다",+ "relocatedElsewhere": "이제 Agent가 다른 컴퓨터에서 실행됩니다"},"contextRebuild": {"labelOverflow": "컨텍스트를 정리하고 계속합니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 592eb375a6..7cbcf7dcdb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -404,7 +404,9 @@"REMOTE_WORKDIR_UNAVAILABLE": "远程项目目录不可访问,请恢复网络盘连接后重试。","RIGHT_SIDEBAR_TOO_MANY_TABS": "当前任务已达标签数量上限,请先关闭一些标签","RIGHT_SIDEBAR_STATE_TOO_LARGE": "标签内容过大,无法添加",- "RIGHT_SIDEBAR_UNKNOWN_KIND": "该标签类型暂不可用"+ "RIGHT_SIDEBAR_UNKNOWN_KIND": "该标签类型暂不可用",+ "REMOTE_AGENT_DEVICE_UNREACHABLE": "模型未切换:要运行 Agent 的那台电脑暂时连不上。确认它在线并允许远程控制后重试。",+ "REMOTE_AGENT_MODEL_UNAVAILABLE": "模型未切换:那台电脑上没有这个模型,或没有对这个供应商打开「允许被远程调用」。请换一个模型。"},"providerError": {"AUTH_INVALID": "API 密钥无效或已过期(401),请检查密钥后重试",@@ -9285,6 +9287,13 @@"cancel": "保留当前 Agent","dontShowAgain": "下次不再提醒"}+ },+ "agentRelocation": {+ "titleLocal": "改回这台电脑运行 Agent?",+ "titleOther": "改到「{{device}}」上运行 Agent?",+ "description": "原来那台电脑上的对话记录带不过来,会整理成交接摘要接上,思考内容等不能保证完美继承。下一条消息发出时生效。",+ "confirm": "换电脑运行",+ "cancel": "保持不变"}},"agentSelect": {@@ -10118,7 +10127,11 @@"toggleHint": "查看交接内容","handoffTitle": "交接内容——切换时发送给新引擎的上下文摘要(不计入对话记录,仅在此展示)","handoffTitleEnglishSource": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",- "resumedBadge": "已续接原任务"+ "resumedBadge": "已续接原任务",+ "relocatedHere": "Agent 已改到这台电脑上运行",+ "relocatedTo": "Agent 已改到 {{device}} 上运行",+ "relocatedTaskComputer": "Agent 已改到任务所在的电脑上运行",+ "relocatedElsewhere": "Agent 已改到另一台电脑上运行"},"contextRebuild": {"labelOverflow": "已整理上下文并继续",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5dd21b68fe..52bff2a8f4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -404,7 +404,9 @@"REMOTE_WORKDIR_UNAVAILABLE": "遠端專案目錄不可訪問,請恢復網路盤連線後重試。","RIGHT_SIDEBAR_TOO_MANY_TABS": "目前任務已達標籤數量上限,請先關閉一些標籤","RIGHT_SIDEBAR_STATE_TOO_LARGE": "標籤內容過大,無法新增",- "RIGHT_SIDEBAR_UNKNOWN_KIND": "此標籤類型暫時無法使用"+ "RIGHT_SIDEBAR_UNKNOWN_KIND": "此標籤類型暫時無法使用",+ "REMOTE_AGENT_DEVICE_UNREACHABLE": "模型未切換:要執行 Agent 的那台電腦暫時連不上。確認它在線並允許遠端控制後重試。",+ "REMOTE_AGENT_MODEL_UNAVAILABLE": "模型未切換:那台電腦上沒有這個模型,或沒有對這個供應商開啟「允許遠端呼叫」。請換一個模型。"},"providerError": {"AUTH_INVALID": "API 金鑰無效或已過期(401),請檢查金鑰後重試",@@ -9285,6 +9287,13 @@"cancel": "保留當前 Agent","dontShowAgain": "下次不再提醒"}+ },+ "agentRelocation": {+ "titleLocal": "改回這台電腦執行 Agent?",+ "titleOther": "改到「{{device}}」上執行 Agent?",+ "description": "原來那台電腦上的對話記錄帶不過來,會整理成交接摘要接上,思考內容等不能保證完美繼承。下一則訊息送出時生效。",+ "confirm": "換電腦執行",+ "cancel": "保持不變"}},"agentSelect": {@@ -10117,7 +10126,11 @@"toggleHint": "檢視交接內容","handoffTitle": "交接內容——切換時傳送給新引擎的上下文摘要(不計入對話記錄,僅在此展示)","handoffTitleEnglishSource": "交接內容——切換時傳送給新引擎的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)",- "resumedBadge": "已續接原任務"+ "resumedBadge": "已續接原任務",+ "relocatedHere": "Agent 已改到這台電腦上執行",+ "relocatedTo": "Agent 已改到 {{device}} 上執行",+ "relocatedTaskComputer": "Agent 已改到任務所在的電腦上執行",+ "relocatedElsewhere": "Agent 已改到另一台電腦上執行"},"contextRebuild": {"labelOverflow": "已整理上下文並繼續",diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 1a9310ded1..b2cf1498ce 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -2453,6 +2453,11 @@ export interface AgentSwitchIntentRecord {providerId: string | null;effort?: string;fastMode?: boolean;+ /**+ * 远程 Agent:这次选择同时换 Agent 所在电脑(null = 任务所在电脑)。缺省 = 位置不变。+ * 意图期内模型目录、选中态与 trigger 都按这台电脑显示。+ */+ agentDeviceId?: string | null;}export type ContinuationInFlightProjectionCapability = 'unknown' | 'supported' | 'legacy';@@ -17119,7 +17124,13 @@ function noteAgentSwitched(sessionId: string, agentKind: 'claude-code' | 'codex'function noteAgentSwitchIntent(sessionId: string,target: 'claude-code' | 'codex' | 'pi',- opts: { model: string; providerId: string | null; effort?: string; fastMode?: boolean },+ opts: {+ model: string;+ providerId: string | null;+ effort?: string;+ fastMode?: boolean;+ agentDeviceId?: string | null;+ },): void {if (!sessionId) return;setState(sessionId, (s) => ({@@ -17130,6 +17141,7 @@ function noteAgentSwitchIntent(providerId: opts.providerId,effort: opts.effort,fastMode: opts.fastMode,+ ...(opts.agentDeviceId !== undefined ? { agentDeviceId: opts.agentDeviceId } : {}),},agentSwitchIntentRev: s.agentSwitchIntentRev + 1,}));@@ -17178,12 +17190,18 @@ function normalizeAgentSwitchIntent(value: unknown): AgentSwitchIntentRecord | nif (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;+ // 位置字段只在换 Agent 所在电脑时出现;脏值按「位置不变」处理,不丢掉整份意图。+ const agentDeviceId =+ item.agentDeviceId === null || (typeof item.agentDeviceId === 'string' && item.agentDeviceId.length > 0)+ ? item.agentDeviceId+ : undefined;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 } : {}),+ ...(agentDeviceId !== undefined ? { agentDeviceId } : {}),};}@@ -17198,7 +17216,8 @@ function agentSwitchIntentEquals(a.model === b.model &&a.providerId === b.providerId &&a.effort === b.effort &&- a.fastMode === b.fastMode+ a.fastMode === b.fastMode &&+ a.agentDeviceId === b.agentDeviceId);}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex c1f37386f2..6915cca876 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -6235,6 +6235,8 @@ interface ElectronAPI {providerId?: string | null,effort?: string,fastMode?: boolean,+ /** 远程 Agent:同时换 Agent 所在电脑(null = 任务所在电脑)。不传 = 位置不变。 */+ options?: { agentDeviceId?: string | null },) => Promise<{switched: boolean;agentKind: 'claude-code' | 'codex' | 'pi';diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 5965e5c893..c82efcd8b3 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -89,6 +89,10 @@ export type IpcErrorCode =| 'MODEL_WINDOW_PROTECTION_UNAVAILABLE'| 'MODEL_SWITCH_TASK_RUNNING'| 'MODEL_WINDOW_PREPARATION_IN_PROGRESS'+ // 远程 Agent 选择准入(选模型时目标电脑不可达 / 目录里没有)。device-link 同样降级为+ // PRECONDITION_FAILED,只在本机窗口给可行动的说明。+ | 'REMOTE_AGENT_DEVICE_UNREACHABLE'+ | 'REMOTE_AGENT_MODEL_UNAVAILABLE'| 'MAKER_MEMORY_NOT_READY'| 'SCHEDULER_NOT_READY'| 'PERMISSION_DENIED'@@ -325,6 +329,8 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['MODEL_WINDOW_PROTECTION_UNAVAILABLE','MODEL_SWITCH_TASK_RUNNING','MODEL_WINDOW_PREPARATION_IN_PROGRESS',+ 'REMOTE_AGENT_DEVICE_UNREACHABLE',+ 'REMOTE_AGENT_MODEL_UNAVAILABLE','MAKER_MEMORY_NOT_READY','SCHEDULER_NOT_READY','PERMISSION_DENIED',diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 027081b9f5..0c03a897d2 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -352,14 +352,22 @@ import { formatQuotesForSend, stripChatQuoteMarkerLines } from '@cindy/maker-shaimport { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';import { confirmFullAccessChange } from '@/session/fullAccessConfirmation';-import { confirmMobileSessionAgentSwitch } from '@/session/sessionAgentSwitchConfirmation';import {+ confirmAgentLocationForPick,+ confirmMobileSessionAgentSwitch,+} from '@/session/sessionAgentSwitchConfirmation';+import {+ effectiveAgentDeviceId,+ intentChangesAgentLocation,mobileAgentLabel,normalizeSessionAgentSwitchIntent,sessionAgentKind as resolveSessionAgentKind,+ sessionAgentRunsOnOtherComputer,supportsMobileSessionAgentSwitch,type MobileSessionAgentKind,} from '@/session/sessionAgentSwitch';+import { useRemoteAgentCatalogs } from '@/session/useRemoteAgentCatalogs';+import { RemoteSourceMark } from '@/session/RemoteSourceMark';import {drainComposerAnnotationSubmissions,drainComposerAttachments,@@ -843,6 +851,8 @@ const ENQUEUE_RECONNECT_BACKOFF_MS = 300;* 闪一下、计时还被重置回 0s。真停了推迟这点时间熄灭无感,交接空隙则被吃掉。*/const COMPOSER_ACTIVITY_SETTLE_MS = 600;+/** 另一台电脑的目录还没读到时的空供应商列表(稳定引用,不触发下游 memo 重算)。 */+const EMPTY_PROVIDER_VIEWS: readonly ProviderView[] = [];/** 落定集合 / 基线的空值(模块级常量:引用稳定,不让 memo 每帧失效)。 */const EMPTY_SETTLING_ITEMS: readonly QueuedRemoteMessage[] = [];@@ -2569,6 +2579,54 @@ export default function SessionScreen() {const composerSwitchesAgent = composerDisplayAgentKind !== sessionAgentKind;const sessionAgentSwitchSupported = !!currentSession&& supportsMobileSessionAgentSwitch(currentSession, capabilities);+ // 远程 Agent:模型列表在被控电脑自己的供应商之外,另列同账号其他电脑上开放了远程调用的供应商+ // (与桌面同一套,2026-10-07 产品裁决)。选另一台电脑的模型 = 把 Agent 挪过去,先二次确认;+ // 同一台电脑内换模型直接切。共享任务访客不能换电脑(被控端拒绝),SSH / Orca 任务不支持切换;+ // 旧被控端不投影 agentDeviceId 字段、也不认换位置参数,这些情况维持原有调用与展示。+ const agentLocationMovable = sessionAgentSwitchSupported+ && !isSharedTaskPeer(deviceId)+ && !!currentSession+ && Object.prototype.hasOwnProperty.call(currentSession, 'agentDeviceId');+ /** Agent 现在所在的电脑(null = 被控电脑)。 */+ const currentAgentDeviceId = sessionAgentRunsOnOtherComputer(currentSession)+ ? currentSession!.agentDeviceId!+ : null;+ /** 下一条消息时 Agent 所在的电脑(挂着换位置的意图就按意图)。 */+ const nextAgentDeviceId = effectiveAgentDeviceId(currentSession, agentSwitchIntent);+ const remoteAgentKeepDeviceIds = useMemo(+ () => [...new Set([currentAgentDeviceId, nextAgentDeviceId].filter((id): id is string => !!id))],+ [currentAgentDeviceId, nextAgentDeviceId],+ );+ const remoteAgentCatalogs = useRemoteAgentCatalogs({+ // 选择器打开时才读其他电脑;Agent 已在另一台电脑时还要按那台的目录显示模型药丸。+ // 共享任务访客读到的是自己账号的设备,与任务无关,不读。+ enabled: !!deviceId && !isSharedTaskPeer(deviceId) && (+ (agentLocationMovable && modelSheetOpen) || remoteAgentKeepDeviceIds.length > 0+ ),+ controlledDeviceId: deviceId,+ keepDeviceIds: remoteAgentKeepDeviceIds,+ keepOnly: !(agentLocationMovable && modelSheetOpen),+ });+ // Agent 在另一台电脑时,模型 / 来源都属于那台的目录:展示与校验按那份,读不到时按加载中处理。+ const agentCatalogFor = useCallback((agentDeviceId: string | null) => {+ if (!agentDeviceId) return composerDeviceProviders;+ const catalog = remoteAgentCatalogs.find((item) => item.deviceId === agentDeviceId);+ return {+ providers: catalog?.providers ?? EMPTY_PROVIDER_VIEWS,+ modelVisibilityOverrides: catalog?.modelVisibilityOverrides,+ loading: !catalog || catalog.status === 'loading',+ // 读不到那台电脑的目录不等于来源被断开:不报错,药丸退回不带来源的写法。+ error: null,+ };+ }, [composerDeviceProviders, remoteAgentCatalogs]);+ const currentAgentCatalog = useMemo(+ () => agentCatalogFor(currentAgentDeviceId),+ [agentCatalogFor, currentAgentDeviceId],+ );+ const composerAgentCatalog = useMemo(+ () => agentCatalogFor(nextAgentDeviceId),+ [agentCatalogFor, nextAgentDeviceId],+ );const runtimeOptions = useMemo(() => currentSession ? buildSessionRuntimeOptions(currentSession, capabilities) : null,[capabilities, currentSession],@@ -2579,7 +2637,7 @@ export default function SessionScreen() {if (!model) return null;const fromRuntime = runtimeOptions?.currentModel?.label?.trim();if (fromRuntime && fromRuntime !== model) return fromRuntime;- const providers = composerDeviceProviders.providers;+ const providers = currentAgentCatalog.providers;const ordered = currentSession?.providerId? [...providers.filter((p) => p.id === currentSession.providerId), ...providers.filter((p) => p.id !== currentSession.providerId)]: providers;@@ -2592,7 +2650,7 @@ export default function SessionScreen() {}}return null;- }, [composerDeviceProviders.providers, currentSession?.model, currentSession?.providerId, runtimeOptions]);+ }, [currentAgentCatalog.providers, currentSession?.model, currentSession?.providerId, runtimeOptions]);// pending intent 只覆盖 composer / selector 的展示,不改 RemoteSession 的真实 DB 字段;// main 在下一条消息发送时提交切换,sessions:patched 回流后展示自然交回真实行。const composerDisplaySession = useMemo(() => {@@ -2625,19 +2683,20 @@ export default function SessionScreen() {[composerDisplayRuntimeOptions, composerDisplaySession, i18nInstance.language],);// 被控端供应商目录 → provider-aware 模型分段(与新建会话页同逻辑;0 供应商回退扁平 modelOptions)。+ // Agent 下一条消息在另一台电脑运行时,模型与来源属于那台的目录。const composerModelSections = useMemo(() => composerDisplaySession? buildMobileModelSections({- providers: composerDeviceProviders.providers,+ providers: composerAgentCatalog.providers,agentKind: composerDisplayAgentKind,selectedModelId: composerDisplaySession.model,selectedProviderId: composerDisplaySession.providerId ?? null,- visibilityOverrides: composerDeviceProviders.modelVisibilityOverrides,+ visibilityOverrides: composerAgentCatalog.modelVisibilityOverrides,// 已建会话:实际路由口径(运行中会话跟真实扣费路由,含停用拷贝)。existingSessionRoute: true,}): null,- [composerDeviceProviders.providers, composerDeviceProviders.modelVisibilityOverrides, composerDisplayAgentKind, composerDisplaySession],+ [composerAgentCatalog.providers, composerAgentCatalog.modelVisibilityOverrides, composerDisplayAgentKind, composerDisplaySession],);// 模型列表元信息(单价 / 折扣版 key presence)—— 与新建会话页同一套隧道缓存 hook。const deviceModelPricing = useDeviceModelPricing(deviceId || undefined);@@ -2648,6 +2707,8 @@ export default function SessionScreen() {// 发送前鉴权提示(对齐 new.tsx 的门禁判定,但不拦截发送:会话内消息走排队,// 用户在电脑端配好 key 后可直接「重试发送」,拦死反而丢掉这条恢复路径)。const composerAgentAuthHint = useMemo(() => {+ // Agent 在另一台电脑运行:凭证在那台,被控电脑没登录不影响发送。+ if (currentAgentDeviceId) return null;const verdict = agentAuthGateVerdict({providers: composerDeviceProviders.providers,loading: composerDeviceProviders.loading,@@ -2661,6 +2722,7 @@ export default function SessionScreen() {composerDeviceProviders.providers,composerDeviceProviders.loading,composerDeviceProviders.error,+ currentAgentDeviceId,sessionAgentKind,]);const sessionMirrorAccessors = useMemo(@@ -2725,28 +2787,28 @@ export default function SessionScreen() {const composerSelectedSourceDisconnected = useMemo(() => {if (!composerDisplaySession) return false;return isSelectedSourceDisconnected({- providers: composerDeviceProviders.providers,+ providers: composerAgentCatalog.providers,providerId: composerDisplaySession.providerId,modelId: composerDisplaySession.model,agentKind: composerDisplayAgentKind,- loading: composerDeviceProviders.loading,- error: composerDeviceProviders.error,+ loading: composerAgentCatalog.loading,+ error: composerAgentCatalog.error,});}, [- composerDeviceProviders.error,- composerDeviceProviders.loading,- composerDeviceProviders.providers,+ composerAgentCatalog.error,+ composerAgentCatalog.loading,+ composerAgentCatalog.providers,composerDisplaySession,composerDisplayAgentKind,]);const composerPillSourceProvider = useMemo(() => {if (!composerSelectedSourceDisconnected) return composerActiveSourceProvider;- return composerDeviceProviders.providers.find(+ return composerAgentCatalog.providers.find((provider) => provider.id === composerDisplaySession?.providerId,) ?? null;}, [composerActiveSourceProvider,- composerDeviceProviders.providers,+ composerAgentCatalog.providers,composerSelectedSourceDisconnected,composerDisplaySession?.providerId,]);@@ -2770,6 +2832,24 @@ export default function SessionScreen() {}): composerRuntimeSummary.modelSummary: '';+ // 下一条消息时 Agent 所在的另一台电脑名(药丸带远程标记,读屏一并读出);目录在缺名时以 deviceId+ // 兜底,那种情况不读出来。+ const nextAgentDeviceName = nextAgentDeviceId+ ? remoteAgentCatalogs.find((item) => item.deviceId === nextAgentDeviceId)?.name ?? null+ : null;+ const composerRuntimeAccessibilityLabel = nextAgentDeviceName && nextAgentDeviceName !== nextAgentDeviceId+ ? [composerRuntimeLabel, nextAgentDeviceName].filter(Boolean).join(', ')+ : composerRuntimeLabel;+ // 换电脑确认里的被控电脑名;路由参数缺设备名时会以 deviceId 兜底,那不是给人看的名字。+ const controlledComputerName = (() => {+ const name = currentSession?.deviceLinkDeviceName?.trim();+ return name && name !== deviceId ? name : null;+ })();+ const remoteAgentDeviceName = useCallback(+ (agentDeviceId: string) =>+ remoteAgentCatalogs.find((item) => item.deviceId === agentDeviceId)?.name ?? agentDeviceId,+ [remoteAgentCatalogs],+ );const adaptiveWindow = useAdaptiveWindow();const paneLayout = sessionPaneLayout(adaptiveWindow);const horizontalSystemHeader = Platform.OS === 'ios' && adaptiveWindow.barEdge === 'none'@@ -6867,6 +6947,7 @@ export default function SessionScreen() {{!sessionManagedByHost && composerRuntimeSummary ? (<ComposerRuntimePilldisabled={sessionManagedByHost || controlBusy || !canUseRemoteSessionControls}+ accessibilityLabel={composerRuntimeAccessibilityLabel}fastOn={composerPillFastOn}label={composerRuntimeLabel}leading={agentSwitchIntent && composerSwitchesAgent ? (@@ -6875,20 +6956,26 @@ export default function SessionScreen() {color={colors.textSecondary}size={iconSize.sm}/>- ) : composerPillSourceId ? (+ ) : composerPillSourceId ? (() => {// 正常态显示真正生效来源;断开态显示 DB 中的真实来源并使用状态色,// 不静默换成 activeSourceId 的默认回退 Logo。- <MobileModelIconMark- color={composerSelectedSourceDisconnected ? colors.statusError : undefined}- icon={composerDisplaySession && composerPillSourceProvider- ? getModel(composerPillSourceProvider, composerDisplaySession.model, composerDisplayAgentKind)?.icon- : undefined}- name={composerPillSourceProvider?.name ?? composerPillSourceId}- providerId={composerPillSourceId}- routing={composerPillSourceProvider?.routing}- logoKind={composerPillSourceProvider?.logoKind}- />- ) : null}+ const sourceMark = (+ <MobileModelIconMark+ color={composerSelectedSourceDisconnected ? colors.statusError : undefined}+ icon={composerDisplaySession && composerPillSourceProvider+ ? getModel(composerPillSourceProvider, composerDisplaySession.model, composerDisplayAgentKind)?.icon+ : undefined}+ name={composerPillSourceProvider?.name ?? composerPillSourceId}+ providerId={composerPillSourceId}+ routing={composerPillSourceProvider?.routing}+ logoKind={composerPillSourceProvider?.logoKind}+ />+ );+ // Agent(下一条消息起)在另一台电脑运行:与桌面 trigger 同一个远程标记。+ return nextAgentDeviceId+ ? <RemoteSourceMark size={iconSize.lg}>{sourceMark}</RemoteSourceMark>+ : sourceMark;+ })() : null}onPress={toggleComposerModelPicker}testID="session.composerModelButton"/>@@ -7690,6 +7777,10 @@ export default function SessionScreen() {nextIntent.providerId,nextIntent.effort,nextIntent.fastMode,+ // 远程 Agent:intent 带位置(null = 改回被控电脑)才发第 7 参;缺省 = 位置不变。+ nextIntent.agentDeviceId !== undefined+ ? { agentDeviceId: nextIntent.agentDeviceId }+ : undefined,);if (agentSwitchWriteSeqRef.current !== seq) return true;// 正常跨引擎写入应返回 deferred。若另一控制端已先完成真实切换,desktop@@ -8075,20 +8166,31 @@ export default function SessionScreen() {hasFastModeCap: modelSheetCapabilities?.hasFastMode === true,memory: sessionMirrorAccessors,});- if (modelSheetAgentKind !== sessionAgentKind) {- void writeSessionAgentSwitchIntent({- targetAgentKind: modelSheetAgentKind,- model: next.model,- providerId: next.providerId,- ...(next.effort ? { effort: next.effort } : {}),- fastMode: next.fastMode,- });- return;- }const atomicSelection = modelSheetCapabilities?.supportsModelWindowSwitchGuard === true? { effort: next.effort || null, fastMode: next.fastMode }: undefined;void (async () => {+ // 这份列表只有被控电脑的目录:Agent 在另一台电脑运行时,选中 = 改回被控电脑运行(先确认)。+ const location = await confirmAgentLocationForPick({+ movable: agentLocationMovable,+ session: currentSession,+ intent: agentSwitchIntent,+ catalogDeviceId: null,+ deviceName: remoteAgentDeviceName,+ hostName: controlledComputerName,+ });+ if (!location) return;+ if (modelSheetAgentKind !== sessionAgentKind || location.agentDeviceId !== undefined) {+ await writeSessionAgentSwitchIntent({+ targetAgentKind: modelSheetAgentKind,+ model: next.model,+ providerId: next.providerId,+ ...(next.effort ? { effort: next.effort } : {}),+ fastMode: next.fastMode,+ ...location,+ });+ return;+ }await runControlAction(async () => {const applied = await setComposerModel({model: next.model,@@ -8118,13 +8220,16 @@ export default function SessionScreen() {}, { recover: 'refetch' });})();}, [+ agentLocationMovable,agentSwitchIntent,canUseRemoteSessionControls,+ controlledComputerName,currentSession,maker,modelSheetAgentKind,modelSheetCapabilities,modelSheetSelection,+ remoteAgentDeviceName,runControlAction,sessionAgentKind,sessionId,@@ -8132,18 +8237,53 @@ export default function SessionScreen() {setComposerModel,writeSessionAgentSwitchIntent,]);- const selectUnifiedComposerModel = useCallback(async (config: MobileModelConfiguration): Promise<boolean> => {+ const selectUnifiedComposerModel = useCallback(async (+ config: MobileModelConfiguration,+ source?: { deviceId: string | null },+ ): Promise<boolean> => {if (!canUseRemoteSessionControls || !currentSession || controlBusy) return false;- const capability = resolveAgentCapability(composerDeviceProviders.providers, config.providerId, config.modelId, config.agent);+ // 远程 Agent:这一行来自哪台电脑的目录(null = 被控电脑),能力就按那份目录核对+ // (同 id 模型两台电脑的档位 / Fast 可以不同)。+ const catalogDeviceId = source?.deviceId ?? null;+ const catalogProviders = catalogDeviceId+ ? remoteAgentCatalogs.find((item) => item.deviceId === catalogDeviceId)?.providers ?? []+ : composerDeviceProviders.providers;+ const capability = resolveAgentCapability(catalogProviders, config.providerId, config.modelId, config.agent);if (!capability) return false;const targetCapabilities = normalizeMobileAgentCapabilities(await maker.getCapabilities(config.agent));if (!targetCapabilities || deviceIdRef.current !== deviceId) return false;if (config.fast && (!capability.supportsFastMode || !targetCapabilities.hasFastMode)) return false;+ // 与任务当前所在电脑不同 = 连 Agent 的运行位置一起换(先确认,下一条消息生效);+ // 同一台电脑内换模型直接切。+ const location = await confirmAgentLocationForPick({+ movable: agentLocationMovable,+ session: currentSession,+ intent: agentSwitchIntent,+ catalogDeviceId,+ deviceName: remoteAgentDeviceName,+ hostName: controlledComputerName,+ });+ if (!location || deviceIdRef.current !== deviceId) return false;+ const relocates = location.agentDeviceId !== undefined;if (config.agent !== sessionAgentKind) {if (!sessionAgentSwitchSupported) return false;- if (agentSwitchIntent?.targetAgentKind !== config.agent && !await confirmMobileSessionAgentSwitch(config.agent, !!agentSwitchIntent)) return false;+ // 换电脑与换引擎是同一份交接风险:换电脑那一步已经确认过,不再叠一层换引擎确认。+ if (!relocates && agentSwitchIntent?.targetAgentKind !== config.agent && !await confirmMobileSessionAgentSwitch(config.agent, !!agentSwitchIntent)) return false;const applied = await writeSessionAgentSwitchIntent({targetAgentKind:config.agent,model:config.modelId,- providerId:config.providerId,effort:config.effort,fastMode:config.fast});+ providerId:config.providerId,effort:config.effort,fastMode:config.fast,...location});+ if (applied) setModelSheetAgentKind(config.agent);+ return applied;+ }+ if (relocates) {+ // 同引擎换电脑:原生会话在原来那台、接不上,同样走下一条消息生效的切换意图。+ const applied = await writeSessionAgentSwitchIntent({+ targetAgentKind: config.agent,+ model: config.modelId,+ providerId: config.providerId,+ ...(config.effort ? { effort: config.effort } : {}),+ fastMode: config.fast,+ ...location,+ });if (applied) setModelSheetAgentKind(config.agent);return applied;}@@ -8162,7 +8302,8 @@ export default function SessionScreen() {return applied;}, [canUseRemoteSessionControls,currentSession,controlBusy,composerDeviceProviders.providers,maker,sessionAgentKind,sessionAgentSwitchSupported,agentSwitchIntent,writeSessionAgentSwitchIntent,- runControlAction,setComposerModel,sessionId,deviceId]);+ runControlAction,setComposerModel,sessionId,deviceId,agentLocationMovable,remoteAgentCatalogs,+ remoteAgentDeviceName,controlledComputerName]);const selectComposerFlatModel = useCallback((option: MobileModelOption) => {setModelSheetOpen(false);@@ -8177,6 +8318,28 @@ export default function SessionScreen() {? { effort: next.effort || null, fastMode: next.fastMode }: undefined;void (async () => {+ // 扁平目录同样是被控电脑的:Agent 在另一台电脑运行时,换模型 = 改回被控电脑运行(先确认,+ // 不带来源 = 默认路由)。+ const location = await confirmAgentLocationForPick({+ movable: agentLocationMovable,+ session: currentSession,+ intent: agentSwitchIntent,+ catalogDeviceId: null,+ deviceName: remoteAgentDeviceName,+ hostName: controlledComputerName,+ });+ if (!location) return;+ if (location.agentDeviceId !== undefined) {+ await writeSessionAgentSwitchIntent({+ targetAgentKind: sessionAgentKind,+ model: option.id,+ providerId: null,+ ...(next.effort ? { effort: next.effort } : {}),+ fastMode: next.fastMode,+ ...location,+ });+ return;+ }await runControlAction(() => setComposerModel({model: option.id,@@ -8191,7 +8354,7 @@ export default function SessionScreen() {},);})();- }, [agentSwitchIntent, canUseRemoteSessionControls, currentSession?.permissionMode, modelSheetAgentKind, modelSheetCapabilities, modelSheetSelection?.effort, modelSheetSelection?.fastMode, runControlAction, sessionAgentKind, setComposerModel]);+ }, [agentLocationMovable, agentSwitchIntent, canUseRemoteSessionControls, controlledComputerName, currentSession, modelSheetAgentKind, modelSheetCapabilities, modelSheetSelection?.effort, modelSheetSelection?.fastMode, remoteAgentDeviceName, runControlAction, sessionAgentKind, setComposerModel, writeSessionAgentSwitchIntent]);const browseComposerModelAgent = useCallback(async (next: MobileSessionAgentKind) => {if (next === modelSheetAgentKind) return true;if (next !== sessionAgentKind) {@@ -8203,8 +8366,10 @@ export default function SessionScreen() {return true;}, [agentSwitchIntent, modelSheetAgentKind, sessionAgentKind, sessionAgentSwitchSupported]);const changeComposerSelectedEffort = useCallback((effort: string) => {+ // 跨引擎 intent,或已登记「改回被控电脑」的同引擎 intent:改 intent 本身(带着位置),+ // 否则 setEffort 的值会在发送时被 intent 里的旧值盖回。if (- modelSheetAgentKind !== sessionAgentKind+ (modelSheetAgentKind !== sessionAgentKind || intentChangesAgentLocation(agentSwitchIntent))&& agentSwitchIntent?.targetAgentKind === modelSheetAgentKind) {void writeSessionAgentSwitchIntent({ ...agentSwitchIntent, effort });@@ -8216,7 +8381,7 @@ export default function SessionScreen() {}, [agentSwitchIntent, maker, modelSheetAgentKind, runControlAction, sessionAgentKind, sessionId, writeSessionAgentSwitchIntent]);const changeComposerSelectedFastMode = useCallback((enabled: boolean) => {if (- modelSheetAgentKind !== sessionAgentKind+ (modelSheetAgentKind !== sessionAgentKind || intentChangesAgentLocation(agentSwitchIntent))&& agentSwitchIntent?.targetAgentKind === modelSheetAgentKind) {void writeSessionAgentSwitchIntent({ ...agentSwitchIntent, fastMode: enabled });@@ -9421,6 +9586,10 @@ export default function SessionScreen() {return result;},onSelect: selectUnifiedComposerModel,+ // 远程 Agent:其他电脑上开放了远程调用的供应商接在后面,每个供应商一段、标题带电脑名。+ ...(agentLocationMovable+ ? { remote: { catalogs: remoteAgentCatalogs, selectedDeviceId: nextAgentDeviceId } }+ : {}),}}activeModelId={modelSheetSelection.model}existingSessionRoute@@ -11762,6 +11931,7 @@ const RouteActionButton = forwardRef<View, RouteActionButtonProps>(function Rout});function ComposerRuntimePill({+ accessibilityLabel,disabled = false,icon: Icon,fastOn = false,@@ -11771,6 +11941,8 @@ function ComposerRuntimePill({testID,tone,}: {+ /** 读屏标签;缺省 = 可见 label(远程 Agent 任务追加 Agent 位置说明)。 */+ accessibilityLabel?: string;disabled?: boolean;icon?: typeof Hand;/** Fast 已生效 → label 后缀 Zap 闪电(对齐桌面 trigger)。 */@@ -11787,7 +11959,7 @@ function ComposerRuntimePill({const color = tone === 'bypassPermissions' ? colors.statusAccent : colors.textSecondary;return (<RouteActionButton- accessibilityLabel={label}+ accessibilityLabel={accessibilityLabel ?? label}disabled={disabled}hitSlop={COMPOSER_CONTROL_HIT_SLOP}onPress={onPress}diff --git a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsxindex c9e3f9dfc8..bcb700261f 100644--- a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx+++ b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx@@ -231,6 +231,12 @@ vi.mock("@/session/MobileProviderMark", async () => {el("i", { "data-model-mark": providerId }),};});+vi.mock("@/session/RemoteSourceMark", async () => {+ const { createElement: el } = await import("react");+ return {+ RemoteSourceMark: ({ children }: AnyProps) => el("span", { "data-remote-mark": "" }, children),+ };+});vi.mock("@/session/sessionAgentSwitch", () => ({mobileAgentLabel: (agent: string) => `agent:${agent}`,}));diff --git a/apps/mobile/src/__tests__/designTokenDiscipline.test.ts b/apps/mobile/src/__tests__/designTokenDiscipline.test.tsindex b03cc29999..485de94d78 100644--- a/apps/mobile/src/__tests__/designTokenDiscipline.test.ts+++ b/apps/mobile/src/__tests__/designTokenDiscipline.test.ts@@ -76,6 +76,11 @@ const ALLOWLIST: Array<{ file: string; snippet: string; reason: string }> = [snippet: 'borderRadius: 0',reason: '显式方角覆盖,非漂移(通栏布局回退恢复,用户改稿 2026-07-21)',},+ {+ file: 'src/session/RemoteSourceMark.tsx',+ snippet: 'strokeWidth={1.4}',+ reason: '远程标记波纹:16 单位 viewBox 内的图形几何(移植桌面同值,随图标缩放),非阶梯图标描边',+ },];function collectFiles(): string[] {diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex 5a58487dbb..9d276269ca 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -682,6 +682,28 @@ describe("mobile maker transport", () => {]);});+ it("sends the remote-Agent location as the 7th switch-session-agent arg only when given", async () => {+ const { calls, maker } = harness();++ await maker.switchSessionAgent("s1", "claude-code", "claude-sonnet-4-6", "anthropic", "high", false, {+ agentDeviceId: null,+ });+ await maker.switchSessionAgent("s1", "codex", "gpt-5.5", null, undefined, undefined, {+ agentDeviceId: null,+ });+ await maker.switchSessionAgent("s1", "codex", "gpt-5.5", "openai", "high", true, {});+ await maker.switchSessionAgent("s1", "codex", "gpt-5.5", "openai", "high", true);++ expect(calls.map((call) => call.args)).toEqual([+ ["s1", "claude-code", "claude-sonnet-4-6", "anthropic", "high", false, { agentDeviceId: null }],+ ["s1", "codex", "gpt-5.5", null, null, null, { agentDeviceId: null }],+ // 未给位置 = 位置不变:与旧 6 参 wire 完全一致,旧被控端无感。+ ["s1", "codex", "gpt-5.5", "openai", "high", true],+ ["s1", "codex", "gpt-5.5", "openai", "high", true],+ ]);+ expect(calls.every((call) => call.channel === "maker:switch-session-agent")).toBe(true);+ });+it("fails closed when a legacy Desktop returns model-window confirmation data", async () => {const invoke: RemoteInvoke = async () =>({diff --git a/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts b/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.tsindex 5acb04a207..3e13c7b8ff 100644--- a/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts+++ b/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts@@ -3,6 +3,10 @@ import { resolve } from 'node:path';import ts from 'typescript';import { expect, it, vi } from 'vitest';+vi.mock('react-native', () => ({ Alert: { alert: vi.fn() } }));++import { confirmAgentLocationForPick } from '@/session/sessionAgentSwitchConfirmation';+const source = ts.createSourceFile('screen.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);let callback: ts.Expression | undefined;function visit(node: ts.Node) {@@ -13,21 +17,46 @@ function visit(node: ts.Node) {}visit(source);const js = ts.transpileModule(`const select = ${callback!.getText(source)};`, {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;-function harness(confirmed = true, saved = true) {+const studioProviders = [{ id: 'studio-account' }];+function harness(+ confirmed = true,+ saved = true,+ session: Record<string, unknown> = {},+ overrides: Record<string, unknown> = {},+) {const state = { agent: 'codex', intent: null as any };const setModelSheetAgentKind = vi.fn((agent: string) => { state.agent = agent; });+ const writeSessionAgentSwitchIntent = vi.fn(async(intent:unknown)=>{if(saved) state.intent=intent;return saved;});+ const setComposerModel = vi.fn(async()=>saved);+ const confirmMobileSessionAgentSwitch = vi.fn(async()=>confirmed);+ // 换电脑确认:按 confirmed 点「换电脑运行」或「保持不变」。+ const relocationAlert = vi.fn((_title: string, _message?: string, buttons?: { onPress?: () => void }[]) => {+ buttons?.[confirmed ? 1 : 0]?.onPress?.();+ });+ const resolveAgentCapability = vi.fn(() => ({ supportsFastMode: true }));const env = {- canUseRemoteSessionControls:true, currentSession:{effort:'low',fastMode:false},controlBusy:false,- composerDeviceProviders:{providers:[]}, resolveAgentCapability:()=>({supportsFastMode:true}),+ agentLocationMovable:true,+ remoteAgentCatalogs:[{ deviceId:'device-studio-mac', name:'工作室 Mac', status:'ready', providers:studioProviders }],+ remoteAgentDeviceName:(id:string)=>id === 'device-studio-mac' ? '工作室 Mac' : id,+ controlledComputerName:'Home Mac',+ confirmAgentLocationForPick:(input: Parameters<typeof confirmAgentLocationForPick>[0]) =>+ confirmAgentLocationForPick(input, relocationAlert),+ canUseRemoteSessionControls:true,+ currentSession:{effort:'low',fastMode:false,agentKind:'codex',model:'current-model',providerId:null,agentDeviceId:null,...session},controlBusy:false,+ composerDeviceProviders:{providers:[]}, resolveAgentCapability,normalizeMobileAgentCapabilities:(x:unknown)=>x, maker:{getCapabilities:async()=>({hasFastMode:true}),setEffort:vi.fn(),setFastMode:vi.fn()},deviceId:'device',deviceIdRef:{current:'device'},sessionAgentKind:'codex',sessionAgentSwitchSupported:true,- confirmMobileSessionAgentSwitch:async()=>confirmed,- writeSessionAgentSwitchIntent:async(intent:unknown)=>{if(saved) state.intent=intent;return saved;},- setModelSheetAgentKind, setComposerModel:async()=>saved,sessionId:'session',+ confirmMobileSessionAgentSwitch,+ writeSessionAgentSwitchIntent,+ setModelSheetAgentKind, setComposerModel,sessionId:'session',runControlAction:async(action:()=>Promise<boolean>,patch:any)=>{const ok=await action();if(ok)state.intent=patch.agentSwitchIntent;return ok;},+ ...overrides,};const render = () => new Function(...Object.keys(env), 'agentSwitchIntent', `${js}; return select;`)(...Object.values(env),state.intent);- return {state,render,setModelSheetAgentKind};+ return {+ state, render, setModelSheetAgentKind, writeSessionAgentSwitchIntent, setComposerModel,+ confirmMobileSessionAgentSwitch, relocationAlert, resolveAgentCapability,+ };}const config = {agent:'pi',providerId:'account',modelId:'model',effort:'high',fast:false};it('keeps the new Harness for subsequent effort/Fast edits and switches back on success',async()=>{@@ -46,3 +75,65 @@ it.each([[false,true],[true,false]])('does not change the browsed Harness on rejexpect(h.setModelSheetAgentKind).not.toHaveBeenCalled();expect(h.state.intent).toBeNull();});++// 远程 Agent:模型列表另列其他电脑的供应商。同一台电脑内换模型直接切,换到另一台电脑先确认、+// 再带 agentDeviceId(null = 被控电脑)。+const studio = { deviceId: 'device-studio-mac' };+const studioConfig = { ...config, agent: 'codex', providerId: 'studio-account' };+it('switches directly between models of the same computer', async () => {+ const h = harness(true, true, { agentDeviceId: 'device-studio-mac' });+ expect(await h.render()(studioConfig, studio)).toBe(true);+ expect(h.relocationAlert).not.toHaveBeenCalled();+ expect(h.writeSessionAgentSwitchIntent).not.toHaveBeenCalled();+ expect(h.setComposerModel).toHaveBeenCalledWith(expect.objectContaining({ model: 'model', providerId: 'studio-account' }));+ // 能力按这一行所属电脑的目录核对。+ expect(h.resolveAgentCapability).toHaveBeenCalledWith(studioProviders, 'studio-account', 'model', 'codex');+});+it('asks before moving the Agent to another computer and registers the move', async () => {+ const h = harness();+ expect(await h.render()(studioConfig, studio)).toBe(true);+ expect(h.relocationAlert).toHaveBeenCalledTimes(1);+ expect(h.relocationAlert.mock.calls[0]?.[0]).toContain('工作室 Mac');+ expect(h.setComposerModel).not.toHaveBeenCalled();+ expect(h.writeSessionAgentSwitchIntent).toHaveBeenCalledWith({+ targetAgentKind: 'codex', model: 'model', providerId: 'studio-account', effort: 'high', fastMode: false,+ agentDeviceId: 'device-studio-mac',+ });+ // 已确认过的同一台:在那台的目录里改选不再问,继续带位置。+ expect(await h.render()({ ...studioConfig, modelId: 'other-model' }, studio)).toBe(true);+ expect(h.relocationAlert).toHaveBeenCalledTimes(1);+ expect(h.state.intent).toMatchObject({ model: 'other-model', agentDeviceId: 'device-studio-mac' });+});+it('keeps everything unchanged when the move is cancelled', async () => {+ const h = harness(false);+ expect(await h.render()(studioConfig, studio)).toBe(false);+ expect(h.writeSessionAgentSwitchIntent).not.toHaveBeenCalled();+ expect(h.setComposerModel).not.toHaveBeenCalled();+ expect(h.state.intent).toBeNull();+});+it('asks before moving a remote Agent back to the controlled computer', async () => {+ const h = harness(true, true, { agentDeviceId: 'device-studio-mac' });+ expect(await h.render()({ ...config, agent: 'codex' }, { deviceId: null })).toBe(true);+ expect(h.relocationAlert.mock.calls[0]?.[0]).toContain('Home Mac');+ expect(h.setComposerModel).not.toHaveBeenCalled();+ expect(h.writeSessionAgentSwitchIntent).toHaveBeenCalledWith(expect.objectContaining({+ targetAgentKind: 'codex', model: 'model', providerId: 'account', agentDeviceId: null,+ }));+});+it('confirms a cross-engine move to another computer only once', async () => {+ const h = harness();+ expect(await h.render()({ ...config, providerId: 'studio-account' }, studio)).toBe(true);+ expect(h.relocationAlert).toHaveBeenCalledTimes(1);+ expect(h.confirmMobileSessionAgentSwitch).not.toHaveBeenCalled();+ expect(h.state.intent).toMatchObject({ targetAgentKind: 'pi', agentDeviceId: 'device-studio-mac' });+ expect(h.state.agent).toBe('pi');+});+it('does not move the Agent when the controller may not change its location', async () => {+ // 共享任务访客 / 不支持切换 / 旧被控端:agentLocationMovable=false,只接受被控电脑的目录。+ const h = harness(true, true, {}, { agentLocationMovable: false });+ expect(await h.render()(studioConfig, studio)).toBe(false);+ expect(h.relocationAlert).not.toHaveBeenCalled();+ expect(h.writeSessionAgentSwitchIntent).not.toHaveBeenCalled();+ expect(await h.render()({ ...config, agent: 'codex' })).toBe(true);+ expect(h.setComposerModel).toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts b/apps/mobile/src/__tests__/remoteAgentCatalogs.test.tsnew file mode 100644index 0000000000..ac541a3c7c--- /dev/null+++ b/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts@@ -0,0 +1,88 @@+import type { DeviceView } from '@cindy/device-link';+import type { ProviderView } from '@cindy/model-providers/registry';+import { describe, expect, it } from 'vitest';++import { remoteAgentProviders, selectRemoteAgentDevices } from '@/session/remoteAgentCatalogs';+import { groupSourceFilters, remoteFilterId } from '@/session/remoteSourceFilters';++const device = (deviceId: string, patch: Partial<DeviceView> = {}): DeviceView => ({+ deviceId,+ name: deviceId,+ platform: 'darwin',+ appVersion: '1.0.0',+ lastSeenAt: null,+ online: true,+ busy: false,+ remoteControlEnabled: true,+ isSelf: false,+ ...patch,+});++describe('remote Agent catalogs', () => {+ it('lists the other computers the Agent can run on', () => {+ const devices = [+ device('controlled', { name: 'Home Mac' }),+ device('studio', { name: 'Studio Mac' }),+ device('office', { name: 'Office PC', platform: 'win32', busy: true }),+ device('offline', { name: 'Old Laptop', online: false }),+ device('locked', { name: 'Locked PC', remoteControlEnabled: false }),+ device('revoked', { name: 'Revoked PC' }),+ device('phone', { name: 'iPhone', platform: 'ios' }),+ device('self', { name: 'This phone', isSelf: true }),+ device('unnamed', { name: ' ' }),+ ];+ expect(selectRemoteAgentDevices({+ devices,+ controlledDeviceId: 'controlled',+ keepDeviceIds: [],+ revokedDeviceIds: new Set(['revoked']),+ })).toEqual([+ { deviceId: 'unnamed', name: 'unnamed', canOpen: true },+ { deviceId: 'office', name: 'Office PC', canOpen: true },+ { deviceId: 'studio', name: 'Studio Mac', canOpen: true },+ ]);+ });++ it('keeps the computer the Agent runs on even when it cannot be reached', () => {+ const selected = selectRemoteAgentDevices({+ devices: [device('controlled'), device('offline', { name: 'Old Laptop', online: false })],+ controlledDeviceId: 'controlled',+ keepDeviceIds: ['offline'],+ });+ expect(selected).toEqual([{ deviceId: 'offline', name: 'Old Laptop', canOpen: false }]);+ });++ it('only offers providers that computer allows to be used remotely', () => {+ const providers = [+ { id: 'allowed', remoteInvocationEnabled: true },+ { id: 'closed', remoteInvocationEnabled: false },+ { id: 'legacy' },+ ] as unknown as ProviderView[];+ expect(remoteAgentProviders(providers).map((provider) => provider.id)).toEqual(['allowed']);+ });++ it('groups source choices into one block per computer', () => {+ type Filter = { id: string; remote?: { deviceId: string; deviceName: string } };+ const remote = (deviceId: string, deviceName: string, providerId: string): Filter => ({+ id: remoteFilterId(deviceId, providerId),+ remote: { deviceId, deviceName },+ });+ const filters: Filter[] = [+ { id: 'all' },+ { id: 'favorites' },+ remote('studio', 'Studio Mac', 'claude'),+ { id: 'local-provider' },+ remote('office', 'Office PC', 'codex'),+ remote('studio', 'Studio Mac', 'openrouter'),+ ];+ const groups = groupSourceFilters(filters);+ expect(groups.local.map((item) => item.id)).toEqual(['all', 'favorites', 'local-provider']);+ expect(groups.devices.map((item) => [item.deviceId, item.name, item.filters.map((f) => f.id)])).toEqual([+ ['studio', 'Studio Mac', [remoteFilterId('studio', 'claude'), remoteFilterId('studio', 'openrouter')]],+ ['office', 'Office PC', [remoteFilterId('office', 'codex')]],+ ]);+ // 远程格 id 不会和本机供应商 id 撞,哪怕供应商 id 相同。+ expect(remoteFilterId('studio', 'local-provider')).not.toBe('local-provider');+ expect(remoteFilterId('a:b', 'c')).not.toBe(remoteFilterId('a', 'b:c'));+ });+});diff --git a/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitch.test.tsindex dde9113804..bd8acb110a 100644--- a/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts+++ b/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts@@ -1,11 +1,16 @@import { describe, expect, it } from 'vitest';import {+ effectiveAgentDeviceId,+ intentChangesAgentLocation,mobileAgentLabel,mobileAgentLabelFromUnknown,mobileAgentVendor,normalizeSessionAgentSwitchIntent,+ readAgentSwitchLocationTarget,+ resolveAgentLocationPick,sessionAgentKind,+ sessionAgentRunsOnOtherComputer,supportsMobileSessionAgentSwitch,} from '@/session/sessionAgentSwitch';import type { MobileAgentCapabilities } from '@/session/agentCapabilities';@@ -76,3 +81,108 @@ describe('mobile session Agent switch contract', () => {expect(supportsMobileSessionAgentSwitch({ remoteHostId: null, orcaRole: null }, null)).toBe(false);});});++describe('remote Agent location (Agent runs on another computer)', () => {+ const remoteSession = { agentDeviceId: 'device-office-pc' };+ const localSession = { agentDeviceId: null };+ const intentTo = (agentDeviceId: string | null) => ({+ targetAgentKind: 'claude-code' as const, model: 'm', providerId: null, agentDeviceId,+ });++ it('keeps the optional agentDeviceId of a pending intent', () => {+ expect(normalizeSessionAgentSwitchIntent({+ targetAgentKind: 'claude-code',+ model: 'claude-sonnet-4-6',+ providerId: 'anthropic',+ agentDeviceId: null,+ })).toEqual({+ targetAgentKind: 'claude-code',+ model: 'claude-sonnet-4-6',+ providerId: 'anthropic',+ agentDeviceId: null,+ });+ expect(normalizeSessionAgentSwitchIntent({+ targetAgentKind: 'codex', model: 'gpt-5.5', providerId: null, agentDeviceId: 'device-office-pc',+ })).toEqual({+ targetAgentKind: 'codex', model: 'gpt-5.5', providerId: null, agentDeviceId: 'device-office-pc',+ });+ // 缺省 = 位置不变,不补出该键。+ expect(normalizeSessionAgentSwitchIntent({+ targetAgentKind: 'codex', model: 'gpt-5.5', providerId: null,+ })).not.toHaveProperty('agentDeviceId');+ // 脏值与其它字段同口径判非法。+ expect(normalizeSessionAgentSwitchIntent({+ targetAgentKind: 'codex', model: 'gpt-5.5', providerId: null, agentDeviceId: 42,+ })).toBeNull();+ expect(normalizeSessionAgentSwitchIntent({+ targetAgentKind: 'codex', model: 'gpt-5.5', providerId: null, agentDeviceId: '',+ })).toBeNull();+ });++ it('tells where the Agent runs now and for the next message', () => {+ expect(sessionAgentRunsOnOtherComputer(remoteSession)).toBe(true);+ expect(sessionAgentRunsOnOtherComputer({ agentDeviceId: null })).toBe(false);+ expect(sessionAgentRunsOnOtherComputer({ agentDeviceId: '' })).toBe(false);+ expect(sessionAgentRunsOnOtherComputer({})).toBe(false);+ expect(sessionAgentRunsOnOtherComputer(null)).toBe(false);+ expect(intentChangesAgentLocation(intentTo(null))).toBe(true);+ expect(intentChangesAgentLocation(intentTo('device-studio-mac'))).toBe(true);+ expect(intentChangesAgentLocation({ targetAgentKind: 'codex', model: 'm', providerId: null })).toBe(false);+ expect(intentChangesAgentLocation(null)).toBe(false);+ expect(effectiveAgentDeviceId(remoteSession, null)).toBe('device-office-pc');+ expect(effectiveAgentDeviceId(localSession, null)).toBeNull();+ expect(effectiveAgentDeviceId(remoteSession, intentTo(null))).toBeNull();+ expect(effectiveAgentDeviceId(localSession, intentTo('device-studio-mac'))).toBe('device-studio-mac');+ // 不带位置的意图(只换引擎 / 模型)不改位置。+ expect(effectiveAgentDeviceId(remoteSession, {+ targetAgentKind: 'codex', model: 'm', providerId: null,+ })).toBe('device-office-pc');+ });++ it('switches directly inside the same computer', () => {+ // 被控电脑上的任务选被控电脑的模型;另一台电脑上的任务选那台的模型。+ expect(resolveAgentLocationPick({ session: localSession, intent: null, catalogDeviceId: null }))+ .toEqual({ relocateTo: undefined, needsConfirm: false });+ expect(resolveAgentLocationPick({+ session: remoteSession, intent: null, catalogDeviceId: 'device-office-pc',+ })).toEqual({ relocateTo: undefined, needsConfirm: false });+ });++ it('asks before moving the Agent to another computer and carries the new location', () => {+ expect(resolveAgentLocationPick({+ session: localSession, intent: null, catalogDeviceId: 'device-studio-mac',+ })).toEqual({ relocateTo: 'device-studio-mac', needsConfirm: true });+ // 改回被控电脑同样是换电脑(null = 被控电脑)。+ expect(resolveAgentLocationPick({ session: remoteSession, intent: null, catalogDeviceId: null }))+ .toEqual({ relocateTo: null, needsConfirm: true });+ expect(resolveAgentLocationPick({+ session: remoteSession, intent: null, catalogDeviceId: 'device-studio-mac',+ })).toEqual({ relocateTo: 'device-studio-mac', needsConfirm: true });+ });++ it('does not ask again within an already confirmed move, nor when undoing it', () => {+ // 已确认换到工作室 Mac:在那台的目录里改选,继续带位置、不再问。+ expect(resolveAgentLocationPick({+ session: localSession, intent: intentTo('device-studio-mac'), catalogDeviceId: 'device-studio-mac',+ })).toEqual({ relocateTo: 'device-studio-mac', needsConfirm: false });+ // 选回任务当前所在电脑 = 撤销挂着的换位置:不带位置、不问。+ expect(resolveAgentLocationPick({+ session: localSession, intent: intentTo('device-studio-mac'), catalogDeviceId: null,+ })).toEqual({ relocateTo: undefined, needsConfirm: false });+ // 挂着换位置时又换到第三台电脑:要再问一次。+ expect(resolveAgentLocationPick({+ session: localSession, intent: intentTo('device-studio-mac'), catalogDeviceId: 'device-office-pc',+ })).toEqual({ relocateTo: 'device-office-pc', needsConfirm: true });+ });++ it('reads the boundary location only when the Agent changed computers', () => {+ expect(readAgentSwitchLocationTarget(undefined)).toBeNull();+ expect(readAgentSwitchLocationTarget({ fromAgentKind: 'cc', toAgentKind: 'codex' })).toBeNull();+ expect(readAgentSwitchLocationTarget({ toAgentDeviceId: null, toAgentDeviceName: 'Studio Mac' }))+ .toEqual({ kind: 'named', name: 'Studio Mac' });+ expect(readAgentSwitchLocationTarget({ toAgentDeviceId: null, toAgentDeviceName: null }))+ .toEqual({ kind: 'thisComputer' });+ expect(readAgentSwitchLocationTarget({ toAgentDeviceId: 'device-office-pc', toAgentDeviceName: ' ' }))+ .toEqual({ kind: 'otherComputer' });+ });+});diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.tsindex 3ee9c2e276..611bc9c11d 100644--- a/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts+++ b/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts@@ -3,7 +3,10 @@ import { beforeAll, describe, expect, it, vi } from 'vitest';vi.mock('react-native', () => ({ Alert: { alert: vi.fn() } }));import { i18n } from '@/i18n';-import { confirmMobileSessionAgentSwitch } from '@/session/sessionAgentSwitchConfirmation';+import {+ confirmAgentLocationForPick,+ confirmMobileSessionAgentSwitch,+} from '@/session/sessionAgentSwitchConfirmation';// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。beforeAll(async () => {@@ -32,3 +35,75 @@ describe('confirmMobileSessionAgentSwitch', () => {expect(showAlert.mock.calls[0]?.[1]).toContain('下一条消息发送时');});});++describe('confirmAgentLocationForPick (remote Agent)', () => {+ const base = {+ movable: true,+ session: { agentDeviceId: null },+ intent: null,+ deviceName: (deviceId: string) => (deviceId === 'device-studio-mac' ? '工作室 Mac' : deviceId),+ hostName: '家里的 Mac',+ };+ const confirm = () => vi.fn((_title, _message, buttons) => buttons?.[1]?.onPress?.());++ it('switches directly inside the same computer without asking', async () => {+ const showAlert = vi.fn();+ await expect(confirmAgentLocationForPick({ ...base, catalogDeviceId: null }, showAlert)).resolves.toEqual({});+ await expect(confirmAgentLocationForPick({+ ...base, session: { agentDeviceId: 'device-studio-mac' }, catalogDeviceId: 'device-studio-mac',+ }, showAlert)).resolves.toEqual({});+ expect(showAlert).not.toHaveBeenCalled();+ });++ it('asks before moving to another computer, naming it', async () => {+ const showAlert = confirm();+ await expect(confirmAgentLocationForPick({ ...base, catalogDeviceId: 'device-studio-mac' }, showAlert))+ .resolves.toEqual({ agentDeviceId: 'device-studio-mac' });+ expect(showAlert.mock.calls[0]?.[0]).toBe('改到「工作室 Mac」上运行 Agent?');+ expect(showAlert.mock.calls[0]?.[1]).toContain('交接摘要');+ expect(showAlert.mock.calls[0]?.[2]?.map((button: { text: string }) => button.text))+ .toEqual(['保持不变', '换电脑运行']);+ });++ it('asks before moving back to the controlled computer', async () => {+ const named = confirm();+ await expect(confirmAgentLocationForPick({+ ...base, session: { agentDeviceId: 'device-studio-mac' }, catalogDeviceId: null,+ }, named)).resolves.toEqual({ agentDeviceId: null });+ expect(named.mock.calls[0]?.[0]).toBe('改回「家里的 Mac」上运行 Agent?');+ const unnamed = confirm();+ await confirmAgentLocationForPick({+ ...base, hostName: null, session: { agentDeviceId: 'device-studio-mac' }, catalogDeviceId: null,+ }, unnamed);+ expect(unnamed.mock.calls[0]?.[0]).toBe('改回任务所在的电脑运行 Agent?');+ });++ it('changes nothing when the move is cancelled or dismissed', async () => {+ const cancel = vi.fn((_title, _message, buttons) => buttons?.[0]?.onPress?.());+ await expect(confirmAgentLocationForPick({ ...base, catalogDeviceId: 'device-studio-mac' }, cancel))+ .resolves.toBeNull();+ const dismiss = vi.fn((_title, _message, _buttons, options) => options?.onDismiss?.());+ await expect(confirmAgentLocationForPick({ ...base, catalogDeviceId: 'device-studio-mac' }, dismiss))+ .resolves.toBeNull();+ });++ it('does not ask again for an already confirmed target', async () => {+ const showAlert = vi.fn();+ await expect(confirmAgentLocationForPick({+ ...base,+ intent: { targetAgentKind: 'codex', model: 'm', providerId: null, agentDeviceId: 'device-studio-mac' },+ catalogDeviceId: 'device-studio-mac',+ }, showAlert)).resolves.toEqual({ agentDeviceId: 'device-studio-mac' });+ expect(showAlert).not.toHaveBeenCalled();+ });++ it('only accepts the controlled computer when the task cannot move', async () => {+ const showAlert = vi.fn();+ await expect(confirmAgentLocationForPick({ ...base, movable: false, catalogDeviceId: null }, showAlert))+ .resolves.toEqual({});+ await expect(confirmAgentLocationForPick({+ ...base, movable: false, catalogDeviceId: 'device-studio-mac',+ }, showAlert)).resolves.toBeNull();+ expect(showAlert).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.tsindex 5980c4b36c..a556baf981 100644--- a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts@@ -18,6 +18,66 @@ describe('session Agent switch UI wiring', () => {expect(source).toContain('...(agentSwitchIntent ? { agentSwitchIntent: null } : {})');});+ it('lists other computers in the model sheet and moves the Agent only after confirmation', () => {+ const source = readSource('app/sessions/[sessionId].tsx');+ const writerStart = source.indexOf('const writeSessionAgentSwitchIntent = useCallback');+ const writer = source.slice(writerStart, source.indexOf('// Context 面板', writerStart));+ // 唯一写出口把 intent 的位置作为第 7 参转给被控端;没有位置时不发(旧 6 参 wire)。+ expect(writer).toContain('nextIntent.agentDeviceId !== undefined');+ expect(writer).toContain('? { agentDeviceId: nextIntent.agentDeviceId }');+ // 共享任务访客不能挪 Agent 位置,SSH / Orca 不支持切换,旧被控端不投影位置字段。+ expect(source).toContain('const agentLocationMovable = sessionAgentSwitchSupported');+ expect(source).toContain("&& !isSharedTaskPeer(deviceId)");+ expect(source).toContain("Object.prototype.hasOwnProperty.call(currentSession, 'agentDeviceId')");+ // 模型列表另列其他电脑的供应商,选中态跟着下一条消息时 Agent 所在的电脑。+ expect(source).toContain(+ '? { remote: { catalogs: remoteAgentCatalogs, selectedDeviceId: nextAgentDeviceId } }',+ );+ // 顶部常驻说明已去掉,由换电脑前的二次确认代替。+ expect(source).not.toContain('notice={agentLocationNotice}');++ const rowSelector = source.slice(+ source.indexOf('const selectComposerModelRow'),+ source.indexOf('const selectUnifiedComposerModel'),+ );+ const unifiedSelector = source.slice(+ source.indexOf('const selectUnifiedComposerModel'),+ source.indexOf('const selectComposerFlatModel'),+ );+ const flatSelector = source.slice(+ source.indexOf('const selectComposerFlatModel'),+ source.indexOf('const browseComposerModelAgent'),+ );+ for (const selector of [rowSelector, unifiedSelector, flatSelector]) {+ expect(selector).toContain('await confirmAgentLocationForPick({');+ expect(selector).toContain('intent: agentSwitchIntent,');+ // 换电脑的选择走切换意图,而且必须在 setModel 之前分流;取消 = 什么都不改。+ expect(selector).toMatch(/if \(!location(?: \|\| deviceIdRef\.current !== deviceId)?\) return/);+ expect(selector.indexOf('writeSessionAgentSwitchIntent(')).toBeGreaterThan(-1);+ expect(selector.indexOf('writeSessionAgentSwitchIntent(')).toBeLessThan(+ selector.indexOf('setComposerModel('),+ );+ }+ // 被控电脑自己的列表(旧版 / 扁平)只来自被控电脑。+ expect(rowSelector).toContain('catalogDeviceId: null,');+ expect(flatSelector).toContain('catalogDeviceId: null,');+ expect(unifiedSelector).toContain('const catalogDeviceId = source?.deviceId ?? null;');++ // 已登记换位置时,推理强度 / Fast 改的是 intent 本身(带着位置),不是 setEffort / setFastMode。+ const toggles = source.slice(+ source.indexOf('const changeComposerSelectedEffort'),+ source.indexOf('const toggleComposerModelPicker'),+ );+ expect(toggles.match(+ /\(modelSheetAgentKind !== sessionAgentKind \|\| intentChangesAgentLocation\(agentSwitchIntent\)\)/g,+ )).toHaveLength(2);++ // 模型药丸按 Agent 所在电脑的目录显示,带远程标记;读屏标签读出那台电脑。+ expect(source).toContain('providers: composerAgentCatalog.providers,');+ expect(source).toContain('<RemoteSourceMark size={iconSize.lg}>{sourceMark}</RemoteSourceMark>');+ expect(source).toContain('accessibilityLabel={composerRuntimeAccessibilityLabel}');+ });+it('uses the browsed Agent capabilities and selection in the shared model sheet', () => {const source = readSource('app/sessions/[sessionId].tsx');expect(source).toContain('agentKind={modelSheetAgentKind}');diff --git a/apps/mobile/src/__tests__/systemCard.test.ts b/apps/mobile/src/__tests__/systemCard.test.tsindex fca34109d1..e84d7084e9 100644--- a/apps/mobile/src/__tests__/systemCard.test.ts+++ b/apps/mobile/src/__tests__/systemCard.test.ts@@ -205,6 +205,43 @@ describe('formatMobileSystemCard — Agent 切换', () => {toModel: 'gpt-5.6',}).title).toContain('Pi');});++ it('describes the new location when the Agent changed computers', () => {+ const base = { fromAgentKind: 'cc', toAgentKind: 'cc', toModel: 'claude-sonnet-4-6' };+ // 只有 content 带 toAgentDeviceId 键才算换电脑;没带仍是「已从 X 切换到 Y」。+ expect(formatMobileSystemCard('agent-switch', base).title).toBe(+ i18n.t('message.systemCard.agentSwitch', { from: 'Claude Code', to: 'Claude Code' }),+ );+ expect(formatMobileSystemCard('agent-switch', {+ ...base,+ fromAgentDeviceId: 'device-office-pc',+ toAgentDeviceId: null,+ fromAgentDeviceName: 'Office PC',+ toAgentDeviceName: 'Studio Mac',+ })).toEqual({+ title: i18n.t('message.systemCard.agentSwitchLocation', { device: 'Studio Mac' }),+ rows: [{ label: i18n.t('message.systemCard.modelLabel'), value: 'claude-sonnet-4-6' }],+ });+ expect(formatMobileSystemCard('agent-switch', {+ ...base,+ toAgentDeviceId: null,+ toAgentDeviceName: null,+ }).title).toBe(i18n.t('message.systemCard.agentSwitchLocationThisComputer'));+ expect(formatMobileSystemCard('agent-switch', {+ ...base,+ toAgentDeviceId: 'device-office-pc',+ toAgentDeviceName: null,+ }).title).toBe(i18n.t('message.systemCard.agentSwitchLocationOtherComputer'));+ // 换电脑的同时换了引擎:位置后带上目标引擎。+ expect(formatMobileSystemCard('agent-switch', {+ ...base,+ toAgentKind: 'codex',+ toAgentDeviceId: null,+ toAgentDeviceName: 'Studio Mac',+ }).title).toBe(+ `${i18n.t('message.systemCard.agentSwitchLocation', { device: 'Studio Mac' })} · Codex`,+ );+ });});describe('commandNeedsRemoteSession', () => {diff --git a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsxindex 307c21578b..48c0bd6186 100644--- a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx+++ b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx@@ -47,7 +47,7 @@ it('keeps the sheet and preferences unchanged after cancelled selection',async()it('only closes after selection succeeds and passes the full wire configuration',async()=>{const {onSelect,onClose}=await mount();await act(async()=>test.view.onSelect(test.view.groups[0].rows[0]));- expect(onSelect).toHaveBeenCalledWith({providerId:'account',modelId:'codex/model',agent:'codex',effort:'medium',fast:false});+ expect(onSelect).toHaveBeenCalledWith({providerId:'account',modelId:'codex/model',agent:'codex',effort:'medium',fast:false},{deviceId:null});expect(onClose).toHaveBeenCalledOnce();});it('shows favorites before recommendations, with selected mark only on the model',async()=>{@@ -539,3 +539,69 @@ it('explains a closed current model without changing it and still allows choosinawait act(async () => test.view.onSelect(test.view.groups[0].rows[0]));expect(onSelect).toHaveBeenCalledOnce();});++// 远程 Agent:其他电脑上开放了远程调用的供应商接在被控电脑自己的之后,每个供应商一段、标题带电脑名。+const studioCatalog = {+ deviceId:'device-studio-mac', name:'Studio Mac', status:'ready',+ providers:[{id:'account',name:'Studio Provider',models:{},connected:true,logoKind:'anthropic'}],+};+const remoteId = 'remote:["device-studio-mac","account"]';+async function mountRemote(selectedDeviceId:string|null,onSelect=vi.fn(async()=>true)) {+ const onClose=vi.fn();+ await act(async()=>root.render(createElement(UnifiedModelPickerSheet,{+ visible:true,onClose,providers:[{id:'account',name:'Provider',models:{},connected:true}],agentKind:'codex',capabilities:{hasFastMode:true},+ activeModelId:'codex/model',selectedProviderId:'account',selectedEffort:'medium',selectedFastMode:false,+ existingSessionRoute:true,modelMemory:{getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()},+ unified:{scope:'user-device',agents:['codex','claude-code'],loadCapabilities:async()=>({hasFastMode:true}),onSelect,+ remote:{catalogs:[studioCatalog],selectedDeviceId}},+ } as any)));+ return {onSelect,onClose};+}+it('lists another computer\'s providers after the controlled computer\'s own',async()=>{+ await mountRemote(null);+ expect(test.view.groups.map((g:any)=>g.key)).toEqual(['recommended',remoteId]);+ expect(test.view.groups[1].title).toBe('models.unified.remoteProvider');+ const remoteRow = test.view.groups[1].rows[0];+ expect(remoteRow.remoteDevice).toEqual({deviceId:'device-studio-mac',name:'Studio Mac'});+ expect(remoteRow.providerMark).toMatchObject({name:'Studio Provider',logoKind:'anthropic'});+ // 选中态只在 Agent 所在的那份目录里。+ expect(remoteRow.selected).toBe(false);+ expect(test.view.groups[0].rows[0].selected).toBe(true);+ expect(test.view.filters.at(-1)).toMatchObject({+ id:remoteId,+ remote:{deviceId:'device-studio-mac',deviceName:'Studio Mac',providerLabel:'Studio Provider'},+ });+ // 只看被控电脑的某个供应商 / 收藏时,不夹带其他电脑。+ await act(async()=>test.view.onFilter('account'));+ expect(test.view.groups.map((g:any)=>g.key)).toEqual(['account']);+ await act(async()=>test.view.onFilter(remoteId));+ expect(test.view.groups.map((g:any)=>g.key)).toEqual([remoteId]);+});+it('passes the computer of the picked row with the selection',async()=>{+ const {onSelect}=await mountRemote(null);+ await act(async()=>test.view.onSelect(test.view.groups[1].rows[0]));+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({providerId:'account',agent:'codex'}),{deviceId:'device-studio-mac'});+});+it('opens on the Agent\'s computer and marks the current model there',async()=>{+ await mountRemote('device-studio-mac');+ expect(test.view.filter).toBe(remoteId);+ expect(test.view.groups.map((g:any)=>g.key)).toEqual([remoteId]);+ expect(test.view.groups[0].rows[0].selected).toBe(true);+ await act(async()=>test.view.onFilter('all'));+ expect(test.view.groups.find((g:any)=>g.key==='recommended')?.rows.some((row:any)=>row.selected)??false).toBe(false);+});+it('keeps settings of another computer\'s rows out of this phone\'s preferences',async()=>{+ const {onSelect}=await mountRemote(null);+ await act(async()=>test.view.onOptions(test.view.groups[1].rows[0]));+ expect(test.view.options.favoritesDisabled).toBe(true);+ expect(test.view.options.canReset).toBe(false);+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));+ expect(test.save).not.toHaveBeenCalled();+ expect(onSelect).not.toHaveBeenCalled();+ // 调好的档位跟着这一行,选中时一并带上。+ expect(test.view.options.row.config.effort).toBe('high');+ expect(test.view.options.canReset).toBe(true);+ await act(async()=>test.view.onBack());+ await act(async()=>test.view.onSelect(test.view.groups[1].rows[0]));+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({effort:'high'}),{deviceId:'device-studio-mac'});+});diff --git a/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsxindex cd8b310009..387ee94ac0 100644--- a/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx+++ b/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx@@ -69,11 +69,12 @@ vi.mock('@expo/ui/swift-ui/modifiers', () => ({...Object.fromEntries(), shapes:{rectangle:()=>({})}}));vi.mock('@expo/ui', () => ({Host:({children}:any)=>children}));vi.mock('@/session/ComposerSheet', () => import('@/session/ComposerSheet.ios'));-vi.mock('@/session/ComposerNativeSection', () => ({ ComposerNativeSection: ({ children }: any) => children }));+vi.mock('@/session/ComposerNativeSection', () => ({ ComposerNativeSection: ({ children, title }: any) => createElement('div', null, title, children) }));vi.mock('@/session/ComposerNativeRow', () => ({ ComposerNativeRow: ({ leading, title }: any) => createElement('div', null, leading, title) }));vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: ({ children }: any) => children, NativeSwitch: () => null, usesNativePullDownMenu: () => true }));vi.mock('@/components/MobileAgentMark', () => ({ MobileAgentMark: () => null }));vi.mock('@/session/MobileProviderMark', () => ({ MobileModelIconMark: () => null, MobileProviderMark: () => null }));+vi.mock('@/session/RemoteSourceMark', () => ({ RemoteSourceMark: ({ children }: any) => createElement('span', { 'data-remote-mark': '' }, children) }));vi.mock('@/session/SheetModal', () => ({ SheetModal: ({ children }: any) => children }));vi.mock('@/session/SheetSurface', () => ({ SheetSurface: ({ children, pinnedTop, onBack, backAccessibilityLabel, testID, renderScrollContent }: any) => createElement('section', null,onBack ? createElement('button', {onClick:onBack, 'aria-label':backAccessibilityLabel ?? 'shared.back'}, 'Back') : null,@@ -210,6 +211,60 @@ it.each([expect(list.closest('[aria-hidden="true"]')).toBeNull();});+it.each([+ ['Android', UnifiedModelPickerView],+ ['iOS', IosModelPickerView],+] as const)('lists each other computer as its own source block on %s', async (_platform, Component) => {+ const remote = (deviceId: string, deviceName: string, providerLabel: string) => ({+ id: `remote:${deviceId}:${providerLabel}`,+ label: `${providerLabel} · ${deviceName}`,+ providerMark: { name: providerLabel },+ remote: { deviceId, deviceName, providerLabel },+ });+ const filters = [+ { id: 'all', label: 'All' },+ { id: 'account', label: 'Local Provider', providerMark: { name: 'Local Provider' } },+ remote('studio', 'Studio Mac', 'Claude Sub'),+ remote('office', 'Office PC', 'Codex Sub'),+ remote('studio', 'Studio Mac', 'OpenRouter'),+ ];+ const onFilter = vi.fn();+ await act(async () => root.render(createElement(Component, {+ visible: true, testID: 'modelSheet', title: 'Models', query: '', filter: 'all', filters, groups: [], onFilter,+ } as any)));+ const sourceButton = host.querySelector('button[aria-label="models.unified.source"]') as HTMLButtonElement;+ await act(async () => sourceButton.click());+ const text = host.textContent ?? '';+ // 每台电脑一块,块标题是电脑名;块里的行只写供应商名。+ expect(text).toContain('Studio Mac');+ expect(text).toContain('Office PC');+ expect(text.indexOf('Local Provider')).toBeLessThan(text.indexOf('Studio Mac'));+ expect(text.indexOf('Studio Mac')).toBeLessThan(text.indexOf('Claude Sub'));+ expect(text.indexOf('OpenRouter')).toBeLessThan(text.indexOf('Office PC'));+ expect(text).not.toContain('Claude Sub · Studio Mac');+ // 其他电脑的供应商图标带远程标记,本机的不带。+ expect(host.querySelectorAll('[data-remote-mark]')).toHaveLength(3);+});++it.each([+ ['Android', UnifiedModelPickerView],+ ['iOS', IosModelPickerView],+] as const)('marks model rows from another computer on %s', async (_platform, Component) => {+ const row = (key: string, remoteDevice?: { deviceId: string; name: string }) => ({+ key, entry: { displayName: key, capabilities: { codex: { efforts: [] } } },+ config: { agent: 'codex' }, subtitle: '', providerMark: {}, ...(remoteDevice ? { remoteDevice } : {}),+ });+ await act(async () => root.render(createElement(Component, {+ visible: true, testID: 'modelSheet', title: 'Models', query: '', filter: 'all', filters: [],+ groups: [+ { key: 'account', title: 'Local Provider', rows: [row('local')] },+ { key: 'remote', title: 'Claude Sub · Studio Mac', rows: [row('remote', { deviceId: 'studio', name: 'Studio Mac' })] },+ ],+ } as any)));+ expect(host.textContent).toContain('Claude Sub · Studio Mac');+ expect(host.querySelectorAll('[data-remote-mark]')).toHaveLength(1);+});+it('keeps selection errors visible in the retained native root list', async () => {await act(async () => root.render(createElement(IosModelPickerView, {visible:true, testID:'modelSheet', query:'', filters:[], groups:[], error:'Save failed',diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex d3d015ae72..f3b5f6d5a1 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -562,7 +562,11 @@ export interface MobileMakerTransport {providerId?: string,selection?: { effort: string | null; fastMode: boolean },): Promise<{ deferred?: boolean; superseded?: boolean } | undefined>;- /** 登记跨 Agent 切换意图;真正切换在下一条消息发送时由 desktop main 执行。 */+ /**+ * 登记跨 Agent 切换意图;真正切换在下一条消息发送时由 desktop main 执行。+ * 可选 options.agentDeviceId(远程 Agent)同时换 Agent 所在电脑:null = 改回被控电脑本机+ * 运行;只在显式传入时作为第 7 个 wire 参数发送,缺省 = 位置不变(旧被控端忽略多余参数)。+ */switchSessionAgent(sessionId: string,targetAgentKind: MobileAgentKind,@@ -570,6 +574,7 @@ export interface MobileMakerTransport {providerId: string | null,effort?: string,fastMode?: boolean,+ options?: { agentDeviceId?: string | null },): Promise<MobileSessionAgentSwitchResult>;/** 读取 desktop main 的权威 pending intent,用于重连 / 重进页面恢复。 */getSessionAgentSwitchIntent(@@ -1159,15 +1164,22 @@ export function createMobileMakerTransport({providerId,effort,fastMode,+ options,) =>- call("maker:switch-session-agent", [- sessionId,- targetAgentKind,- model,- providerId,- effort,- fastMode,- ]),+ call(+ "maker:switch-session-agent",+ options?.agentDeviceId !== undefined+ ? [+ sessionId,+ targetAgentKind,+ model,+ providerId,+ effort ?? null,+ fastMode ?? null,+ { agentDeviceId: options.agentDeviceId },+ ]+ : [sessionId, targetAgentKind, model, providerId, effort, fastMode],+ ),getSessionAgentSwitchIntent: (sessionId) =>call("maker:get-session-agent-switch-intent", [sessionId]),setEffort: (sessionId, effort) =>diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 0e755f7ea2..860d8f4661 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -265,6 +265,9 @@"sessionLabel": "Session","sessionResumed": "Resumed","agentSwitch": "Switched from {{from}} to {{to}}",+ "agentSwitchLocation": "Agent moved to {{device}}",+ "agentSwitchLocationThisComputer": "Agent moved back to this computer",+ "agentSwitchLocationOtherComputer": "Agent moved to another computer","learnStarted": "Skill learning started","learnStartedBody": "Distillation runs in the background on desktop. When it's done, review the skill draft on desktop.","learnFailed": "Skill learning couldn't start",diff --git a/apps/mobile/src/i18n/locales/en/models.json b/apps/mobile/src/i18n/locales/en/models.jsonindex 6ab8332c01..8bc6bdef58 100644--- a/apps/mobile/src/i18n/locales/en/models.json+++ b/apps/mobile/src/i18n/locales/en/models.json@@ -58,6 +58,14 @@"cancel": "Cancel","confirm": "Continue"},+ "agentRelocation": {+ "titleOther": "Run the Agent on “{{device}}”?",+ "titleHost": "Run the Agent on “{{host}}” again?",+ "titleHostUnnamed": "Run the Agent on the session’s computer again?",+ "message": "The conversation record on the other computer can’t be moved over, so it continues from a handoff summary. Thinking and similar details may not carry over completely. Takes effect when you send the next message.",+ "confirm": "Switch computer",+ "cancel": "Keep as is"+ },"unified": {"favoriteConfiguration": "Favorite This Configuration","savedConfiguration": "Favorited · Tap to Remove",@@ -83,6 +91,7 @@"all": "All models","recommended": "Recommended","source": "Source",+ "remoteProvider": "{{provider}} · {{device}}","harness": "Harness","restoreRecommended": "Restore recommended","saveFailed": "Could not save. Please try again.",diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex f829dff12a..1aa8fa173a 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -556,7 +556,8 @@"REMOTE_AGENT_NOT_FOUND": "This session already ended on the computer running the Agent. Send your message again.","REMOTE_AGENT_BUSY": "Too many sessions are running on the other computer. End some of them and try again.","REMOTE_AGENT_UNSUPPORTED": "This Agent isn't available on the other computer. Install or sign in to it there, or pick another Agent.",- "REMOTE_AGENT_INVALID": "Something went wrong talking to the computer running the Agent. Try again; if it keeps happening, update Cindy on both computers."+ "REMOTE_AGENT_INVALID": "Something went wrong talking to the computer running the Agent. Try again; if it keeps happening, update Cindy on both computers.",+ "REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "That computer hasn’t allowed remote use of this provider. On that computer, turn on “Allow remote use” in Settings → Providers, or pick another model."},"collab": {"modeLabel": "Collaboration mode",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex 6d774255b7..9039728b39 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -265,6 +265,9 @@"sessionLabel": "セッション","sessionResumed": "再開済み","agentSwitch": "{{from}} から {{to}} に切り替えました",+ "agentSwitchLocation": "Agent の実行先を {{device}} に変更しました",+ "agentSwitchLocationThisComputer": "Agent の実行先をこのパソコンに戻しました",+ "agentSwitchLocationOtherComputer": "Agent の実行先を別のパソコンに変更しました","learnStarted": "スキル学習を開始しました","learnStartedBody": "蒸留はデスクトップのバックグラウンドで進行します。完了後、デスクトップでスキルの草案を確認・レビューしてください。","learnFailed": "スキル学習を開始できませんでした",diff --git a/apps/mobile/src/i18n/locales/ja/models.json b/apps/mobile/src/i18n/locales/ja/models.jsonindex d4baa1e8a8..8a90953a49 100644--- a/apps/mobile/src/i18n/locales/ja/models.json+++ b/apps/mobile/src/i18n/locales/ja/models.json@@ -58,6 +58,14 @@"cancel": "キャンセル","confirm": "続けて選択"},+ "agentRelocation": {+ "titleOther": "Agent を「{{device}}」で実行しますか?",+ "titleHost": "Agent を「{{host}}」で実行し直しますか?",+ "titleHostUnnamed": "Agent をセッションのあるパソコンで実行し直しますか?",+ "message": "元のパソコンにある会話の記録は移せないため、引き継ぎの要約から続けます。思考内容などは完全には引き継がれない場合があります。次のメッセージを送信したときに反映されます。",+ "confirm": "パソコンを切り替える",+ "cancel": "このままにする"+ },"unified": {"favoriteConfiguration": "この設定をお気に入りに追加","savedConfiguration": "登録済み · タップして解除",@@ -83,6 +91,7 @@"all": "すべてのモデル","recommended": "おすすめ","source": "接続元",+ "remoteProvider": "{{provider}} · {{device}}","harness": "Harness","restoreRecommended": "推奨設定に戻す","saveFailed": "保存できませんでした。再試行してください。",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 9c986a099d..f0f128217b 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -556,7 +556,8 @@"REMOTE_AGENT_NOT_FOUND": "このセッションは Agent を実行しているパソコンですでに終了しています。もう一度送信してください。","REMOTE_AGENT_BUSY": "相手のパソコンで実行中のセッションが多すぎます。いくつか終了してからもう一度お試しください。","REMOTE_AGENT_UNSUPPORTED": "相手のパソコンではこの Agent を使えません。そのパソコンでインストールまたはサインインするか、別の Agent を選んでください。",- "REMOTE_AGENT_INVALID": "Agent を実行しているパソコンとの通信でエラーが発生しました。もう一度お試しください。続く場合は両方のパソコンの Cindy を最新版に更新してください。"+ "REMOTE_AGENT_INVALID": "Agent を実行しているパソコンとの通信でエラーが発生しました。もう一度お試しください。続く場合は両方のパソコンの Cindy を最新版に更新してください。",+ "REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "そのパソコンでは、このプロバイダーのリモート利用が許可されていません。そのパソコンの「設定 → モデルプロバイダー」で「リモート利用を許可」をオンにするか、別のモデルを選んでください。"},"collab": {"modeLabel": "コラボレーションモード",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex 1b0ed8334d..95ba7661fe 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -265,6 +265,9 @@"sessionLabel": "세션","sessionResumed": "재개됨","agentSwitch": "{{from}}에서 {{to}}(으)로 전환됨",+ "agentSwitchLocation": "Agent 실행 위치가 {{device}}(으)로 변경됨",+ "agentSwitchLocationThisComputer": "Agent 실행 위치가 이 컴퓨터로 돌아옴",+ "agentSwitchLocationOtherComputer": "Agent 실행 위치가 다른 컴퓨터로 변경됨","learnStarted": "스킬 학습을 시작했습니다","learnStartedBody": "증류는 데스크톱 백그라운드에서 진행됩니다. 완료되면 데스크톱에서 스킬 초안을 확인하고 검토하세요.","learnFailed": "스킬 학습을 시작하지 못했습니다",diff --git a/apps/mobile/src/i18n/locales/ko/models.json b/apps/mobile/src/i18n/locales/ko/models.jsonindex c0882e5914..765fb15390 100644--- a/apps/mobile/src/i18n/locales/ko/models.json+++ b/apps/mobile/src/i18n/locales/ko/models.json@@ -58,6 +58,14 @@"cancel": "취소","confirm": "계속 선택"},+ "agentRelocation": {+ "titleOther": "Agent를 “{{device}}”에서 실행할까요?",+ "titleHost": "Agent를 다시 “{{host}}”에서 실행할까요?",+ "titleHostUnnamed": "Agent를 다시 세션이 있는 컴퓨터에서 실행할까요?",+ "message": "원래 컴퓨터에 있는 대화 기록은 옮길 수 없어 인수인계 요약으로 이어집니다. 사고 내용 등은 완전히 이어지지 않을 수 있습니다. 다음 메시지를 보낼 때 적용됩니다.",+ "confirm": "컴퓨터 전환",+ "cancel": "그대로 두기"+ },"unified": {"favoriteConfiguration": "이 설정을 즐겨찾기에 추가","savedConfiguration": "즐겨찾기에 추가됨 · 눌러서 해제",@@ -83,6 +91,7 @@"all": "모든 모델","recommended": "추천","source": "공급원",+ "remoteProvider": "{{provider}} · {{device}}","harness": "Harness","restoreRecommended": "권장 설정 복원","saveFailed": "저장하지 못했습니다. 다시 시도하세요.",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 3f8dec5586..b64d3bbad6 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -552,7 +552,8 @@"REMOTE_AGENT_NOT_FOUND": "이 세션은 Agent를 실행하는 컴퓨터에서 이미 종료되었습니다. 다시 보내 주세요.","REMOTE_AGENT_BUSY": "상대 컴퓨터에서 실행 중인 세션이 너무 많습니다. 일부를 종료한 뒤 다시 시도하세요.","REMOTE_AGENT_UNSUPPORTED": "상대 컴퓨터에서는 이 Agent를 사용할 수 없습니다. 그 컴퓨터에서 설치하거나 로그인한 뒤 다시 시도하거나, 다른 Agent를 선택하세요.",- "REMOTE_AGENT_INVALID": "Agent를 실행하는 컴퓨터와 통신하는 중 오류가 발생했습니다. 다시 시도하고, 계속되면 두 컴퓨터의 Cindy를 모두 최신 버전으로 업데이트하세요."+ "REMOTE_AGENT_INVALID": "Agent를 실행하는 컴퓨터와 통신하는 중 오류가 발생했습니다. 다시 시도하고, 계속되면 두 컴퓨터의 Cindy를 모두 최신 버전으로 업데이트하세요.",+ "REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "그 컴퓨터에서 이 제공자의 원격 사용을 허용하지 않았습니다. 그 컴퓨터의 설정 → 모델 제공자에서 원격 사용 허용을 켜거나 다른 모델을 선택하세요."},"collab": {"modeLabel": "협업 모드",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 93c03cfb4c..0ccb440cd9 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -265,6 +265,9 @@"sessionLabel": "任务","sessionResumed": "已续接","agentSwitch": "已从 {{from}} 切换到 {{to}}",+ "agentSwitchLocation": "Agent 改到 {{device}} 运行",+ "agentSwitchLocationThisComputer": "Agent 改回这台电脑运行",+ "agentSwitchLocationOtherComputer": "Agent 改到另一台电脑运行","learnStarted": "技能学习已启动","learnStartedBody": "蒸馏在电脑端后台进行,完成后请到电脑端查看并评审技能草案。","learnFailed": "技能学习未能启动",diff --git a/apps/mobile/src/i18n/locales/zh-CN/models.json b/apps/mobile/src/i18n/locales/zh-CN/models.jsonindex b9b4bbcce9..cf46b4996b 100644--- a/apps/mobile/src/i18n/locales/zh-CN/models.json+++ b/apps/mobile/src/i18n/locales/zh-CN/models.json@@ -58,6 +58,14 @@"cancel": "取消","confirm": "继续选择"},+ "agentRelocation": {+ "titleOther": "改到「{{device}}」上运行 Agent?",+ "titleHost": "改回「{{host}}」上运行 Agent?",+ "titleHostUnnamed": "改回任务所在的电脑运行 Agent?",+ "message": "原来那台电脑上的对话记录带不过来,会整理成交接摘要接上,思考内容等不能保证完美继承。下一条消息发出时生效。",+ "confirm": "换电脑运行",+ "cancel": "保持不变"+ },"unified": {"favoriteConfiguration": "收藏此配置","savedConfiguration": "已收藏 · 点击取消",@@ -83,6 +91,7 @@"all": "全部模型","recommended": "推荐","source": "来源",+ "remoteProvider": "{{provider}} · {{device}}","harness": "Harness","restoreRecommended": "恢复推荐","saveFailed": "未能保存,请重试。",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 95e85ca94f..46b7735663 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -552,7 +552,8 @@"REMOTE_AGENT_NOT_FOUND": "这个任务在运行 Agent 的电脑上已经结束。请重新发送。","REMOTE_AGENT_BUSY": "那台电脑上同时运行的任务太多。先结束一些任务后再试。","REMOTE_AGENT_UNSUPPORTED": "那台电脑上这个 Agent 不可用。在那台电脑上安装或登录后再试,或换一个 Agent。",- "REMOTE_AGENT_INVALID": "和运行 Agent 的电脑通信出错。请重试;如果一直出现,请把两台电脑上的 Cindy 都更新到最新版。"+ "REMOTE_AGENT_INVALID": "和运行 Agent 的电脑通信出错。请重试;如果一直出现,请把两台电脑上的 Cindy 都更新到最新版。",+ "REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "那台电脑没有允许远程调用这个供应商。请在那台电脑的「设置 → 模型供应商」里打开「允许被远程调用」,或换一个模型。"},"collab": {"modeLabel": "协同模式",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex 44d84b2dbd..76e3bdaf3b 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -265,6 +265,9 @@"sessionLabel": "任務","sessionResumed": "已續接","agentSwitch": "已從 {{from}} 切換到 {{to}}",+ "agentSwitchLocation": "Agent 改到 {{device}} 執行",+ "agentSwitchLocationThisComputer": "Agent 改回這台電腦執行",+ "agentSwitchLocationOtherComputer": "Agent 改到另一台電腦執行","learnStarted": "技能學習已啟動","learnStartedBody": "蒸餾在電腦端後臺進行,完成後請到電腦端檢視並評審技能草案。","learnFailed": "技能學習未能啟動",diff --git a/apps/mobile/src/i18n/locales/zh-TW/models.json b/apps/mobile/src/i18n/locales/zh-TW/models.jsonindex 3a39de6556..532a9c0430 100644--- a/apps/mobile/src/i18n/locales/zh-TW/models.json+++ b/apps/mobile/src/i18n/locales/zh-TW/models.json@@ -58,6 +58,14 @@"cancel": "取消","confirm": "繼續選擇"},+ "agentRelocation": {+ "titleOther": "改到「{{device}}」上執行 Agent?",+ "titleHost": "改回「{{host}}」上執行 Agent?",+ "titleHostUnnamed": "改回任務所在的電腦執行 Agent?",+ "message": "原來那台電腦上的對話記錄帶不過來,會整理成交接摘要接上,思考內容等不能保證完美繼承。下一則訊息送出時生效。",+ "confirm": "換電腦執行",+ "cancel": "保持不變"+ },"unified": {"favoriteConfiguration": "收藏此設定","savedConfiguration": "已收藏 · 點擊取消",@@ -83,6 +91,7 @@"all": "全部模型","recommended": "推薦","source": "來源",+ "remoteProvider": "{{provider}} · {{device}}","harness": "Harness","restoreRecommended": "恢復推薦","saveFailed": "無法儲存,請重試。",diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.jsonindex 383ffe4d77..2fa10f856f 100644--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@ -556,7 +556,8 @@"REMOTE_AGENT_NOT_FOUND": "這個任務在執行 Agent 的電腦上已經結束。請重新傳送。","REMOTE_AGENT_BUSY": "那臺電腦上同時執行的任務太多。先結束一些任務後再試。","REMOTE_AGENT_UNSUPPORTED": "那臺電腦上這個 Agent 無法使用。在那臺電腦上安裝或登入後再試,或換一個 Agent。",- "REMOTE_AGENT_INVALID": "與執行 Agent 的電腦通訊時出錯。請重試;如果持續出現,請把兩臺電腦上的 Cindy 都更新到最新版。"+ "REMOTE_AGENT_INVALID": "與執行 Agent 的電腦通訊時出錯。請重試;如果持續出現,請把兩臺電腦上的 Cindy 都更新到最新版。",+ "REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "那臺電腦沒有允許遠端呼叫這個供應商。請在那臺電腦的「設定 → 模型供應商」裡開啟「允許遠端呼叫」,或換一個模型。"},"collab": {"modeLabel": "協同模式",diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 4314ce0267..d8a4d8ca0b 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -347,7 +347,7 @@ import type {MobileMediaPlayerKind,MobileMediaPlayerStatus,} from '@/session/mediaPlayerWebViewHtml';-import { formatMobileSystemCard } from '@/session/systemCard';+import { formatAgentSwitchLocationLabel, formatMobileSystemCard } from '@/session/systemCard';import { MobileBoundaryNotice } from '@/session/MobileBoundaryNotice';import {getMobileAutoResumePresentation,@@ -5201,7 +5201,9 @@ function MobileAgentSwitchCard({ data }: { data?: Record<string, unknown> }) {const toModel = typeof data?.toModel === 'string' ? data.toModel : '';const handoff = typeof data?.handoff === 'string' ? data.handoff : '';const resumed = data?.resumed === true;- const label = t('message.renderer.agentSwitchLabel', { from, to });+ // 远程 Agent 换了电脑:药丸说位置(「Agent 改到 X 运行」),否则仍是「已从 X 切换到 Y」。+ const label = formatAgentSwitchLocationLabel(data, (key, options) => t(key, options))+ ?? t('message.renderer.agentSwitchLabel', { from, to });return (<View style={styles.agentSwitchWrap} testID="message.systemCard.agent-switch">diff --git a/apps/mobile/src/session/RemoteSourceMark.tsx b/apps/mobile/src/session/RemoteSourceMark.tsxnew file mode 100644index 0000000000..aa86f99e9c--- /dev/null+++ b/apps/mobile/src/session/RemoteSourceMark.tsx@@ -0,0 +1,84 @@+/**+ * RemoteSourceMark —— 「另一台电脑上的供应商」图标(移植自桌面+ * apps/desktop/src/renderer/components/icons/RemoteSourceMark.tsx)。+ *+ * 品牌图形缩到左下 12.5 / 16,右上角用一道波纹加一个点标出远端:仍是**一个**图标位,+ * 一眼读出「这个供应商,在远处」。不在 Logo 旁另放电脑图标(2026-10-06 用户裁决)。+ * 波纹与点跟随 color(缺省 textSecondary,与供应商 mark 同色),Light / Dark 走主题 token。+ */+import type { ReactNode } from 'react';+import { StyleSheet, View } from 'react-native';+import Svg, { Circle, Path } from 'react-native-svg';++import { useTheme } from '@/theme';++/** 品牌图形在 16 单位画布里所占边长(左下对齐)。 */+const BRAND_UNITS = 12.5;+/** MobileProviderMark / MobileModelIconMark 的原生盒边长。 */+const DEFAULT_MARK_SIZE = 18;++export function RemoteSourceMark({+ size,+ markSize = DEFAULT_MARK_SIZE,+ color,+ children,+ testID,+}: {+ /** 整个图标(品牌 + 波纹)的边长。 */+ size: number;+ /** children 的原生边长;按比例缩进品牌区。 */+ markSize?: number;+ color?: string;+ /** 品牌图形(MobileProviderMark 等)。 */+ children: ReactNode;+ testID?: string;+}) {+ const { colors } = useTheme();+ const stroke = color ?? colors.textSecondary;+ const scale = (size * BRAND_UNITS) / 16 / markSize;+ // RN 的 scale 以盒中心为原点:缩放后再平移,让品牌贴住左下角。+ const offset = (markSize * (1 - scale)) / 2;+ return (+ <View+ accessibilityElementsHidden+ importantForAccessibility="no-hide-descendants"+ pointerEvents="none"+ style={{ height: size, width: size }}+ testID={testID}+ >+ <View+ style={[+ styles.brand,+ {+ height: markSize,+ width: markSize,+ transform: [{ translateX: -offset }, { translateY: offset }, { scale }],+ },+ ]}+ >+ {children}+ </View>+ <Svg height={size} style={StyleSheet.absoluteFill} viewBox="0 0 16 16" width={size}>+ {/* 波纹描边是 16 单位画布里的图形几何(与桌面同值、随 size 缩放),不是阶梯图标描边。 */}+ <Path+ d="M12 1.4A2.6 2.6 0 0 1 14.6 4"+ fill="none"+ stroke={stroke}+ strokeLinecap="round"+ strokeWidth={1.4}+ />+ <Circle cx={12.6} cy={3.4} fill={stroke} r={0.95} />+ </Svg>+ </View>+ );+}++const styles = StyleSheet.create({+ brand: {+ alignItems: 'flex-start',+ bottom: 0,+ justifyContent: 'flex-end',+ left: 0,+ position: 'absolute',+ },+});diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsxindex 870090981a..435643c90a 100644--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx@@ -29,6 +29,10 @@ import { UnifiedModelPickerView } from "./UnifiedModelPickerView";import { budgetRowDisabled, presentPickerPrice } from "./modelPickerRows";import { mobileWeeklyQuota } from "./mobileModelRowPresentation";import { mobileAgentLabel } from "./sessionAgentSwitch";+import type { RemoteAgentCatalog } from "./remoteAgentCatalogs";+import { remoteFilterId } from "./remoteSourceFilters";++const NO_REMOTE_CATALOGS: readonly RemoteAgentCatalog[] = [];function createFavoriteUid(): string {const cryptoWithUuid = globalThis.crypto as Crypto | undefined;@@ -60,7 +64,20 @@ export interface UnifiedMobilePickerOptions {scope: string;agents: readonly AgentKind[];loadCapabilities(agent: AgentKind): Promise<MobileAgentCapabilities>;- onSelect(configuration: MobileModelConfiguration): Promise<boolean>;+ /**+ * 远程 Agent(已建任务):同账号其他电脑上开放了远程调用的供应商,接在被控电脑自己的供应商+ * 之后,每个供应商一段、标题带电脑名(与桌面模型面板同口径)。缺省 = 只列被控电脑的目录。+ */+ remote?: {+ catalogs: readonly RemoteAgentCatalog[];+ /** 当前选中态(下一条消息时 Agent 所在电脑)属于哪份目录;null = 被控电脑。 */+ selectedDeviceId: string | null;+ };+ /** source.deviceId = 这一行来自哪台电脑的目录(null / 缺省 = 被控电脑)。 */+ onSelect(+ configuration: MobileModelConfiguration,+ source?: { deviceId: string | null },+ ): Promise<boolean>;}export interface UnifiedMobileRow {key: string;@@ -74,6 +91,8 @@ export interface UnifiedMobileRow {effortLabel: string;quotaLabel: string | null;providerMark: MobileProviderMarkProps;+ /** 这一行来自哪台其他电脑的目录(图标带远程标记);缺省 = 被控电脑自己的。 */+ remoteDevice?: { deviceId: string; name: string };}export interface UnifiedMobileGroup {key: string;@@ -96,6 +115,11 @@ export interface UnifiedMobilePickerViewProps {label: string;providerMark?: MobileProviderMarkProps;quota?: { remaining: number; label: string };+ /**+ * 另一台电脑上的供应商:来源页里每台电脑单独一块(块标题 = 电脑名,行标题 = providerLabel),+ * 图标带远程标记;label 是带电脑名的完整说法,用在搜索栏旁的来源按钮上。+ */+ remote?: { deviceId: string; deviceName: string; providerLabel: string };}[];groups: UnifiedMobileGroup[];busy: boolean;@@ -144,7 +168,16 @@ export function UnifiedModelPickerSheet(modelId: string;uid?: string;config?: MobileModelConfiguration;+ /** 另一台电脑目录里的行;缺省 = 被控电脑的。 */+ deviceId?: string;} | null>(null);+ // 另一台电脑目录里的行:手机这边的偏好与档位记忆都按被控电脑的供应商记,不写给它们;+ // 详情页里调的档位 / 引擎只在这次打开期间跟着那一行。+ const [remoteConfigs, setRemoteConfigs] = useState<+ ReadonlyMap<string, MobileModelConfiguration>+ >(new Map());+ // 打开时 Agent 在另一台电脑:目录读到后停在那台电脑的当前供应商上(用户先手动换过就不再跳)。+ const initialRemoteFilter = useRef(false);const [favoriteEdit, setFavoriteEdit] = useState<{original: MobileModelFavorite;config: MobileModelConfiguration;@@ -162,7 +195,9 @@ export function UnifiedModelPickerSheet(opening.current += 1;setQuery("");setFilter("all");+ initialRemoteFilter.current = true;setTarget(null);+ setRemoteConfigs(new Map());setFavoriteEdit(null);setNotice(null);setError(null);@@ -183,6 +218,17 @@ export function UnifiedModelPickerSheet(opening.current += 1;};}, [p.visible, p.unified.scope]);+ const remoteCatalogs = p.unified.remote?.catalogs ?? NO_REMOTE_CATALOGS;+ /** 选中态属于哪台其他电脑的目录;null = 被控电脑自己的(含没有远程 Agent 的情况)。 */+ const selectedDeviceId = p.unified.remote?.selectedDeviceId ?? null;+ const keepModel = useMemo(+ () => ({+ providerId: p.selectedProviderId,+ modelId: p.activeModelId,+ agent: p.agentKind,+ }),+ [p.selectedProviderId, p.activeModelId, p.agentKind],+ );const entries = useMemo(() =>mobileUnifiedEntries(@@ -190,30 +236,68 @@ export function UnifiedModelPickerSheet(p.unified.agents,p.modelVisibilityOverrides,!!p.existingSessionRoute,- {- providerId: p.selectedProviderId,- modelId: p.activeModelId,- agent: p.agentKind,- },+ selectedDeviceId === null ? keepModel : undefined,),[p.providers,p.unified.agents,p.modelVisibilityOverrides,p.existingSessionRoute,+ keepModel,+ selectedDeviceId,+ ],+ );+ // 另一台电脑的目录:每台按自己的供应商与可见性派生,选中态只落在 Agent 所在那台。+ const remoteDirectories = useMemo(+ () =>+ remoteCatalogs.flatMap((catalog) => {+ if (catalog.providers.length === 0) return [];+ const selectedHere = catalog.deviceId === selectedDeviceId;+ return [+ {+ catalog,+ entries: mobileUnifiedEntries(+ catalog.providers,+ p.unified.agents,+ catalog.modelVisibilityOverrides,+ !!p.existingSessionRoute,+ selectedHere ? keepModel : undefined,+ ),+ sourceId: selectedHere+ ? buildMobileModelSections({+ providers: catalog.providers,+ agentKind: p.agentKind,+ selectedModelId: p.activeModelId,+ selectedProviderId: p.selectedProviderId,+ existingSessionRoute: p.existingSessionRoute,+ visibilityOverrides: catalog.modelVisibilityOverrides,+ }).activeSourceId+ : null,+ },+ ];+ }),+ [+ remoteCatalogs,+ selectedDeviceId,+ keepModel,+ p.unified.agents,+ p.existingSessionRoute,p.selectedProviderId,p.activeModelId,p.agentKind,],);- const sourceId = buildMobileModelSections({- providers: p.providers,- agentKind: p.agentKind,- selectedModelId: p.activeModelId,- selectedProviderId: p.selectedProviderId,- existingSessionRoute: p.existingSessionRoute,- visibilityOverrides: p.modelVisibilityOverrides,- }).activeSourceId;+ const sourceId =+ selectedDeviceId === null+ ? buildMobileModelSections({+ providers: p.providers,+ agentKind: p.agentKind,+ selectedModelId: p.activeModelId,+ selectedProviderId: p.selectedProviderId,+ existingSessionRoute: p.existingSessionRoute,+ visibilityOverrides: p.modelVisibilityOverrides,+ }).activeSourceId+ : null;const selection: MobileModelConfiguration = {providerId: sourceId ?? "",modelId: p.activeModelId,@@ -242,24 +326,22 @@ export function UnifiedModelPickerSheet(}: selection;const fastCapable = (agent: AgentKind) => caps[agent]?.hasFastMode === true;+ const effortText = (config: MobileModelConfiguration) =>+ config.effort+ ? t(`models.options.effortLevels.${config.effort}`, {+ defaultValue: config.effort,+ })+ : "";const describe = (entry: UnifiedModelEntry,config: MobileModelConfiguration,+ providers: readonly (typeof p.providers)[number][] = p.providers,) => {- const provider = p.providers.find((item) => item.id === entry.providerId);+ const provider = providers.find((item) => item.id === entry.providerId);const identity =provider?.openAiAccount?.identity?.trim() ||provider?.subscriptionAccount?.identity?.trim();- return [- identity,- config.effort- ? t(`models.options.effortLevels.${config.effort}`, {- defaultValue: config.effort,- })- : null,- ]- .filter(Boolean)- .join(" · ");+ return [identity, effortText(config)].filter(Boolean).join(" · ");};const makeRow = (entry: UnifiedModelEntry,@@ -296,11 +378,7 @@ export function UnifiedModelPickerSheet(!caps[config.agent] ||budgetRowDisabled(config.modelId, p.apiKeyStatus ?? "unknown"),subtitle: describe(entry, config),- effortLabel: config.effort- ? t(`models.options.effortLevels.${config.effort}`, {- defaultValue: config.effort,- })- : "",+ effortLabel: effortText(config),costMarks: mobileCostMarks(p.providers.find((item) => item.id === entry.providerId),config.modelId,@@ -344,9 +422,80 @@ export function UnifiedModelPickerSheet(if (!provider) return id;return mobileProviderAccountTitle(provider);};+ // 另一台电脑目录里的供应商,说法带电脑名(「Claude 订阅 · 工作室 Mac」)。+ const remoteProviderName = (catalog: RemoteAgentCatalog, id: string) => {+ const provider = catalog.providers.find((item) => item.id === id);+ return provider ? mobileProviderAccountTitle(provider) : id;+ };+ const remoteProviderLabel = (catalog: RemoteAgentCatalog, id: string) =>+ t("models.unified.remoteProvider", {+ provider: remoteProviderName(catalog, id),+ device: catalog.name,+ });+ const makeRemoteRow = (+ directory: (typeof remoteDirectories)[number],+ entry: UnifiedModelEntry,+ ): UnifiedMobileRow => {+ const { catalog } = directory;+ const selected =+ directory.sourceId !== null &&+ entry.providerId === directory.sourceId &&+ matchesEntry(entry, p.activeModelId);+ const key = `remote:${catalog.deviceId}:${modelKey(entry.providerId, entry.modelId)}`;+ const provider = catalog.providers.find(+ (item) => item.id === entry.providerId,+ );+ // 不用手机这边按被控电脑供应商记的引擎偏好与档位记忆:同 id 的供应商在两台电脑上不是同一个。+ const config =+ (!selected ? remoteConfigs.get(key) : undefined) ??+ resolveMobileModelConfig(entry, {+ live: selected+ ? { ...selection, providerId: directory.sourceId ?? "" }+ : undefined,+ pinned: p.existingSessionRoute ? p.agentKind : undefined,+ fastCapable,+ });+ return {+ key,+ entry,+ config,+ providerMark: {+ providerId: entry.providerId,+ name: provider?.name ?? entry.providerId,+ routing: provider?.routing,+ logoKind: provider?.logoKind,+ },+ remoteDevice: { deviceId: catalog.deviceId, name: catalog.name },+ selected,+ disabled: !caps[config.agent],+ subtitle: describe(entry, config, catalog.providers),+ effortLabel: effortText(config),+ costMarks: mobileCostMarks(+ provider,+ config.modelId,+ config.agent,+ p.pricing,+ ),+ // 用量镜像按被控电脑的供应商取,另一台电脑的不在这里显示。+ quotaLabel: null,+ };+ };+ const remoteRows = remoteDirectories.map((directory) => ({+ catalog: directory.catalog,+ rows: directory.entries.map((entry) => makeRemoteRow(directory, entry)),+ }));+ const rowProviderName = (row: UnifiedMobileRow) => {+ const device = row.remoteDevice;+ const catalog = device+ ? remoteCatalogs.find((item) => item.deviceId === device.deviceId)+ : undefined;+ return catalog+ ? remoteProviderLabel(catalog, row.entry.providerId)+ : providerName(row.entry.providerId);+ };const matches = (row: UnifiedMobileRow) =>!query.trim() ||- `${row.entry.displayName} ${row.entry.modelId} ${row.entry.description ?? ""} ${providerName(row.entry.providerId)}`+ `${row.entry.displayName} ${row.entry.modelId} ${row.entry.description ?? ""} ${rowProviderName(row)}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase());const all = query.trim() || filter === "all";@@ -386,13 +535,37 @@ export function UnifiedModelPickerSheet(rows: group,});}+ // 其他电脑的供应商接在后面:每个供应商一段,标题带电脑名;「收藏」与本机供应商视图里不出现。+ for (const { catalog, rows: deviceRows } of remoteRows)+ for (const provider of catalog.providers) {+ const id = remoteFilterId(catalog.deviceId, provider.id);+ if (!all && filter !== id) continue;+ const group = deviceRows.filter(+ (row) => row.entry.providerId === provider.id && matches(row),+ );+ if (group.length)+ groups.push({+ key: id,+ title: remoteProviderLabel(catalog, provider.id),+ rows: group,+ });+ }const sourceRow = target- ? rows.find(+ ? (target.deviceId+ ? remoteRows.find((item) => item.catalog.deviceId === target.deviceId)+ ?.rows+ : rows+ )?.find((row) =>row.entry.providerId === target.providerId &&row.entry.modelId === target.modelId,): undefined;+ const sourceRemoteCatalog = sourceRow?.remoteDevice+ ? remoteCatalogs.find(+ (item) => item.deviceId === sourceRow.remoteDevice!.deviceId,+ )+ : undefined;const originFavorite = target?.uid? prefs.value.favorites.find((item) => item.uid === target.uid): undefined;@@ -406,8 +579,10 @@ export function UnifiedModelPickerSheet(};// A source model can have several saved configurations. Match the complete// configuration without applying capability fallbacks to the saved values.+ // 收藏按被控电脑的供应商记;另一台电脑目录里的行不参与(同 id 供应商不是同一个)。const matchingFavorite =row &&+ !row.remoteDevice &&prefs.value.favorites.find((item) =>matchesEntry(row.entry, item.modelId) &&@@ -422,7 +597,7 @@ export function UnifiedModelPickerSheet(const resetAgents = row? [...new Set([row.config.agent, recommendedConfig!.agent])]: [];- const canReset =+ const localCanReset =!!row &&(!sameConfiguration(row.config, recommendedConfig!) ||prefs.value.engines[modelKey(row.entry.providerId, row.entry.modelId)] !==@@ -450,6 +625,10 @@ export function UnifiedModelPickerSheet((fast !== undefined && (!!p.modelMemory?.clearFast || fast)));}));+ // 另一台电脑目录里的行:只有这次打开期间调过档位 / 引擎才能恢复推荐。+ const canReset = row?.remoteDevice+ ? !row.selected && remoteConfigs.has(row.key)+ : localCanReset;useEffect(() => {if (target && !row) {setTarget(null);@@ -480,7 +659,9 @@ export function UnifiedModelPickerSheet(const select = (row: UnifiedMobileRow) => {if (row.disabled) return;void transact(async (isCurrent) => {- if ((await p.unified.onSelect(row.config)) && isCurrent()) p.onClose();+ const source = { deviceId: row.remoteDevice?.deviceId ?? null };+ if ((await p.unified.onSelect(row.config, source)) && isCurrent())+ p.onClose();});};const change = (config: MobileModelConfiguration, reset = false) => {@@ -490,6 +671,27 @@ export function UnifiedModelPickerSheet(setFavoriteEdit({ ...favoriteEdit, config });return;}+ const remoteDevice = row.remoteDevice;+ if (remoteDevice) {+ // 另一台电脑目录里的行:正在用的那行直接生效;其余只在这次打开期间跟着该行,+ // 不写手机的引擎偏好与档位记忆(那些按被控电脑的供应商记)。+ const key = row.key;+ void transact(async (isCurrent) => {+ if (+ row.selected &&+ !(await p.unified.onSelect(config, { deviceId: remoteDevice.deviceId }))+ )+ return;+ if (!isCurrent() || row.selected) return;+ setRemoteConfigs((current) => {+ const next = new Map(current);+ if (reset) next.delete(key);+ else next.set(key, config);+ return next;+ });+ });+ return;+ }void transact(async (isCurrent) => {const previousConfig =row.favorite && sameConfiguration(row.config, live)@@ -565,7 +767,10 @@ export function UnifiedModelPickerSheet(};const cap = row?.entry.capabilities[row.config.agent];const provider =- row && p.providers.find((item) => item.id === row.entry.providerId);+ row &&+ (sourceRemoteCatalog?.providers ?? p.providers).find(+ (item) => item.id === row.entry.providerId,+ );const price = row? presentPickerPrice({pricing: p.pricing ?? null,@@ -574,6 +779,48 @@ export function UnifiedModelPickerSheet(agentKind: row.config.agent,}): null;+ // 来源页:其他电脑的供应商按电脑分块(一个都没开放的电脑没有行,整块不出现)。+ const remoteFilters = remoteDirectories.flatMap(({ catalog, entries }) =>+ catalog.providers+ .filter((provider) => entries.some((e) => e.providerId === provider.id))+ .map((provider) => ({+ id: remoteFilterId(catalog.deviceId, provider.id),+ label: remoteProviderLabel(catalog, provider.id),+ providerMark: {+ providerId: provider.id,+ name: provider.name,+ routing: provider.routing,+ logoKind: provider.logoKind,+ },+ remote: {+ deviceId: catalog.deviceId,+ deviceName: catalog.name,+ providerLabel: remoteProviderName(catalog, provider.id),+ },+ })),+ );+ const selectedDirectory = remoteDirectories.find(+ (directory) => directory.catalog.deviceId === selectedDeviceId,+ );+ const selectedCatalogStatus = remoteCatalogs.find(+ (catalog) => catalog.deviceId === selectedDeviceId,+ )?.status;+ const selectedRemoteFilter =+ selectedDeviceId && selectedDirectory?.sourceId+ ? remoteFilterId(selectedDeviceId, selectedDirectory.sourceId)+ : null;+ useEffect(() => {+ if (!p.visible || !initialRemoteFilter.current) return;+ if (selectedDeviceId === null) {+ initialRemoteFilter.current = false;+ return;+ }+ // 那台电脑的目录还没读到:等一等再定;读不到就留在「全部模型」。+ if (selectedCatalogStatus === undefined || selectedCatalogStatus === "loading")+ return;+ initialRemoteFilter.current = false;+ if (selectedRemoteFilter) setFilter(selectedRemoteFilter);+ }, [p.visible, selectedDeviceId, selectedCatalogStatus, selectedRemoteFilter]);return (<UnifiedModelPickerViewvisible={p.visible}@@ -599,7 +846,10 @@ export function UnifiedModelPickerSheet(query={query}onQuery={setQuery}filter={filter}- onFilter={setFilter}+ onFilter={(value) => {+ initialRemoteFilter.current = false;+ setFilter(value);+ }}filters={[{ id: "all", label: t("models.unified.all") },...(prefs.favoritesReady@@ -638,10 +888,11 @@ export function UnifiedModelPickerSheet(logoKind: provider.logoKind,},})),+ ...remoteFilters,]}groups={groups}busy={busy || !!p.disabled || !prefs.ready}- error={error ?? (p.providersReady && modelNeedsReselection(p.modelVisibilityOverrides, p.agentKind, p.activeModelId, p.selectedProviderId)+ error={error ?? (selectedDeviceId === null && p.providersReady && modelNeedsReselection(p.modelVisibilityOverrides, p.agentKind, p.activeModelId, p.selectedProviderId)? t('session.common.modelHiddenReselect', { model: p.activeModelId }) : null)}loading={!!p.loading}emptyHint={p.emptyHint ?? t("models.picker.noResults")}@@ -656,6 +907,7 @@ export function UnifiedModelPickerSheet(modelId: row.entry.modelId,uid: row.favorite?.uid,config: row.favorite ? { ...row.config } : undefined,+ ...(row.remoteDevice ? { deviceId: row.remoteDevice.deviceId } : {}),});}}options={@@ -669,7 +921,7 @@ export function UnifiedModelPickerSheet(!!cap?.supportsFastMode && fastCapable(row.config.agent),onChange: change,context: [- providerName(row.entry.providerId),+ rowProviderName(row),cap?.contextWindow? t("models.picker.contextSuffix", {size: `${Math.round(cap.contextWindow / 1000)}K`,@@ -679,7 +931,7 @@ export function UnifiedModelPickerSheet(.filter(Boolean).join(" · "),price: price ? `${price.title}\n${price.amountsLine}` : null,- favoritesDisabled: !prefs.favoritesReady,+ favoritesDisabled: !prefs.favoritesReady || !!row.remoteDevice,isFavorite: !!matchingFavorite,canReset,configurationSummary: [@@ -756,7 +1008,8 @@ export function UnifiedModelPickerSheet(});},onFavorite: () => {- if (!prefs.favoritesReady || favoriteEdit) return;+ if (!prefs.favoritesReady || favoriteEdit || row.remoteDevice)+ return;void transact(async (isCurrent) => {if (matchingFavorite) {await prefs.save({diff --git a/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx b/apps/mobile/src/session/UnifiedModelPickerView.ios.tsxindex 4d2903e96f..3a99c9d378 100644--- a/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx+++ b/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx@@ -45,6 +45,8 @@ import { ComposerSheet } from "./ComposerSheet";import { ComposerNativeSection as Section } from "./ComposerNativeSection";import { ComposerNativeRow } from "./ComposerNativeRow";import { MobileModelIconMark, MobileProviderMark } from "./MobileProviderMark";+import { RemoteSourceMark } from "./RemoteSourceMark";+import { groupSourceFilters } from "./remoteSourceFilters";import { mobileAgentLabel } from "./sessionAgentSwitch";import type { UnifiedMobilePickerViewProps } from "./UnifiedModelPickerSheet";@@ -66,6 +68,25 @@ function NativeMark({ children }: { children: ReactNode }) {);}+/** 来源格的供应商 mark;另一台电脑上的供应商带远程标记(右上角一道波纹加一个点)。 */+function ProviderSourceMark({+ filter,+}: {+ filter: UnifiedMobilePickerViewProps["filters"][number] | undefined;+}) {+ const mark = (+ <MobileProviderMark+ {...filter?.providerMark}+ name={filter?.providerMark?.name ?? ""}+ />+ );+ return filter?.remote ? (+ <RemoteSourceMark size={iconSize.action}>{mark}</RemoteSourceMark>+ ) : (+ mark+ );+}+export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {const { t } = useTranslation();const { colors } = useTheme();@@ -134,13 +155,8 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {mark(LayoutGrid)) : (<NativeMark>- <MobileProviderMark- {...p.filters.find((item) => item.id === p.filter)- ?.providerMark}- name={- p.filters.find((item) => item.id === p.filter)?.providerMark- ?.name ?? ""- }+ <ProviderSourceMark+ filter={p.filters.find((item) => item.id === p.filter)}/></NativeMark>)}@@ -238,11 +254,21 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {justifyContent: "center",}}>- <MobileModelIconMark- icon={row.entry.icon}- {...row.providerMark}- color={colors.textSecondary}- />+ {row.remoteDevice ? (+ <RemoteSourceMark size={iconSize.action}>+ <MobileModelIconMark+ icon={row.entry.icon}+ {...row.providerMark}+ color={colors.textSecondary}+ />+ </RemoteSourceMark>+ ) : (+ <MobileModelIconMark+ icon={row.entry.icon}+ {...row.providerMark}+ color={colors.textSecondary}+ />+ )}</View></RNHostView>}@@ -270,6 +296,48 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {) : null}</>);+ const sourceRow = (item: (typeof p.filters)[number]) => (+ <ComposerNativeRow+ key={item.id}+ title={item.remote?.providerLabel ?? item.label}+ subtitle={item.quota?.label}+ testID={`${p.testID}.source.${item.id}`}+ selected={p.filter === item.id}+ selectionIcon={mark(Check)}+ leading={+ item.providerMark ? (+ <VStack spacing={2}>+ <NativeMark>+ <ProviderSourceMark filter={item} />+ </NativeMark>+ {item.quota ? (+ <ProgressView+ value={item.quota.remaining / 100}+ modifiers={[+ progressViewStyle("linear"),+ frame({ width: 24 }),+ tint(colors.textSecondary),+ accessibilityLabel(item.quota.label),+ ]}+ testID={`${p.testID}.source.${item.id}.quota`}+ />+ ) : null}+ </VStack>+ ) : (+ mark(+ item.id === "favorites" ? Star : LayoutGrid,+ item.id === "favorites" && p.filter === "favorites",+ )+ )+ }+ onPress={() => {+ p.onFilter(item.id);+ setPage(null);+ }}+ />+ );+ // 来源页分块:被控电脑自己的格一块,其他电脑每台一块。+ const sourceGroups = groupSourceFilters(p.filters);return (<ComposerSheetnativeContent@@ -298,48 +366,15 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {</Section>) : null}{page === "sources" ? (- <Section>- {p.filters.map((item) => (- <ComposerNativeRow- key={item.id}- title={item.label}- subtitle={item.quota?.label}- testID={`${p.testID}.source.${item.id}`}- selected={p.filter === item.id}- selectionIcon={mark(Check)}- leading={- item.providerMark ? (- <VStack spacing={2}>- <NativeMark>- <MobileProviderMark {...item.providerMark} />- </NativeMark>- {item.quota ? (- <ProgressView- value={item.quota.remaining / 100}- modifiers={[- progressViewStyle("linear"),- frame({ width: 24 }),- tint(colors.textSecondary),- accessibilityLabel(item.quota.label),- ]}- testID={`${p.testID}.source.${item.id}.quota`}- />- ) : null}- </VStack>- ) : (- mark(- item.id === "favorites" ? Star : LayoutGrid,- item.id === "favorites" && p.filter === "favorites",- )- )- }- onPress={() => {- p.onFilter(item.id);- setPage(null);- }}- />+ <>+ <Section>{sourceGroups.local.map(sourceRow)}</Section>+ {/* 其他电脑的供应商:每台电脑单独一块,块标题是电脑名。 */}+ {sourceGroups.devices.map((device) => (+ <Section key={device.deviceId} title={device.name}>+ {device.filters.map(sourceRow)}+ </Section>))}- </Section>+ </>) : page === "harness" && options && config ? (<Section>{options.agents.map((agent) => (diff --git a/apps/mobile/src/session/UnifiedModelPickerView.tsx b/apps/mobile/src/session/UnifiedModelPickerView.tsxindex b57d257c82..4bb131c7c2 100644--- a/apps/mobile/src/session/UnifiedModelPickerView.tsx+++ b/apps/mobile/src/session/UnifiedModelPickerView.tsx@@ -52,6 +52,8 @@ import {type ThemeColors,} from "@/theme";import { MobileModelIconMark, MobileProviderMark } from "./MobileProviderMark";+import { RemoteSourceMark } from "./RemoteSourceMark";+import { groupSourceFilters } from "./remoteSourceFilters";import { SheetModal } from "./SheetModal";import { SheetSurface } from "./SheetSurface";import {@@ -274,7 +276,13 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {) : filter.id === "favorites" ? (icon(Star, selected || p.filter === "favorites")) : filter.providerMark ? (- <MobileProviderMark {...filter.providerMark} />+ filter.remote ? (+ <RemoteSourceMark size={iconSize.action}>+ <MobileProviderMark {...filter.providerMark} />+ </RemoteSourceMark>+ ) : (+ <MobileProviderMark {...filter.providerMark} />+ )) : (icon(LayoutGrid));@@ -345,37 +353,51 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {</View>);+ const sourceRow = (item: (typeof p.filters)[number]) => (+ <Row+ key={item.id}+ leading={+ <View style={styles.sourceLeading}>+ {filterMark(+ item,+ item.id === "favorites" && p.filter === "favorites",+ )}+ {item.quota ? (+ <QuotaBar+ label={item.quota.label}+ remaining={item.quota.remaining}+ testID={`${p.testID}.source.${item.id}.quota`}+ />+ ) : null}+ </View>+ }+ onPress={() => {+ p.onFilter(item.id);+ setPage(null);+ }}+ selected={p.filter === item.id}+ subtitle={item.quota?.label}+ testID={`${p.testID}.source.${item.id}`}+ title={item.remote?.providerLabel ?? item.label}+ />+ );+ // 其他电脑的供应商:每台电脑单独一块,块标题是电脑名。+ const sourceGroups = groupSourceFilters(p.filters);const sourcesPage = (- <Group testID={`${p.testID}.sources`}>- {p.filters.map((item) => (- <Row- key={item.id}- leading={- <View style={styles.sourceLeading}>- {filterMark(- item,- item.id === "favorites" && p.filter === "favorites",- )}- {item.quota ? (- <QuotaBar- label={item.quota.label}- remaining={item.quota.remaining}- testID={`${p.testID}.source.${item.id}.quota`}- />- ) : null}- </View>- }- onPress={() => {- p.onFilter(item.id);- setPage(null);- }}- selected={p.filter === item.id}- subtitle={item.quota?.label}- testID={`${p.testID}.source.${item.id}`}- title={item.label}- />+ <>+ <Group testID={`${p.testID}.sources`}>+ {sourceGroups.local.map(sourceRow)}+ </Group>+ {sourceGroups.devices.map((device) => (+ <Group+ key={device.deviceId}+ testID={`${p.testID}.sources.device.${device.deviceId}`}+ title={device.name}+ >+ {device.filters.map(sourceRow)}+ </Group>))}- </Group>+ </>);const harnessPage =@@ -627,6 +649,7 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {<PressableaccessibilityLabel={[row.entry.displayName,+ row.remoteDevice?.name,agentLabel,row.subtitle,row.config.fast ? t("models.options.fastMode") : null,@@ -646,11 +669,21 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {testID={`${p.testID}.model.${row.key}`}><View style={styles.leading}>- <MobileModelIconMark- icon={row.entry.icon}- {...row.providerMark}- color={colors.textSecondary}- />+ {row.remoteDevice ? (+ <RemoteSourceMark size={iconSize.action}>+ <MobileModelIconMark+ icon={row.entry.icon}+ {...row.providerMark}+ color={colors.textSecondary}+ />+ </RemoteSourceMark>+ ) : (+ <MobileModelIconMark+ icon={row.entry.icon}+ {...row.providerMark}+ color={colors.textSecondary}+ />+ )}</View><View style={styles.rowMain}><View style={styles.titleLine}>diff --git a/apps/mobile/src/session/remoteAgentCatalogs.ts b/apps/mobile/src/session/remoteAgentCatalogs.tsnew file mode 100644index 0000000000..8eacc4f681--- /dev/null+++ b/apps/mobile/src/session/remoteAgentCatalogs.ts@@ -0,0 +1,50 @@+/**+ * 远程 Agent 的「其他电脑」模型目录(纯逻辑,与桌面模型面板同口径):+ * 手机的模型选择器在被控电脑自己的供应商之后,列出同账号其他电脑上开了「允许被远程调用」的+ * 供应商,每个供应商一段、标题带电脑名;来源页里每台电脑一块,块标题就是电脑名,没有总的+ * 「其他电脑」标题。一个都没开的电脑不出现,列表不随设备数变长。+ */+import type { DeviceView } from '@cindy/device-link';+import type { ProviderView } from '@cindy/model-providers/registry';++import { toDeviceListItems } from '@/device-link/devices';++/** 一台可选电脑的目录状态(providers 只含开了远程调用的供应商)。 */+export interface RemoteAgentCatalog {+ deviceId: string;+ name: string;+ /** loading = 还没读到;error = 读不到(离线 / 没开远程控制 / 旧版本)且没有缓存。 */+ status: 'loading' | 'ready' | 'error';+ providers: ProviderView[];+ modelVisibilityOverrides?: Record<string, boolean>;+}++/** 那台电脑允许远程调用的供应商;没有该标记(旧数据)按未开放处理。 */+export function remoteAgentProviders(providers: readonly ProviderView[]): ProviderView[] {+ return providers.filter(+ (provider) => (provider as { remoteInvocationEnabled?: unknown }).remoteInvocationEnabled === true,+ );+}++/**+ * 可以让 Agent 运行的其他电脑,顺序同设备列表(可用在前、再按名字,稳定)。排除被控电脑、+ * 手机与已撤销的电脑;离线 / 没开远程控制的电脑读不了目录也不列,但任务当前(或挂着的)+ * Agent 所在电脑始终保留,让用户看得到 Agent 在哪台。+ */+export function selectRemoteAgentDevices(input: {+ devices: readonly DeviceView[];+ controlledDeviceId: string;+ keepDeviceIds: readonly string[];+ revokedDeviceIds?: ReadonlySet<string>;+ now?: number;+}): { deviceId: string; name: string; canOpen: boolean }[] {+ return toDeviceListItems(input.devices, input.now ?? Date.now(), input.revokedDeviceIds)+ .filter((item) => item.device.deviceId !== input.controlledDeviceId)+ .filter((item) => item.state !== 'access_revoked')+ .filter((item) => item.canOpen || input.keepDeviceIds.includes(item.device.deviceId))+ .map((item) => ({+ deviceId: item.device.deviceId,+ name: item.device.name?.trim() || item.device.deviceId,+ canOpen: item.canOpen,+ }));+}diff --git a/apps/mobile/src/session/remoteSourceFilters.ts b/apps/mobile/src/session/remoteSourceFilters.tsnew file mode 100644index 0000000000..1ce9fd652a--- /dev/null+++ b/apps/mobile/src/session/remoteSourceFilters.ts@@ -0,0 +1,31 @@+/**+ * 模型选择器来源页里「其他电脑上的供应商」格(远程 Agent)。纯函数,不依赖设备与 i18n,+ * 供选择器的数据层与 iOS / Android 两套视图共用。+ */++/** 远程供应商格的稳定 id(与本机格的 'all' / 'favorites' / providerId 不会撞)。 */+export function remoteFilterId(deviceId: string, providerId: string): string {+ return `remote:${JSON.stringify([deviceId, providerId])}`;+}++/**+ * 来源页分块:被控电脑自己的格(全部 / 收藏 / 各供应商)一块,其他电脑每台一块(块标题 = 电脑名),+ * 块与块内顺序保持传入顺序。+ */+export function groupSourceFilters<T extends { remote?: { deviceId: string; deviceName: string } }>(+ filters: readonly T[],+): { local: T[]; devices: { deviceId: string; name: string; filters: T[] }[] } {+ const local: T[] = [];+ const devices: { deviceId: string; name: string; filters: T[] }[] = [];+ for (const filter of filters) {+ const remote = filter.remote;+ if (!remote) {+ local.push(filter);+ continue;+ }+ const device = devices.find((item) => item.deviceId === remote.deviceId);+ if (device) device.filters.push(filter);+ else devices.push({ deviceId: remote.deviceId, name: remote.deviceName, filters: [filter] });+ }+ return { local, devices };+}diff --git a/apps/mobile/src/session/sessionAgentSwitch.ts b/apps/mobile/src/session/sessionAgentSwitch.tsindex 6dc7c08a85..8ec3cd6ffc 100644--- a/apps/mobile/src/session/sessionAgentSwitch.ts+++ b/apps/mobile/src/session/sessionAgentSwitch.ts@@ -2,19 +2,15 @@* 手机端跨 Agent 切换的纯契约适配:只接收 desktop main 的公开 pending intent,* 不在控制端持久化第二份真相。*/-import type {- MobileSessionAgentSwitchIntent,-} from '@cindy/maker-shared/device-link-contract';-import type { MobileAgentCapabilities } from './agentCapabilities';-import type { RemoteSession } from './types';+import type { RemoteSession, RemoteSessionAgentSwitchIntent } from './types';export type MobileSessionAgentKind = 'claude-code' | 'codex' | 'pi';/** 将不可信 device-link payload 收窄为公开 intent;非法值按“无意图”处理。 */export function normalizeSessionAgentSwitchIntent(value: unknown,-): MobileSessionAgentSwitchIntent | null {+): RemoteSessionAgentSwitchIntent | null {if (!value || typeof value !== 'object' || Array.isArray(value)) return null;const item = value as Record<string, unknown>;if (@@ -29,6 +25,13 @@ export function normalizeSessionAgentSwitchIntent(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;+ // 远程 Agent:只在这笔切换同时换 Agent 所在电脑时出现(null = 改回被控电脑本机)。+ // 缺省 = 位置不变;非空 string / null 之外的脏值与其它字段同口径判非法。+ if (+ item.agentDeviceId !== undefined+ && item.agentDeviceId !== null+ && (typeof item.agentDeviceId !== 'string' || item.agentDeviceId.length === 0)+ ) return null;return {targetAgentKind: item.targetAgentKind,model: item.model,@@ -37,6 +40,9 @@ export function normalizeSessionAgentSwitchIntent(? { effort: item.effort }: {}),...(typeof item.fastMode === 'boolean' ? { fastMode: item.fastMode } : {}),+ ...(item.agentDeviceId !== undefined+ ? { agentDeviceId: item.agentDeviceId as string | null }+ : {}),};}@@ -68,3 +74,68 @@ export function mobileAgentLabelFromUnknown(agentKind: unknown): string {export function mobileAgentVendor(agentKind: MobileSessionAgentKind): 'cc' | 'codex' | 'pi' {return agentKind === 'claude-code' ? 'cc' : agentKind;}++/** 任务的 Agent 是否在同账号另一台电脑上运行(desktop sessions.agent_device_id 非空)。 */+export function sessionAgentRunsOnOtherComputer(+ session: Pick<RemoteSession, 'agentDeviceId'> | null | undefined,+): boolean {+ return typeof session?.agentDeviceId === 'string' && session.agentDeviceId.length > 0;+}++/** pending intent 是否同时改 Agent 所在电脑(带 agentDeviceId 键,null = 改回被控电脑)。 */+export function intentChangesAgentLocation(+ intent: RemoteSessionAgentSwitchIntent | null | undefined,+): boolean {+ return !!intent && intent.agentDeviceId !== undefined;+}++/**+ * 下一条消息时 Agent 所在的电脑(与桌面 effectiveAgentDeviceId 同口径):pending intent 带+ * 位置就用它,否则用任务当前的位置。null = 被控电脑本机。+ */+export function effectiveAgentDeviceId(+ session: Pick<RemoteSession, 'agentDeviceId'> | null | undefined,+ intent: RemoteSessionAgentSwitchIntent | null | undefined,+): string | null {+ if (intent && intent.agentDeviceId !== undefined) return intent.agentDeviceId;+ return sessionAgentRunsOnOtherComputer(session) ? session!.agentDeviceId! : null;+}++/**+ * 选中一行模型时 Agent 位置怎么处理(与桌面已建任务的换电脑规则同口径):+ * - catalogDeviceId = 这一行来自哪台电脑的目录(null = 被控电脑本机);+ * - relocateTo:与任务当前位置不同才带给被控端(switchSessionAgent 第 7 参);选回任务当前+ * 所在电脑 = 撤销挂着的换位置,不带位置;+ * - needsConfirm:换到下一条消息时所在电脑以外、且不是任务当前所在电脑时才确认(已确认过的+ * 同一目标、或撤销挂着的换位置都不再问)。+ */+export function resolveAgentLocationPick(input: {+ session: Pick<RemoteSession, 'agentDeviceId'> | null | undefined;+ intent: RemoteSessionAgentSwitchIntent | null | undefined;+ catalogDeviceId: string | null;+}): { relocateTo: string | null | undefined; needsConfirm: boolean } {+ const current = sessionAgentRunsOnOtherComputer(input.session)+ ? input.session!.agentDeviceId!+ : null;+ const effective = effectiveAgentDeviceId(input.session, input.intent);+ const target = input.catalogDeviceId;+ return {+ relocateTo: target !== current ? target : undefined,+ needsConfirm: target !== effective && target !== current,+ };+}++/** agent_switch 边界行里 Agent 换电脑后的目标位置;缺 toAgentDeviceId 键 = 没换电脑。 */+export type AgentSwitchLocationTarget =+ | { kind: 'named'; name: string }+ | { kind: 'thisComputer' }+ | { kind: 'otherComputer' };++export function readAgentSwitchLocationTarget(+ data: Record<string, unknown> | undefined,+): AgentSwitchLocationTarget | null {+ if (!data || !Object.prototype.hasOwnProperty.call(data, 'toAgentDeviceId')) return null;+ const name = typeof data.toAgentDeviceName === 'string' ? data.toAgentDeviceName.trim() : '';+ if (name) return { kind: 'named', name };+ return data.toAgentDeviceId === null ? { kind: 'thisComputer' } : { kind: 'otherComputer' };+}diff --git a/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts b/apps/mobile/src/session/sessionAgentSwitchConfirmation.tsindex 7ecf51b08e..8c7b9fbed9 100644--- a/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts+++ b/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts@@ -1,9 +1,14 @@-/** 手机端首次进入另一 Agent 浏览态时的原生确认门。 */+/** 手机端首次进入另一 Agent 浏览态、以及把 Agent 换到另一台电脑运行时的原生确认门。 */import { Alert, type AlertButton, type AlertOptions } from 'react-native';import { i18n } from '@/i18n';-import { mobileAgentLabel, type MobileSessionAgentKind } from './sessionAgentSwitch';+import {+ mobileAgentLabel,+ resolveAgentLocationPick,+ type MobileSessionAgentKind,+} from './sessionAgentSwitch';+import type { RemoteSession, RemoteSessionAgentSwitchIntent } from './types';type ShowAlert = (title: string,@@ -41,3 +46,69 @@ export function confirmMobileSessionAgentSwitch();});}++/** 换位置的结果:{} = 位置不变;agentDeviceId = 带给被控端的新位置(null = 被控电脑)。 */+export type AgentLocationPatch = { agentDeviceId?: string | null };++/**+ * 远程 Agent:选中一行模型时 Agent 的运行位置怎么处理(规则见 resolveAgentLocationPick)。+ * 换到另一台电脑(或改回被控电脑)先确认;取消 = null,调用方什么都不改。+ * movable = false(访客 / 不支持切换 / 旧被控端)时只接受被控电脑自己的目录。+ */+export async function confirmAgentLocationForPick(+ input: {+ movable: boolean;+ session: Pick<RemoteSession, 'agentDeviceId'> | null | undefined;+ intent: RemoteSessionAgentSwitchIntent | null | undefined;+ /** 这一行来自哪台电脑的目录(null = 被控电脑)。 */+ catalogDeviceId: string | null;+ /** 其他电脑的展示名。 */+ deviceName(deviceId: string): string;+ /** 被控电脑的展示名;未知 = null。 */+ hostName: string | null;+ },+ showAlert: ShowAlert = Alert.alert,+): Promise<AgentLocationPatch | null> {+ if (!input.movable) return input.catalogDeviceId === null ? {} : null;+ const pick = resolveAgentLocationPick(input);+ if (pick.needsConfirm) {+ const target = input.catalogDeviceId+ ? { kind: 'device' as const, name: input.deviceName(input.catalogDeviceId) }+ : { kind: 'host' as const, name: input.hostName };+ if (!await confirmMobileAgentRelocation(target, showAlert)) return null;+ }+ return pick.relocateTo !== undefined ? { agentDeviceId: pick.relocateTo } : {};+}++/**+ * 远程 Agent:选中另一台电脑(或被控电脑)目录里的模型 = 把 Agent 换到那台电脑运行,+ * 下一条消息发出时生效。与桌面同一份风险说明;取消 / 系统 dismiss = 什么都不变。+ * target.kind = 'host' 指任务所在的被控电脑,name 未知时用不带名字的说法。+ */+export function confirmMobileAgentRelocation(+ target: { kind: 'device'; name: string } | { kind: 'host'; name: string | null },+ showAlert: ShowAlert = Alert.alert,+): Promise<boolean> {+ const title = target.kind === 'device'+ ? i18n.t('models.agentRelocation.titleOther', { device: target.name })+ : target.name+ ? i18n.t('models.agentRelocation.titleHost', { host: target.name })+ : i18n.t('models.agentRelocation.titleHostUnnamed');+ return new Promise((resolve) => {+ let settled = false;+ const finish = (confirmed: boolean) => {+ if (settled) return;+ settled = true;+ resolve(confirmed);+ };+ showAlert(+ title,+ i18n.t('models.agentRelocation.message'),+ [+ { text: i18n.t('models.agentRelocation.cancel'), style: 'cancel', onPress: () => finish(false) },+ { text: i18n.t('models.agentRelocation.confirm'), onPress: () => finish(true) },+ ],+ { cancelable: true, onDismiss: () => finish(false) },+ );+ });+}diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.tsindex 96703c8d1d..72b6ef29f6 100644--- a/apps/mobile/src/session/systemCard.ts+++ b/apps/mobile/src/session/systemCard.ts@@ -11,7 +11,10 @@ import {type SystemCardType,} from '@cindy/maker-shared/system-card';import { i18n } from '@/i18n';-import { mobileAgentLabelFromUnknown } from '@/session/sessionAgentSwitch';+import {+ mobileAgentLabelFromUnknown,+ readAgentSwitchLocationTarget,+} from '@/session/sessionAgentSwitch';import { formatCompactTokens } from '@cindy/maker-shared/usage-format';/**@@ -190,6 +193,29 @@ function formatAutoResumeCard(data: Record<string, unknown> | undefined): Systemreturn { title, ...(error ? { body: error } : {}), subtitle, rows: [] };}+type AgentSwitchTranslate = (key: string, options?: Record<string, unknown>) => string;++/**+ * 远程 Agent:边界行带 toAgentDeviceId 键 = 这次切换把 Agent 换到了另一台电脑上运行+ * (null = 被控电脑本机),标题改说位置;引擎同时换了再以「 · 目标引擎」带上。没换电脑+ * 返回 null,调用方沿用「已从 X 切换到 Y」。名称是切换时的快照,缺名时按位置给通用说法。+ */+export function formatAgentSwitchLocationLabel(+ data: Record<string, unknown> | undefined,+ translate: AgentSwitchTranslate,+): string | null {+ const location = readAgentSwitchLocationTarget(data);+ if (!location) return null;+ const label = location.kind === 'named'+ ? translate('message.systemCard.agentSwitchLocation', { device: location.name })+ : translate(location.kind === 'thisComputer'+ ? 'message.systemCard.agentSwitchLocationThisComputer'+ : 'message.systemCard.agentSwitchLocationOtherComputer');+ const from = mobileAgentLabelFromUnknown(data?.fromAgentKind);+ const to = mobileAgentLabelFromUnknown(data?.toAgentKind);+ return from === to ? label : `${label} · ${to}`;+}+/*** session-agent-switch 边界卡的纯数据兜底(标题 + 目标模型行)。* 注意:实际渲染已改由 MessageRenderer 的 MobileAgentSwitchCard 直接读 data@@ -204,7 +230,8 @@ function formatAgentSwitchCard(data: Record<string, unknown> | undefined): Syste// Phase 2:resumed = 目标引擎续接了自己的停泊原生会话(增量交接)。if (data?.resumed === true) rows.push({ label: i18n.t('message.systemCard.sessionLabel'), value: i18n.t('message.systemCard.sessionResumed') });return {- title: i18n.t('message.systemCard.agentSwitch', { from, to }),+ title: formatAgentSwitchLocationLabel(data, (key, options) => i18n.t(key, options))+ ?? i18n.t('message.systemCard.agentSwitch', { from, to }),rows,};}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex aeab5b959e..bd2dba7f81 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -6,6 +6,15 @@ import type { MobileToolInputProjection } from '@/session/messageToolPayloadProjimport type { AnnotationRegion } from '@cindy/maker-shared/image-annotation';export type RemoteSessionStatus = 'active' | 'archived' | 'deleted';++/**+ * desktop main 公开的 pending intent(共享契约)+ 远程 Agent 的位置字段:只在这笔切换+ * 同时换 Agent 所在电脑时出现,null = 改回被控电脑本机运行。共享契约类型尚未声明该+ * 可选字段,手机端在这里补齐,旧被控端不发即缺省。+ */+export type RemoteSessionAgentSwitchIntent = MobileSessionAgentSwitchIntent & {+ agentDeviceId?: string | null;+};export type RemoteMessageRole =| 'user'| 'assistant'@@ -66,8 +75,13 @@ export interface RemoteSession {lastTurnEndedAt?: number | null;status: RemoteSessionStatus;agentKind: 'cc' | 'codex' | 'pi';+ /**+ * 远程 Agent:非空 = Agent 在同账号另一台电脑上运行(desktop sessions.agent_device_id),+ * 任务与文件仍留在被控电脑;null / 缺省 = Agent 就在被控电脑运行(含旧被控端)。+ */+ agentDeviceId?: string | null;/** main 进程内的下一条消息跨 Agent 切换意图;null = 已确认没有。 */- agentSwitchIntent?: MobileSessionAgentSwitchIntent | null;+ agentSwitchIntent?: RemoteSessionAgentSwitchIntent | null;source?: string;orcaRole?: 'lead' | 'worker' | string | null;parentSessionId?: string | null;diff --git a/apps/mobile/src/session/useRemoteAgentCatalogs.ts b/apps/mobile/src/session/useRemoteAgentCatalogs.tsnew file mode 100644index 0000000000..c9bee48fd6--- /dev/null+++ b/apps/mobile/src/session/useRemoteAgentCatalogs.ts@@ -0,0 +1,150 @@+/**+ * 远程 Agent:读同账号其他电脑的模型目录,供模型选择器按电脑分段列出(见 remoteAgentCatalogs)。+ *+ * - 电脑清单 = 账号设备列表(readDeviceList,与首页同一次 single-flight 读取);+ * - 每台电脑的目录 = 手机直接经 device-link 向那台电脑取 `maker:provider:list`(与被控电脑+ * 同参数、同一份按设备隔离的供应商缓存);有缓存先显示,再在后台刷新;+ * - 读不到(离线 / 没开远程控制 / 旧版本)只影响那一台,绝不挡住被控电脑自己的列表。+ */+import { useEffect, useMemo, useRef, useState } from 'react';++import { useAuth } from '@/auth/AuthContext';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import {+ fetchDeviceProviders,+ fetchDeviceProvidersFresh,+ getCachedDeviceProviders,+ subscribeDeviceProviders,+ subscribeDeviceProvidersError,+ type DeviceProvidersPayload,+} from '@/device-link/deviceProvidersCache';+import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';++import {+ remoteAgentProviders,+ selectRemoteAgentDevices,+ type RemoteAgentCatalog,+} from './remoteAgentCatalogs';++type CatalogState = { status: RemoteAgentCatalog['status']; payload?: DeviceProvidersPayload };++const NO_CATALOGS: RemoteAgentCatalog[] = [];++export function useRemoteAgentCatalogs(input: {+ /** 只在需要时读(选择器打开,或任务的 Agent 在另一台电脑)。 */+ enabled: boolean;+ controlledDeviceId: string;+ /** 任务当前 / 挂着的 Agent 所在电脑:离线也保留在清单里。 */+ keepDeviceIds: readonly string[];+ /** 只读 keepDeviceIds 里的电脑(选择器没打开、只为模型药丸取 Agent 所在那台的目录时)。 */+ keepOnly?: boolean;+}): RemoteAgentCatalog[] {+ const { readDeviceList, invoke, openLink, connectionEpoch, status } = useDeviceLink();+ const { accountGeneration } = useAuth();+ const revoked = useRevokedDevices();+ const [devices, setDevices] = useState<{ deviceId: string; name: string; canOpen: boolean }[]>([]);+ const [catalogs, setCatalogs] = useState<ReadonlyMap<string, CatalogState>>(new Map());+ const ownerRef = useRef({ accountGeneration, controlledDeviceId: input.controlledDeviceId });+ const keepKey = input.keepDeviceIds.join('\n');+ const keepOnly = input.keepOnly === true;++ // 换账号 / 换被控电脑:旧清单不再属于当前视图。+ useEffect(() => {+ const owner = ownerRef.current;+ if (owner.accountGeneration === accountGeneration+ && owner.controlledDeviceId === input.controlledDeviceId) return;+ ownerRef.current = { accountGeneration, controlledDeviceId: input.controlledDeviceId };+ setDevices([]);+ setCatalogs(new Map());+ }, [accountGeneration, input.controlledDeviceId]);++ useEffect(() => {+ if (!input.enabled || !input.controlledDeviceId || status !== 'online') return;+ let cancelled = false;+ const cleanups: (() => void)[] = [];+ const patch = (deviceId: string, next: CatalogState) => {+ if (cancelled) return;+ setCatalogs((current) => {+ const map = new Map(current);+ map.set(deviceId, next);+ return map;+ });+ };+ void readDeviceList()+ .then((response) => {+ if (cancelled) return;+ const keepDeviceIds = keepKey ? keepKey.split('\n') : [];+ const selected = selectRemoteAgentDevices({+ devices: response.devices,+ controlledDeviceId: input.controlledDeviceId,+ keepDeviceIds,+ revokedDeviceIds: revoked,+ }).filter((device) => !keepOnly || keepDeviceIds.includes(device.deviceId));+ setDevices(selected);+ for (const device of selected) {+ const cached = getCachedDeviceProviders(device.deviceId);+ patch(device.deviceId, cached+ ? { status: 'ready', payload: cached }+ : { status: device.canOpen ? 'loading' : 'error' });+ cleanups.push(subscribeDeviceProviders(device.deviceId, (payload) => {+ patch(device.deviceId, { status: 'ready', payload });+ }));+ cleanups.push(subscribeDeviceProvidersError(device.deviceId, () => {+ // 有缓存继续显示缓存;从未读到过才标成读不到。+ const fallback = getCachedDeviceProviders(device.deviceId);+ patch(device.deviceId, fallback ? { status: 'ready', payload: fallback } : { status: 'error' });+ }));+ if (!device.canOpen) continue;+ const transport = createMobileMakerTransport({+ deviceId: device.deviceId,+ invoke,+ isCurrent: () => !cancelled,+ });+ const read = () => transport.listProviders();+ void openLink(device.deviceId)+ .then(() => (cached+ ? fetchDeviceProvidersFresh(device.deviceId, read)+ : fetchDeviceProviders(device.deviceId, read)))+ .catch(() => {+ if (!getCachedDeviceProviders(device.deviceId)) patch(device.deviceId, { status: 'error' });+ });+ }+ })+ .catch(() => {+ // 设备清单读不到时保留上一份;被控电脑自己的列表不受影响。+ });+ return () => {+ cancelled = true;+ for (const cleanup of cleanups) cleanup();+ };+ }, [+ connectionEpoch,+ input.controlledDeviceId,+ input.enabled,+ invoke,+ keepKey,+ keepOnly,+ openLink,+ readDeviceList,+ revoked,+ status,+ ]);++ return useMemo(() => {+ if (devices.length === 0) return NO_CATALOGS;+ return devices.map((device): RemoteAgentCatalog => {+ const state = catalogs.get(device.deviceId);+ const payload = state?.payload;+ return {+ deviceId: device.deviceId,+ name: device.name,+ status: state?.status ?? (device.canOpen ? 'loading' : 'error'),+ providers: payload ? remoteAgentProviders(payload.providers) : [],+ ...(payload?.modelVisibilityOverrides !== undefined+ ? { modelVisibilityOverrides: payload.modelVisibilityOverrides }+ : {}),+ };+ });+ }, [catalogs, devices]);+}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 03bd0c4345..1993a8697c 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -479,6 +479,18 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自`open` 时把来源落到已开放的供应商上(A 没指定来源时只在已开放的里按默认规则挑)并以显式来源启动;`setModel` 显式换来源时同样核对;关掉后进行中的这一轮照常结束,下一次 `send` 被拒。拒绝统一回`REMOTE_AGENT_PROVIDER_NOT_ALLOWED`,A 按 `chat.remoteError` 提示去那台电脑打开开关或换模型。+- **已建任务换 Agent 所在电脑**(2026-10-07):选模型时可把 Agent 挪到本机或另一台电脑,与任务中途换+ 引擎同一套意图——下一条消息发送时落地,原生会话在原来那台、接不上,一律全量交接 + 全新原生会话,+ 并插 `agent_switch` 边界行。`maker:switch-session-agent` 新增可选第 7 参 `{ agentDeviceId: string | null }`+ (null = 任务所在电脑);不带 = 位置不变(旧控制端与内部调用都走这里,A 不做推断)。pending 意图投影与+ 边界行内容只在换电脑时多出 `agentDeviceId` / `fromAgentDeviceId`、`toAgentDeviceId`、+ `fromAgentDeviceName`、`toAgentDeviceName`,旧端忽略即可(旧端的分隔条显示成「从 X 切换到 X」)。+ Agent 要落在另一台电脑时,A 在**选择时**就读那台的目录核对(在线、供应商已开放、有这个模型),不留+ 发送时才在那台失败、且之后每次发送都重试的意图;本机窗口拿到 `REMOTE_AGENT_DEVICE_UNREACHABLE` /+ `REMOTE_AGENT_MODEL_UNAVAILABLE`,device-link 控制端降级为 `PRECONDITION_FAILED`。Mobile 与桌面同一套+ 模型列表:A 自己的供应商之外,另列其他同账号电脑已开放远程调用的供应商(Mobile 直接经 device-link 读那台的+ `maker:provider:list`,不新增 A 侧 channel);同一台电脑内换模型不带位置,换到另一台电脑先二次确认、再带+ `agentDeviceId`(null = A)。共享任务访客不能换电脑。- **暂不支持**:分叉、审查、移动项目、复制到其他电脑、导出 `.cshare`(Agent 会话记录在 B),入口隐藏、主进程拒绝。