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(notebook): move the topic notebook documents onto @lobechat/replica (#20606)

Arvin Xu1680034654d1
diff --git a/src/hooks/useFetchNotebookDocuments.ts b/src/hooks/useFetchNotebookDocuments.ts
index 9a158fa0a1c..42de20963f0 100644
--- a/src/hooks/useFetchNotebookDocuments.ts
+++ b/src/hooks/useFetchNotebookDocuments.ts
@@ -2,13 +2,22 @@ import { useNotebookStore } from '@/store/notebook';
import { notebookSelectors } from '@/store/notebook/selectors';
/**
- * Fetch notebook documents for the current topic
+ * Fetch notebook documents for the current topic.
+ *
+ * The documents are read from the topic's local-first replica (`notebookMap`),
+ * so a previously visited topic paints at once; the hook only starts the
+ * hydrate + network sync and derives the loading flag.
*/
export const useFetchNotebookDocuments = (topicId?: string) => {
const useFetchDocuments = useNotebookStore((s) => s.useFetchDocuments);
const documents = useNotebookStore((s) => notebookSelectors.getDocumentsByTopicId(topicId)(s));
- const { isLoading } = useFetchDocuments(topicId);
+ const { isHydrated, isValidating } = useFetchDocuments(topicId);
+
+ // Show the spinner only while nothing can be painted yet: before the
+ // persisted row is read, or on an empty topic that is still fetching. A
+ // hydrated topic with rows paints at once instead of flashing the spinner.
+ const isLoading = !!topicId && (!isHydrated || (documents.length === 0 && isValidating));
return {
documents,
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 310702fc08f..a067116f375 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -14,17 +14,13 @@
* Each factory also exposes `.root` (the namespace string) for `mutate`
* matchers that compare `key[0]`.
*
- * Document / page / notebook / agent-document keys are defined in
+ * Document / page / agent-document keys are defined in
* `@/services/document/swrKeys` (already a factory, widely imported) and
* re-exported here so the whole set is reachable from one place.
*/
import { type ConversationContext } from '@lobechat/types';
-import {
- agentDocumentSWRKeys,
- documentSWRKeys,
- notebookSWRKeys,
-} from '@/services/document/swrKeys';
+import { agentDocumentSWRKeys, documentSWRKeys } from '@/services/document/swrKeys';
type KeyFactory<A extends unknown[]> = ((...args: A) => readonly unknown[]) & { root: string };
@@ -1487,7 +1483,6 @@ export const swrKeys = {
message: messageKeys,
messenger: messengerKeys,
scm: scmKeys,
- notebook: notebookSWRKeys,
ollama: ollamaKeys,
onboarding: onboardingKeys,
openInApp: openInAppKeys,
diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.ts
index e7f7c2fbb08..52f4e0e33a6 100644
--- a/src/services/agentDocument.test.ts
+++ b/src/services/agentDocument.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cacheScope } from '@/libs/replica';
import { mutate } from '@/libs/swr';
import { agentDocumentService, resolveAgentDocumentsContext } from './agentDocument';
@@ -64,12 +65,15 @@ describe('AgentDocumentService', () => {
});
expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);
- // `documentsList` now revalidates via a prefix matcher so the full list and
- // the `non-web` variant (and their workspace-scoped keys) refresh together.
- const listMatcher = vi
+ // `documentsList` revalidates via a prefix matcher so the full list and the
+ // `non-web` variant (and their workspace-scoped keys) refresh together. Pick
+ // the agent-documents matcher out of the list: the notebook branch also
+ // pushes a function matcher (its replica sync key) for `topic-1`.
+ const matchers = vi
.mocked(mutate)
.mock.calls.map((call) => call[0])
- .find((key) => typeof key === 'function') as ((key: unknown) => boolean) | undefined;
+ .filter((key): key is (queryKey: unknown) => boolean => typeof key === 'function');
+ const listMatcher = matchers.find((matcher) => matcher(['agent:documentsList', 'agent-1']));
expect(listMatcher).toBeDefined();
expect(listMatcher!(['agent:documentsList', 'agent-1'])).toBe(true);
expect(listMatcher!(['agent:documentsList', 'agent-1', 'non-web'])).toBe(true);
@@ -80,7 +84,14 @@ describe('AgentDocumentService', () => {
expect(mutate).toHaveBeenCalledWith(['page:meta', 'page-doc-1']);
expect(mutate).toHaveBeenCalledWith(['page:detail', 'page-doc-1']);
expect(mutate).toHaveBeenCalledWith(['page:list']);
- expect(mutate).toHaveBeenCalledWith(['notebook:documents', 'topic-1']);
+ // The notebook list is a replica now, so `topicId` refreshes its sync key
+ // instead of the removed `notebook:documents` SWR entry.
+ const scope = cacheScope.get();
+ expect(
+ matchers.some((matcher) =>
+ matcher(['replica:sync', 'notebookDocuments', 1, scope, 'topic-1', 'topic-1']),
+ ),
+ ).toBe(true);
});
it('should revalidate agent documents after updateLoadRule', async () => {
diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.ts
index 40f92ff4ad2..8b6e921fef9 100644
--- a/src/services/document/invalidation.ts
+++ b/src/services/document/invalidation.ts
@@ -1,9 +1,10 @@
import { revalidateReplica } from '@/libs/replica';
import { mutate } from '@/libs/swr';
import { portalKeys } from '@/libs/swr/keys';
+import { notebookDocumentsResource } from '@/store/notebook/projection';
import { agentDocumentSkillsResource } from '@/store/tool/slices/agentDocumentSkills/projection';
-import { agentDocumentSWRKeys, documentSWRKeys, notebookSWRKeys } from './swrKeys';
+import { agentDocumentSWRKeys, documentSWRKeys } from './swrKeys';
export type DocumentMutationCause =
'agent-document' | 'document-service' | 'notebook' | 'page-title';
@@ -45,7 +46,11 @@ export const invalidateDocumentMutation = async (
}
if (topicId) {
- revalidations.push(mutate(notebookSWRKeys.documents(topicId)));
+ // The topic's document list is a replica, so its sync lives outside the
+ // legacy `notebook:documents` SWR entry. Refresh the affected topic only: a
+ // create / update / delete must reach the notebook portal without waiting
+ // for a remount.
+ revalidations.push(revalidateReplica(notebookDocumentsResource, topicId));
}
if (agentId) {
diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.ts
index 18ea650bc88..53cca7f3934 100644
--- a/src/services/document/swrKeys.ts
+++ b/src/services/document/swrKeys.ts
@@ -1,6 +1,4 @@
// Domain-namespaced SWR key roots. See the central registry in `@/libs/swr/keys`.
-export const SWR_USE_FETCH_NOTEBOOK_DOCUMENTS = 'notebook:documents';
-
export const agentDocumentSWRKeys = {
documents: (agentId: string) => ['agent:documents', agentId] as const,
/**
@@ -22,7 +20,3 @@ export const documentSWRKeys = {
pageDocuments: () => ['page:list'] as const,
pageMeta: (documentId: string) => ['page:meta', documentId] as const,
};
-
-export const notebookSWRKeys = {
- documents: (topicId: string) => [SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId] as const,
-};
diff --git a/src/store/notebook/action.ts b/src/store/notebook/action.ts
index 53bd2d7a246..241c121af67 100644
--- a/src/store/notebook/action.ts
+++ b/src/store/notebook/action.ts
@@ -2,23 +2,19 @@ import { type DocumentType } from '@lobechat/builtin-tool-notebook';
import type { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
import { type DocumentItem } from '@lobechat/database/schemas';
import { type NotebookDocument } from '@lobechat/types';
-import isEqual from 'fast-deep-equal';
-import { type SWRResponse } from 'swr';
-import { mutate, useClientDataSWR } from '@/libs/swr';
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { invalidateDocumentMutation } from '@/services/document/invalidation';
-import { notebookSWRKeys } from '@/services/document/swrKeys';
import { notebookService } from '@/services/notebook';
import { useChatStore } from '@/store/chat';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
+import { notebookDocumentsResource } from './projection';
import { type NotebookStore } from './store';
const n = setNamespace('notebook');
-export { SWR_USE_FETCH_NOTEBOOK_DOCUMENTS } from '@/services/document/swrKeys';
-
type ExtendedDocumentType = DocumentType | typeof AGENT_PLAN_FILE_TYPE;
interface CreateDocumentParams {
@@ -43,13 +39,20 @@ export const createNotebookAction = (set: Setter, get: () => NotebookStore, _api
new NotebookActionImpl(set, get, _api);
export class NotebookActionImpl {
- readonly #get: () => NotebookStore;
- readonly #set: Setter;
+ /** One topic's documents, persisted per `topicId` (`notebookMap`). */
+ readonly #documents;
constructor(set: Setter, get: () => NotebookStore, _api?: unknown) {
void _api;
- this.#set = set;
- this.#get = get;
+ this.#documents = createReplicaSlice(notebookDocumentsResource, {
+ actionPrefix: n('notebookDocuments'),
+ fetcher: (topicId) =>
+ notebookService.listDocuments({ topicId }).then((result) => result.data),
+ get,
+ set,
+ stateKey: 'notebookDocumentsReplica',
+ view: recordLens<NotebookStore, NotebookDocument[]>('notebookMap'),
+ });
}
createDocument = async (params: CreateDocumentParams): Promise<DocumentItem> => {
@@ -77,8 +80,13 @@ export class NotebookActionImpl {
await invalidateDocumentMutation({ cause: 'notebook', documentId: id, topicId });
};
+ /**
+ * Force a fresh sync of one topic's documents (or every loaded topic). The
+ * list is read through `notebookSelectors`; this only schedules the network
+ * round-trip, so the caller never touches the replica directly.
+ */
refreshDocuments = async (topicId: string): Promise<void> => {
- await mutate(notebookSWRKeys.documents(topicId));
+ await this.#documents.revalidate(topicId);
};
updateDocument = async (
@@ -92,36 +100,13 @@ export class NotebookActionImpl {
return document;
};
- useFetchDocuments = (topicId: string | undefined): SWRResponse<NotebookDocument[]> => {
- return useClientDataSWR<NotebookDocument[]>(
- topicId ? notebookSWRKeys.documents(topicId) : null,
- async () => {
- if (!topicId) return [];
-
- const result = await notebookService.listDocuments({ topicId });
-
- return result.data;
- },
- {
- onSuccess: (documents) => {
- if (!topicId) return;
-
- const currentDocuments = this.#get().notebookMap[topicId];
-
- // Skip update if data is the same
- if (currentDocuments && isEqual(documents, currentDocuments)) return;
-
- this.#set(
- {
- notebookMap: { ...this.#get().notebookMap, [topicId]: documents },
- },
- false,
- n('useFetchDocuments(onSuccess)', { topicId }),
- );
- },
- },
- );
- };
+ /**
+ * Fetch orchestration for one topic: the persisted copy paints the first
+ * frame and the network only confirms. Read the documents with
+ * `notebookSelectors`, not from the return value.
+ */
+ useFetchDocuments = (topicId: string | undefined): ReplicaSyncResult =>
+ this.#documents.useSync(topicId ?? null, { revalidateOnFocus: false });
}
export type NotebookAction = Pick<NotebookActionImpl, keyof NotebookActionImpl>;
diff --git a/src/store/notebook/index.ts b/src/store/notebook/index.ts
index d698a5a453c..8a3f56fa962 100644
--- a/src/store/notebook/index.ts
+++ b/src/store/notebook/index.ts
@@ -1,5 +1,6 @@
export type { NotebookAction } from './action';
export type { NotebookState } from './initialState';
+export { type NotebookDocument, notebookDocumentsResource } from './projection';
export { notebookSelectors } from './selectors';
export type { NotebookStore } from './store';
export { getNotebookStoreState, useNotebookStore } from './store';
diff --git a/src/store/notebook/initialState.ts b/src/store/notebook/initialState.ts
index 84a479e1b15..b7c972f95ea 100644
--- a/src/store/notebook/initialState.ts
+++ b/src/store/notebook/initialState.ts
@@ -1,12 +1,20 @@
import { type NotebookDocument } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
export interface NotebookState {
+ /** Replica bookkeeping for `notebookMap`. */
+ notebookDocumentsReplica: ReplicaState<NotebookDocument[]>;
/**
- * Map of topicId -> notebook documents list
+ * Map of topicId -> notebook documents list.
+ *
+ * This is the view of `notebookDocumentsResource`; it is written only by the
+ * replica slice in `action.ts` and read through `notebookSelectors`.
*/
notebookMap: Record<string, NotebookDocument[]>;
}
export const initialNotebookState: NotebookState = {
notebookMap: {},
+ notebookDocumentsReplica: createReplicaState(),
};
diff --git a/src/store/notebook/notebookInvalidation.test.ts b/src/store/notebook/notebookInvalidation.test.ts
new file mode 100644
index 00000000000..dfb6de5790e
--- /dev/null
+++ b/src/store/notebook/notebookInvalidation.test.ts
@@ -0,0 +1,55 @@
+/**
+ * Guards the migration's cross-layer wiring: a notebook document write must
+ * revalidate the topic's documents, which now live in a replica (`replica:sync`
+ * keys) instead of the `notebook:documents` SWR entry.
+ */
+import { describe, expect, it, vi } from 'vitest';
+
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
+
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn() }));
+
+const functionKeys = async () => {
+ const { mutate } = await import('@/libs/swr');
+ return vi
+ .mocked(mutate)
+ .mock.calls.map(([key]) => key)
+ .filter((key): key is (queryKey: unknown) => boolean => typeof key === 'function');
+};
+
+describe('notebook documents invalidation wiring', () => {
+ it('revalidates the notebook documents replica for the mutated topic only', async () => {
+ const { cacheScope } = await import('@/libs/replica');
+ const scope = cacheScope.get();
+
+ await invalidateDocumentMutation({
+ cause: 'notebook',
+ documentId: 'doc-1',
+ topicId: 'topic-1',
+ });
+
+ const matchers = await functionKeys();
+ const matches = (key: unknown) => matchers.some((matcher) => matcher(key));
+
+ expect(matches(['replica:sync', 'notebookDocuments', 1, scope, 'topic-1', 'topic-1'])).toBe(
+ true,
+ );
+ expect(matches(['replica:sync', 'notebookDocuments', 1, scope, 'topic-2', 'topic-2'])).toBe(
+ false,
+ );
+ });
+
+ it('does not touch the notebook documents when no topic is involved', async () => {
+ await invalidateDocumentMutation({ documentId: 'page-doc-1' });
+
+ const matchers = await functionKeys();
+ const { cacheScope } = await import('@/libs/replica');
+ const scope = cacheScope.get();
+
+ expect(
+ matchers.some((matcher) =>
+ matcher(['replica:sync', 'notebookDocuments', 1, scope, 'topic-1', 'topic-1']),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/src/store/notebook/projection.ts b/src/store/notebook/projection.ts
new file mode 100644
index 00000000000..b42203771c9
--- /dev/null
+++ b/src/store/notebook/projection.ts
@@ -0,0 +1,22 @@
+import { type NotebookDocument } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+
+export type { NotebookDocument };
+
+/**
+ * One topic's notebook documents, keyed by `topicId` (`notebookMap[topicId]`).
+ *
+ * Read-mostly: the notebook tool executor and the portal's delete are the
+ * writers, and both revalidate this entry through `invalidateDocumentMutation`
+ * (see `@/services/document/invalidation`). The persisted copy therefore paints
+ * the topic's first frame and the network only confirms. IndexedDB, not
+ * localStorage, because the list is only read once a topic's notebook or
+ * document portal is open.
+ */
+export const notebookDocumentsResource = defineReplica<string, NotebookDocument[]>({
+ key: (topicId) => topicId,
+ name: 'notebookDocuments',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/notebook/store.test.ts b/src/store/notebook/store.test.ts
new file mode 100644
index 00000000000..4d0230869ef
--- /dev/null
+++ b/src/store/notebook/store.test.ts
@@ -0,0 +1,190 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * A topic's notebook documents are a replica: they paint from the persisted
+ * copy on the first frame and the network only confirms, keyed per topic so
+ * switching topics never leaks the previous topic's rows.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, 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 { notebookService } from '@/services/notebook';
+
+import { initialNotebookState } from './initialState';
+import { type NotebookDocument, notebookDocumentsResource } from './projection';
+import { getNotebookStoreState, useNotebookStore } from './store';
+
+vi.mock('@/services/notebook', () => ({
+ notebookService: {
+ createDocument: vi.fn(),
+ deleteDocument: vi.fn(),
+ getDocument: vi.fn(),
+ listDocuments: vi.fn(),
+ updateDocument: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => ({ closeDocument: vi.fn(), portalDocumentId: undefined }) },
+}));
+
+vi.mock('@/services/document/invalidation', () => ({
+ invalidateDocumentMutation: vi.fn(async () => undefined),
+}));
+
+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 doc = (id: string): NotebookDocument =>
+ ({
+ associatedAt: new Date(0),
+ content: null,
+ createdAt: new Date(0),
+ description: null,
+ fileType: 'markdown',
+ id,
+ metadata: {},
+ title: id,
+ totalCharCount: 0,
+ totalLineCount: 0,
+ updatedAt: new Date(0),
+ }) as unknown as NotebookDocument;
+
+const storageKeyFor = (topicId: string) => notebookDocumentsResource.storageKey(topicId);
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+describe('notebook store 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(() => {
+ useScope(`notebook-user-${randomUUID()}:personal`);
+ act(() => useNotebookStore.setState(initialNotebookState));
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ ['topic-1', 'topic-2'].map((topicId) =>
+ notebookDocumentsResource.storage!.remove({
+ queryKey: storageKeyFor(topicId),
+ scope: value,
+ }),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted documents of a topic before the network answers', async () => {
+ await notebookDocumentsResource.storage!.set(
+ { queryKey: storageKeyFor('topic-1'), scope },
+ { data: [doc('cached')], updatedAt: 1 },
+ );
+ vi.mocked(notebookService.listDocuments).mockImplementation(pending as any);
+
+ const sync = renderHook(() => useNotebookStore((s) => s.useFetchDocuments)('topic-1'), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(getNotebookStoreState().notebookMap['topic-1']?.map((d) => d.id)).toEqual(['cached']),
+ );
+ expect(sync.result.current.isHydrated).toBe(true);
+ expect(sync.result.current.isValidating).toBe(true);
+ });
+
+ it('replaces the topic list with the server response and persists it', async () => {
+ vi.mocked(notebookService.listDocuments).mockResolvedValue({
+ data: [doc('server')],
+ total: 1,
+ } as any);
+
+ renderHook(() => useNotebookStore((s) => s.useFetchDocuments)('topic-1'), { wrapper });
+
+ await waitFor(() =>
+ expect(getNotebookStoreState().notebookMap['topic-1']?.[0]?.id).toBe('server'),
+ );
+ await waitFor(async () =>
+ expect(
+ (
+ await notebookDocumentsResource.storage!.get({
+ queryKey: storageKeyFor('topic-1'),
+ scope,
+ })
+ )?.data,
+ ).toEqual([doc('server')]),
+ );
+ });
+
+ it('keeps each topic in its own entry', async () => {
+ vi.mocked(notebookService.listDocuments).mockImplementation(
+ async ({ topicId }) => ({ data: [doc(`${topicId}-doc`)], total: 1 }) as any,
+ );
+
+ renderHook(
+ () => {
+ useNotebookStore((s) => s.useFetchDocuments)('topic-1');
+ useNotebookStore((s) => s.useFetchDocuments)('topic-2');
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => {
+ expect(getNotebookStoreState().notebookMap['topic-1']?.[0]?.id).toBe('topic-1-doc');
+ expect(getNotebookStoreState().notebookMap['topic-2']?.[0]?.id).toBe('topic-2-doc');
+ });
+ });
+
+ it('refreshDocuments revalidates the network for that topic', async () => {
+ vi.mocked(notebookService.listDocuments).mockResolvedValue({
+ data: [doc('first')],
+ total: 1,
+ } as any);
+ renderHook(() => useNotebookStore((s) => s.useFetchDocuments)('topic-1'), { wrapper });
+ await waitFor(() =>
+ expect(getNotebookStoreState().notebookMap['topic-1']?.[0]?.id).toBe('first'),
+ );
+
+ vi.mocked(notebookService.listDocuments).mockResolvedValue({
+ data: [doc('second')],
+ total: 1,
+ } as any);
+ await act(async () => {
+ await getNotebookStoreState().refreshDocuments('topic-1');
+ });
+
+ await waitFor(() =>
+ expect(getNotebookStoreState().notebookMap['topic-1']?.[0]?.id).toBe('second'),
+ );
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.ts b/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.ts
index 1abae0f78fb..9e5e14261d6 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.ts
@@ -1,11 +1,14 @@
+/**
+ * Guards the migration's cross-layer wiring: syncing todos into the plan
+ * document's metadata must revalidate the topic's notebook documents, which now
+ * live in a replica (`replica:sync` keys) instead of the `notebook:documents`
+ * SWR entry.
+ */
import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client/executor';
import type { BuiltinToolContext } from '@lobechat/types';
-import { act, renderHook, waitFor } from '@testing-library/react';
-import useSWR from 'swr';
+import { act } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import { notebookSWRKeys } from '@/services/document/swrKeys';
-
const { row, updateDocument } = vi.hoisted(() => {
const row = { current: { metadata: {} as Record<string, any> } };
return {
@@ -16,25 +19,31 @@ const { row, updateDocument } = vi.hoisted(() => {
};
});
-vi.mock('@/libs/swr', async () => ({ mutate: (await import('swr')).mutate }));
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn() }));
vi.mock('@/services/notebook', () => ({
notebookService: {
- listDocuments: vi.fn().mockResolvedValue({
- data: [{ createdAt: new Date(), id: 'plan-1', metadata: {}, updatedAt: new Date() }],
- }),
+ listDocuments: vi.fn(async () => ({
+ data: [
+ {
+ createdAt: new Date(),
+ id: 'plan-1',
+ metadata: row.current.metadata,
+ updatedAt: new Date(),
+ },
+ ],
+ })),
updateDocument,
},
}));
vi.mock('@/store/notebook', () => ({ useNotebookStore: { getState: () => ({}) } }));
describe('lobeAgentExecutor plan todos sync', () => {
- it('revalidates the plan document after syncing todos into its metadata', async () => {
+ it('revalidates the notebook documents replica after syncing todos into its metadata', async () => {
+ const { mutate } = await import('@/libs/swr');
+ const { cacheScope } = await import('@/libs/replica');
+
const ctx = { currentTodos: [], topicId: 'topic-1' } as unknown as BuiltinToolContext;
- const { result: cache } = renderHook(() =>
- useSWR(notebookSWRKeys.documents('topic-1'), async () => row.current),
- );
- await waitFor(() => expect(cache.current.data).toBeDefined());
let result: Awaited<ReturnType<typeof lobeAgentExecutor.createTodos>>;
await act(async () => {
result = await lobeAgentExecutor.createTodos({ adds: ['ship it'] }, ctx);
@@ -47,8 +56,17 @@ describe('lobeAgentExecutor plan todos sync', () => {
metadata: expect.objectContaining({ todos: expect.anything() }),
}),
);
- expect(cache.current.data?.metadata.todos.items).toEqual([
- expect.objectContaining({ text: 'ship it' }),
- ]);
+
+ const matchers = vi
+ .mocked(mutate)
+ .mock.calls.map(([key]) => key)
+ .filter((key): key is (queryKey: unknown) => boolean => typeof key === 'function');
+ const scope = cacheScope.get();
+
+ expect(
+ matchers.some((match) =>
+ match(['replica:sync', 'notebookDocuments', 1, scope, 'topic-1', 'topic-1']),
+ ),
+ ).toBe(true);
});
});