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。

merge: reconcile bot defaults with upstream reset settings

zqchrisc6d9ca977854
diff --cc apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts
index 73e05a3f3a,aa44c878b8..5a5d24fe8d
--- a/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts
@@@ -11,12 -13,13 +14,19 @@@ 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 owner = vi.hoisted(() => ({ root: '', key: 'owner-a:1' }));
+ vi.mock('../../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ dataOwnerId: owner.key }),
+ activeOwnerScopeKey: () => owner.key,
+ ownerScopedUserDataPath: () => owner.root,
+ }));
+
const roots: string[] = [];
async function testRoot(): Promise<string> {
@@@ -110,4 -103,70 +121,76 @@@ describe('bot model chain settings stor
modelChainOverride: explicit,
}, { rootPath })).toEqual(explicit);
});
+ it('clears even an explicitly saved default and leaves per-Bot overrides and other owners intact', async () => {
+ const rootPath = await testRoot();
+ const otherRoot = await testRoot();
- const defaults = readBotModelChainSettingsState({ rootPath }).value.modelChain;
++ 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 defaults = (await readBotModelChainSettingsState({ rootPath, providers })).value.modelChain;
+ const custom = [{ ...defaults[0]!, model: 'custom-model' }];
+ await writeBotModelChainSettings(defaults, { rootPath });
+ await writeBotModelChainSettings(custom, { rootPath: otherRoot });
- expect(readBotModelChainSettingsState({ rootPath }).isCustomized).toBe(true);
++ expect((await readBotModelChainSettingsState({ rootPath })).isCustomized).toBe(true);
+
- expect(await resetBotModelChainSettings({ rootPath })).toMatchObject({
++ expect(await resetBotModelChainSettings({ rootPath, providers })).toMatchObject({
+ value: { modelChain: defaults }, isCustomized: false, customizedKeys: [],
+ });
+ await expect(fs.stat(path.join(rootPath, 'bot-model-chain-settings.json'))).rejects.toMatchObject({ code: 'ENOENT' });
- expect(readEffectiveBotModelChain({ modelChainOverride: null }, { rootPath })).toEqual(defaults);
- expect(readEffectiveBotModelChain({ modelChainOverride: custom }, { rootPath })).toEqual(custom);
- expect(readBotModelChainSettingsState({ rootPath: otherRoot })).toMatchObject({
++ expect(await readEffectiveBotModelChain({ modelChainOverride: null }, { rootPath, providers })).toEqual(defaults);
++ expect(await readEffectiveBotModelChain({ modelChainOverride: custom }, { rootPath })).toEqual(custom);
++ expect(await readBotModelChainSettingsState({ rootPath: otherRoot })).toMatchObject({
+ isCustomized: true, value: { modelChain: custom },
+ });
+ // Repeating restore is safe and never writes a default snapshot.
- expect((await resetBotModelChainSettings({ rootPath })).isCustomized).toBe(false);
++ expect((await resetBotModelChainSettings({ rootPath, providers })).isCustomized).toBe(false);
+ });
+
+ it('preserves disk and customized state if removing the override fails', async () => {
+ const rootPath = await testRoot();
+ const custom = [{ harness: 'pi', model: 'custom-model' }];
+ await writeBotModelChainSettings(custom, { rootPath });
+ const file = path.join(rootPath, 'bot-model-chain-settings.json');
+ const before = await fs.readFile(file, 'utf8');
+ const unlink = syncFs.unlinkSync;
+ vi.spyOn(syncFs, 'unlinkSync').mockImplementation((target) => {
+ if (target === file) throw new Error('permission denied');
+ unlink(target);
+ });
+ await expect(resetBotModelChainSettings({ rootPath })).rejects.toThrow('permission denied');
+ expect(await fs.readFile(file, 'utf8')).toBe(before);
- expect(readBotModelChainSettingsState({ rootPath }).isCustomized).toBe(true);
++ expect((await readBotModelChainSettingsState({ rootPath })).isCustomized).toBe(true);
+ });
+
+ it('does not clear either account when the owner changes while waiting for the lock', async () => {
+ owner.root = await testRoot();
+ owner.key = 'owner-a:1';
+ await writeBotModelChainSettings([{ harness: 'pi', model: 'owner-a-model' }]);
+ const file = path.join(owner.root, 'bot-model-chain-settings.json');
+ const before = await fs.readFile(file, 'utf8');
+ const oldRoot = owner.root;
+ const otherRoot = await testRoot();
+ await writeBotModelChainSettings([{ harness: 'pi', model: 'owner-b-model' }], { rootPath: otherRoot });
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (_path, _options, operation) => {
+ owner.root = otherRoot;
+ owner.key = 'owner-b:2';
+ return operation({ held: true });
+ });
+ await expect(resetBotModelChainSettings()).rejects.toThrow('scope changed');
+ expect(await fs.readFile(file, 'utf8')).toBe(before);
- expect(readBotModelChainSettingsState({ rootPath: oldRoot }).isCustomized).toBe(true);
- expect(readBotModelChainSettingsState({ rootPath: otherRoot }).value.modelChain[0]?.model).toBe('owner-b-model');
++ expect((await readBotModelChainSettingsState({ rootPath: oldRoot })).isCustomized).toBe(true);
++ expect((await readBotModelChainSettingsState({ rootPath: otherRoot })).value.modelChain[0]?.model).toBe('owner-b-model');
+ });
+
+ it('preserves the override if the shared lock cannot be acquired', async () => {
+ const rootPath = await testRoot();
+ await writeBotModelChainSettings([{ harness: 'pi', model: 'custom-model' }], { rootPath });
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (_path, _options, operation) => operation({ held: false, reason: 'busy' }));
+ await expect(resetBotModelChainSettings({ rootPath })).rejects.toThrow('busy');
- expect(readBotModelChainSettingsState({ rootPath }).isCustomized).toBe(true);
++ expect((await readBotModelChainSettingsState({ rootPath })).isCustomized).toBe(true);
+ });
+
});
diff --cc apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx
index 60bfa41199,29dc2c90d4..6257509c91
--- a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx
@@@ -3,10 -3,10 +3,12 @@@ import { useEffect, useRef, useState }
import { useBotTranslation } from './botPronounContext';
import { cn } from '@/lib/utils';
+import { useProviders } from '@/hooks/useProviders';
+import { useAvailableAgents } from '@/hooks/useAvailableAgents';
import {
getEffectiveBotModelChain,
+ isBotGlobalModelChainCustomized,
+ resetBotGlobalModelChain,
setBotGlobalModelChain,
subscribeBotGlobalModel,
} from './botStore';
@@@ -57,7 -64,16 +70,17 @@@ export function BotsGlobalSettingsSecti
{t('bots.globalSettings.description')}
</p>
</div>
- <BotModelChainEditor value={modelChain} onChange={saveModelChain} />
+ <fieldset disabled={pending} aria-busy={pending} className="min-w-0">
+ <BotModelChainEditor
++ disabled={pending}
+ value={modelChain}
+ onChange={(next) => changeModelChain(() => setBotGlobalModelChain(next))}
+ onRestoreDefault={customized !== false
+ ? () => changeModelChain(resetBotGlobalModelChain, true)
+ : undefined}
+ />
+ </fieldset>
+ <p className={ROW_HINT_CLASS}>{t('bots.globalSettings.restoreHint')}</p>
{notice ? (
<p className={ROW_HINT_CLASS} role="status">
{notice}
diff --cc apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx
index 8c2f0720e9,0000000000..1fad4b731b
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx
@@@ -1,178 -1,0 +1,198 @@@
+// @vitest-environment jsdom
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ProviderView } from '@cindy/model-providers';
+import type { BotModelRoute } from '../../../../shared/botModelChain';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/lib/localCatalogSnapshot', () => ({ refreshLocalCatalogSnapshot: vi.fn() }));
+vi.mock('@/hooks/useAgentCapabilities', () => ({
+ refreshLocalCapabilities: vi.fn(async () => {}),
+ evictDeviceCapabilities: vi.fn(),
+ prefetchDeviceCapabilities: vi.fn(async () => {}),
+}));
+vi.mock('@/state/modelVisibilityPrefs', () => ({ migrateModelVisibilityDefaults: vi.fn() }));
+vi.mock('@/state/newMakerDraft', () => ({
+ getDraft: () => ({ lastByVendor: { pi: {}, cc: {}, codex: {} } }),
+ getPersistedVendorModel: () => '',
+}));
+vi.mock('@/lib/modelDefinitions', () => ({
+ getDefaultModelForVendor: () => ({ id: '', defaultEffort: 'medium' }),
+}));
+vi.mock('../BotModelChainEditor', () => ({
+ BotModelChainEditor: ({ value, onChange }: {
+ value: BotModelRoute[];
+ onChange: (value: BotModelRoute[]) => void;
+ }) => (
+ <div>
+ <output data-testid="chain">{JSON.stringify(value)}</output>
+ <button onClick={() => onChange(value.map((route) => ({ ...route, effort: 'high' })))}>
+ Change effort
+ </button>
+ </div>
+ ),
+}));
+
+const gateway: BotModelRoute = {
+ harness: 'pi', providerId: 'xd', model: 'z-ai/glm-5.3-flash', effort: 'medium', fastMode: false,
+};
+const openai: BotModelRoute = {
+ harness: 'codex', providerId: 'openai', model: 'gpt-5.6-sol', effort: 'medium', fastMode: false,
+};
+
+function providers(gatewayConnected: boolean, openaiConnected: boolean): ProviderView[] {
+ return [gateway, openai].map((route, index) => ({
+ id: route.providerId,
+ name: route.providerId,
+ source: 'builtin',
+ connected: index === 0 ? gatewayConnected : openaiConnected,
+ agents: [route.harness],
+ access: index === 0 ? { kind: 'managed' } : { kind: 'subscription', product: 'openai' },
+ models: { [route.harness]: [{
+ id: route.model, name: route.model, status: 'active', sortOrder: 0,
+ contextWindow: 200_000, efforts: ['medium', 'high'], defaultEffort: 'medium',
+ supportsFastMode: false, newSessionDefault: [route.harness], supportsImageInput: true,
+ }] },
+ })) as unknown as ProviderView[];
+}
+
+function shownChain(): BotModelRoute[] {
+ return JSON.parse(screen.getByTestId('chain').textContent ?? '[]');
+}
+
+async function setup(options: { customized?: boolean; empty?: boolean; pending?: boolean } = {}) {
+ const listeners = new Set<() => void>();
+ const initial = options.empty ? [] : [gateway];
+ let resolveSettings!: (state: { modelChain: BotModelRoute[]; isCustomized: boolean }) => void;
+ const getModelChainSettings = vi.fn(() => options.pending
+ ? new Promise<{ modelChain: BotModelRoute[]; isCustomized: boolean }>((resolve) => {
+ resolveSettings = resolve;
+ })
+ : Promise.resolve({ modelChain: initial, isCustomized: options.customized === true }));
+ const setModelChainSettings = vi.fn(async ({ modelChain }: { modelChain: BotModelRoute[] }) => ({
+ modelChain, isCustomized: true,
+ }));
++ const resetModelChainSettings = vi.fn(async () => ({ modelChain: [gateway], isCustomized: false }));
+ const list = vi.fn(async () => []);
+ const create = vi.fn(async (input: Record<string, unknown>) => ({
+ ...input, enabled: true, createdAt: 1, sessions: [],
+ }));
+ const listAvailableAgents = vi.fn(async (): Promise<('pi' | 'codex')[]> => ['pi', 'codex']);
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: {
- localDb: { bots: { getModelChainSettings, setModelChainSettings, list, create } },
++ localDb: { bots: { getModelChainSettings, setModelChainSettings, resetModelChainSettings, list, create } },
+ maker: {
+ listAvailableAgents,
+ onAgentsChanged: (listener: () => void) => { listeners.add(listener); return () => listeners.delete(listener); },
+ },
+ } });
+ const snapshots = await import('@/lib/providersSnapshotStore');
+ const publish = (next: ProviderView[]) => act(() => {
+ snapshots.commitProvidersSnapshot(snapshots.beginProvidersRefresh(), {
+ dataOwnerId: null, ownerGeneration: 0, providers: next, providerOrder: next.map((item) => item.id),
+ });
+ });
+ publish(providers(!options.empty, false));
+ const store = await import('../botStore');
+ await waitFor(() => expect(getModelChainSettings).toHaveBeenCalledOnce());
+ if (!options.pending) await waitFor(() => expect(list).toHaveBeenCalledOnce());
+ const { BotsGlobalSettingsSection } = await import('../BotsGlobalSettingsSection');
+ render(<BotsGlobalSettingsSection />);
+ await waitFor(() => expect(listAvailableAgents).toHaveBeenCalledOnce());
+ const agents = await import('@/hooks/useAvailableAgents');
+ await waitFor(() => expect(agents.getCachedAvailableVendors()).toEqual(new Set(['pi', 'codex'])));
+ return {
- store, publish, getModelChainSettings, setModelChainSettings, resolveSettings,
++ store, publish, getModelChainSettings, setModelChainSettings, resetModelChainSettings, resolveSettings,
+ changeAgents: async (next: ('pi' | 'codex')[]) => {
+ listAvailableAgents.mockResolvedValue(next);
+ await act(async () => { for (const listener of listeners) listener(); });
+ await waitFor(() => expect(agents.getCachedAvailableVendors()).toEqual(new Set(next)));
+ },
+ };
+}
+
+beforeEach(() => { vi.resetModules(); window.localStorage.clear(); });
+afterEach(() => cleanup());
+
+describe('live derived Bot defaults', () => {
+ it('updates the mounted global editor after a connection change and saves effort on the new route', async () => {
+ const api = await setup();
+ expect(shownChain()).toEqual([gateway]);
+ api.publish(providers(false, true));
+ expect(shownChain()).toEqual([openai]);
+ expect(api.store.getEffectiveBotModelChain()).toEqual([openai]); // Restore-default consumer.
+ expect(api.setModelChainSettings).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByText('Change effort'));
+ await waitFor(() => expect(api.setModelChainSettings).toHaveBeenCalledWith({
+ modelChain: [{ ...openai, effort: 'high' }],
+ }));
+ api.publish(providers(true, false));
+ expect(shownChain()).toEqual([{ ...openai, effort: 'high' }]);
+ });
+
+ it('recovers a hydrated empty chain after connecting and returns to empty after disconnecting', async () => {
+ const api = await setup({ empty: true });
+ expect(shownChain()).toEqual([]);
+ api.publish(providers(false, true));
+ expect(shownChain()).toEqual([openai]);
+ api.publish(providers(false, false));
+ expect(shownChain()).toEqual([]);
+ });
+
+ it('recomputes defaults when engines are removed or installed without a provider update', async () => {
+ const api = await setup();
+ api.publish(providers(true, true));
+ expect(shownChain()).toEqual([gateway, openai]);
+ await api.changeAgents(['codex']);
+ expect(shownChain()).toEqual([openai]);
+ await api.changeAgents([]);
+ expect(shownChain()).toEqual([]);
+ await api.changeAgents(['pi', 'codex']);
+ expect(shownChain()).toEqual([gateway, openai]);
+ });
+
+ it('preserves a hydrated explicit global override across provider and engine changes', async () => {
+ const api = await setup({ customized: true });
+ api.publish(providers(false, true));
+ await api.changeAgents(['codex']);
+ expect(shownChain()).toEqual([gateway]);
+ expect(api.store.getEffectiveBotModelChain()).toEqual([gateway]);
+ expect(api.setModelChainSettings).not.toHaveBeenCalled();
+ });
+
+ it('does not revive an obsolete default when its hydration response arrives after a source change', async () => {
+ const api = await setup({ pending: true });
+ api.publish(providers(false, true));
+ await act(async () => api.resolveSettings({ modelChain: [gateway], isCustomized: false }));
+ expect(shownChain()).toEqual([openai]);
+ expect(api.store.getEffectiveBotModelChain()).toEqual([openai]);
+ });
+
++ it('keeps restored defaults live when sources change while reset is pending', async () => {
++ const api = await setup({ customized: true });
++ let finishReset!: (state: { modelChain: BotModelRoute[]; isCustomized: boolean }) => void;
++ api.resetModelChainSettings.mockImplementationOnce(() => new Promise((resolve) => { finishReset = resolve; }));
++ let reset!: Promise<void>;
++ await act(async () => { reset = api.store.resetBotGlobalModelChain(); });
++ expect(api.resetModelChainSettings).toHaveBeenCalledOnce();
++ api.publish(providers(false, true));
++ await act(async () => {
++ finishReset({ modelChain: [gateway], isCustomized: false });
++ await reset;
++ });
++ expect(shownChain()).toEqual([openai]);
++ expect(api.store.isBotGlobalModelChainCustomized()).toBe(false);
++ api.publish(providers(false, false));
++ expect(shownChain()).toEqual([]);
++ expect(api.setModelChainSettings).not.toHaveBeenCalled();
++ });
++
+ it('also expires the derived settings cached by profile creation', async () => {
+ const api = await setup();
+ await act(async () => { await api.store.addBotProfileAndWait({ name: 'Helper', description: '' }); });
+ expect(api.getModelChainSettings).toHaveBeenCalledTimes(2);
+ api.publish(providers(false, true));
+ expect(api.store.getEffectiveBotModelChain()).toEqual([openai]);
+ expect(shownChain()).toEqual([openai]);
+ });
+});
diff --cc apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx
index 830ae3b71a,815ac62082..bc13a5230d
--- a/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx
@@@ -30,10 -32,9 +32,11 @@@ vi.mock('react-i18next', () => (
vi.mock('@/components/new-chat/ModelSelector', () => ({
ModelSelector: () => <div data-testid="model-selector" />,
}));
+vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({}) }));
+vi.mock('@/hooks/useAvailableAgents', () => ({ useAvailableAgents: () => ({}) }));
vi.mock('../BotModelChainEditor', () => ({
- BotModelChainEditor: ({ onChange }: { onChange: (value: unknown[]) => void }) => (
+ BotModelChainEditor: ({ onChange, onRestoreDefault }: { onChange: (value: unknown[]) => void; onRestoreDefault?: () => void }) => (
+ <>
<button type="button" onClick={() => onChange([{
harness: 'pi',
model: 'z-ai/glm-5.3-flash',
diff --cc apps/desktop/src/renderer/features/bots/botStore.ts
index c86c37d849,03082474c3..8475c94ff2
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@@ -225,18 -281,28 +225,39 @@@ const BOT_GLOBAL_MODEL_KEY = 'cindy.bot
const BOT_GLOBAL_MODEL_CHAIN_KEY = 'cindy.bots.global-model-chain.v2';
type BotModelVendor = ReturnType<typeof vendorForHarness>;
const botModelListeners = new Set<() => void>();
-let globalModelChainCache: BotModelRoute[] | null = null;
+function getDefaultModelInputs() {
+ return {
+ providers: getCachedProvidersSnapshot(),
+ availableAgents: getCachedAvailableVendors(),
+ };
+}
+
+let globalModelChainCache: {
+ modelChain: BotModelRoute[];
+ /** null means an explicit override; derived results are leased to their inputs. */
+ defaultInputs: ReturnType<typeof getDefaultModelInputs> | null;
+} | null = null;
+ // Unknown until Main answers; a failed read must not hide the recovery action.
+ let globalModelChainCustomized: boolean | null = null;
+ // Serialize writes and legacy migration with settings reads. A late read must not
+ // reapply an old override, and a migration must finish before a requested reset.
+ let modelSettingsQueue: Promise<unknown> = Promise.resolve();
+
+ function queueModelSettings<T>(operation: () => Promise<T>): Promise<T> {
+ ensureProfileOwner();
+ const owner = getDataOwnerGeneration();
+ const result = modelSettingsQueue.then(async () => {
+ assertCurrentOwner(owner);
+ return operation();
+ });
+ modelSettingsQueue = result.catch(() => undefined);
+ return result;
+ }
+
+ export function isBotGlobalModelChainCustomized(): boolean | null {
+ ensureProfileOwner();
+ return globalModelChainCustomized;
+ }
function readGlobalModelOverrides(): Partial<Record<BotModelVendor, BotModelOverride>> {
if (typeof window === 'undefined') return {};
@@@ -321,29 -381,31 +342,30 @@@ export function getEffectiveBotModelCha
): 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> {
- ensureProfileOwner();
- const owner = getDataOwnerGeneration();
- const api = botsApi();
- if (!api || typeof api.setModelChainSettings !== 'function') {
- throw new Error('Bot model settings are not ready');
- }
- const normalized = normalizeBotModelChain(chain);
- if (normalized.length === 0) throw new Error('Choose at least one Bot model route');
- const state = await api.setModelChainSettings({ modelChain: normalized });
- assertCurrentOwner(owner);
-function applyGlobalModelChain(state: { modelChain: BotModelRoute[]; isCustomized: boolean }): void {
++function applyGlobalModelChain(
++ state: { modelChain: BotModelRoute[]; isCustomized: boolean },
++ defaultInputs: ReturnType<typeof getDefaultModelInputs>,
++): void {
const persisted = normalizeBotModelChain(state.modelChain);
- if (persisted.length === 0) throw new Error('Bot model settings were not saved');
- globalModelChainCache = { modelChain: persisted, defaultInputs: null };
- globalModelChainCache = persisted;
++ globalModelChainCache = { modelChain: persisted, defaultInputs: state.isCustomized ? null : defaultInputs };
+ globalModelChainCustomized = state.isCustomized;
window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);
- const primary = persisted[0]!;
+ projectGlobalModelChain();
+ for (const listener of botModelListeners) listener();
+ emit();
+ }
+
+ function projectGlobalModelChain(): void {
- const chain = globalModelChainCache;
- if (!chain) return;
++ if (!globalModelChainCache) return;
++ const chain = getEffectiveBotModelChain();
+ const primary = chain[0] ?? { model: '', providerId: null, effort: '', fastMode: false };
profiles = profiles.map((bot) =>
bot.capabilities.modelChainOverride === null
? {
@@@ -358,8 -420,39 +380,41 @@@
}
: bot,
);
- for (const listener of botModelListeners) listener();
- emit();
+ }
+
+ export async function setBotGlobalModelChain(chain: BotModelRoute[]): Promise<void> {
+ const normalized = normalizeBotModelChain(chain);
+ if (normalized.length === 0) throw new Error('Choose at least one Bot model route');
+ return queueModelSettings(async () => {
+ const owner = getDataOwnerGeneration();
+ const api = botsApi();
+ if (!api || typeof api.setModelChainSettings !== 'function') {
+ throw new Error('Bot model settings are not ready');
+ }
++ const defaultInputs = getDefaultModelInputs();
+ const state = await api.setModelChainSettings({ modelChain: normalized });
+ assertCurrentOwner(owner);
+ if (normalizeBotModelChain(state.modelChain).length === 0) {
+ throw new Error('Bot model settings were not saved');
+ }
- applyGlobalModelChain(state);
++ applyGlobalModelChain(state, defaultInputs);
+ });
+ }
+
+ export function resetBotGlobalModelChain(): Promise<void> {
+ return queueModelSettings(async () => {
+ const owner = getDataOwnerGeneration();
+ const api = botsApi();
+ if (!api || typeof api.resetModelChainSettings !== 'function') {
+ throw new Error('Bot model settings are not ready');
+ }
++ const defaultInputs = getDefaultModelInputs();
+ const state = await api.resetModelChainSettings();
+ assertCurrentOwner(owner);
+ // A default resolver may return no available models. Do not turn that into
+ // a failed reset or save the derived chain as a new override.
- applyGlobalModelChain(state);
++ applyGlobalModelChain(state, defaultInputs);
+ });
}
function defaultCapabilities(
@@@ -659,23 -754,17 +716,18 @@@ async function hydrateFromDatabase(): P
try {
if (typeof api.getModelChainSettings === 'function') {
try {
- // Capture before the IPC read: a late response must not renew a default
- // computed before a provider/roster change with the newer inputs.
- const defaultInputs = getDefaultModelInputs();
- let state = await api.getModelChainSettings();
- if (!isCurrent()) return;
- const legacy = readLegacyBotGlobalModelChain();
- if (!state.isCustomized && legacy && typeof api.setModelChainSettings === 'function') {
- state = await api.setModelChainSettings({ modelChain: legacy });
+ await queueModelSettings(async () => {
if (!isCurrent()) return;
- }
- const persisted = normalizeBotModelChain(state.modelChain);
- globalModelChainCache = {
- modelChain: persisted,
- defaultInputs: state.isCustomized ? null : defaultInputs,
- };
- window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);
- for (const listener of botModelListeners) listener();
++ const defaultInputs = getDefaultModelInputs();
+ let state = await api.getModelChainSettings();
+ if (!isCurrent()) return;
+ const legacy = readLegacyBotGlobalModelChain();
+ if (!state.isCustomized && legacy && typeof api.setModelChainSettings === 'function') {
+ state = await api.setModelChainSettings({ modelChain: legacy });
+ if (!isCurrent()) return;
+ }
- applyGlobalModelChain(state);
++ applyGlobalModelChain(state, defaultInputs);
+ });
} catch {
// Profile hydration remains usable if the settings file is temporarily
// unavailable. A later explicit refresh retries the Main-owned source.
@@@ -831,23 -919,7 +884,22 @@@ export async function addBotProfileAndW
if (needsPiDefault && getCachedProvidersSnapshot() === null && typeof window !== 'undefined') {
await refreshLocalCatalogSnapshot();
}
+ const settingsApi = botsApi();
+ if (settingsApi?.getModelChainSettings) {
- const defaultInputs = getDefaultModelInputs();
- const state = await settingsApi.getModelChainSettings();
- assertCurrentOwner(owner);
- globalModelChainCache = {
- modelChain: normalizeBotModelChain(state.modelChain),
- defaultInputs: state.isCustomized ? null : defaultInputs,
- };
++ await queueModelSettings(async () => {
++ const defaultInputs = getDefaultModelInputs();
++ const state = await settingsApi.getModelChainSettings();
++ assertCurrentOwner(owner);
++ applyGlobalModelChain(state, defaultInputs);
++ });
+ }
assertCurrentOwner(owner);
+ const requested = input.capabilities;
+ const explicit = normalizeBotModelChain(requested?.modelChainOverride, requested?.modelOverride
+ ? { harness: requested.harness, ...requested.modelOverride } : null);
+ if (!explicit.length && !getEffectiveBotModelChain().length) {
+ throw new BotModelSelectionRequiredError();
+ }
const bot = addBotProfile(input);
const api = botsApi();
if (!api) return bot;