Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 支持伙伴全局模型恢复默认 (#4143)
Chris Zhang9630a9c8f28b
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex dcd2ed7bea..191dc6c64f 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -147,6 +147,7 @@ import {listBotRemoteResourceSources,} from '../bots';import { tx as runWorkerTx } from '../../worker/opHandlers/tx.js';+import * as modelSettings from '../../../maker-host/bot-model-chain-settings-store.js';import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';import { runDeviceLinkInvokeContext } from '../../../device-link/invoke-context.js';import {@@ -423,6 +424,36 @@ beforeEach(async () => {});});+describe('Bot global model restore IPC', () => {+ it('checks the sender before clearing settings', async () => {+ const reset = vi.spyOn(modelSettings, 'resetBotModelChainSettings');+ vi.mocked(assertTrustedAppRendererEvent).mockImplementationOnce(() => { throw new Error('untrusted'); });+ try {+ await expect(invoke('local-db:bots:model-chain-settings-reset', undefined)).rejects.toThrow('untrusted');+ expect(reset).not.toHaveBeenCalled();+ } finally { reset.mockRestore(); }+ });++ it('returns the resolved state and sanitizes filesystem failures', async () => {+ const reset = vi.spyOn(modelSettings, 'resetBotModelChainSettings');+ try {+ reset.mockResolvedValueOnce({ value: { modelChain: [] }, defaults: { modelChain: [] }, isCustomized: false, customizedKeys: [] });+ await expect(invoke('local-db:bots:model-chain-settings-reset', undefined)).resolves.toEqual({ modelChain: [], isCustomized: false });+ reset.mockRejectedValueOnce(new Error('/private/account/settings.json: denied'));+ await expect(invoke('local-db:bots:model-chain-settings-reset', undefined)).rejects.toThrow('Could not restore Bot model defaults');+ } finally { reset.mockRestore(); }+ });++ it('rejects an account transition before clearing settings', async () => {+ const reset = vi.spyOn(modelSettings, 'resetBotModelChainSettings');+ try {+ h.ownerBoundaryPending = true;+ await expect(invoke('local-db:bots:model-chain-settings-reset', undefined)).rejects.toThrow('PRECONDITION_FAILED');+ expect(reset).not.toHaveBeenCalled();+ } finally { reset.mockRestore(); }+ });+});+describe('Bot canonical Session lifecycle', () => {it.each(['../bot', 'Bot', 'a:b', 'con', 'aux', 'lpt1'])('rejects nonportable new companion ID %s before persistence', async (id) => {diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex e5fd37961c..d2a269b0bb 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -35,6 +35,7 @@ import { ensureProjectGitInitialized } from '../../git-snapshot/projectGitBootstimport { readGitSafetySettings } from '../../maker-host/git-safety-settings-store.js';import {readBotModelChainSettingsState,+ resetBotModelChainSettings,readEffectiveBotModelChain,writeBotModelChainSettings,} from '../../maker-host/bot-model-chain-settings-store.js';@@ -1093,6 +1094,20 @@ export function registerBotIpc(): void {return { modelChain: state.value.modelChain, isCustomized: state.isCustomized };});+ // Global model preferences are desktop-local settings, like get/set above.+ ipcMain.handle('local-db:bots:model-chain-settings-reset', async (event) => {+ assertTrustedAppRendererEvent(event);+ const owner = captureBotOperationOwner();+ try {+ const state = await resetBotModelChainSettings();+ owner.assertCurrent();+ return { modelChain: state.value.modelChain, isCustomized: state.isCustomized };+ } catch {+ owner.assertCurrent();+ throwIpcError('INTERNAL', 'Could not restore Bot model defaults');+ }+ });+ipcMain.handle('local-db:bots:list', async (event, raw: unknown) => {const remote = isDeviceLinkInvoke();if (!remote) assertTrustedAppRendererEvent(event);diff --git a/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts b/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.tsindex c050bcd283..aa44c878b8 100644--- a/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/botModelChainSettingsStore.test.ts@@ -1,15 +1,25 @@import fs from 'node:fs/promises';+import syncFs from 'node:fs';+import * as locks from '../../device-link/crossProcessLock';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {readBotModelChainSettingsState,+ resetBotModelChainSettings,readEffectiveBotModelChain,writeBotModelChainSettings,} from '../bot-model-chain-settings-store';+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> {@@ -19,6 +29,7 @@ async function testRoot(): Promise<string> {}afterEach(async () => {+ vi.restoreAllMocks();await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));});@@ -92,4 +103,70 @@ describe('bot model chain settings store', () => {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 custom = [{ ...defaults[0]!, model: 'custom-model' }];+ await writeBotModelChainSettings(defaults, { rootPath });+ await writeBotModelChainSettings(custom, { rootPath: otherRoot });+ expect(readBotModelChainSettingsState({ rootPath }).isCustomized).toBe(true);++ expect(await resetBotModelChainSettings({ rootPath })).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({+ isCustomized: true, value: { modelChain: custom },+ });+ // Repeating restore is safe and never writes a default snapshot.+ expect((await resetBotModelChainSettings({ rootPath })).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);+ });++ 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');+ });++ 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);+ });+});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.tsindex 54d6397854..d08218a35b 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@@ -11,7 +11,7 @@ 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 {createOverrideSettingsFile,@@ -65,7 +65,7 @@ function currentStore(rootPath?: string) {label: 'bot-model-chain',scopeKey: rootPath? () => `root:${rootPath}`- : () => getActiveAppSession().dataOwnerId ?? '<global>',+ : activeOwnerScopeKey,});stores.set(key, current);}@@ -100,6 +100,18 @@ export async function writeBotModelChainSettings(return store.readState();}+/** Clear only the current owner's global override, then use the normal default resolver. */+export async function resetBotModelChainSettings(+ options?: Parameters<typeof readBotModelChainSettingsState>[0],+): Promise<OverrideSettingsState<BotModelChainSettings>> {+ const owner = activeOwnerScopeKey();+ await currentStore(options?.rootPath).resetAtomic();+ if (!options?.rootPath && activeOwnerScopeKey() !== owner) {+ throw new Error('Bot model settings owner changed');+ }+ return readBotModelChainSettingsState(options);+}+/*** A null override means the permanent Bot Profile follows the owner-scoped* global route chain. Explicit per-Bot chains remain frozen in its profile.diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex cb14290ffb..c9986e33af 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5117,6 +5117,10 @@ contextBridge.exposeInMainWorld('electronAPI', {modelChain: import('../shared/botModelChain').BotModelRoute[];isCustomized: boolean;}> => ipcRenderer.invoke('local-db:bots:model-chain-settings-get'),+ resetModelChainSettings: (): Promise<{+ modelChain: import('../shared/botModelChain').BotModelRoute[];+ isCustomized: boolean;+ }> => ipcRenderer.invoke('local-db:bots:model-chain-settings-reset'),setModelChainSettings: (body: {modelChain: import('../shared/botModelChain').BotModelRoute[];}): Promise<{diff --git a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsxindex 519cbfcdf1..29dc2c90d4 100644--- a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx@@ -1,10 +1,12 @@/** Shared default model chain; individual teammates may override it. */-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { useBotTranslation } from './botPronounContext';import { cn } from '@/lib/utils';import {getEffectiveBotModelChain,+ isBotGlobalModelChainCustomized,+ resetBotGlobalModelChain,setBotGlobalModelChain,subscribeBotGlobalModel,} from './botStore';@@ -27,11 +29,22 @@ export function BotsGlobalSettingsSection() {useEffect(() => subscribeBotGlobalModel(() => bumpModelSettings((value) => value + 1)), []);const modelChain = getEffectiveBotModelChain();+ const customized = isBotGlobalModelChainCustomized();+ const pendingRef = useRef(false);+ const [pending, setPending] = useState(false);- const saveModelChain = (next: typeof modelChain) => {+ const changeModelChain = (operation: () => Promise<void>, restoring = false) => {+ if (pendingRef.current) return;+ pendingRef.current = true;+ setPending(true);setNotice(null);- void setBotGlobalModelChain(next).catch((error: unknown) => {- setNotice(error instanceof Error ? error.message : String(error));+ void operation().catch((error: unknown) => {+ setNotice(restoring+ ? t('bots.globalSettings.restoreFailed')+ : error instanceof Error ? error.message : String(error));+ }).finally(() => {+ pendingRef.current = false;+ setPending(false);});};@@ -51,7 +64,16 @@ export function BotsGlobalSettingsSection() {{t('bots.globalSettings.description')}</p></div>- <BotModelChainEditor value={modelChain} onChange={saveModelChain} />+ <fieldset disabled={pending} aria-busy={pending} className="min-w-0">+ <BotModelChainEditor+ 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 --git a/apps/desktop/src/renderer/features/bots/__tests__/botStore.modelSettings.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botStore.modelSettings.test.tsnew file mode 100644index 0000000000..8f15258c2e--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/botStore.modelSettings.test.ts@@ -0,0 +1,159 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/state/newMakerDraft', () => ({+ getDraft: () => ({ lastByVendor: { cc: {}, codex: {}, pi: {} } }),+ getPersistedVendorModel: () => '',+}));+vi.mock('@/lib/modelDefinitions', () => ({+ getDefaultModelForVendor: () => ({ id: 'default', defaultEffort: 'medium' }),+}));+vi.mock('../botReadState', () => ({+ getBotLastReadAtMap: () => ({}), pruneBotReadState: vi.fn(), seedMissingBotReadState: vi.fn(),+}));++const route = (model: string) => ({ harness: 'pi' as const, model, providerId: 'xd', effort: '', fastMode: false });+const saved = { modelChain: [route('saved')], isCustomized: true };+const defaults = { modelChain: [route('current-default')], isCustomized: false };+const legacyKey = 'cindy.bots.global-model-chain.v2';+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => { resolve = r; });+ return { promise, resolve };+}+function apiFixture() {+ let disk = saved;+ const api = {+ list: vi.fn(async () => [] as unknown[]),+ getModelChainSettings: vi.fn(async () => disk),+ setModelChainSettings: vi.fn(async ({ modelChain }: { modelChain: typeof saved.modelChain }) => {+ disk = { modelChain, isCustomized: true };+ return disk;+ }),+ resetModelChainSettings: vi.fn(async () => { disk = defaults; return disk; }),+ };+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { localDb: { bots: api } } });+ return api;+}+async function hydratedStore(api: ReturnType<typeof apiFixture>) {+ const store = await import('../botStore');+ await vi.waitFor(() => expect(api.list).toHaveBeenCalledOnce());+ return store;+}++beforeEach(() => { vi.resetModules(); window.localStorage.clear(); });++describe('global teammate model restore', () => {+ it('refreshes followers, preserves explicit per-Bot models, and drops the legacy cache', async () => {+ const api = apiFixture();+ const bot = { id: 'following', name: 'Follower', capabilities: { ...route('saved'), modelChain: saved.modelChain, modelChainOverride: null, modelOverride: null } };+ api.list.mockResolvedValueOnce([bot, { ...bot, id: 'custom', capabilities: { ...bot.capabilities, modelChainOverride: [route('per-bot')] } }]);+ const store = await hydratedStore(api);+ window.localStorage.setItem(legacyKey, JSON.stringify(saved.modelChain));+ const listener = vi.fn();+ store.subscribeBotGlobalModel(listener);+ await store.resetBotGlobalModelChain();+ expect(store.getEffectiveBotModelChain()).toEqual(defaults.modelChain);+ expect(store.isBotGlobalModelChainCustomized()).toBe(false);+ expect(store.getBotProfiles().find((b) => b.id === 'following')?.capabilities.modelChain).toEqual(defaults.modelChain);+ expect(store.getBotProfiles().find((b) => b.id === 'custom')?.capabilities.modelChainOverride).toEqual([route('per-bot')]);+ expect(window.localStorage.getItem(legacyKey)).toBeNull();+ expect(api.setModelChainSettings).not.toHaveBeenCalled();+ expect(listener).toHaveBeenCalledOnce();+ store.refreshBotProfiles();+ await vi.waitFor(() => expect(api.list).toHaveBeenCalledTimes(2));+ expect(store.isBotGlobalModelChainCustomized()).toBe(false);+ expect(api.setModelChainSettings).not.toHaveBeenCalled();+ });++ it('preserves state after reset failure and allows the next save to succeed', async () => {+ const api = apiFixture();+ const store = await hydratedStore(api);+ api.resetModelChainSettings.mockRejectedValueOnce(new Error('reset failed'));+ await expect(store.resetBotGlobalModelChain()).rejects.toThrow('reset failed');+ expect(store.getEffectiveBotModelChain()).toEqual(saved.modelChain);+ expect(store.isBotGlobalModelChainCustomized()).toBe(true);+ await store.setBotGlobalModelChain([route('next')]);+ expect(store.getEffectiveBotModelChain()).toEqual([route('next')]);+ });++ it('serializes save, restore and save in user order', async () => {+ const api = apiFixture();+ const store = await hydratedStore(api);+ const pending = deferred<typeof saved>();+ api.setModelChainSettings.mockReturnValueOnce(pending.promise);+ const first = store.setBotGlobalModelChain([route('first')]);+ const reset = store.resetBotGlobalModelChain();+ const last = store.setBotGlobalModelChain([route('last')]);+ await vi.waitFor(() => expect(api.setModelChainSettings).toHaveBeenCalledOnce());+ expect(api.resetModelChainSettings).not.toHaveBeenCalled();+ pending.resolve({ ...saved, modelChain: [route('first')] });+ await Promise.all([first, reset, last]);+ expect(store.getEffectiveBotModelChain()).toEqual([route('last')]);+ expect(store.isBotGlobalModelChainCustomized()).toBe(true);+ expect(api.resetModelChainSettings.mock.invocationCallOrder[0]).toBeLessThan(api.setModelChainSettings.mock.invocationCallOrder[1]!);+ });++ it('finishes a late legacy migration before restore, so it cannot resurrect the override', async () => {+ const api = apiFixture();+ const read = deferred<typeof defaults>();+ api.getModelChainSettings.mockReturnValueOnce(read.promise);+ window.localStorage.setItem(legacyKey, JSON.stringify([route('legacy')]));+ const store = await import('../botStore');+ await vi.waitFor(() => expect(api.getModelChainSettings).toHaveBeenCalledOnce());+ const reset = store.resetBotGlobalModelChain();+ read.resolve(defaults);+ await reset;+ expect(api.setModelChainSettings).toHaveBeenCalledWith({ modelChain: [route('legacy')] });+ expect(api.setModelChainSettings.mock.invocationCallOrder[0]).toBeLessThan(api.resetModelChainSettings.mock.invocationCallOrder[0]!);+ expect(store.getEffectiveBotModelChain()).toEqual(defaults.modelChain);+ expect(store.isBotGlobalModelChainCustomized()).toBe(false);+ expect(window.localStorage.getItem(legacyKey)).toBeNull();+ });++ it('rejects old-owner responses and queued writes before they reach the new account', async () => {+ const api = apiFixture();+ const store = await hydratedStore(api);+ const owner = await import('@/contexts/dataOwnerGeneration');+ const pending = deferred<typeof defaults>();+ api.resetModelChainSettings.mockReturnValueOnce(pending.promise);+ const reset = store.resetBotGlobalModelChain();+ const queued = store.setBotGlobalModelChain([route('old-owner')]);+ const resetRejected = expect(reset).rejects.toThrow('owner changed');+ const queuedRejected = expect(queued).rejects.toThrow('owner changed');+ await vi.waitFor(() => expect(api.resetModelChainSettings).toHaveBeenCalledOnce());+ owner.setDataOwnerGeneration('next-owner');+ const nextChain = [route('new-owner')];+ await store.setBotGlobalModelChain(nextChain);+ pending.resolve(defaults);+ await Promise.all([resetRejected, queuedRejected]);+ expect(store.getEffectiveBotModelChain()).toEqual(nextChain);+ expect(api.setModelChainSettings).toHaveBeenCalledTimes(1);+ });++ it('accepts an empty derived default and later refreshed defaults without persisting them', async () => {+ const api = apiFixture();+ const store = await hydratedStore(api);+ api.resetModelChainSettings.mockResolvedValueOnce({ modelChain: [], isCustomized: false });+ await store.resetBotGlobalModelChain();+ expect(store.getEffectiveBotModelChain()).toEqual([]);+ api.getModelChainSettings.mockResolvedValueOnce({ modelChain: [route('new-source-default')], isCustomized: false });+ store.refreshBotProfiles();+ await vi.waitFor(() => expect(store.getEffectiveBotModelChain()).toEqual([route('new-source-default')]));+ expect(api.setModelChainSettings).not.toHaveBeenCalled();+ expect(store.isBotGlobalModelChainCustomized()).toBe(false);+ });+ it('keeps initial read failure unknown and allows direct recovery without visiting the roster', async () => {+ const api = apiFixture();+ api.getModelChainSettings.mockRejectedValueOnce(new Error('temporarily unavailable'));+ const store = await hydratedStore(api);+ expect(store.isBotGlobalModelChainCustomized()).toBeNull();+ await store.resetBotGlobalModelChain();+ expect(api.getModelChainSettings).toHaveBeenCalledOnce();+ expect(api.resetModelChainSettings).toHaveBeenCalledOnce();+ expect(api.setModelChainSettings).not.toHaveBeenCalled();+ expect(store.isBotGlobalModelChainCustomized()).toBe(false);+ expect(store.getEffectiveBotModelChain()).toEqual(defaults.modelChain);+ });++});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsxindex 0fe590a7a5..815ac62082 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botsGlobalSettingsSection.test.tsx@@ -18,6 +18,8 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ resetBotGlobalModelChain: vi.fn(async (): Promise<void> => undefined),+ customized: true as boolean | null,setBotGlobalModelChain: vi.fn(async (_chain: unknown[]) => undefined),}));@@ -31,7 +33,8 @@ vi.mock('@/components/new-chat/ModelSelector', () => ({ModelSelector: () => <div data-testid="model-selector" />,}));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',@@ -39,9 +42,13 @@ vi.mock('../BotModelChainEditor', () => ({effort: 'high',fastMode: false,}])}>model-chain-editor</button>+ {onRestoreDefault && <button onClick={onRestoreDefault}>restore-default</button>}+ </>),}));vi.mock('../botStore', () => ({+ isBotGlobalModelChainCustomized: () => mocks.customized,+ resetBotGlobalModelChain: () => mocks.resetBotGlobalModelChain(),getEffectiveBotModelChain: () => [{harness: 'pi',model: 'z-ai/glm-5.3-flash',@@ -57,6 +64,8 @@ import { BotsGlobalSettingsSection } from '../BotsGlobalSettingsSection';beforeEach(() => {mocks.setBotGlobalModelChain.mockClear();+ mocks.resetBotGlobalModelChain.mockReset();+ mocks.customized = true;});afterEach(() => cleanup());@@ -96,4 +105,41 @@ describe('设置 › 伙伴', () => {expect.objectContaining({ harness: 'pi', model: 'z-ai/glm-5.3-flash' }),]));});+ it('restores through the dedicated reset operation and prevents duplicate clicks', async () => {+ let finish!: () => void;+ mocks.resetBotGlobalModelChain.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));+ render(<BotsGlobalSettingsSection />);+ fireEvent.click(screen.getByText('restore-default'));+ fireEvent.click(screen.getByText('restore-default'));+ fireEvent.click(screen.getByText('model-chain-editor'));+ expect(mocks.resetBotGlobalModelChain).toHaveBeenCalledOnce();+ expect(mocks.setBotGlobalModelChain).not.toHaveBeenCalled();+ finish();+ await waitFor(() => expect(screen.getByText('restore-default').closest('fieldset')?.disabled).toBe(false));+ });++ it('keeps failures visible and allows retry without saving a default snapshot', async () => {+ mocks.resetBotGlobalModelChain.mockRejectedValueOnce(new Error('internal path'));+ render(<BotsGlobalSettingsSection />);+ fireEvent.click(screen.getByText('restore-default'));+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('bots.globalSettings.restoreFailed'));+ fireEvent.click(screen.getByText('restore-default'));+ await waitFor(() => expect(mocks.resetBotGlobalModelChain).toHaveBeenCalledTimes(2));+ expect(mocks.setBotGlobalModelChain).not.toHaveBeenCalled();+ });++ it('only offers restore for an explicit customization', () => {+ mocks.customized = false;+ render(<BotsGlobalSettingsSection />);+ expect(screen.queryByText('restore-default')).toBeNull();+ });++ it('keeps restore reachable while customization is unknown after a failed read', async () => {+ mocks.customized = null;+ render(<BotsGlobalSettingsSection />);+ fireEvent.click(screen.getByText('restore-default'));+ await waitFor(() => expect(mocks.resetBotGlobalModelChain).toHaveBeenCalledOnce());+ expect(mocks.setBotGlobalModelChain).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.tsindex bd53b093d0..03082474c3 100644--- a/apps/desktop/src/renderer/features/bots/botStore.ts+++ b/apps/desktop/src/renderer/features/bots/botStore.ts@@ -282,6 +282,27 @@ 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;+// 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 {};@@ -371,22 +392,20 @@ export function getEffectiveBotModelChain(];}-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 {const persisted = normalizeBotModelChain(state.modelChain);- if (persisted.length === 0) throw new Error('Bot model settings were not saved');globalModelChainCache = persisted;+ 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;+ const primary = chain[0] ?? { model: '', providerId: null, effort: '', fastMode: false };profiles = profiles.map((bot) =>bot.capabilities.modelChainOverride === null? {@@ -395,14 +414,45 @@ export async function setBotGlobalModelChain(chain: BotModelRoute[]): Promise<vo...bot.capabilities,...primary,modelOverride: null,- modelChain: persisted,+ modelChain: chain,modelChainOverride: null,},}: 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 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);+ });+}++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 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);+ });}function defaultCapabilities(@@ -485,6 +535,8 @@ function ensureProfileOwner(): void {profiles = [];unreadCounts = {};globalModelChainCache = null;+ globalModelChainCustomized = null;+ modelSettingsQueue = Promise.resolve();profileWriteGenerations.clear();hydrationPromises.clear();hydrationGeneration += 1;@@ -702,19 +754,17 @@ async function hydrateFromDatabase(): Promise<void> {try {if (typeof api.getModelChainSettings === 'function') {try {- 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);- if (persisted.length > 0) {- globalModelChainCache = persisted;- window.localStorage.removeItem(BOT_GLOBAL_MODEL_CHAIN_KEY);- for (const listener of botModelListeners) listener();- }+ 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);+ });} catch {// Profile hydration remains usable if the settings file is temporarily// unavailable. A later explicit refresh retries the Main-owned source.@@ -725,6 +775,7 @@ async function hydrateFromDatabase(): Promise<void> {if (!isCurrent()) return;const dbProfiles = rows.map(normalizeDbProfile).filter((item): item is BotProfile => !!item);profiles = dbProfiles;+ projectGlobalModelChain();applyUnreadCounts(rows);// A Bot we have never tracked starts read: shipping unread badges must not// retroactively mark every existing conversation as unread. Pruning keepsdiff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex debdee9e00..c8cc90a023 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7165,6 +7165,8 @@"composerPlaceholderLatin": "Say something to {{name}}…"},"globalSettings": {+ "restoreHint": "Restoring defaults follows the client’s default model settings. Individual teammates’ custom models stay unchanged.",+ "restoreFailed": "Could not restore defaults. Try again.","title": "Teammates","description": "Settings shared by all teammates. Anything about one teammate lives on their own page.","rosterNote": "The shipped roster grows with each release."diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex afd11717f0..a5eddf4f40 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7163,6 +7163,8 @@"composerPlaceholderLatin": "{{name}} に話しかける…"},"globalSettings": {+ "restoreHint": "復元後はクライアントの既定のモデル設定に従います。各パートナーのカスタムモデルは変更されません。",+ "restoreFailed": "既定値を復元できませんでした。もう一度お試しください。","title": "パートナー","description": "パートナー全体に共通する設定です。個々のパートナーの設定は、その子のページにあります。","rosterNote": "あらかじめ用意された顔ぶれは、バージョンごとに増えていきます。"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 3d23f66f24..d772821b6e 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7163,6 +7163,8 @@"composerPlaceholderLatin": "{{name}} 에게 말 걸기…"},"globalSettings": {+ "restoreHint": "기본값으로 복원하면 클라이언트의 기본 모델 설정을 따릅니다. 개별 파트너의 사용자 지정 모델은 유지됩니다.",+ "restoreFailed": "기본값을 복원하지 못했습니다. 다시 시도해 주세요.","title": "파트너","description": "파트너 전체에 적용되는 설정입니다. 개별 파트너 설정은 각자의 페이지에 있어요.","rosterNote": "기본 제공되는 구성원은 버전마다 늘어납니다."diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex fc35b0b9f2..a97c4af21d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7163,6 +7163,8 @@"composerPlaceholderLatin": "跟 {{name}} 说点什么…"},"globalSettings": {+ "restoreHint": "恢复默认后将跟随客户端默认模型设置,单个伙伴的自定义模型保持不变。",+ "restoreFailed": "恢复默认失败,请重试。","title": "伙伴","description": "和伙伴有关的通用设置。单个伙伴的设置在{{pronoun}}自己的页面里。","rosterNote": "预置阵容会随版本更新。"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 4a7c86caaf..c86f53f6fe 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7163,6 +7163,8 @@"composerPlaceholderLatin": "跟 {{name}} 說點什麼…"},"globalSettings": {+ "restoreHint": "恢復預設後將跟隨用戶端預設模型設定,個別夥伴的自訂模型保持不變。",+ "restoreFailed": "恢復預設失敗,請重試。","title": "伙伴","description": "和伙伴有關的通用設定。單個伙伴的設定在{{pronoun}}自己的頁面裡。","rosterNote": "預置陣容會隨版本更新。"diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex b2dee83984..4622d62ce0 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4535,6 +4535,10 @@ interface ElectronAPI {modelChain: import('../shared/botModelChain').BotModelRoute[];isCustomized: boolean;}>;+ resetModelChainSettings: () => Promise<{+ modelChain: import('../shared/botModelChain').BotModelRoute[];+ isCustomized: boolean;+ }>;setModelChainSettings: (body: {modelChain: import('../shared/botModelChain').BotModelRoute[];}) => Promise<{