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(video): move generation topics and batches onto @lobechat/replica (#20643)

Arvin Xu75a1a73c2edf
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 523c2bdab2d..d590b0ecc30 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -425,17 +425,15 @@ export const imageKeys = {
};
// ---- video generation ---------------------------------------------------
+// The topic list and the per-topic batches live in `@lobechat/replica`
+// resources now (see `src/store/video/slices/*/projection.ts`); only the
+// generation-status poll is still an SWR key.
export const videoKeys = {
- generationBatches: def('video:generationBatches', (topicId: string) => [
- 'video:generationBatches',
- topicId,
- ]),
generationStatus: def('video:generationStatus', (generationId: string, asyncTaskId?: string) => [
'video:generationStatus',
generationId,
asyncTaskId,
]),
- generationTopics: def('video:generationTopics', () => ['video:generationTopics']),
};
// ---- serverConfig -------------------------------------------------------
diff --git a/src/store/video/slices/generationBatch/action.test.ts b/src/store/video/slices/generationBatch/action.test.ts
new file mode 100644
index 00000000000..7b8f5b0f7a3
--- /dev/null
+++ b/src/store/video/slices/generationBatch/action.test.ts
@@ -0,0 +1,354 @@
+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';
+import { generationBatchService } from '@/services/generationBatch';
+import { useVideoStore } from '@/store/video';
+import { generationBatchSelectors } from '@/store/video/slices/generationBatch/selectors';
+import { AsyncTaskStatus } from '@/types/asyncTask';
+import { type GenerationBatch } from '@/types/generation';
+
+// 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(),
+ getGenerationStatus: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/generationBatch', () => ({
+ generationBatchService: {
+ deleteGenerationBatch: vi.fn(),
+ getGenerationBatches: 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[]) => {
+ useVideoStore.setState({
+ activeGenerationTopicId: topicId,
+ generationBatchesMap: { [topicId]: batches },
+ generationBatchesReplica: createReplicaState(),
+ });
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useVideoStore.setState({
+ activeGenerationTopicId: null,
+ generationBatchesMap: {},
+ generationBatchesReplica: createReplicaState(),
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('VideoGenerationBatchAction', () => {
+ describe('setTopicBatchLoaded', () => {
+ it('seeds an empty list and marks the topic as loaded', () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ useVideoStore.setState({ activeGenerationTopicId: topicId });
+ });
+
+ expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(result.current)).toBe(false);
+
+ act(() => {
+ result.current.setTopicBatchLoaded(topicId);
+ });
+
+ expect(result.current.generationBatchesMap[topicId]).toEqual([]);
+ expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(result.current)).toBe(true);
+ });
+
+ it('keeps the existing list reference when the topic is already loaded', () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, []);
+ });
+
+ const stateBefore = result.current.generationBatchesMap;
+
+ act(() => {
+ result.current.setTopicBatchLoaded(topicId);
+ });
+
+ expect(result.current.generationBatchesMap).toBe(stateBefore);
+ });
+ });
+
+ describe('removeGeneration', () => {
+ it('should remove generation and clean up empty batch', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1'])]);
+ });
+
+ const deleteBatchSpy = vi
+ .spyOn(result.current, 'internal_deleteGenerationBatch')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.removeGeneration('gen_1');
+ });
+
+ expect(generationService.deleteGeneration).toHaveBeenCalledWith('gen_1');
+ expect(deleteBatchSpy).toHaveBeenCalledWith('gb_batch_1', topicId);
+ });
+
+ it('should only remove generation if batch is not empty', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1', 'gen_2'])]);
+ });
+
+ const deleteBatchSpy = vi.spyOn(result.current, 'internal_deleteGenerationBatch');
+
+ await act(async () => {
+ await result.current.removeGeneration('gen_1');
+ });
+
+ expect(deleteBatchSpy).not.toHaveBeenCalled();
+ });
+
+ it('should do nothing if no active topic', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ await act(async () => {
+ await result.current.removeGeneration('gen_1');
+ });
+
+ expect(generationService.deleteGeneration).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('internal_deleteGeneration', () => {
+ it('should delete the generation optimistically and confirm with the server', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1', 'gen_2'])]);
+ });
+
+ await act(async () => {
+ await result.current.internal_deleteGeneration('gen_1');
+ });
+
+ 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 roll the generation back into the list when the server rejects', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1', 'gen_2'])]);
+ });
+
+ vi.mocked(generationService.deleteGeneration).mockRejectedValueOnce(new Error('nope'));
+
+ await act(async () => {
+ await expect(result.current.internal_deleteGeneration('gen_1')).rejects.toThrow('nope');
+ });
+
+ const generations = result.current.generationBatchesMap[topicId][0].generations;
+ expect(generations.map((generation) => generation.id)).toEqual(['gen_1', 'gen_2']);
+ });
+
+ it('should do nothing if generation not found', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ seedBatch('gt_topic_1', []);
+ });
+
+ await act(async () => {
+ await result.current.internal_deleteGeneration('non_existent_gen');
+ });
+
+ expect(generationService.deleteGeneration).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('removeGenerationBatch', () => {
+ it('should call internal_deleteGenerationBatch', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ const deleteBatchSpy = vi
+ .spyOn(result.current, 'internal_deleteGenerationBatch')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.removeGenerationBatch('gb_batch_1', 'gt_topic_1');
+ });
+
+ expect(deleteBatchSpy).toHaveBeenCalledWith('gb_batch_1', 'gt_topic_1');
+ });
+ });
+
+ describe('internal_deleteGenerationBatch', () => {
+ it('should delete the batch optimistically and confirm with the server', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1'])]);
+ });
+
+ await act(async () => {
+ await result.current.internal_deleteGenerationBatch('gb_batch_1', topicId);
+ });
+
+ expect(generationBatchService.deleteGenerationBatch).toHaveBeenCalledWith('gb_batch_1');
+ expect(result.current.generationBatchesMap[topicId]).toEqual([]);
+ });
+
+ it('should restore the batch when the server rejects', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, [batch('gb_batch_1', ['gen_1'])]);
+ });
+
+ vi.mocked(generationBatchService.deleteGenerationBatch).mockRejectedValueOnce(
+ new Error('nope'),
+ );
+
+ await act(async () => {
+ await expect(
+ result.current.internal_deleteGenerationBatch('gb_batch_1', topicId),
+ ).rejects.toThrow('nope');
+ });
+
+ expect(result.current.generationBatchesMap[topicId]).toHaveLength(1);
+ });
+ });
+
+ describe('internal_dispatchGenerationBatch', () => {
+ it('should update a loaded topic when state changes', () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedBatch(topicId, []);
+ });
+
+ act(() => {
+ 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 leave an unloaded topic untouched', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ result.current.internal_dispatchGenerationBatch('gt_not_loaded', {
+ type: 'addBatch',
+ value: batch('gb_batch_1', []),
+ });
+ });
+
+ expect(result.current.generationBatchesMap['gt_not_loaded']).toBeUndefined();
+ });
+ });
+
+ describe('refreshGenerationBatches', () => {
+ it('should revalidate the active topic entry', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ useVideoStore.setState({ activeGenerationTopicId: 'gt_topic_1' });
+ });
+
+ await act(async () => {
+ await result.current.refreshGenerationBatches();
+ });
+
+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));
+ });
+
+ it('should not revalidate when no active topic', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ await act(async () => {
+ await result.current.refreshGenerationBatches();
+ });
+
+ expect(mutate).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('useFetchGenerationBatches', () => {
+ it('should not fetch when no topicId', () => {
+ const { result } = renderHook(() => useVideoStore().useFetchGenerationBatches(null));
+
+ expect(result.current.data).toBeUndefined();
+ expect(generationBatchService.getGenerationBatches).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('useCheckGenerationStatus', () => {
+ it('should not check status for temporary generations', () => {
+ const { result } = renderHook(() =>
+ useVideoStore().useCheckGenerationStatus('temp-gen-1', 'task_1', 'gt_topic_1'),
+ );
+
+ expect(result.current.data).toBeUndefined();
+ expect(generationService.getGenerationStatus).not.toHaveBeenCalled();
+ });
+
+ it('should not check status when disabled', () => {
+ const { result } = renderHook(() =>
+ useVideoStore().useCheckGenerationStatus('gen_1', 'task_1', 'gt_topic_1', false),
+ );
+
+ expect(result.current.data).toBeUndefined();
+ expect(generationService.getGenerationStatus).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/store/video/slices/generationBatch/action.ts b/src/store/video/slices/generationBatch/action.ts
index 9f78aeab205..dbf0d9cc2ed 100644
--- a/src/store/video/slices/generationBatch/action.ts
+++ b/src/store/video/slices/generationBatch/action.ts
@@ -1,8 +1,9 @@
import { isEqual } from 'es-toolkit/compat';
import { useRef } from 'react';
-import type { SWRResponse } from 'swr';
+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 { videoKeys } from '@/libs/swr/keys';
import { type GetGenerationStatusResult } from '@/server/routers/lambda/generation';
import { generationService } from '@/services/generation';
@@ -14,11 +15,24 @@ import { setNamespace } from '@/utils/storeDebug';
import { type VideoStore } from '../../store';
import { generationTopicSelectors } from '../generationTopic/selectors';
+import { generationBatchesResource } from './projection';
import { type GenerationBatchDispatch, generationBatchReducer } from './reducer';
const n = setNamespace('generationBatch');
-// ====== SWR key ====== //
+/**
+ * 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<VideoStore>;
@@ -26,82 +40,33 @@ export const createGenerationBatchSlice = (set: Setter, get: () => VideoStore, _
new GenerationBatchActionImpl(set, get, _api);
export class GenerationBatchActionImpl {
+ readonly #batches;
readonly #get: () => VideoStore;
- readonly #set: Setter;
constructor(set: Setter, get: () => VideoStore, _api?: unknown) {
void _api;
- this.#set = set;
this.#get = get;
+ this.#batches = createReplicaSlice(generationBatchesResource, {
+ actionPrefix: n('generationBatches'),
+ fetcher: ({ topicId }) => generationBatchService.getGenerationBatches(topicId, 'video'),
+ get,
+ // An unchanged topic list must not re-render the feed.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set,
+ stateKey: 'generationBatchesReplica',
+ view: recordLens<VideoStore, GenerationBatch[]>('generationBatchesMap'),
+ });
}
- internal_deleteGeneration = async (generationId: string): Promise<void> => {
- const { activeGenerationTopicId, refreshGenerationBatches, internal_dispatchGenerationBatch } =
- this.#get();
-
- if (!activeGenerationTopicId) return;
-
- const currentBatches = this.#get().generationBatchesMap[activeGenerationTopicId] || [];
- const targetBatch = currentBatches.find((batch) =>
- batch.generations.some((gen) => gen.id === generationId),
- );
-
- if (!targetBatch) return;
-
- // Optimistic update
- internal_dispatchGenerationBatch(
- activeGenerationTopicId,
- { batchId: targetBatch.id, generationId, type: 'deleteGenerationInBatch' },
- 'internal_deleteGeneration',
- );
-
- await generationService.deleteGeneration(generationId);
- await refreshGenerationBatches();
- };
-
- internal_deleteGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {
- const { internal_dispatchGenerationBatch, refreshGenerationBatches } = this.#get();
-
- // Optimistic update
- internal_dispatchGenerationBatch(
- topicId,
- { id: batchId, type: 'deleteBatch' },
- 'internal_deleteGenerationBatch',
- );
-
- await generationBatchService.deleteGenerationBatch(batchId);
- 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,
- };
-
- if (isEqual(nextMap, this.#get().generationBatchesMap)) return;
-
- this.#set(
- {
- generationBatchesMap: nextMap,
- },
- false,
- action ?? n(`dispatchGenerationBatch/${payload.type}`),
- );
- };
-
- refreshGenerationBatches = async (): Promise<void> => {
- const { activeGenerationTopicId } = this.#get();
- if (activeGenerationTopicId) {
- await mutate(videoKeys.generationBatches(activeGenerationTopicId));
- }
+ /**
+ * 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 => {
+ this.#batches.update(topicId, (batches) => (Array.isArray(batches) ? batches : []), {
+ persist: false,
+ });
};
removeGeneration = async (generationId: string): Promise<void> => {
@@ -123,6 +88,35 @@ 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 = this.#get().activeGenerationTopicId;
+ if (!activeGenerationTopicId) return;
+
+ const currentBatches = this.#get().generationBatchesMap[activeGenerationTopicId] ?? [];
+ const targetBatch = currentBatches.find((batch) =>
+ batch.generations.some((gen) => gen.id === generationId),
+ );
+
+ if (!targetBatch) return;
+
+ await this.#batches.optimistic(
+ activeGenerationTopicId,
+ (batches) =>
+ generationBatchReducer(batches, {
+ batchId: targetBatch.id,
+ generationId,
+ type: 'deleteGenerationInBatch',
+ }),
+ () => generationService.deleteGeneration(generationId),
+ { revalidate: true },
+ );
+ };
+
removeGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {
const { editingGenerationId, generationBatchesMap, internal_deleteGenerationBatch } =
this.#get();
@@ -137,23 +131,54 @@ export class GenerationBatchActionImpl {
if (containsEditingSource) this.#get().cancelEditingVideo();
};
- setTopicBatchLoaded = (topicId: string): void => {
- const nextMap = {
- ...this.#get().generationBatchesMap,
- [topicId]: [],
- };
-
- if (isEqual(nextMap, this.#get().generationBatchesMap)) return;
+ internal_deleteGenerationBatch = async (batchId: string, topicId: string): Promise<void> => {
+ await this.#batches.optimistic(
+ topicId,
+ (batches) => generationBatchReducer(batches, { id: batchId, type: 'deleteBatch' }),
+ () => generationBatchService.deleteGenerationBatch(batchId),
+ { revalidate: true },
+ );
+ };
- this.#set(
- {
- generationBatchesMap: nextMap,
- },
- false,
- n('setTopicBatchLoaded'),
+ /**
+ * 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 this.#batches.revalidate(activeGenerationTopicId);
+ }
+ };
+
+ /**
+ * 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 = (
generationId: string,
asyncTaskId: string,
@@ -193,18 +218,12 @@ export class GenerationBatchActionImpl {
requestCountRef.current = 0;
if (data.generation) {
- this.#get().internal_dispatchGenerationBatch(
- topicId,
- {
- batchId: targetBatch.id,
- generationId,
- type: 'updateGenerationInBatch',
- 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 it
if (data.status === AsyncTaskStatus.Success && data.generation.asset?.thumbnailUrl) {
@@ -246,32 +265,6 @@ export class GenerationBatchActionImpl {
},
);
};
-
- useFetchGenerationBatches = (topicId?: string | null): SWRResponse<GenerationBatch[]> =>
- useClientDataSWR<GenerationBatch[]>(
- topicId ? videoKeys.generationBatches(topicId) : null,
- async ([, topicId]: [string, string]) => {
- return generationBatchService.getGenerationBatches(topicId, 'video');
- },
- {
- onSuccess: (data) => {
- const nextMap = {
- ...this.#get().generationBatchesMap,
- [topicId!]: data,
- };
-
- if (isEqual(nextMap, this.#get().generationBatchesMap)) return;
-
- this.#set(
- {
- generationBatchesMap: nextMap,
- },
- false,
- n('useFetchGenerationBatches(success)', { topicId }),
- );
- },
- },
- );
}
export type GenerationBatchAction = Pick<
diff --git a/src/store/video/slices/generationBatch/initialState.ts b/src/store/video/slices/generationBatch/initialState.ts
index 354657fb1c6..3bdaf954fdc 100644
--- a/src/store/video/slices/generationBatch/initialState.ts
+++ b/src/store/video/slices/generationBatch/initialState.ts
@@ -1,9 +1,18 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { type GenerationBatch } from '@/types/generation';
export interface GenerationBatchState {
+ /**
+ * 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/video/slices/generationBatch/projection.ts b/src/store/video/slices/generationBatch/projection.ts
new file mode 100644
index 00000000000..67d1d8c9746
--- /dev/null
+++ b/src/store/video/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: 'videoGenerationBatches',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/video/slices/generationBatch/replica.test.ts b/src/store/video/slices/generationBatch/replica.test.ts
new file mode 100644
index 00000000000..b064cfa6134
--- /dev/null
+++ b/src/store/video/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 { useVideoStore } from '@/store/video';
+import { generationBatchSelectors } from '@/store/video/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(() => useVideoStore((s) => s.useFetchGenerationBatches)(TOPIC), { wrapper });
+
+describe('video 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(`video-user-${randomUUID()}:personal`);
+ useVideoStore.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(useVideoStore.getState()),
+ ).toBe(true),
+ );
+ expect(useVideoStore.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(useVideoStore.getState().generationBatchesMap[TOPIC]).toHaveLength(1),
+ );
+ const before = useVideoStore.getState().generationBatchesMap[TOPIC];
+
+ getBatches.mockResolvedValue([batch('gb_1')]);
+ await act(() => useVideoStore.getState().refreshGenerationBatches());
+
+ expect(useVideoStore.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(useVideoStore.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(useVideoStore.getState().generationBatchesMap).toEqual({});
+ expect(generationBatchSelectors.isCurrentGenerationTopicLoaded(useVideoStore.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/video/slices/generationBatch/selectors.ts b/src/store/video/slices/generationBatch/selectors.ts
index a01fa52b7a1..a355ead4e7f 100644
--- a/src/store/video/slices/generationBatch/selectors.ts
+++ b/src/store/video/slices/generationBatch/selectors.ts
@@ -23,6 +23,8 @@ const getGenerationBatchByBatchId = (batchId: string) => (s: VideoStoreState) =>
const isCurrentGenerationTopicLoaded = (s: VideoStoreState): 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/video/slices/generationTopic/action.test.ts b/src/store/video/slices/generationTopic/action.test.ts
index 0dcafef94e8..3d37adb9e05 100644
--- a/src/store/video/slices/generationTopic/action.test.ts
+++ b/src/store/video/slices/generationTopic/action.test.ts
@@ -1,16 +1,18 @@
import { act, renderHook } from '@testing-library/react';
import { 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 { generationTopicService } from '@/services/generationTopic';
-import { useVideoStore } from '@/store/video';
-
-vi.mock('@/libs/swr', async () => {
- const actual = await vi.importActual('@/libs/swr');
- return {
- ...actual,
- mutate: vi.fn(),
- };
+import { useVideoStore, type VideoStore } from '@/store/video';
+import { type ImageGenerationTopic } from '@/types/generation';
+
+// 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/generationTopic', () => ({
@@ -29,29 +31,23 @@ 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<VideoStore> = {}) => {
+ useVideoStore.setState({
+ generationTopics: topics,
+ generationTopicsReplica: createReplicaState(),
+ isGenerationTopicsInit: true,
+ ...extra,
+ });
+};
beforeEach(() => {
vi.clearAllMocks();
useVideoStore.setState({
activeGenerationTopicId: null,
generationTopics: [],
+ generationTopicsReplica: createReplicaState(),
+ isGenerationTopicsInit: false,
loadingGenerationTopicIds: [],
newGenerationTopicVisibility: 'private',
});
@@ -121,7 +117,8 @@ describe('VideoGenerationTopicAction', () => {
});
expect(generationTopicService.createTopic).toHaveBeenCalledWith('video', 'private');
- expect(mutate).toHaveBeenCalledWith(['video:generationTopics']);
+ // The replica driver revalidates through the scoped mutate with a matcher.
+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));
});
it('should create video topic with selected public visibility', async () => {
@@ -142,4 +139,116 @@ describe('VideoGenerationTopicAction', () => {
expect(generationTopicService.createTopic).toHaveBeenCalledWith('video', 'public');
});
});
+
+ describe('internal_dispatchGenerationTopic', () => {
+ it('should write the reduced topics into the replica view', () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ act(() => {
+ seedTopics([{ id: 'gt_topic_1', title: 'Topic 1' } as ImageGenerationTopic]);
+ });
+
+ act(() => {
+ result.current.internal_dispatchGenerationTopic({
+ type: 'addTopic',
+ value: { id: 'gt_topic_2', title: 'Topic 2' },
+ });
+ });
+
+ expect(result.current.generationTopics).toHaveLength(2);
+ expect(result.current.generationTopics.find((t) => t.id === 'gt_topic_2')).toBeDefined();
+ });
+
+ it('should update a topic in place', () => {
+ const { result } = renderHook(() => useVideoStore());
+ const existingDate = new Date('2024-01-01T00:00:00.000Z');
+
+ act(() => {
+ seedTopics([
+ {
+ id: 'gt_topic_1',
+ title: 'Topic 1',
+ createdAt: existingDate,
+ updatedAt: existingDate,
+ } as ImageGenerationTopic,
+ ]);
+ });
+
+ act(() => {
+ result.current.internal_dispatchGenerationTopic({
+ type: 'updateTopic',
+ id: 'gt_topic_1',
+ value: { title: 'Renamed' },
+ });
+ });
+
+ expect(result.current.generationTopics[0].title).toBe('Renamed');
+ expect(result.current.generationTopics[0].updatedAt.getTime()).toBeGreaterThan(
+ existingDate.getTime(),
+ );
+ });
+ });
+
+ describe('refreshGenerationTopics', () => {
+ it('should revalidate the topic list replica', async () => {
+ const { result } = renderHook(() => useVideoStore());
+
+ await act(async () => {
+ await result.current.refreshGenerationTopics();
+ });
+
+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));
+ });
+ });
+
+ describe('internal_updateGenerationTopicCover', () => {
+ it('should write the optimistic cover into the replica view and confirm it', async () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+ const coverUrl = 'https://example.com/cover.jpg';
+
+ act(() => {
+ seedTopics([{ id: topicId, title: 'Topic 1', coverUrl: '' } as ImageGenerationTopic]);
+ });
+
+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationTopic');
+
+ await act(async () => {
+ await result.current.updateGenerationTopicCover(topicId, coverUrl);
+ });
+
+ expect(dispatchSpy).toHaveBeenCalledWith({
+ id: topicId,
+ type: 'updateTopic',
+ 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);
+ });
+ });
+
+ describe('internal_updateGenerationTopicTitleInSummary', () => {
+ it('should write the streamed title into the replica view', () => {
+ const { result } = renderHook(() => useVideoStore());
+ const topicId = 'gt_topic_1';
+
+ act(() => {
+ seedTopics([{ id: topicId, title: 'Original' } as ImageGenerationTopic]);
+ });
+
+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchGenerationTopic');
+
+ act(() => {
+ result.current.internal_updateGenerationTopicTitleInSummary(topicId, 'Summary Title');
+ });
+
+ expect(dispatchSpy).toHaveBeenCalledWith({
+ id: topicId,
+ type: 'updateTopic',
+ value: { title: 'Summary Title' },
+ });
+ expect(result.current.generationTopics[0].title).toBe('Summary Title');
+ });
+ });
});
diff --git a/src/store/video/slices/generationTopic/action.ts b/src/store/video/slices/generationTopic/action.ts
index 19b8a1f6730..d8f472e4b1d 100644
--- a/src/store/video/slices/generationTopic/action.ts
+++ b/src/store/video/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 { videoKeys } 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,11 +16,48 @@ import { setNamespace } from '@/utils/storeDebug';
import type { VideoStore } from '../../store';
import type { GenerationTopicVisibility } from './initialState';
+import { GENERATION_TOPICS_KEY, generationTopicsResource } from './projection';
import { type GenerationTopicDispatch, generationTopicReducer } from './reducer';
import { generationTopicSelectors } from './selectors';
const n = setNamespace('videoGenerationTopic');
+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<VideoStore, 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<VideoStore>;
export const createGenerationTopicSlice = (set: Setter, get: () => VideoStore, _api?: unknown) =>
@@ -31,11 +66,22 @@ export const createGenerationTopicSlice = (set: Setter, get: () => VideoStore, _
export class GenerationTopicActionImpl {
readonly #get: () => VideoStore;
readonly #set: Setter;
+ readonly #topics;
constructor(set: Setter, get: () => VideoStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#topics = createReplicaSlice(generationTopicsResource, {
+ actionPrefix: n('generationTopics'),
+ fetcher: () => generationTopicService.getAllGenerationTopics('video'),
+ 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> => {
@@ -56,13 +102,11 @@ export class GenerationTopicActionImpl {
const tmpId = Date.now().toString();
const { newGenerationTopicVisibility } = this.#get();
- this.#get().internal_dispatchGenerationTopic(
- {
- type: 'addTopic',
- value: { id: tmpId, title: '', visibility: newGenerationTopicVisibility },
- },
- 'internal_createGenerationTopic',
- );
+ // 1. Optimistic update - add temporary topic
+ this.#get().internal_dispatchGenerationTopic({
+ type: 'addTopic',
+ value: { id: tmpId, title: '', visibility: newGenerationTopicVisibility },
+ });
this.#get().internal_updateGenerationTopicLoading(tmpId, true);
@@ -84,15 +128,16 @@ export class GenerationTopicActionImpl {
);
};
- internal_dispatchGenerationTopic = (payload: GenerationTopicDispatch, action?: any): void => {
- const nextTopics = generationTopicReducer(this.#get().generationTopics, payload);
-
- 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 },
);
};
@@ -121,24 +166,21 @@ export class GenerationTopicActionImpl {
topicId: string,
coverUrl: string,
): Promise<void> => {
- const {
- internal_dispatchGenerationTopic,
- internal_updateGenerationTopicLoading,
- refreshGenerationTopics,
- } = this.#get();
+ const { internal_dispatchGenerationTopic, internal_updateGenerationTopicLoading } = this.#get();
- internal_dispatchGenerationTopic(
- { id: topicId, type: 'updateTopic', value: { coverUrl } },
- 'internal_updateGenerationTopicCover/optimistic',
- );
+ // 1. Optimistic update - immediately show the new cover URL in UI
+ internal_dispatchGenerationTopic({ type: 'updateTopic', id: topicId, value: { coverUrl } });
+ // 2. Set loading state
internal_updateGenerationTopicLoading(topicId, true);
try {
await generationTopicService.updateTopicCover(topicId, coverUrl);
- await refreshGenerationTopics();
+ // 3. Refresh data to get the final processed cover URL from S3
+ await this.#get().refreshGenerationTopics();
} finally {
+ // 4. Clear loading state
internal_updateGenerationTopicLoading(topicId, false);
}
};
@@ -158,10 +200,7 @@ export class GenerationTopicActionImpl {
};
internal_updateGenerationTopicTitleInSummary = (id: string, title: string): void => {
- this.#get().internal_dispatchGenerationTopic(
- { id, type: 'updateTopic', value: { title } },
- 'updateGenerationTopicTitleInSummary',
- );
+ this.#get().internal_dispatchGenerationTopic({ type: 'updateTopic', id, value: { title } });
};
openNewGenerationTopic = (): void => {
@@ -176,8 +215,28 @@ export class GenerationTopicActionImpl {
);
};
+ /**
+ * 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(videoKeys.generationTopics());
+ await this.#topics.revalidate();
};
removeGenerationTopic = async (id: string): Promise<void> => {
@@ -295,18 +354,6 @@ export class GenerationTopicActionImpl {
const { internal_updateGenerationTopicCover } = this.#get();
await internal_updateGenerationTopicCover(topicId, coverUrl);
};
-
- useFetchGenerationTopics = (enabled: boolean): SWRResponse<ImageGenerationTopic[]> =>
- useClientDataSWR<ImageGenerationTopic[]>(
- enabled ? videoKeys.generationTopics() : null,
- () => generationTopicService.getAllGenerationTopics('video'),
- {
- onSuccess: (data) => {
- if (isEqual(data, this.#get().generationTopics)) return;
- this.#set({ generationTopics: data }, false, n('useFetchGenerationTopics'));
- },
- },
- );
}
export type GenerationTopicAction = Pick<
diff --git a/src/store/video/slices/generationTopic/initialState.ts b/src/store/video/slices/generationTopic/initialState.ts
index 824374d5d07..32e1b50d602 100644
--- a/src/store/video/slices/generationTopic/initialState.ts
+++ b/src/store/video/slices/generationTopic/initialState.ts
@@ -1,10 +1,20 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { type ImageGenerationTopic } from '@/types/generation';
export type GenerationTopicVisibility = NonNullable<ImageGenerationTopic['visibility']>;
export interface GenerationTopicState {
activeGenerationTopicId: string | null;
+ /** 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;
loadingGenerationTopicIds: string[];
newGenerationTopicVisibility: GenerationTopicVisibility;
}
@@ -12,7 +22,9 @@ export interface GenerationTopicState {
export const initialGenerationTopicState: GenerationTopicState = {
activeGenerationTopicId:
typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('topic') : null,
- generationTopics: [],
loadingGenerationTopicIds: [],
+ generationTopics: [],
+ generationTopicsReplica: createReplicaState(),
+ isGenerationTopicsInit: false,
newGenerationTopicVisibility: 'private',
};
diff --git a/src/store/video/slices/generationTopic/projection.ts b/src/store/video/slices/generationTopic/projection.ts
new file mode 100644
index 00000000000..48a7f13f687
--- /dev/null
+++ b/src/store/video/slices/generationTopic/projection.ts
@@ -0,0 +1,27 @@
+import { defineReplica } from '@/libs/replica';
+import type { ImageGenerationTopic } from '@/types/generation';
+
+/**
+ * The video generation topics list is a single entry per cache scope. The
+ * server returns every topic the caller may see (`getAllGenerationTopics('video')`),
+ * 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 = 'video';
+
+/**
+ * Video 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: 'videoGenerationTopics',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/video/slices/generationTopic/replica.test.ts b/src/store/video/slices/generationTopic/replica.test.ts
new file mode 100644
index 00000000000..5fcee0fc952
--- /dev/null
+++ b/src/store/video/slices/generationTopic/replica.test.ts
@@ -0,0 +1,168 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The video generation topic list is a `@lobechat/replica` resource whose view
+ * is the video 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 { useVideoStore } from '@/store/video';
+import { generationTopicSelectors } from '@/store/video/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(),
+ 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(() => useVideoStore((s) => s.useFetchGenerationTopics)(true), { wrapper });
+
+describe('video 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(`video-user-${randomUUID()}:personal`);
+ useVideoStore.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(useVideoStore.getState().isGenerationTopicsInit).toBe(true));
+ expect(generationTopicSelectors.generationTopics(useVideoStore.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(useVideoStore.getState().generationTopics).toHaveLength(1));
+ const before = useVideoStore.getState().generationTopics;
+
+ getAll.mockResolvedValue([topic('t1')]);
+ await act(() => useVideoStore.getState().refreshGenerationTopics());
+
+ expect(useVideoStore.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(useVideoStore.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(useVideoStore.getState().generationTopics).toEqual([]);
+ expect(useVideoStore.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(useVideoStore.getState().isGenerationTopicsInit).toBe(true));
+
+ getAll.mockResolvedValue([topic('t1', { title: 'Fresh' })]);
+ await act(() => useVideoStore.getState().internal_createGenerationTopic());
+
+ await waitFor(() =>
+ expect(generationTopicSelectors.generationTopics(useVideoStore.getState())).toHaveLength(1),
+ );
+ expect(generationTopicSelectors.generationTopics(useVideoStore.getState())[0].title).toBe(
+ 'Fresh',
+ );
+ });
+});