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): refresh derived defaults when provider and engine state changes

zqchris5bf23876f75f
diff --git a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx
index 519cbfcdf1..60bfa41199 100644
--- a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx
@@ -3,6 +3,8 @@ import { useEffect, useState } from 'react';
import { useBotTranslation } from './botPronounContext';
import { cn } from '@/lib/utils';
+import { useProviders } from '@/hooks/useProviders';
+import { useAvailableAgents } from '@/hooks/useAvailableAgents';
import {
getEffectiveBotModelChain,
setBotGlobalModelChain,
@@ -22,6 +24,10 @@ const ROW_HINT_CLASS =
export function BotsGlobalSettingsSection() {
const { t } = useBotTranslation();
+ // Re-render derived defaults when the shared picker inputs change, including
+ // when the empty-chain editor has no ModelSelector mounted yet.
+ useProviders();
+ useAvailableAgents();
const [, bumpModelSettings] = useState(0);
const [notice, setNotice] = useState<string | null>(null);
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx
new file mode 100644
index 0000000000..8c2f0720e9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botModelChainDefaults.test.tsx
@@ -0,0 +1,178 @@
+// @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 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 } },
+ 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,
+ 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('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 --git a/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx
index 0fe590a7a5..830ae3b71a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx
@@ -30,6 +30,8 @@ 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 }) => (
<button type="button" onClick={() => onChange([{
diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.ts
index 62d5c146c9..c86c37d849 100644
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@ -225,7 +225,18 @@ const BOT_GLOBAL_MODEL_KEY = 'cindy.bots.global-model-overrides.v1';
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;
function readGlobalModelOverrides(): Partial<Record<BotModelVendor, BotModelOverride>> {
if (typeof window === 'undefined') return {};
@@ -284,7 +295,13 @@ export function subscribeBotGlobalModel(listener: () => void): () => void {
export function getBotGlobalModelChain(): BotModelRoute[] | null {
ensureProfileOwner();
- return globalModelChainCache;
+ if (!globalModelChainCache) return null;
+ const inputs = globalModelChainCache.defaultInputs;
+ if (inputs && (
+ inputs.providers !== getCachedProvidersSnapshot()
+ || inputs.availableAgents !== getCachedAvailableVendors()
+ )) return null;
+ return globalModelChainCache.modelChain;
}
function readLegacyBotGlobalModelChain(): BotModelRoute[] | null {
@@ -324,7 +341,7 @@ export async function setBotGlobalModelChain(chain: BotModelRoute[]): Promise<vo
assertCurrentOwner(owner);
const persisted = normalizeBotModelChain(state.modelChain);
if (persisted.length === 0) throw new Error('Bot model settings were not saved');
- globalModelChainCache = persisted;
+ globalModelChainCache = { modelChain: persisted, defaultInputs: null };
window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);
const primary = persisted[0]!;
profiles = profiles.map((bot) =>
@@ -642,6 +659,9 @@ async function hydrateFromDatabase(): Promise<void> {
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();
@@ -650,7 +670,10 @@ async function hydrateFromDatabase(): Promise<void> {
if (!isCurrent()) return;
}
const persisted = normalizeBotModelChain(state.modelChain);
- globalModelChainCache = persisted;
+ globalModelChainCache = {
+ modelChain: persisted,
+ defaultInputs: state.isCustomized ? null : defaultInputs,
+ };
window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);
for (const listener of botModelListeners) listener();
} catch {
@@ -810,9 +833,13 @@ export async function addBotProfileAndWait(input: CreateBotProfileInput): Promis
}
const settingsApi = botsApi();
if (settingsApi?.getModelChainSettings) {
+ const defaultInputs = getDefaultModelInputs();
const state = await settingsApi.getModelChainSettings();
assertCurrentOwner(owner);
- globalModelChainCache = normalizeBotModelChain(state.modelChain);
+ globalModelChainCache = {
+ modelChain: normalizeBotModelChain(state.modelChain),
+ defaultInputs: state.isCustomized ? null : defaultInputs,
+ };
}
assertCurrentOwner(owner);
const requested = input.capabilities;