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(bots): reuse client model defaults and standard configuration picker

zqchris7e90620e3f41
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 5dca3db23f..bac653dba6 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -1,4 +1,5 @@
import Database from 'better-sqlite3';
+import type { ProviderView } from '@cindy/model-providers';
import { createHash } from 'node:crypto';
import { join } from 'node:path';
import { rmSync } from 'node:fs';
@@ -54,6 +55,7 @@ const h = await vi.hoisted(async () => {
searchConversations: vi.fn(),
requestRuntimeRefresh: vi.fn(),
seedTemplateSkills: vi.fn(async () => ({ completedNow: true, skills: [] })),
+ providers: [] as ProviderView[],
ownerScopeKey: 'owner-a:1',
ownerBoundaryPending: false,
});
@@ -92,8 +94,12 @@ vi.mock('../../../git-snapshot/projectGitBootstrap.js', () => ({
vi.mock('../../../maker-host/git-safety-settings-store.js', () => ({
readGitSafetySettings: () => ({ autoSnapshotEnabled: true }),
}));
+vi.mock('../../../maker-host/createDesktopProviderService.js', () => ({
+ getDesktopProviderService: () => ({ listProviders: async () => h.providers }),
+}));
vi.mock('../../../maker-host/index.js', () => ({
getMakerIfReady: () => ({
+ listAvailableAgents: () => ['claude-code', 'codex', 'pi'],
isSessionAlive: h.isSessionAlive,
closeSession: h.closeSession,
getSession: h.getSession,
@@ -391,6 +397,11 @@ beforeEach(async () => {
vi.clearAllMocks();
h.handlers.clear();
h.nextSession = 0;
+ h.providers = [{
+ id: 'xd', connected: true, source: 'builtin', agents: ['pi'], access: { kind: 'managed' },
+ models: { pi: [{ id: 'z-ai/glm-5.3-flash', efforts: ['high'], defaultEffort: 'high',
+ newSessionDefault: ['pi'], supportsImageInput: true }] },
+ }] as ProviderView[];
h.worktrees = [];
h.isSessionAlive.mockReturnValue(false);
h.ensureGit.mockResolvedValue(undefined);
@@ -477,6 +488,23 @@ describe('Bot canonical Session lifecycle', () => {
expect((await listBotRemoteResourceSources()).map((row) => row.id)).not.toContain(created.id);
});
+ 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'],
+ access: { kind: 'subscription', product: 'ChatGPT' },
+ routing: { codex: { upstream: 'https://example.invalid', authStrategy: 'oauth-passthrough' } },
+ models: { codex: [{ id: 'gpt-5.6-sol', mode: 'chat', status: 'active', efforts: ['medium'], defaultEffort: 'medium' }] },
+ }] as ProviderView[];
+ const created = await invoke('local-db:bots:create', { id: 'codex-only', name: 'Codex Bot' });
+ const canonical = await invoke('local-db:bots:create-canonical-session', {
+ botId: created.id, expectedCanonicalSessionId: created.canonicalSessionId ?? null,
+ expectedProfileVersion: 1,
+ });
+ const row = h.sqlite!.prepare('SELECT agent_kind, model, provider_id, effort FROM sessions WHERE id = ?')
+ .get(canonical.session.id);
+ expect(row).toMatchObject({ agent_kind: 'codex', model: 'gpt-5.6-sol', provider_id: 'openai', effort: 'medium' });
+ });
+
it('uses the official Bot defaults when created without renderer capabilities', async () => {
await invoke('local-db:bots:create', {
id: 'bot-defaults',
@@ -824,7 +852,7 @@ describe('Bot canonical Session lifecycle', () => {
expect(reopened.session.permissionMode).toBe('ask');
});
- it('preserves an explicitly empty model when a Pi Bot has no selectable model', async () => {
+ it('keeps an unconfigured profile but rejects a model-less canonical task', async () => {
await invoke('local-db:bots:create', {
id: 'bot-pi-default',
name: 'Pi Default Bot',
@@ -837,17 +865,11 @@ describe('Bot canonical Session lifecycle', () => {
},
});
- const created = await invoke('local-db:bots:create-canonical-session', {
+ await expect(invoke('local-db:bots:create-canonical-session', {
botId: 'bot-pi-default',
expectedCanonicalSessionId: null,
expectedProfileVersion: 1,
- });
-
- expect(created.session).toMatchObject({
- agentKind: 'pi',
- providerId: null,
- model: '',
- });
+ })).rejects.toThrow('请先连接模型供应商或选择伙伴模型');
});
it('repairs a physically missing canonical task using the persisted pointer as its CAS', async () => {
diff --git a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts
index 3f0fc3beb9..f51b31ed1c 100644
--- a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts
+++ b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts
@@ -38,14 +38,18 @@ export function normalizeBotProfileModelChain(
const next = { ...value };
if (Object.prototype.hasOwnProperty.call(next, 'modelChain')) {
const chain = normalizeBotModelChain(next.modelChain);
- if (chain.length === 0) throw new Error('modelChain must contain at least one valid route');
- const primary = chain[0]!;
+ if (chain.length === 0 && next.modelChainOverride !== null && next.modelOverride !== null) {
+ throw new Error('modelChain must contain at least one valid route');
+ }
+ const primary = chain[0];
next.modelChain = chain;
- next.harness = primary.harness;
- next.model = primary.model;
- next.providerId = primary.providerId;
- next.effort = primary.effort;
- next.fastMode = primary.fastMode;
+ if (primary) {
+ next.harness = primary.harness;
+ next.model = primary.model;
+ next.providerId = primary.providerId;
+ next.effort = primary.effort;
+ next.fastMode = primary.fastMode;
+ }
}
if (Array.isArray(next.modelChainOverride)) {
const override = normalizeBotModelChain(next.modelChainOverride);
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index e5fd37961c..ee28917717 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -522,7 +522,7 @@ async function readProfile(
lastReadAt,
);
const config = parseJson(version?.capabilitiesJson ?? '{}');
- const modelChain = readEffectiveBotModelChain(config);
+ const modelChain = await readEffectiveBotModelChain(config);
const primaryModelRoute = modelChain[0];
const invitation = botInvitationProgress(config.invitation);
if (invitation && isManagedBotAvatarUrl(profile.avatar)) invitation.avatarSkipped = false;
@@ -798,19 +798,18 @@ async function fileExists(candidate: string): Promise<boolean> {
}
}
-function defaultNewBotCapabilities(): Record<string, unknown> {
- let modelChain = readEffectiveBotModelChain({
+async function defaultNewBotCapabilities(): Promise<Record<string, unknown>> {
+ const modelChain = await readEffectiveBotModelChain({
modelChainOverride: null,
modelOverride: null,
});
const primary = modelChain[0] ?? {
harness: 'pi' as const,
- model: NEW_BOT_DEFAULT_PI_MODEL,
- providerId: NEW_BOT_DEFAULT_PI_PROVIDER,
- effort: NEW_BOT_DEFAULT_PI_EFFORT,
+ model: '',
+ providerId: null,
+ effort: '',
fastMode: false,
};
- if (modelChain.length === 0) modelChain = [primary];
return {
...primary,
modelOverride: null,
@@ -978,7 +977,7 @@ export async function createBotProfile(raw: unknown) {
}
const persistedCapabilities = normalizeBotModelCapabilitiesOrThrow({
permissions: 'auto',
- ...(hasRequestedCapabilities ? {} : defaultNewBotCapabilities()),
+ ...(hasRequestedCapabilities ? {} : await defaultNewBotCapabilities()),
...requestedCapabilities,
skills,
userContextSource,
@@ -1081,7 +1080,7 @@ export function registerBotIpc(): void {
setRemoteBotSessionLookup(readRemoteBotSessionAccess);
ipcMain.handle('local-db:bots:model-chain-settings-get', async (event) => {
assertTrustedAppRendererEvent(event);
- const state = readBotModelChainSettingsState();
+ const state = await readBotModelChainSettingsState();
return { modelChain: state.value.modelChain, isCustomized: state.isCustomized };
});
@@ -1480,7 +1479,8 @@ export function registerBotIpc(): void {
const invitation = botInvitationProgress(config.invitation);
if (invitation && invitation.stage !== 'ready' && invitation.stage !== 'welcome')
throwIpcError('PRECONDITION_FAILED', '伙伴正在准备见面');
- const primaryRoute = readEffectiveBotModelChain(config)[0] ?? null;
+ const primaryRoute = (await readEffectiveBotModelChain(config))[0] ?? null;
+ if (!primaryRoute) throwIpcError('PRECONDITION_FAILED', '请先连接模型供应商或选择伙伴模型');
const workspaceKind = 'dialogue' as const;
const workingDir = await ensureBotWorkspaceDir(
owner.userDataDir,
diff --git a/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts b/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts
index c050bcd283..73e05a3f3a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts
@@ -2,7 +2,8 @@ import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, describe, expect, it } from 'vitest';
+import type { ProviderView } from '@cindy/model-providers';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
readBotModelChainSettingsState,
@@ -10,6 +11,12 @@ import {
writeBotModelChainSettings,
} from '../bot-model-chain-settings-store';
+vi.mock('../createDesktopProviderService.js', () => ({
+ getDesktopProviderService: () => ({ listProviders: async () => [] }),
+}));
+
+vi.mock('../index.js', () => ({ getMakerIfReady: () => ({ listAvailableAgents: () => ['claude-code', 'codex', 'pi'] }) }));
+
const roots: string[] = [];
async function testRoot(): Promise<string> {
@@ -23,21 +30,32 @@ afterEach(async () => {
});
describe('bot model chain settings store', () => {
- it('defaults to Pi + GLM-5.3-Flash without creating an override', async () => {
+ it('keeps unconfigured defaults empty without writing a Gateway placeholder', async () => {
const rootPath = await testRoot();
+ expect(await readBotModelChainSettingsState({ rootPath, providers: [] })).toMatchObject({
+ isCustomized: false, value: { modelChain: [] },
+ });
+ });
- expect(readBotModelChainSettingsState({ rootPath })).toMatchObject({
- isCustomized: false,
- value: {
- modelChain: [{
- harness: 'pi',
- model: 'z-ai/glm-5.3-flash',
- providerId: 'xd',
- effort: 'high',
- fastMode: false,
- }],
- },
+ it('resolves uncustomized defaults from current connections without writing an override', async () => {
+ const rootPath = await testRoot();
+ const providers = [{
+ id: 'openai', source: 'builtin', connected: true, agents: ['codex'],
+ access: { kind: 'subscription', product: 'ChatGPT' },
+ routing: { codex: { upstream: 'https://example.invalid', authStrategy: 'oauth-passthrough' } },
+ models: { codex: [{ id: 'gpt-5.6-sol', mode: 'chat', status: 'active', efforts: ['medium'], defaultEffort: 'medium' }] },
+ }] as ProviderView[];
+ const state = await readBotModelChainSettingsState({ rootPath, providers });
+ expect(state.isCustomized).toBe(false);
+ expect(state.value.modelChain[0]).toMatchObject({
+ harness: 'codex', providerId: 'openai', model: 'gpt-5.6-sol', effort: 'medium',
});
+ expect(await fs.readdir(rootPath)).toEqual([]);
+ expect(await readEffectiveBotModelChain({ modelChainOverride: null }, { rootPath, providers }))
+ .toEqual(state.value.modelChain);
+ await writeBotModelChainSettings(state.value.modelChain, { rootPath });
+ expect((await readBotModelChainSettingsState({ rootPath, providers: [] })).value)
+ .toEqual(state.value);
});
it('persists an ordered 1-5 route chain as the Main-owned source of truth', async () => {
@@ -61,17 +79,17 @@ describe('bot model chain settings store', () => {
await writeBotModelChainSettings(modelChain, { rootPath });
- expect(readBotModelChainSettingsState({ rootPath })).toMatchObject({
+ expect(await readBotModelChainSettingsState({ rootPath, providers: [] })).toMatchObject({
isCustomized: true,
value: { modelChain },
});
- expect(readEffectiveBotModelChain({
+ expect(await readEffectiveBotModelChain({
model: 'legacy-cache',
harness: 'claude',
modelOverride: null,
}, { rootPath })).toEqual(modelChain);
- expect(readEffectiveBotModelChain({
+ expect(await readEffectiveBotModelChain({
modelChainOverride: null,
modelChain: [{ harness: 'claude', model: 'stale-cache' }],
}, { rootPath })).toEqual(modelChain);
@@ -87,7 +105,7 @@ describe('bot model chain settings store', () => {
fastMode: false,
}];
- expect(readEffectiveBotModelChain({
+ expect(await readEffectiveBotModelChain({
modelChain: [{ harness: 'pi', model: 'stale-cache' }],
modelChainOverride: explicit,
}, { rootPath })).toEqual(explicit);
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 54d6397854..baa734ab09 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
@@ -1,18 +1,16 @@
import { app } from 'electron';
import path from 'node:path';
+import type { ProviderView } from '@cindy/model-providers';
+import { defaultBotModelChain } from '../../shared/botDefaultModelChain.js';
-import {
- NEW_BOT_DEFAULT_HARNESS,
- NEW_BOT_DEFAULT_PI_EFFORT,
- NEW_BOT_DEFAULT_PI_MODEL,
- NEW_BOT_DEFAULT_PI_PROVIDER,
-} from '../../shared/botDefaults.js';
import {
normalizeBotModelChain,
type BotModelRoute,
} from '../../shared/botModelChain.js';
-import { getActiveAppSession, ownerScopedUserDataPath } from '../appSessionState.js';
+import { activeOwnerScopeKey, getActiveAppSession, ownerScopedUserDataPath } from '../appSessionState.js';
import { desktopMakerLogger } from './logger-adapter.js';
+import { getMakerIfReady } from './index.js';
+import { getDesktopProviderService } from './createDesktopProviderService.js';
import {
createOverrideSettingsFile,
type OverrideSettingsState,
@@ -24,22 +22,14 @@ export interface BotModelChainSettings {
modelChain: BotModelRoute[];
}
-const DEFAULT_MODEL_CHAIN: BotModelRoute[] = [{
- harness: NEW_BOT_DEFAULT_HARNESS,
- model: NEW_BOT_DEFAULT_PI_MODEL,
- providerId: NEW_BOT_DEFAULT_PI_PROVIDER,
- effort: NEW_BOT_DEFAULT_PI_EFFORT,
- fastMode: false,
-}];
-
-const DEFAULTS: BotModelChainSettings = { modelChain: DEFAULT_MODEL_CHAIN };
+const DEFAULTS: BotModelChainSettings = { modelChain: [] };
function normalize(raw: unknown): BotModelChainSettings {
const record = raw && typeof raw === 'object' && !Array.isArray(raw)
? raw as Record<string, unknown>
: {};
const modelChain = normalizeBotModelChain(record.modelChain);
- return { modelChain: modelChain.length > 0 ? modelChain : DEFAULT_MODEL_CHAIN };
+ return { modelChain };
}
function settingsFilePath(rootPath?: string): string {
@@ -51,6 +41,18 @@ const stores = new Map<
ReturnType<typeof createOverrideSettingsFile<BotModelChainSettings>>
>();
+let providerRead: { owner: string; promise: Promise<ProviderView[]> } | undefined;
+
+function readConnectedProviders(owner: string): Promise<ProviderView[]> {
+ if (providerRead?.owner === owner) return providerRead.promise;
+ // A roster read resolves several profiles together. Share only the in-flight
+ // credential read, never a cached connection state or another owner's result.
+ const promise = getDesktopProviderService().listProviders({ allowSideEffects: false })
+ .finally(() => { if (providerRead?.promise === promise) providerRead = undefined; });
+ providerRead = { owner, promise };
+ return promise;
+}
+
function currentStore(rootPath?: string) {
const ownerRoot = rootPath
?? (getActiveAppSession().dataOwnerId ? ownerScopedUserDataPath() : null);
@@ -72,20 +74,32 @@ function currentStore(rootPath?: string) {
return current;
}
-export function readBotModelChainSettings(
- options?: { rootPath?: string },
-): BotModelChainSettings {
- const store = currentStore(options?.rootPath);
- store.invalidateIfChanged();
- return store.read();
+export async function readBotModelChainSettings(
+ options?: { rootPath?: string; providers?: readonly ProviderView[]; availableAgents?: ReadonlySet<'cc' | 'codex' | 'pi'> },
+): Promise<BotModelChainSettings> {
+ return (await readBotModelChainSettingsState(options)).value;
}
-export function readBotModelChainSettingsState(
- options?: { rootPath?: string },
-): OverrideSettingsState<BotModelChainSettings> {
+export async function readBotModelChainSettingsState(
+ options?: { rootPath?: string; providers?: readonly ProviderView[]; availableAgents?: ReadonlySet<'cc' | 'codex' | 'pi'> },
+): Promise<OverrideSettingsState<BotModelChainSettings>> {
const store = currentStore(options?.rootPath);
store.invalidateIfChanged();
- return store.readState();
+ const state = store.readState();
+ if (state.isCustomized) return state;
+ // Capture the owner before reading live connections; never persist derived defaults.
+ const owner = activeOwnerScopeKey();
+ const providers = options?.providers ?? await readConnectedProviders(owner);
+ if (activeOwnerScopeKey() !== owner) throw new Error('Bot model defaults owner changed');
+ store.invalidateIfChanged();
+ const latest = store.readState();
+ if (latest.isCustomized) return latest;
+ const availableAgents = options?.availableAgents ?? new Set(
+ (getMakerIfReady()?.listAvailableAgents() ?? []).map((agent) => agent === 'claude-code' ? 'cc' : agent),
+ );
+ const value = { modelChain: defaultBotModelChain({ providers, providersLoading: false,
+ availableAgents, availableAgentsLoaded: true }) };
+ return { ...latest, value, defaults: value };
}
export async function writeBotModelChainSettings(
@@ -104,10 +118,10 @@ export async function writeBotModelChainSettings(
* A null override means the permanent Bot Profile follows the owner-scoped
* global route chain. Explicit per-Bot chains remain frozen in its profile.
*/
-export function readEffectiveBotModelChain(
+export async function readEffectiveBotModelChain(
config: Record<string, unknown>,
- options?: { rootPath?: string },
-): BotModelRoute[] {
+ options?: { rootPath?: string; providers?: readonly ProviderView[]; availableAgents?: ReadonlySet<'cc' | 'codex' | 'pi'> },
+): Promise<BotModelRoute[]> {
if (Array.isArray(config.modelChainOverride)) {
const explicit = normalizeBotModelChain(config.modelChainOverride);
if (explicit.length > 0) return explicit;
@@ -115,7 +129,8 @@ export function readEffectiveBotModelChain(
// Before modelChainOverride existed, modelOverride:null was the durable
// marker for “follow the Bot default”. Preserve that meaning on upgrade.
if (config.modelChainOverride === null || config.modelOverride === null) {
- return readBotModelChainSettings(options).modelChain;
+ return (await readBotModelChainSettings(options)).modelChain;
}
- return normalizeBotModelChain(config.modelChain, config);
+ const legacy = normalizeBotModelChain(config.modelChain, config);
+ return legacy.length || typeof config.model === 'string' ? legacy : (await readBotModelChainSettings(options)).modelChain;
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c65fa4b24f..915037a9ad 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10599,7 +10599,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
eq(sessions.status, 'active'),
)).limit(1);
if (!row) return null;
- const chain = readEffectiveBotModelChain(JSON.parse(row.capabilitiesJson));
+ const chain = await readEffectiveBotModelChain(JSON.parse(row.capabilitiesJson));
const control = getSessionRuntimeControlSnapshot(sessionId);
const live = maker.getSession(sessionId);
return {
@@ -10674,7 +10674,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} catch {
return { isBot: true, candidate: null };
}
- const chain = readEffectiveBotModelChain(config);
+ const chain = await readEffectiveBotModelChain(config);
const toAgentKind = (harness: string): AgentKind =>
harness === 'codex' ? 'codex' : harness === 'pi' ? 'pi' : 'claude-code';
const currentHarness = current.agentKind === 'codex'
diff --git a/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx b/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx
index 07da09076b..3176f5987b 100644
--- a/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx
@@ -77,6 +77,7 @@ export function BotModelChainEditor({
const picker = (route: BotModelRoute, index: number) => (
<div className="min-w-0 flex-1">
<ModelSelector
+ vendorKey={vendorFor(route.harness)}
modelId={route.model}
effort={route.effort}
currentProviderId={route.providerId}
@@ -86,12 +87,12 @@ export function BotModelChainEditor({
excludeSubscriptionDirect={remote}
excludeChatBridgedCodex={remote}
fastMode={route.fastMode}
- onModelChange={() => undefined}
- onEffortChange={() => undefined}
- configurationEnabled={false}
+ onModelChange={(model) => replace(index, { model })}
+ onEffortChange={(effort) => replace(index, { effort })}
+ onFastModeChange={(fastMode) => replace(index, { fastMode })}
+ configurationEnabled
unifiedPanel
unifiedAgents={unifiedAgents}
- unifiedSelectionPolicy="official"
onUnifiedSelect={(selection) =>
replace(index, {
harness: harnessFor(selection.engine),
diff --git a/apps/desktop/src/renderer/features/bots/BotRosterView.tsx b/apps/desktop/src/renderer/features/bots/BotRosterView.tsx
index 4bafba0502..4d52c960bc 100644
--- a/apps/desktop/src/renderer/features/bots/BotRosterView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotRosterView.tsx
@@ -5,6 +5,8 @@ import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { BotInvitationWelcome } from './BotInvitationWelcome';
+import { ConnectProviderCard } from '@/components/onboarding/ConnectProviderCard';
+import { useProviderOnboarding } from '@/hooks/useProviderOnboarding';
import { Spinner } from '@/components/ui/spinner';
import { BOT_AVATAR_MAX_BYTES } from '../../../shared/botAvatarValue';
import {
@@ -37,6 +39,7 @@ export function BotRosterView({ onCreated, onClose, restoreFocus }: BotRosterVie
const { t } = useTranslation();
const navigate = useNavigate();
const bots = useBotProfiles();
+ const providerOnboarding = useProviderOnboarding();
const [invited, setInvited] = useState<BotProfile | null>(null);
useEffect(() => {
if (!invited) return;
@@ -187,7 +190,12 @@ export function BotRosterView({ onCreated, onClose, restoreFocus }: BotRosterVie
}}
className="fixed left-1/2 top-1/2 z-50 max-h-[85vh] w-[calc(100vw-32px)] max-w-[440px] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-[var(--border-default)] bg-[var(--confirm-bg)] p-5 outline-none"
>
- {invitedBot ? (
+ {providerOnboarding.visible ? (
+ <>
+ <Dialog.Title className="sr-only">{t('onboarding.connectProvider.title')}</Dialog.Title>
+ <ConnectProviderCard />
+ </>
+ ) : invitedBot ? (
<>
<Dialog.Title className="sr-only">{t('bots.invitation.title')}</Dialog.Title>
<BotInvitationWelcome bot={invitedBot} />
diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
index af1ef58213..02e0a4391b 100644
--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
@@ -1,3 +1,5 @@
+import { ConnectProviderCard } from '@/components/onboarding/ConnectProviderCard';
+import { useProviderOnboarding } from '@/hooks/useProviderOnboarding';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Bot, Check, FolderOpen } from 'lucide-react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
@@ -381,6 +383,7 @@ export function BotsHomeView() {
const { botId, sessionId } = useParams();
const [searchParams] = useSearchParams();
const bots = useBotProfiles();
+ const providerOnboarding = useProviderOnboarding();
const creatingBotRef = useRef<{ botId: string; token: symbol } | null>(null);
const [isCreatingSession, setIsCreatingSession] = useState(false);
const [createSessionError, setCreateSessionError] = useState<unknown>(null);
@@ -490,6 +493,7 @@ export function BotsHomeView() {
useRegisterContentHeader(headerContent);
useEffect(() => {
+ if (providerOnboarding.visible) return;
if (selectedBot?.invitation && selectedBot.invitation.stage !== 'ready') return;
if (!selectedBot || shouldDeferCanonicalBotSessionNavigation({ settingsOpen, addRequested }))
return;
@@ -581,7 +585,11 @@ export function BotsHomeView() {
creatingBotRef.current = null;
}
};
- }, [addRequested, createCanonicalSession, selectedBot, sessionId, settingsOpen, navigate]);
+ }, [addRequested, createCanonicalSession, selectedBot, sessionId, settingsOpen, navigate, providerOnboarding.visible]);
+
+ if (providerOnboarding.visible && !settingsOpen) {
+ return <main className="flex h-full items-center justify-center px-6" role="main"><ConnectProviderCard /></main>;
+ }
if (!selectedBot) {
if (bots.length === 0)
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 d850d64902..2596c4fff7 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botModelChainEditor.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botModelChainEditor.test.tsx
@@ -9,6 +9,8 @@ const { modelSelectorProps } = vi.hoisted(() => ({
vi.mock('@/components/new-chat/ModelSelector', () => ({
ModelSelector: (props: {
+ onEffortChange: (effort: string) => void;
+ onFastModeChange: (enabled: boolean) => void;
onUnifiedSelect: (selection: {
providerId: string;
modelId: string;
@@ -21,6 +23,8 @@ vi.mock('@/components/new-chat/ModelSelector', () => ({
modelSelectorProps(props);
return (
<>
+ <button onClick={() => props.onEffortChange("high")}>set-high-effort</button>
+ <button onClick={() => props.onFastModeChange(true)}>enable-fast-mode</button>
<button
type="button"
onClick={() =>
@@ -79,7 +83,7 @@ afterEach(() => {
});
describe('BotModelChainEditor', () => {
- it('uses the model-only unified picker with official routing', () => {
+ it('uses the standard configurable picker for the current harness', () => {
render(
<BotModelChainEditor
value={[
@@ -100,14 +104,27 @@ describe('BotModelChainEditor', () => {
expect(modelSelectorProps.mock.calls[0]?.[0].unifiedLayout).toBeUndefined();
expect(modelSelectorProps.mock.calls[0]?.[0].unifiedLayoutControls).toBeUndefined();
expect(modelSelectorProps.mock.calls[0]?.[0]).toMatchObject({
- configurationEnabled: false,
+ configurationEnabled: true,
+ vendorKey: 'pi',
unifiedPanel: true,
unifiedAgents: ['pi', 'claude-code'],
- unifiedSelectionPolicy: 'official',
triggerVariant: 'toolbar',
});
});
+ it('writes depth and fast mode to the selected route without changing its model', () => {
+ const route = { harness: 'codex' as const, model: 'gpt-5.6-sol',
+ providerId: 'openai', effort: 'medium', fastMode: false };
+ const fallback = { ...route, model: 'fallback-model' };
+ const onChange = vi.fn();
+ render(<BotModelChainEditor value={[route, fallback]} onChange={onChange} />);
+ fireEvent.click(screen.getByText('set-high-effort'));
+ expect(onChange).toHaveBeenLastCalledWith([{ ...route, effort: 'high' }, fallback]);
+ fireEvent.click(screen.getByText('enable-fast-mode'));
+ expect(onChange).toHaveBeenLastCalledWith([{ ...route, fastMode: true }, fallback]);
+ expect(modelSelectorProps.mock.calls[0]?.[0].unifiedSelectionPolicy).toBeUndefined();
+ });
+
it('atomically stores the official harness, provider, model, effort, and fast mode', () => {
const onChange = vi.fn();
render(
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botRosterView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botRosterView.test.tsx
index 7bdbf86201..bf62c755ee 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botRosterView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botRosterView.test.tsx
@@ -10,8 +10,11 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
const mocks = vi.hoisted(() => ({
addBotProfileAndWait: vi.fn(),
navigate: vi.fn(),
+ onboarding: false,
profiles: [] as Array<{ id: string; name: string; invitation: { stage: string } }>,
}));
+vi.mock('@/hooks/useProviderOnboarding', () => ({ useProviderOnboarding: () => ({ visible: mocks.onboarding }) }));
+vi.mock('@/components/onboarding/ConnectProviderCard', () => ({ ConnectProviderCard: () => <div>Shared provider setup</div> }));
vi.mock('../botStore', () => ({
addBotProfileAndWait: mocks.addBotProfileAndWait,
useBotProfiles: () => mocks.profiles,
@@ -27,11 +30,23 @@ beforeEach(() => {
mocks.addBotProfileAndWait.mockResolvedValue({ id: 'bot-new', name: 'Ops buddy' });
mocks.navigate.mockReset();
mocks.profiles = [];
+ mocks.onboarding = false;
});
afterEach(() => cleanup());
describe('BotRosterView — 唯一的伙伴创建界面', () => {
+ it('uses the shared connection guide before creating an unconfigured teammate', () => {
+ mocks.onboarding = true;
+ const view = render(<BotRosterView />);
+ expect(screen.getByText('Shared provider setup')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'bots.roster.create' })).toBeNull();
+ expect(mocks.addBotProfileAndWait).not.toHaveBeenCalled();
+ mocks.onboarding = false;
+ view.rerender(<BotRosterView />);
+ expect(screen.getByRole('button', { name: 'bots.roster.create' })).toBeTruthy();
+ });
+
it('waits in the invitation dialog and meets only after preparation completes', async () => {
const preparing = { id: 'new', name: '阿橙', invitation: { stage: 'skills' } };
mocks.addBotProfileAndWait.mockResolvedValue(preparing);
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
index 2387c9c81e..9981cd8787 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSettings.test.tsx
@@ -4,6 +4,13 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BotCapabilities, BotProfile } from '../botStore';
+vi.mock('@/hooks/useProviderOnboarding', () => ({
+ useProviderOnboarding: () => ({ visible: false }),
+}));
+vi.mock('@/components/onboarding/ConnectProviderCard', () => ({
+ ConnectProviderCard: () => null,
+}));
+
const translate = (key: string, opts?: Record<string, unknown>) =>
opts ? `${key}:${JSON.stringify(opts)}` : key;
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts
index 1ce13b03d3..2f4b4ac41c 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botStore.test.ts
@@ -16,6 +16,8 @@ import { getDefaultModelForVendor } from '@/lib/modelDefinitions';
import { getCachedProvidersSnapshot } from '@/lib/providersSnapshotStore';
import { getPersistedVendorModel } from '@/state/newMakerDraft';
+vi.mock('@/hooks/useAvailableAgents', () => ({ getCachedAvailableVendors: () => new Set(['cc', 'codex', 'pi']) }));
+
vi.mock('@/lib/modelDefinitions', () => ({
getDefaultModelForVendor: vi.fn(() => ({
id: 'catalog-new-session-default',
@@ -50,6 +52,8 @@ function piModel(
defaultEffort,
supportsFastMode: false,
status: 'active',
+ newSessionDefault: ['pi'],
+ supportsImageInput: true,
} as CatalogModel;
}
@@ -145,14 +149,14 @@ describe('bot profile store', () => {
});
});
- it('does not invent an unconfigured fallback when GLM-5.3-Flash is unavailable', () => {
+ it('selects connected client defaults when GLM-5.3-Flash is unavailable', () => {
setProviders([
piProvider(
'openai',
true,
[
piModel('chatgpt/gpt-second', 9),
- piModel('chatgpt/gpt-first', 0, 'medium'),
+ piModel('chatgpt/gpt-5.6-sol', 0, 'medium'),
],
'subscription',
),
@@ -164,13 +168,13 @@ describe('bot profile store', () => {
expect(bot.capabilities).toMatchObject({
harness: 'pi',
- model: 'z-ai/glm-5.3-flash',
- providerId: 'xd',
- effort: 'high',
+ model: 'chatgpt/gpt-5.6-sol',
+ providerId: 'openai',
+ effort: 'medium',
});
});
- it('keeps the durable Pi + GLM default while the catalog is still unavailable', () => {
+ it('leaves the model empty when no source is configured', () => {
setProviders([
piProvider('xd', false, [piModel('z-ai/glm-5.3-flash')]),
]);
@@ -180,9 +184,9 @@ describe('bot profile store', () => {
expect(bot.capabilities).toMatchObject({
harness: 'pi',
- model: 'z-ai/glm-5.3-flash',
- providerId: 'xd',
- effort: 'high',
+ model: '',
+ providerId: null,
+ effort: '',
});
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx
index c92a8d044f..ffdaa894e1 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx
@@ -4,6 +4,13 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('@/hooks/useProviderOnboarding', () => ({
+ useProviderOnboarding: () => ({ visible: false }),
+}));
+vi.mock('@/components/onboarding/ConnectProviderCard', () => ({
+ ConnectProviderCard: () => null,
+}));
+
const translate = (key: string, opts?: Record<string, unknown>) =>
opts ? `${key}:${JSON.stringify(opts)}` : key;
vi.mock('react-i18next', () => ({
diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.ts
index bd53b093d0..2f3682f0b9 100644
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@ -1,17 +1,16 @@
import { botInvitationProgress, type BotInvitationProgress } from '../../../shared/botInvitation';
import { useSyncExternalStore } from 'react';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
-import { effectiveSourceIdForModel, getModel } from '@cindy/model-providers';
+import { getModel } from '@cindy/model-providers';
import { getDraft, getPersistedVendorModel } from '@/state/newMakerDraft';
import { getDefaultModelForVendor } from '@/lib/modelDefinitions';
-import { pickFirstConnectedModelForAgent } from '@/lib/draftModelCalibration';
+import { pickConnectedModelForAgent } from '@/lib/draftModelCalibration';
import { refreshLocalCatalogSnapshot } from '@/lib/localCatalogSnapshot';
+import { defaultBotModelChain } from '../../../shared/botDefaultModelChain';
+import { getCachedAvailableVendors } from '@/hooks/useAvailableAgents';
import { getCachedProvidersSnapshot } from '@/lib/providersSnapshotStore';
import {
NEW_BOT_DEFAULT_HARNESS,
- NEW_BOT_DEFAULT_PI_EFFORT,
- NEW_BOT_DEFAULT_PI_MODEL,
- NEW_BOT_DEFAULT_PI_PROVIDER,
} from '../../../shared/botDefaults';
import { getBotLastReadAtMap, pruneBotReadState, seedMissingBotReadState } from './botReadState';
import type { BotGender } from '../../../shared/botGender';
@@ -206,70 +205,15 @@ export function canonicalBotSessionId(bot: BotProfile): string | undefined {
return canonicalBotSession(bot)?.id;
}
-/**
- * 伙伴该用哪个模型:用户真正选过的优先,没选过就跟系统默认。
- *
- * 新建伙伴与**设置页换 harness** 共用这一条 —— 换 harness 时原来直接读
- * `lastByVendor[vendor].model`,把种子快照当成用户的选择,与新建那边曾经的
- * bug 完全同形。同一个决定不留两份实现。
- *
- * 两条都必须走既有来源,这里只加一层有界首选:
- * - `lastByVendor` 的整份快照会随任意 draft 写入落盘,里面的 model 即使用户从没碰过
- * 也带着种子默认 —— 直接读它,新建的每个伙伴都会撞上种子档,与用户自己选的无关
- * (2026-08-21 用户实测投诉)。`modelChosenByVendor` 才是「真选过」的判据,
- * `getPersistedVendorModel` 就是按它做的读取。
- * - 新建 Pi Bot 优先 GLM-5.3-Flash,但只有它在当前**已连接来源**里真的可路由才选;
- * 否则取当前可选模型的第一项。一个可选模型都没有时 model 留空,让选择器展示空态。
- * model / provider / effort 始终从同一个来源条目一起解析。
- * - 其它 harness 仍直接取 `getDefaultModelForVendor()`,也就是模型选择器给新对话用的
- * 同一个默认值(服务端目录的 newSessionDefault)。
- */
+/** Manual harness changes use the ordinary client model picker calibration. */
function defaultBotModelSettings(vendor: ReturnType<typeof vendorForHarness>): BotModelOverride {
- if (vendor === 'pi') {
- const providers = getCachedProvidersSnapshot()?.providers ?? [];
- const preferredProviderId = effectiveSourceIdForModel(
- providers,
- null,
- NEW_BOT_DEFAULT_PI_MODEL,
- 'pi',
- );
- if (preferredProviderId) {
- const provider = providers.find((item) => item.id === preferredProviderId);
- const preferred = provider ? getModel(provider, NEW_BOT_DEFAULT_PI_MODEL, 'pi') : undefined;
- return {
- model: NEW_BOT_DEFAULT_PI_MODEL,
- providerId: preferredProviderId,
- effort: preferred?.defaultEffort ?? '',
- fastMode: false,
- };
- }
- const fallback = pickFirstConnectedModelForAgent(providers, 'pi');
- if (fallback) {
- const provider = providers.find((item) => item.id === fallback.providerId);
- const model = provider ? getModel(provider, fallback.model, 'pi') : undefined;
- return {
- model: fallback.model,
- providerId: fallback.providerId,
- effort: model?.defaultEffort ?? '',
- fastMode: false,
- };
- }
- // The Bot default is a durable product choice, not a transient projection
- // of whether the provider catalog happened to finish loading first.
- return {
- model: NEW_BOT_DEFAULT_PI_MODEL,
- providerId: NEW_BOT_DEFAULT_PI_PROVIDER,
- effort: NEW_BOT_DEFAULT_PI_EFFORT,
- fastMode: false,
- };
- }
- const fallback = getDefaultModelForVendor(vendor);
- return {
- model: fallback.id,
- providerId: null,
- effort: fallback.defaultEffort ?? '',
- fastMode: false,
- };
+ const providers = getCachedProvidersSnapshot()?.providers ?? [];
+ const agent = vendor === 'cc' ? 'claude-code' : vendor;
+ const picked = pickConnectedModelForAgent(providers, agent, getDefaultModelForVendor(vendor).id);
+ const provider = providers.find((item) => item.id === picked?.providerId);
+ const model = provider && picked ? getModel(provider, picked.model, agent) : undefined;
+ return { model: picked?.model ?? '', providerId: picked?.providerId ?? null,
+ effort: model?.defaultEffort ?? '', fastMode: false };
}
export function defaultBotModel(vendor: ReturnType<typeof vendorForHarness>): string {
@@ -360,15 +304,11 @@ export function getEffectiveBotModelChain(
): BotModelRoute[] {
const stored = getBotGlobalModelChain();
if (stored) return stored;
- return [
- {
- harness: NEW_BOT_DEFAULT_HARNESS,
- model: NEW_BOT_DEFAULT_PI_MODEL,
- providerId: NEW_BOT_DEFAULT_PI_PROVIDER,
- effort: NEW_BOT_DEFAULT_PI_EFFORT,
- fastMode: false,
- },
- ];
+ const providers = getCachedProvidersSnapshot();
+ const availableAgents = getCachedAvailableVendors();
+ return defaultBotModelChain({ providers: providers?.providers ?? [],
+ providersLoading: !providers, availableAgents: availableAgents ?? new Set(),
+ availableAgentsLoaded: availableAgents !== null });
}
export async function setBotGlobalModelChain(chain: BotModelRoute[]): Promise<void> {
@@ -410,10 +350,8 @@ function defaultCapabilities(
): BotCapabilities {
const vendor = vendorForHarness(harness);
const prefs = getDraft().lastByVendor[vendor];
- const override = getBotGlobalModelOverride(vendor);
- const resolved = getEffectiveBotModelSettings(vendor, override);
const globalChain = getEffectiveBotModelChain(harness);
- const primary = globalChain[0] ?? { harness, ...resolved };
+ const primary = globalChain[0] ?? { harness, model: '', providerId: null, effort: '', fastMode: false };
const model = primary.model;
return {
model,
@@ -531,9 +469,11 @@ function normalizeDbProfile(value: unknown): BotProfile | null {
rawCapabilities ?? {},
harness,
);
- const resolvedModel =
- modelOverride ?? getEffectiveBotModelSettings(vendorForHarness(harness), null);
- const modelChain = normalizeBotModelChain(rawCapabilities?.modelChain, {
+ const followsDefault = rawCapabilities?.modelChainOverride === null || rawCapabilities?.modelOverride === null;
+ const resolvedModel = modelOverride ?? (followsDefault
+ ? { model: '', providerId: null, effort: '', fastMode: false }
+ : getEffectiveBotModelSettings(vendorForHarness(harness), null));
+ const modelChain = normalizeBotModelChain(rawCapabilities?.modelChain, followsDefault ? null : {
harness,
model: resolvedModel.model || rawCapabilities?.model,
providerId: resolvedModel.providerId ?? rawCapabilities?.providerId,
@@ -710,11 +650,9 @@ async function hydrateFromDatabase(): Promise<void> {
if (!isCurrent()) return;
}
const persisted = normalizeBotModelChain(state.modelChain);
- if (persisted.length > 0) {
- globalModelChainCache = persisted;
- window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);
- for (const listener of botModelListeners) listener();
- }
+ globalModelChainCache = persisted;
+ window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);
+ for (const listener of botModelListeners) listener();
} catch {
// Profile hydration remains usable if the settings file is temporarily
// unavailable. A later explicit refresh retries the Main-owned source.
@@ -868,6 +806,12 @@ export async function addBotProfileAndWait(input: CreateBotProfileInput): Promis
if (needsPiDefault && getCachedProvidersSnapshot() === null && typeof window !== 'undefined') {
await refreshLocalCatalogSnapshot();
}
+ const settingsApi = botsApi();
+ if (settingsApi?.getModelChainSettings) {
+ const state = await settingsApi.getModelChainSettings();
+ assertCurrentOwner(owner);
+ globalModelChainCache = normalizeBotModelChain(state.modelChain);
+ }
assertCurrentOwner(owner);
const bot = addBotProfile(input);
const api = botsApi();
diff --git a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
index 84886d0653..de85a901a5 100644
--- a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
+++ b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
@@ -298,3 +298,8 @@ export function __resetAvailableAgentsCacheForTest(): void {
inFlight.clear();
agentsCacheInvalidationScheduled.clear();
}
+
+/** Synchronous projection of the same runtime roster used by the client picker. */
+export function getCachedAvailableVendors(): ReadonlySet<MakerVendor> | null {
+ return agentsCache.get('')?.vendors ?? null;
+}
diff --git a/apps/desktop/src/renderer/lib/newMakerDefaultTuple.ts b/apps/desktop/src/renderer/lib/newMakerDefaultTuple.ts
index be180e9efb..eacbd6e7e2 100644
--- a/apps/desktop/src/renderer/lib/newMakerDefaultTuple.ts
+++ b/apps/desktop/src/renderer/lib/newMakerDefaultTuple.ts
@@ -1,162 +1 @@
-import {
- isModelSelectableForNewRoute,
- defaultEffortForCapabilities,
- clampEffortToSupported,
- type AgentKind,
- type Effort,
- type ProviderView,
-} from '@cindy/model-providers';
-
-import type { MakerVendor } from '@/lib/ccAgent.types';
-
-export interface NewMakerDefaultTuple {
- vendor: Extract<MakerVendor, 'cc' | 'codex' | 'pi'>;
- providerId: string;
- model: string;
- effort: Effort | null;
-}
-
-interface ProviderDefaultPolicy {
- providerId: 'openai' | 'anthropic' | 'xai' | 'xd';
- accessKind: 'subscription' | 'managed';
- agents: readonly AgentKind[];
- modelIds: readonly string[];
- requireNewSessionDefault?: boolean;
- requireImageInput?: boolean;
-}
-
-/**
- * 新用户的产品默认顺序。
- *
- * Gateway 的可用推荐组合优先于订阅;Gateway 未就绪或推荐组合不可用时回退订阅。
- * 多订阅又没有“最近连接时间”可用时,固定按
- * OpenAI → Anthropic → xAI,避免依赖目录下发顺序造成升级后随机换默认。
- * 每个来源的首个 agent 是推荐 Harness,其余只在本机没有安装首选 Harness 时降级。
- */
-const DEFAULT_POLICIES: readonly ProviderDefaultPolicy[] = [
- {
- providerId: 'xd',
- accessKind: 'managed',
- agents: ['pi'],
- modelIds: ['z-ai/glm-5.3-flash', 'glm-5.3-flash'],
- requireNewSessionDefault: true,
- requireImageInput: true,
- },
- {
- providerId: 'openai',
- accessKind: 'subscription',
- agents: ['codex', 'claude-code', 'pi'],
- modelIds: ['chatgpt/gpt-5.6-sol', 'gpt-5.6-sol'],
- },
- {
- providerId: 'anthropic',
- accessKind: 'subscription',
- agents: ['claude-code', 'codex', 'pi'],
- modelIds: ['claude-opus-5', 'anthropic/claude-opus-5'],
- },
- {
- providerId: 'xai',
- accessKind: 'subscription',
- agents: ['pi', 'codex', 'claude-code'],
- modelIds: ['grok-4.6', 'xai/grok-4.6'],
- },
-];
-
-function vendorForAgent(agent: AgentKind): NewMakerDefaultTuple['vendor'] {
- return agent === 'claude-code' ? 'cc' : agent;
-}
-
-/**
- * 仅供旧草稿迁移辨认“产品曾自动写入的 tuple 身份”。这里不判断账号实时可用性,
- * 也不产生默认值;真正下放仍只能走 resolveNewMakerDefaultTuple 的实时能力门控。
- */
-export function isKnownProductDefaultTupleIdentity(args: {
- vendor: MakerVendor;
- providerId: string;
- model: string;
-}): boolean {
- return DEFAULT_POLICIES.some(
- (policy) =>
- policy.providerId === args.providerId &&
- policy.modelIds.includes(args.model) &&
- policy.agents.some((agent) => vendorForAgent(agent) === args.vendor),
- );
-}
-
-function supportsImageInput(
- model: NonNullable<ProviderView['models'][AgentKind]>[number],
-): boolean {
- return model.supportsImageInput === true || model.modalities?.input.includes('image') === true;
-}
-
-function matchingModel(
- provider: ProviderView,
- agent: AgentKind,
- modelIds: readonly string[],
- requireNewSessionDefault = false,
- requireImageInput = false,
-) {
- const models = provider.models[agent] ?? [];
- return modelIds
- .map((id) => models.find((model) => model.id === id))
- .find(
- (model) =>
- model !== undefined &&
- model.defaultEnabled !== false &&
- (!requireNewSessionDefault || model.newSessionDefault?.includes(agent) === true) &&
- (!requireImageInput || supportsImageInput(model)) &&
- isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }),
- );
-}
-
-/**
- * 为“尚未自定义”的本地新任务挑一份完整默认组合。
- *
- * 返回 null 表示没有足够证据给默认值:供应商仍在加载、没有可用来源,或推荐模型不在
- * 当前账号目录里。调用方此时保留连接引导/既有空态,绝不编造一个看似可发送的组合。
- */
-export function resolveNewMakerDefaultTuple(args: {
- providers: readonly ProviderView[];
- providersLoading: boolean;
- availableAgents: ReadonlySet<MakerVendor>;
- availableAgentsLoaded: boolean;
-}): NewMakerDefaultTuple | null {
- const { providers, providersLoading, availableAgents, availableAgentsLoaded } = args;
- if (providersLoading || !availableAgentsLoaded) return null;
-
- for (const policy of DEFAULT_POLICIES) {
- const provider = providers.find(
- (candidate) =>
- candidate.id === policy.providerId &&
- candidate.connected &&
- !candidate.suspended &&
- !candidate.modelDiscoveryFailure &&
- candidate.access?.kind === policy.accessKind,
- );
- if (!provider) continue;
-
- for (const agent of policy.agents) {
- const vendor = vendorForAgent(agent);
- if (!availableAgents.has(vendor)) continue;
- const model = matchingModel(
- provider,
- agent,
- policy.modelIds,
- policy.requireNewSessionDefault,
- policy.requireImageInput,
- );
- if (!model) continue;
- return {
- vendor,
- providerId: provider.id,
- model: model.id,
- // Missing or stale optional metadata does not disqualify a usable route.
- effort: model.efforts.length === 0 ? null
- : model.defaultEffort === null ? null
- : (clampEffortToSupported(model.defaultEffort, model.efforts)
- ?? defaultEffortForCapabilities(model.efforts)) as Effort | null,
- };
- }
- }
- return null;
-}
+export * from '../../shared/newMakerDefaultTuple';
diff --git a/apps/desktop/src/shared/__tests__/botDefaultModelChain.test.ts b/apps/desktop/src/shared/__tests__/botDefaultModelChain.test.ts
new file mode 100644
index 0000000000..2e7f835a1f
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/botDefaultModelChain.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { type AgentKind, type CatalogModel, type ProviderView } from '@cindy/model-providers';
+import { defaultBotModelChain } from '../botDefaultModelChain';
+import { resolveNewMakerDefaultTuple } from '../newMakerDefaultTuple';
+import { nextBotModelRoute } from '../botModelChain';
+
+function provider(id: string, agent: AgentKind, ids: string[], subscription = false): ProviderView {
+ return {
+ id, name: id, source: 'builtin', connected: true, agents: [agent],
+ auth: { method: subscription ? 'oauth' : 'managed' },
+ access: subscription ? { kind: 'subscription', product: id } : { kind: 'managed' },
+ routing: { [agent]: {
+ upstream: 'https://example.invalid',
+ authStrategy: subscription ? 'oauth-passthrough' : 'gateway-key',
+ } },
+ models: { [agent]: ids.map((model, index) => ({
+ id: model, name: model, mode: 'chat', group: 'openai', status: 'active',
+ contextWindow: 200_000, efforts: ['low', 'medium'], defaultEffort: 'medium',
+ supportsFastMode: false, sortOrder: index,
+ } as CatalogModel)) },
+ } as ProviderView;
+}
+
+const availableAgents = new Set(['cc', 'codex', 'pi'] as const);
+function resolve(providers: ProviderView[], agents = availableAgents) {
+ return defaultBotModelChain({ providers, providersLoading: false, availableAgents: agents,
+ availableAgentsLoaded: true });
+}
+
+describe('Bot reuses the client default model policy', () => {
+ it('selects Codex and the same default as a normal new task without Gateway', () => {
+ const providers = [provider('openai', 'codex', ['gpt-5.6-sol'], true)];
+ const first = resolveNewMakerDefaultTuple({ providers, providersLoading: false,
+ availableAgents, availableAgentsLoaded: true });
+ expect(resolve(providers)[0]).toEqual({ harness: first!.vendor, providerId: first!.providerId,
+ model: first!.model, effort: first!.effort, fastMode: false });
+ expect(resolve(providers)[0]?.harness).toBe('codex');
+ });
+
+ it('uses the exact client Gateway → OpenAI → Anthropic order for fallback', () => {
+ const gateway = provider('xd', 'pi', ['z-ai/glm-5.3-flash']);
+ gateway.models.pi![0]!.newSessionDefault = ['pi'];
+ gateway.models.pi![0]!.supportsImageInput = true;
+ const openai = provider('openai', 'codex', ['gpt-5.6-sol'], true);
+ const anthropic = provider('anthropic', 'claude-code', ['claude-opus-5'], true);
+ const chain = resolve([anthropic, openai, gateway]);
+ expect(chain.map((route) => route.providerId)).toEqual(['xd', 'openai', 'anthropic']);
+ expect(nextBotModelRoute(chain, chain[0]!)).toEqual(chain[1]);
+ });
+
+ it('does not invent GLM when there is no configured source or recommended model', () => {
+ expect(resolve([])).toEqual([]);
+ expect(resolve([provider('openai', 'codex', ['unconfigured-model'], true)])).toEqual([]);
+ expect(resolve([{ ...provider('openai', 'codex', ['gpt-5.6-sol'], true), connected: false }])).toEqual([]);
+ });
+
+ it('uses the same installed-runtime gate and alternative harness as the client', () => {
+ const openai = provider('openai', 'codex', ['gpt-5.6-sol'], true);
+ expect(resolve([openai], new Set())).toEqual([]);
+ openai.agents.push('pi');
+ openai.models.pi = openai.models.codex;
+ expect(resolve([openai], new Set(['pi']))[0]?.harness).toBe('pi');
+ expect(resolve([openai])).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/shared/botDefaultModelChain.ts b/apps/desktop/src/shared/botDefaultModelChain.ts
new file mode 100644
index 0000000000..6a3f473965
--- /dev/null
+++ b/apps/desktop/src/shared/botDefaultModelChain.ts
@@ -0,0 +1,15 @@
+import { resolveNewMakerDefaultTuples } from './newMakerDefaultTuple.js';
+import { BOT_MODEL_CHAIN_MAX, type BotModelRoute } from './botModelChain.js';
+
+/** Adapt the client's ordered defaults to Bot routes without another selection policy. */
+export function defaultBotModelChain(
+ args: Parameters<typeof resolveNewMakerDefaultTuples>[0],
+): BotModelRoute[] {
+ return resolveNewMakerDefaultTuples(args).slice(0, BOT_MODEL_CHAIN_MAX).map((tuple) => ({
+ harness: tuple.vendor === 'cc' ? 'claude' : tuple.vendor,
+ providerId: tuple.providerId,
+ model: tuple.model,
+ effort: tuple.effort ?? '',
+ fastMode: false,
+ }));
+}
diff --git a/apps/desktop/src/shared/newMakerDefaultTuple.ts b/apps/desktop/src/shared/newMakerDefaultTuple.ts
new file mode 100644
index 0000000000..1cc342fc40
--- /dev/null
+++ b/apps/desktop/src/shared/newMakerDefaultTuple.ts
@@ -0,0 +1,171 @@
+import {
+ isModelSelectableForNewRoute,
+ defaultEffortForCapabilities,
+ clampEffortToSupported,
+ type AgentKind,
+ type Effort,
+ type ProviderView,
+} from '@cindy/model-providers';
+
+type MakerVendor = 'cc' | 'codex' | 'pi' | 'orca';
+
+export interface NewMakerDefaultTuple {
+ vendor: Extract<MakerVendor, 'cc' | 'codex' | 'pi'>;
+ providerId: string;
+ model: string;
+ effort: Effort | null;
+}
+
+interface ProviderDefaultPolicy {
+ providerId: 'openai' | 'anthropic' | 'xai' | 'xd';
+ accessKind: 'subscription' | 'managed';
+ agents: readonly AgentKind[];
+ modelIds: readonly string[];
+ requireNewSessionDefault?: boolean;
+ requireImageInput?: boolean;
+}
+
+/**
+ * 新用户的产品默认顺序。
+ *
+ * Gateway 的可用推荐组合优先于订阅;Gateway 未就绪或推荐组合不可用时回退订阅。
+ * 多订阅又没有“最近连接时间”可用时,固定按
+ * OpenAI → Anthropic → xAI,避免依赖目录下发顺序造成升级后随机换默认。
+ * 每个来源的首个 agent 是推荐 Harness,其余只在本机没有安装首选 Harness 时降级。
+ */
+const DEFAULT_POLICIES: readonly ProviderDefaultPolicy[] = [
+ {
+ providerId: 'xd',
+ accessKind: 'managed',
+ agents: ['pi'],
+ modelIds: ['z-ai/glm-5.3-flash', 'glm-5.3-flash'],
+ requireNewSessionDefault: true,
+ requireImageInput: true,
+ },
+ {
+ providerId: 'openai',
+ accessKind: 'subscription',
+ agents: ['codex', 'claude-code', 'pi'],
+ modelIds: ['chatgpt/gpt-5.6-sol', 'gpt-5.6-sol'],
+ },
+ {
+ providerId: 'anthropic',
+ accessKind: 'subscription',
+ agents: ['claude-code', 'codex', 'pi'],
+ modelIds: ['claude-opus-5', 'anthropic/claude-opus-5'],
+ },
+ {
+ providerId: 'xai',
+ accessKind: 'subscription',
+ agents: ['pi', 'codex', 'claude-code'],
+ modelIds: ['grok-4.6', 'xai/grok-4.6'],
+ },
+];
+
+function vendorForAgent(agent: AgentKind): NewMakerDefaultTuple['vendor'] {
+ return agent === 'claude-code' ? 'cc' : agent;
+}
+
+/**
+ * 仅供旧草稿迁移辨认“产品曾自动写入的 tuple 身份”。这里不判断账号实时可用性,
+ * 也不产生默认值;真正下放仍只能走 resolveNewMakerDefaultTuple 的实时能力门控。
+ */
+export function isKnownProductDefaultTupleIdentity(args: {
+ vendor: MakerVendor;
+ providerId: string;
+ model: string;
+}): boolean {
+ return DEFAULT_POLICIES.some(
+ (policy) =>
+ policy.providerId === args.providerId &&
+ policy.modelIds.includes(args.model) &&
+ policy.agents.some((agent) => vendorForAgent(agent) === args.vendor),
+ );
+}
+
+function supportsImageInput(
+ model: NonNullable<ProviderView['models'][AgentKind]>[number],
+): boolean {
+ return model.supportsImageInput === true || model.modalities?.input.includes('image') === true;
+}
+
+function matchingModel(
+ provider: ProviderView,
+ agent: AgentKind,
+ modelIds: readonly string[],
+ requireNewSessionDefault = false,
+ requireImageInput = false,
+) {
+ const models = provider.models[agent] ?? [];
+ return modelIds
+ .map((id) => models.find((model) => model.id === id))
+ .find(
+ (model) =>
+ model !== undefined &&
+ model.defaultEnabled !== false &&
+ (!requireNewSessionDefault || model.newSessionDefault?.includes(agent) === true) &&
+ (!requireImageInput || supportsImageInput(model)) &&
+ isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }),
+ );
+}
+
+/**
+ * 为“尚未自定义”的本地新任务与伙伴按产品顺序挑选可用默认组合。
+ *
+ * 返回空数组表示没有足够证据给默认值:供应商仍在加载、没有可用来源,或推荐模型不在
+ * 当前账号目录里。调用方此时保留连接引导/既有空态,绝不编造一个看似可发送的组合。
+ */
+export function resolveNewMakerDefaultTuples(args: {
+ providers: readonly ProviderView[];
+ providersLoading: boolean;
+ availableAgents: ReadonlySet<MakerVendor>;
+ availableAgentsLoaded: boolean;
+}): NewMakerDefaultTuple[] {
+ const { providers, providersLoading, availableAgents, availableAgentsLoaded } = args;
+ if (providersLoading || !availableAgentsLoaded) return [];
+ const tuples: NewMakerDefaultTuple[] = [];
+
+ for (const policy of DEFAULT_POLICIES) {
+ const provider = providers.find(
+ (candidate) =>
+ candidate.id === policy.providerId &&
+ candidate.connected &&
+ !candidate.suspended &&
+ !candidate.modelDiscoveryFailure &&
+ candidate.access?.kind === policy.accessKind,
+ );
+ if (!provider) continue;
+
+ for (const agent of policy.agents) {
+ const vendor = vendorForAgent(agent);
+ if (!availableAgents.has(vendor)) continue;
+ const model = matchingModel(
+ provider,
+ agent,
+ policy.modelIds,
+ policy.requireNewSessionDefault,
+ policy.requireImageInput,
+ );
+ if (!model) continue;
+ tuples.push({
+ vendor,
+ providerId: provider.id,
+ model: model.id,
+ // Missing or stale optional metadata does not disqualify a usable route.
+ effort: model.efforts.length === 0 ? null
+ : model.defaultEffort === null ? null
+ : (clampEffortToSupported(model.defaultEffort, model.efforts)
+ ?? defaultEffortForCapabilities(model.efforts)) as Effort | null,
+ });
+ break;
+ }
+ }
+ return tuples;
+}
+
+/** The first candidate remains the ordinary new-task default. */
+export function resolveNewMakerDefaultTuple(
+ args: Parameters<typeof resolveNewMakerDefaultTuples>[0],
+): NewMakerDefaultTuple | null {
+ return resolveNewMakerDefaultTuples(args)[0] ?? null;
+}
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index a72abc38be..0b531262fa 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -105,12 +105,18 @@ harness + provider + model + effort + fastMode
- 第一项是首选;首次主任务启动和确定性重建从第一项开始尝试。
- 只有连接、鉴权、配额、容量、模型不可用和启动失败等“候选不可用”错误才进入下一项。
- 用户拒绝授权、工具业务失败、参数错误和已经产生副作用后的失败不得触发透明重放。
-- 同一轮最多按链表各尝试一次;不得循环,也不得临时从 Catalog 猜一个用户没配置的模型。
+- 同一轮最多按生效候选链各尝试一次;不得循环。用户显式配置的链不得追加目录候选。
- 同 harness 可在安全边界切模型;跨 harness 必须走既有 agent-switch / 交接重建事务。
- fallback 只改变当前任务的有效路由,不暗改 Profile 顺序。下一次确定性重建仍从首选开始。
- 存量单模型配置归一成一项候选链,不能在升级时改变用户已有选择。
-全局伙伴设置保存默认候选链。单个伙伴没有显式覆盖时跟随全局链;一旦用户在伙伴设置里调整,
+未自定义时,伙伴直接复用客户端新任务的默认组合选择器及其顺序、模型和引擎可用性判定,
+不得另造伙伴专属的推荐型号或来源排序。首次创建取同一首选,fallback 顺序取该选择器的
+后续可用组合;用户自定义伙伴候选链仍优先。生成的默认候选不写成用户 override。
+未连接或没有可用默认组合时保持空值,不写入 GLM / Gateway 占位;伙伴创建和打开入口
+复用客户端现有连接引导,配置完成后重新解析,不能创建没有模型的主任务。
+
+全局伙伴设置保存用户自定义的默认候选链。单个伙伴没有显式覆盖时跟随全局链;一旦用户在伙伴设置里调整,
该伙伴保存自己的链。全局链由主进程按当前数据 owner 持久化,并由所有 Session 创建与 fallback
入口直接读取;不得只存在 renderer localStorage。