Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(aiModel): move reasoning config and disabled models onto @lobechat/replica (#21315)

Arvin Xue7d3888f57be
diff --git a/src/features/Settings/provider/features/ModelList/DisabledModels.test.tsx b/src/features/Settings/provider/features/ModelList/DisabledModels.test.tsx
new file mode 100644
index 00000000000..7bd28f0d256
--- /dev/null
+++ b/src/features/Settings/provider/features/ModelList/DisabledModels.test.tsx
@@ -0,0 +1,83 @@
+import { act, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiModelService } from '@/services/aiModel';
+
+import DisabledModels from './DisabledModels';
+
+const models = Array.from({ length: 40 }, (_, i) => ({
+ enabled: false,
+ id: `model-${i}`,
+ type: 'chat',
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/store/aiInfra', () => ({
+ useAiInfraStore: (selector: (s: any) => unknown) => selector({ disabledModels: models }),
+}));
+
+vi.mock('@/store/aiInfra/selectors', () => ({
+ aiModelSelectors: {
+ disabledAiProviderModelList: (s: any) => s.disabledModels,
+ },
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (s: any) => unknown) =>
+ selector({ status: { disabledModelsSortType: 'default' }, updateSystemStatus: vi.fn() }),
+}));
+
+vi.mock('./ModelItem', () => ({
+ default: ({ id }: { id: string }) => <div data-testid="model-item">{id}</div>,
+}));
+
+describe('DisabledModels', () => {
+ let intersect: (() => void) | undefined;
+
+ beforeEach(() => {
+ intersect = undefined;
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor(callback: IntersectionObserverCallback) {
+ intersect = () =>
+ callback(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ disconnect() {}
+ observe() {}
+ },
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('renders every disabled model from the model-list replica without fetching pages', async () => {
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiProviderModelList').mockResolvedValue([]);
+
+ render(<DisabledModels activeTab="all" providerId="openai" />);
+
+ // First paint is windowed
+ expect(screen.getAllByTestId('model-item')).toHaveLength(30);
+
+ // Scrolling reveals the rest of the rows already in the replica
+ act(() => intersect?.());
+ expect(screen.getAllByTestId('model-item')).toHaveLength(40);
+
+ // Reaching the end must not refetch rows the replica already holds
+ act(() => intersect?.());
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 20));
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Settings/provider/features/ModelList/DisabledModels.tsx b/src/features/Settings/provider/features/ModelList/DisabledModels.tsx
index ef88bb1fe1d..5c17f0ff982 100644
--- a/src/features/Settings/provider/features/ModelList/DisabledModels.tsx
+++ b/src/features/Settings/provider/features/ModelList/DisabledModels.tsx
@@ -2,13 +2,9 @@ import type { ItemType } from '@lobehub/ui';
import { ActionIcon, DropdownMenu, Flexbox, Icon, Text, TooltipGroup } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { ArrowDownUpIcon, LucideCheck } from 'lucide-react';
-import { type AiProviderModelListItem } from 'model-bank';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWRInfinite from 'swr/infinite';
-import { aiModelKeys } from '@/libs/swr/keys';
-import { aiModelService } from '@/services/aiModel';
import { useAiInfraStore } from '@/store/aiInfra';
import { aiModelSelectors } from '@/store/aiInfra/selectors';
import { useGlobalStore } from '@/store/global';
@@ -33,16 +29,16 @@ enum SortType {
const PAGE_SIZE = 30;
const DisabledModels = memo<DisabledModelsProps>(({ activeTab, providerId }) => {
- const { t } = useTranslation(['modelProvider', 'common']);
+ const { t } = useTranslation('modelProvider');
const [sortType, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.disabledModelsSortType(s),
s.updateSystemStatus,
]);
- // Only render at most PAGE_SIZE items from the store on first paint.
- // As user scrolls, we reveal more store items in PAGE_SIZE steps, then start remote loading.
- const [visibleBaseSize, setVisibleBaseSize] = useState(PAGE_SIZE);
+ // Only render at most PAGE_SIZE items on first paint and reveal more in
+ // PAGE_SIZE steps as the user scrolls.
+ const [visibleSize, setVisibleSize] = useState(PAGE_SIZE);
const updateSortType = useCallback(
(newSortType: SortType) => {
@@ -51,101 +47,31 @@ const DisabledModels = memo<DisabledModelsProps>(({ activeTab, providerId }) =>
[updateSystemStatus],
);
- // initial render source: provider list already in store (typically built-in + user merged)
+ // The provider's model-list replica already holds every model (enabled and
+ // disabled), so the section renders from it β€” painted from the persisted
+ // copy on the first frame β€” and never refetches pages of the same rows.
const disabledModels = useAiInfraStore(aiModelSelectors.disabledAiProviderModelList, isEqual);
- const baseIds = useMemo(() => new Set(disabledModels.map((m) => m.id)), [disabledModels]);
-
useEffect(() => {
// reset visible window on provider change
- setVisibleBaseSize(PAGE_SIZE);
+ setVisibleSize(PAGE_SIZE);
}, [providerId]);
- const visibleBaseModels = useMemo(
- () => disabledModels.slice(0, visibleBaseSize),
- [disabledModels, visibleBaseSize],
- );
-
- const hasMoreBase = visibleBaseSize < disabledModels.length;
- const remoteEnabled = !!providerId && !hasMoreBase;
-
- const getKey = useCallback(
- (pageIndex: number, previousPageData: AiProviderModelListItem[] | null) => {
- if (!remoteEnabled) return null;
- if (previousPageData && previousPageData.length < PAGE_SIZE) return null;
-
- // start fetching after the initial list from store
- const offset = disabledModels.length + pageIndex * PAGE_SIZE;
- return aiModelKeys.disabledModelsPage(providerId, offset);
- },
- [disabledModels.length, providerId, remoteEnabled],
+ const sourceDisabledModels = useMemo(
+ () => disabledModels.slice(0, visibleSize),
+ [disabledModels, visibleSize],
);
- const {
- data: pages,
- error,
- isValidating,
- setSize,
- size,
- } = useSWRInfinite<AiProviderModelListItem[]>(getKey, async ([, id, offset]) => {
- return aiModelService.getAiProviderModelList(id as string, {
- enabled: false,
- limit: PAGE_SIZE,
- offset: offset as number,
- });
- });
-
- const pagedDisabledModels = useMemo(() => (pages ? pages.flat() : []), [pages]);
-
- // ensure "load more" pages do not duplicate the initial store list
- const appendedDisabledModels = useMemo(() => {
- if (!pagedDisabledModels.length) return [];
- return pagedDisabledModels.filter((m) => !baseIds.has(m.id));
- }, [baseIds, pagedDisabledModels]);
-
- const mergedDisabledModels = useMemo(() => {
- // keep store order for initial items; append new ones afterwards
- const exists = new Set<string>();
- const merged: AiProviderModelListItem[] = [];
-
- visibleBaseModels.forEach((m) => {
- if (exists.has(m.id)) return;
- exists.add(m.id);
- merged.push(m);
- });
-
- appendedDisabledModels.forEach((m) => {
- if (exists.has(m.id)) return;
- exists.add(m.id);
- merged.push(m);
- });
-
- return merged;
- }, [appendedDisabledModels, visibleBaseModels]);
-
- const isInitialLoading = remoteEnabled && !pages && !error;
- const isReachingEnd = useMemo(() => {
- if (!pages || pages.length === 0) return false;
- const lastPage = pages.at(-1);
- if (!lastPage) return false;
- return lastPage.length < PAGE_SIZE;
- }, [pages]);
- const isLoadingMore = isValidating && size > 0 && !!pages && pages.length < size;
+ const hasMore = visibleSize < disabledModels.length;
const loadMoreRef = useRef<HTMLDivElement>(null);
const triggerLoadMore = useCallback(() => {
- if (hasMoreBase) {
- setVisibleBaseSize((v) => Math.min(v + PAGE_SIZE, disabledModels.length));
- return;
- }
- if (isReachingEnd) return;
- if (isValidating) return;
- setSize(size + 1);
- }, [disabledModels.length, hasMoreBase, isReachingEnd, isValidating, setSize, size]);
+ setVisibleSize((v) => Math.min(v + PAGE_SIZE, disabledModels.length));
+ }, [disabledModels.length]);
useEffect(() => {
- if (!hasMoreBase && isReachingEnd) return;
+ if (!hasMore) return;
if (!loadMoreRef.current) return;
const observer = new IntersectionObserver(
@@ -166,12 +92,9 @@ const DisabledModels = memo<DisabledModelsProps>(({ activeTab, providerId }) =>
return () => {
observer.disconnect();
};
- }, [hasMoreBase, isReachingEnd, triggerLoadMore]);
+ }, [hasMore, triggerLoadMore]);
- const sourceDisabledModels = mergedDisabledModels;
-
- const shouldRenderSection =
- disabledModels.length > 0 || isInitialLoading || sourceDisabledModels.length > 0;
+ const shouldRenderSection = disabledModels.length > 0;
// Filter models based on active tab
const filteredDisabledModels = useMemo(() => {
@@ -305,11 +228,6 @@ const DisabledModels = memo<DisabledModelsProps>(({ activeTab, providerId }) =>
<Flexbox horizontal align="center" justify="center" paddingBlock={8}>
<div ref={loadMoreRef} style={{ height: 1, width: '0' }} />
- {(isInitialLoading || isLoadingMore) && (
- <Text style={{ fontSize: 12, marginTop: 4 }} type={'secondary'}>
- {t('common:loading')}
- </Text>
- )}
</Flexbox>
</Flexbox>
)
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
index ca9d8c5310f..254734a9ff5 100644
--- a/src/libs/replica/index.ts
+++ b/src/libs/replica/index.ts
@@ -83,6 +83,31 @@ export const cacheScope: ReplicaScope = {
use: useSourceScope,
};
+/**
+ * The identity half of a cache scope (`${userId}:${workspaceId}`), with the
+ * workspace replaced by a marker no workspace id can take.
+ */
+export const identityScopeOf = (scope: string): string => {
+ const separator = scope.indexOf(':');
+ return `${separator === -1 ? scope : scope.slice(0, separator)}:*`;
+};
+
+/**
+ * A scope partitioned by identity only, for data the server owns per user and
+ * shares across workspaces (user memories, personal model preferences).
+ *
+ * Partitioning such a resource per workspace lets a switch hydrate another
+ * workspace's older persisted copy, and leaves one `clear()` unable to reach
+ * the rows written in the others. The gates still follow the live scope, so an
+ * untrusted (identity-unresolved) scope keeps refusing writes.
+ */
+export const identityOnlyScope: ReplicaScope = {
+ canHydrate: () => cacheScope.canHydrate?.() ?? true,
+ canPersist: () => cacheScope.canPersist(),
+ get: () => identityScopeOf(cacheScope.get()),
+ use: () => identityScopeOf(cacheScope.use()),
+};
+
export type ReplicaStorageKind = 'indexedDB' | 'localStorage' | 'memory';
type AppStorageOption<TData> =
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 38e7ebae466..3dbe6245a7a 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -304,23 +304,6 @@ export const agentConfigKeys = {
search: def('agent:search', (keyword?: string) => ['agent:search', keyword]),
};
-// ---- aiModel ------------------------------------------------------------
-// The provider model list and the provider list live in `@lobechat/replica`
-// resources now (see `src/store/aiInfra/slices/*/projection.ts`); only the
-// paged disabled-models fetch and the per-model reasoning config are SWR keys.
-export const aiModelKeys = {
- disabledModelsPage: def('aiModel:disabledModelsPage', (providerId: string, offset: number) => [
- 'aiModel:disabledModelsPage',
- providerId,
- offset,
- ]),
- reasoningConfig: def('aiModel:reasoningConfig', (provider: string, model: string) => [
- 'aiModel:reasoningConfig',
- provider,
- model,
- ]),
-};
-
// ---- image generation ---------------------------------------------------
// The topic list and the per-topic batches live in `@lobechat/replica`
// resources now (see `src/store/image/slices/*/projection.ts`); only the
@@ -955,7 +938,6 @@ export const swrKeys = {
agentDocument: agentDocumentSWRKeys,
agentHome: agentHomeKeys,
agentSignal: agentSignalKeys,
- aiModel: aiModelKeys,
auth: authKeys,
brief: briefKeys,
changelog: changelogKeys,
diff --git a/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.ts b/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.ts
new file mode 100644
index 00000000000..425028d9a86
--- /dev/null
+++ b/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.ts
@@ -0,0 +1,675 @@
+import { randomUUID } from 'node:crypto';
+
+import { toast } from '@lobehub/ui';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type * as I18nextModule from 'i18next';
+import { t } from 'i18next';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, identityScopeOf } from '@/libs/replica';
+import type * as SwrModule from '@/libs/swr';
+import { aiModelService } from '@/services/aiModel';
+import { withSWR } from '~test-utils';
+
+import { useAiInfraStore as useStore } from '../../store';
+import { initialAIModelState } from './initialState';
+import { aiModelReasoningConfigResource } from './projection';
+import { aiModelSelectors } from './selectors';
+
+vi.mock('i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof I18nextModule>();
+ return {
+ ...actual,
+ t: vi.fn((key: string) => key),
+ };
+});
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
+
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const actual = await importOriginal<typeof SwrModule>();
+ return {
+ ...actual,
+ mutate: vi.fn(),
+ };
+});
+
+/**
+ * The per-model-instance reasoning config is a replica
+ * (`modelReasoningConfigMap[provider/model]`): it paints from the persisted
+ * copy on the first frame, the network only confirms, and a save persists the
+ * confirmed value. Read it through the selectors.
+ */
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const REASONING_PARAMS = { model: 'gpt-5.2', provider: 'openai' };
+const REASONING_STORAGE_KEY = aiModelReasoningConfigResource.storageKey(REASONING_PARAMS);
+
+describe('AiModelAction reasoning config', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ /** Reasoning configs are personal, so their rows land in the identity partition. */
+ const rowScope = (value = scope) => identityScopeOf(value);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useScope(`ai-model-user-${randomUUID()}:personal`);
+
+ // Reset store to initial state
+ act(() => {
+ useStore.setState({
+ ...initialAIModelState,
+ activeAiProvider: 'test-provider',
+ refreshAiProviderRuntimeState: vi.fn(),
+ });
+ });
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].map((value) =>
+ aiModelReasoningConfigResource.storage!.remove({
+ queryKey: REASONING_STORAGE_KEY,
+ scope: identityScopeOf(value),
+ }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ });
+
+ describe('updateModelReasoningConfig', () => {
+ it('should optimistically merge the value and persist it via the service', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'updateAiModelReasoningConfig')
+ .mockResolvedValue(undefined as any);
+
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ expect(serviceSpy).toHaveBeenCalledWith('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ // merged with the previous value, not replaced
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ reasoningEffort: 'low',
+ });
+ expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
+ });
+
+ it('should refresh after clearing the updating marker and adopt the server-merged value', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockResolvedValue(undefined as any);
+
+ // The replica drops responses while the key is marked updating, so
+ // refreshing before the marker clears would discard the server-merged
+ // config (sibling fields preserved by the partial write)
+ const updatingKeysAtFetch: string[][] = [];
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(async () => {
+ updatingKeysAtFetch.push([...useStore.getState().modelReasoningConfigUpdatingKeys]);
+ return { gpt5_2ReasoningEffort: 'high', reasoningEffort: 'medium' };
+ });
+
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ expect(updatingKeysAtFetch).toEqual([[]]);
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ reasoningEffort: 'medium',
+ });
+ });
+
+ it('persists the saved value so a reload paints it even when the refresh fails', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockResolvedValue(undefined as any);
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockRejectedValue(new Error('offline'));
+
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ await waitFor(async () =>
+ expect(
+ (
+ await aiModelReasoningConfigResource.storage!.get({
+ queryKey: REASONING_STORAGE_KEY,
+ scope: rowScope(),
+ })
+ )?.data,
+ ).toEqual({ value: { gpt5_2ReasoningEffort: 'high' } }),
+ );
+ });
+
+ it('keeps a save that settles after a scope switch out of the new scope', async () => {
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(pending);
+ const sync = renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
+ { wrapper },
+ );
+ let finishSave!: () => void;
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockImplementation(
+ () => new Promise((r) => (finishSave = () => r(undefined as any))),
+ );
+ const fetchSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockResolvedValue({ reasoningEffort: 'low' });
+
+ let saving!: Promise<void>;
+ act(() => {
+ saving = useStore.getState().updateModelReasoningConfig('gpt-5.2', 'openai', {
+ reasoningEffort: 'high',
+ });
+ });
+
+ // The account / workspace changes while the save is in flight
+ useScope(`ai-model-user-${randomUUID()}:personal`);
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(pending);
+ sync.rerender();
+ await waitFor(() =>
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false),
+ );
+ fetchSpy.mockClear();
+
+ await act(async () => {
+ finishSave();
+ await saving;
+ });
+
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
+ expect(
+ useStore.getState().modelReasoningConfigReplica.entries['openai/gpt-5.2'],
+ ).toBeUndefined();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ await new Promise((r) => setTimeout(r, 50));
+ expect(
+ await aiModelReasoningConfigResource.storage!.get({
+ queryKey: REASONING_STORAGE_KEY,
+ scope: rowScope(),
+ }),
+ ).toBeUndefined();
+ });
+
+ it('lets the new scope load the model while a save of the previous scope is in flight', async () => {
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(pending);
+ const sync = renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
+ { wrapper },
+ );
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockImplementation(pending);
+ act(() => {
+ void useStore.getState().updateModelReasoningConfig('gpt-5.2', 'openai', {
+ reasoningEffort: 'high',
+ });
+ });
+ expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual(['openai/gpt-5.2']);
+
+ // Switch identity; the new scope's own config must land
+ useScope(`ai-model-user-${randomUUID()}:personal`);
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
+ reasoningEffort: 'low',
+ });
+ sync.rerender();
+
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ }),
+ );
+ expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
+ });
+
+ it('should rollback the optimistic value and toast on failure', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockRejectedValue(
+ new Error('Service error'),
+ );
+
+ await expect(async () => {
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+ }).rejects.toThrow('Service error');
+
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ });
+ expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
+ expect(toast.error).toHaveBeenCalledWith(t('reasoningEffort.updateFailed', { ns: 'chat' }));
+ });
+
+ it('should drop the key on failed rollback when it was not cached before', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockRejectedValue(
+ new Error('Service error'),
+ );
+
+ await expect(async () => {
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+ }).rejects.toThrow('Service error');
+
+ // A leftover `[key]: undefined` would make ensureModelReasoningConfig
+ // treat the key as cached and never fetch the saved server value
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
+ });
+ });
+
+ describe('ensureModelReasoningConfig', () => {
+ beforeEach(() => {
+ vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => true);
+ // Make the runtime-state warm-up a no-op so tests exercise the fetch logic
+ act(() => {
+ useStore.setState({ isInitAiProviderRuntimeState: true });
+ });
+ });
+
+ it('should skip the fetch for models without reasoning extend params', async () => {
+ vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => false);
+
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-4o', 'openai');
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ });
+
+ it('should fetch and cache the config when the key is absent', async () => {
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockResolvedValue({ reasoningEffort: 'high' });
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ });
+
+ expect(serviceSpy).toHaveBeenCalledWith('gpt-5.2', 'openai');
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'high',
+ });
+ });
+
+ it('should keep the key for an empty config so it is not refetched', async () => {
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ });
+
+ expect(serviceSpy).toHaveBeenCalledTimes(1);
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(true);
+ });
+
+ it('should not fetch when the config is already cached', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ });
+ });
+
+ it('confirms a value only restored from the local replica before the send path uses it', async () => {
+ await aiModelReasoningConfigResource.storage!.set(
+ { queryKey: REASONING_STORAGE_KEY, scope: rowScope() },
+ { data: { value: { reasoningEffort: 'low' } }, updatedAt: 1 },
+ );
+ let resolve!: (value: { reasoningEffort: 'high' }) => void;
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockImplementation(() => new Promise((r) => (resolve = r)));
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ }),
+ );
+
+ // The stale copy is not trusted: ensure waits for the server answer
+ let settled = false;
+ const ensured = useStore
+ .getState()
+ .ensureModelReasoningConfig('gpt-5.2', 'openai')
+ .then(() => (settled = true));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(settled).toBe(false);
+
+ await act(async () => {
+ resolve({ reasoningEffort: 'high' });
+ await ensured;
+ });
+
+ expect(serviceSpy).toHaveBeenCalledTimes(1);
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'high',
+ });
+ });
+
+ it('should swallow fetch failures', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockRejectedValue(
+ new Error('Service error'),
+ );
+
+ await act(async () => {
+ await expect(
+ result.current.ensureModelReasoningConfig('gpt-5.2', 'openai'),
+ ).resolves.toBeUndefined();
+ });
+
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
+ });
+ });
+
+ describe('useFetchAiModelReasoningConfig', () => {
+ it('paints the persisted config before the network answers, then adopts the server value', async () => {
+ await aiModelReasoningConfigResource.storage!.set(
+ { queryKey: REASONING_STORAGE_KEY, scope: rowScope() },
+ { data: { value: { gpt5_2ReasoningEffort: 'low' } }, updatedAt: 1 },
+ );
+ let resolve!: (value: { gpt5_2ReasoningEffort: 'high' }) => void;
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(
+ () => new Promise((r) => (resolve = r)),
+ );
+
+ const sync = renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
+ { wrapper },
+ );
+
+ // First frame after a reload: the saved level, before any response
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'low',
+ }),
+ );
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(
+ aiModelSelectors.isModelReasoningConfigLoaded('gpt-5.2', 'openai')(useStore.getState()),
+ ).toBe(true);
+
+ await act(async () => resolve({ gpt5_2ReasoningEffort: 'high' }));
+
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ }),
+ );
+ await waitFor(async () =>
+ expect(
+ (
+ await aiModelReasoningConfigResource.storage!.get({
+ queryKey: REASONING_STORAGE_KEY,
+ scope: rowScope(),
+ })
+ )?.data,
+ ).toEqual({ value: { gpt5_2ReasoningEffort: 'high' } }),
+ );
+ });
+
+ it('repaints the saved config after a reload before the network answers', async () => {
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
+ reasoningEffort: 'high',
+ });
+ const first = renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'high',
+ }),
+ );
+ // let the confirmed value reach storage
+ await new Promise((r) => setTimeout(r, 50));
+ first.unmount();
+
+ // Reload: a fresh store and query cache, and a network that has not answered
+ act(() => {
+ useStore.setState({ ...initialAIModelState });
+ });
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(pending);
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'high',
+ }),
+ );
+ });
+
+ it('should not fetch when model or provider is missing', () => {
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
+
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig(undefined, 'openai'), {
+ wrapper,
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ });
+
+ it('sends one request for every surface mounted on the same model', async () => {
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockResolvedValue({ reasoningEffort: 'high' });
+
+ // ChatInput loader, the Params sub-agent controls and the profile picker
+ renderHook(
+ () => {
+ useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai');
+ useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai');
+ useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai');
+ },
+ { wrapper: withSWR },
+ );
+
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'high',
+ }),
+ );
+ expect(serviceSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the last saved value when the refresh fails', async () => {
+ await aiModelReasoningConfigResource.storage!.set(
+ { queryKey: REASONING_STORAGE_KEY, scope: rowScope() },
+ { data: { value: { reasoningEffort: 'low' } }, updatedAt: 1 },
+ );
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockRejectedValue(new Error('offline'));
+
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(serviceSpy).toHaveBeenCalled());
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ }),
+ );
+ });
+
+ it("never shows the previous identity's saved config after a scope switch", async () => {
+ const scopeA = scope;
+ await aiModelReasoningConfigResource.storage!.set(
+ { queryKey: REASONING_STORAGE_KEY, scope: rowScope(scopeA) },
+ { data: { value: { reasoningEffort: 'low' } }, updatedAt: 1 },
+ );
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(pending);
+
+ const sync = renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ }),
+ );
+
+ useScope(`ai-model-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() =>
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false),
+ );
+ expect(
+ aiModelSelectors.isModelReasoningConfigLoaded('gpt-5.2', 'openai')(useStore.getState()),
+ ).toBe(false);
+ });
+
+ it('should not clobber an in-flight optimistic value', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { gpt5_2ReasoningEffort: 'high' } },
+ modelReasoningConfigUpdatingKeys: ['openai/gpt-5.2'],
+ });
+ });
+
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
+ gpt5_2ReasoningEffort: 'low',
+ });
+
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalled();
+ });
+
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ it('settles a model with nothing saved as a loaded, undefined config', async () => {
+ // The server legitimately returns nothing when the user never customized
+ // this model's reasoning params; the key still counts as settled.
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue(undefined);
+
+ renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('test-model', 'test-provider'),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(
+ aiModelSelectors.isModelReasoningConfigLoaded(
+ 'test-model',
+ 'test-provider',
+ )(useStore.getState()),
+ ).toBe(true),
+ );
+ expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalledTimes(1);
+ expect(
+ useStore.getState().modelReasoningConfigMap['test-provider/test-model'],
+ ).toBeUndefined();
+ });
+ });
+
+ describe('seedModelReasoningConfigs', () => {
+ it('seeds the snapshot as confirmed entries and keeps an in-flight save', () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'high' } },
+ modelReasoningConfigUpdatingKeys: ['openai/gpt-5.2'],
+ });
+ });
+
+ act(() => {
+ useStore.getState().seedModelReasoningConfigs(
+ { 'anthropic/claude-sonnet-4-5': { reasoningEffort: 'low' } },
+ [
+ { id: 'gpt-5.2', providerId: 'openai' },
+ { id: 'claude-sonnet-4-5', providerId: 'anthropic' },
+ ] as any,
+ );
+ });
+
+ const state = useStore.getState();
+ // A save in flight keeps its optimistic value and gets no replica entry.
+ expect(state.modelReasoningConfigMap['openai/gpt-5.2']).toEqual({ reasoningEffort: 'high' });
+ expect(state.modelReasoningConfigReplica.entries['openai/gpt-5.2']).toBeUndefined();
+ // The server's snapshot lands as a confirmed entry, so a hydration still
+ // in flight cannot repaint an older persisted row over it.
+ expect(state.modelReasoningConfigMap['anthropic/claude-sonnet-4-5']).toEqual({
+ reasoningEffort: 'low',
+ });
+ expect(
+ state.modelReasoningConfigReplica.entries['anthropic/claude-sonnet-4-5'],
+ ).toBeDefined();
+ });
+ });
+});
diff --git a/src/store/aiInfra/slices/aiModel/action.test.ts b/src/store/aiInfra/slices/aiModel/action.test.ts
index c99e4fa0ef4..0e1f29d2295 100644
--- a/src/store/aiInfra/slices/aiModel/action.test.ts
+++ b/src/store/aiInfra/slices/aiModel/action.test.ts
@@ -14,12 +14,10 @@ import { cacheScope } from '@/libs/replica';
import type * as SwrModule from '@/libs/swr';
import { mutate } from '@/libs/swr';
import { aiModelService } from '@/services/aiModel';
-import { withSWR } from '~test-utils';
import { useAiInfraStore as useStore } from '../../store';
import { initialAIModelState } from './initialState';
import { aiModelListResource } from './projection';
-import { aiModelSelectors } from './selectors';
vi.mock('i18next', async (importOriginal) => {
const actual = await importOriginal<typeof I18nextModule>();
@@ -687,195 +685,6 @@ describe('AiModelAction', () => {
});
});
- describe('updateModelReasoningConfig', () => {
- it('should optimistically merge the value and persist it via the service', async () => {
- act(() => {
- useStore.setState({
- modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
- });
- });
-
- const { result } = renderHook(() => useStore());
- const serviceSpy = vi
- .spyOn(aiModelService, 'updateAiModelReasoningConfig')
- .mockResolvedValue(undefined as any);
-
- await act(async () => {
- await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
- gpt5_2ReasoningEffort: 'high',
- });
- });
-
- expect(serviceSpy).toHaveBeenCalledWith('gpt-5.2', 'openai', {
- gpt5_2ReasoningEffort: 'high',
- });
- // merged with the previous value, not replaced
- expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
- gpt5_2ReasoningEffort: 'high',
- reasoningEffort: 'low',
- });
- expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
- expect(mutate).toHaveBeenCalledWith(['aiModel:reasoningConfig', 'openai', 'gpt-5.2']);
- });
-
- it('should clear the updating marker before revalidating', async () => {
- const { result } = renderHook(() => useStore());
- vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockResolvedValue(undefined as any);
-
- // The fetch hook's onSuccess skips writes while the key is marked
- // updating, so revalidating before the marker clears would discard the
- // server-merged config (sibling fields preserved by the partial write)
- const updatingKeysAtMutate: string[][] = [];
- vi.mocked(mutate).mockImplementationOnce(async () => {
- updatingKeysAtMutate.push([...useStore.getState().modelReasoningConfigUpdatingKeys]);
- return undefined as any;
- });
-
- await act(async () => {
- await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
- gpt5_2ReasoningEffort: 'high',
- });
- });
-
- expect(updatingKeysAtMutate).toEqual([[]]);
- });
-
- it('should rollback the optimistic value and toast on failure', async () => {
- act(() => {
- useStore.setState({
- modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
- });
- });
-
- const { result } = renderHook(() => useStore());
- vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockRejectedValue(
- new Error('Service error'),
- );
-
- await expect(async () => {
- await act(async () => {
- await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
- gpt5_2ReasoningEffort: 'high',
- });
- });
- }).rejects.toThrow('Service error');
-
- expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
- reasoningEffort: 'low',
- });
- expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
- expect(toast.error).toHaveBeenCalledWith(t('reasoningEffort.updateFailed', { ns: 'chat' }));
- });
-
- it('should drop the key on failed rollback when it was not cached before', async () => {
- const { result } = renderHook(() => useStore());
- vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockRejectedValue(
- new Error('Service error'),
- );
-
- await expect(async () => {
- await act(async () => {
- await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
- gpt5_2ReasoningEffort: 'high',
- });
- });
- }).rejects.toThrow('Service error');
-
- // A leftover `[key]: undefined` would make ensureModelReasoningConfig
- // treat the key as cached and never fetch the saved server value
- expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
- });
- });
-
- describe('ensureModelReasoningConfig', () => {
- beforeEach(() => {
- vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => true);
- // Make the runtime-state warm-up a no-op so tests exercise the fetch logic
- act(() => {
- useStore.setState({ isInitAiProviderRuntimeState: true });
- });
- });
-
- it('should skip the fetch for models without reasoning extend params', async () => {
- vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => false);
-
- const { result } = renderHook(() => useStore());
- const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
-
- await act(async () => {
- await result.current.ensureModelReasoningConfig('gpt-4o', 'openai');
- });
-
- expect(serviceSpy).not.toHaveBeenCalled();
- });
-
- it('should fetch and cache the config when the key is absent', async () => {
- const { result } = renderHook(() => useStore());
- const serviceSpy = vi
- .spyOn(aiModelService, 'getAiModelReasoningConfig')
- .mockResolvedValue({ reasoningEffort: 'high' });
-
- await act(async () => {
- await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
- });
-
- expect(serviceSpy).toHaveBeenCalledWith('gpt-5.2', 'openai');
- expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
- reasoningEffort: 'high',
- });
- });
-
- it('should keep the key for an empty config so it is not refetched', async () => {
- const { result } = renderHook(() => useStore());
- const serviceSpy = vi
- .spyOn(aiModelService, 'getAiModelReasoningConfig')
- .mockResolvedValue(undefined);
-
- await act(async () => {
- await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
- await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
- });
-
- expect(serviceSpy).toHaveBeenCalledTimes(1);
- expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(true);
- });
-
- it('should not fetch when the config is already cached', async () => {
- act(() => {
- useStore.setState({
- modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
- });
- });
-
- const { result } = renderHook(() => useStore());
- const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
-
- await act(async () => {
- await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
- });
-
- expect(serviceSpy).not.toHaveBeenCalled();
- expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
- reasoningEffort: 'low',
- });
- });
-
- it('should swallow fetch failures', async () => {
- const { result } = renderHook(() => useStore());
- vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockRejectedValue(
- new Error('Service error'),
- );
-
- await act(async () => {
- await expect(
- result.current.ensureModelReasoningConfig('gpt-5.2', 'openai'),
- ).resolves.toBeUndefined();
- });
-
- expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
- });
- });
-
describe('updateAiModelsConfig', () => {
it('should update model config and refresh list', async () => {
const updateData = {
@@ -994,80 +803,4 @@ describe('AiModelAction', () => {
expect(useStore.getState().aiModelListMap['provider-a']?.[0]?.id).toBe('provider-a-model');
});
});
-
- describe('useFetchAiModelReasoningConfig', () => {
- it('should fetch the reasoning config and write it to the store map', async () => {
- vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
- gpt5_2ReasoningEffort: 'high',
- });
-
- const { result } = renderHook(
- () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
- { wrapper: withSWR },
- );
-
- await waitFor(() => {
- expect(result.current.data).toEqual({ gpt5_2ReasoningEffort: 'high' });
- });
-
- expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalledWith('gpt-5.2', 'openai');
- expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
- gpt5_2ReasoningEffort: 'high',
- });
- });
-
- it('should not fetch when model or provider is missing', () => {
- const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
-
- renderHook(() => useStore.getState().useFetchAiModelReasoningConfig(undefined, 'openai'), {
- wrapper: withSWR,
- });
-
- expect(serviceSpy).not.toHaveBeenCalled();
- });
-
- it('should not clobber an in-flight optimistic value', async () => {
- act(() => {
- useStore.setState({
- modelReasoningConfigMap: { 'openai/gpt-5.2': { gpt5_2ReasoningEffort: 'high' } },
- modelReasoningConfigUpdatingKeys: ['openai/gpt-5.2'],
- });
- });
-
- vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
- gpt5_2ReasoningEffort: 'low',
- });
-
- renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {
- wrapper: withSWR,
- });
-
- await waitFor(() => {
- expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalled();
- });
-
- expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
- gpt5_2ReasoningEffort: 'high',
- });
- });
-
- it('resolves a missing config as null so SWR data is never undefined', async () => {
- // The server legitimately returns nothing when the user never customized
- // this model's reasoning params; `null` keeps that distinguishable from a
- // fetch that has not settled yet.
- vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue(undefined);
-
- const { result } = renderHook(
- () => useStore.getState().useFetchAiModelReasoningConfig('test-model', 'test-provider'),
- { wrapper: withSWR },
- );
-
- await waitFor(() => expect(result.current.data).toBeNull());
- expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalledTimes(1);
- // The store map keeps its `| undefined` contract β€” null never leaks in.
- expect(
- useStore.getState().modelReasoningConfigMap['test-provider/test-model'],
- ).toBeUndefined();
- });
- });
});
diff --git a/src/store/aiInfra/slices/aiModel/action.ts b/src/store/aiInfra/slices/aiModel/action.ts
index 63617c59479..35b19f50ca9 100644
--- a/src/store/aiInfra/slices/aiModel/action.ts
+++ b/src/store/aiInfra/slices/aiModel/action.ts
@@ -6,25 +6,61 @@ import type {
AiModelSortMap,
AiProviderModelListItem,
CreateAiModelParams,
+ EnabledAiModel,
ToggleAiModelEnableParams,
UpdateAiModelParams,
} from 'model-bank';
-import type { SWRResponse } from 'swr';
-import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { aiModelKeys } from '@/libs/swr/keys';
+import {
+ createReplicaSlice,
+ recordLens,
+ type ReplicaLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
import { aiModelService } from '@/services/aiModel';
import type { AiInfraStore } from '@/store/aiInfra/store';
import type { StoreSetter } from '@/store/types';
-import { modelReasoningConfigKey } from './initialState';
-import { aiModelListEntity, aiModelListResource } from './projection';
+import { modelReasoningConfigKey, seedModelReasoningConfigMap } from './initialState';
+import {
+ aiModelListEntity,
+ aiModelListResource,
+ type AiModelReasoningConfigEntry,
+ aiModelReasoningConfigResource,
+} from './projection';
import { aiModelSelectors } from './selectors';
import { deduplicateRemoteModels } from './utils';
const MAX_DUPLICATE_MODEL_IDS_IN_WARNING = 3;
+/**
+ * The effort picker, the chat input loader and the sub-agent controls can all
+ * mount for the same model at once; one request serves them all.
+ */
+const REASONING_CONFIG_DEDUPING_INTERVAL = 10_000;
+
+/**
+ * `modelReasoningConfigMap` keeps its flat `Record<key, config | undefined>`
+ * shape for the existing selectors: key presence means "settled", and an
+ * `undefined` value means "nothing saved". The replica entry wraps the value so
+ * that "nothing saved" is still a confirmed (and persisted) value.
+ */
+const modelReasoningConfigLens: ReplicaLens<AiInfraStore, AiModelReasoningConfigEntry> = {
+ // A scope reset also drops the previous scope's in-flight save markers:
+ // left behind, they would make the new scope drop its own responses.
+ clear: () => ({ modelReasoningConfigMap: {}, modelReasoningConfigUpdatingKeys: [] }),
+ get: (state, key) =>
+ key in state.modelReasoningConfigMap
+ ? { value: state.modelReasoningConfigMap[key] }
+ : undefined,
+ set: (state, key, data) => {
+ const modelReasoningConfigMap = { ...state.modelReasoningConfigMap };
+ if (data === undefined) delete modelReasoningConfigMap[key];
+ else modelReasoningConfigMap[key] = data.value;
+ return { modelReasoningConfigMap };
+ },
+};
+
/** Sync result of one provider's model list: replica flags plus the SWR-era aliases. */
export interface AiProviderModelsSyncResult extends ReplicaSyncResult {
/** The provider's models, `undefined` until the first entry lands. */
@@ -42,6 +78,7 @@ export const createAiModelSlice = (set: Setter, get: () => AiInfraStore, _api?:
export class AiModelActionImpl {
readonly #get: () => AiInfraStore;
readonly #list;
+ readonly #reasoningConfig;
readonly #set: Setter;
constructor(set: Setter, get: () => AiInfraStore, _api?: unknown) {
@@ -57,6 +94,21 @@ export class AiModelActionImpl {
stateKey: 'aiModelListReplica',
view: recordLens<AiInfraStore, AiProviderModelListItem[]>('aiModelListMap'),
});
+ this.#reasoningConfig = createReplicaSlice(aiModelReasoningConfigResource, {
+ actionPrefix: 'aiModelReasoningConfig',
+ fetcher: async ({ model, provider }) => ({
+ value: (await aiModelService.getAiModelReasoningConfig(model, provider)) ?? undefined,
+ }),
+ get,
+ // Don't clobber an in-flight optimistic value with a stale response
+ prepareHead: (incoming, _current, { model, provider }) =>
+ get().modelReasoningConfigUpdatingKeys.includes(modelReasoningConfigKey(provider, model))
+ ? undefined
+ : incoming,
+ set,
+ stateKey: 'modelReasoningConfigReplica',
+ view: modelReasoningConfigLens,
+ });
}
batchToggleAiModels = async (ids: string[], enabled: boolean): Promise<void> => {
@@ -183,6 +235,40 @@ export class AiModelActionImpl {
await this.#get().refreshAiModelList();
};
+ /**
+ * Seeds the map from a complete server snapshot of saved reasoning configs
+ * (the runtime-state response) through the replica.
+ *
+ * A raw write to `modelReasoningConfigMap` would leave the replica entry β€” and
+ * its bookkeeping β€” absent, so a storage hydration resolving after this
+ * response would treat memory as empty and repaint an older persisted row over
+ * the confirmed snapshot. Routing the seed through `updateMany` writes those
+ * values as confirmed entries: they persist, and a later hydration keeps them.
+ *
+ * Keys with an in-flight save keep their optimistic value (`seedModelReasoningConfigMap`
+ * skips them), and unchanged keys are left alone so a revalidation costs no writes.
+ */
+ seedModelReasoningConfigs = (
+ configs: Record<string, AiModelReasoningConfig>,
+ models: Pick<EnabledAiModel, 'id' | 'providerId'>[],
+ ): void => {
+ const state = this.#get();
+ const next = seedModelReasoningConfigMap(
+ state.modelReasoningConfigMap,
+ configs,
+ models,
+ state.modelReasoningConfigUpdatingKeys,
+ );
+
+ const entries = Object.keys(next)
+ .filter((key) => !isEqual(next[key], state.modelReasoningConfigMap[key]))
+ .map((key) => ({ apply: () => ({ value: next[key] }), key }));
+
+ if (entries.length === 0) return;
+
+ this.#reasoningConfig.updateMany(entries);
+ };
+
/**
* Toggle a model of an arbitrary provider, without requiring the provider settings
* page context (`activeAiProvider`). Used by ModelSelect to re-enable a persisted
@@ -225,12 +311,17 @@ export class AiModelActionImpl {
): Promise<void> => {
const key = modelReasoningConfigKey(provider, id);
const previous = this.#get().modelReasoningConfigMap[key];
+ const saved = { ...previous, ...value };
+ // The identity / workspace the save belongs to. A switch while it is in
+ // flight clears the map; nothing of this save may land in the new scope.
+ const scope = aiModelReasoningConfigResource.scope.get();
+ const isSameScope = () => aiModelReasoningConfigResource.scope.get() === scope;
this.#set(
(state) => ({
modelReasoningConfigMap: {
...state.modelReasoningConfigMap,
- [key]: { ...previous, ...value },
+ [key]: saved,
},
modelReasoningConfigUpdatingKeys: [...state.modelReasoningConfigUpdatingKeys, key],
}),
@@ -241,47 +332,63 @@ export class AiModelActionImpl {
try {
await aiModelService.updateAiModelReasoningConfig(id, provider, value);
} catch (error) {
- this.#set(
- (state) => {
- const modelReasoningConfigMap = { ...state.modelReasoningConfigMap };
- // A leftover `[key]: undefined` would read as "cached empty" and stop
- // ensureModelReasoningConfig from ever fetching the server value
- if (previous === undefined) delete modelReasoningConfigMap[key];
- else modelReasoningConfigMap[key] = previous;
- return { modelReasoningConfigMap };
- },
- false,
- `updateModelReasoningConfig/rollback/${key}`,
- );
+ if (isSameScope())
+ this.#set(
+ (state) => {
+ const modelReasoningConfigMap = { ...state.modelReasoningConfigMap };
+ // A leftover `[key]: undefined` would read as "cached empty" and stop
+ // ensureModelReasoningConfig from ever fetching the server value
+ if (previous === undefined) delete modelReasoningConfigMap[key];
+ else modelReasoningConfigMap[key] = previous;
+ return { modelReasoningConfigMap };
+ },
+ false,
+ `updateModelReasoningConfig/rollback/${key}`,
+ );
toast.error(t('reasoningEffort.updateFailed', { ns: 'chat' }));
throw error;
} finally {
- this.#set(
- (state) => ({
- modelReasoningConfigUpdatingKeys: state.modelReasoningConfigUpdatingKeys.filter(
- (i) => i !== key,
- ),
- }),
- false,
- `updateModelReasoningConfig/settled/${key}`,
- );
+ // After a scope switch the marker is already gone; one with the same key
+ // now belongs to a save of the new scope.
+ if (isSameScope())
+ this.#set(
+ (state) => ({
+ modelReasoningConfigUpdatingKeys: state.modelReasoningConfigUpdatingKeys.filter(
+ (i) => i !== key,
+ ),
+ }),
+ false,
+ `updateModelReasoningConfig/settled/${key}`,
+ );
}
- // Revalidate only AFTER the updating marker is cleared: the server merges
- // this partial write into previously saved fields, and the fetch hook's
- // onSuccess skips writes while the key is marked updating β€” revalidating
- // inside the try block would drop server-preserved sibling fields whenever
- // the optimistic base (`previous`) had not been fetched yet.
- await mutate(aiModelKeys.reasoningConfig(provider, id));
+ if (!isSameScope()) return;
+
+ // The saved value is confirmed now: persist it, so a reload paints it
+ // even when the refresh below never lands.
+ this.#reasoningConfig.update(key, () => ({ value: saved }));
+
+ // Refresh only AFTER the updating marker is cleared: the server merges
+ // this partial write into previously saved fields, and the replica drops
+ // responses while the key is marked updating β€” refreshing inside the try
+ // block would drop server-preserved sibling fields whenever the optimistic
+ // base (`previous`) had not been fetched yet.
+ try {
+ await this.#reasoningConfig.fetch({ model: id, provider }, { fresh: true, scope });
+ } catch {
+ // best-effort: the saved value above stays
+ }
};
/**
* Best-effort imperative warm-up of the model-instance reasoning config for
* non-React callers β€” e.g. the client sub-agent executor, whose override
- * model may never mount a ChatInput fetch hook. No-op when the key is
- * already cached or an optimistic update is in flight; fetch failures are
- * swallowed so the send path falls back to defaults instead of breaking.
+ * model may never mount a ChatInput fetch hook. No-op when the server has
+ * already settled the key (a fetch or the runtime-state seed); a value only
+ * restored from the local replica is confirmed first, since the send path
+ * must not run on a stale copy. Fetch failures are swallowed so the send
+ * path falls back to the local value or defaults instead of breaking.
*/
ensureModelReasoningConfig = async (id: string, provider: string): Promise<void> => {
// Right after a reload the model metadata may still be hydrating β€” settle
@@ -295,57 +402,31 @@ export class AiModelActionImpl {
if (!aiModelSelectors.isModelHasReasoningExtendParams(id, provider)(this.#get())) return;
const key = modelReasoningConfigKey(provider, id);
- if (key in this.#get().modelReasoningConfigMap) return;
+ const state = this.#get();
+ if (state.modelReasoningConfigUpdatingKeys.includes(key)) return;
+ const restoredOnly = state.modelReasoningConfigReplica.entries[key]?.source === 'storage';
+ if (key in state.modelReasoningConfigMap && !restoredOnly) return;
try {
- const data = await aiModelService.getAiModelReasoningConfig(id, provider);
-
- const state = this.#get();
- if (state.modelReasoningConfigUpdatingKeys.includes(key)) return;
- if (key in state.modelReasoningConfigMap) return;
-
- this.#set(
- (s) => ({
- // An empty config keeps the key (value undefined) so repeated calls
- // don't refetch a model that simply has nothing saved yet
- modelReasoningConfigMap: { ...s.modelReasoningConfigMap, [key]: data },
- }),
- false,
- `ensureModelReasoningConfig/${key}`,
- );
+ await this.#reasoningConfig.fetch({ model: id, provider });
} catch {
- // best-effort: resolver falls back to level defaults
+ // best-effort: resolver falls back to the local value or level defaults
}
};
+ /**
+ * Fetch orchestration for one model instance's saved reasoning defaults.
+ * Hydrates the persisted copy first, so the effort picker paints the saved
+ * level on the first frame, then lets the network confirm. Read the value
+ * through `aiModelSelectors.modelReasoningConfig`.
+ */
useFetchAiModelReasoningConfig = (
id: string | undefined,
provider: string | undefined,
- ): SWRResponse<AiModelReasoningConfig | null> => {
- return useClientDataSWR<AiModelReasoningConfig | null>(
- id && provider ? aiModelKeys.reasoningConfig(provider, id) : null,
- async ([, provider, id]) =>
- (await aiModelService.getAiModelReasoningConfig(id as string, provider as string)) ?? null,
- {
- onSuccess: (data) => {
- const key = modelReasoningConfigKey(provider!, id!);
- // Don't clobber an in-flight optimistic value with a stale response
- if (this.#get().modelReasoningConfigUpdatingKeys.includes(key)) return;
- // The store map keeps its `| undefined` shape β€” only SWR needs null.
- const value = data ?? undefined;
- if (isEqual(value, this.#get().modelReasoningConfigMap[key])) return;
-
- this.#set(
- (state) => ({
- modelReasoningConfigMap: { ...state.modelReasoningConfigMap, [key]: value },
- }),
- false,
- `useFetchAiModelReasoningConfig/${key}`,
- );
- },
- },
- );
- };
+ ): ReplicaSyncResult =>
+ this.#reasoningConfig.useSync(id && provider ? { model: id, provider } : null, {
+ dedupingInterval: REASONING_CONFIG_DEDUPING_INTERVAL,
+ });
updateAiModelsConfig = async (
id: string,
diff --git a/src/store/aiInfra/slices/aiModel/initialState.ts b/src/store/aiInfra/slices/aiModel/initialState.ts
index 86cc55cf5bb..f4150623284 100644
--- a/src/store/aiInfra/slices/aiModel/initialState.ts
+++ b/src/store/aiInfra/slices/aiModel/initialState.ts
@@ -7,6 +7,8 @@ import {
import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type { AiModelReasoningConfigEntry } from './projection';
+
export interface AIModelsState {
/**
* Replica view of the models of every visited provider
@@ -23,6 +25,8 @@ export interface AIModelsState {
* `${providerId}/${modelId}` (personal scope, cross-workspace).
*/
modelReasoningConfigMap: Record<string, AiModelReasoningConfig | undefined>;
+ /** Replica bookkeeping of `modelReasoningConfigMap`. */
+ modelReasoningConfigReplica: ReplicaState<AiModelReasoningConfigEntry>;
/**
* `${providerId}/${modelId}` keys with an in-flight reasoning-config save.
*/
@@ -36,6 +40,7 @@ export const initialAIModelState: AIModelsState = {
aiModelLoadingIds: [],
builtinAiModelList: [],
modelReasoningConfigMap: {},
+ modelReasoningConfigReplica: createReplicaState(),
modelReasoningConfigUpdatingKeys: [],
modelSearchKeyword: '',
};
diff --git a/src/store/aiInfra/slices/aiModel/projection.test.ts b/src/store/aiInfra/slices/aiModel/projection.test.ts
new file mode 100644
index 00000000000..68e8fb5715b
--- /dev/null
+++ b/src/store/aiInfra/slices/aiModel/projection.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+
+import { aiModelListResource, aiModelReasoningConfigResource } from './projection';
+
+describe('aiModelReasoningConfigResource scope', () => {
+ it('is partitioned by identity only, so a workspace switch keeps the same rows', () => {
+ const get = vi.spyOn(cacheScope, 'get').mockReturnValue('user-1:workspace-a');
+ const personal = aiModelReasoningConfigResource.scope.get();
+
+ get.mockReturnValue('user-1:workspace-b');
+ expect(aiModelReasoningConfigResource.scope.get()).toBe(personal);
+ expect(personal).toBe('user-1:*');
+
+ get.mockReturnValue('user-2:workspace-a');
+ expect(aiModelReasoningConfigResource.scope.get()).not.toBe(personal);
+
+ vi.restoreAllMocks();
+ });
+
+ it('keeps the model list per workspace', () => {
+ const get = vi.spyOn(cacheScope, 'get').mockReturnValue('user-1:workspace-a');
+ expect(aiModelListResource.scope.get()).toBe('user-1:workspace-a');
+
+ get.mockReturnValue('user-1:workspace-b');
+ expect(aiModelListResource.scope.get()).toBe('user-1:workspace-b');
+
+ vi.restoreAllMocks();
+ });
+});
diff --git a/src/store/aiInfra/slices/aiModel/projection.ts b/src/store/aiInfra/slices/aiModel/projection.ts
index bd8888d6d7b..c7c2c2c7baa 100644
--- a/src/store/aiInfra/slices/aiModel/projection.ts
+++ b/src/store/aiInfra/slices/aiModel/projection.ts
@@ -1,6 +1,8 @@
-import type { AiProviderModelListItem } from 'model-bank';
+import type { AiModelReasoningConfig, AiProviderModelListItem } from 'model-bank';
-import { arrayEntity, defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';
+import { arrayEntity, defineReplica, identityOnlyScope, type ReplicaEntityAdapter } from '@/libs/replica';
+
+import { modelReasoningConfigKey } from './initialState';
/**
* The models of one provider, keyed by provider id (`aiModelListMap[providerId]`).
@@ -22,3 +24,41 @@ export const aiModelListEntity: ReplicaEntityAdapter<
AiProviderModelListItem[],
AiProviderModelListItem
> = arrayEntity<AiProviderModelListItem>((model) => model.id);
+
+export interface AiModelReasoningConfigParams {
+ model: string;
+ provider: string;
+}
+
+/**
+ * One model instance's saved reasoning defaults, wrapped so "nothing saved"
+ * (`{ value: undefined }`) stays a confirmed value instead of an absent entry.
+ */
+export interface AiModelReasoningConfigEntry {
+ value?: AiModelReasoningConfig;
+}
+
+/**
+ * The user's per-model-instance reasoning defaults, one entry per
+ * `${providerId}/${modelId}` (`modelReasoningConfigMap`). Persisted so the
+ * effort picker paints the saved level on the first frame after a reload; the
+ * payload is a handful of enum fields, but a user may touch many models, so the
+ * stored rows are capped.
+ *
+ * Partitioned by identity only: the server keys these rows by userId +
+ * providerId + modelId and shares them across workspaces (see
+ * `AiModelModel.getModelReasoningConfig`). A workspace-partitioned replica would
+ * hydrate another workspace's older copy after a switch and keep using it while
+ * confirmation is offline or fails.
+ */
+export const aiModelReasoningConfigResource = defineReplica<
+ AiModelReasoningConfigParams,
+ AiModelReasoningConfigEntry
+>({
+ key: ({ model, provider }) => modelReasoningConfigKey(provider, model),
+ name: 'aiModelReasoningConfig',
+ persist: { maxEntries: 200 },
+ scope: identityOnlyScope,
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index b71af366bff..81dc0b7818e 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -163,10 +163,11 @@ const modelReasoningConfig = (id: string, provider: string) => (s: AIProviderSto
s.modelReasoningConfigMap?.[modelReasoningConfigKey(provider, id)];
/**
- * Whether `ensureModelReasoningConfig` / the SWR loader has settled the saved
- * config for this model (the key is kept even when nothing is saved). Topic
- * snapshots must not pin "model defaults" while the real value is still in
- * flight, so they skip pinning until this is true.
+ * Whether the replica holds a saved config for this model (the key is kept
+ * even when nothing is saved) β€” confirmed by the server, or restored from the
+ * local copy for display. Topic snapshots must not pin "model defaults" while
+ * the real value is still in flight, so they run `ensureModelReasoningConfig`
+ * (which confirms a restored-only value) and skip pinning until this is true.
*/
const isModelReasoningConfigLoaded = (id: string, provider: string) => (s: AIProviderStoreState) =>
modelReasoningConfigKey(provider, id) in (s.modelReasoningConfigMap ?? {});
diff --git a/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts b/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts
index e4f5061772f..4b154088466 100644
--- a/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts
+++ b/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts
@@ -17,6 +17,7 @@ import {
aiProviderListResource,
aiProviderRuntimeStateQueryKey,
aiProviderRuntimeStateResource,
+ type AiProviderRuntimeStateView,
} from '../projection';
vi.mock('@/services/aiProvider', () => ({
@@ -257,6 +258,38 @@ describe('AiProviderSlice (replica)', () => {
).toEqual(value);
});
+ it('seeds the saved reasoning configs through the aiModel replica', async () => {
+ const value: AiProviderRuntimeStateView = {
+ ...runtimeState(),
+ modelReasoningConfigs: { 'openai/gpt-4o': { reasoningEffort: 'low' } },
+ };
+
+ renderHook(() => useStore.getState().useFetchAiProviderRuntimeState(true));
+ const [call] = await syncCalls('aiProviderRuntimeState');
+ act(() => call.config.onSuccess!(value));
+
+ const state = useStore.getState();
+ expect(state.modelReasoningConfigMap['openai/gpt-4o']).toEqual({ reasoningEffort: 'low' });
+ // Seeded as a *confirmed* replica entry, not a bare map write: only then
+ // does a storage hydration that resolves later leave it alone instead of
+ // repainting an older persisted row over the server's value.
+ expect(state.modelReasoningConfigReplica.entries['openai/gpt-4o']).toBeDefined();
+ });
+
+ it('does not seed reasoning configs from a display snapshot', async () => {
+ const value: AiProviderRuntimeStateView = {
+ ...runtimeState(),
+ isDisplaySnapshot: true,
+ modelReasoningConfigs: { 'openai/gpt-4o': { reasoningEffort: 'low' } },
+ };
+
+ renderHook(() => useStore.getState().useFetchAiProviderRuntimeState(true));
+ const [call] = await syncCalls('aiProviderRuntimeState');
+ act(() => call.config.onSuccess!(value));
+
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-4o']).toBeUndefined();
+ });
+
it('persists only the secret-free display fields of a confirmed value', async () => {
const value = {
...runtimeState(),
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index 6b0ddda8c2c..9b95c9ba7ed 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -40,7 +40,7 @@ import { AiProviderSourceEnum } from '@/types/aiProvider';
import { filterEnabledProvidersByModelType, filterHiddenBuiltinModels } from '@/utils/aiProvider';
import { setNamespace } from '@/utils/storeDebug';
-import { initialAIModelState, seedModelReasoningConfigMap } from '../aiModel/initialState';
+import { initialAIModelState } from '../aiModel/initialState';
import {
AI_PROVIDER_LIST_KEY,
aiProviderDetailResource,
@@ -508,11 +508,13 @@ const aiProviderListLens: ReplicaLens<AiInfraStore, AiProviderListItem[]> = {
* Projects a confirmed runtime-state value onto the flat fields the many
* existing selectors read. `enabled*` stays derived here rather than becoming a
* selector over the entry map, so no reader has to change.
+ *
+ * The saved reasoning configs are the one field not written here: they belong to
+ * the aiModel replica, which seeds them through `seedModelReasoningConfigs` (see
+ * the `runtimeState` effects) so a storage hydration cannot repaint an older row
+ * over this server snapshot.
*/
-const projectRuntimeState = (
- state: AiInfraStore,
- data: AiProviderRuntimeStateView,
-): Partial<AiInfraStore> => ({
+const projectRuntimeState = (data: AiProviderRuntimeStateView): Partial<AiInfraStore> => ({
aiProviderRuntimeConfig: data.runtimeConfig,
builtinAiModelList: data.builtinAiModelList,
enabledAiModels: data.enabledAiModels,
@@ -525,14 +527,6 @@ const projectRuntimeState = (
hiddenBuiltinModels: data.hiddenBuiltinModels,
isInitAiProviderRuntimeState: true,
modelRedirects: data.modelRedirects,
- ...(data.modelReasoningConfigs && {
- modelReasoningConfigMap: seedModelReasoningConfigMap(
- state.modelReasoningConfigMap,
- data.modelReasoningConfigs,
- data.enabledAiModels,
- state.modelReasoningConfigUpdatingKeys,
- ),
- }),
providerBindingAgentTypes: data.providerBindingAgentTypes ?? {},
});
@@ -586,7 +580,7 @@ const aiProviderRuntimeStateLens: ReplicaLens<AiInfraStore, AiProviderRuntimeSta
aiProviderRuntimeStateMap: next,
...(data.isDisplaySnapshot
? projectRuntimeStateDisplay(state, data)
- : projectRuntimeState(state, data)),
+ : projectRuntimeState(data)),
};
},
};
@@ -624,6 +618,17 @@ export class AiProviderActionImpl {
});
this.#runtimeState = createReplicaSlice(aiProviderRuntimeStateResource, {
actionPrefix: n('runtimeState'),
+ // The runtime state carries the complete saved reasoning-config snapshot.
+ // Seeding it through the aiModel replica keeps those values *confirmed*
+ // entries, so a storage hydration that resolves after this response can no
+ // longer repaint an older persisted row over the server's value.
+ effects: {
+ onApplied: (data) => {
+ if (data.isDisplaySnapshot || !data.modelReasoningConfigs) return;
+
+ get().seedModelReasoningConfigs(data.modelReasoningConfigs, data.enabledAiModels);
+ },
+ },
fetcher: (params) => fetchAiProviderRuntimeState(params.isLogin),
get,
set,
diff --git a/src/store/userMemory/utils/replica.ts b/src/store/userMemory/utils/replica.ts
index fd3596277d4..d101382242f 100644
--- a/src/store/userMemory/utils/replica.ts
+++ b/src/store/userMemory/utils/replica.ts
@@ -1,19 +1,13 @@
import {
- cacheScope,
definePagedReplica,
defineReplica,
+ identityOnlyScope,
+ identityScopeOf,
type ReplicaScope,
stableQueryKey,
} from '@/libs/replica';
-/**
- * The identity half of a cache scope (`${userId}:${workspaceId}`), with the
- * workspace replaced by a marker no workspace id can take.
- */
-export const identityScopeOf = (scope: string): string => {
- const separator = scope.indexOf(':');
- return `${separator === -1 ? scope : scope.slice(0, separator)}:*`;
-};
+export { identityScopeOf };
/**
* User memories belong to the user, not to a workspace: the server reads and
@@ -24,12 +18,7 @@ export const identityScopeOf = (scope: string): string => {
* the rows written in every workspace, and a workspace switch keeps showing
* the same user's memories.
*/
-export const userMemoryIdentityScope: ReplicaScope = {
- canHydrate: () => cacheScope.canHydrate?.() ?? true,
- canPersist: () => cacheScope.canPersist(),
- get: () => identityScopeOf(cacheScope.get()),
- use: () => identityScopeOf(cacheScope.use()),
-};
+export const userMemoryIdentityScope: ReplicaScope = identityOnlyScope;
/**
* How many distinct search / sort page sets each memory list keeps persisted