Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(companions): use shared model routes across settings and execution

Chrisf0ca2ec5e65a
diff --git a/apps/desktop/src/main/im/remoteProviderRoute.ts b/apps/desktop/src/main/im/remoteProviderRoute.ts
index e7d97e17ef..3f58b8afdb 100644
--- a/apps/desktop/src/main/im/remoteProviderRoute.ts
+++ b/apps/desktop/src/main/im/remoteProviderRoute.ts
@@ -1,27 +1,7 @@
import type { AgentKind } from '@cindy/maker-core';
-import { effectiveSourceIdForModel, getModel, isModelSelectableForNewRoute } from '@cindy/model-providers';
-import { readDeviceProviderViews } from '../remote-agent/controller/deviceCatalog';
-/** 与普通任务共用授权目录;失败不回落到本机的同名供应商。 */
-export async function readImRemoteProviderRoute(route: {
- agentDeviceId: string;
- agentKind: AgentKind;
- providerId: string | null;
- model: string;
-}) {
- const { remoteBackgroundInvoke } = await import('../device-link');
- const providers = await readDeviceProviderViews(remoteBackgroundInvoke, route.agentDeviceId);
- // 已有远程任务可以未指定来源;只在执行端授权目录内按原生默认规则解析。
- // 显式来源失效仍拒绝,不换到另一个同名模型账号。
- const providerId = route.providerId ?? effectiveSourceIdForModel(providers, null, route.model, route.agentKind);
- const provider = providers.find((p) => p.id === providerId && p.connected && !p.suspended && p.agents.includes(route.agentKind));
- const model = provider && getModel(provider, route.model, route.agentKind);
- if (!provider || !model || !isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' })) {
- throw new Error('[REMOTE_AGENT_UNAVAILABLE] Selected remote provider or model is unavailable.');
- }
- return { provider, model };
-}
+export { readRemoteProviderRoute as readImRemoteProviderRoute } from '../remote-agent/controller/deviceCatalog';
/** 权限档也取执行端能力,发起电脑可能没有安装该引擎。 */
export async function readImRemotePermissionModes(agentDeviceId: string, agentKind: AgentKind): Promise<string[]> {
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index aabc127c8a..72e087ffc9 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -707,6 +707,7 @@ export interface BotsReplaceCanonicalSessionArgs {
agentKind: string;
remoteHostId: string | null;
providerId: string | null;
+ agentDeviceId?: string | null;
parentSessionId?: string | null;
extraDirs: string;
fastMode?: boolean;
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index b43f41dbab..557bda6812 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -664,6 +664,19 @@ describe('Bot canonical Session lifecycle', () => {
expect((await listBotRemoteResourceSources()).map((row) => row.id)).not.toContain(created.id);
});
+ it('persists a shared model location when creating the canonical session', async () => {
+ const route = { harness: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ agentDeviceId: 'share:test-account', effort: 'high', fastMode: false };
+ h.sqlite!.prepare('UPDATE bot_profile_versions SET capabilities_json = ? WHERE bot_id = ? AND version = 1')
+ .run(JSON.stringify({ modelChainOverride: [route] }), 'bot-1');
+ const canonical = await invoke('local-db:bots:create-canonical-session', {
+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,
+ });
+ expect(h.sqlite!.prepare('SELECT agent_device_id, model, provider_id FROM sessions WHERE id = ?')
+ .get(canonical.session.id)).toEqual({ agent_device_id: route.agentDeviceId,
+ model: route.model, provider_id: route.providerId });
+ });
+
it('creates the first canonical task on Codex when only its subscription is connected', async () => {
h.providers = [{
id: 'openai', source: 'builtin', connected: true, agents: ['codex'],
@@ -5984,6 +5997,27 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { runtime.dispose(); }
});
+ it('preserves the shared account when inheriting or overriding a background task model', async () => {
+ await seedPair();
+ const shared = { harness: 'codex' as const, model: 'gpt-6-astra', providerId: 'openai',
+ agentDeviceId: 'share:task-account', effort: 'high', fastMode: false };
+ const runtime = createDelegationRuntime({
+ resolveTaskModelSelection: async () => shared,
+ readCallerRuntime: () => ({ agentKind: 'codex', model: shared.model, providerId: shared.providerId,
+ agentDeviceId: shared.agentDeviceId, effort: 'high', fastMode: false }),
+ });
+ try {
+ for (const modelSelection of [undefined, { id: 'selected-shared-route' }]) {
+ const result = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1',
+ objective: 'Use the selected shared account.', modelSelection });
+ expect(result.ok).toBe(true); if (!result.ok) throw new Error(result.message);
+ expect(result.modelRoute).toEqual(shared);
+ expect(h.sqlite!.prepare('SELECT agent_device_id, provider_id FROM sessions WHERE id = ?')
+ .get(result.childSessionId)).toEqual({ agent_device_id: shared.agentDeviceId, provider_id: shared.providerId });
+ }
+ } finally { runtime.dispose(); }
+ });
+
it('rejects a stale one-task model selection before creating a task instead of using the default', async () => {
await seedPair();
const runtime = createDelegationRuntime({ resolveTaskModelSelection: async () => { throw new Error('Unavailable'); } });
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteEditors.ts b/apps/desktop/src/main/localDb/ipc/botRemoteEditors.ts
index 58542fc5ee..5326aa9618 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteEditors.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteEditors.ts
@@ -1,3 +1,4 @@
+import { serializeModelRoutes } from '@cindy/maker-shared/model-route';
import { normalizeBotModelChain, type BotModelRoute } from '../../../shared/botModelChain.js';
import { createHash } from 'node:crypto';
import { resolveRemoteText, type RemoteActionDescriptor, type RemoteActionInvokeResponse, type RemoteLocalizedText, type RemoteResource } from '@cindy/device-link';
@@ -69,7 +70,7 @@ export function createBotRemoteEditors(deps: BotRemoteEditorDeps, bind: ReturnTy
{ id: 'avatarImageBase64', label: editorCopy.avatar, kind: 'text', required: true },
], { name: '', avatarImageBase64: '' });
// Metadata keeps older generic form renderers from displaying raw model JSON.
- const block = { ...panel.block, data: { ...panel.block.data, creationModelChain: JSON.stringify(modelChain.slice(0, 1)) } };
+ const block = { ...panel.block, data: { ...panel.block.data, creationModelChain: serializeModelRoutes(modelChain.slice(0, 1)) } };
return bind(context, { ref: ref(id), revision: '1', display: { title: editorCopy.create }, links: [], blocks: [block], actions: [panel.action] }, async () => '1', async request => {
const input = request.input ?? {}; keys(input, ['name', 'avatarImageBase64', 'requestId', 'modelChain']);
const requestId = string(input.requestId, 80);
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsResource.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsResource.ts
index 2e3c32e351..0e6b43644e 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsResource.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsResource.ts
@@ -1,3 +1,4 @@
+import { serializeModelRoutes } from '@cindy/maker-shared/model-route';
import { normalizeBotModelChain, readBotTaskModelOverride, type BotModelRoute } from '../../../shared/botModelChain.js';
import { createHash, randomUUID } from 'node:crypto';
import type { RemoteActionDescriptor, RemoteActionInvokeRequest, RemoteActionInvokeResponse, RemoteLocalizedText, RemoteResource } from '@cindy/device-link';
@@ -133,9 +134,9 @@ export function createBotRemoteSettingsResource(deps: BotRemoteSettingsDeps) {
form('models', [{ id: 'followsDefault', label: copy.followsDefault, kind: 'toggle' }, { id: 'modelChain', label: copy.models, kind: 'multiline' },
{ id: 'taskFollowsPrimary', label: copy.taskFollowsPrimary, kind: 'toggle' },
{ id: 'taskModel', label: copy.taskModel, kind: 'multiline' }],
- { followsDefault: settings.followsDefault, modelChain: JSON.stringify(settings.modelChain),
+ { followsDefault: settings.followsDefault, modelChain: serializeModelRoutes(settings.modelChain),
taskFollowsPrimary: !settings.taskModelOverride,
- taskModel: JSON.stringify(settings.taskModelOverride ? [settings.taskModelOverride] : settings.modelChain.slice(0, 1)) }),
+ taskModel: serializeModelRoutes(settings.taskModelOverride ? [settings.taskModelOverride] : settings.modelChain.slice(0, 1)) }),
{ id: 'connections', primitive: 'markdown', fallbackMarkdown: [...settings.skills, ...settings.connections, ...settings.toolsets].join('\n') },
];
// A failed shelf read must not turn into an empty shelf or prevent profile recovery.
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index a9144f47c4..56f7bf205f 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -400,6 +400,7 @@ export async function ensureBotGroupLaneSession(input: {
agentKind: row.agentKind,
remoteHostId: null,
providerId: row.providerId ?? null,
+ agentDeviceId: row.agentDeviceId ?? null,
extraDirs: row.extraDirs,
source: row.source,
createdAt: row.createdAt,
@@ -511,6 +512,7 @@ export async function ensureBotChannelLaneSession(input: {
agentKind: row.agentKind,
remoteHostId: null,
providerId: row.providerId ?? null,
+ agentDeviceId: row.agentDeviceId ?? null,
extraDirs: row.extraDirs,
source: row.source,
createdAt: row.createdAt,
@@ -678,6 +680,7 @@ function botSessionRouteFields(config: Record<string, unknown>, primaryRoute: Bo
? NEW_BOT_DEFAULT_PI_EFFORT
: undefined),
fastMode: primaryRoute?.fastMode ?? config.fastMode === true,
+ agentDeviceId: primaryRoute?.agentDeviceId ?? null,
agentKind: botSessionAgentKind(primaryRoute ?? config),
permissionMode: botSessionPermissionMode(config),
};
@@ -2167,6 +2170,7 @@ export function registerBotIpc(): void {
agentKind: insertRow.agentKind,
remoteHostId: insertRow.remoteHostId ?? null,
providerId: insertRow.providerId ?? null,
+ agentDeviceId: insertRow.agentDeviceId ?? null,
extraDirs: insertRow.extraDirs,
source: insertRow.source,
createdAt: insertRow.createdAt,
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index de0ec52056..fa6798a7a5 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -559,32 +559,7 @@ function botsReplaceCanonicalSession(
return { created: false, canonicalSessionId, archivedCanonicalSessionId: null };
}
}
- db.prepare(
- `INSERT INTO sessions
- (id, title, working_dir, workspace_kind, model, effort, permission_mode, status,
- sdk_session_id, total_token_usage, total_cost_usd, context_tokens, context_window,
- fast_mode, plan_mode_enabled, cleared_at, pinned_at, user_send_at, agent_kind,
- orca_role, parent_session_id, forked_at_message_id, worktree_path, extra_dirs,
- remote_host_id, provider_id, source, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, 'active', NULL, 0, 0, 0, 0, ?, 0, NULL, NULL, NULL,
- ?, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
- ).run(
- sessionId,
- expectString(s.title, 'session.title'),
- nullableString(s.workingDir),
- expectString(s.workspaceKind, 'session.workspaceKind'),
- expectString(s.model, 'session.model'),
- expectString(s.effort, 'session.effort'),
- expectString(s.permissionMode, 'session.permissionMode'),
- s.fastMode === true ? 1 : 0,
- expectString(s.agentKind, 'session.agentKind'),
- expectString(s.extraDirs, 'session.extraDirs'),
- nullableString(s.remoteHostId),
- nullableString(s.providerId),
- expectString(s.source, 'session.source'),
- expectNumber(s.createdAt, 'session.createdAt'),
- expectNumber(s.updatedAt, 'session.updatedAt'),
- );
+ insertBotSession(db, { ...s, id: sessionId, parentSessionId: null });
let archived: string | null = null;
let missingCanonicalSessionId: string | null = compatibilityMissingCanonicalSessionId;
if (canonicalSessionId) {
@@ -784,9 +759,9 @@ function insertBotSession(db: Database.Database, s: Record<string, unknown>): vo
sdk_session_id, total_token_usage, total_cost_usd, context_tokens, context_window,
fast_mode, plan_mode_enabled, cleared_at, pinned_at, user_send_at, agent_kind,
orca_role, parent_session_id, forked_at_message_id, worktree_path, extra_dirs,
- remote_host_id, provider_id, source, created_at, updated_at)
+ remote_host_id, provider_id, source, created_at, updated_at, agent_device_id)
VALUES (?, ?, ?, ?, ?, ?, ?, 'active', NULL, 0, 0, 0, 0, ?, 0, NULL, NULL, NULL,
- ?, NULL, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`)
+ ?, NULL, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?)`)
.run(expectString(s.id, 'session.id'), expectString(s.title, 'session.title'),
nullableString(s.workingDir), expectString(s.workspaceKind, 'session.workspaceKind'),
expectString(s.model, 'session.model'), expectString(s.effort, 'session.effort'),
@@ -795,7 +770,7 @@ function insertBotSession(db: Database.Database, s: Record<string, unknown>): vo
nullableString(s.parentSessionId),
expectString(s.extraDirs, 'session.extraDirs'), nullableString(s.remoteHostId), nullableString(s.providerId),
expectString(s.source, 'session.source'), expectNumber(s.createdAt, 'session.createdAt'),
- expectNumber(s.updatedAt, 'session.updatedAt'));
+ expectNumber(s.updatedAt, 'session.updatedAt'), nullableString(s.agentDeviceId));
}
/** One hidden lane per (group, Bot); reuses an active lane instead of creating a second. */
diff --git a/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts b/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts
index 878b56f244..e6c456cc0c 100644
--- a/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts
+++ b/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts
@@ -98,6 +98,17 @@ export async function readBotModelChainSettingsState(
// Capture the owner before reading live connections; never persist derived defaults.
const owner = activeOwnerScopeKey();
await waitForModelVisibilityMirror();
+ const preferredRoute = getSelectedNewMakerRoute(owner);
+ if (preferredRoute?.agentDeviceId) {
+ const { resolveAvailableTaskModels } = await import('../maker-ipc/appDefaultModelControl.js');
+ const [route] = await resolveAvailableTaskModels([preferredRoute]).catch(() => [null]);
+ if (activeOwnerScopeKey() !== owner) throw new Error('Bot model defaults owner changed');
+ store.invalidateIfChanged();
+ const confirmed = store.readState();
+ if (confirmed.isCustomized) return confirmed;
+ const value = { modelChain: route ? [route] : [] };
+ return { ...confirmed, value, defaults: value };
+ }
const providers = options?.providers ?? await readConnectedProviders(owner);
if (activeOwnerScopeKey() !== owner) throw new Error('Bot model defaults owner changed');
store.invalidateIfChanged();
@@ -162,7 +173,7 @@ async function followMovedCindyAuto(
providers: readonly ProviderView[] | undefined,
): Promise<BotModelRoute[]> {
// 预设 auto 只在 Cindy AI 上、不会被挪动;只有模型组 Auto 才值得为此读一次目录。
- if (!chain.some((route) => route.model !== 'auto' && isCindyAutoModelId(route.model)))
+ if (!chain.some((route) => !route.agentDeviceId && route.model !== 'auto' && isCindyAutoModelId(route.model)))
return chain;
let views = providers;
if (!views) {
@@ -180,6 +191,7 @@ async function followMovedCindyAuto(
}
const catalog = views;
return chain.map((route) => {
+ if (route.agentDeviceId) return route;
const providerId = movedCindyAutoSourceId(catalog, {
agent: route.harness === 'claude' ? 'claude-code' : route.harness,
model: route.model,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts
index 7dcef67ac3..2fee3c0cc7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts
@@ -5,7 +5,8 @@ import { changeAppDefaultModel, configureAppDefaultModelSelection, inspectAppDef
import { setNewMakerDraftCache, syncNewMakerDraftCache } from '../../maker-host/newMakerDefaultsCache';
const host = vi.hoisted(() => ({ owner: 'owner:1', enabled: true, connected: true, agents: ['codex'],
- enableSecond: false, providers: vi.fn() }));
+ enableSecond: false, providers: vi.fn(), remote: vi.fn() }));
+vi.mock('../../remote-agent/controller/deviceCatalog.js', () => ({ readRemoteProviderRoute: host.remote }));
vi.mock('../../maker-host/index.js', () => ({ getMakerIfReady: () => ({ listAvailableAgents: () => host.agents }) }));
vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
getDesktopProviderService: () => ({ listProviders: host.providers }),
@@ -196,3 +197,16 @@ describe('Bot control of the real Cindy default', () => {
expect(dispatch).not.toHaveBeenCalled();
});
});
+
+// A shared account is independent of the recipient's installed harnesses and local credentials.
+it('validates remote task routes without reading or falling back to local providers', async () => {
+ host.agents = [];
+ host.providers.mockClear();
+ const shared = { ...route, agentDeviceId: 'share:one' };
+ host.remote.mockResolvedValue({ provider: { id: 'openai' }, model: { efforts: ['medium'], supportsFastMode: false } });
+ expect(await validateTaskModel(shared)).toBe(true);
+ expect(await validateTaskModel({ ...shared, effort: 'ultra' })).toBe(false);
+ host.remote.mockRejectedValue(new Error('revoked'));
+ await expect(validateTaskModel(shared)).rejects.toThrow('revoked');
+ expect(host.providers).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts
index 78641ef33c..812ace0933 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botModelRouteReconciler.test.ts
@@ -218,3 +218,17 @@ it('does not retry a superseded failed switch after the account owner changes',
expect((await results).map(result => result.status)).toEqual(['rejected', 'rejected']);
expect(h.apply).toHaveBeenCalledOnce();
});
+
+// Regression: changing only the account location must still move the runtime.
+it('reconciles shared-to-local and local-to-shared selections of the same model', async () => {
+ const h = harness();
+ const local = { agentKind: 'codex' as const, model: 'luna', providerId: 'xd', effort: 'medium' as const, fastMode: false };
+ h.state.current = local;
+ h.state.chain[0]!.agentDeviceId = 'share:one';
+ await h.reconcile('canonical');
+ expect(h.apply).toHaveBeenLastCalledWith('canonical', { ...local, agentDeviceId: 'share:one' }, local);
+ h.state.current = { ...local, agentDeviceId: 'share:one' };
+ delete h.state.chain[0]!.agentDeviceId;
+ await h.reconcile.profileChanged('canonical');
+ expect(h.apply).toHaveBeenLastCalledWith('canonical', local, h.state.current);
+});
diff --git a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
index 9e865a70ad..67842a1d1f 100644
--- a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
+++ b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
@@ -99,8 +99,21 @@ export async function resolveTaskModelSelection(selection: TaskModelSelection):
/** Resolve legacy implicit sources using the ordinary default policy, without persisting changes. */
export async function resolveAvailableTaskModels(routes: readonly BotModelRoute[]): Promise<Array<BotModelRoute | null>> {
- const { available, inputs } = await readSelection();
- return routes.map(route => {
+ const owner = activeOwnerScopeKey();
+ const local = routes.some(route => !route.agentDeviceId) ? await readSelection() : null;
+ return Promise.all(routes.map(async route => {
+ if (route.agentDeviceId) {
+ const { readRemoteProviderRoute } = await import('../remote-agent/controller/deviceCatalog.js');
+ const { provider, model } = await readRemoteProviderRoute({
+ agentDeviceId: route.agentDeviceId, agentKind: route.harness === 'claude' ? 'claude-code' : route.harness,
+ providerId: route.providerId, model: route.model,
+ });
+ if (activeOwnerScopeKey() !== owner || isAppSessionBoundaryPending()) throw new Error('账号已变化,请重新选择');
+ if ((route.effort && !model.efforts.some(effort => effort === route.effort)) || (route.fastMode && !model.supportsFastMode)) return null;
+ return { ...route, providerId: provider.id };
+ }
+ if (!local) return null;
+ const { available, inputs } = local;
const resolved = defaultBotModelChain({ providers: inputs.providers, providersLoading: false,
availableAgents: inputs.availableAgents, availableAgentsLoaded: true,
preferredRoute: route, isModelEnabled: inputs.enabled })[0];
@@ -109,7 +122,7 @@ export async function resolveAvailableTaskModels(routes: readonly BotModelRoute[
&& item.route.model === resolved.model && item.route.providerId === resolved.providerId);
return entry && (!resolved.effort || entry.efforts.some(effort => effort === resolved.effort))
&& (!resolved.fastMode || entry.supportsFastMode) ? resolved : null;
- });
+ }));
}
/** Check a saved full route without changing the application or teammate's primary model. */
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 1b7f00c64f..1a4b1f8837 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -184,7 +184,7 @@ export interface BotDelegationServiceDeps {
readCallerRuntime?: (sessionId: string) => (Pick<
typeof sessions.$inferSelect,
'model' | 'agentKind' | 'providerId' | 'fastMode'
- > & { effort?: (typeof sessions.$inferSelect)['effort'] }) | null;
+ > & { effort?: (typeof sessions.$inferSelect)['effort']; agentDeviceId?: string | null }) | null;
validateTaskModel?: typeof validateTaskModel;
resolveTaskModelSelection?: typeof resolveTaskModelSelection;
/** null means the live permission is changing or the caller is closing. */
@@ -2374,6 +2374,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
effort?: string;
fastMode?: boolean;
providerId?: string | null;
+ agentDeviceId?: string | null;
agentKind: 'cc' | 'codex' | 'pi';
title: string;
workspaceKind?: 'project' | 'dialogue';
@@ -2461,6 +2462,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
fastMode: childRow.fastMode,
permissionMode: childRow.permissionMode,
agentKind: childRow.agentKind,
+ agentDeviceId: childRow.agentDeviceId ?? null,
remoteHostId: null,
providerId: childRow.providerId ?? null,
parentSessionId,
@@ -2620,6 +2622,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
model: sessions.model,
agentKind: sessions.agentKind,
providerId: sessions.providerId,
+ agentDeviceId: sessions.agentDeviceId,
effort: sessions.effort,
fastMode: sessions.fastMode,
})
@@ -2658,6 +2661,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
agentKind: taskModel.harness === 'claude' ? 'cc' : taskModel.harness,
model: taskModel.model,
providerId: taskModel.providerId,
+ agentDeviceId: taskModel.agentDeviceId ?? null,
effort: taskModel.effort as typeof callerRuntime.effort,
fastMode: taskModel.fastMode,
} : callerRuntime;
@@ -2705,6 +2709,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
workingDir,
workspaceKind: input.workingDir?.trim() ? 'project' : 'dialogue',
model: taskRuntime.model,
+ agentDeviceId: taskRuntime.agentDeviceId ?? null,
...(taskRuntime.effort ? { effort: taskRuntime.effort } : {}),
...(taskRuntime.fastMode !== null && taskRuntime.fastMode !== undefined
? { fastMode: taskRuntime.fastMode }
@@ -2729,6 +2734,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
modelRoute: {
harness: taskRuntime.agentKind === 'codex' ? 'codex' : taskRuntime.agentKind === 'pi' ? 'pi' : 'claude',
model: taskRuntime.model,
+ ...(taskRuntime.agentDeviceId ? { agentDeviceId: taskRuntime.agentDeviceId } : {}),
providerId: taskRuntime.providerId ?? null,
effort: taskRuntime.effort ?? '',
fastMode: Boolean(taskRuntime.fastMode),
diff --git a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
index 6ef629de51..10437b6802 100644
--- a/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
+++ b/apps/desktop/src/main/maker-ipc/botModelRouteReconciler.ts
@@ -3,6 +3,7 @@ import type { AgentKind } from '@cindy/maker-core';
import { normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';
interface RuntimeRoute {
+ agentDeviceId?: string | null;
agentKind: AgentKind;
model: string;
providerId: string | null;
@@ -31,6 +32,7 @@ function configuredRoute(
return {
agentKind: primary.harness === 'claude' ? 'claude-code' : primary.harness,
model: primary.model,
+ ...(primary.agentDeviceId ? { agentDeviceId: primary.agentDeviceId } : {}),
providerId: primary.providerId,
effort: primary.effort || null,
fastMode: primary.fastMode,
@@ -39,7 +41,7 @@ function configuredRoute(
function sameRoute(a: RuntimeRoute, b: RuntimeRoute): boolean {
return a.agentKind === b.agentKind && a.model === b.model && a.providerId === b.providerId
- && a.effort === b.effort && a.fastMode === b.fastMode;
+ && a.effort === b.effort && a.fastMode === b.fastMode && (a.agentDeviceId ?? null) === (b.agentDeviceId ?? null);
}
/** Apply the permanent profile through ordinary Session model/switch controls.
diff --git a/apps/desktop/src/main/maker-ipc/mcpHandlers.ts b/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
index 793a02f14d..fa5d2ee51b 100644
--- a/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
@@ -61,6 +61,7 @@ const listContextSchema = z.object({
botSessionId: z.string().min(1).optional(),
modelChain: z.array(z.object({
harness: z.enum(['claude', 'codex', 'pi']),
+ agentDeviceId: z.string().regex(/^[A-Za-z0-9_.:-]{1,128}$/).nullable().optional(),
model: z.string().trim().min(1),
providerId: z.string().nullable(),
effort: z.string(),
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 89b60ba954..8959893986 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -12181,6 +12181,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const session = maker.getSession(sessionId);
return session ? {
agentKind: makerToDbAgentKind(session.agentKind),
+ agentDeviceId: session.agentDeviceId ?? null,
model: session.model,
providerId: getSessionProvider(sessionId) ?? null,
effort: (getSessionEffort(sessionId) ?? undefined) as CreateOpts['effort'],
@@ -15005,6 +15006,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const [row] = await getDbClient()
.drizzle.select({
agentKind: sessions.agentKind,
+ agentDeviceId: sessions.agentDeviceId,
model: sessions.model,
providerId: sessions.providerId,
effort: sessions.effort,
@@ -15016,6 +15018,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (row) {
baseline = {
agentKind: dbToMakerAgentKind(row.agentKind),
+ agentDeviceId: row.agentDeviceId,
model: row.model,
providerId: row.providerId?.trim() || null,
effort: row.effort,
@@ -15031,6 +15034,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const control = getSessionRuntimeControlSnapshot(sessionId);
const live = maker.getSession(sessionId);
const effective: SessionRuntimeProfile = control.effectiveOverride ?? {
+ agentDeviceId: baseline.agentDeviceId,
agentKind: live?.agentKind ?? meta.agentKind,
model: live?.model ?? meta.model,
providerId: hasSessionProvider(sessionId)
@@ -15055,10 +15059,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
route: SessionRouteSelection,
currentAgentKind: AgentKind,
): Promise<void> => {
- // 未指定位置的调用方(伙伴模型)仍只管本机;IM 默认携带明确位置,允许跨电脑跟随。
+ // Legacy callers without a location must not move a remote session implicitly.
const currentDeviceId = await readSessionAgentDeviceId(sessionId);
if (route.agentDeviceId === undefined && currentDeviceId) return;
- if (route.agentKind !== currentAgentKind || currentDeviceId !== (route.agentDeviceId ?? null)) {
+ if (route.agentKind !== currentAgentKind || currentDeviceId !== (route.agentDeviceId ?? null) || currentDeviceId) {
await performSessionAgentSwitch(agentSwitchDeps, {
sessionId, targetAgentKind: route.agentKind, model: route.model,
providerId: route.providerId, effort: route.effort, fastMode: route.fastMode,
@@ -15165,6 +15169,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const [row] = await getDbClient().drizzle.select({
capabilitiesJson: botProfileVersions.capabilitiesJson,
agentKind: sessions.agentKind,
+ agentDeviceId: sessions.agentDeviceId,
model: sessions.model,
providerId: sessions.providerId,
effort: sessions.effort,
@@ -15197,6 +15202,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
chain: selection.chain,
followsCindyDefault: selection.followsCindyDefault,
current: {
+ agentDeviceId: row.agentDeviceId,
agentKind: live?.agentKind ?? dbToMakerAgentKind(row.agentKind),
model: live?.model ?? row.model ?? '',
providerId: live && hasSessionProvider(sessionId)
@@ -15205,13 +15211,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fastMode: live ? getSessionFastMode(sessionId) : !!row.fastMode,
},
hasRuntimeOverride: control.effectiveOverride !== null || control.pending !== null || !!intent,
- next: intent ? { agentKind: intent.targetAgentKind, model: intent.model,
+ next: intent ? { agentDeviceId: intent.targetAgentDeviceId === undefined ? row.agentDeviceId : intent.targetAgentDeviceId, agentKind: intent.targetAgentKind, model: intent.model,
providerId: intent.providerId ?? null, effort: intent.effort ?? null, fastMode: intent.fastMode ?? false }
: control.pending?.profile ?? control.effectiveOverride ?? undefined,
};
},
apply: async (sessionId, route, current) => {
- await stageSessionRouteSelection(sessionId, route, current.agentKind);
+ await stageSessionRouteSelection(sessionId, { ...route, agentDeviceId: route.agentDeviceId ?? null }, current.agentKind);
// Consume the same model/Harness intent as the normal send path. Its
// verified window protection and history handoff also apply here; a Bot
// settings save need not wait for a second user message. Busy runtimes
@@ -15355,7 +15361,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.from(sessions).where(eq(sessions.id, controlSessionId)).limit(1);
const route = nextBotModelRoute(
chain,
- { harness: currentHarness, model: current.model, providerId: current.providerId },
+ { harness: currentHarness, model: current.model, providerId: current.providerId, agentDeviceId: current.agentDeviceId },
control.visitedRoutes,
(candidate) => !controlSession?.remoteHostId || candidate.harness === currentHarness,
);
@@ -15364,6 +15370,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
candidate: route
? {
agentKind: toAgentKind(route.harness),
+ agentDeviceId: route.agentDeviceId ?? null,
model: route.model,
providerId: route.providerId,
effort: (route.effort || null) as SessionRuntimeProfile['effort'],
@@ -15426,10 +15433,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
try {
const profiles = await readSessionRuntimeProfiles(sessionId);
if (!profiles || !isCurrent()) return { session: null, outcome: 'superseded' };
- // 自动换模型的候选来自本机目录;Agent 在另一台电脑运行的任务不在本机换,照常重试原路由。
- if (await readSessionAgentDeviceId(sessionId)) {
- return { session: null, outcome: requireRouteChange ? 'exhausted' : 'unchanged' };
- }
// A previously accepted Agent/fallback mutation owns the next boundary.
// Do not let a later infrastructure retry replace that pending intent.
if (profiles.control.pending ||
@@ -15447,6 +15450,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
let currentForFallback = profiles.effective;
let candidate = botFallback.candidate;
if (!botFallback.isBot) {
+ if (await readSessionAgentDeviceId(sessionId)) return { session: null, outcome: requireRouteChange ? 'exhausted' : 'unchanged' };
if (requireRouteChange) return { session: null, outcome: 'exhausted' };
if (episodeAttempt < 2 || !readSessionRuntimeFallbackSettings().enabled) return { session: null, outcome: 'unchanged' };
const providers = await getDesktopProviderService().listProviders({
@@ -15554,7 +15558,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
return result;
});
- if (selected.agentKind !== currentForFallback.agentKind) {
+ if (selected.agentKind !== currentForFallback.agentKind
+ || (selected.agentDeviceId ?? null) !== (currentForFallback.agentDeviceId ?? null)
+ || selected.agentDeviceId) {
try {
const result = await withSendToSessionLock(sessionId, async () => {
if (!isCurrent() || !sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch) ||
@@ -15562,6 +15568,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const switched = await performSessionAgentSwitch(agentSwitchDeps, {
sessionId,
targetAgentKind: selected.agentKind,
+ agentDeviceId: selected.agentDeviceId ?? null,
model: selected.model,
providerId: selected.providerId,
effort: selected.effort,
diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
index 102ecf129e..fb93529331 100644
--- a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
@@ -1,3 +1,4 @@
+import { modelRouteLocationKey } from '@cindy/maker-shared/model-route';
import type { AgentKind, Effort } from '@cindy/maker-core';
import type { Session as RendererSession } from '../../renderer/lib/ccAgent.types';
import {
@@ -11,6 +12,7 @@ import {
export type SessionRuntimeMutationSource = 'agent' | 'fallback';
export interface SessionRuntimeProfile {
+ agentDeviceId?: string | null;
agentKind: AgentKind;
model: string;
providerId: string | null;
@@ -87,9 +89,9 @@ const states = new Map<string, SessionRuntimeControlState>();
let ownerEpoch = 0;
function routeKey(
- profile: Pick<SessionRuntimeProfile, 'agentKind' | 'providerId' | 'model'>,
+ profile: Pick<SessionRuntimeProfile, 'agentKind' | 'providerId' | 'model' | 'agentDeviceId'>,
): string {
- return `${profile.agentKind}\u0000${profile.providerId ?? ''}\u0000${profile.model}`;
+ return `${profile.agentKind}\u0000${profile.providerId ?? ''}\u0000${profile.model}${modelRouteLocationKey(profile.agentDeviceId)}`;
}
function stateFor(sessionId: string): SessionRuntimeControlState {
diff --git a/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts b/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts
index a758db4244..37b0ce8dfd 100644
--- a/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts
+++ b/apps/desktop/src/main/remote-agent/controller/deviceCatalog.ts
@@ -8,7 +8,7 @@
* 换模型、协同 Worker、定时任务的默认来源都只能落在这些供应商上。
*/
import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';
-import type { ProviderView } from '@cindy/model-providers';
+import { effectiveSourceIdForModel, getModel, isModelSelectableForNewRoute, type ProviderView, type AgentKind } from '@cindy/model-providers';
type RemoteInvoke = (
deviceId: string,
@@ -58,3 +58,23 @@ export async function readDeviceProviderViews(invoke: RemoteInvoke, deviceId: st
}
return parseDeviceProviderViews(result.result).filter((view) => view.remoteInvocationEnabled === true);
}
+
+/** 与普通任务共用授权目录;失败不回落到本机的同名供应商。 */
+export async function readRemoteProviderRoute(route: {
+ agentDeviceId: string;
+ agentKind: AgentKind;
+ providerId: string | null;
+ model: string;
+}) {
+ const { remoteBackgroundInvoke } = await import('../../device-link');
+ const providers = await readDeviceProviderViews(remoteBackgroundInvoke, route.agentDeviceId);
+ // 已有远程任务可以未指定来源;只在执行端授权目录内按原生默认规则解析。
+ // 显式来源失效仍拒绝,不换到另一个同名模型账号。
+ const providerId = route.providerId ?? effectiveSourceIdForModel(providers, null, route.model, route.agentKind);
+ const provider = providers.find((p) => p.id === providerId && p.connected && !p.suspended && p.agents.includes(route.agentKind));
+ const model = provider && getModel(provider, route.model, route.agentKind);
+ if (!provider || !model || !isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' })) {
+ throw new Error('[REMOTE_AGENT_UNAVAILABLE] Selected remote provider or model is unavailable.');
+ }
+ return { provider, model };
+}
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 2a6a914132..4f7ae75743 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -129,6 +129,7 @@ function syncNewMakerPrefs(appDefaultModelRequestId?: string) {
...(appDefaultModelRequestId ? { appDefaultModelRequestId } : {}),
ownerStamp: { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },
selectedRoute: {
+ ...(draft.agentDeviceId ? { agentDeviceId: draft.agentDeviceId } : {}),
harness: draft.vendor === 'cc' || draft.vendor === 'orca' ? 'claude' : draft.vendor,
providerId: selected.providerId ?? null,
model: selected.model,
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelRouteSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelRouteSelector.tsx
new file mode 100644
index 0000000000..50d7ca1267
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/ModelRouteSelector.tsx
@@ -0,0 +1,13 @@
+import type { ComponentProps } from 'react';
+import { ModelSelector } from './ModelSelector';
+import { useModelRouteDevices } from '@/hooks/useModelRouteDevices';
+
+/** Settings consume the same location catalog as ordinary tasks and workers. */
+export function ModelRouteSelector({ agentDeviceId, sshRemote, deviceId, ...props }:
+ ComponentProps<typeof ModelSelector> & { agentDeviceId?: string | null; sshRemote?: boolean }) {
+ const locations = useModelRouteDevices({ controlledDeviceId: deviceId ?? null,
+ leadAgentDeviceId: agentDeviceId, sshRemote });
+ return <ModelSelector {...props} deviceId={deviceId}
+ remoteAgent={locations.devices ? { devices: locations.devices,
+ selectedDeviceId: agentDeviceId ?? null, homeDeviceId: deviceId } : undefined} />;
+}
diff --git a/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx b/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx
index f1b359f326..edd219464f 100644
--- a/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx
@@ -2,7 +2,6 @@ import { Button } from '@/components/ui/button';
import { Fragment, useState, type ReactNode } from 'react';
import { ArrowDown, ArrowUp, Plus, Trash2 } from 'lucide-react';
-import { ModelSelector } from '@/components/new-chat/ModelSelector';
import { DefaultOverrideControls } from '@/components/settings/DefaultOverrideControls';
import {
SETTINGS_ROW_CLASS,
@@ -14,14 +13,13 @@ import { cn } from '@/lib/utils';
import type { AgentKind } from '@/hooks/useAgentCapabilities';
import { useDeviceProviders } from '@/hooks/useDeviceProviders';
import { providerAccountLabel, providerDisplayName } from '@/lib/providerDisplayName';
-import { useAvailableAgents } from '@/hooks/useAvailableAgents';
+import { ModelRouteSelector } from '@/components/new-chat/ModelRouteSelector';
import type { MakerVendor } from '@/lib/ccAgent.types';
import {
BOT_MODEL_CHAIN_MAX,
type BotHarness,
type BotModelRoute,
} from '../../../shared/botModelChain';
-import { getEffectiveBotModelSettings } from './botStore';
import { useBotTranslation } from './botPronounContext';
function vendorFor(harness: BotHarness): 'cc' | 'codex' | 'pi' {
@@ -36,10 +34,6 @@ function agentKindFor(vendor: 'cc' | 'codex' | 'pi'): AgentKind {
return vendor === 'cc' ? 'claude-code' : vendor;
}
-function defaultRoute(vendor: 'cc' | 'codex' | 'pi'): BotModelRoute {
- return { harness: harnessFor(vendor), ...getEffectiveBotModelSettings(vendor, null) };
-}
-
export function BotModelChainEditor({
value,
onChange: onValueChange,
@@ -74,7 +68,6 @@ export function BotModelChainEditor({
settingsRows?: { primaryLabel: string; primaryHint: string };
}) {
const { t } = useBotTranslation();
- const { availableVendors, loaded } = useAvailableAgents(deviceId);
const catalog = useDeviceProviders(deviceId);
const [expanded, setExpanded] = useState(false);
const [pendingRoute, setPendingRoute] = useState<BotModelRoute | null>(null);
@@ -83,22 +76,12 @@ export function BotModelChainEditor({
const onChange = (next: BotModelRoute[]) => {
if (!disabled) onValueChange(next);
};
- // Keep the local roster gate and SSH hiddenVendors contract. Device-link
- // rosters are advisory until loaded: a failed request must not block editing
- // the target device's independently loaded provider catalog.
- const waitingForLocalRoster = !remote && !deviceId && !loaded;
const visibleVendors = (['pi', 'codex', 'cc'] as const)
- .filter((vendor) => !hiddenVendors.includes(vendor))
- .filter(
- (vendor) =>
- (remote && !deviceId) ||
- (deviceId && !loaded) ||
- (loaded && availableVendors.has(vendor)),
- );
+ .filter((vendor) => !hiddenVendors.includes(vendor));
const unifiedAgents = visibleVendors.map(agentKindFor);
const replace = (index: number, patch: Partial<BotModelRoute>) => {
- if (disabled || waitingForLocalRoster) return;
+ if (disabled) return;
if (pendingRoute && index === routes.length) {
const next = { ...pendingRoute, ...patch };
if (next.model && routes.length < BOT_MODEL_CHAIN_MAX) {
@@ -126,18 +109,16 @@ export function BotModelChainEditor({
);
const vendor = unused ?? visibleVendors[0];
if (!vendor) return;
- const route = deviceId
- ? { harness: harnessFor(vendor), model: '', providerId: null, effort: '', fastMode: false }
- : defaultRoute(vendor);
- if (route.model) onChange([...routes, route]);
- else setPendingRoute(route);
+ setPendingRoute({ harness: harnessFor(vendor), model: '', providerId: null, effort: '', fastMode: false });
};
const picker = (route: BotModelRoute, index: number, wrapperClassName = 'min-w-0 flex-1') => (
<div className={wrapperClassName}>
- <ModelSelector
- disabled={disabled || waitingForLocalRoster}
+ <ModelRouteSelector
+ disabled={disabled}
deviceId={deviceId}
+ agentDeviceId={route.agentDeviceId}
+ sshRemote={remote && !deviceId}
vendorKey={vendorFor(route.harness)}
modelId={route.model}
effort={route.effort}
@@ -160,6 +141,7 @@ export function BotModelChainEditor({
if (!visibleVendors.includes(selection.engine)) return;
replace(index, {
harness: harnessFor(selection.engine),
+ ...(route.agentDeviceId || selection.agentDevice ? { agentDeviceId: selection.agentDevice?.deviceId ?? null } : {}),
providerId: selection.providerId,
model: selection.modelId,
effort: selection.effort ?? '',
@@ -168,7 +150,7 @@ export function BotModelChainEditor({
}}
unknownModelLabel={(model) => t('bots.modelUnavailable', { model })}
/>
- {deviceId && route.providerId
+ {deviceId && !route.agentDeviceId && route.providerId
? (() => {
const provider = catalog.providers.find((item) => item.id === route.providerId);
return provider ? (
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx
index 8065e82467..1d11bca6cd 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx
@@ -1,3 +1,4 @@
+import { serializeModelRoutes } from '@cindy/maker-shared/model-route';
import { useCallback, useEffect, useMemo, useRef, useState, type MutableRefObject } from 'react';
import { ArrowLeft, ChevronRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -550,7 +551,7 @@ function RemoteBotSettingsContent({ bot, beforeCloseRef, onDeleted, initialPage
if (!disabled && !revisionPendingRef.current)
setDraft((previous) => ({
...previous,
- modelChain: JSON.stringify(chain),
+ modelChain: serializeModelRoutes(chain),
followsDefault: false,
}));
}}
@@ -562,7 +563,7 @@ function RemoteBotSettingsContent({ bot, beforeCloseRef, onDeleted, initialPage
onChange={route => {
if (!disabled && !revisionPendingRef.current) setDraft(previous => ({ ...previous,
taskFollowsPrimary: route === null,
- taskModel: JSON.stringify(route ? [route] : readRemoteBotModelChain(previous.modelChain).slice(0, 1)),
+ taskModel: serializeModelRoutes(route ? [route] : readRemoteBotModelChain(previous.modelChain).slice(0, 1)),
}));
}} />}
</>
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botModelChainEditor.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botModelChainEditor.test.tsx
index 85c6429ce4..6713ffa897 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botModelChainEditor.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botModelChainEditor.test.tsx
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
+vi.mock('@/hooks/useModelRouteDevices', () => ({ useModelRouteDevices: () => ({ devices: [{ deviceId: 'share:one', name: 'Shared account' }] }) }));
vi.mock('@/hooks/useDeviceProviders', () => ({ useDeviceProviders: () => ({ providers: [] }) }));
@@ -155,7 +156,9 @@ describe('BotModelChainEditor', () => {
expect(fallbacks.queryByTestId('model-selector-primary-model')).toBeNull();
expect(fallbacks.queryByLabelText('bots.modelChain.remove')).toBeNull();
fireEvent.click(fallbacks.getByText('bots.modelChain.add'));
- expect(onChange).toHaveBeenLastCalledWith([primary, expect.objectContaining({ model: 'default-model' })]);
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.click(within(fallbacks.getByTestId('model-selector-')).getByText('choose-official-codex-model'));
+ expect(onChange).toHaveBeenLastCalledWith([primary, expect.objectContaining({ model: 'gpt-5.6-sol' })]);
});
it('uses the standard configurable picker for the current harness', () => {
@@ -219,65 +222,24 @@ describe('BotModelChainEditor', () => {
expect(onChange).toHaveBeenCalledWith([{ harness: 'codex', providerId: 'openai', model: 'gpt-5.6-sol', effort: 'medium', fastMode: true }]);
});
- it('filters both first-route selection and added fallbacks with the local runtime roster', () => {
- roster.availableVendors = new Set(['codex']);
- const onChange = vi.fn();
- const view = render(<BotModelChainEditor value={[]} onChange={onChange} />);
- expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual(['codex']);
- // A callback from a now-hidden row must not create an unavailable override.
- fireEvent.click(screen.getByText('choose-official-claude-model'));
- expect(onChange).not.toHaveBeenCalled();
- const details = view.container.querySelector('details')!;
- details.open = true;
- fireEvent(details, new Event('toggle'));
- fireEvent.click(screen.getByText('bots.modelChain.add'));
- expect(onChange).toHaveBeenCalledWith([expect.objectContaining({ harness: 'codex' })]);
- });
-
- it('does not fabricate a Pi fallback when no runtime is installed', () => {
+ it('allows shared models without a locally installed harness and waits for an explicit backup choice', () => {
roster.availableVendors = new Set();
+ roster.loaded = false;
const onChange = vi.fn();
const view = render(<BotModelChainEditor value={[]} onChange={onChange} />);
- expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual([]);
+ const props = modelSelectorProps.mock.lastCall?.[0];
+ expect(props).toMatchObject({ disabled: false, unifiedAgents: ['pi', 'codex', 'claude-code'],
+ remoteAgent: { devices: [{ deviceId: 'share:one', name: 'Shared account' }] } });
+ props.onUnifiedSelect({ engine: 'codex', modelId: 'remote-model', providerId: 'openai', effort: 'medium', fast: false,
+ agentDevice: { deviceId: 'share:one', name: 'Shared account' } });
+ expect(onChange).toHaveBeenLastCalledWith([{ harness: 'codex', model: 'remote-model', providerId: 'openai',
+ effort: 'medium', fastMode: false, agentDeviceId: 'share:one' }]);
+ onChange.mockClear();
const details = view.container.querySelector('details')!;
details.open = true;
fireEvent(details, new Event('toggle'));
- const add = screen.getByText('bots.modelChain.add') as HTMLButtonElement;
- expect(add.disabled).toBe(true);
- fireEvent.click(add);
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it('refreshes runtime filtering after installation without rewriting an existing route', () => {
- roster.availableVendors = new Set(['codex']);
- const onChange = vi.fn();
- const route = { harness: 'pi' as const, model: 'saved-pi', providerId: 'custom', effort: '', fastMode: false };
- const view = render(<BotModelChainEditor value={[route]} onChange={onChange} />);
- expect(modelSelectorProps.mock.lastCall?.[0]).toMatchObject({ modelId: 'saved-pi', unifiedAgents: ['codex'] });
- roster.availableVendors = new Set(['pi', 'codex']);
- view.rerender(<BotModelChainEditor value={[route]} onChange={onChange} />);
- expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual(['pi', 'codex']);
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it('blocks unknown local runtimes until the roster loads and preserves remote filtering', () => {
- roster.availableVendors = new Set();
- roster.loaded = false;
- const onChange = vi.fn();
- const view = render(<BotModelChainEditor value={[]} onChange={onChange} />);
- expect(modelSelectorProps.mock.lastCall?.[0]).toMatchObject({ unifiedAgents: [], disabled: true });
- fireEvent.click(screen.getByText('choose-official-codex-model'));
- fireEvent.click(screen.getByText('set-high-effort'));
- fireEvent.click(screen.getByText('enable-fast-mode'));
+ fireEvent.click(screen.getByText('bots.modelChain.add'));
expect(onChange).not.toHaveBeenCalled();
- roster.availableVendors = new Set(['codex']);
- roster.loaded = true;
- view.rerender(<BotModelChainEditor value={[]} onChange={onChange} />);
- fireEvent.click(screen.getByText('choose-official-codex-model'));
- expect(onChange).toHaveBeenCalledWith([expect.objectContaining({ harness: 'codex' })]);
- roster.loaded = true;
- view.rerender(<BotModelChainEditor value={[]} onChange={vi.fn()} remote hiddenVendors={['codex']} />);
- expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual(['pi', 'claude-code']);
});
it('writes depth and fast mode to the selected route without changing its model', () => {
@@ -320,20 +282,20 @@ describe('BotModelChainEditor', () => {
roster.availableVendors = new Set(['codex']);
onChange.mockClear();
view.rerender(<BotModelChainEditor {...props} hiddenVendors={['pi']} />);
- expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual(['codex']);
+ expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual(['codex', 'claude-code']);
expect(onChange).not.toHaveBeenCalled();
fireEvent.click(screen.getByText('choose-official-claude-model'));
- expect(onChange).not.toHaveBeenCalled();
+ expect(onChange).toHaveBeenCalledWith([expect.objectContaining({ harness: 'claude' })]);
});
- it('keeps an explicitly empty remote roster authoritative', () => {
+ it('keeps remote catalog selection available when the home roster is empty', () => {
roster.availableVendors = new Set();
const onChange = vi.fn();
const view = render(<BotModelChainEditor deviceId="remote-host" value={[]} onChange={onChange} />);
- expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual([]);
- expect((expand(view.container).getByText('bots.modelChain.add') as HTMLButtonElement).disabled).toBe(true);
+ expect(modelSelectorProps.mock.lastCall?.[0].unifiedAgents).toEqual(['pi', 'codex', 'claude-code']);
+ expect((expand(view.container).getByText('bots.modelChain.add') as HTMLButtonElement).disabled).toBe(false);
fireEvent.click(screen.getByText('choose-official-codex-model'));
- expect(onChange).not.toHaveBeenCalled();
+ expect(onChange).toHaveBeenCalledWith([expect.objectContaining({ harness: 'codex' })]);
});
it('honors disabled remote settings even with an unknown roster', () => {
diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.ts
index e0972bcec6..903e11eb5b 100644
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@ -254,7 +254,7 @@ function getDefaultModelInputs() {
const draft = getDraftForPreferenceSync();
return {
visibilityVersion: getModelVisibilityVersion(),
- preference: JSON.stringify([draft.vendor, draft.lastByVendor[draft.vendor], draft.fastModeByModel]),
+ preference: JSON.stringify([draft.vendor, draft.lastByVendor[draft.vendor], draft.fastModeByModel, draft.agentDeviceId]),
providers: getCachedProvidersSnapshot(),
availableAgents: getCachedAvailableVendors(),
};
@@ -379,6 +379,7 @@ export function getEffectiveBotModelChain(
return defaultBotModelChain({ providers: providers?.providers ?? [],
isModelEnabled,
preferredRoute: {
+ ...(draft.agentDeviceId ? { agentDeviceId: draft.agentDeviceId } : {}),
harness: draft.vendor === 'cc' || draft.vendor === 'orca' ? 'claude' : draft.vendor,
providerId: selected.providerId ?? null, model: selected.model,
effort: selected.effort ?? '', fastMode: draft.fastModeByModel[selected.model] === true,
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts
index 222b1f2cfb..0cc2fb61b2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useWorkerAgentDevices.ts
@@ -1,75 +1,3 @@
-/**
- * 协同 Worker 可以放 Agent 的其他电脑与分享(远程供应商),给「创建 Worker」面板的模型选择器用。
- *
- * 与任务输入框同一套候选:本机 Lead 列在线的同账号电脑(当前位置掉线也保留)与收到的分享;远程
- * 控制的被控电脑上的 Lead 列被控电脑之外的同账号电脑与两端都可用的分享。分享按账号授予,
- * 不要求 Lead 已经在该分享上运行;暂停或已删除的分享只保留当前位置。
- * 远程控制时 Lead 的 Agent 在控制端读不到目录的地方(控制端自己、只有被控电脑收到的分享):与任务输入框
- * 一样维持被控电脑的目录、不列远程供应商,Worker 跟 Lead(返回的 leadAgentDeviceId 为 null)。
- * devices 为 undefined = 不提供(Lead 归属未解析、SSH Lead、上面这种读不到的情况)。
- */
-import { useMemo } from 'react';
-
-import { useAuth } from '@/contexts/AuthContext';
-import { useSelectableDevices } from '@/hooks/useControllableDevices';
-import {
- controlledTaskAgentLocationReadable,
- controlledTaskReadableShareIds,
- selectControlledTaskAgentDevices,
-} from '@/lib/controlledTaskAgentLocation';
-import { useProviderShareAgentDevices } from '@/features/provider-share/useProviderShareAgentDevices';
-
-export interface WorkerAgentDevices {
- /** 面板默认选中、并按它读模型目录的 Lead 位置;null = 任务所在电脑。 */
- leadAgentDeviceId: string | null;
- devices: readonly { deviceId: string; name: string }[] | undefined;
-}
-
-export function useWorkerAgentDevices(input: {
- /** Lead 任务所在的被控电脑:string = 被控电脑,null = 本机,undefined = 尚未解析。 */
- controlledDeviceId: string | null | undefined;
- /** Lead 的 Agent 所在电脑(或分享);null / undefined = 任务所在电脑。 */
- leadAgentDeviceId: string | null | undefined;
- sshRemote?: boolean;
-}): WorkerAgentDevices {
- const { controlledDeviceId, sshRemote } = input;
- const lead = input.leadAgentDeviceId ?? null;
- const { deviceId: selfDeviceId } = useAuth();
- const { devices: selectableDevices } = useSelectableDevices();
- const { devices: shareDevices, isReceived } = useProviderShareAgentDevices([lead], controlledDeviceId);
- return useMemo(() => {
- if (controlledDeviceId === undefined || sshRemote) return { leadAgentDeviceId: lead, devices: undefined };
- if (controlledDeviceId) {
- const readableShareIds = controlledTaskReadableShareIds({
- agentDeviceId: lead,
- pendingAgentDeviceId: null,
- isReceived,
- });
- const readable = controlledTaskAgentLocationReadable({
- agentDeviceId: lead,
- pendingAgentDeviceId: null,
- selfDeviceId: selfDeviceId ?? null,
- ...(readableShareIds ? { readableShareIds } : {}),
- });
- if (!readable) return { leadAgentDeviceId: null, devices: undefined };
- return {
- leadAgentDeviceId: lead,
- devices: selectControlledTaskAgentDevices({
- devices: selectableDevices,
- controlledDeviceId,
- keepDeviceIds: [lead],
- shareDevices,
- }),
- };
- }
- return {
- leadAgentDeviceId: lead,
- devices: [
- ...selectableDevices
- .filter((device) => device.online || device.deviceId === lead)
- .map(({ deviceId, name }) => ({ deviceId, name })),
- ...shareDevices,
- ],
- };
- }, [controlledDeviceId, isReceived, lead, selectableDevices, selfDeviceId, shareDevices, sshRemote]);
-}
+/** Workers and settings use the same task-scoped model locations. */
+export { useModelRouteDevices as useWorkerAgentDevices } from '@/hooks/useModelRouteDevices';
+export type { ModelRouteDevices as WorkerAgentDevices } from '@/hooks/useModelRouteDevices';
diff --git a/apps/desktop/src/renderer/hooks/useModelRouteDevices.ts b/apps/desktop/src/renderer/hooks/useModelRouteDevices.ts
new file mode 100644
index 0000000000..b9c6976d62
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useModelRouteDevices.ts
@@ -0,0 +1,75 @@
+/**
+ * 任务、Worker 与模型设置共用的执行位置候选:其他电脑与分享(远程供应商)。
+ *
+ * 与任务输入框同一套候选:本机 Lead 列在线的同账号电脑(当前位置掉线也保留)与收到的分享;远程
+ * 控制的被控电脑上的 Lead 列被控电脑之外的同账号电脑与两端都可用的分享。分享按账号授予,
+ * 不要求 Lead 已经在该分享上运行;暂停或已删除的分享只保留当前位置。
+ * 远程控制时 Lead 的 Agent 在控制端读不到目录的地方(控制端自己、只有被控电脑收到的分享):与任务输入框
+ * 一样维持被控电脑的目录、不列远程供应商,Worker 跟 Lead(返回的 leadAgentDeviceId 为 null)。
+ * devices 为 undefined = 不提供(Lead 归属未解析、SSH Lead、上面这种读不到的情况)。
+ */
+import { useMemo } from 'react';
+
+import { useAuth } from '@/contexts/AuthContext';
+import { useSelectableDevices } from '@/hooks/useControllableDevices';
+import {
+ controlledTaskAgentLocationReadable,
+ controlledTaskReadableShareIds,
+ selectControlledTaskAgentDevices,
+} from '@/lib/controlledTaskAgentLocation';
+import { useProviderShareAgentDevices } from '@/features/provider-share/useProviderShareAgentDevices';
+
+export interface ModelRouteDevices {
+ /** 面板默认选中、并按它读模型目录的 Lead 位置;null = 任务所在电脑。 */
+ leadAgentDeviceId: string | null;
+ devices: readonly { deviceId: string; name: string }[] | undefined;
+}
+
+export function useModelRouteDevices(input: {
+ /** Lead 任务所在的被控电脑:string = 被控电脑,null = 本机,undefined = 尚未解析。 */
+ controlledDeviceId: string | null | undefined;
+ /** Lead 的 Agent 所在电脑(或分享);null / undefined = 任务所在电脑。 */
+ leadAgentDeviceId: string | null | undefined;
+ sshRemote?: boolean;
+}): ModelRouteDevices {
+ const { controlledDeviceId, sshRemote } = input;
+ const lead = input.leadAgentDeviceId ?? null;
+ const { deviceId: selfDeviceId } = useAuth();
+ const { devices: selectableDevices } = useSelectableDevices();
+ const { devices: shareDevices, isReceived } = useProviderShareAgentDevices([lead], controlledDeviceId);
+ return useMemo(() => {
+ if (controlledDeviceId === undefined || sshRemote) return { leadAgentDeviceId: lead, devices: undefined };
+ if (controlledDeviceId) {
+ const readableShareIds = controlledTaskReadableShareIds({
+ agentDeviceId: lead,
+ pendingAgentDeviceId: null,
+ isReceived,
+ });
+ const readable = controlledTaskAgentLocationReadable({
+ agentDeviceId: lead,
+ pendingAgentDeviceId: null,
+ selfDeviceId: selfDeviceId ?? null,
+ ...(readableShareIds ? { readableShareIds } : {}),
+ });
+ if (!readable) return { leadAgentDeviceId: null, devices: undefined };
+ return {
+ leadAgentDeviceId: lead,
+ devices: selectControlledTaskAgentDevices({
+ devices: selectableDevices,
+ controlledDeviceId,
+ keepDeviceIds: [lead],
+ shareDevices,
+ }),
+ };
+ }
+ return {
+ leadAgentDeviceId: lead,
+ devices: [
+ ...selectableDevices
+ .filter((device) => device.online || device.deviceId === lead)
+ .map(({ deviceId, name }) => ({ deviceId, name })),
+ ...shareDevices,
+ ],
+ };
+ }, [controlledDeviceId, isReceived, lead, selectableDevices, selfDeviceId, shareDevices, sshRemote]);
+}
diff --git a/apps/desktop/src/shared/__tests__/botModelChain.test.ts b/apps/desktop/src/shared/__tests__/botModelChain.test.ts
index ee4ebfa1ad..1d085d8db3 100644
--- a/apps/desktop/src/shared/__tests__/botModelChain.test.ts
+++ b/apps/desktop/src/shared/__tests__/botModelChain.test.ts
@@ -1,3 +1,4 @@
+import { serializeModelRoutes } from '@cindy/maker-shared/model-route';
import { describe, expect, it } from 'vitest';
import {
@@ -145,3 +146,23 @@ describe('Bot model chain', () => {
).toBeNull();
});
});
+
+// Regression: shared/local accounts used to collapse to the same candidate and lose their location.
+it('preserves locations through persistence and ordered fallback', () => {
+ const local = { harness: 'codex' as const, model: 'same-model', providerId: 'openai', effort: 'medium', fastMode: false };
+ const shared = { ...local, agentDeviceId: 'share:one' };
+ const other = { ...local, agentDeviceId: 'device-two' };
+ const chain = normalizeBotModelChain(JSON.parse(JSON.stringify([shared, local, other, shared])));
+ expect(chain).toEqual([shared, local, other]);
+ expect(nextBotModelRoute(chain, shared)).toEqual(local);
+ expect(nextBotModelRoute(chain, local)).toEqual(other);
+ expect(nextBotModelRoute(chain, other)).toBeNull();
+});
+
+it('round trips remote forms without exposing a same-named local source to older peers', () => {
+ const route = { harness: 'codex' as const, model: 'same-model', providerId: 'openai', effort: '', fastMode: false, agentDeviceId: 'share:one' };
+ const wire = JSON.parse(serializeModelRoutes([route]));
+ expect(wire[0].providerId).not.toBe('openai');
+ delete wire[0].agentDeviceId; // old editors keep providerId but strip unknown fields
+ expect(normalizeBotModelChain(wire)).toEqual([route]);
+});
diff --git a/apps/desktop/src/shared/appDefaultModelSelection.ts b/apps/desktop/src/shared/appDefaultModelSelection.ts
index 49df32e46e..bf74de7c35 100644
--- a/apps/desktop/src/shared/appDefaultModelSelection.ts
+++ b/apps/desktop/src/shared/appDefaultModelSelection.ts
@@ -13,5 +13,5 @@ export interface AppDefaultModelSelection {
export function sameModelRoute(a: BotModelRoute | null | undefined, b: BotModelRoute | null | undefined): boolean {
if (!a || !b) return !a && !b;
return a.harness === b.harness && a.providerId === b.providerId && a.model === b.model
- && a.effort === b.effort && a.fastMode === b.fastMode;
+ && a.effort === b.effort && a.fastMode === b.fastMode && (a.agentDeviceId ?? null) === (b.agentDeviceId ?? null);
}
diff --git a/apps/desktop/src/shared/botDefaultModelChain.ts b/apps/desktop/src/shared/botDefaultModelChain.ts
index 7f5cb85838..b04bf887fa 100644
--- a/apps/desktop/src/shared/botDefaultModelChain.ts
+++ b/apps/desktop/src/shared/botDefaultModelChain.ts
@@ -7,6 +7,8 @@ export function defaultBotModelChain(
args: Parameters<typeof resolveNewMakerDefaultTuples>[0] & { preferredRoute?: BotModelRoute | null },
): BotModelRoute[] {
const preferred = args.preferredRoute;
+ // Remote selections are validated against their own authorized catalog in Main.
+ if (preferred?.agentDeviceId) return [];
if (preferred && !args.providersLoading && args.availableAgentsLoaded) {
const agent = preferred.harness === 'claude' ? 'claude-code' : preferred.harness;
const vendor = agent === 'claude-code' ? 'cc' : agent;
diff --git a/apps/desktop/src/shared/botModelChain.ts b/apps/desktop/src/shared/botModelChain.ts
index 73f230def2..0fa5c939ab 100644
--- a/apps/desktop/src/shared/botModelChain.ts
+++ b/apps/desktop/src/shared/botModelChain.ts
@@ -1,43 +1,24 @@
+import { normalizeModelRoute, modelRouteLocationKey, type ModelRoute } from '@cindy/maker-shared/model-route';
+
export const BOT_MODEL_CHAIN_MAX = 5;
export type BotHarness = 'claude' | 'codex' | 'pi';
-/** One complete, ordered Bot runtime route. */
-export interface BotModelRoute {
- harness: BotHarness;
- model: string;
- providerId: string | null;
- effort: string;
- fastMode: boolean;
-}
+export type BotModelRoute = ModelRoute;
/** Runtime-control uses the same full route identity as the Bot editor. */
export function botModelRouteRuntimeKey(
- route: Pick<BotModelRoute, 'harness' | 'providerId' | 'model'>,
+ route: Pick<BotModelRoute, 'harness' | 'providerId' | 'model' | 'agentDeviceId'>,
): string {
const agentKind = route.harness === 'claude' ? 'claude-code' : route.harness;
- return `${agentKind}\u0000${route.providerId ?? ''}\u0000${route.model}`;
+ return `${agentKind}\u0000${route.providerId ?? ''}\u0000${route.model}${modelRouteLocationKey(route.agentDeviceId)}`;
}
export function normalizeBotHarness(value: unknown): BotHarness {
return value === 'codex' || value === 'pi' || value === 'claude' ? value : 'claude';
}
-export function normalizeBotModelRoute(value: unknown): BotModelRoute | null {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- const record = value as Record<string, unknown>;
- if (typeof record.model !== 'string' || !record.model.trim()) return null;
- return {
- harness: normalizeBotHarness(record.harness),
- model: record.model.trim(),
- providerId:
- typeof record.providerId === 'string' && record.providerId.trim()
- ? record.providerId.trim()
- : null,
- effort: typeof record.effort === 'string' ? record.effort : '',
- fastMode: record.fastMode === true,
- };
-}
+export const normalizeBotModelRoute = normalizeModelRoute;
/** Optional task-specific route. Absence inherits the live primary route, never a stored copy. */
export function readBotTaskModelOverride(value: unknown): BotModelRoute | null {
@@ -69,7 +50,7 @@ export function normalizeBotModelChain(
}
const seen = new Set<string>();
return candidates.filter((item) => {
- const key = `${item.harness}\u0000${item.providerId ?? ''}\u0000${item.model}`;
+ const key = `${item.harness}\u0000${item.providerId ?? ''}\u0000${item.model}${modelRouteLocationKey(item.agentDeviceId)}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
@@ -89,12 +70,13 @@ export function primaryBotModelRoute(
*/
export function botModelRouteIndex(
chain: readonly BotModelRoute[],
- current: Pick<BotModelRoute, 'harness' | 'model' | 'providerId'>,
+ current: Pick<BotModelRoute, 'harness' | 'model' | 'providerId' | 'agentDeviceId'>,
): number {
const exact = chain.findIndex((route) =>
route.harness === current.harness
&& route.model === current.model
- && route.providerId === current.providerId);
+ && route.providerId === current.providerId
+ && (route.agentDeviceId ?? null) === (current.agentDeviceId ?? null));
if (exact >= 0) return exact;
// A null provider is a single explicit "let the harness resolve it" route,
// not a wildcard over every source serving the same model. Prefer a real
@@ -104,18 +86,20 @@ export function botModelRouteIndex(
.filter(({ route }) =>
route.harness === current.harness
&& route.model === current.model
- && route.providerId === null);
+ && route.providerId === null
+ && (route.agentDeviceId ?? null) === (current.agentDeviceId ?? null));
if (implicitMatches.length === 1) return implicitMatches[0]!.index;
const legacyMatches = chain
.map((route, index) => ({ route, index }))
- .filter(({ route }) => route.harness === current.harness && route.model === current.model);
+ .filter(({ route }) => route.harness === current.harness && route.model === current.model
+ && (route.agentDeviceId ?? null) === (current.agentDeviceId ?? null));
return legacyMatches.length === 1 ? legacyMatches[0]!.index : -1;
}
/** Select the next explicit route; never invent one from the global catalog. */
export function nextBotModelRoute(
value: unknown,
- current: Pick<BotModelRoute, 'harness' | 'model' | 'providerId'>,
+ current: Pick<BotModelRoute, 'harness' | 'model' | 'providerId' | 'agentDeviceId'>,
visitedRoutes: readonly string[] = [],
isUsable: (route: BotModelRoute) => boolean = () => true,
): BotModelRoute | null {
diff --git a/apps/mobile/src/__tests__/CompanionModelChain.test.tsx b/apps/mobile/src/__tests__/CompanionModelChain.test.tsx
index 44e1279889..605d7d78d9 100644
--- a/apps/mobile/src/__tests__/CompanionModelChain.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionModelChain.test.tsx
@@ -1,3 +1,4 @@
+vi.mock('@/session/useRemoteAgentCatalogs', () => ({ useRemoteAgentCatalogs: () => [] }));
// @vitest-environment jsdom
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
@@ -184,5 +185,14 @@ it("passes the full account, engine, effort and fast route back from the unified
effort: "high",
fast: true,
});
- expect(select).toHaveBeenCalledWith(route);
+ expect(select).toHaveBeenCalledWith({ ...route, agentDeviceId: null });
+});
+
+it('keeps the selected shared location in the complete route', async () => {
+ const select = vi.fn(() => true);
+ await act(async () => root.render(createElement(CompanionModelPicker, {
+ visible: true, deviceId: 'remote-mac', onClose() {}, onClosed() {}, onSelect: select,
+ })));
+ await h.picker.unified.onSelect({ agent: 'codex', modelId: 'gpt-6', providerId: 'openai:second', effort: 'high', fast: true }, { deviceId: 'share:one' });
+ expect(select).toHaveBeenCalledWith({ ...route, agentDeviceId: 'share:one' });
});
diff --git a/apps/mobile/src/session/CompanionModelChain.tsx b/apps/mobile/src/session/CompanionModelChain.tsx
index b9a9a4c1ff..a0ca5d39ea 100644
--- a/apps/mobile/src/session/CompanionModelChain.tsx
+++ b/apps/mobile/src/session/CompanionModelChain.tsx
@@ -1,3 +1,4 @@
+import { serializeModelRoutes, normalizeModelRoute, type ModelRoute } from '@cindy/maker-shared/model-route';
import { findCatalogModel } from '@cindy/model-providers';
import { buildMobileModelSections } from './providerModelSections';
import { mobileProviderAccountTitle } from './mobileModelRowPresentation';
@@ -17,13 +18,15 @@ import { ModelPickerSheet } from './ModelPickerSheet';
import { normalizeMobileAgentCapabilities } from './agentCapabilities';
import type { MobileModelConfiguration } from './unifiedMobileModels';
import type { ProfileValues } from './companionProfileData';
-export interface CompanionModelRoute { harness: 'claude' | 'codex' | 'pi'; model: string; providerId: string | null; effort: string; fastMode: boolean }
+import { useRemoteAgentCatalogs } from './useRemoteAgentCatalogs';
+export type CompanionModelRoute = ModelRoute;
export function readCompanionModelChain(value: unknown): CompanionModelRoute[] {
if (typeof value !== 'string') return [];
try {
const rows: unknown = JSON.parse(value);
if (!Array.isArray(rows) || rows.length > 5 || rows.some(r => !r || !['claude', 'codex', 'pi'].includes(r.harness) || typeof r.model !== 'string' || !r.model || !(typeof r.providerId === 'string' || r.providerId === null) || typeof r.effort !== 'string' || typeof r.fastMode !== 'boolean')) return [];
- return rows;
+ const normalized = rows.map(normalizeModelRoute);
+ return normalized.every((row): row is ModelRoute => row !== null) ? normalized : [];
} catch { return []; }
}
export function CompanionModelChain({ deviceId, values, onChange, onPick, disabled, single = false, inheritanceLabel }: { deviceId: string; values: ProfileValues; onChange(values: ProfileValues): void; onPick(index: number): void; disabled: boolean; single?: boolean; inheritanceLabel?: string }) {
@@ -32,16 +35,20 @@ export function CompanionModelChain({ deviceId, values, onChange, onPick, disabl
// Only a ready catalog for this device may name a route. Never borrow a cached other-device account.
const providers = catalog.ready ? catalog.providers : [];
const chain = readCompanionModelChain(values.modelChain);
+ const routeCatalogs = useRemoteAgentCatalogs({ enabled: chain.some(route => !!route.agentDeviceId),
+ controlledDeviceId: deviceId, keepDeviceIds: chain.flatMap(route => route.agentDeviceId ? [route.agentDeviceId] : []), keepOnly: true });
const following = values.followsDefault === true;
- const update = (chain: CompanionModelRoute[]) => onChange({ ...values, modelChain: JSON.stringify(chain) });
+ const update = (chain: CompanionModelRoute[]) => onChange({ ...values, modelChain: serializeModelRoutes(chain) });
const [showBackups, setShowBackups] = useState(false);
const routeRow = (route: CompanionModelRoute, index: number) => {
const agent = route.harness === 'claude' ? 'claude-code' : route.harness;
- const providerId = route.providerId ?? buildMobileModelSections({ providers, agentKind: agent, selectedModelId: route.model, selectedProviderId: null, existingSessionRoute: true, visibilityOverrides: catalog.modelVisibilityOverrides }).activeSourceId;
- const provider = providers.find(item => item.id === providerId);
+ const remote = route.agentDeviceId ? routeCatalogs.find(item => item.deviceId === route.agentDeviceId) : undefined;
+ const routeProviders = route.agentDeviceId ? remote?.providers ?? [] : providers;
+ const providerId = route.providerId ?? buildMobileModelSections({ providers: routeProviders, agentKind: agent, selectedModelId: route.model, selectedProviderId: null, existingSessionRoute: true, visibilityOverrides: catalog.modelVisibilityOverrides }).activeSourceId;
+ const provider = routeProviders.find(item => item.id === providerId);
const model = provider ? findCatalogModel(provider, route.model, agent) : undefined;
- const source = provider ? mobileProviderAccountTitle(provider) : route.providerId;
- return <View key={`${route.harness}:${route.providerId}:${route.model}`} style={styles.row}>
+ const source = [provider ? mobileProviderAccountTitle(provider) : route.providerId, remote?.name].filter(Boolean).join(' · ');
+ return <View key={JSON.stringify([route.agentDeviceId ?? null, route.harness, route.providerId, route.model])} style={styles.row}>
<Pressable accessibilityRole="button" disabled={disabled || following} onPress={() => onPick(index)} style={[styles.row, { flex: 1 }]}>
<Text style={{ ...styles.value, color: colors.textSecondary }}>{index + 1}</Text><View style={{ flex: 1 }}><Text style={{ ...styles.title, color: colors.textPrimary }}>{model?.name ?? route.model}</Text><Text style={{ color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption }}>{[source, route.harness === 'claude' ? 'Claude Code' : route.harness === 'codex' ? 'Codex' : 'Pi', route.effort ? t(`models.options.effortLevels.${route.effort}`, { defaultValue: route.effort }) : '', route.fastMode ? 'Fast' : ''].filter(Boolean).join(' · ')}</Text></View><ChevronRight size={iconSize.lg} color={colors.textTertiary} strokeWidth={iconStroke.regular} />
</Pressable>
@@ -71,14 +78,16 @@ export function CompanionModelPicker({ visible, deviceId, route, onClose, onClos
const { user } = useAuth(); const { t } = useTranslation();
const catalog = useDeviceProviders(visible ? deviceId : undefined, visible);
const maker = useMobileMakerTransport(deviceId);
+ const remoteCatalogs = useRemoteAgentCatalogs({ enabled: visible, controlledDeviceId: deviceId,
+ keepDeviceIds: route?.agentDeviceId ? [route.agentDeviceId] : [] });
const agent = route?.harness === 'claude' ? 'claude-code' : route?.harness ?? 'pi';
- const select = async (config: MobileModelConfiguration) => onSelect({ harness: config.agent === 'claude-code' ? 'claude' : config.agent, model: config.modelId, providerId: config.providerId, effort: config.effort, fastMode: config.fast });
+ const select = async (config: MobileModelConfiguration, source?: { deviceId: string | null }) => onSelect({ agentDeviceId: source?.deviceId ?? null, harness: config.agent === 'claude-code' ? 'claude' : config.agent, model: config.modelId, providerId: config.providerId, effort: config.effort, fastMode: config.fast });
return <ModelPickerSheet visible={visible} onClose={onClose} onClosed={onClosed} providers={catalog.ready ? catalog.providers : []}
modelVisibilityOverrides={catalog.modelVisibilityOverrides} providersReady={catalog.ready}
flatOptions={[]} agentKind={agent} capabilities={null} activeModelId={route?.model ?? ''} selectedProviderId={route?.providerId ?? null}
selectedEffort={route?.effort ?? ''} selectedFastMode={route?.fastMode ?? false} existingSessionRoute
disabled={!catalog.ready} loading={catalog.loading} emptyHint={catalog.error ?? t('devices.companionProfile.modelsUnavailable')}
- unified={{ scope: JSON.stringify([user?.id, deviceId]), agents: ['claude-code', 'codex', 'pi'],
+ unified={{ remote: { catalogs: remoteCatalogs, selectedDeviceId: route?.agentDeviceId ?? null, hostDeviceId: deviceId }, scope: JSON.stringify([user?.id, deviceId]), agents: ['claude-code', 'codex', 'pi'],
loadCapabilities: async agent => { const value = normalizeMobileAgentCapabilities(await maker.getCapabilities(agent)); if (!value) throw new Error('Capabilities unavailable'); return value; }, onSelect: select }}
onSelectFlatModel={() => {}} onSelectProviderRow={() => {}} permissionOptions={[]} activePermissionMode="ask" onSelectPermissionMode={() => {}} hidePermissionTrigger keyboardAvoidingBehavior="padding" />;
}
diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsx
index b1d7c7e09c..f3597be933 100644
--- a/apps/mobile/src/session/CompanionProfileSheet.tsx
+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx
@@ -1,3 +1,4 @@
+import { serializeModelRoutes } from '@cindy/maker-shared/model-route';
import { CompanionImportSheet } from './CompanionImportSheet';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'expo-router';
@@ -306,7 +307,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
const changeValues = (next: ProfileValues) => { if (!editing) draftBase.current = panel?.values ?? {}; setValues(next); setEditing(true); };
const taskValues = {
modelChain: modelValues.taskFollowsPrimary === true
- ? JSON.stringify(readCompanionModelChain(modelValues.modelChain).slice(0, 1))
+ ? serializeModelRoutes(readCompanionModelChain(modelValues.modelChain).slice(0, 1))
: modelValues.taskModel,
followsDefault: modelValues.taskFollowsPrimary === true,
};
@@ -342,11 +343,11 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {
onClose={() => setModelStage('closing-picker')} onClosed={() => setModelStage('profile')}
onSelect={route => {
if (modelPurpose === 'task') {
- changeValues({ ...modelValues, taskModel: JSON.stringify([route]), taskFollowsPrimary: false }); return true;
+ changeValues({ ...modelValues, taskModel: serializeModelRoutes([route]), taskFollowsPrimary: false }); return true;
}
const chain = readCompanionModelChain(modelValues.modelChain);
- if (chain.some((item, index) => index !== modelIndex && item.harness === route.harness && item.model === route.model && item.providerId === route.providerId)) return false;
- chain[modelIndex] = route; changeValues({ ...modelValues, modelChain: JSON.stringify(chain), followsDefault: false }); return true; }} />;
+ if (chain.some((item, index) => index !== modelIndex && item.harness === route.harness && item.model === route.model && item.providerId === route.providerId && (item.agentDeviceId ?? null) === (route.agentDeviceId ?? null))) return false;
+ chain[modelIndex] = route; changeValues({ ...modelValues, modelChain: serializeModelRoutes(chain), followsDefault: false }); return true; }} />;
if (Platform.OS === 'ios') return <>{modelPicker}<CompanionProfileNativeView models={models}
visible={visible && modelStage === 'profile'} title={confirmation?.action?.confirmation ? label(confirmation.action.confirmation.title) : page === 'editor' && editor ? label(editor.resource.display.title) : t(`devices.companionProfile.${titleKey}`)}
@@ -539,7 +540,7 @@ function CompanionCreateSheetContent({ visible, onClose, onClosed, deviceId, dev
onPick={() => setModelStage('closing-form')} /> : null;
const modelPicker = <CompanionModelPicker visible={visible && modelStage === 'picker'} deviceId={deviceId} route={modelChain[0]}
onClose={() => setModelStage('closing-picker')} onClosed={() => setModelStage('form')}
- onSelect={route => { setModelValues({ followsDefault: false, modelChain: JSON.stringify([route]) }); return true; }} />;
+ onSelect={route => { setModelValues({ followsDefault: false, modelChain: serializeModelRoutes([route]) }); return true; }} />;
if (importing) return <CompanionImportSheet visible={visible} onClose={onClose} onClosed={onClosed} deviceId={deviceId} deviceName={deviceName} online={online} onCreated={onCreated} />;
if (Platform.OS === 'ios') return <>{modelPicker}<CompanionCreateNativeView models={models} modelMissing={modelMissing} onImport={data?.resource.actions?.some(action => action.id === 'open-agent-import') ? openImport : undefined} deviceName={deviceName} nameTaken={nameTaken} duplicate={duplicate} locked={unconfirmed} visible={visible && !openingImport && modelStage === 'form'} onClose={close} onClosed={creationClosed} panel={data?.panels[0]} values={values} onChange={change} onSubmit={() => void submit()} onRetry={() => void reload()} online={online} busy={busy} loading={loading} error={error} dirty={dirty} /></>;
const panel = data?.panels[0];
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index a56f154549..922dad8a98 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -296,8 +296,15 @@ Mobile 使用电脑端已连接的模型目录;目录为空时保持创建禁
发送前按持久 Profile 协调长期主任务的路由,复用普通任务的模型控制与跨引擎交接。显式候选链未变时保留运行期 fallback;跟随 Cindy 默认时每次核对当前唯一可用默认,不沿用自动切出的其它型号。用户改变候选链后按新选择执行。后台任务默认继承发起时的实际路由,不读取可能过时的主任务创建模型。
+伙伴的创建、全局默认、主模型、任务模型和备用模型都使用普通任务的模型目录与来源选择;
+共享账号和另一台电脑的可用来源不受本机引擎安装情况限制。业务仅维护有序备用链,
+不得另建供应商清单、可选引擎白名单或简化路由结构。完整路由使用 `@cindy/maker-shared/model-route`,
+持久化和新建会话保留 `agentDeviceId`;缺失/null 表示所属电脑,`share:<id>` 表示共享来源。
+失效来源不能改投本机同名账号。远控表单统一使用 `serializeModelRoutes`,把远程来源编码到旧协议
+也保留的 provider 字段;新端解码,旧端不能识别时拒绝,不能静默消费本机额度。
+
伙伴设置的模型页按用途显示「主模型」与「任务模型」,都复用统一选择器。任务模型默认继承主模型;
-用户可独立选择一条完整路由(Harness、来源、型号、思考深度、Fast),也可恢复继承。
+用户可独立选择一条完整路由(执行位置、Harness、来源、型号、思考深度、Fast),也可恢复继承。
`capabilities.taskModelOverride` 缺失或为 `null` 表示继承,非空表示显式路由;不保存继承模型的副本。
独立配置只影响此后通过 `start_session_task` 创建的普通后台任务,不切换伙伴主任务或已有后台任务。
伙伴也可先通过 `get_app_default_model` 读取本机已启用的完整路由,再给 `start_session_task`
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index f04573a977..ffef077898 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -8,6 +8,7 @@
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
+ "./model-route": "./src/modelRoute.ts",
"./agent-capabilities": "./src/agentCapabilities.ts",
"./agent-input-projection": "./src/agentInputProjection.ts",
"./auto-review-intent": "./src/autoReviewIntent.ts",
diff --git a/packages/maker-shared/src/modelRoute.ts b/packages/maker-shared/src/modelRoute.ts
new file mode 100644
index 0000000000..e818ee5894
--- /dev/null
+++ b/packages/maker-shared/src/modelRoute.ts
@@ -0,0 +1,50 @@
+/** Persisted model selection shared by settings, defaults and companion chains.
+ * Missing location is the task's own computer; a share uses the ordinary share:<id> location.
+ * No credentials or provider metadata belong in this record.
+ */
+export interface ModelRoute {
+ harness: 'claude' | 'codex' | 'pi';
+ model: string;
+ providerId: string | null;
+ effort: string;
+ fastMode: boolean;
+ agentDeviceId?: string | null;
+}
+
+export function normalizeModelRoute(value: unknown): ModelRoute | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ let record = value as Record<string, unknown>;
+ if (typeof record.providerId === 'string' && record.providerId.startsWith(REMOTE_SOURCE_PREFIX)) {
+ try {
+ const source: unknown = JSON.parse(record.providerId.slice(REMOTE_SOURCE_PREFIX.length));
+ if (!Array.isArray(source) || source.length !== 2 || typeof source[0] !== 'string'
+ || (source[1] !== null && typeof source[1] !== 'string')
+ || (record.agentDeviceId != null && record.agentDeviceId !== source[0])) return null;
+ record = { ...record, agentDeviceId: source[0], providerId: source[1] };
+ } catch { return null; }
+ }
+ if (typeof record.model !== 'string' || !record.model.trim()) return null;
+ if (record.agentDeviceId != null && (typeof record.agentDeviceId !== 'string'
+ || !/^[A-Za-z0-9_.:-]{1,128}$/.test(record.agentDeviceId))) return null;
+ return {
+ harness: record.harness === 'codex' || record.harness === 'pi' ? record.harness : 'claude',
+ model: record.model.trim(),
+ providerId: typeof record.providerId === 'string' && record.providerId.trim() ? record.providerId.trim() : null,
+ effort: typeof record.effort === 'string' ? record.effort : '',
+ fastMode: record.fastMode === true,
+ ...(typeof record.agentDeviceId === 'string' ? { agentDeviceId: record.agentDeviceId.trim() } : {}),
+ };
+}
+
+export function modelRouteLocationKey(agentDeviceId: string | null | undefined): string {
+ return agentDeviceId ? `\u0000${agentDeviceId}` : '';
+}
+
+// Older peers discard unknown route fields. Encode the location into the source on
+// remote forms so they fail closed instead of spending a local account with the same ID.
+const REMOTE_SOURCE_PREFIX = 'model-route:';
+export function serializeModelRoutes(routes: readonly ModelRoute[]): string {
+ return JSON.stringify(routes.map(route => route.agentDeviceId
+ ? { ...route, providerId: REMOTE_SOURCE_PREFIX + JSON.stringify([route.agentDeviceId, route.providerId]) }
+ : route));
+}