Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 远程 Agent 改在模型列表里选,供应商可逐个设置「允许被远程调用」

Lizidcf3337576fe
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index 05d92323b6..a6b919f9bd 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -384,6 +384,21 @@ describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {
expect(providers[0].routing).toEqual({ codex: {}, 'claude-code': {} });
});
+ it('「允许被远程调用」只作标记透传,不裁剪目录(远程控制与手机仍看到全部供应商)', () => {
+ const base = xdProviderWithFullRouting();
+ const { providers } = project({
+ providers: [
+ { ...base, id: 'shared', remoteInvocationEnabled: true },
+ { ...base, id: 'private', remoteInvocationEnabled: false },
+ { ...base, id: 'odd', remoteInvocationEnabled: 'yes' },
+ { ...base, id: 'legacy' },
+ ],
+ });
+ expect(providers.map((p) => p.id)).toEqual(['shared', 'private', 'odd', 'legacy']);
+ expect(providers.map((p) => p.remoteInvocationEnabled)).toEqual([true, false, undefined, undefined]);
+ expect(providers[2]).not.toHaveProperty('remoteInvocationEnabled');
+ });
+
it('非 maker:provider:list 通道 → 原样返回不改', () => {
const other = { foo: 'bar', providers: [xdProviderWithFullRouting()] };
expect(__testing.projectInvokeResultForTunnel('maker:set-model', other)).toBe(other);
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 50bf8b6e32..6d42896d6c 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -649,6 +649,10 @@ function projectInvokeResultForTunnel(
: {};
const providers = (r.providers as Record<string, unknown>[]).map((p) => {
const rest = { ...p };
+ // 「允许被远程调用」只是标记、不裁剪目录:远程控制与手机仍要看到全部供应商,
+ // 只有远程 Agent 的选择入口按它筛选。只放行布尔值。
+ delete rest.remoteInvocationEnabled;
+ if (typeof p.remoteInvocationEnabled === 'boolean') rest.remoteInvocationEnabled = p.remoteInvocationEnabled;
const logoKind = typeof p.id === 'string'
? resolveProviderLogoKind(p.id, p.routing as ProviderLogoRouting | undefined)
: null;
diff --git a/apps/desktop/src/main/maker-host/remote-provider-access-store.ts b/apps/desktop/src/main/maker-host/remote-provider-access-store.ts
new file mode 100644
index 0000000000..a2150579ff
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/remote-provider-access-store.ts
@@ -0,0 +1,68 @@
+/**
+ * 远程 Agent 的供应商级授权。
+ *
+ * 每台电脑、每个 Cindy 账号各自保存一份;缺席表示未授权(默认关闭)。
+ * 这份设置只决定同账号另一台电脑能否使用本机该供应商的登录与额度,
+ * 不改变本机选择器里的模型可见性,也不把凭证或路由细节写进 device-link。
+ */
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { createOverrideSettingsFile } from './override-settings-file.js';
+import { desktopMakerLogger } from './logger-adapter.js';
+
+interface RemoteProviderAccessPrefs {
+ allowedProviders: Record<string, true>;
+}
+
+const DEFAULTS: RemoteProviderAccessPrefs = { allowedProviders: {} };
+const MAX_ENTRIES = 4096;
+const log = desktopMakerLogger.child('remote-provider-access-store');
+
+function normalize(raw: unknown): RemoteProviderAccessPrefs {
+ const source =
+ raw && typeof raw === 'object' && !Array.isArray(raw)
+ ? (raw as { allowedProviders?: unknown }).allowedProviders
+ : undefined;
+ const allowedProviders: Record<string, true> = {};
+ if (source && typeof source === 'object' && !Array.isArray(source)) {
+ for (const [providerId, enabled] of Object.entries(source as Record<string, unknown>)) {
+ if (enabled !== true || !providerId) continue;
+ if (Object.keys(allowedProviders).length >= MAX_ENTRIES) break;
+ allowedProviders[providerId] = true;
+ }
+ }
+ return { allowedProviders };
+}
+
+const store = createOverrideSettingsFile<RemoteProviderAccessPrefs>({
+ filePath: () => ownerScopedUserDataPath('remote-provider-access-prefs.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'remote-provider-access',
+ maxBytes: 256 * 1024,
+});
+
+export function isRemoteProviderInvocationAllowed(providerId: string): boolean {
+ store.invalidateIfChanged();
+ return store.read().allowedProviders[providerId] === true;
+}
+
+export function setRemoteProviderInvocationEnabled(providerId: string, enabled: boolean): void {
+ if (!providerId) return;
+ store.invalidateIfChanged();
+ const allowedProviders = { ...store.read().allowedProviders };
+ if (enabled) {
+ if (allowedProviders[providerId] === true) return;
+ if (Object.keys(allowedProviders).length >= MAX_ENTRIES) {
+ throw new Error('remote provider access limit reached');
+ }
+ allowedProviders[providerId] = true;
+ } else {
+ if (!(providerId in allowedProviders)) return;
+ delete allowedProviders[providerId];
+ }
+ store.writePatch({ allowedProviders });
+ log.info('remote provider access updated', { providerId, enabled });
+}
+
+export const __testing = { normalize };
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 7ed48915de..3df3a8b28a 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -251,6 +251,8 @@ export const MAKER_INVOKE = {
* **不进 device-link allowlist**(远程改被控端全局设置越权,见 allowlist.ts 准入判据)。
*/
MODEL_DISABLE_SET: 'maker:model-disable:set',
+ /** 本机供应商是否允许同账号另一台电脑的远程 Agent 调用;仅本机可信 renderer 可写。 */
+ PROVIDER_REMOTE_ACCESS_SET: 'maker:provider:remote-access:set',
/**
* Owner-scoped provider display-order override.
* Input = { dataOwnerId: string | null; ownerGeneration: number; providerIds: string[] }.
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 56510aa469..81dc3edb89 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -410,6 +410,9 @@ export interface ProviderHandlerDeps {
*/
setModelsDisabled(providerId: string, modelIds: readonly string[], disabled: boolean): void;
setProviderDisabled(providerId: string, disabled: boolean): void;
+ /** Per-provider opt-in for remote Agent use; absent means disabled. */
+ getRemoteProviderInvocationEnabled?(providerId: string): boolean;
+ setRemoteProviderInvocationEnabled?(providerId: string, enabled: boolean): void;
/**
* 「恢复默认」= 删除该供应商的整组停用 override(供应商级 + 全部逐模型条目,含
* 指向已下架模型的陈旧条目)。语义遵循 docs/dev-rules/configuration-and-overrides.md
@@ -1086,6 +1089,9 @@ export function registerProviderHandlers(
}
assertProviderMutationOwner(ownerAtIngress);
const providerOrder = deps.getProviderOrder();
+ const remoteAccess = deps.getRemoteProviderInvocationEnabled
+ ? (providerId: string) => deps.getRemoteProviderInvocationEnabled!(providerId)
+ : null;
// 运行期鉴权请求头(Authorization / x-api-key 等)一律不经 provider:list 下发任何
// Renderer——即使本机主页面 trusted:任何 Renderer 注入(XSS)都能读走这些长期凭证
// (codex review)。头凭证是 main-only 密文,renderer 从不回读:编辑时未显式改动
@@ -1093,7 +1099,12 @@ export function registerProviderHandlers(
return {
dataOwnerId,
ownerGeneration: ownerAtIngress?.generation ?? 0,
- providers: providers.map(withoutProviderHeaderCredentials),
+ providers: providers.map((provider) => {
+ const safe = withoutProviderHeaderCredentials(provider);
+ return remoteAccess
+ ? { ...safe, remoteInvocationEnabled: remoteAccess(provider.id) }
+ : safe;
+ }),
providerOrder,
modelVisibilityOverrides,
};
@@ -1593,6 +1604,38 @@ export function registerProviderHandlers(
return enqueueDisableWrite(run);
});
+ registry.handle(MAKER_INVOKE.PROVIDER_REMOTE_ACCESS_SET, async (event, input: unknown) => {
+ assertTrustedProviderMutationSender(event);
+ const ownerAtIngress = captureProviderOwnerSession();
+ if (!deps.getRemoteProviderInvocationEnabled || !deps.setRemoteProviderInvocationEnabled) {
+ throwIpcError('INTERNAL', 'remote provider access is not wired');
+ }
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throwIpcError('INVALID_PARAMS', 'invalid input');
+ }
+ const value = input as Record<string, unknown>;
+ if (typeof value.providerId !== 'string' || value.providerId.length === 0 || value.providerId.length > 256) {
+ throwIpcError('INVALID_PARAMS', 'providerId required');
+ }
+ if (typeof value.enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'enabled required');
+ const providers = await deps.listProviders({ allowSideEffects: false });
+ assertProviderMutationOwner(ownerAtIngress);
+ const provider = providers.find((item) => item.id === value.providerId);
+ if (!provider) throwIpcError('INVALID_PARAMS', `unknown providerId "${value.providerId}"`);
+ assertProviderMutationOwner(ownerAtIngress, 'active account changed before persisting remote provider access');
+ try {
+ deps.setRemoteProviderInvocationEnabled(value.providerId, value.enabled);
+ } catch (err) {
+ log.warn('remote provider access persist failed', {
+ providerId: value.providerId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ throwIpcError('INTERNAL', 'failed to persist remote provider access');
+ }
+ deps.broadcastChanged();
+ return { ok: true, enabled: value.enabled };
+ });
+
const parsePriceTarget = (value: unknown): ModelPriceOverrideTarget => {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throwIpcError('INVALID_PARAMS', 'price override target must be an object');
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 7c684a2a8b..122718a1ec 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -22,6 +22,10 @@ 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 {
+ isRemoteProviderInvocationAllowed,
+ setRemoteProviderInvocationEnabled,
+} from '../maker-host/remote-provider-access-store.js';
import { registerModelFavoritesSync } from './modelFavoritesSync.js';
import { advanceRuntimeRecoveryNotice } from '../im/shared/runtimeRecoveryNotice.js';
import { markImSessionManualRouteOverride } from '../im/shared/manualRouteOverride.js';
@@ -6077,6 +6081,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
setModelsDisabled: (providerId, modelIds, disabled) =>
setModelsDisabled(providerId, modelIds, disabled),
setProviderDisabled: (providerId, disabled) => setProviderDisabled(providerId, disabled),
+ getRemoteProviderInvocationEnabled: (providerId) =>
+ isRemoteProviderInvocationAllowed(providerId),
+ setRemoteProviderInvocationEnabled: (providerId, enabled) =>
+ setRemoteProviderInvocationEnabled(providerId, enabled),
stageClearProviderDisableOverrides: (providerId) =>
stageProviderDisableOverridesClear(providerId),
// 「恢复默认」= 删除该供应商整组停用 override(configuration-and-overrides.md §4)。
diff --git a/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.ts b/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.ts
index a2e804e1a4..5beccdc4a6 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/deviceCatalog.test.ts
@@ -50,13 +50,22 @@ describe('parseDeviceProviderViews', () => {
describe('readDeviceProviderViews', () => {
it('asks the other computer for its provider list with the controller capabilities', async () => {
- const invoke = vi.fn(async () => ({ ok: true, result: { providers: [provider()] } }));
+ const invoke = vi.fn(async () => ({ ok: true, result: { providers: [provider({ remoteInvocationEnabled: true })] } }));
expect((await readDeviceProviderViews(invoke, 'device-b')).map((view) => view.id)).toEqual(['spark']);
expect(invoke).toHaveBeenCalledWith('device-b', 'maker:provider:list', [
{ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] },
]);
});
+ it('keeps only the providers that computer allows for remote use', async () => {
+ const invoke = vi.fn(async () => ({ ok: true, result: { providers: [
+ provider({ id: 'shared', remoteInvocationEnabled: true }),
+ provider({ id: 'private', remoteInvocationEnabled: false }),
+ provider({ id: 'legacy' }),
+ ] } }));
+ expect((await readDeviceProviderViews(invoke, 'device-b')).map((view) => view.id)).toEqual(['shared']);
+ });
+
it('keeps the error code when the other computer cannot answer', async () => {
const invoke = vi.fn(async () => ({ ok: false, error: { code: 'DEVICE_OFFLINE', message: 'offline' } }));
await expect(readDeviceProviderViews(invoke, 'device-b')).rejects.toMatchObject({ message: 'offline', code: 'DEVICE_OFFLINE' });
diff --git a/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.ts b/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.ts
new file mode 100644
index 0000000000..5141f4941d
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/providerAccess.test.ts
@@ -0,0 +1,159 @@
+/**
+ * 「允许被远程调用」:Agent 替另一台电脑运行时只能用本机开放了的供应商。
+ * 启动、换来源、进行中关掉授权后的下一条消息,都在运行 Agent 的这台核对。
+ */
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { AgentEvent, AgentSessionHandle } from '@cindy/maker-core';
+import type { ProviderView } from '@cindy/model-providers';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { startRemoteAgentSession } from '../controller/startRemote';
+import { resolveSharedProviderId } from '../host/providerAccess';
+import { createRemoteAgentHost, type HostedStartInput } from '../host/runHost';
+
+const RG = path.resolve(__dirname, '../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');
+
+const view = (id: string, models: string[]): ProviderView => ({
+ id,
+ name: id,
+ agents: ['claude-code'],
+ connected: true,
+ models: { 'claude-code': models.map((model) => ({ id: model, name: model, efforts: [], defaultEffort: null })) },
+ routing: { 'claude-code': {} },
+}) as unknown as ProviderView;
+
+describe('resolveSharedProviderId', () => {
+ const views = [view('xd', ['opus']), view('spark', ['opus', 'sonnet'])];
+ const sharedOnly = (allowed: string[]) => (providerId: string) => allowed.includes(providerId);
+
+ it('only accepts an explicit source this computer opened for remote use', () => {
+ expect(resolveSharedProviderId(views, sharedOnly(['spark']), 'claude-code', 'opus', 'spark')).toBe('spark');
+ expect(resolveSharedProviderId(views, sharedOnly(['spark']), 'claude-code', 'opus', 'xd')).toBeNull();
+ // 授权名单里留着、但供应商已经不在了。
+ expect(resolveSharedProviderId(views, sharedOnly(['gone']), 'claude-code', 'opus', 'gone')).toBeNull();
+ });
+
+ it('picks the default only among opened providers when no source is given', () => {
+ // xd 是本机的原生默认,但没开放,落到开放的 spark。
+ expect(resolveSharedProviderId(views, sharedOnly(['spark']), 'claude-code', 'opus', null)).toBe('spark');
+ expect(resolveSharedProviderId(views, sharedOnly(['xd']), 'claude-code', 'sonnet', undefined)).toBeNull();
+ expect(resolveSharedProviderId(views, sharedOnly([]), 'claude-code', 'opus', null)).toBeNull();
+ });
+});
+
+let root: string;
+
+beforeEach(() => {
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ra-access-')));
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function recordingHandle(input: HostedStartInput, calls: { sends: number; models: unknown[][] }): AgentSessionHandle {
+ // 事件流保持打开到 close,任务才不会在第一次调用前就结束。
+ let closed!: () => void;
+ const untilClosed = new Promise<void>((resolve) => {
+ closed = resolve;
+ });
+ return {
+ id: 'sdk-1',
+ agentKind: input.kind,
+ model: input.options.model,
+ async send() {
+ calls.sends += 1;
+ },
+ async steer() {},
+ async abort() {},
+ async close() {
+ closed();
+ },
+ async setModel(...args: unknown[]) {
+ calls.models.push(args);
+ },
+ events: () => ({
+ async *[Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
+ await untilClosed;
+ },
+ }),
+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),
+ setInteractionResolver() {},
+ } as unknown as AgentSessionHandle;
+}
+
+async function setup(allowed: Set<string>) {
+ const project = path.join(root, 'proj');
+ fs.mkdirSync(project, { recursive: true });
+ const inputs: HostedStartInput[] = [];
+ const calls = { sends: 0, models: [] as unknown[][] };
+ const host = createRemoteAgentHost({
+ isAgentAvailable: () => true,
+ startHosted: async (input) => {
+ inputs.push(input);
+ return recordingHandle(input, calls);
+ },
+ isControllerAuthorized: () => true,
+ providerAccess: {
+ resolve: async (kind, model, providerId) =>
+ resolveSharedProviderId([view('xd', ['opus']), view('spark', ['opus'])], (id) => allowed.has(id), kind, model, providerId),
+ isAllowed: (id) => allowed.has(id),
+ },
+ captureOwner: () => 'owner',
+ isOwnerCurrent: () => true,
+ runsRoot: path.join(root, 'host'),
+ });
+ const start = (providerId: string | null) => startRemoteAgentSession('claude-code', {
+ sessionId: `task-${randomUUID()}`,
+ workingDir: project,
+ model: 'opus',
+ providerId,
+ permissionMode: 'default',
+ }, {
+ invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),
+ rgPath: RG,
+ prepareMcp: async () => ({ servers: new Map(), dispose() {} }),
+ collectProjectFiles: async () => [],
+ isGitRepo: async () => false,
+ newId: randomUUID,
+ });
+ return { host, inputs, calls, start };
+}
+
+describe('remote agent provider access on the computer running the agent', () => {
+ it('refuses to start on a provider that is not opened for remote use', async () => {
+ const { host, inputs, start } = await setup(new Set(['spark']));
+ await expect(start('xd')).rejects.toThrow('REMOTE_AGENT_PROVIDER_NOT_ALLOWED');
+ expect(inputs).toHaveLength(0);
+ host.dispose();
+ });
+
+ it('starts with the opened provider made explicit, even when the other computer sent none', async () => {
+ const { host, inputs, start } = await setup(new Set(['spark']));
+ const handle = await start(null);
+ expect(inputs[0]?.options.providerId).toBe('spark');
+ await handle.close({ reason: 'navigation' });
+ host.dispose();
+ });
+
+ it('checks a source switch and stops new turns once the provider is closed again', async () => {
+ const allowed = new Set(['spark']);
+ const { host, calls, start } = await setup(allowed);
+ const handle = await start('spark');
+ await expect(handle.setModel!('opus', { providerId: 'xd' })).rejects.toThrow('REMOTE_AGENT_PROVIDER_NOT_ALLOWED');
+ await handle.setModel!('opus', { providerId: null });
+ expect(calls.models.at(-1)?.[1]).toMatchObject({ providerId: 'spark' });
+
+ await handle.send({ content: [{ type: 'text', text: 'hi' }] } as never);
+ expect(calls.sends).toBe(1);
+ allowed.delete('spark');
+ await expect(handle.send({ content: [{ type: 'text', text: 'again' }] } as never)).rejects.toThrow('REMOTE_AGENT_PROVIDER_NOT_ALLOWED');
+ expect(calls.sends).toBe(1);
+ await handle.close({ reason: 'navigation' });
+ host.dispose();
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts b/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts
index 199aa25c0d..a758db4244 100644
--- a/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts
+++ b/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts
@@ -4,6 +4,8 @@
* 那台电脑经设备互联的 `maker:provider:list` 给出去敏后的供应商视图;Agent 在那台运行的任务
* (以及它的协同 Worker)按这份目录选模型与来源。与渲染端 useDeviceProviders 同一个通道、同一份
* 投影;只做最小校验,缺少 routing 的 Agent 补空 entry(与渲染端解析边界一致)。
+ * 读取时只留那台电脑开了「允许被远程调用」的供应商(`remoteInvocationEnabled === true`):
+ * 换模型、协同 Worker、定时任务的默认来源都只能落在这些供应商上。
*/
import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';
import type { ProviderView } from '@cindy/model-providers';
@@ -46,7 +48,7 @@ export function parseDeviceProviderViews(value: unknown): ProviderView[] {
});
}
-/** 读那台电脑的供应商视图。 */
+/** 读那台电脑允许被远程调用的供应商视图。 */
export async function readDeviceProviderViews(invoke: RemoteInvoke, deviceId: string): Promise<ProviderView[]> {
const result = await invoke(deviceId, 'maker:provider:list', [
{ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2] },
@@ -54,5 +56,5 @@ export async function readDeviceProviderViews(invoke: RemoteInvoke, deviceId: st
if (!result.ok) {
throw Object.assign(new Error(result.error?.message ?? 'provider list unavailable'), { code: result.error?.code });
}
- return parseDeviceProviderViews(result.result);
+ return parseDeviceProviderViews(result.result).filter((view) => view.remoteInvocationEnabled === true);
}
diff --git a/apps/desktop/src/main/remote-agent/host/providerAccess.ts b/apps/desktop/src/main/remote-agent/host/providerAccess.ts
new file mode 100644
index 0000000000..a3cf4227a9
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/host/providerAccess.ts
@@ -0,0 +1,30 @@
+/**
+ * 「允许被远程调用」(供应商级授权)的来源解析:Agent 在本机替另一台电脑运行时,只能用本机
+ * 开放了的供应商。授权本身存在 maker-host/remote-provider-access-store(默认关)。
+ */
+import {
+ actualSourceIdForModel,
+ effectiveSourceIdForModel,
+ type AgentKind,
+ type ProviderView,
+} from '@cindy/model-providers';
+
+/**
+ * 对方指定了来源时只核对它是否开放;没指定时按本机默认规则在开放的供应商里挑(新路由口径
+ * 优先,找不到再按实际路由口径,恢复仍在用已下架模型的任务时不被误拦)。
+ * 返回 null = 没有开放的供应商可用。
+ */
+export function resolveSharedProviderId(
+ views: readonly ProviderView[],
+ isAllowed: (providerId: string) => boolean,
+ kind: AgentKind,
+ model: string,
+ providerId: string | null | undefined,
+): string | null {
+ if (providerId) {
+ return isAllowed(providerId) && views.some((view) => view.id === providerId) ? providerId : null;
+ }
+ const shared = views.filter((view) => isAllowed(view.id));
+ return effectiveSourceIdForModel(shared, null, model, kind)
+ ?? actualSourceIdForModel(shared, null, model, kind);
+}
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index 4e518c00a5..042443569c 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -91,6 +91,16 @@ export interface RemoteAgentHostDeps {
startHosted(input: HostedStartInput): Promise<AgentSessionHandle>;
/** 本机仍允许该控制端远程控制(总开关打开且未撤销)。 */
isControllerAuthorized(controller: string): boolean;
+ /**
+ * 「允许被远程调用」(供应商级授权,默认关)。不提供 = 不做供应商级限制(测试 / 旧接线)。
+ * - resolve:把对方要用的来源落到本机已开放的供应商上。providerId 是字符串时只核对它是否开放;
+ * null / 缺省时在已开放的供应商里按本机默认规则挑一个。返回 null = 没有开放的供应商可用。
+ * - isAllowed:进行中的任务每次发消息前复核(用户可能刚把它关掉)。
+ */
+ providerAccess?: {
+ resolve(kind: RemoteAgentKind, model: string, providerId: string | null | undefined): Promise<string | null>;
+ isAllowed(providerId: string): boolean;
+ };
captureOwner(): unknown;
isOwnerCurrent(owner: unknown): boolean;
/** 本机存放影子目录与附件的根目录。 */
@@ -135,6 +145,8 @@ interface Run {
pushSeq: Set<number>;
/** 拼接中的分段 WebSocket 消息(按连接)。 */
pushParts: Map<string, string>;
+ /** 这个任务正在用的本机供应商(已核对开放);没接供应商授权时为空。 */
+ providerId?: string;
lastState?: string;
stateTimer?: ReturnType<typeof setInterval>;
}
@@ -180,6 +192,10 @@ function fail(code: string, message: string): never {
throw new Error(`[${code}] ${message}`);
}
+function failProviderNotAllowed(): never {
+ fail('REMOTE_AGENT_PROVIDER_NOT_ALLOWED', 'this provider is not allowed for remote use on this computer');
+}
+
export function remoteAgentErrorInfo(error: unknown): RemoteAgentErrorInfo {
const err = error instanceof Error ? error : new Error(String(error));
const rawCode = (err as unknown as { code?: unknown }).code;
@@ -607,6 +623,27 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
const target = (handle as unknown as Record<string, unknown>)[method];
if (typeof target !== 'function') fail('REMOTE_AGENT_UNSUPPORTED', `${method} is not supported by this agent`);
let callArgs: unknown[] = args;
+ // 供应商授权:新一轮对话前复核(关掉后不再开始新的一轮,进行中的这一轮照常结束);
+ // 换模型时显式换来源(含 null = 默认)要落到开放的供应商上,只换模型则沿用当前来源。
+ let nextProviderId: string | undefined;
+ const access = deps.providerAccess;
+ if (access && method === 'send' && run.providerId && !access.isAllowed(run.providerId)) {
+ failProviderNotAllowed();
+ }
+ if (access && method === 'setModel') {
+ const opts = args[1];
+ if (opts && typeof opts === 'object' && !Array.isArray(opts) && 'providerId' in opts) {
+ const requested = (opts as { providerId?: unknown }).providerId;
+ const resolved = await access.resolve(
+ run.kind,
+ typeof args[0] === 'string' ? args[0] : '',
+ typeof requested === 'string' ? requested : null,
+ );
+ if (!resolved) failProviderNotAllowed();
+ nextProviderId = resolved;
+ callArgs = [args[0], { ...opts, providerId: resolved }, ...args.slice(2)];
+ }
+ }
if (method === 'send' || method === 'steer') {
const message = await decodeUserMessage(args[0], (data, ext) => writeAttachment(run, data, ext));
const opts = await decodeSendOptions(args[1], {
@@ -621,6 +658,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
callArgs = [message, opts];
}
const value = await (target as (...a: unknown[]) => unknown).apply(handle, callArgs);
+ if (nextProviderId) run.providerId = nextProviderId;
append(run, { t: 'result', callId, ok: true, ...(value !== undefined ? { value: JSON.parse(JSON.stringify(value)) } : {}) });
} catch (error) {
append(run, { t: 'result', callId, ok: false, error: remoteAgentErrorInfo(error) });
@@ -730,7 +768,21 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
if (!deps.isAgentAvailable(request.agentKind)) fail('REMOTE_AGENT_UNSUPPORTED', `${request.agentKind} is not available on this computer`);
const active = [...runs.values()].filter((run) => run.controller === controller && run.closedAt === undefined).length;
if (active >= REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER) fail('REMOTE_AGENT_BUSY', 'too many tasks are running from this computer');
- const payload = decodeOpenPayload(await resolvePayload(controller, request.payload));
+ let payload = decodeOpenPayload(await resolvePayload(controller, request.payload));
+ // 供应商授权:来源落到本机已开放的供应商上,并以显式来源启动(核对的就是实际用的)。
+ let providerId: string | undefined;
+ if (deps.providerAccess) {
+ const resolved = await deps.providerAccess.resolve(
+ request.agentKind,
+ payload.options.model,
+ payload.options.providerId,
+ );
+ if (!resolved) failProviderNotAllowed();
+ providerId = resolved;
+ payload = { ...payload, options: { ...payload.options, providerId: resolved } };
+ }
+ // 上面有等待:同一个 runId 的重发可能已经先登记了。
+ if (runs.has(key(controller, request.runId))) return {};
const run: Run = {
id: request.runId,
controller,
@@ -744,6 +796,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
calls: new Map(),
pushSeq: new Set(),
pushParts: new Map(),
+ ...(providerId ? { providerId } : {}),
};
runs.set(key(controller, request.runId), run);
ensureSweep();
diff --git a/apps/desktop/src/main/remote-agent/host/service.ts b/apps/desktop/src/main/remote-agent/host/service.ts
index 4c4d6d225e..98c46cd0a9 100644
--- a/apps/desktop/src/main/remote-agent/host/service.ts
+++ b/apps/desktop/src/main/remote-agent/host/service.ts
@@ -14,6 +14,9 @@ import {
} from '../../device-link/broadcast-tap.js';
import { setRemoteAgentHandler } from '../../device-link/dispatch.js';
import { readDeviceLinkSettings } from '../../device-link/settings-store.js';
+import { getDesktopProviderService } from '../../maker-host/createDesktopProviderService.js';
+import { isRemoteProviderInvocationAllowed } from '../../maker-host/remote-provider-access-store.js';
+import { resolveSharedProviderId } from './providerAccess';
import { createRemoteAgentHost, type HostedStartInput, type RemoteAgentHost } from './runHost';
const log = createLogger('remote-agent:host');
@@ -74,6 +77,17 @@ export function installRemoteAgentHost(options: { getMaker: () => Maker; userDat
const settings = readDeviceLinkSettings();
return settings.remoteControlEnabled && !settings.revokedControllers.includes(controller);
},
+ providerAccess: {
+ resolve: async (kind, model, providerId) =>
+ resolveSharedProviderId(
+ await getDesktopProviderService().listProviders({ allowSideEffects: false }),
+ isRemoteProviderInvocationAllowed,
+ kind,
+ model,
+ providerId,
+ ),
+ isAllowed: isRemoteProviderInvocationAllowed,
+ },
captureOwner: captureDataOwnerBroadcastScope,
isOwnerCurrent: (owner) => isDataOwnerBroadcastScopeCurrent(owner as DataOwnerBroadcastScope),
runsRoot: path.join(options.userDataDir, 'remote-agent'),
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index d426f69734..44bb06be68 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6044,6 +6044,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
providers: import('@cindy/model-providers').ProviderView[];
providerOrder: string[];
}> => ipcRenderer.invoke('maker:provider:list'),
+ setProviderRemoteAccess: (input: { providerId: string; enabled: boolean }): Promise<{ ok: true; enabled: boolean }> =>
+ ipcRenderer.invoke('maker:provider:remote-access:set', input),
/** Refresh one built-in provider through its existing main-process discovery source. */
refreshBuiltinProviderModels: (
providerId: import('../shared/providerModelRefresh').BuiltinRefreshableProviderId,
diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
index a5805454e2..6427b18392 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
@@ -489,7 +489,7 @@ describe('ChatInput model source switching wiring', () => {
const draftBlock = chatInputSource.slice(
draftStart,
chatInputSource.indexOf(
- '[sessionId, settingsLocked, modelMemory, onUnifiedDraftSelect]',
+ '[sessionId, settingsLocked, modelMemory, onUnifiedDraftSelect, agentDeviceId]',
draftStart,
),
);
@@ -497,11 +497,16 @@ describe('ChatInput model source switching wiring', () => {
// rowModelId 只在类型声明与注释里出现,**不得**出现在任何写入实参上。
expect(draftBlock).not.toContain('selection.rowModelId');
for (const write of [
- 'modelMemory?.setEffort(',
- 'modelMemory?.setFast(targetKind, selection.providerId, selection.modelId, selection.fast)',
+ 'targetMemory?.setEffort(',
+ 'targetMemory?.setFast(targetKind, selection.providerId, selection.modelId, selection.fast)',
]) {
expect(draftBlock).toContain(write);
}
+ // 远程 Agent 换落点:记忆按目标目录写(回本机写本机预设,去另一台电脑不写),
+ // 落点原样交给草稿层。
+ expect(draftBlock).toContain('selection.agentDevice === null');
+ expect(draftBlock).toContain('? LOCAL_MODEL_MEMORY');
+ expect(draftBlock).toContain('agentDevice: selection.agentDevice');
// 「恢复推荐」已先删除记忆键;直通草稿时不得把推荐档位重新写成 override。
expect(draftBlock).toContain('!selection.resetToRecommended');
expect(draftBlock).toContain(
@@ -512,7 +517,7 @@ describe('ChatInput model source switching wiring', () => {
it('keeps a new conversation model pick on the draft path', () => {
const draftStart = chatInputSource.indexOf('const handleUnifiedDraftSelect = useCallback(');
const draftEnd = chatInputSource.indexOf(
- '[sessionId, settingsLocked, modelMemory, onUnifiedDraftSelect]',
+ '[sessionId, settingsLocked, modelMemory, onUnifiedDraftSelect, agentDeviceId]',
draftStart,
);
const draftHandler = chatInputSource.slice(draftStart, draftEnd);
diff --git a/apps/desktop/src/renderer/__tests__/deviceSwitcherAgentDevice.test.tsx b/apps/desktop/src/renderer/__tests__/deviceSwitcherAgentDevice.test.tsx
deleted file mode 100644
index ff6034bc2b..0000000000
--- a/apps/desktop/src/renderer/__tests__/deviceSwitcherAgentDevice.test.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-// @vitest-environment jsdom
-
-/**
- * 设备 pill 的「只让 Agent 在其他电脑运行」:与「在那台上创建任务」分段列出、互不冒充;
- * 选中后 pill 写明 Agent 所在的电脑,点「本机」回到全部在本机。
- */
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string, values?: Record<string, unknown>) =>
- values?.device ? `${key}(${String(values.device)})` : key,
- }),
-}));
-
-import { DeviceSwitcherPill } from '@/components/new-chat/DeviceSwitcherPill';
-
-const devices = [
- { deviceId: 'dev-b', name: 'Office Mac', platform: 'darwin', online: true },
- { deviceId: 'dev-c', name: 'Old PC', platform: 'win32', online: false },
-];
-
-afterEach(() => cleanup());
-
-function renderPill(props: Partial<Parameters<typeof DeviceSwitcherPill>[0]> = {}) {
- const onChange = vi.fn();
- const onAgentDeviceChange = vi.fn();
- const onOpenChange = vi.fn();
- render(
- <DeviceSwitcherPill
- devices={devices}
- value={null}
- onChange={onChange}
- open
- onOpenChange={onOpenChange}
- onAgentDeviceChange={onAgentDeviceChange}
- {...props}
- />,
- );
- return { onChange, onAgentDeviceChange, onOpenChange };
-}
-
-describe('device pill: agent on another computer', () => {
- it('lists computers for running only the agent separately from creating the task there', () => {
- const { onChange, onAgentDeviceChange, onOpenChange } = renderPill();
- expect(screen.getByText('newChat.deviceSwitcher.agentSection')).toBeTruthy();
- const agentRows = screen.getAllByTestId('create-agent-agent-device-option');
- expect(agentRows).toHaveLength(2);
- // 离线的电脑列出但不能选。
- expect((agentRows[1] as HTMLButtonElement).disabled).toBe(true);
- fireEvent.click(agentRows[0]);
- expect(onAgentDeviceChange).toHaveBeenCalledWith('dev-b', 'Office Mac');
- expect(onChange).not.toHaveBeenCalled();
- expect(onOpenChange).toHaveBeenCalledWith(false);
- });
-
- it('names the agent computer on the pill and returns everything here from 本机', () => {
- const { onChange } = renderPill({ agentDeviceId: 'dev-b' });
- const pill = screen.getByTestId('create-agent-device-pill');
- expect(pill.getAttribute('aria-label')).toContain('newChat.deviceSwitcher.agentPill(Office Mac)');
- const localRow = screen.getAllByTestId('create-agent-device-option')[0];
- fireEvent.click(localRow);
- expect(onChange).toHaveBeenCalledWith(null, null);
- });
-
- it('keeps the old menu when the caller does not offer it', () => {
- renderPill({ onAgentDeviceChange: undefined });
- expect(screen.queryByText('newChat.deviceSwitcher.agentSection')).toBeNull();
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
index a0e5812681..1ef06c41ce 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
@@ -1282,9 +1282,9 @@ describe('Shared create project picker', () => {
it('routes every draft-target transition through the single action', () => {
// 五条路径:设备 pill、设备域浏览器选项目、工作区 picker、所选设备失效后的自动回落、
// “对话”分组导航请求。声明本身是 `= useCallback(` 不匹配这个模式,所以数出来的就是调用点。
- // 第六条:选「只让 Agent 在其他电脑运行」时,原来要建到远程设备 / SSH 的草稿先回本机。
+ // (远程 Agent 由模型选择器选择、只在本机任务出现,不再经设备菜单转移草稿目标。)
const calls = newMakerDraftRouteSource.match(/applyDraftTarget\(\{/g) ?? [];
- expect(calls.length).toBe(6);
+ expect(calls.length).toBe(5);
// 组件里不得再有任何一处手写这些副作用 —— 手写一处就等于又开了一条绕过推导的路。
// patchDraft 仍可出现(入场清 extraDirs、发送后复位),但不得再带设备字段。
expect(newMakerDraftRouteSource).not.toContain('deviceLinkDeviceId: deviceId,');
@@ -1683,7 +1683,9 @@ describe('Shared create project picker', () => {
// 5 → 6:统一模型选择器(M5)新增 handleUnifiedDraftSelect —— 它同样是一次
// 控制端对远程运行配置的显式编辑,漏打这个标记的话下一次 capabilities 刷新
// 会把用户刚选的模型重种回被控端默认。
- expect((runtimeHandlers.match(/dlRuntimeTouchedRef\.current = true;/g) ?? []).length).toBe(6);
+ // 6 → 7:同一处理器里「选到另一台电脑上的模型」(远程 Agent 换落点)也是显式编辑,
+ // 那台的 capabilities 到达时同样只能夹紧、不能重种。
+ expect((runtimeHandlers.match(/dlRuntimeTouchedRef\.current = true;/g) ?? []).length).toBe(7);
});
/**
@@ -1779,9 +1781,9 @@ describe('New Maker 草稿的 wire model id 口径', () => {
handlerStart,
newMakerDraftRouteSource.indexOf('// ─── 用户改 workingDir', handlerStart),
);
- // 本地草稿落 lastByVendor(→ createSession)、device-link 草稿落 dlSel —— 两条都用
- // selection.modelId(wire id),一处都不能换成行 id。
- expect((handler.match(/model: selection\.modelId,/g) ?? []).length).toBe(2);
+ // 本地草稿落 lastByVendor(→ createSession)、device-link 草稿落 dlSel、远程 Agent 换落点
+ // 时播种那台电脑的 dlSel —— 三条都用 selection.modelId(wire id),一处都不能换成行 id。
+ expect((handler.match(/model: selection\.modelId,/g) ?? []).length).toBe(3);
// 归一化行 id 不进草稿层,连字段都不该出现在写入实参里。
expect(handler).not.toContain('rowModelId');
});
diff --git a/apps/desktop/src/renderer/__tests__/remoteAgentModelRail.test.tsx b/apps/desktop/src/renderer/__tests__/remoteAgentModelRail.test.tsx
new file mode 100644
index 0000000000..4d1e719ad9
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteAgentModelRail.test.tsx
@@ -0,0 +1,156 @@
+// @vitest-environment jsdom
+/**
+ * 远程 Agent 从模型选择器左侧栏选择(2026-10-06 用户裁决:不再走设备菜单)。
+ *
+ * 锁三件事:远程供应商格与本机格互不串(同名供应商在本机与两台电脑上是三格);远程格用
+ * 带信号波纹的 Logo、按「供应商 · 电脑」命名、每台电脑一段;列表筛选把远程格当作按供应商筛。
+ */
+import React from 'react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { ProviderView, UnifiedModelEntry } from '@cindy/model-providers';
+
+vi.mock('@/hooks/useCodexRateLimits', () => ({ useCodexRateLimits: vi.fn() }));
+vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({ useClaudeSubscriptionUsage: vi.fn() }));
+vi.mock('@/hooks/useXaiSubscriptionUsage', () => ({ useXaiSubscriptionUsage: vi.fn() }));
+vi.mock('@/hooks/useRemoteDeviceUsage', () => ({
+ useRemoteCodexAccountUsage: vi.fn(),
+ useRemoteXaiSubscriptionUsage: vi.fn(),
+}));
+vi.mock('@/hooks/useRemoteClaudeSubscriptionUsage', () => ({
+ useRemoteClaudeSubscriptionUsage: vi.fn(),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+
+import { UnifiedModelRail } from '@/components/new-chat/UnifiedModelRail';
+import {
+ buildUnifiedListSections,
+ railItemKey,
+ railProviderFilterId,
+ remoteAgentProviders,
+ type UnifiedRailItem,
+} from '@/components/new-chat/unifiedModelSelection';
+
+const provider = (id: string, name = id): ProviderView => ({
+ id,
+ name,
+ source: 'builtin',
+ auth: { method: 'oauth' },
+ access: { kind: 'subscription', product: 'test' },
+ connected: true,
+ agents: [],
+ routing: {},
+ models: {},
+});
+
+function entryOf(providerId: string, modelId: string): UnifiedModelEntry {
+ return {
+ providerId,
+ modelId,
+ displayName: modelId,
+ candidates: ['claude-code'],
+ recommended: 'claude-code',
+ nativeAgent: 'claude-code',
+ capabilities: {
+ 'claude-code': {
+ agent: 'claude-code',
+ wireModelId: modelId,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ defaultEffortSource: 'catalog',
+ supportsFastMode: false,
+ contextWindow: 200_000,
+ contextWindowVerified: false,
+ },
+ },
+ };
+}
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('providers another computer allows for remote use', () => {
+ it('lists only providers that computer opened; missing flags count as closed', () => {
+ const views = [
+ { ...provider('shared'), remoteInvocationEnabled: true },
+ { ...provider('private'), remoteInvocationEnabled: false },
+ provider('legacy'),
+ ];
+ expect(remoteAgentProviders(views).map((view) => view.id)).toEqual(['shared']);
+ });
+});
+
+describe('remote provider rail items', () => {
+ it('keeps the same provider on this computer and on two others as distinct cells', () => {
+ const keys = [
+ railItemKey({ kind: 'provider', providerId: 'anthropic' }),
+ railItemKey({ kind: 'remote-provider', deviceId: 'office', providerId: 'anthropic' }),
+ railItemKey({ kind: 'remote-provider', deviceId: 'studio', providerId: 'anthropic' }),
+ ];
+ expect(new Set(keys).size).toBe(3);
+ expect(
+ railProviderFilterId({ kind: 'remote-provider', deviceId: 'office', providerId: 'openai' }),
+ ).toBe('openai');
+ expect(railProviderFilterId({ kind: 'all' })).toBeNull();
+ });
+
+ it('filters the list by provider when a remote provider cell is active', () => {
+ const sections = buildUnifiedListSections({
+ entries: [entryOf('anthropic', 'claude-opus-5'), entryOf('openai', 'gpt-5.5')],
+ favorites: [],
+ query: '',
+ rail: { kind: 'remote-provider', deviceId: 'office', providerId: 'openai' },
+ });
+ expect(sections.map((section) => section.group)).toEqual([
+ { type: 'provider', providerId: 'openai' },
+ ]);
+ });
+
+ it('renders remote cells with the remote mark, one segment per computer', () => {
+ const items: UnifiedRailItem[] = [
+ { kind: 'favorites' },
+ { kind: 'all' },
+ { kind: 'provider', providerId: 'anthropic' },
+ { kind: 'remote-provider', deviceId: 'office', providerId: 'anthropic' },
+ { kind: 'remote-provider', deviceId: 'office', providerId: 'openai' },
+ { kind: 'remote-provider', deviceId: 'studio', providerId: 'anthropic' },
+ ];
+ const onSelect = vi.fn();
+ const devices: Record<string, string> = { office: 'Office Mac', studio: 'Studio PC' };
+ const { container } = render(
+ <UnifiedModelRail
+ items={items}
+ active={{ kind: 'remote-provider', deviceId: 'office', providerId: 'openai' }}
+ onSelect={onSelect}
+ // 正在浏览 office 的目录:本机格不能拿这份当自己的名字 / 图标。
+ providers={[provider('anthropic', 'Office catalog')]}
+ providerLabel={(id) => `current ${id}`}
+ remoteSources={{
+ localProviders: [provider('anthropic', 'Anthropic')],
+ localProviderLabel: (id) => `local ${id}`,
+ providersOf: () => [provider('anthropic'), provider('openai')],
+ labelOf: (deviceId, providerId) => `${providerId} · ${devices[deviceId]}`,
+ }}
+ />,
+ );
+
+ const local = screen.getByRole('button', { name: 'local anthropic' });
+ expect(local.querySelector('[data-remote-source-mark]')).toBeNull();
+ const remote = screen.getByRole('button', { name: 'openai · Office Mac' });
+ expect(remote.querySelector('[data-remote-source-mark]')).not.toBeNull();
+ expect(remote.getAttribute('aria-pressed')).toBe('true');
+ expect(screen.getByRole('button', { name: 'anthropic · Studio PC' })).toBeTruthy();
+ // 分隔线:全部之前一条 + 每台电脑的段首各一条。
+ expect(container.querySelectorAll('div[aria-hidden].border-t').length).toBe(3);
+
+ fireEvent.click(screen.getByRole('button', { name: 'anthropic · Studio PC' }));
+ expect(onSelect).toHaveBeenCalledWith({
+ kind: 'remote-provider',
+ deviceId: 'studio',
+ providerId: 'anthropic',
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/components/icons/RemoteSourceMark.tsx b/apps/desktop/src/renderer/components/icons/RemoteSourceMark.tsx
new file mode 100644
index 0000000000..dc118b5835
--- /dev/null
+++ b/apps/desktop/src/renderer/components/icons/RemoteSourceMark.tsx
@@ -0,0 +1,65 @@
+/**
+ * RemoteSourceMark —— 「另一台电脑上的供应商」图标。
+ *
+ * 品牌图形缩到左下,右上角用一道波纹加一个点标出远端:仍是**一个**图标位,
+ * 一眼读出「这个供应商,在远处」。不在 Logo 旁边另放电脑图标(2026-10-06 用户裁决)。
+ *
+ * 几何(16 单位画布):品牌占左下 12.5 × 12.5,波纹从品牌右上角向外发出,
+ * 点落在连接角内。颜色全部跟随 currentColor,Light / Dark 由外层文字色决定。
+ */
+import type { ReactNode } from 'react';
+
+import { cn } from '@/lib/utils';
+
+/** 品牌图形在 16 单位画布里所占边长(左下对齐)。 */
+const BRAND_UNITS = 12.5;
+
+export function RemoteSourceMark({
+ size,
+ markSize = 13,
+ className,
+ children,
+}: {
+ /** 整个图标(品牌 + 波纹)的边长,px。 */
+ size: number;
+ /** children 渲染时的原生边长,px;按比例缩进品牌区。 */
+ markSize?: number;
+ className?: string;
+ /** 品牌图形(ProviderMark / ModelIconMark 等,颜色请用 currentColor)。 */
+ children: ReactNode;
+}) {
+ const scale = (size * BRAND_UNITS) / 16 / markSize;
+ return (
+ <span
+ aria-hidden
+ data-remote-source-mark
+ className={cn('relative inline-block shrink-0', className)}
+ style={{ width: size, height: size }}
+ >
+ <span
+ className="absolute bottom-0 left-0 flex items-end justify-start"
+ style={{
+ width: markSize,
+ height: markSize,
+ transform: `scale(${scale})`,
+ transformOrigin: 'left bottom',
+ }}
+ >
+ {children}
+ </span>
+ <svg
+ viewBox="0 0 16 16"
+ width={size}
+ height={size}
+ className="absolute inset-0"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.4}
+ strokeLinecap="round"
+ >
+ <path d="M12 1.4A2.6 2.6 0 0 1 14.6 4" />
+ <circle cx="12.6" cy="3.4" r="0.95" fill="currentColor" stroke="none" />
+ </svg>
+ </span>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 72dcd441df..0de2b0ffec 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -122,6 +122,8 @@ import {
resolveModelSelectorAgentIdentity,
type EffortChangeOptions,
type ModelMemoryAccessors,
+ type RemoteAgentSelectorOptions,
+ type UnifiedSelectionAgentDevice,
} from './ModelSelector';
import {
enqueueEffortChange,
@@ -532,6 +534,14 @@ interface ChatInputProps {
* 切换模型也走本机 IPC(由本机转给那台的 Agent)。与 deviceLinkDeviceId 互斥。
*/
agentDeviceId?: string | null;
+ /** agentDeviceId 那台电脑的名字(模型选择器悬停 / 读屏用);未知时显示「另一台电脑」。 */
+ agentDeviceName?: string | null;
+ /**
+ * 新任务草稿可选的「Agent 在其他电脑运行」目标(在线的同账号电脑)。传了且非空时,模型面板
+ * 左侧栏在本机供应商之后列出这些电脑上的供应商;选中那里的模型会经 onUnifiedDraftSelect 的
+ * agentDevice 交给草稿层。已建任务 / 远程任务 / SSH 任务不传。
+ */
+ remoteAgentDevices?: readonly { deviceId: string; name: string }[];
/**
* device-link「纯显示镜像」记忆 override:非空时优先于本机全局模型预设注入 ModelSelector,
* 用于远程草稿 / 远程会话——非选中行读被控端镜像、改动经隧道写穿被控端,绝不碰控制端本地记忆
@@ -849,6 +859,11 @@ interface ChatInputProps {
favoriteUid: string | null;
/** 来自配置浮层「恢复推荐」,不得把推荐档重新写成用户 override。 */
resetToRecommended?: true;
+ /**
+ * 只在传了 remoteAgentDevices 时出现:这一行属于哪台电脑(null = 本机)。与当前
+ * agentDeviceId 不同 = 连 Agent 的运行位置一起换。
+ */
+ agentDevice?: UnifiedSelectionAgentDevice;
}) => void;
/**
* 统一面板里被选中的收藏锚点 uid(与 onUnifiedDraftSelect 成对,由草稿层持有)。
@@ -857,6 +872,21 @@ interface ChatInputProps {
selectedFavoriteUid?: string | null;
}
+/** 本机模型全局预设的读写器(本机目录的选择器共用一份,引用稳定)。 */
+const LOCAL_MODEL_MEMORY: ModelMemoryAccessors = {
+ getEffort: getProviderModelEffort,
+ setEffort: setProviderModelEffort,
+ setChoice: setProviderModelChoice,
+ getFast: getProviderModelFast,
+ setFast: setProviderModelFast,
+ getThinking: getProviderModelThinking,
+ setThinking: setProviderModelThinking,
+ // 「恢复推荐」= 删记忆键(跟随目录新默认),不是把这一版的默认快照写回去。
+ // device-link 镜像没有这两个入口(隧道协议没有删除那一笔),按各自能力退化。
+ clearEffort: clearProviderModelEffort,
+ clearFast: clearProviderModelFast,
+};
+
/** 统一模型选择器联合列表的候选引擎全集(与 SELECTABLE_VENDORS 同一顺序)。 */
const UNIFIED_AGENT_KINDS: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];
@@ -1118,6 +1148,8 @@ export function ChatInput({
remoteHostId,
deviceLinkDeviceId: _deviceLinkDeviceId,
agentDeviceId: _agentDeviceId,
+ agentDeviceName = null,
+ remoteAgentDevices,
modelMemoryOverride,
initialModel,
initialEffort,
@@ -1999,21 +2031,22 @@ export function ChatInput({
if (modelMemoryOverride) return modelMemoryOverride;
// 模型目录在另一台电脑时不掺本机记忆(那台的来源 id 与本机的不是一回事)。
if (catalogDeviceId) return undefined;
- return {
- getEffort: getProviderModelEffort,
- setEffort: setProviderModelEffort,
- setChoice: setProviderModelChoice,
- getFast: getProviderModelFast,
- setFast: setProviderModelFast,
- getThinking: getProviderModelThinking,
- setThinking: setProviderModelThinking,
- // 「恢复推荐」= 删记忆键(跟随目录新默认),不是把这一版的默认快照写回去。
- // device-link 镜像没有这两个入口(隧道协议没有删除那一笔),按各自能力退化。
- clearEffort: clearProviderModelEffort,
- clearFast: clearProviderModelFast,
- };
+ return LOCAL_MODEL_MEMORY;
}, [catalogDeviceId, modelMemoryOverride, sshCodexHostId]);
+ // 远程 Agent(仅本机新任务草稿):模型面板左侧栏同时列出其他电脑上的供应商。
+ const remoteAgentOptions = useMemo<RemoteAgentSelectorOptions | undefined>(
+ () =>
+ !sessionId && !deviceLinkDeviceId && !remoteHostId && remoteAgentDevices && remoteAgentDevices.length > 0
+ ? {
+ devices: remoteAgentDevices,
+ selectedDeviceId: agentDeviceId,
+ localModelMemory: LOCAL_MODEL_MEMORY,
+ }
+ : undefined,
+ [sessionId, deviceLinkDeviceId, remoteHostId, remoteAgentDevices, agentDeviceId],
+ );
+
// 把「用户在当前来源下选定的 (model, effort)」记进模型全局预设,供其它非活跃行和之后的
// 模型切换恢复。agent / 来源缺失(未知模型 / 0 已连接来源)/ device-link 无镜像时静默跳过。
const rememberProviderChoice = useCallback(
@@ -7044,19 +7077,30 @@ export function ChatInput({
/** 行的归一化 id(面板行身份)。草稿层不消费,更不作为发送 id。 */
rowModelId?: string;
resetToRecommended?: true;
+ agentDevice?: UnifiedSelectionAgentDevice;
}) => {
if (sessionId || settingsLocked) return;
const targetKind = vendorKeyToAgentKind(selection.engine);
+ // 这一行与当前目录不在同一台电脑(远程 Agent 换落点):记忆按目标目录写 —— 落到本机就写
+ // 本机预设;落到另一台电脑就不写(那台的记忆由它自己的草稿播种接管)。
+ const crossDevice =
+ selection.agentDevice !== undefined &&
+ (selection.agentDevice?.deviceId ?? null) !== agentDeviceId;
+ const targetMemory = crossDevice
+ ? selection.agentDevice === null
+ ? LOCAL_MODEL_MEMORY
+ : undefined
+ : modelMemory;
if (targetKind && selection.providerId && !selection.resetToRecommended) {
if (selection.effort) {
- modelMemory?.setEffort(
+ targetMemory?.setEffort(
targetKind,
selection.providerId,
selection.modelId,
selection.effort,
);
}
- modelMemory?.setFast(targetKind, selection.providerId, selection.modelId, selection.fast);
+ targetMemory?.setFast(targetKind, selection.providerId, selection.modelId, selection.fast);
}
// 乐观来源:草稿没有 SSoT 回流,pill 的来源图标靠这份本地态即时跟上。
setSelectedProviderId(selection.providerId);
@@ -7068,9 +7112,10 @@ export function ChatInput({
fast: selection.fast,
favoriteUid: selection.favoriteUid,
...(selection.resetToRecommended ? { resetToRecommended: true as const } : {}),
+ ...(selection.agentDevice !== undefined ? { agentDevice: selection.agentDevice } : {}),
});
},
- [sessionId, settingsLocked, modelMemory, onUnifiedDraftSelect],
+ [sessionId, settingsLocked, modelMemory, onUnifiedDraftSelect, agentDeviceId],
);
const showModelSwitchFailure = useCallback(
@@ -9075,6 +9120,21 @@ export function ChatInput({
: undefined
}
deviceId={catalogDeviceId}
+ // 远程 Agent(仅本机新任务草稿):面板同时列出其他电脑上的供应商,选中即换 Agent 落点。
+ {...(remoteAgentOptions && unifiedPanelActive && onUnifiedDraftSelect
+ ? { remoteAgent: remoteAgentOptions }
+ : {})}
+ // Agent 在另一台电脑运行(草稿或已建任务):trigger 用带信号波纹的远程 Logo。
+ agentDevice={
+ agentDeviceId
+ ? {
+ deviceId: agentDeviceId,
+ name:
+ remoteAgentDevices?.find((device) => device.deviceId === agentDeviceId)
+ ?.name ?? agentDeviceName,
+ }
+ : null
+ }
// SSH 远程会话隐藏订阅直连模型(chatgpt/ / xai/):bridge 只挂在本地 compat-proxy,
// 远程模式走 remoteEndpoint 不经翻译,选了必失败。
excludeSubscriptionDirect={!!remoteHostId}
diff --git a/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx b/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx
index 6136d2e210..87ba893cf9 100644
--- a/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx
@@ -15,12 +15,9 @@
* 主场景,默认停在某台远程机器有误发风险。
* - 窄屏且有多台时收成图标 + 状态点:pill 排在窄屏会进正常流并 flex-wrap,省掉设备名可以
* 少一次换行。只有一台对端时不收(名字短,信息更重要)。
- * - 「只让 Agent 在那台运行」单独成段(传了 onAgentDeviceChange 才显示):任务、项目文件与命令
- * 留在本机,Agent 用那台的登录、供应商与网络。它和「在那台上创建」是两件事 —— 后者整个任务
- * 都建在那台 —— 所以分段列出、各自写明,选中后 pill 显示「Agent 在 X」。
*/
-import { Check, ChevronDown, Cpu, Laptop } from 'lucide-react';
+import { Check, ChevronDown, Laptop } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -41,10 +38,6 @@ interface Props {
/** 窄屏(pill 排进正常流)时收成图标 + 状态点。 */
compact?: boolean;
disabled?: boolean;
- /** 任务在本机、Agent 在这台电脑上运行;null = Agent 也在本机。 */
- agentDeviceId?: string | null;
- /** 不传 = 不提供「只让 Agent 在其他电脑运行」。 */
- onAgentDeviceChange?: (deviceId: string, deviceName: string | null) => void;
}
/**
@@ -72,8 +65,6 @@ export function DeviceSwitcherPill({
onOpenChange,
compact = false,
disabled = false,
- agentDeviceId = null,
- onAgentDeviceChange,
}: Props) {
const { t } = useTranslation();
@@ -81,18 +72,10 @@ export function DeviceSwitcherPill({
if (devices.length === 0) return null;
const localLabel = t('ccAgent.sidebar.machineSwitcher.localMachine');
- // 任务在本机、Agent 在另一台:pill 显示 Agent 所在的电脑(状态点也跟它走)。
- const agentDevice = value == null && agentDeviceId != null ? agentDeviceId : null;
- const label = agentDevice
- ? t('newChat.deviceSwitcher.agentPill', { device: resolveDeviceLabel(devices, agentDevice, localLabel) })
- : resolveDeviceLabel(devices, value, localLabel);
- const current = agentDevice
- ? devices.find((d) => d.deviceId === agentDevice)
- : value == null
- ? null
- : devices.find((d) => d.deviceId === value);
+ const label = resolveDeviceLabel(devices, value, localLabel);
+ const current = value == null ? null : devices.find((d) => d.deviceId === value);
// 本机不画状态点(它永远在线,画了只是噪音)。
- const showDot = current != null || agentDevice != null;
+ const showDot = current != null;
// 当前值必须进 aria-label:compact 模式下按钮只剩图标 + 状态点、不渲染设备名文本,只报
// 「设备」会让读屏用户完全不知道当前选的是哪台机器(Copilot review)。非 compact 时名字虽然
// 可见,一并读出也不冗余 —— aria-label 会覆盖内文,不会重复播报。
@@ -123,15 +106,11 @@ export function DeviceSwitcherPill({
compact ? 'px-2.5' : 'min-w-20 max-w-[200px] px-3',
)}
>
- {agentDevice ? (
- <Cpu size={12} strokeWidth={2} className="shrink-0 text-[var(--create-agent-control-icon)]" />
- ) : (
- <Laptop
- size={12}
- strokeWidth={2}
- className="shrink-0 text-[var(--create-agent-control-icon)]"
- />
- )}
+ <Laptop
+ size={12}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--create-agent-control-icon)]"
+ />
{showDot && (
<span
aria-hidden
@@ -176,7 +155,7 @@ export function DeviceSwitcherPill({
icon={<Laptop size={20} strokeWidth={2} className="shrink-0 text-[var(--folder-item-icon)]" />}
name={localLabel}
hint={t('newChat.deviceSwitcher.localHint')}
- selected={value == null && agentDevice == null}
+ selected={value == null}
onSelect={() => select(null, null)}
/>
@@ -203,39 +182,6 @@ export function DeviceSwitcherPill({
/>
))}
</div>
-
- {onAgentDeviceChange && (
- <>
- <div className="mx-2 my-1 h-px bg-[var(--folder-picker-border)]" />
- <div className="px-3 py-2">
- <span className="text-xs font-normal text-[var(--folder-label)]">
- {t('newChat.deviceSwitcher.agentSection')}
- </span>
- </div>
- <div className="pending-queue-scroll -mr-2 max-h-[216px] overflow-x-hidden overflow-y-auto overscroll-contain pr-2">
- {devices.map((device) => (
- <DeviceRow
- key={device.deviceId}
- testId="create-agent-agent-device-option"
- icon={<Cpu size={20} strokeWidth={2} className="shrink-0 text-[var(--folder-item-icon)]" />}
- name={device.name}
- hint={
- device.online
- ? t('newChat.deviceSwitcher.agentHint')
- : t('newChat.deviceSwitcher.offlineHint')
- }
- online={device.online}
- disabled={!device.online}
- selected={agentDevice === device.deviceId}
- onSelect={() => {
- onAgentDeviceChange(device.deviceId, device.name);
- onOpenChange(false);
- }}
- />
- ))}
- </div>
- </>
- )}
</PopoverContent>
</Popover>
);
@@ -249,15 +195,14 @@ interface RowProps {
disabled?: boolean;
selected: boolean;
onSelect: () => void;
- testId?: string;
}
-function DeviceRow({ icon, name, hint, online, disabled, selected, onSelect, testId }: RowProps) {
+function DeviceRow({ icon, name, hint, online, disabled, selected, onSelect }: RowProps) {
return (
<button
type="button"
disabled={disabled}
- data-testid={testId ?? 'create-agent-device-option'}
+ data-testid="create-agent-device-option"
onClick={onSelect}
className={cn(
'flex w-full items-center gap-3 rounded-[8px] px-3 py-[10px] text-left',
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index b4093b4fe6..93427da6a8 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -91,6 +91,9 @@ import {
prefetchDeviceProviders,
useDeviceProviders,
} from '@/hooks/useDeviceProviders';
+import { useDevicesProviders } from '@/hooks/useDevicesProviders';
+import { RemoteSourceMark } from '@/components/icons/RemoteSourceMark';
+import { buildUnifiedRail, remoteAgentProviders } from './unifiedModelSelection';
import { modelPriceDiscountLabelValues, modelPriceDetailRows } from '@/lib/modelPriceFormat';
import { resolveModelPricePresentation } from '@/lib/modelPricePresentation';
import {
@@ -634,6 +637,22 @@ export function resolveModelSelectorAgentIdentity(
};
}
+/**
+ * 远程 Agent 的选择入口(只有本机新任务草稿传)。模型面板的左侧栏在本机供应商之后列出
+ * 这些电脑上的供应商;选中那台电脑上的模型 = Agent 在那台电脑运行,任务和文件仍在本机。
+ */
+export interface RemoteAgentSelectorOptions {
+ /** 可以运行 Agent 的其他电脑(已配对、在线)。 */
+ devices: readonly { deviceId: string; name: string }[];
+ /** 草稿当前的 Agent 所在电脑;null = 本机。 */
+ selectedDeviceId: string | null;
+ /** 本机目录的模型记忆。Agent 当前在其他电脑时,浏览本机目录用它显示各行的档位。 */
+ localModelMemory?: ModelMemoryAccessors;
+}
+
+/** 远程 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[];
@@ -702,6 +721,13 @@ interface ModelSelectorProps {
agentIdentity?: ModelSelectorAgentIdentity;
/** device-link 远程会话所属被控端 id;非空 = 列被控端的模型 + 退化为纯列表(不分供应商段)。 */
deviceId?: string;
+ /** 远程 Agent 选择入口(语义见 RemoteAgentSelectorOptions;传了它 deviceId 不再生效)。 */
+ remoteAgent?: RemoteAgentSelectorOptions;
+ /**
+ * 任务的 Agent 在另一台电脑运行:trigger 的来源图标换成带信号波纹的远程供应商 Logo,
+ * 读屏 / 悬停名带上那台电脑。只影响展示。
+ */
+ agentDevice?: { deviceId: string; name: string | null } | null;
/**
* SSH 远程会话(remoteHostId)传 true:隐藏订阅直连模型(chatgpt/ / xai/)——bridge 只挂在
* 本地 compat-proxy,远程模式不经它,选了必失败(见 selectVisibleModels 同名参数)。
@@ -854,6 +880,8 @@ interface ModelSelectorContentProps {
vendorKey?: 'cc' | 'codex' | 'pi';
/** device-link 远程会话所属被控端 id(列被控端模型)。 */
deviceId?: string;
+ /** 远程 Agent 选择入口(语义同 ModelSelectorProps.remoteAgent)。 */
+ remoteAgent?: RemoteAgentSelectorOptions;
/** SSH 远程会话隐藏订阅直连模型(语义同 ModelSelectorProps 同名字段)。 */
excludeSubscriptionDirect?: boolean;
/** SSH 远程会话隐藏 Chat 桥接的 Codex 供应商模型(语义同 ModelSelectorProps 同名字段)。 */
@@ -969,6 +997,11 @@ interface ModelSelectorContentProps {
favoriteUid: string | null;
/** 配置浮层「恢复推荐」的应用动作;调用方应删除 override,不得重新记忆推荐值。 */
resetToRecommended?: true;
+ /**
+ * 只在传了 `remoteAgent` 时出现:这一行属于哪台电脑的目录(null = 本机)。与草稿
+ * 当前的 Agent 所在电脑不同时,调用方要连 Agent 运行位置一起换。
+ */
+ agentDevice?: UnifiedSelectionAgentDevice;
}) => void | boolean | Promise<void | boolean>;
/** 语义同 ModelSelectorProps.reselectEmitsChange(点当前行照常回调)。 */
reselectEmitsChange?: boolean;
@@ -1092,9 +1125,10 @@ function ModelSelectorContentView({
onFastModeChange,
thinkingEnabled = true,
onThinkingChange,
- modelMemory,
+ modelMemory: modelMemoryProp,
vendorKey,
- deviceId,
+ deviceId: deviceIdProp,
+ remoteAgent,
excludeSubscriptionDirect,
excludeChatBridgedCodex,
onDismiss,
@@ -1134,6 +1168,40 @@ function ModelSelectorContentView({
// 当前来源解析器:已建会话 = 实际路由口径(含停用拷贝),其余 = 准入口径。
const resolveCurrentSourceId = actualRoute ? actualSourceIdForModel : effectiveSourceIdForModel;
const { t, i18n } = useTranslation();
+ // ── 远程 Agent:面板在本机目录与其他电脑的目录之间切换浏览 ─────────────────────
+ // 打开时停在草稿当前的落点(Agent 在哪台电脑就先列哪台);左侧栏点到另一台电脑的供应商时,
+ // 下面整套目录(能力 / 供应商 / 可见性 / 用量 / 收藏)都随 deviceId 换成那台电脑的。
+ const remoteAgentDeviceId = remoteAgent?.selectedDeviceId ?? null;
+ const [remoteBrowse, setRemoteBrowse] = useState<{
+ deviceId: string;
+ /** null = 还不知道该落在哪个供应商格(等那台的目录到了再按当前来源 / 首个供应商定)。 */
+ providerId: string | null;
+ } | null>(() =>
+ remoteAgentDeviceId ? { deviceId: remoteAgentDeviceId, providerId: currentProviderId ?? null } : null,
+ );
+ // 落点在面板之外变了(那台电脑被解除配对而回到本机等):跟到新落点,不停在旧目录上。
+ const lastRemoteAgentDeviceIdRef = useRef(remoteAgentDeviceId);
+ useEffect(() => {
+ if (lastRemoteAgentDeviceIdRef.current === remoteAgentDeviceId) return;
+ lastRemoteAgentDeviceIdRef.current = remoteAgentDeviceId;
+ setRemoteBrowse((current) =>
+ (current?.deviceId ?? null) === remoteAgentDeviceId
+ ? current
+ : remoteAgentDeviceId
+ ? { deviceId: remoteAgentDeviceId, providerId: null }
+ : null,
+ );
+ }, [remoteAgentDeviceId]);
+ const deviceId = remoteAgent ? remoteBrowse?.deviceId : deviceIdProp;
+ /** 正在浏览的就是草稿当前落点的目录 —— 选中态、档位记忆与引擎集合只对它成立。 */
+ const browsingSelectedCatalog =
+ !remoteAgent || (remoteBrowse?.deviceId ?? null) === remoteAgentDeviceId;
+ const modelMemory =
+ !remoteAgent || browsingSelectedCatalog
+ ? modelMemoryProp
+ : remoteBrowse
+ ? undefined
+ : remoteAgent.localModelMemory;
// 列表样式试用开关(本机偏好):footer 的切换按钮 + 面板行样式共用。
const constrainedListMaxHeight = modelListMaxHeightForRows(maxVisibleModelRows);
const [paneElement, setPaneElement] = useState<HTMLDivElement | null>(null);
@@ -1187,7 +1255,8 @@ function ModelSelectorContentView({
? vendorKeyToAgentKind(browseVendor)
: vendorKeyToAgentKind(vendorKey);
// A field that only persists a model must not offer another Harness.
- const unifiedAgents = requestedUnifiedAgents ??
+ // 调用方给的引擎集合是**草稿当前落点**那台电脑上已注册的;浏览另一台时不套用(fail-open)。
+ const unifiedAgents = (browsingSelectedCatalog ? requestedUnifiedAgents : undefined) ??
(vendorKey && agentKind && !onUnifiedSelect && !sessionEngineFilter ? [agentKind] : undefined);
const browseTargetLabel =
browseVendor === 'codex' ? 'Codex' : browseVendor === 'pi' ? 'Pi' : 'Claude Code';
@@ -1213,7 +1282,16 @@ function ModelSelectorContentView({
// (useDeviceProviders,隧道 maker:provider:list)。两 hook 都无条件调用(hooks 规则),按 deviceId 取。
const localProviders = useProviders();
const remoteProviders = useDeviceProviders(deviceId);
- const providers = deviceId ? remoteProviders.providers : providersOverride ?? localProviders.providers;
+ // 远程 Agent 只能用那台电脑「允许被远程调用」的供应商(远程控制照常列全部)。
+ const remoteAgentBrowsing = remoteAgent !== undefined && !!deviceId;
+ const remoteCatalogProviders = useMemo(
+ () =>
+ remoteAgentBrowsing
+ ? remoteAgentProviders(remoteProviders.providers)
+ : remoteProviders.providers,
+ [remoteAgentBrowsing, remoteProviders.providers],
+ );
+ const providers = deviceId ? remoteCatalogProviders : providersOverride ?? localProviders.providers;
// 订阅用量跟随目录归属:本机目录读本机账号,远程目录读被控端镜像(与会话用量 chip 共用缓存);
// 外部注入的目录(providersOverride)归属不明,不显示任何账号用量。
const providerUsageScope = useMemo<ProviderUsageScope | null>(
@@ -1393,6 +1471,68 @@ function ModelSelectorContentView({
const unifiedScope: 'draft' | 'session' = actualRoute ? 'session' : 'draft';
const unifiedAgentsKey = unifiedAgents ? unifiedAgents.join(',') : 'all';
+ // ── 远程 Agent 的左侧栏数据 ──────────────────────────────────────────────────
+ // 栏位要同时列出本机与各台电脑的供应商,而列表此刻只装着其中一份目录:本机格与远程格
+ // 各自按**自己的**目录与可见性派生,不借用正在浏览的那一份。
+ const remoteAgentDevices = remoteAgent?.devices;
+ const remoteAgentDeviceIds = useMemo(
+ () => (remoteAgentDevices ?? []).map((device) => device.deviceId),
+ [remoteAgentDevices],
+ );
+ const remoteDeviceCatalogs = useDevicesProviders(remoteAgentDeviceIds);
+ const remoteAgentGroups = useMemo(() => {
+ if (!remoteAgentDevices) return [];
+ return remoteAgentDevices.flatMap((device) => {
+ const catalog = remoteDeviceCatalogs.get(device.deviceId);
+ // 只列那台电脑开了「允许被远程调用」的供应商;一个都没开的电脑整段不出现。
+ const shared = catalog ? remoteAgentProviders(catalog.providers) : [];
+ if (!catalog || shared.length === 0) return [];
+ const entries = unifiedModelEntries({
+ providers: shared,
+ isVisible: (providerId, model, agent) =>
+ isDeviceModelVisible(catalog.modelVisibilityOverrides, agent, providerId, model),
+ includePaymentRequired: true,
+ scope: 'draft',
+ });
+ const providerIds = [...new Set(entries.map((entry) => entry.providerId))];
+ return providerIds.length > 0
+ ? [{ deviceId: device.deviceId, providers: shared, providerIds }]
+ : [];
+ });
+ }, [remoteAgentDevices, remoteDeviceCatalogs]);
+ const hasRemoteAgent = remoteAgent !== undefined;
+ const remoteAgentLocalRailItems = useMemo(() => {
+ if (!hasRemoteAgent) return undefined;
+ void visibilityVersion;
+ const entries = unifiedModelEntries({
+ providers: localProviders.providers,
+ isVisible: (providerId, model, agent) => isModelEnabled(agent, providerId, model),
+ includePaymentRequired: true,
+ scope: 'draft',
+ });
+ return buildUnifiedRail(entries, undefined, localProviders.providerOrder);
+ }, [hasRemoteAgent, localProviders.providers, localProviders.providerOrder, visibilityVersion]);
+ const remoteAgentLocalLabel = useCallback(
+ (providerId: string): string => {
+ const provider = localProviders.providers.find((entry) => entry.id === providerId);
+ return provider ? providerDisplayName(provider, t) : providerId;
+ },
+ [localProviders.providers, t],
+ );
+ const remoteAgentLabelOf = useCallback(
+ (targetDeviceId: string, providerId: string): string => {
+ const device = remoteAgentDevices?.find((entry) => entry.deviceId === targetDeviceId);
+ const provider = remoteAgentGroups
+ .find((group) => group.deviceId === targetDeviceId)
+ ?.providers.find((entry) => entry.id === providerId);
+ return t('newChat.modelSelector.unified.railRemoteProvider', {
+ provider: provider ? providerDisplayName(provider, t) : providerId,
+ device: device?.name || targetDeviceId,
+ });
+ },
+ [remoteAgentDevices, remoteAgentGroups, t],
+ );
+
// 官方默认推荐 → 一次性**种子收藏**(Chris 2026-08-16 裁决,替代列表里的「默认」
// 小节):服务端目录用 `newSessionDefault` 标记推荐模型(gateway 下发),首个命中
// 项以收藏形态投放。只投一次、取消不复种、已有收藏的用户不打扰 —— 这三条都由
@@ -2871,6 +3011,29 @@ function ModelSelectorContentView({
if (unifiedPanel) {
// 可见性 / 排除谓词与 scope 一律从组件作用域取(见 unifiedIsVisible 的定义处):
// 种子收藏 effect 用的是同一份,两边不能各写一遍。
+ //
+ // 远程 Agent:正在浏览的远程供应商格。打开时只知道落点电脑,供应商格按当前来源 /
+ // 那台的首个供应商补齐;那台的目录到齐之前列表只显示加载态。
+ const remoteActiveProviderId = remoteBrowse
+ ? (remoteBrowse.providerId ??
+ (browsingSelectedCatalog ? activeSourceId : null) ??
+ remoteAgentGroups.find((group) => group.deviceId === remoteBrowse.deviceId)?.providerIds[0] ??
+ null)
+ : null;
+ const remoteBrowseDevice: UnifiedSelectionAgentDevice = remoteBrowse
+ ? {
+ deviceId: remoteBrowse.deviceId,
+ name:
+ remoteAgentDevices?.find((device) => device.deviceId === remoteBrowse.deviceId)?.name ||
+ remoteBrowse.deviceId,
+ }
+ : null;
+ // 选中直通带上这一行属于哪台电脑(仅远程 Agent 入口);落点不同由调用方连运行位置一起换。
+ const withAgentDevice = remoteAgent ? { agentDevice: remoteBrowseDevice } : {};
+ // 浏览的不是草稿当前落点的目录时,没有任何一行是「正在用的那一行」。
+ const panelSelection = browsingSelectedCatalog
+ ? { providerId: activeSourceId, modelId }
+ : { providerId: null, modelId: '' };
return (
// 外层多包一层「百分比钳制」:面板列自身的 max-h 公式(560px/100vh)不知道宿主
// popover 实际给了多少纵向空间 —— morph 弹层按锚点位置算出的可用高度可能更小,
@@ -2943,15 +3106,56 @@ function ModelSelectorContentView({
query={query}
// field 形态的面板宽度绑 trigger,定宽 sizer 无用武之地(见该 prop 说明)。
panelWidthFluid={fluidWidth}
- selected={{ providerId: activeSourceId, modelId }}
- selectedFavoriteUid={selectedFavoriteUid}
- liveAgentKind={unifiedSelectionPolicy === 'official' ? null : currentAgentKind}
- fastMode={unifiedSelectionPolicy === 'official' ? false : fastMode}
- selectedEffort={unifiedSelectionPolicy === 'official' ? undefined : effort}
+ selected={panelSelection}
+ selectedFavoriteUid={browsingSelectedCatalog ? selectedFavoriteUid : null}
+ liveAgentKind={
+ unifiedSelectionPolicy === 'official' || !browsingSelectedCatalog ? null : currentAgentKind
+ }
+ fastMode={unifiedSelectionPolicy === 'official' || !browsingSelectedCatalog ? false : fastMode}
+ selectedEffort={
+ unifiedSelectionPolicy === 'official' || !browsingSelectedCatalog ? undefined : effort
+ }
{...(modelMemory ? { modelMemory } : {})}
+ {...(remoteAgent && remoteAgentLocalRailItems
+ ? {
+ remoteSources: {
+ localRailItems: remoteAgentLocalRailItems,
+ localProviders: localProviders.providers,
+ localProviderLabel: remoteAgentLocalLabel,
+ groups: remoteAgentGroups,
+ labelOf: remoteAgentLabelOf,
+ active: remoteBrowse
+ ? { deviceId: remoteBrowse.deviceId, providerId: remoteActiveProviderId ?? '' }
+ : null,
+ ready:
+ remoteBrowse === null ||
+ (remoteModelListStatus === 'ready' && remoteActiveProviderId !== null),
+ ...(remoteBrowse && remoteModelListStatus === 'error'
+ ? {
+ failure: (
+ <RemoteModelLoadNotice
+ status="error"
+ onRetry={retryRemoteModels}
+ compact
+ />
+ ),
+ }
+ : {}),
+ onActivate: (target: { deviceId: string; providerId: string } | null) => {
+ closeOptionsPanel();
+ setRemoteBrowse(target);
+ },
+ },
+ }
+ : {})}
agentFastModeCapable={unifiedAgentFastCapable}
priceOf={(providerId, id, agent) => pricePresentationOf(providerId, id, agent)}
- providerLabel={unifiedProviderLabel}
+ // 浏览其他电脑的目录时,分组标题带上电脑名(「Claude 订阅 · 工作室 Mac」)。
+ providerLabel={
+ remoteBrowse
+ ? (providerId: string) => remoteAgentLabelOf(remoteBrowse.deviceId, providerId)
+ : unifiedProviderLabel
+ }
effortLabelOf={unifiedEffortLabel}
{...(constrainedListMaxHeight !== undefined
? { listMaxHeight: constrainedListMaxHeight }
@@ -2990,6 +3194,7 @@ function ModelSelectorContentView({
...(rowConfig.resetToRecommended
? { resetToRecommended: true as const }
: {}),
+ ...withAgentDevice,
}),
).then((applied) => {
if (applied) {
@@ -3021,6 +3226,7 @@ function ModelSelectorContentView({
fast: rowConfig.fast,
favoriteUid: rowConfig.favoriteUid,
...(rowConfig.resetToRecommended ? { resetToRecommended: true as const } : {}),
+ ...withAgentDevice,
});
}
return applyUnifiedSessionSelect({
@@ -3046,6 +3252,7 @@ function ModelSelectorContentView({
engine: rowConfig.engine,
fast: rowConfig.fast,
favoriteUid: null,
+ ...withAgentDevice,
});
}
onSessionFavoriteAnchorChange?.(null);
@@ -3293,6 +3500,8 @@ export function ModelSelector({
vendorKey,
agentIdentity,
deviceId,
+ remoteAgent,
+ agentDevice = null,
excludeSubscriptionDirect,
excludeChatBridgedCodex,
switching = false,
@@ -3726,11 +3935,19 @@ export function ModelSelector({
next: describeSelection({ agentKind: currentAgentKind, model: modelId, providerId: currentProviderId ?? null, effort: showEffort ? effort : null, fastMode: triggerFastOn }),
})
: null;
- const triggerTitle = pendingSelectionTitle
+ // Agent 在另一台电脑运行:图标上的信号波纹之外,悬停 / 读屏也要说出是哪台。
+ const agentDeviceLabel = agentDevice
+ ? agentDevice.name
+ ? t('newChat.modelSelector.trigger.agentDevice', { device: agentDevice.name })
+ : t('newChat.modelSelector.trigger.agentDeviceUnnamed')
+ : null;
+ const withAgentDeviceLabel = (label: string): string =>
+ agentDeviceLabel ? `${label} · ${agentDeviceLabel}` : label;
+ const triggerTitle = withAgentDeviceLabel(pendingSelectionTitle
? `${pendingSelectionTitle}${showSourceDisconnected ? ` · ${sourceIssueLabel}` : ''}`
- : showSourceDisconnected ? baseAriaLabel : displayIdentityLabel;
+ : showSourceDisconnected ? baseAriaLabel : displayIdentityLabel);
// 多实例同屏(IM 目录偏好)时前置「字段名 · 行别名」,读屏才能区分行与行。
- const accessibleLabel = pendingSelectionTitle ? triggerTitle : baseAriaLabel;
+ const accessibleLabel = pendingSelectionTitle ? triggerTitle : withAgentDeviceLabel(baseAriaLabel);
const ariaLabel = ariaContext ? `${ariaContext}:${accessibleLabel}` : accessibleLabel;
const isBudget = modelId.startsWith('codex/');
const isFieldTrigger = triggerVariant === 'field';
@@ -3935,7 +4152,28 @@ export function ModelSelector({
)}
{/* 图标统一规则:模型条目 icon(AI Gateway / 目录设定)优先、缺省回落
当前真正路由的来源标(activeSourceId)——客户端不按 model id 猜厂牌。 */}
- {activeSourceId ? (
+ {activeSourceId && agentDevice ? (
+ // Agent 在另一台电脑:同一个图标位换成带信号波纹的远程供应商 Logo。
+ <RemoteSourceMark
+ size={17}
+ className={cn(
+ 'mr-1.5',
+ isCreateAgentVariant
+ ? 'text-[var(--create-agent-control-icon)]'
+ : 'text-[var(--model-trigger-text)]',
+ )}
+ >
+ <ModelIconMark
+ icon={triggerModelIcon}
+ providerId={activeSourceId}
+ name={triggerActiveProvider?.name}
+ routing={triggerActiveProvider?.routing}
+ logoKind={triggerActiveProvider?.logoKind}
+ colorClass="text-current"
+ withMargin={false}
+ />
+ </RemoteSourceMark>
+ ) : activeSourceId ? (
<ModelIconMark
icon={triggerModelIcon}
providerId={activeSourceId}
@@ -4083,6 +4321,7 @@ export function ModelSelector({
modelMemory={modelMemory}
vendorKey={vendorKey}
deviceId={deviceId}
+ {...(remoteAgent ? { remoteAgent } : {})}
excludeSubscriptionDirect={excludeSubscriptionDirect}
excludeChatBridgedCodex={excludeChatBridgedCodex}
onDismiss={() => setOpenWithoutAutoRefresh(false)}
diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx
index f793729931..98e452deb9 100644
--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx
@@ -1,7 +1,7 @@
import { useRemoteModelFavorites } from '@/state/useRemoteModelFavorites';
import { matchesModelName } from '@/lib/modelDisplayNames';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Check, TriangleAlert } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
+import { Check, Loader2, TriangleAlert } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import {
@@ -58,6 +58,7 @@ import {
type UnifiedAnchor,
type UnifiedEngine,
type UnifiedRailFilter,
+ type UnifiedRailItem,
type UnifiedRowConfig,
} from './unifiedModelSelection';
@@ -247,6 +248,34 @@ export interface UnifiedModelPanelProps {
/** 面板容器元素(浮层按它的左 / 右外侧定位)。 */
panelElement: HTMLElement | null;
overlayClassName?: string;
+ /**
+ * 远程 Agent(仅新任务草稿):左侧栏在本机供应商之后列出其他电脑上的供应商。选中那台
+ * 电脑上的模型 = Agent 在那台电脑运行,任务和文件仍在本机。
+ *
+ * 面板只管栏位与选中态;列表数据(`providers` / `deviceId` 及各谓词)由调用方随
+ * `active` 切到那台电脑的目录 —— 所以 `ready` 为 false 的那几帧列表显示加载态,
+ * 绝不拿上一份目录按同名供应商筛出一份「看起来像远程」的列表。
+ */
+ remoteSources?: {
+ /** 本机格(★ / 全部 / 本机供应商)的栏位,按**本机**目录派生。 */
+ localRailItems: readonly UnifiedRailItem[];
+ localProviders: readonly ProviderView[];
+ localProviderLabel: (providerId: string) => string;
+ /** 每台电脑一段:有可用模型的供应商(按那台的目录顺序)。 */
+ groups: readonly {
+ deviceId: string;
+ providers: readonly ProviderView[];
+ providerIds: readonly string[];
+ }[];
+ labelOf: (deviceId: string, providerId: string) => string;
+ /** 正在浏览的远程供应商;null = 正在浏览本机目录。 */
+ active: { deviceId: string; providerId: string } | null;
+ /** 列表数据是否已经是 `active` 那台电脑的目录。 */
+ ready: boolean;
+ /** `active` 那台的目录读取失败时,列表区显示的提示(含重试)。 */
+ failure?: ReactNode;
+ onActivate: (target: { deviceId: string; providerId: string } | null) => void;
+ };
/**
* 面板宽度是**绑在 trigger 上**的(field 形态,DESIGN.md §4 宽度铁则)。
* 传 true 时关掉定宽 sizer —— 宽度由外部决定,量一份最宽视图既无用也白渲染一遍行
@@ -309,6 +338,7 @@ export function UnifiedModelPanel({
panelElement,
overlayClassName,
panelWidthFluid = false,
+ remoteSources,
}: UnifiedModelPanelProps) {
const { t } = useTranslation();
const storedFavorites = useModelFavorites();
@@ -401,17 +431,53 @@ export function UnifiedModelPanel({
[providers, agentsKey, scope, sourceVersion, keepModelKey, includePaymentRequired],
);
- const railItems = useMemo(
- () => buildUnifiedRail(entries, undefined, providerOrder),
- [entries, providerOrder],
- );
+ const localRailItems = remoteSources?.localRailItems;
+ const remoteGroups = remoteSources?.groups;
+ const railItems = useMemo<UnifiedRailItem[]>(() => {
+ if (!localRailItems) return buildUnifiedRail(entries, undefined, providerOrder);
+ // 远程 Agent:本机格按本机目录派生(此刻 entries 可能是某台电脑的目录),
+ // 其后每台电脑一段远程供应商格。
+ return [
+ ...localRailItems,
+ ...(remoteGroups ?? []).flatMap((group) =>
+ group.providerIds.map((providerId) => ({
+ kind: 'remote-provider' as const,
+ deviceId: group.deviceId,
+ providerId,
+ })),
+ ),
+ ];
+ }, [entries, providerOrder, localRailItems, remoteGroups]);
// rail 上的筛选目标消失(供应商断开 / 收藏清空)时回落「全部」,避免停在空视图。
useEffect(() => {
if (rail.kind === 'all') return;
if (railItems.some((item) => railItemKey(item) === railItemKey(rail))) return;
setRail({ kind: 'all' });
}, [rail, railItems]);
- const effectiveRail = query.trim() ? RAIL_ALL : rail;
+ // 远程供应商格由调用方受控(它决定列表数据是哪台电脑的目录);本机格仍由面板自己记。
+ const remoteActiveDeviceId = remoteSources?.active?.deviceId ?? null;
+ const remoteActiveProviderId = remoteSources?.active?.providerId ?? null;
+ const remoteRail = useMemo<UnifiedRailFilter | null>(
+ () =>
+ remoteActiveDeviceId !== null && remoteActiveProviderId !== null
+ ? { kind: 'remote-provider', deviceId: remoteActiveDeviceId, providerId: remoteActiveProviderId }
+ : null,
+ [remoteActiveDeviceId, remoteActiveProviderId],
+ );
+ const effectiveRail = remoteRail ?? (query.trim() ? RAIL_ALL : rail);
+ // 切到另一台电脑的途中(或读取失败)列表数据还不是那台的目录:列表区只显示状态,不出行。
+ const remoteListPending = remoteRail !== null && !remoteSources?.ready;
+ const handleRailSelect = useCallback(
+ (item: UnifiedRailItem) => {
+ if (item.kind === 'remote-provider') {
+ remoteSources?.onActivate({ deviceId: item.deviceId, providerId: item.providerId });
+ return;
+ }
+ if (remoteSources?.active) remoteSources.onActivate(null);
+ setRail(item);
+ },
+ [remoteSources],
+ );
// ── 行配置合成 ────────────────────────────────────────────────────────────
// 「正在用的引擎」的口径 = 上面推 keepModel 时用的那一个(liveEngineAgent),不另起一份。
@@ -983,10 +1049,21 @@ export function UnifiedModelPanel({
providerUsage={providerUsage}
items={railItems}
active={effectiveRail}
- onSelect={setRail}
+ onSelect={handleRailSelect}
providers={providers}
providerLabel={providerLabel}
interactionDisabled={interactionDisabled || actionPending}
+ {...(remoteSources
+ ? {
+ remoteSources: {
+ localProviders: remoteSources.localProviders,
+ localProviderLabel: remoteSources.localProviderLabel,
+ providersOf: (deviceId: string) =>
+ remoteSources.groups.find((group) => group.deviceId === deviceId)?.providers ?? [],
+ labelOf: remoteSources.labelOf,
+ },
+ }
+ : {})}
/>
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
@@ -1071,7 +1148,17 @@ export function UnifiedModelPanel({
</div>
)}
{deviceId && remoteFavorites.error ? <div role="status" className="px-3 py-2 text-13 text-[var(--text-secondary)]">{t('newChat.modelSelector.unified.favoritesSyncFailed')}</div> : null}
- {!hasRows ? (
+ {remoteListPending ? (
+ remoteSources?.failure ?? (
+ <div
+ role="status"
+ className="flex items-center justify-center gap-1.5 px-3 py-6 text-13 text-[var(--text-tertiary)]"
+ >
+ <Loader2 size={13} className="shrink-0 animate-spinner motion-reduce:animate-none" />
+ {t('newChat.modelSelector.unified.remoteLoading')}
+ </div>
+ )
+ ) : !hasRows ? (
<div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
{/* ★ 视图的空态是引导语,不是「没有匹配」(设计稿 favEmpty;★ 常驻后必经)。 */}
{effectiveRail.kind === 'favorites' && !query.trim()
diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx
index 463b584c61..0e83b9ab87 100644
--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx
@@ -12,6 +12,7 @@ import { useProviderWeeklyQuota, type ProviderUsageScope } from './useProviderWe
import { formatQuotaResetCountdown } from '../status/usageCardModel';
import { agentOptionOf } from './agentOptions';
import { ProviderRailMark } from './UnifiedFlyoutHost';
+import { RemoteSourceMark } from '@/components/icons/RemoteSourceMark';
import {
engineOfAgentKind,
railItemKey,
@@ -23,7 +24,8 @@ import {
* UnifiedModelRail —— 统一面板左侧的视图筛选栏(model-selector-unified §1.2 / §1.6)。
*
* 格位由数据派生(见 `buildUnifiedRail`),这里只负责画:
- * ★收藏 → 同引擎(仅会话内,图标 = 当前会话引擎的品牌 mark)→ ──分隔── → 全部 → 各来源。
+ * ★收藏 → 同引擎(仅会话内,图标 = 当前会话引擎的品牌 mark)→ ──分隔── → 全部 → 各来源
+ * → (新任务草稿)──分隔── → 其他电脑上的供应商(带信号波纹的 Logo,每台电脑一段)。
* rail 常驻(2026-08-13 裁决),分隔线与设计稿 .rail-sep 同构:「个人钉的」与
* 「目录本身的视图」两段之间画一条 22px 细线。
*/
@@ -35,6 +37,7 @@ export function UnifiedModelRail({
providerLabel,
interactionDisabled = false,
providerUsage = null,
+ remoteSources,
}: {
items: readonly UnifiedRailItem[];
active: UnifiedRailFilter;
@@ -44,6 +47,16 @@ export function UnifiedModelRail({
interactionDisabled?: boolean;
/** Whose account usage the directory may show; null hides it. */
providerUsage?: ProviderUsageScope | null;
+ /**
+ * 远程供应商格的数据(只有可选远程 Agent 的新任务草稿传)。传了它,本机供应商格的
+ * 图标 / 名字 / 用量一律按本机读 —— 面板此刻可能正列着某台电脑的目录。
+ */
+ remoteSources?: {
+ localProviders: readonly ProviderView[];
+ localProviderLabel: (providerId: string) => string;
+ providersOf: (deviceId: string) => readonly ProviderView[];
+ labelOf: (deviceId: string, providerId: string) => string;
+ };
}) {
const { t } = useTranslation();
// rail 常驻,不做「项数少就整条隐藏」——设计稿的分类栏在单来源时也在(★/全部/来源),
@@ -53,17 +66,33 @@ export function UnifiedModelRail({
// 设计稿 .rail:宽 48(含 6px 侧距 + 1px 右分隔线)、纵向 8px、格间 2px。
// 与侧栏窄图标栏一致:滚动条不占宽度,避免挤压按钮并触发横向溢出。
<div className="flex min-h-0 w-12 shrink-0 flex-col items-center gap-0.5 overflow-x-hidden overflow-y-auto scrollbar-hide border-r border-[var(--model-dropdown-border)] px-1.5 py-2">
- {items.map((item) => {
+ {items.map((item, index) => {
const key = railItemKey(item);
const isActive = activeKey === key;
- // 设计稿 .rail-sep:「★/同引擎」与「全部/来源」两段之间的 22px 细线。
- const separatorBefore = item.kind === 'all';
+ // 设计稿 .rail-sep:「★/同引擎」与「全部/来源」两段之间的 22px 细线;
+ // 远程供应商每台电脑一段,段首同样一条细线。
+ const previous = index > 0 ? items[index - 1] : undefined;
+ const separatorBefore =
+ item.kind === 'all' ||
+ (item.kind === 'remote-provider' &&
+ (previous?.kind !== 'remote-provider' || previous.deviceId !== item.deviceId));
const engineOption =
item.kind === 'engine' ? agentOptionOf(engineOfAgentKind(item.agent)) : null;
+ const railProviders =
+ item.kind === 'remote-provider'
+ ? (remoteSources?.providersOf(item.deviceId) ?? [])
+ : (remoteSources?.localProviders ?? providers);
const provider =
- item.kind === 'provider'
- ? providers.find((entry) => entry.id === item.providerId)
+ item.kind === 'provider' || item.kind === 'remote-provider'
+ ? railProviders.find((entry) => entry.id === item.providerId)
: undefined;
+ // 用量跟随该格目录的归属:远程格读那台电脑的镜像,本机格在远程 Agent 模式下恒读本机。
+ const usageDeviceId =
+ item.kind === 'remote-provider'
+ ? item.deviceId
+ : remoteSources
+ ? null
+ : (providerUsage?.deviceId ?? null);
const accountIdentity =
provider?.openAiAccount?.identity?.trim() ||
provider?.subscriptionAccount?.identity?.trim();
@@ -76,7 +105,9 @@ export function UnifiedModelRail({
})
: item.kind === 'all'
? t('newChat.modelSelector.unified.railAll')
- : providerLabel(item.providerId);
+ : item.kind === 'remote-provider'
+ ? (remoteSources?.labelOf(item.deviceId, item.providerId) ?? item.providerId)
+ : (remoteSources?.localProviderLabel ?? providerLabel)(item.providerId);
return (
<div key={key} className="contents">
{separatorBefore && (
@@ -93,7 +124,7 @@ export function UnifiedModelRail({
onClick={() => onSelect(item)}
disabled={interactionDisabled}
provider={providerUsage ? provider : undefined}
- usageDeviceId={providerUsage?.deviceId ?? null}
+ usageDeviceId={usageDeviceId}
>
{item.kind === 'favorites' ? (
// ☆ 未激活与其它格同灰(hover 提亮)—— 常亮金色会在没进收藏视图时也
@@ -106,7 +137,11 @@ export function UnifiedModelRail({
) : item.kind === 'all' ? (
<LayoutGrid size={16} />
) : item.kind === 'provider' ? (
- <ProviderRailMark providerId={item.providerId} providers={providers} />
+ <ProviderRailMark providerId={item.providerId} providers={railProviders} />
+ ) : item.kind === 'remote-provider' ? (
+ <RemoteSourceMark size={20}>
+ <ProviderRailMark providerId={item.providerId} providers={railProviders} />
+ </RemoteSourceMark>
) : null}
</RailButton>
</div>
diff --git a/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts b/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts
index 9c8d04fd63..2925e5600c 100644
--- a/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts
+++ b/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts
@@ -17,7 +17,7 @@
* (i18n `effortLevels.*`),绝不把翻译过的文案回灌进配置。
*/
-import type { UnifiedAgentCapability, UnifiedModelEntry } from '@cindy/model-providers';
+import type { ProviderView, UnifiedAgentCapability, UnifiedModelEntry } from '@cindy/model-providers';
import type { AgentKind } from '@/hooks/useAgentCapabilities';
import type { SelectableVendor } from '@/lib/agentVendors';
@@ -310,12 +310,32 @@ export type UnifiedRailItem =
| { kind: 'favorites' }
| { kind: 'engine'; agent: AgentKind }
| { kind: 'all' }
- | { kind: 'provider'; providerId: string };
+ | { kind: 'provider'; providerId: string }
+ /**
+ * 另一台电脑上的供应商(远程 Agent)。选它 = 列那台电脑这个供应商的模型;选中模型后
+ * Agent 在那台电脑运行。只在新任务草稿出现;列表数据由面板调用方切到那台电脑的目录,
+ * 所以在列表筛选上它与 `provider` 格等价。
+ */
+ | { kind: 'remote-provider'; deviceId: string; providerId: string };
export type UnifiedRailFilter = UnifiedRailItem;
+/**
+ * 远程 Agent 只能用那台电脑开了「允许被远程调用」的供应商。没有该标记(旧数据)按未开放处理;
+ * 远程控制那台电脑时照常列全部,不经过这里。
+ */
+export function remoteAgentProviders(providers: readonly ProviderView[]): ProviderView[] {
+ return providers.filter((provider) => provider.remoteInvocationEnabled === true);
+}
+
+/** 该格按哪个供应商筛选(本机或远程供应商格);其余格不按供应商筛。 */
+export function railProviderFilterId(item: UnifiedRailItem): string | null {
+ return item.kind === 'provider' || item.kind === 'remote-provider' ? item.providerId : null;
+}
+
export function railItemKey(item: UnifiedRailItem): string {
if (item.kind === 'provider') return `provider:${item.providerId}`;
+ if (item.kind === 'remote-provider') return `remote:${item.deviceId}:${item.providerId}`;
if (item.kind === 'engine') return `engine:${item.agent}`;
return item.kind;
}
@@ -518,7 +538,8 @@ export function buildUnifiedListSections(args: {
// 收藏指向的模型已不可路由(来源断开 / 目录下架)→ 本轮不显示;**不删条目**:
// 连回来就该回来,静默删掉用户存过的配置是不可逆的。
if (!entry) continue;
- if (rail.kind === 'provider' && entry.providerId !== rail.providerId) continue;
+ const railProviderId = railProviderFilterId(rail);
+ if (railProviderId !== null && entry.providerId !== railProviderId) continue;
// 同引擎视图:收藏按**解析后的生效引擎**过滤。收藏是配置快照,不是模型本体 ——
// 只列点下去仍停在当前引擎的副本。判据只有这一个,不再先按条目自存的 item.agent
// 硬排除(2026-08-19 review P2):两者在「条目引擎掉出候选」时会分叉 ——
@@ -554,10 +575,11 @@ export function buildUnifiedListSections(args: {
// 同引擎视图的准入只有一条:候选里有当前引擎。生效引擎是排序优先级,不是隐藏条件
// (Chris 2026-08-23 纠正 08-19「不显示」裁决):默认 / 用户选过本引擎的在前,其余兼容
// 行在后。不把兼容行转换成当前引擎 —— 点下去仍按其落点走,落点在别处就走跨引擎确认。
+ const groupProviderId = railProviderFilterId(rail);
const visible = entries.filter(
(entry) =>
matches(entry, q) &&
- (rail.kind !== 'provider' || entry.providerId === rail.providerId) &&
+ (groupProviderId === null || entry.providerId === groupProviderId) &&
(rail.kind !== 'engine' || entry.candidates.includes(rail.agent)),
);
const promoted = new Set<UnifiedModelEntry>();
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 2ef0a4384d..324f0ac9f5 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -47,6 +47,7 @@ import { useClaudeAccountUsageResult } from '@/hooks/useClaudeAccountUsage';
import { useXdAssetPrimaryAction } from '@/hooks/useXdAssetPrimaryAction';
import { useReducedMotion } from '@/hooks/useReducedMotion';
import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
import { Tip } from '@/components/ui/tooltip';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { useSignInToCindy } from '@/hooks/useSignInToCindy';
@@ -138,6 +139,71 @@ function writeProviderDisabled(providerId: string, disabled: boolean, errorText:
.catch(() => toast.error(errorText));
}
+/**
+ * 「允许被远程调用」(供应商级远程 Agent 授权)。默认关闭;只在本机允许远程控制时出现,
+ * 由调用方判定。成功后 main 广播 PROVIDER_CHANGED 刷新快照。
+ */
+function RemoteProviderAccessRow({ provider }: { provider: ProviderView }) {
+ const { t } = useTranslation();
+ const [enabled, setEnabled] = useState(provider.remoteInvocationEnabled === true);
+ const [busy, setBusy] = useState(false);
+ useEffect(() => {
+ setEnabled(provider.remoteInvocationEnabled === true);
+ }, [provider.remoteInvocationEnabled]);
+ return (
+ <div
+ data-testid="provider-remote-access"
+ className="flex shrink-0 items-start justify-between gap-3 border-t px-5 py-3"
+ style={{ borderColor: 'var(--settings-theme-card-border)' }}
+ >
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="text-13 font-medium text-[var(--text-primary)]">
+ {t('settings.providers.detail.remoteAccess.label')}
+ </span>
+ <span className="text-12 leading-[1.4] text-[var(--text-tertiary)]">
+ {t('settings.providers.detail.remoteAccess.description')}
+ </span>
+ </div>
+ <Switch
+ checked={enabled}
+ disabled={busy}
+ aria-label={t('settings.providers.detail.remoteAccess.ariaLabel')}
+ onCheckedChange={(next) => {
+ const previous = enabled;
+ setEnabled(next);
+ setBusy(true);
+ void window.electronAPI.maker
+ .setProviderRemoteAccess({ providerId: provider.id, enabled: next })
+ .catch(() => {
+ setEnabled(previous);
+ toast.error(t('settings.providers.detail.remoteAccess.writeFailed'));
+ })
+ .finally(() => setBusy(false));
+ }}
+ />
+ </div>
+ );
+}
+
+/** 本机是否允许同账号设备远程控制。「允许被远程调用」只在它打开时有意义。 */
+function useRemoteControlEnabled(): boolean {
+ const [enabled, setEnabled] = useState(false);
+ useEffect(() => {
+ let cancelled = false;
+ // 读不到(设备互联未就绪等)按未开启处理:开关不出现,不影响供应商页其余部分。
+ void Promise.resolve()
+ .then(() => window.electronAPI.deviceLink.getState())
+ .then((state) => {
+ if (!cancelled) setEnabled(state.remoteControlEnabled);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ return enabled;
+}
+
/** 供应商行图标(内置品牌 mark / 首字母 monogram)。 */
function providerIcon(p: ProviderView, size: number): ReactNode {
if (hasProviderLogo(p.id, p.routing)) {
@@ -2260,6 +2326,7 @@ export function ProvidersSection() {
// OpenAI 的 reconnect-required 是 useCodexAuth 独有状态(目录 connected 此时为 false):
// 该状态下 OpenAI 行必须留在左栏,否则「重新连接」入口不可达,用户被迫从向导重发现。
const codexAuth = useCodexAuth();
+ const remoteControlEnabled = useRemoteControlEnabled();
const openaiReconnectRequired = codexAuth.state.kind === 'reconnect-required';
const [selectedId, setSelectedId] = useState<string | null>(null);
@@ -3044,6 +3111,17 @@ export function ProvidersSection() {
/>
</div>
)}
+ {/* 允许被远程调用:只在本机允许远程控制、供应商已连接且能跑 Agent 时出现。 */}
+ {remoteControlEnabled &&
+ !effectiveSelected.suspended &&
+ effectiveSelected.connected &&
+ effectiveSelected.agents.length > 0 &&
+ effectiveSelected.remoteInvocationEnabled !== undefined && (
+ <RemoteProviderAccessRow
+ key={effectiveSelected.id}
+ provider={effectiveSelected}
+ />
+ )}
{!effectiveSelected.suspended &&
(providerHasModels(effectiveSelected) ||
isCustomRoutedProvider(effectiveSelected) ||
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 8c58034c11..3fd34b0462 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -909,6 +909,21 @@ export function NewMakerDraftRoute() {
const effectiveAgentDeviceId =
!effectiveDeviceLinkDeviceId && !effectiveRemoteHostId ? (draft.agentDeviceId ?? undefined) : undefined;
const isAgentDeviceDraft = effectiveAgentDeviceId != null;
+ /**
+ * 远程 Agent 的可选落点:在线的同账号电脑,在模型选择器左侧栏里按供应商列出(选中那里的
+ * 模型 = Agent 在那台运行)。只有已允许远程调用的供应商会投影出来;没有可用供应商的
+ * 设备不会占模型列表的位置。当前落点即使掉线也保留,让用户看得到、换得回来。
+ */
+ const remoteAgentDevices = useMemo(
+ () =>
+ selectableDevices
+ .filter(
+ (device) =>
+ device.online || device.deviceId === effectiveAgentDeviceId,
+ )
+ .map(({ deviceId, name }) => ({ deviceId, name })),
+ [selectableDevices, effectiveAgentDeviceId],
+ );
/**
* 模型目录所在的电脑:任务建到远程设备时是那台;Agent 在另一台电脑运行时也是那台(模型、
* Agent 登录与可用引擎都以运行 Agent 的电脑为准)。本机任务为 undefined。
@@ -2742,6 +2757,8 @@ export function NewMakerDraftRoute() {
fast: boolean;
favoriteUid: string | null;
resetToRecommended?: true;
+ /** 远程 Agent:这一行属于哪台电脑(null = 本机);未带 = 面板没有远程 Agent 入口。 */
+ agentDevice?: { deviceId: string; name: string } | null;
}) => {
// 收藏锚点写进**目标引擎的槽**(Chris 2026-08-19 起持久化,见 draftFavoriteAnchor 的
// 说明):记的是 uid + **本次写进草稿的 wire id**,失效判定才有可比的同类值。
@@ -2762,7 +2779,44 @@ export function NewMakerDraftRoute() {
// 必须无条件进入 store 的 rebase:当前 renderer 的 draft.vendor 可能还停在 storage
// event 到达前的旧 Harness。switchVendor 自身同值早返,不会制造额外写入。
switchVendor(selection.vendor);
- if (usesDeviceCatalog) {
+ // ── 远程 Agent:模型面板里选到了另一台电脑上的模型(或从那台回到本机)──────────
+ // 连 Agent 的运行位置一起换。任务、项目、附件都在本机,一概不动;只有模型目录与这次
+ // 选择改按目标电脑。
+ const targetAgentDevice = selection.agentDevice;
+ const switchesAgentDevice =
+ targetAgentDevice !== undefined &&
+ (targetAgentDevice?.deviceId ?? null) !== (effectiveAgentDeviceId ?? null);
+ if (switchesAgentDevice && targetAgentDevice) {
+ // 这次显式选择就是那台电脑上的种子:seed key 按播种 effect 的构造逐字前置,并标记
+ // 控制端已触碰 —— 那台的 capabilities 到达时只做合法性夹紧,不会换成那台的默认模型
+ // (与下方跨引擎选择同一条修法)。
+ dlRuntimeTouchedRef.current = true;
+ dlSeedKeyRef.current = `${targetAgentDevice.deviceId}:${dbToMakerAgentKind(
+ normalizeDbAgentKind(selection.vendor),
+ )}`;
+ dlSeedCapabilitiesRef.current = null;
+ setDlSel({
+ model: selection.modelId,
+ // 没有档位的模型由播种夹紧按那台的目录补成合法值。
+ effort: selection.effort ?? 'high',
+ fastMode: selection.fast,
+ providerId: selection.providerId,
+ });
+ patchDraft({
+ agentDeviceId: targetAgentDevice.deviceId,
+ agentDeviceName: targetAgentDevice.name,
+ });
+ return;
+ }
+ if (switchesAgentDevice) {
+ // 回到本机:清掉那台电脑的选择,下面按本机草稿写入这次选择。
+ setDlSel(null);
+ dlSeedKeyRef.current = null;
+ dlSeedCapabilitiesRef.current = null;
+ dlRuntimeTouchedRef.current = false;
+ patchDraft({ agentDeviceId: null, agentDeviceName: null });
+ }
+ if (usesDeviceCatalog && !switchesAgentDevice) {
dlRuntimeTouchedRef.current = true;
// ★ 跨引擎选择必须**前置**把 seed key 推到目标引擎(2026-08-17 review 第三轮 G1)。
//
@@ -2863,6 +2917,7 @@ export function NewMakerDraftRoute() {
draft.vendor,
usesDeviceCatalog,
catalogDeviceId,
+ effectiveAgentDeviceId,
deviceLinkInitial,
capabilities,
deviceDraftDefaults,
@@ -3006,12 +3061,7 @@ export function NewMakerDraftRoute() {
// 点已选中的那一行(包括本机时点「本机」)只是确认当前选择,不该有任何副作用。
// 下面会剥 mention chip、丢路径型附件并清 workingDir / extraDirs —— 重选同一设备时执行这些,
// 等于用户点一下就静默丢掉已选的项目、附件和部分已写好的消息。必须先早返回。
- // 「Agent 在另一台电脑」时点「本机」= 回到全部在本机:只清掉运行 Agent 的电脑,任务本来
- // 就在本机,项目、附件与草稿都保持不变。
- if (deviceId === null && effectiveAgentDeviceId && !effectiveDeviceLinkDeviceId) {
- patchDraft({ agentDeviceId: null, agentDeviceName: null });
- return;
- }
+ // (Agent 在哪台电脑运行跟着模型走,由模型选择器决定;这里的「本机」只表示任务在本机。)
if (deviceId === (effectiveDeviceLinkDeviceId ?? null)) return;
// 换完停在这台设备的「对话」(workingDir=null):上一台的项目路径在新机器上基本不存在,
// 留着会让用户以为项目跟过来了、发送时才在被控端 path guard 上失败。与 mobile 切设备后
@@ -3024,28 +3074,7 @@ export function NewMakerDraftRoute() {
// 早返回掉,deviceId 必然变化 → hook effect 必然重跑 → evict 后必然 cache miss 并自行 fetch。
applyDraftTarget({ deviceId, deviceName, workingDir: null });
},
- [effectiveDeviceLinkDeviceId, effectiveAgentDeviceId, applyDraftTarget],
- );
- /**
- * 「只让 Agent 在那台电脑运行」:任务、项目文件与命令留在本机。原来要把任务建到远程设备 /
- * SSH 主机时先回到本机(那边的项目路径在本机无效);模型目录换成那台的,按那台重新播种选择。
- */
- const handleAgentDeviceChange = useCallback(
- (deviceId: string, deviceName: string | null) => {
- if (sendInFlightRef.current) return;
- if (deviceId === (effectiveAgentDeviceId ?? null)) return;
- if (effectiveDeviceLinkDeviceId || effectiveRemoteHostId) {
- applyDraftTarget({ deviceId: null, deviceName: null, workingDir: null });
- }
- // 目录快照不在这里作废:catalogDeviceId 变了 hook 会按新电脑取,模型选择器打开时
- // 也会对这台电脑作废并重新预取(与远程任务同一条路径)。
- setDlSel(null);
- dlSeedKeyRef.current = null;
- dlSeedCapabilitiesRef.current = null;
- dlRuntimeTouchedRef.current = false;
- patchDraft({ agentDeviceId: deviceId, agentDeviceName: deviceName });
- },
- [effectiveAgentDeviceId, effectiveDeviceLinkDeviceId, effectiveRemoteHostId, applyDraftTarget],
+ [effectiveDeviceLinkDeviceId, applyDraftTarget],
);
const handleOpenRemoteProject = useCallback((deviceId?: string) => {
setAddRemoteProjectDeviceId(deviceId ?? null);
@@ -5517,8 +5546,6 @@ export function NewMakerDraftRoute() {
devices={selectableDevices}
value={effectiveDeviceLinkDeviceId ?? null}
onChange={handleDeviceChange}
- agentDeviceId={effectiveAgentDeviceId ?? null}
- onAgentDeviceChange={handleAgentDeviceChange}
open={devicePickerOpen}
onOpenChange={handleDevicePickerOpenChange}
// 窄屏 pill 排会进正常流并 flex-wrap;多台时收成图标 + 状态点少占一行。
@@ -5617,6 +5644,8 @@ export function NewMakerDraftRoute() {
remoteHostId={draft.remoteHostId ?? null}
deviceLinkDeviceId={effectiveDeviceLinkDeviceId ?? null}
agentDeviceId={effectiveAgentDeviceId ?? null}
+ agentDeviceName={draft.agentDeviceName}
+ remoteAgentDevices={remoteAgentDevices}
modelMemoryOverride={deviceLinkDraftMemory}
initialModel={draftInitialModel}
initialEffort={draftInitialEffort}
diff --git a/apps/desktop/src/renderer/hooks/useDevicesProviders.ts b/apps/desktop/src/renderer/hooks/useDevicesProviders.ts
new file mode 100644
index 0000000000..546fc3cadb
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useDevicesProviders.ts
@@ -0,0 +1,79 @@
+/**
+ * useDevicesProviders — 同时订阅多台电脑的供应商目录(只读快照)。
+ *
+ * 模型选择器的左侧栏要把「其他电脑上的供应商」与本机供应商并排列出(远程 Agent),台数
+ * 不定,不能按台数调用 useDeviceProviders。这里复用 useDeviceProviders 的同一份缓存、
+ * 代际驱逐与推送:未命中缓存的设备在这里发起预取,之后靠订阅事件刷新。
+ *
+ * 没有设备时什么都不读 —— 绝大多数选择器入口都走这条空路径。
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+
+import type { ProviderView } from '@cindy/model-providers';
+
+import {
+ getCachedDeviceProviders,
+ prefetchDeviceProviders,
+ subscribeDeviceProviders,
+} from './useDeviceProviders';
+
+export interface DeviceProvidersSnapshot {
+ providers: ProviderView[];
+ /** 那台电脑的「模型显示 / 隐藏」override 快照;undefined = 旧版,不过滤。 */
+ modelVisibilityOverrides?: Record<string, boolean>;
+ loading: boolean;
+ error: string | null;
+}
+
+export function useDevicesProviders(
+ deviceIds: readonly string[],
+): ReadonlyMap<string, DeviceProvidersSnapshot> {
+ const idsKey = deviceIds.join('\n');
+ const [version, setVersion] = useState(0);
+ const errorsRef = useRef(new Map<string, string>());
+
+ useEffect(() => {
+ if (!idsKey) return;
+ const ids = idsKey.split('\n');
+ let cancelled = false;
+ const bump = () => {
+ if (!cancelled) setVersion((value) => value + 1);
+ };
+ const unsubscribes = ids.map((deviceId) =>
+ subscribeDeviceProviders(deviceId, (event) => {
+ if (event.status === 'error') errorsRef.current.set(deviceId, event.error);
+ else errorsRef.current.delete(deviceId);
+ bump();
+ }),
+ );
+ for (const deviceId of ids) {
+ if (getCachedDeviceProviders(deviceId)) continue;
+ // 结果(含失败)经上面的订阅事件回来;这里只负责发起。
+ void prefetchDeviceProviders(deviceId).finally(bump);
+ }
+ return () => {
+ cancelled = true;
+ for (const unsubscribe of unsubscribes) unsubscribe();
+ };
+ }, [idsKey]);
+
+ // 快照随订阅事件(version)与设备集合(idsKey)重建,两者不变时引用稳定。
+ return useMemo(() => {
+ void version;
+ const result = new Map<string, DeviceProvidersSnapshot>();
+ if (!idsKey) return result;
+ for (const deviceId of idsKey.split('\n')) {
+ const cached = getCachedDeviceProviders(deviceId);
+ const error = cached ? null : (errorsRef.current.get(deviceId) ?? null);
+ result.set(deviceId, {
+ providers: cached?.providers ?? [],
+ ...(cached?.modelVisibilityOverrides !== undefined
+ ? { modelVisibilityOverrides: cached.modelVisibilityOverrides }
+ : {}),
+ loading: !cached && error === null,
+ error,
+ });
+ }
+ return result;
+ }, [idsKey, version]);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f2c48fe87a..13580077a0 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2526,6 +2526,12 @@
"empty": "This provider returned no usable models this time. The list below is from the last successful refresh. Check your account's access, then retry."
},
"suspendedBanner": "This provider is disabled. Credentials are kept; enable it to use its models again.",
+ "remoteAccess": {
+ "label": "Allow remote use",
+ "description": "When on, other computers on your account can use this provider's models to run an Agent on this computer, using this computer's sign-in and quota.",
+ "ariaLabel": "Allow other computers on this account to use this provider",
+ "writeFailed": "Couldn't save the remote access setting. Please try again."
+ },
"moreActionsAria": "More Actions"
},
"detect": {
@@ -8948,6 +8954,8 @@
"ariaWithEffort": "Select model. Current: {{model}}, effort: {{effort}}",
"pendingAria": "Select model. Next message: {{agent}} · {{model}}",
"pendingAriaWithEffort": "Select model. Next message: {{agent}} · {{model}}, effort: {{effort}}",
+ "agentDevice": "Agent runs on {{device}}",
+ "agentDeviceUnnamed": "Agent runs on another computer",
"agent": {
"claudeCode": "Claude Code",
"codex": "Codex",
@@ -9003,6 +9011,8 @@
"unified": {
"railFavorites": "Favorites",
"railAll": "All",
+ "railRemoteProvider": "{{provider}} · {{device}}",
+ "remoteLoading": "Loading models from that computer…",
"favoritesGroup": "Favorites",
"favoritesEmpty": "No favorites yet — hover a model and hit ☆ to pin it here",
"addFavorite": "Save to favorites",
@@ -9369,10 +9379,7 @@
"onlineHint": "Connected — available",
"offlineHint": "Offline — available once connected",
"attachmentsDropped": "Removed {{count}} attachment(s) — they live on the previous device",
- "attachmentsRemoteUnsupported": "File attachments aren't supported on a remote device — skipped {{count}} (images are fine)",
- "agentSection": "Run Only the Agent on Another Computer",
- "agentHint": "Session and files stay here; uses its sign-in and models",
- "agentPill": "Agent on {{device}}"
+ "attachmentsRemoteUnsupported": "File attachments aren't supported on a remote device — skipped {{count}} (images are fine)"
},
"pluginSuggestions": {
"changed": "This suggestion has changed. Shuffle the suggestions and choose again.",
@@ -10364,7 +10371,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."
},
"generatedFiles": {
"title": "Files created this message",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9b72839b19..1c4a3f0a08 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2525,6 +2525,12 @@
"empty": "今回このプロバイダーから利用可能なモデルが返されませんでした。以下は前回取得した一覧です。アカウントの権限を確認してから再試行してください。"
},
"suspendedBanner": "このプロバイダーは無効になっています。認証情報は保持されており、有効にすると再びモデルを利用できます。",
+ "remoteAccess": {
+ "label": "リモート利用を許可",
+ "description": "オンにすると、同じアカウントの他のコンピューターがこのプロバイダーのモデルを使い、このコンピューター上で Agent を実行できます。このコンピューターのサインインとクォータを使います。",
+ "ariaLabel": "このアカウントの他のコンピューターにこのプロバイダーの利用を許可",
+ "writeFailed": "リモート利用の設定を保存できませんでした。もう一度お試しください。"
+ },
"moreActionsAria": "その他の操作"
},
"detect": {
@@ -8935,6 +8941,8 @@
"ariaWithEffort": "モデルを選択。現在:{{model}}、推論強度:{{effort}}",
"pendingAria": "モデルを選択。次のメッセージ:{{agent}} · {{model}}",
"pendingAriaWithEffort": "モデルを選択。次のメッセージ:{{agent}} · {{model}}、推論強度:{{effort}}",
+ "agentDevice": "Agent は {{device}} で実行",
+ "agentDeviceUnnamed": "Agent は別のパソコンで実行",
"agent": {
"claudeCode": "Claude Code",
"codex": "Codex",
@@ -8990,6 +8998,8 @@
"unified": {
"railFavorites": "お気に入り",
"railAll": "すべて",
+ "railRemoteProvider": "{{provider}} · {{device}}",
+ "remoteLoading": "そのパソコンのモデルを読み込み中…",
"favoritesGroup": "お気に入り",
"favoritesEmpty": "お気に入りはまだありません——モデルの行にカーソルを合わせて ☆ で保存できます",
"addFavorite": "お気に入りに保存",
@@ -9356,10 +9366,7 @@
"onlineHint": "接続済み — 作成できます",
"offlineHint": "オフライン — 接続後に利用可能",
"attachmentsDropped": "添付ファイル {{count}} 件を削除しました(前のデバイス上のファイルです)",
- "attachmentsRemoteUnsupported": "リモートデバイスではファイル添付に未対応のため {{count}} 件をスキップしました(画像は可)",
- "agentSection": "Agent だけ別のパソコンで実行",
- "agentHint": "セッションとファイルはこちらに残し、そのパソコンのサインインとモデルを使います",
- "agentPill": "Agent: {{device}}"
+ "attachmentsRemoteUnsupported": "リモートデバイスではファイル添付に未対応のため {{count}} 件をスキップしました(画像は可)"
},
"pluginSuggestions": {
"changed": "このおすすめは更新されました。おすすめを入れ替えて、もう一度選んでください。",
@@ -10347,7 +10354,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": "そのパソコンでは、このプロバイダーのリモート利用が許可されていません。そのパソコンの「設定 → モデルプロバイダー」で「リモート利用を許可」をオンにするか、別のモデルを選んでください。"
},
"generatedFiles": {
"title": "このメッセージで作成されたファイル",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 363acfdd14..962c2237c1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2525,6 +2525,12 @@
"empty": "이번에는 이 제공자가 사용 가능한 모델을 반환하지 않았습니다. 아래는 마지막으로 가져온 목록입니다. 계정 권한을 확인한 후 다시 시도하세요."
},
"suspendedBanner": "이 제공자는 비활성화되어 있습니다. 자격 증명은 유지되며, 활성화하면 모델을 다시 사용할 수 있습니다.",
+ "remoteAccess": {
+ "label": "원격 사용 허용",
+ "description": "켜면 같은 계정의 다른 컴퓨터가 이 제공자의 모델로 이 컴퓨터에서 Agent를 실행할 수 있습니다. 이 컴퓨터의 로그인과 할당량을 씁니다.",
+ "ariaLabel": "이 계정의 다른 컴퓨터에서 이 제공자를 사용하도록 허용",
+ "writeFailed": "원격 사용 설정을 저장하지 못했습니다. 다시 시도해 주세요."
+ },
"moreActionsAria": "추가 작업"
},
"detect": {
@@ -8935,6 +8941,8 @@
"ariaWithEffort": "모델 선택. 현재: {{model}}, 추론 강도: {{effort}}",
"pendingAria": "모델 선택. 다음 메시지: {{agent}} · {{model}}",
"pendingAriaWithEffort": "모델 선택. 다음 메시지: {{agent}} · {{model}}, 추론 강도: {{effort}}",
+ "agentDevice": "Agent가 {{device}}에서 실행",
+ "agentDeviceUnnamed": "Agent가 다른 컴퓨터에서 실행",
"agent": {
"claudeCode": "Claude Code",
"codex": "Codex",
@@ -8990,6 +8998,8 @@
"unified": {
"railFavorites": "즐겨찾기",
"railAll": "전체",
+ "railRemoteProvider": "{{provider}} · {{device}}",
+ "remoteLoading": "그 컴퓨터의 모델을 불러오는 중…",
"favoritesGroup": "즐겨찾기",
"favoritesEmpty": "즐겨찾기가 없습니다 — 모델 행에 마우스를 올리고 ☆를 눌러 저장하세요",
"addFavorite": "즐겨찾기에 저장",
@@ -9356,10 +9366,7 @@
"onlineHint": "연결됨 — 생성 가능",
"offlineHint": "오프라인 — 연결 후 사용 가능",
"attachmentsDropped": "첨부파일 {{count}}개를 제거했습니다 — 이전 기기에 있는 파일입니다",
- "attachmentsRemoteUnsupported": "원격 기기에서는 파일 첨부를 지원하지 않아 {{count}}개를 건너뛰었습니다(이미지는 가능)",
- "agentSection": "Agent만 다른 컴퓨터에서 실행",
- "agentHint": "세션과 파일은 이곳에 두고, 그 컴퓨터의 로그인과 모델을 사용합니다",
- "agentPill": "Agent: {{device}}"
+ "attachmentsRemoteUnsupported": "원격 기기에서는 파일 첨부를 지원하지 않아 {{count}}개를 건너뛰었습니다(이미지는 가능)"
},
"pluginSuggestions": {
"changed": "이 추천이 업데이트되었습니다. 추천을 바꾼 뒤 다시 선택해 주세요.",
@@ -10347,7 +10354,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": "그 컴퓨터에서 이 제공자의 원격 사용을 허용하지 않았습니다. 그 컴퓨터의 설정 → 모델 제공자에서 원격 사용 허용을 켜거나 다른 모델을 선택하세요."
},
"generatedFiles": {
"title": "이 메시지에서 생성된 파일",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 4099b879de..592eb375a6 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2525,6 +2525,12 @@
"empty": "该供应商这次没有返回任何可用模型,下面是上次获取的列表。请确认账号权限后重试。"
},
"suspendedBanner": "该供应商已停用,凭证已保留;启用后其模型才会重新可用",
+ "remoteAccess": {
+ "label": "允许被远程调用",
+ "description": "开启后,同账号的其他电脑可以用这个供应商的模型,让 Agent 在这台电脑上运行,使用这台电脑的登录和配额。",
+ "ariaLabel": "允许同账号的其他电脑调用此供应商",
+ "writeFailed": "远程调用设置未能保存,请重试"
+ },
"moreActionsAria": "更多操作"
},
"detect": {
@@ -8935,6 +8941,8 @@
"ariaWithEffort": "选择模型。当前:{{model}},推理强度:{{effort}}",
"pendingAria": "选择模型。下条消息:{{agent}} · {{model}}",
"pendingAriaWithEffort": "选择模型。下条消息:{{agent}} · {{model}},推理强度:{{effort}}",
+ "agentDevice": "Agent 在 {{device}} 上运行",
+ "agentDeviceUnnamed": "Agent 在另一台电脑上运行",
"agent": {
"claudeCode": "Claude Code",
"codex": "Codex",
@@ -8990,6 +8998,8 @@
"unified": {
"railFavorites": "收藏",
"railAll": "全部",
+ "railRemoteProvider": "{{provider}} · {{device}}",
+ "remoteLoading": "正在读取那台电脑的模型…",
"favoritesGroup": "收藏",
"favoritesEmpty": "还没有收藏——把鼠标停到模型行上,点 ☆ 存到这里",
"addFavorite": "存为收藏",
@@ -9356,10 +9366,7 @@
"onlineHint": "已连接,可在其上创建",
"offlineHint": "离线 · 连上后可用",
"attachmentsDropped": "已移除 {{count}} 个附件:它们是上一台设备上的文件",
- "attachmentsRemoteUnsupported": "远程设备暂不支持文件附件,已跳过 {{count}} 个(图片可以)",
- "agentSection": "只让 Agent 在其他电脑运行",
- "agentHint": "任务和文件留在本机,用这台的登录与模型",
- "agentPill": "Agent 在 {{device}}"
+ "attachmentsRemoteUnsupported": "远程设备暂不支持文件附件,已跳过 {{count}} 个(图片可以)"
},
"pluginSuggestions": {
"changed": "这条推荐已更新,请换一批后重新选择。",
@@ -10347,7 +10354,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": "那台电脑没有允许远程调用这个供应商。请在那台电脑的「设置 → 模型供应商」里打开「允许被远程调用」,或换一个模型。"
},
"generatedFiles": {
"title": "本条消息生成的文件",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index cc062b57d6..5dd21b68fe 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2525,6 +2525,12 @@
"empty": "該供應商這次沒有返回任何可用模型,下面是上次獲取的列表。請確認帳號權限後重試。"
},
"suspendedBanner": "該供應商已停用,憑證已保留;啟用後其模型才會重新可用",
+ "remoteAccess": {
+ "label": "允許遠端呼叫",
+ "description": "開啟後,同帳號的其他電腦可以用這個供應商的模型,讓 Agent 在這台電腦上執行,使用這台電腦的登入和配額。",
+ "ariaLabel": "允許同帳號的其他電腦呼叫此供應商",
+ "writeFailed": "遠端呼叫設定未能儲存,請重試"
+ },
"moreActionsAria": "更多操作"
},
"detect": {
@@ -8934,6 +8940,8 @@
"ariaWithEffort": "選擇模型。當前:{{model}},推理強度:{{effort}}",
"pendingAria": "選擇模型。下條訊息:{{agent}} · {{model}}",
"pendingAriaWithEffort": "選擇模型。下條訊息:{{agent}} · {{model}},推理強度:{{effort}}",
+ "agentDevice": "Agent 在 {{device}} 上執行",
+ "agentDeviceUnnamed": "Agent 在另一臺電腦上執行",
"agent": {
"claudeCode": "Claude Code",
"codex": "Codex",
@@ -8989,6 +8997,8 @@
"unified": {
"railFavorites": "收藏",
"railAll": "全部",
+ "railRemoteProvider": "{{provider}} · {{device}}",
+ "remoteLoading": "正在讀取那臺電腦的模型…",
"favoritesGroup": "收藏",
"favoritesEmpty": "還沒有收藏——把滑鼠停到模型列上,點 ☆ 存到這裡",
"addFavorite": "存為收藏",
@@ -9356,10 +9366,7 @@
"onlineHint": "已連線,可在其上建立",
"offlineHint": "離線 · 連上後可用",
"attachmentsDropped": "已移除 {{count}} 個附件:它們是上一臺裝置上的檔案",
- "attachmentsRemoteUnsupported": "遠端裝置暫不支援檔案附件,已跳過 {{count}} 個(圖片可以)",
- "agentSection": "只讓 Agent 在其他電腦執行",
- "agentHint": "任務和檔案留在本機,使用這臺的登入與模型",
- "agentPill": "Agent 在 {{device}}"
+ "attachmentsRemoteUnsupported": "遠端裝置暫不支援檔案附件,已跳過 {{count}} 個(圖片可以)"
},
"pluginSuggestions": {
"changed": "這條推薦已更新,請換一批後重新選擇。",
@@ -10346,7 +10353,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": "那臺電腦沒有允許遠端呼叫這個供應商。請在那臺電腦的「設定 → 模型供應商」裡開啟「允許遠端呼叫」,或換一個模型。"
},
"generatedFiles": {
"title": "本條訊息生成的檔案",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 63c6383273..c1f37386f2 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5692,6 +5692,11 @@ interface ElectronAPI {
// reset = 恢复默认:删除该供应商整组停用 override(含指向已下架模型的陈旧条目)。
| { kind: 'reset'; providerId: string },
) => Promise<{ ok: true }>;
+ /** 供应商级远程 Agent 授权;默认关闭,设置页写入后经 PROVIDER_CHANGED 刷新。 */
+ setProviderRemoteAccess: (input: {
+ providerId: string;
+ enabled: boolean;
+ }) => Promise<{ ok: true; enabled: boolean }>;
/** Persist the visible provider order only if the active owner still matches. */
setProviderOrder: (
dataOwnerId: string | null,
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index c282467f66..03bd0c4345 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -471,6 +471,14 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
升级那台的 Cindy。
- **持久化**:A 的 `sessions.agent_device_id`(migration 0123)记住 Agent 所在电脑;旧版本读不到该列,
按本机任务处理。服务端代码无改动。
+- **供应商授权(「允许被远程调用」)**:B 在模型供应商设置里逐个打开,默认关;B 没开「允许远程控制」时
+ 不显示这个开关。授权按账号存在 B 本地(`remote-provider-access-prefs.json`),凭证与路由细节不出 B。
+ `maker:provider:list` 每条供应商附带 `remoteInvocationEnabled: boolean`,**只作标记、不裁剪目录**:
+ 远程控制与 Mobile 仍看到全部供应商,忽略该字段即可。A 的远程 Agent 入口(模型选择器左侧栏、换模型、
+ 协同 Worker、定时任务读的那台目录)只用值为 `true` 的供应商,缺少该字段按未开放。B 是最终裁决方:
+ `open` 时把来源落到已开放的供应商上(A 没指定来源时只在已开放的里按默认规则挑)并以显式来源启动;
+ `setModel` 显式换来源时同样核对;关掉后进行中的这一轮照常结束,下一次 `send` 被拒。拒绝统一回
+ `REMOTE_AGENT_PROVIDER_NOT_ALLOWED`,A 按 `chat.remoteError` 提示去那台电脑打开开关或换模型。
- **暂不支持**:分叉、审查、移动项目、复制到其他电脑、导出 `.cshare`(Agent 会话记录在 B),入口隐藏、
主进程拒绝。
diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.ts
index 034cb1360e..9cade9a4c7 100644
--- a/packages/device-link/src/remoteAgent.ts
+++ b/packages/device-link/src/remoteAgent.ts
@@ -82,6 +82,8 @@ export const REMOTE_AGENT_ERROR_CODES = [
'REMOTE_AGENT_EXPIRED',
'REMOTE_AGENT_ACCOUNT_CHANGED',
'REMOTE_AGENT_UNAVAILABLE',
+ // 那台电脑没有对这个供应商打开「允许被远程调用」(或已关闭)。
+ 'REMOTE_AGENT_PROVIDER_NOT_ALLOWED',
] as const;
export type RemoteAgentErrorCode = (typeof REMOTE_AGENT_ERROR_CODES)[number];
diff --git a/packages/model-providers/src/registry.ts b/packages/model-providers/src/registry.ts
index 7d2dbf6072..8b4c08b988 100644
--- a/packages/model-providers/src/registry.ts
+++ b/packages/model-providers/src/registry.ts
@@ -94,6 +94,8 @@ export type ModelDiscoveryFailureState = Partial<
/** 供应商 + 连接状态。 */
export interface ProviderView extends Provider {
+ /** 本机是否允许同账号另一台电脑调用该供应商;缺省等同关闭。 */
+ remoteInvocationEnabled?: boolean;
/** Definition remains available for adding a removed local connection again. */
removed?: boolean;
subscriptionAccount?: { source: 'local' | 'oauth' | 'unknown'; identity?: string; reconnectRequired?: boolean };