🤯 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
♻️ refactor(image): move generation topics and batches onto replica (#20639)
Arvin Xu8cf312b90995
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex ff004d137ce..78f31d6cd9b 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -417,17 +417,15 @@ export const aiModelKeys = {};// ---- 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+// generation-status poll is still an SWR key.export const imageKeys = {- generationBatches: def('image:generationBatches', (topicId: string) => [- 'image:generationBatches',- topicId,- ]),generationStatus: def('image:generationStatus', (generationId: string, asyncTaskId?: string) => ['image:generationStatus',generationId,asyncTaskId,]),- generationTopics: def('image:generationTopics', () => ['image:generationTopics']),};// ---- video generation ---------------------------------------------------diff --git a/src/store/image/slices/generationBatch/action.test.ts b/src/store/image/slices/generationBatch/action.test.tsindex b59118c2640..45b3227818c 100644--- a/src/store/image/slices/generationBatch/action.test.ts+++ b/src/store/image/slices/generationBatch/action.test.ts@@ -1,7 +1,7 @@-import { act, renderHook, waitFor } from '@testing-library/react';-import React from 'react';+import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createReplicaState } from '@/libs/replica';import type * as SwrModule from '@/libs/swr';import { mutate } from '@/libs/swr';import { generationService } from '@/services/generation';@@ -11,7 +11,13 @@ import { generationBatchSelectors } from '@/store/image/slices/generationBatch/simport { AsyncTaskStatus } from '@/types/asyncTask';import { type GenerationBatch } from '@/types/generation';-// Mock services and dependencies+// The replica driver revalidates through the scoped `mutate`; mock it so the+// imperative refresh assertions below can observe the call.+vi.mock('@/libs/swr', async (importOriginal) => {+ const actual = await importOriginal<typeof SwrModule>();+ return { ...actual, mutate: vi.fn() };+});+vi.mock('@/services/generation', () => ({generationService: {deleteGeneration: vi.fn(),@@ -26,19 +32,37 @@ vi.mock('@/services/generationBatch', () => ({},}));-vi.mock('@/libs/swr', async (importOriginal) => {- const actual = await importOriginal<typeof SwrModule>();- return {- ...actual,- mutate: vi.fn(),- };-});+const batch = (id: string, generationIds: string[]): GenerationBatch =>+ ({+ id,+ provider: 'openai',+ model: 'dall-e-3',+ prompt: 'Test prompt',+ createdAt: new Date(),+ generations: generationIds.map((generationId) => ({+ id: generationId,+ seed: 12345,+ createdAt: new Date(),+ asyncTaskId: null,+ task: { id: `task_${generationId}`, status: AsyncTaskStatus.Success },+ })),+ }) as unknown as GenerationBatch;++/** Seed one loaded topic into the batch replica view. */+const seedBatch = (topicId: string, batches: GenerationBatch[]) => {+ useImageStore.setState({+ activeGenerationTopicId: topicId,+ generationBatchesMap: { [topicId]: batches },+ generationBatchesReplica: createReplicaState(),+ });+};beforeEach(() => {vi.clearAllMocks();useImageStore.setState({- generationBatchesMap: {},activeGenerationTopicId: null,+ generationBatchesMap: {},+ generationBatchesReplica: createReplicaState(),});});@@ -48,51 +72,39 @@ afterEach(() => {describe('GenerationBatchAction', () => {describe('setTopicBatchLoaded', () => {- it('should set topic batch as loaded with empty array and mark topic as loaded', async () => {+ it('seeds an empty list and marks the topic as loaded', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';- // Set the topic as active firstact(() => {useImageStore.setState({ activeGenerationTopicId: topicId });});- // Initially topic should not be loadedexpect(generationBatchSelectors.isCurrentGenerationTopicLoaded(result.current)).toBe(false);- // Set topic batch as loadedact(() => {result.current.setTopicBatchLoaded(topicId);});- // Verify both the direct state and the selectorexpect(result.current.generationBatchesMap[topicId]).toEqual([]);expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(result.current)).toBe(true);});- it('should not update state if map already has the same value', async () => {+ it('keeps the existing list reference when the topic is already loaded', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';act(() => {- useImageStore.setState({- generationBatchesMap: { [topicId]: [] },- activeGenerationTopicId: topicId,- });+ seedBatch(topicId, []);});const stateBefore = result.current.generationBatchesMap;- // Should already be loaded- expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(result.current)).toBe(true);-act(() => {result.current.setTopicBatchLoaded(topicId);});- // State reference should remain the same due to isEqual checkexpect(result.current.generationBatchesMap).toBe(stateBefore);- expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(result.current)).toBe(true);});});@@ -100,93 +112,31 @@ describe('GenerationBatchAction', () => {it('should remove generation and clean up empty batch', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';- const batchId = 'gb_batch_1';- const generationId = 'gen_1';-- const batches: GenerationBatch[] = [- {- id: batchId,- provider: 'openai',- model: 'dall-e-3',- prompt: 'Test prompt',- createdAt: new Date(),- generations: [- {- id: generationId,- seed: 12345,- createdAt: new Date(),- asyncTaskId: null,- task: {- id: 'task_1',- status: AsyncTaskStatus.Success,- },- },- ],- },- ];act(() => {- useImageStore.setState({- activeGenerationTopicId: topicId,- generationBatchesMap: { [topicId]: batches },- });+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1'])]);});- const deleteGenerationSpy = vi.spyOn(result.current, 'internal_deleteGeneration');- const deleteBatchSpy = vi.spyOn(result.current, 'internal_deleteGenerationBatch');+ const deleteBatchSpy = vi+ .spyOn(result.current, 'internal_deleteGenerationBatch')+ .mockResolvedValue(undefined);const refreshSpy = vi.spyOn(result.current, 'refreshGenerationBatches');await act(async () => {- await result.current.removeGeneration(generationId);+ await result.current.removeGeneration('gen_1');});- expect(deleteGenerationSpy).toHaveBeenCalledWith(generationId);- expect(deleteBatchSpy).toHaveBeenCalledWith(batchId, topicId);+ expect(generationService.deleteGeneration).toHaveBeenCalledWith('gen_1');+ expect(deleteBatchSpy).toHaveBeenCalledWith('gb_batch_1', topicId);expect(refreshSpy).toHaveBeenCalled();});it('should only remove generation if batch is not empty', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';- const batchId = 'gb_batch_1';-- const batches: GenerationBatch[] = [- {- id: batchId,- provider: 'openai',- model: 'dall-e-3',- prompt: 'Test prompt',- createdAt: new Date(),- generations: [- {- id: 'gen_1',- seed: 12345,- createdAt: new Date(),- asyncTaskId: null,- task: {- id: 'task_1',- status: AsyncTaskStatus.Success,- },- },- {- id: 'gen_2',- seed: 54321,- createdAt: new Date(),- asyncTaskId: null,- task: {- id: 'task_2',- status: AsyncTaskStatus.Success,- },- },- ],- },- ];act(() => {- useImageStore.setState({- activeGenerationTopicId: topicId,- generationBatchesMap: { [topicId]: batches },- });+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1', 'gen_2'])]);});const deleteBatchSpy = vi.spyOn(result.current, 'internal_deleteGenerationBatch');@@ -201,78 +151,37 @@ describe('GenerationBatchAction', () => {it('should do nothing if no active topic', async () => {const { result } = renderHook(() => useImageStore());- const deleteGenerationSpy = vi.spyOn(result.current, 'internal_deleteGeneration');-await act(async () => {await result.current.removeGeneration('gen_1');});- expect(deleteGenerationSpy).toHaveBeenCalledWith('gen_1');expect(generationService.deleteGeneration).not.toHaveBeenCalled();});});describe('internal_deleteGeneration', () => {- it('should delete generation with optimistic update', async () => {+ it('should delete the generation optimistically and confirm with the server', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';- const batchId = 'gb_batch_1';- const generationId = 'gen_1';-- const batches: GenerationBatch[] = [- {- id: batchId,- provider: 'openai',- model: 'dall-e-3',- prompt: 'Test prompt',- createdAt: new Date(),- generations: [- {- id: generationId,- seed: 12345,- createdAt: new Date(),- asyncTaskId: null,- task: {- id: 'task_1',- status: AsyncTaskStatus.Success,- },- },- ],- },- ];act(() => {- useImageStore.setState({- activeGenerationTopicId: topicId,- generationBatchesMap: { [topicId]: batches },- });+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1', 'gen_2'])]);});- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationBatch');- const refreshSpy = vi.spyOn(result.current, 'refreshGenerationBatches');-await act(async () => {- await result.current.internal_deleteGeneration(generationId);+ await result.current.internal_deleteGeneration('gen_1');});- expect(dispatchSpy).toHaveBeenCalledWith(- topicId,- { type: 'deleteGenerationInBatch', batchId, generationId },- 'internal_deleteGeneration',- );- expect(generationService.deleteGeneration).toHaveBeenCalledWith(generationId);- expect(refreshSpy).toHaveBeenCalled();+ expect(generationService.deleteGeneration).toHaveBeenCalledWith('gen_1');+ const generations = result.current.generationBatchesMap[topicId][0].generations;+ expect(generations.map((generation) => generation.id)).toEqual(['gen_2']);});it('should do nothing if generation not found', async () => {const { result } = renderHook(() => useImageStore());- const topicId = 'gt_topic_1';act(() => {- useImageStore.setState({- activeGenerationTopicId: topicId,- generationBatchesMap: { [topicId]: [] },- });+ seedBatch('gt_topic_1', []);});await act(async () => {@@ -286,128 +195,87 @@ describe('GenerationBatchAction', () => {describe('removeGenerationBatch', () => {it('should call internal_deleteGenerationBatch', async () => {const { result } = renderHook(() => useImageStore());- const batchId = 'gb_batch_1';- const topicId = 'gt_topic_1';- const deleteBatchSpy = vi.spyOn(result.current, 'internal_deleteGenerationBatch');+ const deleteBatchSpy = vi+ .spyOn(result.current, 'internal_deleteGenerationBatch')+ .mockResolvedValue(undefined);await act(async () => {- await result.current.removeGenerationBatch(batchId, topicId);+ await result.current.removeGenerationBatch('gb_batch_1', 'gt_topic_1');});- expect(deleteBatchSpy).toHaveBeenCalledWith(batchId, topicId);+ expect(deleteBatchSpy).toHaveBeenCalledWith('gb_batch_1', 'gt_topic_1');});});describe('internal_deleteGenerationBatch', () => {- it('should delete batch with optimistic update', async () => {+ it('should delete the batch optimistically and confirm with the server', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';- const batchId = 'gb_batch_1';- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationBatch');- const refreshSpy = vi.spyOn(result.current, 'refreshGenerationBatches');+ act(() => {+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1'])]);+ });await act(async () => {- await result.current.internal_deleteGenerationBatch(batchId, topicId);+ await result.current.internal_deleteGenerationBatch('gb_batch_1', topicId);});- expect(dispatchSpy).toHaveBeenCalledWith(- topicId,- { type: 'deleteBatch', id: batchId },- 'internal_deleteGenerationBatch',- );- expect(generationBatchService.deleteGenerationBatch).toHaveBeenCalledWith(batchId);- expect(refreshSpy).toHaveBeenCalled();+ expect(generationBatchService.deleteGenerationBatch).toHaveBeenCalledWith('gb_batch_1');+ expect(result.current.generationBatchesMap[topicId]).toEqual([]);});});describe('internal_dispatchGenerationBatch', () => {- it('should update batch map when state changes', async () => {+ it('should update a loaded topic when state changes', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';act(() => {- useImageStore.setState({ generationBatchesMap: { [topicId]: [] } });+ seedBatch(topicId, []);});act(() => {- result.current.internal_dispatchGenerationBatch(- topicId,- {- type: 'addBatch',- value: {- id: 'gb_batch_1',- provider: 'openai',- model: 'dall-e-3',- prompt: 'Test prompt',- createdAt: new Date(),- generations: [],- },- },- 'test_action',- );+ result.current.internal_dispatchGenerationBatch(topicId, {+ type: 'addBatch',+ value: batch('gb_batch_1', []),+ });});expect(result.current.generationBatchesMap[topicId]).toHaveLength(1);expect(result.current.generationBatchesMap[topicId][0].id).toBe('gb_batch_1');});- it('should not update when map is equal', async () => {+ it('should leave an unloaded topic untouched', async () => {const { result } = renderHook(() => useImageStore());- const topicId = 'gt_topic_1';- const existingBatches: GenerationBatch[] = [- {- id: 'gb_batch_1',- provider: 'openai',- model: 'dall-e-3',- prompt: 'Test prompt',- createdAt: new Date('2024-01-01'),- generations: [],- },- ];act(() => {- useImageStore.setState({ generationBatchesMap: { [topicId]: existingBatches } });- });-- const stateBefore = result.current.generationBatchesMap;-- // Try to update with same data (reducer will return same array reference)- act(() => {- result.current.internal_dispatchGenerationBatch(- topicId,- {- type: 'updateBatch',- id: 'gb_batch_1',- value: { prompt: 'Test prompt' }, // Same prompt- },- 'test_action',- );+ result.current.internal_dispatchGenerationBatch('gt_not_loaded', {+ type: 'addBatch',+ value: batch('gb_batch_1', []),+ });});- // State reference should remain the same due to isEqual check- expect(result.current.generationBatchesMap).toBe(stateBefore);+ expect(result.current.generationBatchesMap['gt_not_loaded']).toBeUndefined();});});describe('refreshGenerationBatches', () => {- it('should call mutate when there is active topic', async () => {+ it('should revalidate the active topic entry', async () => {const { result } = renderHook(() => useImageStore());- const topicId = 'gt_topic_1';act(() => {- useImageStore.setState({ activeGenerationTopicId: topicId });+ useImageStore.setState({ activeGenerationTopicId: 'gt_topic_1' });});await act(async () => {await result.current.refreshGenerationBatches();});- expect(mutate).toHaveBeenCalledWith(['image:generationBatches', topicId]);+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));});- it('should not call mutate when no active topic', async () => {+ it('should not revalidate when no active topic', async () => {const { result } = renderHook(() => useImageStore());await act(async () => {@@ -419,48 +287,9 @@ describe('GenerationBatchAction', () => {});describe('useFetchGenerationBatches', () => {- it('should fetch batches for a topic', async () => {- const topicId = 'gt_topic_1';- const batches: GenerationBatch[] = [- {- id: 'gb_batch_1',- provider: 'openai',- model: 'dall-e-3',- prompt: 'Test prompt',- createdAt: new Date(),- generations: [],- },- ];-- vi.mocked(generationBatchService.getGenerationBatches).mockResolvedValue(batches);-- const { result } = renderHook(() => {- const store = useImageStore();-- // Simulate the onSuccess callback behavior directly- React.useEffect(() => {- useImageStore.setState({- generationBatchesMap: { [topicId]: batches },- });- }, []);-- return { data: batches };- });-- await waitFor(() => {- expect(useImageStore.getState().generationBatchesMap[topicId]).toEqual(batches);- });- });-it('should not fetch when no topicId', async () => {- const { result } = renderHook(() => {- const store = useImageStore();- // Test the actual hook with null parameter- const swrResult = store.useFetchGenerationBatches(null);- return swrResult;- });+ const { result } = renderHook(() => useImageStore().useFetchGenerationBatches(null));- // When key is null, SWR returns an object with undefined dataexpect(result.current.data).toBeUndefined();expect(generationBatchService.getGenerationBatches).not.toHaveBeenCalled();});@@ -468,27 +297,19 @@ describe('GenerationBatchAction', () => {describe('useCheckGenerationStatus', () => {it('should not check status for temporary generations', async () => {- const { result } = renderHook(() => {- const store = useImageStore();- // Test the actual hook with temporary generation ID- const swrResult = store.useCheckGenerationStatus('temp-gen-1', 'task_1', 'gt_topic_1');- return swrResult;- });+ const { result } = renderHook(() =>+ useImageStore().useCheckGenerationStatus('temp-gen-1', 'task_1', 'gt_topic_1'),+ );- // When conditions aren't met, SWR returns an object with undefined dataexpect(result.current.data).toBeUndefined();expect(generationService.getGenerationStatus).not.toHaveBeenCalled();});it('should not check status when disabled', async () => {- const { result } = renderHook(() => {- const store = useImageStore();- // Test the actual hook with enable=false- const swrResult = store.useCheckGenerationStatus('gen_1', 'task_1', 'gt_topic_1', false);- return swrResult;- });+ const { result } = renderHook(() =>+ useImageStore().useCheckGenerationStatus('gen_1', 'task_1', 'gt_topic_1', false),+ );- // When disabled, SWR returns an object with undefined dataexpect(result.current.data).toBeUndefined();expect(generationService.getGenerationStatus).not.toHaveBeenCalled();});diff --git a/src/store/image/slices/generationBatch/action.ts b/src/store/image/slices/generationBatch/action.tsindex ce8b52ed99c..b24c4d5d6a3 100644--- a/src/store/image/slices/generationBatch/action.ts+++ b/src/store/image/slices/generationBatch/action.ts@@ -2,7 +2,8 @@ import { isEqual } from 'es-toolkit/compat';import { useRef } from 'react';import { type SWRResponse } from 'swr';-import { mutate, useClientDataSWR } from '@/libs/swr';+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';+import { useClientDataSWR } from '@/libs/swr';import { imageKeys } from '@/libs/swr/keys';import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';import { generationService } from '@/services/generation';@@ -14,47 +15,58 @@ import { setNamespace } from '@/utils/storeDebug';import { type ImageStore } from '../../store';import { generationTopicSelectors } from '../generationTopic/selectors';+import { generationBatchesResource } from './projection';import { type GenerationBatchDispatch } from './reducer';import { generationBatchReducer } from './reducer';const n = setNamespace('generationBatch');-// ====== SWR key ====== //--// ====== action interface ====== //--// ====== action implementation ====== //+/**+ * Result of the per-topic batch sync. `data` mirrors the SWR-era shape the+ * shared generation workspace reads (`error` / `mutate`); read the batches+ * through `generationBatchSelectors` and treat `mutate` as an alias of+ * `revalidate`.+ */+export interface GenerationBatchesSyncResult extends ReplicaSyncResult {+ data?: GenerationBatch[];+ /** A request is in flight and this topic has never loaded. */+ isLoading: boolean;+ /** Alias of `revalidate`. */+ mutate: () => Promise<unknown>;+}type Setter = StoreSetter<ImageStore>;export const createGenerationBatchSlice = (set: Setter, get: () => ImageStore, _api?: unknown) =>new GenerationBatchActionImpl(set, get, _api);export class GenerationBatchActionImpl {+ readonly #batches;readonly #get: () => ImageStore;- readonly #set: Setter;constructor(set: Setter, get: () => ImageStore, _api?: unknown) {void _api;- this.#set = set;this.#get = get;+ this.#batches = createReplicaSlice(generationBatchesResource, {+ actionPrefix: n('generationBatches'),+ fetcher: ({ topicId }) => generationBatchService.getGenerationBatches(topicId, 'image'),+ get,+ // An unchanged topic list must not re-render the feed.+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'generationBatchesReplica',+ view: recordLens<ImageStore, GenerationBatch[]>('generationBatchesMap'),+ });}+ /**+ * Seed an empty list for a just-created topic so the workspace paints the+ * empty state instead of a skeleton while the first batch request is in+ * flight. Memory-only: the server confirmation persists the real value.+ */setTopicBatchLoaded = (topicId: string): void => {- const nextMap = {- ...this.#get().generationBatchesMap,- [topicId]: [],- };-- // no need to update map if the map is the same- if (isEqual(nextMap, this.#get().generationBatchesMap)) return;-- this.#set(- {- generationBatchesMap: nextMap,- },- false,- n('setTopicBatchLoaded'),- );+ this.#batches.update(topicId, (batches) => (Array.isArray(batches) ? batches : []), {+ persist: false,+ });};removeGeneration = async (generationId: string): Promise<void> => {@@ -80,32 +92,34 @@ export class GenerationBatchActionImpl {}};+ /**+ * Remove a generation optimistically (the whole empty batch is cleaned up by+ * `removeGeneration`), roll back if the server rejects, and revalidate so the+ * confirmed list wins.+ */internal_deleteGeneration = async (generationId: string): Promise<void> => {- const { activeGenerationTopicId, refreshGenerationBatches, internal_dispatchGenerationBatch } =- this.#get();-+ const activeGenerationTopicId = this.#get().activeGenerationTopicId;if (!activeGenerationTopicId) return;// Find the batch containing this generation- const currentBatches = this.#get().generationBatchesMap[activeGenerationTopicId] || [];+ const currentBatches = this.#get().generationBatchesMap[activeGenerationTopicId] ?? [];const targetBatch = currentBatches.find((batch) =>batch.generations.some((gen) => gen.id === generationId),);if (!targetBatch) return;- // 1. Immediately update frontend state (optimistic update)- internal_dispatchGenerationBatch(+ await this.#batches.optimistic(activeGenerationTopicId,- { type: 'deleteGenerationInBatch', batchId: targetBatch.id, generationId },- 'internal_deleteGeneration',+ (batches) =>+ generationBatchReducer(batches, {+ batchId: targetBatch.id,+ generationId,+ type: 'deleteGenerationInBatch',+ }),+ () => generationService.deleteGeneration(generationId),+ { revalidate: true },);-- // 2. Call backend service to delete generation- await generationService.deleteGeneration(generationId);-- // 3. Refresh data to ensure consistency- await refreshGenerationBatches();};removeGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {@@ -114,80 +128,51 @@ export class GenerationBatchActionImpl {};internal_deleteGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {- const { internal_dispatchGenerationBatch, refreshGenerationBatches } = this.#get();-- // 1. Immediately update frontend state (optimistic update)- internal_dispatchGenerationBatch(+ await this.#batches.optimistic(topicId,- { type: 'deleteBatch', id: batchId },- 'internal_deleteGenerationBatch',+ (batches) => generationBatchReducer(batches, { id: batchId, type: 'deleteBatch' }),+ () => generationBatchService.deleteGenerationBatch(batchId),+ { revalidate: true },);-- // 2. Call backend service- await generationBatchService.deleteGenerationBatch(batchId);-- // 3. Refresh data to ensure consistency- await refreshGenerationBatches();};- internal_dispatchGenerationBatch = (- topicId: string,- payload: GenerationBatchDispatch,- action?: string,- ): void => {- const currentBatches = this.#get().generationBatchesMap[topicId] || [];- const nextBatches = generationBatchReducer(currentBatches, payload);-- const nextMap = {- ...this.#get().generationBatchesMap,- [topicId]: nextBatches,- };-- // no need to update map if the map is the same- if (isEqual(nextMap, this.#get().generationBatchesMap)) return;-- this.#set(- {- generationBatchesMap: nextMap,- },- false,- action ?? n(`dispatchGenerationBatch/${payload.type}`),+ /**+ * Optimistic write into the batch replica of one topic. Memory-only — live+ * status updates are confirmed by the follow-up `refreshGenerationBatches`.+ * A topic that has not loaded yet is left untouched.+ */+ internal_dispatchGenerationBatch = (topicId: string, payload: GenerationBatchDispatch): void => {+ this.#batches.update(+ topicId,+ (batches) => (batches ? generationBatchReducer(batches, payload) : batches),+ { persist: false },);};refreshGenerationBatches = async (): Promise<void> => {const { activeGenerationTopicId } = this.#get();if (activeGenerationTopicId) {- await mutate(imageKeys.generationBatches(activeGenerationTopicId));+ await this.#batches.revalidate(activeGenerationTopicId);}};- useFetchGenerationBatches = (topicId?: string | null): SWRResponse<GenerationBatch[]> => {- return useClientDataSWR<GenerationBatch[]>(- topicId ? imageKeys.generationBatches(topicId) : null,- async ([, topicId]: [string, string]) => {- return generationBatchService.getGenerationBatches(topicId, 'image');- },- {- onSuccess: (data) => {- const nextMap = {- ...this.#get().generationBatchesMap,- [topicId!]: data,- };-- // no need to update map if the map is the same- if (isEqual(nextMap, this.#get().generationBatchesMap)) return;-- this.#set(- {- generationBatchesMap: nextMap,- },- false,- n('useFetchGenerationBatches(success)', { topicId }),- );- },- },- );+ /**+ * Fetch orchestration for the active topic's batches. The batches are read+ * through `generationBatchSelectors`, not from this return value.+ */+ useFetchGenerationBatches = (topicId?: string | null): GenerationBatchesSyncResult => {+ const sync = this.#batches.useSync(topicId ? { topicId } : undefined, { enabled: !!topicId });+ const data = topicId ? this.#get().generationBatchesMap[topicId] : undefined;++ return {+ data,+ error: sync.error,+ isHydrated: sync.isHydrated,+ isLoading: sync.isValidating && data === undefined,+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ revalidate: sync.revalidate,+ };};useCheckGenerationStatus = (@@ -263,18 +248,12 @@ export class GenerationBatchActionImpl {if (data.generation) {// Update generation data- this.#get().internal_dispatchGenerationBatch(- topicId,- {- type: 'updateGenerationInBatch',- batchId: targetBatch.id,- generationId,- value: data.generation,- },- n(- `useCheckGenerationStatus/${data.status === AsyncTaskStatus.Success ? 'success' : 'error'}`,- ),- );+ this.#get().internal_dispatchGenerationBatch(topicId, {+ batchId: targetBatch.id,+ generationId,+ type: 'updateGenerationInBatch',+ value: data.generation,+ });// The server fills an empty topic cover before reporting success; refresh to show itif (data.status === AsyncTaskStatus.Success && data.generation.asset?.thumbnailUrl) {diff --git a/src/store/image/slices/generationBatch/initialState.ts b/src/store/image/slices/generationBatch/initialState.tsindex 1a50e516dba..3bdaf954fdc 100644--- a/src/store/image/slices/generationBatch/initialState.ts+++ b/src/store/image/slices/generationBatch/initialState.ts@@ -1,13 +1,18 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { type GenerationBatch } from '@/types/generation';export interface GenerationBatchState {/**- * Generation batches mapped by topic ID- * Key: generationTopicId, Value: array of GenerationBatch+ * Generation batches per topic id. View of the `generationBatches` replica,+ * read through `generationBatchSelectors`; a topic key is absent until its+ * batches have been hydrated or confirmed.*/generationBatchesMap: Record<string, GenerationBatch[]>;+ /** Replica bookkeeping of `generationBatchesMap`. */+ generationBatchesReplica: ReplicaState<GenerationBatch[]>;}export const initialGenerationBatchState: GenerationBatchState = {generationBatchesMap: {},+ generationBatchesReplica: createReplicaState(),};diff --git a/src/store/image/slices/generationBatch/projection.ts b/src/store/image/slices/generationBatch/projection.tsnew file mode 100644index 00000000000..c9f84a8ad47--- /dev/null+++ b/src/store/image/slices/generationBatch/projection.ts@@ -0,0 +1,19 @@+import { defineReplica } from '@/libs/replica';+import type { GenerationBatch } from '@/types/generation';++export interface GenerationBatchesParams {+ topicId: string;+}++/**+ * Generation batches are owned by one topic and fetched per topic, so the+ * replica keeps one entry per topic id (`generationBatchesMap[topicId]`) and+ * two topics never share — or reset — one list. The identity scope partitions+ * the entries the same way it partitions the topic list.+ */+export const generationBatchesResource = defineReplica<GenerationBatchesParams, GenerationBatch[]>({+ key: ({ topicId }) => topicId,+ name: 'imageGenerationBatches',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/image/slices/generationBatch/replica.test.ts b/src/store/image/slices/generationBatch/replica.test.tsnew file mode 100644index 00000000000..eb63105b67b--- /dev/null+++ b/src/store/image/slices/generationBatch/replica.test.ts@@ -0,0 +1,167 @@+/**+ * @vitest-environment happy-dom+ *+ * Generation batches are a `@lobechat/replica` resource with one entry per+ * topic (`generationBatchesMap[topicId]`): the persisted projection paints the+ * feed before the network answers, an unchanged response keeps the array+ * reference, and a cache-scope switch drops the previous identity's batches+ * before paint.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { generationBatchService } from '@/services/generationBatch';+import { useImageStore } from '@/store/image';+import { generationBatchSelectors } from '@/store/image/slices/generationBatch/selectors';+import { AsyncTaskStatus } from '@/types/asyncTask';+import { type GenerationBatch } from '@/types/generation';++import { initialGenerationBatchState } from './initialState';+import { generationBatchesResource } from './projection';++vi.mock('@/services/generationBatch', () => ({+ generationBatchService: {+ deleteGenerationBatch: vi.fn(),+ getGenerationBatches: vi.fn(),+ },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const batch = (id: string): GenerationBatch =>+ ({+ id,+ provider: 'openai',+ model: 'dall-e-3',+ prompt: 'Test prompt',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ generations: [+ {+ id: `${id}-gen`,+ seed: 1,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ asyncTaskId: null,+ task: { id: `${id}-task`, status: AsyncTaskStatus.Success },+ },+ ],+ }) as unknown as GenerationBatch;++/** Never-resolving fetch: what the store holds can only have come from storage. */+const pending = () => new Promise<never>(() => {});++const TOPIC = 'gt_topic_1';+const STORAGE_KEY = generationBatchesResource.storageKey({ topicId: TOPIC });++const renderSync = () =>+ renderHook(() => useImageStore((s) => s.useFetchGenerationBatches)(TOPIC), { wrapper });++describe('image generation batches replica', () => {+ 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);+ };++ beforeEach(() => {+ vi.clearAllMocks();+ useScope(`image-user-${randomUUID()}:personal`);+ useImageStore.setState({ ...initialGenerationBatchState, activeGenerationTopicId: TOPIC });+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].map((value) =>+ generationBatchesResource.storage!.remove({ queryKey: STORAGE_KEY, scope: value }),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted batches before the network answers', async () => {+ await generationBatchesResource.storage!.set(+ { queryKey: STORAGE_KEY, scope },+ { data: [batch('gb_cached')], updatedAt: 1 },+ );+ vi.spyOn(generationBatchService, 'getGenerationBatches').mockImplementation(pending);++ renderSync();++ await waitFor(() =>+ expect(+ generationBatchSelectors.isCurrentGenerationTopicLoaded(useImageStore.getState()),+ ).toBe(true),+ );+ expect(useImageStore.getState().generationBatchesMap[TOPIC][0].id).toBe('gb_cached');+ });++ it('keeps the batch reference when the server returns an unchanged list', async () => {+ const getBatches = vi+ .spyOn(generationBatchService, 'getGenerationBatches')+ .mockResolvedValue([batch('gb_1')]);+ renderSync();+ await waitFor(() =>+ expect(useImageStore.getState().generationBatchesMap[TOPIC]).toHaveLength(1),+ );+ const before = useImageStore.getState().generationBatchesMap[TOPIC];++ getBatches.mockResolvedValue([batch('gb_1')]);+ await act(() => useImageStore.getState().refreshGenerationBatches());++ expect(useImageStore.getState().generationBatchesMap[TOPIC]).toBe(before);+ });++ it('drops the previous scope’s batches on a cache-scope switch', async () => {+ const getBatches = vi+ .spyOn(generationBatchService, 'getGenerationBatches')+ .mockResolvedValue([batch('gb_1')]);+ const { rerender } = renderSync();+ await waitFor(() =>+ expect(useImageStore.getState().generationBatchesMap[TOPIC]).toHaveLength(1),+ );++ // Switch identity: the new scope's batches are still in flight.+ useScope(`${scope.split(':')[0]}:ws-1`);+ getBatches.mockImplementation(pending);+ rerender();++ expect(useImageStore.getState().generationBatchesMap).toEqual({});+ expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(useImageStore.getState())).toBe(+ false,+ );+ });++ it('loads the active topic’s batches from the server', async () => {+ vi.spyOn(generationBatchService, 'getGenerationBatches').mockResolvedValue([batch('gb_1')]);++ const { result } = renderSync();++ await waitFor(() => expect(result.current.data).toHaveLength(1));+ expect(result.current.data?.[0].id).toBe('gb_1');+ });+});diff --git a/src/store/image/slices/generationBatch/selectors.ts b/src/store/image/slices/generationBatch/selectors.tsindex 11915217417..edff70197e2 100644--- a/src/store/image/slices/generationBatch/selectors.ts+++ b/src/store/image/slices/generationBatch/selectors.ts@@ -23,6 +23,8 @@ const getGenerationBatchByBatchId = (batchId: string) => (s: ImageStoreState) =>const isCurrentGenerationTopicLoaded = (s: ImageStoreState): boolean => {const activeTopicId = generationTopicSelectors.activeGenerationTopicId(s);if (!activeTopicId) return false;+ // The batches replica removes the key when a topic leaves the view, so a+ // present array (even empty) is exactly "hydrated or server-confirmed".return Array.isArray(s.generationBatchesMap[activeTopicId]);};diff --git a/src/store/image/slices/generationTopic/action.test.ts b/src/store/image/slices/generationTopic/action.test.tsindex 9a92ad111db..d779c509b09 100644--- a/src/store/image/slices/generationTopic/action.test.ts+++ b/src/store/image/slices/generationTopic/action.test.ts@@ -1,38 +1,30 @@import { RequestTrigger } from '@lobechat/types';-import { act, renderHook, waitFor } from '@testing-library/react';-import React from 'react';+import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createReplicaState } from '@/libs/replica';+import type * as SwrModule from '@/libs/swr';import { mutate } from '@/libs/swr';import { chatService } from '@/services/chat';import { generationTopicService } from '@/services/generationTopic';-import { useImageStore } from '@/store/image';+import { type ImageStore, useImageStore } from '@/store/image';import { type ImageGenerationTopic } from '@/types/generation';-// Mock @/libs/swr mutate-vi.mock('@/libs/swr', async () => {- const actual = await vi.importActual('@/libs/swr');- return {- ...actual,- mutate: vi.fn(),- };-});--vi.mock('swr', async () => {- const actual = await vi.importActual('swr');- return {- ...(actual as any),- mutate: vi.fn(),- };+// The replica driver revalidates through the scoped `mutate`; mock it so the+// imperative refresh assertions below can observe the call.+vi.mock('@/libs/swr', async (importOriginal) => {+ const actual = await importOriginal<typeof SwrModule>();+ return { ...actual, mutate: vi.fn() };});// Mock services and dependenciesvi.mock('@/services/generationTopic', () => ({generationTopicService: {createTopic: vi.fn(),- updateTopic: vi.fn(),deleteTopic: vi.fn(),getAllGenerationTopics: vi.fn(),+ setTopicVisibility: vi.fn(),+ updateTopic: vi.fn(),updateTopicCover: vi.fn(),},}));@@ -43,28 +35,22 @@ vi.mock('@/services/chat', () => ({},}));-vi.mock('@/store/user', () => ({- useUserStore: {- getState: vi.fn(),- },-}));--vi.mock('@/store/user/selectors', () => ({- systemAgentSelectors: {- generationTopic: vi.fn().mockReturnValue({- model: 'gpt-4',- provider: 'openai',- }),- },- userGeneralSettingsSelectors: {- currentResponseLanguage: vi.fn(() => 'en-US'),- },-}));+/** Seed the topic-list replica view (init true, so `internal_dispatch*` reduces over it). */+const seedTopics = (topics: ImageGenerationTopic[], extra: Partial<ImageStore> = {}) => {+ useImageStore.setState({+ generationTopics: topics,+ generationTopicsReplica: createReplicaState(),+ isGenerationTopicsInit: true,+ ...extra,+ });+};beforeEach(() => {vi.clearAllMocks();useImageStore.setState({generationTopics: [],+ generationTopicsReplica: createReplicaState(),+ isGenerationTopicsInit: false,activeGenerationTopicId: null,loadingGenerationTopicIds: [],newGenerationTopicVisibility: 'private',@@ -163,7 +149,7 @@ describe('GenerationTopicAction', () => {] as ImageGenerationTopic[];act(() => {- useImageStore.setState({ generationTopics: topics });+ seedTopics(topics);});act(() => {@@ -179,10 +165,7 @@ describe('GenerationTopicAction', () => {const topics = [{ id: 'gt_topic_1', title: 'Topic 1' }] as ImageGenerationTopic[];act(() => {- useImageStore.setState({- generationTopics: topics,- activeGenerationTopicId: topicId,- });+ seedTopics(topics, { activeGenerationTopicId: topicId });});const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});@@ -200,7 +183,7 @@ describe('GenerationTopicAction', () => {const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});act(() => {- useImageStore.setState({ generationTopics: [] });+ seedTopics([]);});act(() => {@@ -235,14 +218,12 @@ describe('GenerationTopicAction', () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';const prompts = ['A beautiful sunset over mountains'];- const topics = [{ id: topicId, title: 'Original Title' }] as ImageGenerationTopic[];const generatedTitle = 'Mountain Sunset Landscape';act(() => {- useImageStore.setState({ generationTopics: topics });+ seedTopics([{ id: topicId, title: 'Original Title' }] as ImageGenerationTopic[]);});- // Mock successful AI responsevi.mocked(chatService.fetchPresetTaskResult).mockImplementation((params) => {if (params.onFinish) {params.onFinish(generatedTitle, { type: 'done' });@@ -266,13 +247,11 @@ describe('GenerationTopicAction', () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';const prompts = ['A beautiful sunset over mountains with clear sky'];- const topics = [{ id: topicId, title: 'Original Title' }] as ImageGenerationTopic[];act(() => {- useImageStore.setState({ generationTopics: topics });+ seedTopics([{ id: topicId, title: 'Original Title' }] as ImageGenerationTopic[]);});- // Mock AI errorvi.mocked(chatService.fetchPresetTaskResult).mockImplementation((params) => {if (params.onError) {params.onError(new Error('AI service failed'));@@ -295,7 +274,7 @@ describe('GenerationTopicAction', () => {const { result } = renderHook(() => useImageStore());act(() => {- useImageStore.setState({ generationTopics: [] });+ seedTopics([]);});await act(async () => {@@ -309,10 +288,9 @@ describe('GenerationTopicAction', () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';const prompts = ['Test prompt'];- const topics = [{ id: topicId, title: 'Original Title' }] as ImageGenerationTopic[];act(() => {- useImageStore.setState({ generationTopics: topics });+ seedTopics([{ id: topicId, title: 'Original Title' }] as ImageGenerationTopic[]);});const updateTitleSpy = vi.spyOn(@@ -320,7 +298,6 @@ describe('GenerationTopicAction', () => {'internal_updateGenerationTopicTitleInSummary',);- // Mock streaming responsevi.mocked(chatService.fetchPresetTaskResult).mockImplementation((params) => {if (params.onMessageHandle) {params.onMessageHandle({ type: 'text', text: 'Streaming' });@@ -344,17 +321,16 @@ describe('GenerationTopicAction', () => {describe('removeGenerationTopic', () => {it('should remove topic and switch to next topic when removing active topic', async () => {const { result } = renderHook(() => useImageStore());- const topics = [- { id: 'gt_topic_1', title: 'Topic 1' },- { id: 'gt_topic_2', title: 'Topic 2' },- { id: 'gt_topic_3', title: 'Topic 3' },- ] as ImageGenerationTopic[];act(() => {- useImageStore.setState({- generationTopics: topics,- activeGenerationTopicId: 'gt_topic_2',- });+ seedTopics(+ [+ { id: 'gt_topic_1', title: 'Topic 1' },+ { id: 'gt_topic_2', title: 'Topic 2' },+ { id: 'gt_topic_3', title: 'Topic 3' },+ ] as ImageGenerationTopic[],+ { activeGenerationTopicId: 'gt_topic_2' },+ );});vi.mocked(generationTopicService.getAllGenerationTopics).mockResolvedValue([@@ -374,23 +350,17 @@ describe('GenerationTopicAction', () => {it('should open new topic when removing the last topic', async () => {const { result } = renderHook(() => useImageStore());- const topics = [{ id: 'gt_topic_1', title: 'Topic 1' }] as ImageGenerationTopic[];act(() => {- useImageStore.setState({- generationTopics: topics,+ seedTopics([{ id: 'gt_topic_1', title: 'Topic 1' }] as ImageGenerationTopic[], {activeGenerationTopicId: 'gt_topic_1',});});- // Mock getAllGenerationTopics to return empty array after deletion- vi.mocked(generationTopicService.getAllGenerationTopics).mockResolvedValue([]);-const openNewTopicSpy = vi.spyOn(result.current, 'openNewGenerationTopic');const refreshSpy = vi.spyOn(result.current, 'refreshGenerationTopics').mockImplementation(async () => {- // Simulate state update after refresh - empty topics arrayuseImageStore.setState({ generationTopics: [] });});@@ -405,16 +375,15 @@ describe('GenerationTopicAction', () => {it('should not switch topic when removing non-active topic', async () => {const { result } = renderHook(() => useImageStore());- const topics = [- { id: 'gt_topic_1', title: 'Topic 1' },- { id: 'gt_topic_2', title: 'Topic 2' },- ] as ImageGenerationTopic[];act(() => {- useImageStore.setState({- generationTopics: topics,- activeGenerationTopicId: 'gt_topic_1',- });+ seedTopics(+ [+ { id: 'gt_topic_1', title: 'Topic 1' },+ { id: 'gt_topic_2', title: 'Topic 2' },+ ] as ImageGenerationTopic[],+ { activeGenerationTopicId: 'gt_topic_1' },+ );});const switchTopicSpy = vi.spyOn(result.current, 'switchGenerationTopic');@@ -431,36 +400,6 @@ describe('GenerationTopicAction', () => {});describe('useFetchGenerationTopics', () => {- it('should fetch generation topics when enabled', async () => {- const topics = [- { id: 'gt_topic_1', title: 'Topic 1', createdAt: new Date(), updatedAt: new Date() },- { id: 'gt_topic_2', title: 'Topic 2', createdAt: new Date(), updatedAt: new Date() },- ] as ImageGenerationTopic[];-- vi.mocked(generationTopicService.getAllGenerationTopics).mockResolvedValue(topics);-- await act(async () => {- renderHook(() => {- const store = useImageStore();- // Actually call the SWR hook to trigger the service call- const swrResult = store.useFetchGenerationTopics(true);-- // Simulate the SWR onSuccess callback behavior- React.useEffect(() => {- useImageStore.setState({ generationTopics: topics });- }, []);-- return swrResult;- });- });-- // Wait for service to be called and state to be updated- await waitFor(() => {- expect(generationTopicService.getAllGenerationTopics).toHaveBeenCalled();- expect(useImageStore.getState().generationTopics).toEqual(topics);- });- });-it('should not fetch when disabled', async () => {const { result } = renderHook(() => useImageStore().useFetchGenerationTopics(false));@@ -470,18 +409,15 @@ describe('GenerationTopicAction', () => {});describe('refreshGenerationTopics', () => {- afterEach(() => {- vi.resetAllMocks();- });-- it('should call mutate to refresh topics', async () => {+ it('should revalidate the topic list replica', async () => {const { result } = renderHook(() => useImageStore());await act(async () => {await result.current.refreshGenerationTopics();});- expect(mutate).toHaveBeenCalledWith(['image:generationTopics']);+ // The replica driver revalidates through the scoped mutate with a matcher.+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));});});@@ -490,10 +426,9 @@ describe('GenerationTopicAction', () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';const coverUrl = 'https://example.com/cover.jpg';- const topics = [{ id: topicId, title: 'Topic 1', coverUrl: '' }] as ImageGenerationTopic[];act(() => {- useImageStore.setState({ generationTopics: topics });+ seedTopics([{ id: topicId, title: 'Topic 1', coverUrl: '' }] as ImageGenerationTopic[]);});const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationTopic');@@ -502,11 +437,14 @@ describe('GenerationTopicAction', () => {await result.current.updateGenerationTopicCover(topicId, coverUrl);});- expect(dispatchSpy).toHaveBeenCalledWith(- { type: 'updateTopic', id: topicId, value: { coverUrl } },- 'internal_updateGenerationTopicCover/optimistic',- );+ expect(dispatchSpy).toHaveBeenCalledWith({+ type: 'updateTopic',+ id: topicId,+ value: { coverUrl },+ });expect(generationTopicService.updateTopicCover).toHaveBeenCalledWith(topicId, coverUrl);+ // the optimistic cover is written into the replica view+ expect(result.current.generationTopics[0].coverUrl).toBe(coverUrl);});});@@ -543,12 +481,11 @@ describe('GenerationTopicAction', () => {});describe('internal_dispatchGenerationTopic', () => {- it('should update topics when state changes', async () => {+ it('should write the reduced topics into the replica view', async () => {const { result } = renderHook(() => useImageStore());- const initialTopics = [{ id: 'gt_topic_1', title: 'Topic 1' }] as ImageGenerationTopic[];act(() => {- useImageStore.setState({ generationTopics: initialTopics });+ seedTopics([{ id: 'gt_topic_1', title: 'Topic 1' }] as ImageGenerationTopic[]);});act(() => {@@ -562,20 +499,19 @@ describe('GenerationTopicAction', () => {expect(result.current.generationTopics.find((t) => t.id === 'gt_topic_2')).toBeDefined();});- it('should not update when topics are equal', async () => {+ it('should update a topic in place', async () => {const { result } = renderHook(() => useImageStore());const existingDate = new Date('2024-01-01T00:00:00.000Z');- const topics = [- {- id: 'gt_topic_1',- title: 'Topic 1',- createdAt: existingDate,- updatedAt: existingDate,- },- ] as ImageGenerationTopic[];act(() => {- useImageStore.setState({ generationTopics: topics });+ seedTopics([+ {+ id: 'gt_topic_1',+ title: 'Topic 1',+ createdAt: existingDate,+ updatedAt: existingDate,+ },+ ] as ImageGenerationTopic[]);});const stateBefore = result.current.generationTopics;@@ -584,15 +520,12 @@ describe('GenerationTopicAction', () => {result.current.internal_dispatchGenerationTopic({type: 'updateTopic',id: 'gt_topic_1',- value: { title: 'Topic 1' }, // Same title, but updatedAt will still change+ value: { title: 'Renamed' },});});- // The state object reference should change due to updatedAt being updatedexpect(result.current.generationTopics).not.toBe(stateBefore);- // But the topic should still exist with updated timestamp- expect(result.current.generationTopics[0].id).toBe('gt_topic_1');- expect(result.current.generationTopics[0].title).toBe('Topic 1');+ expect(result.current.generationTopics[0].title).toBe('Renamed');expect(result.current.generationTopics[0].updatedAt.getTime()).toBeGreaterThan(existingDate.getTime(),);@@ -653,6 +586,10 @@ describe('GenerationTopicAction', () => {const topicId = 'gt_topic_1';const updateData = { title: 'Updated Title' };+ act(() => {+ seedTopics([{ id: topicId, title: 'Topic 1' }] as ImageGenerationTopic[]);+ });+const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationTopic');const loadingSpy = vi.spyOn(result.current, 'internal_updateGenerationTopicLoading');const refreshSpy = vi.spyOn(result.current, 'refreshGenerationTopics');@@ -674,21 +611,26 @@ describe('GenerationTopicAction', () => {});describe('internal_updateGenerationTopicTitleInSummary', () => {- it('should dispatch title update action', async () => {+ it('should write the streamed title into the replica view', async () => {const { result } = renderHook(() => useImageStore());const topicId = 'gt_topic_1';- const title = 'Summary Title';++ act(() => {+ seedTopics([{ id: topicId, title: 'Original' }] as ImageGenerationTopic[]);+ });const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationTopic');act(() => {- result.current.internal_updateGenerationTopicTitleInSummary(topicId, title);+ result.current.internal_updateGenerationTopicTitleInSummary(topicId, 'Summary Title');});- expect(dispatchSpy).toHaveBeenCalledWith(- { type: 'updateTopic', id: topicId, value: { title } },- 'updateGenerationTopicTitleInSummary',- );+ expect(dispatchSpy).toHaveBeenCalledWith({+ type: 'updateTopic',+ id: topicId,+ value: { title: 'Summary Title' },+ });+ expect(result.current.generationTopics[0].title).toBe('Summary Title');});});diff --git a/src/store/image/slices/generationTopic/action.ts b/src/store/image/slices/generationTopic/action.tsindex f14451b5c49..c4f5feb95ea 100644--- a/src/store/image/slices/generationTopic/action.ts+++ b/src/store/image/slices/generationTopic/action.ts@@ -1,11 +1,9 @@import { chainSummaryGenerationTitle } from '@lobechat/prompts';import { RequestTrigger } from '@lobechat/types';import isEqual from 'fast-deep-equal';-import { type SWRResponse } from 'swr';import { LOADING_FLAT } from '@/const/message';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { imageKeys } from '@/libs/swr/keys';+import { createReplicaSlice, type ReplicaLens, type ReplicaSyncResult } from '@/libs/replica';import { type UpdateTopicValue } from '@/server/routers/lambda/generationTopic';import { chatService } from '@/services/chat';import { generationTopicService } from '@/services/generationTopic';@@ -18,12 +16,49 @@ import { setNamespace } from '@/utils/storeDebug';import { type ImageStore } from '../../store';import { type GenerationTopicVisibility } from './initialState';+import { GENERATION_TOPICS_KEY, generationTopicsResource } from './projection';import { type GenerationTopicDispatch } from './reducer';import { generationTopicReducer } from './reducer';import { generationTopicSelectors } from './selectors';const n = setNamespace('generationTopic');+const TOPICS_PARAMS = {} as Record<string, never>;++/**+ * Result of the topic-list sync. `data` mirrors the SWR-era shape the shared+ * generation layout reads (`data !== undefined` marks the list as loaded at+ * least once, so an absent routed topic is a settled "not found"); the replica+ * flags are what the owner should use going forward.+ */+export interface GenerationTopicsSyncResult extends ReplicaSyncResult {+ data?: ImageGenerationTopic[];+ /** A request is in flight and the list has never loaded. */+ isLoading: boolean;+ /** Alias of `revalidate`. */+ mutate: () => Promise<unknown>;+}++/**+ * The topic list keeps its long-standing flat field (`generationTopics`) as the+ * replica view, gated by `isGenerationTopicsInit` so a loaded-but-empty list+ * stays distinguishable from one that was never fetched — and so `hydrate` is+ * not skipped by an always-array view.+ *+ * The cache scope (`${userId}:${workspaceId}`) owns the partition: a switch+ * clears the view before paint, so one identity's topics can never render under+ * another.+ */+const generationTopicsLens: ReplicaLens<ImageStore, ImageGenerationTopic[]> = {+ clear: () => ({ generationTopics: [], isGenerationTopicsInit: false }),+ get: (state) => (state.isGenerationTopicsInit ? state.generationTopics : undefined),+ keys: (state) => (state.isGenerationTopicsInit ? [GENERATION_TOPICS_KEY] : []),+ set: (_state, _key, data) =>+ data+ ? { generationTopics: data, isGenerationTopicsInit: true }+ : { generationTopics: [], isGenerationTopicsInit: false },+};+type Setter = StoreSetter<ImageStore>;export const createGenerationTopicSlice = (set: Setter, get: () => ImageStore, _api?: unknown) =>new GenerationTopicActionImpl(set, get, _api);@@ -31,11 +66,22 @@ export const createGenerationTopicSlice = (set: Setter, get: () => ImageStore, _export class GenerationTopicActionImpl {readonly #get: () => ImageStore;readonly #set: Setter;+ readonly #topics;constructor(set: Setter, get: () => ImageStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#topics = createReplicaSlice(generationTopicsResource, {+ actionPrefix: n('generationTopics'),+ fetcher: () => generationTopicService.getAllGenerationTopics('image'),+ get,+ // An unchanged list must not re-render the sidebar / command menu.+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'generationTopicsReplica',+ view: generationTopicsLens,+ });}createGenerationTopic = async (prompts: string[]): Promise<string> => {@@ -142,13 +188,10 @@ export class GenerationTopicActionImpl {const { newGenerationTopicVisibility } = this.#get();// 1. Optimistic update - add temporary topic- this.#get().internal_dispatchGenerationTopic(- {- type: 'addTopic',- value: { id: tmpId, title: '', visibility: newGenerationTopicVisibility },- },- 'internal_createGenerationTopic',- );+ this.#get().internal_dispatchGenerationTopic({+ type: 'addTopic',+ value: { id: tmpId, title: '', visibility: newGenerationTopicVisibility },+ });this.#get().internal_updateGenerationTopicLoading(tmpId, true);@@ -207,10 +250,7 @@ export class GenerationTopicActionImpl {};internal_updateGenerationTopicTitleInSummary = (id: string, title: string): void => {- this.#get().internal_dispatchGenerationTopic(- { type: 'updateTopic', id, value: { title } },- 'updateGenerationTopicTitleInSummary',- );+ this.#get().internal_dispatchGenerationTopic({ type: 'updateTopic', id, value: { title } });};internal_updateGenerationTopicLoading = (id: string, loading: boolean): void => {@@ -227,35 +267,41 @@ export class GenerationTopicActionImpl {);};- internal_dispatchGenerationTopic = (payload: GenerationTopicDispatch, action?: any): void => {- const nextTopics = generationTopicReducer(this.#get().generationTopics, payload);-- // No need to update if the topics are the same- if (isEqual(nextTopics, this.#get().generationTopics)) return;-- this.#set(- { generationTopics: nextTopics },- false,- action ?? n(`dispatchGenerationTopic/${payload.type}`),+ /**+ * Optimistic write into the topic-list replica. Not persisted on its own: the+ * follow-up `refreshGenerationTopics` confirms the server value and persists+ * that, so a local placeholder never outlives the request that created it.+ */+ internal_dispatchGenerationTopic = (payload: GenerationTopicDispatch): void => {+ this.#topics.update(+ GENERATION_TOPICS_KEY,+ (topics) => generationTopicReducer(topics, payload),+ { persist: false },);};- useFetchGenerationTopics = (enabled: boolean): SWRResponse<ImageGenerationTopic[]> => {- return useClientDataSWR<ImageGenerationTopic[]>(- enabled ? imageKeys.generationTopics() : null,- () => generationTopicService.getAllGenerationTopics('image'),- {- onSuccess: (data) => {- // No need to update if data is the same- if (isEqual(data, this.#get().generationTopics)) return;- this.#set({ generationTopics: data }, false, n('useFetchGenerationTopics'));- },- },- );+ /**+ * Fetch orchestration for every surface that renders the topic list (sidebar,+ * routed workspace, command menu). The list is read through+ * `generationTopicSelectors`, not from this return value.+ */+ useFetchGenerationTopics = (enabled: boolean): GenerationTopicsSyncResult => {+ const sync = this.#topics.useSync(TOPICS_PARAMS, { enabled });+ const { generationTopics, isGenerationTopicsInit } = this.#get();++ return {+ data: isGenerationTopicsInit ? generationTopics : undefined,+ error: sync.error,+ isHydrated: sync.isHydrated,+ isLoading: sync.isValidating && !isGenerationTopicsInit,+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ revalidate: sync.revalidate,+ };};refreshGenerationTopics = async (): Promise<void> => {- await mutate(imageKeys.generationTopics());+ await this.#topics.revalidate();};removeGenerationTopic = async (id: string): Promise<void> => {@@ -317,17 +363,10 @@ export class GenerationTopicActionImpl {topicId: string,coverUrl: string,): Promise<void> => {- const {- internal_dispatchGenerationTopic,- internal_updateGenerationTopicLoading,- refreshGenerationTopics,- } = this.#get();+ const { internal_dispatchGenerationTopic, internal_updateGenerationTopicLoading } = this.#get();// 1. Optimistic update - immediately show the new cover URL in UI- internal_dispatchGenerationTopic(- { type: 'updateTopic', id: topicId, value: { coverUrl } },- 'internal_updateGenerationTopicCover/optimistic',- );+ internal_dispatchGenerationTopic({ type: 'updateTopic', id: topicId, value: { coverUrl } });// 2. Set loading stateinternal_updateGenerationTopicLoading(topicId, true);@@ -337,7 +376,7 @@ export class GenerationTopicActionImpl {await generationTopicService.updateTopicCover(topicId, coverUrl);// 4. Refresh data to get the final processed cover URL from S3- await refreshGenerationTopics();+ await this.#get().refreshGenerationTopics();} finally {// 5. Clear loading stateinternal_updateGenerationTopicLoading(topicId, false);diff --git a/src/store/image/slices/generationTopic/initialState.ts b/src/store/image/slices/generationTopic/initialState.tsindex ecd2148bbb2..51e86cceae0 100644--- a/src/store/image/slices/generationTopic/initialState.ts+++ b/src/store/image/slices/generationTopic/initialState.ts@@ -1,3 +1,4 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { type ImageGenerationTopic } from '@/types/generation';export type GenerationTopicVisibility = NonNullable<ImageGenerationTopic['visibility']>;@@ -5,7 +6,16 @@ export type GenerationTopicVisibility = NonNullable<ImageGenerationTopic['visibiexport interface GenerationTopicState {activeGenerationTopicId: string | null;loadingGenerationTopicIds: string[];+ /** Replica view of the topic list, one entry per cache scope (`generationTopicSelectors`). */generationTopics: ImageGenerationTopic[];+ /** Replica bookkeeping of `generationTopics`. */+ generationTopicsReplica: ReplicaState<ImageGenerationTopic[]>;+ /**+ * The topic list has been hydrated or server-confirmed at least once. An+ * absent topic is only a settled "not found" once this is true — before the+ * first load the routed topic is merely not painted yet.+ */+ isGenerationTopicsInit: boolean;newGenerationTopicVisibility: GenerationTopicVisibility;}@@ -14,5 +24,7 @@ export const initialGenerationTopicState: GenerationTopicState = {typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('topic') : null,loadingGenerationTopicIds: [],generationTopics: [],+ generationTopicsReplica: createReplicaState(),+ isGenerationTopicsInit: false,newGenerationTopicVisibility: 'private',};diff --git a/src/store/image/slices/generationTopic/projection.ts b/src/store/image/slices/generationTopic/projection.tsnew file mode 100644index 00000000000..f70f4689ef8--- /dev/null+++ b/src/store/image/slices/generationTopic/projection.ts@@ -0,0 +1,27 @@+import { defineReplica } from '@/libs/replica';+import type { ImageGenerationTopic } from '@/types/generation';++/**+ * The image generation topics list is a single entry per cache scope. The+ * server returns every topic the caller may see (`getAllGenerationTopics('image')`),+ * so there is no server-side filter or pagination to keep apart — the only+ * partition is the identity scope (`${userId}:${workspaceId}`), which the+ * replica owns.+ */+export const GENERATION_TOPICS_KEY = 'image';++/**+ * Image generation topics of the active scope. Read through+ * `generationTopicSelectors.generationTopics`; the persisted copy keeps the+ * sidebar and the routed topic panel populated instead of flashing a skeleton+ * on the first frame after a reload.+ */+export const generationTopicsResource = defineReplica<+ Record<string, never>,+ ImageGenerationTopic[]+>({+ key: () => GENERATION_TOPICS_KEY,+ name: 'imageGenerationTopics',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/image/slices/generationTopic/replica.test.ts b/src/store/image/slices/generationTopic/replica.test.tsnew file mode 100644index 00000000000..3e02d9e91d8--- /dev/null+++ b/src/store/image/slices/generationTopic/replica.test.ts@@ -0,0 +1,169 @@+/**+ * @vitest-environment happy-dom+ *+ * The image generation topic list is a `@lobechat/replica` resource whose view+ * is the image store's `generationTopics` field: the persisted projection paints+ * while the network confirms it, an unchanged response keeps the array+ * reference, a cache-scope switch drops the previous identity's topics before+ * paint, and a create revalidates the list so the new topic appears.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { generationTopicService } from '@/services/generationTopic';+import { useImageStore } from '@/store/image';+import { generationTopicSelectors } from '@/store/image/slices/generationTopic/selectors';+import { type ImageGenerationTopic } from '@/types/generation';++import { initialGenerationTopicState } from './initialState';+import { generationTopicsResource } from './projection';++vi.mock('@/services/generationTopic', () => ({+ generationTopicService: {+ createTopic: vi.fn(),+ deleteTopic: vi.fn(),+ getAllGenerationTopics: vi.fn(),+ setTopicVisibility: vi.fn(),+ updateTopic: vi.fn(),+ updateTopicCover: vi.fn(),+ },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const topic = (id: string, overrides: Partial<ImageGenerationTopic> = {}): ImageGenerationTopic =>+ ({+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id,+ title: id,+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ ...overrides,+ }) as ImageGenerationTopic;++/** Never-resolving fetch: what the store holds can only have come from storage. */+const pending = () => new Promise<never>(() => {});++const STORAGE_KEY = generationTopicsResource.storageKey({});++const renderSync = () =>+ renderHook(() => useImageStore((s) => s.useFetchGenerationTopics)(true), { wrapper });++describe('image generation topics replica', () => {+ 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);+ };++ beforeEach(() => {+ vi.clearAllMocks();+ useScope(`image-user-${randomUUID()}:personal`);+ useImageStore.setState({ ...initialGenerationTopicState });+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].map((value) =>+ generationTopicsResource.storage!.remove({ queryKey: STORAGE_KEY, scope: value }),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted topics before the network answers', async () => {+ await generationTopicsResource.storage!.set(+ { queryKey: STORAGE_KEY, scope },+ { data: [topic('t1', { title: 'Cached' })], updatedAt: 1 },+ );+ vi.spyOn(generationTopicService, 'getAllGenerationTopics').mockImplementation(pending);++ renderSync();++ await waitFor(() => expect(useImageStore.getState().isGenerationTopicsInit).toBe(true));+ expect(generationTopicSelectors.generationTopics(useImageStore.getState())[0].title).toBe(+ 'Cached',+ );+ });++ it('reports `data` only after the list has loaded at least once', async () => {+ vi.spyOn(generationTopicService, 'getAllGenerationTopics').mockResolvedValue([topic('t1')]);++ const { result } = renderSync();++ expect(result.current.data).toBeUndefined();+ await waitFor(() => expect(result.current.data).toHaveLength(1));+ });++ it('keeps the list reference when the server returns an unchanged list', async () => {+ const getAll = vi+ .spyOn(generationTopicService, 'getAllGenerationTopics')+ .mockResolvedValue([topic('t1')]);+ renderSync();+ await waitFor(() => expect(useImageStore.getState().generationTopics).toHaveLength(1));+ const before = useImageStore.getState().generationTopics;++ getAll.mockResolvedValue([topic('t1')]);+ await act(() => useImageStore.getState().refreshGenerationTopics());++ expect(useImageStore.getState().generationTopics).toBe(before);+ });++ it('drops the previous scope’s topics on a cache-scope switch', async () => {+ const getAll = vi+ .spyOn(generationTopicService, 'getAllGenerationTopics')+ .mockResolvedValue([topic('t1', { title: 'Personal' })]);+ const { rerender } = renderSync();+ await waitFor(() => expect(useImageStore.getState().generationTopics).toHaveLength(1));++ // Switch identity: the new scope's list is still in flight.+ useScope(`${scope.split(':')[0]}:ws-1`);+ getAll.mockImplementation(pending);+ rerender();++ expect(useImageStore.getState().generationTopics).toEqual([]);+ expect(useImageStore.getState().isGenerationTopicsInit).toBe(false);+ });++ it('refreshes the list after a topic is created', async () => {+ const getAll = vi.spyOn(generationTopicService, 'getAllGenerationTopics').mockResolvedValue([]);+ vi.spyOn(generationTopicService, 'createTopic').mockResolvedValue('t1');+ renderSync();+ await waitFor(() => expect(useImageStore.getState().isGenerationTopicsInit).toBe(true));++ getAll.mockResolvedValue([topic('t1', { title: 'Fresh' })]);+ await act(() => useImageStore.getState().internal_createGenerationTopic());++ await waitFor(() =>+ expect(generationTopicSelectors.generationTopics(useImageStore.getState())).toHaveLength(1),+ );+ expect(generationTopicSelectors.generationTopics(useImageStore.getState())[0].title).toBe(+ 'Fresh',+ );+ });+});