🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(aiModel): keep the runtime snapshot authoritative over stale reasoning reads (#22645)
Arvin Xu3b1d85327508
diff --git a/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.ts b/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.tsindex 425028d9a86..b2475208e82 100644--- a/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.ts+++ b/src/store/aiInfra/slices/aiModel/action.reasoningConfig.test.ts@@ -649,13 +649,15 @@ describe('AiModelAction reasoning config', () => {});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,- );+ 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();@@ -671,5 +673,116 @@ describe('AiModelAction reasoning config', () => {state.modelReasoningConfigReplica.entries['anthropic/claude-sonnet-4-5'],).toBeDefined();});++ const SEED_MODELS = [{ id: 'gpt-5.2', providerId: 'openai' }] as any;+ const settle = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));+ const readRow = () =>+ aiModelReasoningConfigResource.storage!.get({+ queryKey: REASONING_STORAGE_KEY,+ scope: rowScope(),+ });+ const deferredRead = () => {+ let resolve!: (value: any) => void;+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockReturnValue(+ new Promise((r) => {+ resolve = r;+ }),+ );+ return (value: any) => resolve(value);+ };++ it('keeps a stored row from repainting a key the snapshot confirmed as nothing saved', async () => {+ await aiModelReasoningConfigResource.storage!.set(+ { queryKey: REASONING_STORAGE_KEY, scope: rowScope() },+ { value: { reasoningEffort: 'high' } } as any,+ );+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockImplementation(pending);++ act(() => {+ useStore.getState().seedModelReasoningConfigs({}, SEED_MODELS);+ });+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {+ wrapper,+ });+ await settle();++ const state = useStore.getState();+ expect('openai/gpt-5.2' in state.modelReasoningConfigMap).toBe(true);+ expect(state.modelReasoningConfigMap['openai/gpt-5.2']).toBeUndefined();+ });++ it('does not spend persisted rows on models with nothing saved', async () => {+ act(() => {+ useStore.getState().seedModelReasoningConfigs({}, SEED_MODELS);+ });+ await settle();++ expect(+ useStore.getState().modelReasoningConfigReplica.entries['openai/gpt-5.2'],+ ).toBeDefined();+ expect(await readRow()).toBeUndefined();+ });++ it('lets the snapshot win over a per-model read that started before it', async () => {+ const resolveRead = deferredRead();+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {+ wrapper,+ });+ await waitFor(() =>+ expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalledTimes(1),+ );++ act(() => {+ useStore+ .getState()+ .seedModelReasoningConfigs(+ { 'openai/gpt-5.2': { reasoningEffort: 'high' } },+ SEED_MODELS,+ );+ });+ await act(async () => {+ resolveRead({ reasoningEffort: 'low' });+ });+ await settle();++ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({+ reasoningEffort: 'high',+ });+ expect(await readRow()).toMatchObject({ data: { value: { reasoningEffort: 'high' } } });+ });++ it('lets a post-save refresh win over a snapshot that may predate the save', async () => {+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockResolvedValue(undefined as any);+ const resolveRead = deferredRead();++ let saving!: Promise<void>;+ act(() => {+ saving = useStore+ .getState()+ .updateModelReasoningConfig('gpt-5.2', 'openai', { reasoningEffort: 'high' });+ });+ await waitFor(() =>+ expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalledTimes(1),+ );++ act(() => {+ useStore+ .getState()+ .seedModelReasoningConfigs({ 'openai/gpt-5.2': { reasoningEffort: 'low' } }, SEED_MODELS);+ });+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({+ reasoningEffort: 'high',+ });++ await act(async () => {+ resolveRead({ reasoningEffort: 'high', thinkingBudget: 1024 });+ await saving;+ });++ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({+ reasoningEffort: 'high',+ thinkingBudget: 1024,+ });+ });});});diff --git a/src/store/aiInfra/slices/aiModel/action.ts b/src/store/aiInfra/slices/aiModel/action.tsindex 35b19f50ca9..0e5c9c0cd4a 100644--- a/src/store/aiInfra/slices/aiModel/action.ts+++ b/src/store/aiInfra/slices/aiModel/action.ts@@ -72,6 +72,12 @@ export interface AiProviderModelsSyncResult extends ReplicaSyncResult {}type Setter = StoreSetter<AiInfraStore>;++interface ReasoningConfigSeed {+ apply: () => AiModelReasoningConfigEntry;+ key: string;+}+export const createAiModelSlice = (set: Setter, get: () => AiInfraStore, _api?: unknown) =>new AiModelActionImpl(set, get, _api);@@ -79,6 +85,10 @@ export class AiModelActionImpl {readonly #get: () => AiInfraStore;readonly #list;readonly #reasoningConfig;+ /** Keys whose post-save refresh is in flight; older snapshots must not touch them. */+ readonly #refreshingSavedKeys: string[] = [];+ /** Bumped per key by a snapshot seed, so a read started earlier can tell it lost. */+ readonly #seedGenerations = new Map<string, number>();readonly #set: Setter;constructor(set: Setter, get: () => AiInfraStore, _api?: unknown) {@@ -96,9 +106,16 @@ export class AiModelActionImpl {});this.#reasoningConfig = createReplicaSlice(aiModelReasoningConfigResource, {actionPrefix: 'aiModelReasoningConfig',- fetcher: async ({ model, provider }) => ({- value: (await aiModelService.getAiModelReasoningConfig(model, provider)) ?? undefined,- }),+ fetcher: async ({ model, provider }) => {+ const key = modelReasoningConfigKey(provider, model);+ const generation = this.#seedGenerations.get(key);+ const value =+ (await aiModelService.getAiModelReasoningConfig(model, provider)) ?? undefined;+ // A snapshot seeded while this read was in flight is the newer answer.+ return this.#seedGenerations.get(key) === generation+ ? { value }+ : { value: this.#get().modelReasoningConfigMap[key] };+ },get,// Don't clobber an in-flight optimistic value with a stale responseprepareHead: (incoming, _current, { model, provider }) =>@@ -244,29 +261,46 @@ export class AiModelActionImpl {* 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.+ * A key confirmed as nothing saved still gets an entry so hydration cannot+ * repaint it, but only in memory unless it changed a value: a full model list+ * of empty rows would evict real ones under the resource's `maxEntries`.*- * 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.+ * Per-model reads already in flight lose to the snapshot (see `#seedGenerations`).+ * Keys with an in-flight save or post-save refresh are skipped entirely, since+ * the snapshot may predate that save. Settled, 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;+ const current = state.modelReasoningConfigMap;+ const replicaEntries = state.modelReasoningConfigReplica.entries;+ const skippedKeys = [...state.modelReasoningConfigUpdatingKeys, ...this.#refreshingSavedKeys];+ const next = seedModelReasoningConfigMap(current, configs, models, skippedKeys);++ const persisted: ReasoningConfigSeed[] = [];+ const memoryOnly: ReasoningConfigSeed[] = [];+ const coveredKeys = new Set([+ ...models.map((model) => modelReasoningConfigKey(model.providerId, model.id)),+ ...Object.keys(configs),+ ]);++ for (const key of coveredKeys) {+ if (skippedKeys.includes(key)) continue;+ this.#seedGenerations.set(key, (this.#seedGenerations.get(key) ?? 0) + 1);++ const changed = !isEqual(next[key], current[key]);+ const source = replicaEntries[key]?.source;+ if (!changed && source && source !== 'storage') continue;++ const seed = { apply: () => ({ value: next[key] }), key };+ (changed || next[key] !== undefined ? persisted : memoryOnly).push(seed);+ }- this.#reasoningConfig.updateMany(entries);+ if (persisted.length > 0) this.#reasoningConfig.updateMany(persisted);+ if (memoryOnly.length > 0) this.#reasoningConfig.updateMany(memoryOnly, { persist: false });};/**@@ -374,10 +408,13 @@ export class AiModelActionImpl {// 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.+ this.#refreshingSavedKeys.push(key);try {await this.#reasoningConfig.fetch({ model: id, provider }, { fresh: true, scope });} catch {// best-effort: the saved value above stays+ } finally {+ this.#refreshingSavedKeys.splice(this.#refreshingSavedKeys.indexOf(key), 1);}};