🤯 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
⚡️ perf(agent-document): paint agent document lists and the reader from a replica (#20869)
Arvin Xu02937c881fb3
diff --git a/apps/workbench/app/components/agentDocReader.client.tsx b/apps/workbench/app/components/agentDocReader.client.tsxindex e8106d98490..d28eede0195 100644--- a/apps/workbench/app/components/agentDocReader.client.tsx+++ b/apps/workbench/app/components/agentDocReader.client.tsx@@ -3,6 +3,12 @@ import { useParams } from 'react-router';import AgentDocumentReader from '@/features/AgentDocumentReader';import { getIdFromIdentifier } from '@/utils/identifier';+import { enableWorkbenchIdentity } from '../../src/shell/workbenchReplicaScope';++// A private route: the reader paints its last-read body from disk while the+// session check confirms who is signed in.+void enableWorkbenchIdentity();+export default function AgentDocReader() {const { aid = '', docId = '' } = useParams<{ aid: string; docId: string }>();const agentId = getIdFromIdentifier(aid, 'agt');diff --git a/apps/workbench/app/entry.client.tsx b/apps/workbench/app/entry.client.tsxindex 87b7ced0201..e2c8867708e 100644--- a/apps/workbench/app/entry.client.tsx+++ b/apps/workbench/app/entry.client.tsx@@ -2,13 +2,15 @@ import { startTransition, StrictMode } from 'react';import { hydrateRoot } from 'react-dom/client';import { HydratedRouter } from 'react-router/dom';-import { setReplicaPersistedHydration } from '@/libs/replica';+import { setReplicaScopeSource } from '@/libs/replica';-// The Workbench runtime never mounts the user store, so a replica's cache scope-// would stay the last-known user's partition — hydrating it would paint a-// previous (possibly server-invalidated) session's private rows. Reads here are-// network-only; authorization is whatever the server answers.-setReplicaPersistedHydration(false);+import { workbenchReplicaScope } from '../src/shell/workbenchReplicaScope';++// The Workbench runtime never mounts the user store, so the main SPA's scope+// would stay the last-known user's partition with nothing to verify it. Its own+// source keeps public surfaces network-only and lets a private route opt into+// hydrate-then-verify by running the session check (`enableWorkbenchIdentity`).+setReplicaScopeSource(workbenchReplicaScope);// RR suffixes dynamically-shared route CSS hrefs with `#`, so the vite preload// helper re-requests them with `crossorigin` — against our cross-origin CDN thediff --git a/apps/workbench/src/entry.tsx b/apps/workbench/src/entry.tsxindex abee04b3d90..16c0fc8ae14 100644--- a/apps/workbench/src/entry.tsx+++ b/apps/workbench/src/entry.tsx@@ -4,16 +4,17 @@ import { RouterProvider } from 'react-router/dom';import BootErrorBoundary from '@/components/BootErrorBoundary';import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';-import { setReplicaPersistedHydration } from '@/libs/replica';+import { setReplicaScopeSource } from '@/libs/replica';import { createSPABrowserRouter, createSPARoot } from '@/spa/runtime';import { workbenchRoutes } from './router';+import { workbenchReplicaScope } from './shell/workbenchReplicaScope';-// The Workbench runtime never mounts the user store, so a replica's cache scope-// would stay the last-known user's partition — hydrating it would paint a-// previous (possibly server-invalidated) session's private rows. Reads here are-// network-only; authorization is whatever the server answers.-setReplicaPersistedHydration(false);+// The Workbench runtime never mounts the user store, so the main SPA's scope+// would stay the last-known user's partition with nothing to verify it. Its own+// source keeps public surfaces network-only and lets a private route opt into+// hydrate-then-verify by running the session check (`enableWorkbenchIdentity`).+setReplicaScopeSource(workbenchReplicaScope);const router = createSPABrowserRouter(workbenchRoutes);diff --git a/apps/workbench/src/router.tsx b/apps/workbench/src/router.tsxindex b35f91c7736..8911b12f8d2 100644--- a/apps/workbench/src/router.tsx+++ b/apps/workbench/src/router.tsx@@ -80,6 +80,12 @@ export const workbenchRoutes: RouteObject[] = [children: [{element: lazyElement(() => import('./routes/agent/docs/[docId]')),+ // Seed the persisted reader body before the reader paints. Resolved on+ // first use, so the agent document store stays out of the entry chunk.+ loader: (args) =>+ import('./routes/agent/docs/[docId]/readerLoader').then((module) =>+ module.agentDocumentReaderLoader(args),+ ),path: 'agent/:aid/docs/:docId',},{diff --git a/apps/workbench/src/routes/agent/docs/[docId]/index.tsx b/apps/workbench/src/routes/agent/docs/[docId]/index.tsxindex 05df7945d40..7b2d81ed284 100644--- a/apps/workbench/src/routes/agent/docs/[docId]/index.tsx+++ b/apps/workbench/src/routes/agent/docs/[docId]/index.tsx@@ -5,6 +5,12 @@ import { useParams } from 'react-router';import AgentDocumentReader from '@/features/AgentDocumentReader';import { getIdFromIdentifier } from '@/utils/identifier';+import { enableWorkbenchIdentity } from '../../../../shell/workbenchReplicaScope';++// A private route: the reader paints its last-read body from disk while the+// session check confirms who is signed in.+void enableWorkbenchIdentity();+const AgentDocumentReaderRoute = () => {const { aid = '', docId = '' } = useParams<{ aid: string; docId: string }>();const agentId = getIdFromIdentifier(aid, 'agt');diff --git a/apps/workbench/src/routes/agent/docs/[docId]/readerLoader.ts b/apps/workbench/src/routes/agent/docs/[docId]/readerLoader.tsnew file mode 100644index 00000000000..cbcd0bff112--- /dev/null+++ b/apps/workbench/src/routes/agent/docs/[docId]/readerLoader.ts@@ -0,0 +1,30 @@+import type { LoaderFunctionArgs } from 'react-router';++import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { agentDocumentActions } from '@/store/agentDocument';+import { getIdFromIdentifier } from '@/utils/identifier';++import { enableWorkbenchIdentity } from '../../../../shell/workbenchReplicaScope';++/**+ * Route loader for the Workbench agent document reader.+ *+ * Route loaders run before React commits the route: the only point where the+ * persisted reader body (an async IndexedDB read) can land before the reader+ * paints its content spinner. The route is private, so it opts into the+ * hydrate-then-verify partition first; otherwise the read is refused.+ */+export const agentDocumentReaderLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {+ void enableWorkbenchIdentity();+ if (!params.aid || !params.docId) return null;++ const agentId = getIdFromIdentifier(params.aid, 'agt');+ const documentId = getIdFromIdentifier(params.docId, 'docs');++ await settleWithin(+ agentDocumentActions.preHydrateReaderDocument({ agentId, documentId }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/apps/workbench/src/shell/workbenchReplicaScope.test.ts b/apps/workbench/src/shell/workbenchReplicaScope.test.tsnew file mode 100644index 00000000000..6ab2d320851--- /dev/null+++ b/apps/workbench/src/shell/workbenchReplicaScope.test.ts@@ -0,0 +1,210 @@+/**+ * @vitest-environment happy-dom+ *+ * Workbench never mounts the user store. Its replica scope keeps public+ * surfaces network-only, and lets the agent document reader paint its last-read+ * body on a cold start while its own session check confirms the account.+ */+import { randomUUID } from 'node:crypto';++import { cleanup, renderHook, waitFor } from '@testing-library/react';+import { createElement, type PropsWithChildren, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope, setReplicaScopeSource } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentDocumentService } from '@/services/agentDocument';+import {+ agentDocumentActions,+ agentDocumentSelectors,+ useAgentDocumentStore,+} from '@/store/agentDocument';+import { initialState } from '@/store/agentDocument/initialState';+import {+ type AgentDocumentReaderParams,+ agentDocumentReaderResource,+} from '@/store/agentDocument/projection';++import { workbenchRoutes } from '../router';+import { agentDocumentReaderLoader } from '../routes/agent/docs/[docId]/readerLoader';+import {+ enableWorkbenchIdentity,+ resetWorkbenchReplicaScope,+ workbenchReplicaScope,+} from './workbenchReplicaScope';++const ACTIVE_SCOPE_KEY = 'lobehub:active-scope';+const READER: AgentDocumentReaderParams = { agentId: 'agt_1', documentId: 'docs_1' };+const READER_KEY = agentDocumentReaderResource.storageKey(READER);++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 pending = () => new Promise<never>(() => {});+const reader = () =>+ agentDocumentSelectors.getReaderDocument(READER)(useAgentDocumentStore.getState());+const renderReader = () =>+ renderHook(() => agentDocumentActions.useFetchReaderDocument(READER), { wrapper });++const sessionResponse = (body: unknown, status = 200) =>+ ({ json: async () => body, ok: status >= 200 && status < 300, status }) as Response;++describe('workbench replica scope', () => {+ let userId = '';+ const touched = new Set<string>();++ const persistReaderBody = async (scope: string, content: string) => {+ touched.add(scope);+ await agentDocumentReaderResource.storage!.set(+ { queryKey: READER_KEY, scope },+ { data: { document: { content, filename: 'a.md', title: 'A' } }, updatedAt: 1 },+ );+ };+ const storedReader = async (scope: string) =>+ (await agentDocumentReaderResource.storage!.get({ queryKey: READER_KEY, scope }))?.data;++ beforeEach(() => {+ userId = `wb-user-${randomUUID()}`;+ localStorage.clear();+ resetWorkbenchReplicaScope();+ setReplicaScopeSource(workbenchReplicaScope);+ useAgentDocumentStore.setState({ ...initialState });+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...touched].map((scope) =>+ agentDocumentReaderResource.storage!.remove({ queryKey: READER_KEY, scope }),+ ),+ );+ touched.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('keeps public surfaces network-only: no hydrate, no persist', () => {+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:ws_1`);++ expect(cacheScope.canHydrate?.()).toBe(false);+ expect(cacheScope.canPersist()).toBe(false);+ expect(cacheScope.get()).toBe('anon:workbench');+ });++ it('paints the last-read body on a cold start while the session check is in flight', async () => {+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:ws_1`);+ await persistReaderBody(`${userId}:workbench`, '# Cached');+ vi.stubGlobal('fetch', vi.fn(pending));+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockImplementation(pending);++ void enableWorkbenchIdentity();+ expect(cacheScope.canPersist()).toBe(false);++ renderReader();++ await waitFor(() => expect(reader()?.document?.content).toBe('# Cached'));+ });++ it('seeds the last-read body in the route loader, before the reader mounts', async () => {+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:ws_1`);+ await persistReaderBody(`${userId}:workbench`, '# Cached');+ vi.stubGlobal('fetch', vi.fn(pending));+ const getReaderDocument = vi.spyOn(agentDocumentService, 'getReaderDocument');++ const route = workbenchRoutes[0].children!.find((r) => r.path === 'agent/:aid/docs/:docId');+ expect(route?.loader).toBeTypeOf('function');++ // Bare ids, as in the mobile URL; the loader adds the prefixes.+ await agentDocumentReaderLoader({ params: { aid: '1', docId: '1' } } as never);++ // Already in the store when the reader first renders: no spinner frame.+ expect(reader()?.document?.content).toBe('# Cached');+ expect(getReaderDocument).not.toHaveBeenCalled();+ });++ it('persists the server answer once the session confirms the same account', async () => {+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:ws_1`);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => sessionResponse({ user: { id: userId } })),+ );+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockResolvedValue({+ content: '# Fresh',+ filename: 'a.md',+ title: 'A',+ } as any);+ touched.add(`${userId}:workbench`);++ await enableWorkbenchIdentity();+ expect(cacheScope.canPersist()).toBe(true);+ renderReader();++ await waitFor(async () =>+ expect((await storedReader(`${userId}:workbench`))?.document?.content).toBe('# Fresh'),+ );+ // The main SPA's workspace part is left alone for the same account.+ expect(localStorage.getItem(ACTIVE_SCOPE_KEY)).toBe(`${userId}:ws_1`);+ });++ it('drops the painted body when the session belongs to another account', async () => {+ const other = `wb-other-${randomUUID()}`;+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:personal`);+ await persistReaderBody(`${userId}:workbench`, '# Previous account');+ let answer!: (response: Response) => void;+ vi.stubGlobal(+ 'fetch',+ vi.fn(() => new Promise<Response>((resolve) => (answer = resolve))),+ );+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockImplementation(pending);++ const check = enableWorkbenchIdentity();+ renderReader();+ await waitFor(() => expect(reader()?.document?.content).toBe('# Previous account'));++ answer(sessionResponse({ user: { id: other } }));+ await check;++ await waitFor(() => expect(reader()).toBeUndefined());+ expect(cacheScope.get()).toBe(`${other}:workbench`);+ expect(localStorage.getItem(ACTIVE_SCOPE_KEY)).toBe(`${other}:personal`);+ });++ it('treats a signed-out session as nobody and forgets the last-known account', async () => {+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:personal`);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => sessionResponse(null)),+ );++ await enableWorkbenchIdentity();++ expect(cacheScope.get()).toBe('anon:workbench');+ expect(cacheScope.canPersist()).toBe(false);+ expect(localStorage.getItem(ACTIVE_SCOPE_KEY)).toBeNull();+ });++ it('does not take a failed session check as a sign-out', async () => {+ localStorage.setItem(ACTIVE_SCOPE_KEY, `${userId}:personal`);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => sessionResponse({}, 503)),+ );++ await enableWorkbenchIdentity();++ expect(cacheScope.get()).toBe(`${userId}:workbench`);+ expect(cacheScope.canPersist()).toBe(false);+ expect(localStorage.getItem(ACTIVE_SCOPE_KEY)).toBe(`${userId}:personal`);+ });+});diff --git a/apps/workbench/src/shell/workbenchReplicaScope.ts b/apps/workbench/src/shell/workbenchReplicaScope.tsnew file mode 100644index 00000000000..6fba0dd3dd7--- /dev/null+++ b/apps/workbench/src/shell/workbenchReplicaScope.ts@@ -0,0 +1,136 @@+import { useLayoutEffect, useSyncExternalStore } from 'react';++import { type ReplicaScopeSource } from '@/libs/replica';+import { broadcastCacheScope } from '@/libs/replica/cacheScopeEvents';+import {+ buildCacheScope,+ clearActiveScopeKey,+ isAnonymousScope,+ readActiveScope,+ writeActiveScope,+} from '@/libs/swr/useCacheScope';++/**+ * Workbench replica partition: `${userId}:workbench`.+ *+ * Workbench never mounts the user store or the workspace store, so it cannot+ * resolve the main SPA's `${userId}:${workspaceId}` scope. Its own partition+ * keeps what it persists apart from every main-SPA partition, while the user+ * part still isolates accounts sharing the browser.+ *+ * Public surfaces (acceptance / verify) stay network-only. A private route+ * calls `enableWorkbenchIdentity()`, which runs the same contract as the main+ * SPA: paint the last-known user's partition while the session check is in+ * flight, switch (and drop the painted rows) if the session belongs to someone+ * else or to nobody, and persist only after the session is confirmed.+ */+const WORKBENCH_PARTITION = 'workbench';++type Identity = { status: 'unresolved' } | { status: 'resolved'; userId: string | null };++let identity: Identity = { status: 'unresolved' };+let identityEnabled = false;+let sessionCheck: Promise<void> | undefined;+const listeners = new Set<() => void>();++const emit = () => {+ for (const listener of listeners) listener();+};++/**+ * The last user the main SPA confirmed. The main SPA clears it on a sign-out it+ * observes, so a logged-out browser never guesses a previous account.+ */+const lastKnownUserId = (): string | null => {+ const scope = readActiveScope();+ if (!scope || isAnonymousScope(scope)) return null;++ return scope.split(':', 1)[0] || null;+};++const currentUserId = (): string | null =>+ identity.status === 'resolved' ? identity.userId : identityEnabled ? lastKnownUserId() : null;++const getScope = (): string => buildCacheScope(currentUserId(), WORKBENCH_PARTITION);++const subscribe = (listener: () => void) => {+ listeners.add(listener);++ return () => {+ listeners.delete(listener);+ };+};++const useWorkbenchCacheScope = (): string => {+ const scope = useSyncExternalStore(subscribe, getScope, getScope);++ // Before paint, like `useCacheScope`: imperative replicas drop the previous+ // identity's views in the same frame the switch commits.+ useLayoutEffect(() => {+ broadcastCacheScope(scope);+ }, [scope]);++ return scope;+};++export const workbenchReplicaScope: ReplicaScopeSource = {+ canHydrate: () => identityEnabled,+ canPersist: () => identityEnabled && identity.status === 'resolved' && !!identity.userId,+ get: getScope,+ use: useWorkbenchCacheScope,+};++const resolveIdentity = (userId: string | null) => {+ const guessed = lastKnownUserId();+ identity = { status: 'resolved', userId };++ // Keep the shared last-known scope honest, as the main SPA would: a confirmed+ // sign-out drops it, and another account replaces it so the next boot of+ // either runtime does not paint the previous account first. The same account+ // keeps the main SPA's workspace part untouched.+ if (!userId) clearActiveScopeKey();+ else if (guessed !== userId) writeActiveScope(buildCacheScope(userId, null));++ emit();+};++const fetchSessionUserId = async (): Promise<string | null | undefined> => {+ const response = await fetch('/api/auth/get-session', { credentials: 'include' });+ if (response.status === 401) return null;+ // A transport or server failure is not evidence of sign-out: stay unresolved,+ // so nothing persists and the painted partition is only a guess.+ if (!response.ok) return undefined;++ const session = (await response.json()) as { user?: { id?: string } } | null;++ return session?.user?.id ?? null;+};++/**+ * Turn on persisted hydration for a private Workbench route and start its+ * session check. Call it while the route module loads, before the route renders,+ * so the very first sync of that route may paint from disk.+ */+export const enableWorkbenchIdentity = (): Promise<void> => {+ if (!identityEnabled) {+ identityEnabled = true;+ emit();+ }+ sessionCheck ??= fetchSessionUserId()+ .then((userId) => {+ if (userId !== undefined) resolveIdentity(userId);+ })+ .catch(() => {+ // Offline: keep painting the guess, persist nothing.+ });++ return sessionCheck;+};++/** Tests: back to a fresh, identity-less runtime. */+export const resetWorkbenchReplicaScope = (): void => {+ identity = { status: 'unresolved' };+ identityEnabled = false;+ sessionCheck = undefined;+ listeners.clear();+};diff --git a/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.ts b/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.tsindex 752870b539c..27bfadd92ea 100644--- a/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.ts+++ b/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.ts@@ -1,27 +1,26 @@import { useMemo } from 'react';-import { useClientDataSWR } from '@/libs/swr';-import {- type AgentDocumentListItem,- agentDocumentService,- agentDocumentSWRKeys,-} from '@/services/agentDocument';+import type { AgentDocumentListItem } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';+import {+ agentDocumentActions,+ agentDocumentSelectors,+ useAgentDocumentStore,+} from '@/store/agentDocument';export type AgentDocumentLookup = (ref?: string | null) => AgentDocumentListItem | undefined;/*** Resolve the document ids a tool call carries (either the row `id` or the* `docs_…` documentId) to the rows the user knows by title. Reads the active- * agent's document list under the sidebar's SWR key, so it adds no request- * while the documents panel is mounted.+ * agent's document-list replica the sidebar shares, so it adds no request while+ * the documents panel is mounted and paints from the persisted list on reload.*/export const useAgentDocumentLookup = (): { isLoading: boolean; lookup: AgentDocumentLookup } => {const agentId = useAgentStore((s) => s.activeAgentId);- const { data, isLoading } = useClientDataSWR(- agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,- () => agentDocumentService.listDocuments({ agentId: agentId! }),- );+ const { error } = agentDocumentActions.useFetchDocumentList(agentId);+ const data = useAgentDocumentStore(agentDocumentSelectors.getDocumentList(agentId));+ const isLoading = !!agentId && !data && !error;const lookup = useMemo<AgentDocumentLookup>(() => {const byRef = new Map<string, AgentDocumentListItem>();diff --git a/src/features/AgentDocumentPage/useAgentDocumentItem.ts b/src/features/AgentDocumentPage/useAgentDocumentItem.tsindex 12564ba2e6c..69455e98bfc 100644--- a/src/features/AgentDocumentPage/useAgentDocumentItem.ts+++ b/src/features/AgentDocumentPage/useAgentDocumentItem.ts@@ -1,15 +1,16 @@-import { useClientDataSWR } from '@/libs/swr';+import type { AgentDocumentListItem } from '@/services/agentDocument';import {- type AgentDocumentListItem,- agentDocumentService,- agentDocumentSWRKeys,-} from '@/services/agentDocument';+ agentDocumentActions,+ agentDocumentSelectors,+ useAgentDocumentStore,+} from '@/store/agentDocument';/**- * Resolve the agent-document list row for a documents-table id. Deduped against- * the working-sidebar's documents list (same SWR key), so it adds no extra- * request — it surfaces the agentDocument row id (needed for delete/rename) plus- * title / updatedAt for the page header.+ * Resolve the agent-document list row for a documents-table id. Reads the+ * agent's document-list replica (shared with the working sidebar), so it adds no+ * extra request — it surfaces the agentDocument row id (needed for delete/rename)+ * plus title / updatedAt for the page header. The persisted list paints the+ * header on a reload before the network answers.** For a skill's `SKILL.md` index document the row title is the canonical* `SKILL.md` filename, so we also resolve the parent skill bundle — the page@@ -17,9 +18,10 @@ import {* bundle rename.*/export const useAgentDocumentItem = (agentId: string | undefined, documentId: string) => {- const { data, error, isLoading, mutate } = useClientDataSWR(- agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,- () => agentDocumentService.listDocuments({ agentId: agentId! }),+ const { error, revalidate } = agentDocumentActions.useFetchDocumentList(agentId);+ const data = useAgentDocumentStore(agentDocumentSelectors.getDocumentList(agentId));+ const isConfirmed = useAgentDocumentStore(+ agentDocumentSelectors.isDocumentListConfirmed(agentId),);const item: AgentDocumentListItem | undefined = data?.find((d) => d.documentId === documentId);@@ -29,13 +31,18 @@ export const useAgentDocumentItem = (agentId: string | undefined, documentId: st? data?.find((d) => d.documentId === item.parentId): undefined;- // The list resolved successfully (`data` defined, no `error`) but this- // documentId isn't in it → the doc genuinely doesn't exist for this agent.- // Distinct from a fetch failure (`error`) and from still-loading- // (`data === undefined`). The header title is sourced from this same list, so- // gating not-found here keeps the whole module consistent instead of letting- // the breadcrumb render a placeholder title over a 404 body.- const isNotFound = !!agentId && data !== undefined && !error && !item;+ // The server answered this session (not just the persisted copy of an earlier+ // one) and this documentId isn't in it → the doc genuinely doesn't exist for+ // this agent. Distinct from a fetch failure (`error`) and from still-loading.+ // A persisted list predates documents created since, so a row missing from it+ // is only "not loaded yet". The header title is sourced from this same list,+ // so gating not-found here keeps the whole module consistent instead of+ // letting the breadcrumb render a placeholder title over a 404 body.+ const isNotFound = !!agentId && isConfirmed && !error && !item;- return { error, isLoading, isNotFound, item, mutate, skillBundle };+ // Loading until this row can paint: a persisted list holding the row paints at+ // once, and a revalidation over it never flashes the loader.+ const isLoading = !!agentId && !item && !error && !isConfirmed;++ return { error, isLoading, isNotFound, item, mutate: revalidate, skillBundle };};diff --git a/src/features/AgentDocumentReader/index.tsx b/src/features/AgentDocumentReader/index.tsxindex ab7819940bf..084650d5baa 100644--- a/src/features/AgentDocumentReader/index.tsx+++ b/src/features/AgentDocumentReader/index.tsx@@ -6,12 +6,15 @@ import { Center, Flexbox } from '@lobehub/ui/es/Flex/index';import Markdown from '@lobehub/ui/es/Markdown/index';import Text from '@lobehub/ui/es/Text/index';import { ArrowLeft, RefreshCw } from 'lucide-react';-import { memo } from 'react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import ContentLoading from '@/components/Loading/ContentLoading';-import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';+import {+ agentDocumentActions,+ agentDocumentSelectors,+ useAgentDocumentStore,+} from '@/store/agentDocument';const styles = createStaticStyles(({ css }) => ({article: css`@@ -49,11 +52,21 @@ interface AgentDocumentReaderProps {const AgentDocumentReader = memo<AgentDocumentReaderProps>(({ agentId, documentId }) => {const { t } = useTranslation('common');- const { data, error, isLoading, mutate } = useSWR(- agentId && documentId ? agentDocumentSWRKeys.readerDocument(agentId, documentId) : null,- () => agentDocumentService.getReaderDocument({ agentId, documentId }),- { revalidateOnFocus: false },+ const params = useMemo(+ () => (agentId && documentId ? { agentId, documentId } : null),+ [agentId, documentId],);+ // A reader replica: a revisit paints the last body read and the network only+ // confirms it. Loading / error take over only while there is nothing to show.+ const { error: syncError, revalidate } = agentDocumentActions.useFetchReaderDocument(params);+ const entry = useAgentDocumentStore(agentDocumentSelectors.getReaderDocument(params));+ const data = entry?.document ?? undefined;+ const error = data+ ? undefined+ : entry?.document === null+ ? new Error(entry.missingMessage)+ : (syncError as Error | undefined);+ const isLoading = !!params && !entry && !error;const backToAgent = () => window.location.assign(`/agent/${agentId}`);const title = data?.title || data?.filename || '';@@ -77,7 +90,7 @@ const AgentDocumentReader = memo<AgentDocumentReaderProps>(({ agentId, documentI<Buttonicon={RefreshCw}onClick={() => {- void mutate();+ void revalidate();}}>{t('retry')}diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex cea32f60a1a..b6c744032d4 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -13,7 +13,6 @@ import {import type { ChangeEvent, CSSProperties, MouseEvent } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import type { KeyedMutator } from 'swr';import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';import type {@@ -42,7 +41,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { openConvertToSkillModal, slugifySkillName } from './ConvertToSkillModal';import DocumentExplorerToolbar from './DocumentExplorerToolbar';import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';-import type { AgentDocumentItem } from './types';+import type { AgentDocumentItem, AgentDocumentListMutator } from './types';import { isOrphanSkillBundleItem } from './types';import { canDropDocument } from './utils/canDrop';import { createDocumentComparator } from './utils/sortDocuments';@@ -115,7 +114,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({interface Props {agentId: string;data: AgentDocumentItem[];- mutate: KeyedMutator<AgentDocumentItem[]>;+ mutate: AgentDocumentListMutator;onOpenDocument?: (documentId: string, agentDocumentId?: string) => void;style?: CSSProperties;}diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.tsindex a28ffe35ac9..ba9de6e0530 100644--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts@@ -3,7 +3,6 @@ import { confirmModal, toast } from '@lobehub/ui';import { nanoid } from 'nanoid';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import type { KeyedMutator } from 'swr';import { FILE_UPLOAD_BLACKLIST } from '@/const/file';import { useSingleton } from '@/hooks/useSingleton';@@ -11,14 +10,14 @@ import { agentDocumentService } from '@/services/agentDocument';import { fileService } from '@/services/file';import { useFileStore } from '@/store/file';-import type { AgentDocumentItem } from '../types';+import type { AgentDocumentItem, AgentDocumentListMutator } from '../types';import { isPendingId, isProtectedManagedSkillItem } from '../types';import { makePendingDocument } from '../utils/pendingDocument';interface UseDocumentTreeOpsArgs {agentId: string;data: AgentDocumentItem[];- mutate: KeyedMutator<AgentDocumentItem[]>;+ mutate: AgentDocumentListMutator;topicId?: string;}diff --git a/src/features/AgentDocumentsExplorer/index.ts b/src/features/AgentDocumentsExplorer/index.tsindex ca1fd7373e5..ee551017139 100644--- a/src/features/AgentDocumentsExplorer/index.ts+++ b/src/features/AgentDocumentsExplorer/index.ts@@ -1,3 +1,3 @@export { default as DocumentExplorerTree } from './DocumentExplorerTree';-export type { AgentDocumentItem } from './types';+export type { AgentDocumentItem, AgentDocumentListMutator } from './types';export { hasSkillIndexChild, isOrphanSkillBundleItem, isProtectedManagedSkillItem } from './types';diff --git a/src/features/AgentDocumentsExplorer/types.ts b/src/features/AgentDocumentsExplorer/types.tsindex 39cf91d5f29..9019a07ac86 100644--- a/src/features/AgentDocumentsExplorer/types.ts+++ b/src/features/AgentDocumentsExplorer/types.ts@@ -4,6 +4,17 @@ export type AgentDocumentItem = Awaited<ReturnType<typeof agentDocumentService.listDocuments>>[number];+/**+ * Edits the agent's document list: a value or updater applies a client-side+ * edit (re-synced afterwards unless `revalidate: false`); no argument re-syncs.+ */+export type AgentDocumentListMutator = (+ data?:+ | AgentDocumentItem[]+ | ((prev: AgentDocumentItem[] | undefined) => AgentDocumentItem[] | undefined),+ options?: { revalidate?: boolean },+) => Promise<unknown>;+export const PENDING_ID_PREFIX = 'pending:';export const isPendingId = (id: string): boolean => id.startsWith(PENDING_ID_PREFIX);diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsxindex b2d9dc77b30..656a223009e 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx@@ -11,7 +11,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import AgentDocumentsGroup from './AgentDocumentsGroup';-const useClientDataSWR = vi.fn();+// What the agent's document-list replica holds for this render+// (`data` undefined = no entry yet) and its sync flags.+const documentListMock = vi.hoisted(() => vi.fn());+const documentListState = (): {+ data?: unknown[];+ error?: unknown;+ mutate?: (...args: unknown[]) => unknown;+} => documentListMock() ?? {};const useProjectSkillsMock = vi.hoisted(() => vi.fn());const modalConfirm = vi.hoisted(() => vi.fn());const messageError = vi.hoisted(() => vi.fn());@@ -37,8 +44,14 @@ vi.mock('@/components/AsyncError', () => ({),}));-vi.mock('@/libs/swr', () => ({- useClientDataSWR: (...args: unknown[]) => useClientDataSWR(...args),+vi.mock('@/store/agentDocument', () => ({+ agentDocumentActions: {+ mutateDocumentList: (_agentId: string, ...args: unknown[]) =>+ documentListState().mutate?.(...args),+ useFetchDocumentList: () => ({ error: documentListState().error }),+ },+ agentDocumentSelectors: { getDocumentList: () => () => documentListState().data },+ useAgentDocumentStore: (selector: (state: unknown) => unknown) => selector({}),}));vi.mock('react-i18next', () => ({@@ -162,10 +175,6 @@ vi.mock('@/features/ChatInput/InputEditor/ActionTag/skillDragData', () => ({}));vi.mock('@/services/agentDocument', () => ({- agentDocumentSWRKeys: {- documents: (agentId: string) => ['agent:documents', agentId],- documentsList: (agentId: string) => ['agent:documentsList', agentId],- },agentDocumentService: {getDocuments: vi.fn(),removeDocument: removeDocumentMock,@@ -264,7 +273,7 @@ const webDocRow = {describe('AgentDocumentsGroup', () => {beforeEach(() => {- useClientDataSWR.mockReset();+ documentListMock.mockReset();useProjectSkillsMock.mockReset();useProjectSkillsMock.mockReturnValue({deviceItems: [],@@ -290,7 +299,7 @@ describe('AgentDocumentsGroup', () => {});it('defaults to the Skills tab and renders skill bundles via SkillsList', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -334,7 +343,7 @@ describe('AgentDocumentsGroup', () => {projectItems: [projectItem],raw: undefined,});- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -370,7 +379,7 @@ describe('AgentDocumentsGroup', () => {projectItems: [projectItem],raw: undefined,});- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [],error: undefined,isLoading: false,@@ -386,7 +395,7 @@ describe('AgentDocumentsGroup', () => {});it('opens the SKILL.md document in the portal when clicking a skill bundle row', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow],error: undefined,isLoading: false,@@ -401,7 +410,7 @@ describe('AgentDocumentsGroup', () => {});it('falls back to the bundle id when opening an orphan skill bundle', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow], // no SKILL.md childerror: undefined,isLoading: false,@@ -416,7 +425,7 @@ describe('AgentDocumentsGroup', () => {});it('opens a child file by relative path through onOpenFile', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow],error: undefined,isLoading: false,@@ -432,7 +441,7 @@ describe('AgentDocumentsGroup', () => {it('routes directly when opening a skill from document mode', () => {useParamsMock.mockReturnValue({ docId: 'doc-content-1' });- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow],error: undefined,isLoading: false,@@ -447,7 +456,7 @@ describe('AgentDocumentsGroup', () => {});it('renders the document tree when switching to the Documents tab', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -467,7 +476,7 @@ describe('AgentDocumentsGroup', () => {it('contains document tree render failures in an alert boundary', () => {documentExplorerShouldThrow.current = true;- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [fileDocRow],error: undefined,isLoading: false,@@ -481,7 +490,7 @@ describe('AgentDocumentsGroup', () => {});it('opens document tree files in the portal by default', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -499,7 +508,7 @@ describe('AgentDocumentsGroup', () => {it('routes document tree files directly in document mode', () => {useParamsMock.mockReturnValue({ docId: 'doc-content-1' });- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -516,7 +525,7 @@ describe('AgentDocumentsGroup', () => {it('defaults to Documents first in document mode and keeps Skills as the second tab', () => {useParamsMock.mockReturnValue({ docId: 'doc-content-1' });- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -542,7 +551,7 @@ describe('AgentDocumentsGroup', () => {it('can be controlled by an outer page-mode tab bar', () => {useParamsMock.mockReturnValue({ docId: 'doc-content-1' });- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -565,7 +574,7 @@ describe('AgentDocumentsGroup', () => {});it('resets to Documents when entering document mode', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -589,7 +598,7 @@ describe('AgentDocumentsGroup', () => {it('renders web items as cards in the Web tab and supports deletion', async () => {const mutate = vi.fn().mockResolvedValue(undefined);- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -625,7 +634,7 @@ describe('AgentDocumentsGroup', () => {});it('falls back to a single empty placeholder when every skill source is empty', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [fileDocRow, webDocRow],error: undefined,isLoading: false,@@ -642,7 +651,7 @@ describe('AgentDocumentsGroup', () => {});it('shows the web empty state when no web items are present', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: [fileDocRow],error: undefined,isLoading: false,@@ -655,10 +664,10 @@ describe('AgentDocumentsGroup', () => {expect(screen.getByText('No agent documents yet')).toBeInTheDocument();});- it('renders error state when SWR returns an error', () => {+ it('renders error state when the first load fails', () => {const mutate = vi.fn();- useClientDataSWR.mockReturnValue({- data: [],+ documentListMock.mockReturnValue({+ data: undefined,error: new Error('oops'),isLoading: false,mutate,@@ -670,8 +679,23 @@ describe('AgentDocumentsGroup', () => {expect(mutate).toHaveBeenCalled();});+ it('keeps painting the persisted list when its revalidation fails', () => {+ documentListMock.mockReturnValue({+ data: [fileDocRow, webDocRow],+ error: new Error('offline'),+ isLoading: false,+ mutate: vi.fn(),+ });++ render(<AgentDocumentsGroup />);+ fireEvent.click(screen.getByText('Web'));++ expect(screen.queryByTestId('async-error')).not.toBeInTheDocument();+ expect(screen.getByText('Example')).toBeInTheDocument();+ });+it('renders the loading spinner while data is being fetched', () => {- useClientDataSWR.mockReturnValue({+ documentListMock.mockReturnValue({data: undefined,error: undefined,isLoading: true,diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex cfd5702a796..21270d72d37 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx@@ -29,7 +29,10 @@ import { useParams } from 'react-router';import AsyncError from '@/components/AsyncError';import { withErrorBoundary } from '@/components/ErrorBoundary';import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';-import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';+import {+ type AgentDocumentListMutator,+ DocumentExplorerTree,+} from '@/features/AgentDocumentsExplorer';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';import {openRenameSkillModal,@@ -40,10 +43,14 @@ import {useProjectSkills,} from '@/features/SkillsList';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useClientDataSWR } from '@/libs/swr';-import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';+import { agentDocumentService } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';import { chatConfigByIdSelectors } from '@/store/agent/selectors';+import {+ agentDocumentActions,+ agentDocumentSelectors,+ useAgentDocumentStore,+} from '@/store/agentDocument';import { useChatStore } from '@/store/chat';import { standardizeIdentifier } from '@/utils/identifier';@@ -356,14 +363,20 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(projectItems: projectSkillItems,} = useProjectSkills(showProjectSkills ? workingDirectory : undefined, deviceId);- const {- data = EMPTY_ARRAY,- error,- isLoading,- mutate,- } = useClientDataSWR(- enabled && agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,- () => agentDocumentService.listDocuments({ agentId: agentId! }),+ // The agent's document-list replica: on a reload the persisted list paints+ // the panel at once and the network only confirms it.+ const { error: listError } = agentDocumentActions.useFetchDocumentList(agentId, { enabled });+ const list = useAgentDocumentStore(agentDocumentSelectors.getDocumentList(agentId));+ const data = list ?? EMPTY_ARRAY;+ // Loading / error take over the panel only while there is nothing to show.+ const isLoading = !list && !listError;+ const error = list ? undefined : listError;+ const mutate = useCallback<AgentDocumentListMutator>(+ (edit, options) =>+ agentId+ ? agentDocumentActions.mutateDocumentList(agentId, edit, options)+ : Promise.resolve(),+ [agentId],);const webData = useMemo(diff --git a/src/features/EntityLink/Render/InternalEntityLink.tsx b/src/features/EntityLink/Render/InternalEntityLink.tsxindex 7c7756fe1ec..70b59b9e9c8 100644--- a/src/features/EntityLink/Render/InternalEntityLink.tsx+++ b/src/features/EntityLink/Render/InternalEntityLink.tsx@@ -18,8 +18,12 @@ import { useTranslation } from 'react-i18next';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { shouldHardNavigateToWorkbench } from '@/libs/next/workbenchNavigation';import { useClientDataSWR } from '@/libs/swr';-import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';+import {+ agentDocumentActions,+ agentDocumentSelectors,+ useAgentDocumentStore,+} from '@/store/agentDocument';import { useChatStore } from '@/store/chat';import { useEntityLinkHostDismiss, useEntityLinkPortal } from '../host';@@ -124,9 +128,13 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,const linkedAgentId = reference.type === 'document' ? reference.agentId : undefined;const shouldResolveAgentDocument = !!linkedAgentId && linkedAgentId === activeAgentId;- const { data: agentDocuments, mutate: resolveAgentDocuments } = useClientDataSWR(- shouldResolveAgentDocument ? agentDocumentSWRKeys.documentsList(linkedAgentId) : null,- () => agentDocumentService.listDocuments({ agentId: linkedAgentId! }),+ // Shares the agent's document-list replica with the documents panel, so the+ // row id is usually known (or persisted) before the click; a click that beats+ // the first sync resolves the list on demand.+ const resolvedAgentId = shouldResolveAgentDocument ? linkedAgentId : undefined;+ agentDocumentActions.useFetchDocumentList(resolvedAgentId);+ const agentDocuments = useAgentDocumentStore(+ agentDocumentSelectors.getDocumentList(resolvedAgentId),);const handleClick = useCallback(@@ -214,7 +222,8 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,}case 'document': {const documents = shouldResolveAgentDocument- ? (agentDocuments ?? (await resolveAgentDocuments().catch(() => undefined)))+ ? (agentDocuments ??+ (await agentDocumentActions.fetchDocumentList(linkedAgentId!).catch(() => undefined))): undefined;const agentDocumentId = documents?.find((document) => document.documentId === reference.documentId,@@ -250,7 +259,7 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,openVerifyReport,portalAvailable,reference,- resolveAgentDocuments,+ linkedAgentId,shouldResolveAgentDocument,],);diff --git a/src/features/EntityLink/Render/index.test.tsx b/src/features/EntityLink/Render/index.test.tsxindex e24ea2f02e4..be584090b33 100644--- a/src/features/EntityLink/Render/index.test.tsx+++ b/src/features/EntityLink/Render/index.test.tsx@@ -82,16 +82,18 @@ vi.mock('@/libs/swr', () => ({if (key === null) return { data: undefined, mutate: vi.fn() };if (Array.isArray(key) && key[0] === 'internal-entity-preview')return { data: mockEntityPreview, mutate: vi.fn() };- return {- data: [{ documentId: 'docs_doc1', id: 'agent-document-1' }],- mutate: vi.fn(),- };+ return { data: undefined, mutate: vi.fn() };},}));-vi.mock('@/services/agentDocument', () => ({- agentDocumentService: { listDocuments: vi.fn() },- agentDocumentSWRKeys: { documentsList: (agentId: string) => ['agent-documents', agentId] },+// The active agent's document-list replica, already loaded.+vi.mock('@/store/agentDocument', () => ({+ agentDocumentActions: { fetchDocumentList: vi.fn(), useFetchDocumentList: vi.fn() },+ agentDocumentSelectors: {+ getDocumentList: (agentId?: string) => () =>+ agentId ? [{ documentId: 'docs_doc1', id: 'agent-document-1' }] : undefined,+ },+ useAgentDocumentStore: (selector: (state: unknown) => unknown) => selector({}),}));vi.mock('@/store/agent', () => ({diff --git a/src/features/Portal/Document/usePortalDocumentHeader.test.ts b/src/features/Portal/Document/usePortalDocumentHeader.test.tsindex 7b69908a022..95f9aee29e2 100644--- a/src/features/Portal/Document/usePortalDocumentHeader.test.ts+++ b/src/features/Portal/Document/usePortalDocumentHeader.test.ts@@ -293,7 +293,6 @@ describe('usePortalDocumentHeaderActions', () => {});expect(mockInvalidate).toHaveBeenCalledWith({- agentDocumentId: 'agent-document-1',agentId: 'agent-1',documentId: 'document-1',});diff --git a/src/features/Portal/Document/usePortalDocumentHeader.ts b/src/features/Portal/Document/usePortalDocumentHeader.tsindex 92bab4065e2..b4f509046e7 100644--- a/src/features/Portal/Document/usePortalDocumentHeader.ts+++ b/src/features/Portal/Document/usePortalDocumentHeader.ts@@ -89,7 +89,7 @@ export const usePortalDocumentTitle = () => {if (ticket !== saveTicketRef.current) return result;// Revalidate the caches other surfaces read titles from// (working-sidebar tree, standalone document page read- // `agent:documentsList`), mirroring the full-page editor's+ // the agent document-list replica), mirroring the full-page editor's// post-rename list refresh.void invalidateDocumentMutation({ agentId: agentId ?? undefined, documentId });return result;@@ -158,7 +158,6 @@ export const usePortalDocumentHeaderActions = () => {const refresh = useCallback(async () => {if (!documentId) return;await invalidateDocumentMutation({- agentDocumentId,agentId: agentDocumentId ? (agentId ?? undefined) : undefined,documentId,});diff --git a/src/libs/replica/index.test.ts b/src/libs/replica/index.test.tsindex 0158c179f2b..d3154815045 100644--- a/src/libs/replica/index.test.ts+++ b/src/libs/replica/index.test.ts@@ -1,24 +1,36 @@-import { afterEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { cacheScope, replicaSWRDriver, setReplicaPersistedHydration } from './index';+import {+ cacheScope,+ type ReplicaScopeSource,+ replicaSWRDriver,+ setReplicaScopeSource,+} from './index';// Many suites mock `@/libs/swr` with only the exports they use. The topic store// imports this module eagerly, so it must not touch `mutate` at import time.vi.mock('@/libs/swr', () => ({ useClientDataSWR: vi.fn() }));describe('@/libs/replica', () => {- afterEach(() => setReplicaPersistedHydration(true));+ const source: ReplicaScopeSource = {+ canHydrate: () => false,+ canPersist: () => false,+ get: () => 'u1:workbench',+ use: () => 'u1:workbench',+ };it('imports under a partial `@/libs/swr` mock', () => {expect(replicaSWRDriver).toBeDefined();});- it('lets an identity-less runtime opt out of persisted hydration', () => {+ it('lets a runtime without the user store install its own scope source', () => {expect(cacheScope.canHydrate?.()).toBe(true);- // The Workbench runtime turns this off at boot (it never mounts the user- // store), so its replicas read network-only instead of a guessed partition.- setReplicaPersistedHydration(false);+ // The Workbench runtime installs one at boot (it never mounts the user+ // store), so its replicas follow its own identity check instead.+ setReplicaScopeSource(source);expect(cacheScope.canHydrate?.()).toBe(false);+ expect(cacheScope.canPersist()).toBe(false);+ expect(cacheScope.get()).toBe('u1:workbench');});});diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex 36a88e1f1b0..23b9e6bfcbf 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -32,25 +32,29 @@ import { notifyReplicaDevtools, registerReplicaDevtools } from './devtools';*//**- * Whether this runtime may hydrate replicas from their persisted projection.+ * Where a runtime's replicas take their partition and their persistence gates.*- * The Workbench runtime renders the public acceptance / verify surfaces and- * never mounts the user store, so its cache scope stays the last-known user's- * partition. Hydrating there would paint a previous — possibly expired or- * server-invalidated — session's private rows before any authorization is- * checked, so the Workbench entry turns hydration off at boot. The main SPA- * keeps it on for the instant-from-cache first paint (it hydrates the persisted- * partition in parallel with the session check, then resets on a scope change).+ * The main SPA (the default) resolves the scope from the user store: it+ * hydrates the last-known user's partition in parallel with the session check+ * and resets on a scope change, and it persists only once identity resolves.+ *+ * The Workbench runtime never mounts the user store, so it installs its own+ * source at boot (`apps/workbench/src/shell/workbenchReplicaScope.ts`): network+ * only on its public surfaces, and the same hydrate-then-verify contract as the+ * main SPA on the private routes that run its session check.*/-let replicaHydrationEnabled = true;--/** Enable/disable reads from the persisted projection for this runtime. */-export const setReplicaPersistedHydration = (enabled: boolean): void => {- replicaHydrationEnabled = enabled;-};+export interface ReplicaScopeSource {+ /** Whether a persisted projection may be painted before the network answers. */+ canHydrate: () => boolean;+ /** Whether a server answer may be written to the persisted projection. */+ canPersist: () => boolean;+ get: () => string;+ /** React hook form of `get`; must be stable for the runtime's lifetime. */+ use: () => string;+}/**- * The scope hook, wrapped so `cacheScope` does not *read* it while this module+ * The scope hook and getters are referenced at call time, not while this module* body runs. `@/libs/swr/useCacheScope` imports `@/store/user`, and a user-store* slice imports this module — so when `useCacheScope` is the entry of that* cycle this module's body executes before `useCacheScope`'s exports are@@ -58,13 +62,29 @@ export const setReplicaPersistedHydration = (enabled: boolean): void => {* scope (a resource would then have no `scope.get`); resolving at call time is* equivalent because they are stateless delegating functions.*/-const useCacheScopeLazy = (): string => useCacheScope();+const useAppCacheScope = (): string => useCacheScope();-export const cacheScope: ReplicaScope = {- canHydrate: () => replicaHydrationEnabled,+const appScopeSource: ReplicaScopeSource = {+ canHydrate: () => true,canPersist: () => isScopeTrusted(),get: () => getCacheScope(),- use: useCacheScopeLazy,+ use: useAppCacheScope,+};++let scopeSource: ReplicaScopeSource = appScopeSource;++/** Install this runtime's scope source. Call once at boot, before any render. */+export const setReplicaScopeSource = (source: ReplicaScopeSource): void => {+ scopeSource = source;+};++const useSourceScope = (): string => scopeSource.use();++export const cacheScope: ReplicaScope = {+ canHydrate: () => scopeSource.canHydrate(),+ canPersist: () => scopeSource.canPersist(),+ get: () => scopeSource.get(),+ use: useSourceScope,};export type ReplicaStorageKind = 'indexedDB' | 'localStorage' | 'memory';diff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.tsindex 30d13a2838a..5d09957b4f7 100644--- a/src/libs/swr/useCacheScope.ts+++ b/src/libs/swr/useCacheScope.ts@@ -28,7 +28,8 @@ const ACTIVE_SCOPE_STORAGE_KEY = 'lobehub:active-scope';const isBrowser = () => typeof localStorage !== 'undefined';-const readActiveScope = (): string | null => {+/** The last-known resolved cache scope, or `null` when none is persisted. */+export const readActiveScope = (): string | null => {if (!isBrowser()) return null;try {return localStorage.getItem(ACTIVE_SCOPE_STORAGE_KEY);@@ -37,7 +38,7 @@ const readActiveScope = (): string | null => {}};-const writeActiveScope = (scope: string): void => {+export const writeActiveScope = (scope: string): void => {if (!isBrowser()) return;try {localStorage.setItem(ACTIVE_SCOPE_STORAGE_KEY, scope);diff --git a/src/routes/(main)/agent/docs/documentListLoader.ts b/src/routes/(main)/agent/docs/documentListLoader.tsnew file mode 100644index 00000000000..995a152f55e--- /dev/null+++ b/src/routes/(main)/agent/docs/documentListLoader.ts@@ -0,0 +1,20 @@+import type { LoaderFunctionArgs } from 'react-router';++import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { agentDocumentActions } from '@/store/agentDocument';++/**+ * Route loader for the agent documents surface (`/agent/:aid/docs/*`).+ *+ * Route loaders run before React commits the route: the only point where the+ * persisted document list (an async IndexedDB read) can land before the docs+ * sidebar paints its loading spinner.+ */+export const agentDocumentListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {+ await settleWithin(+ agentDocumentActions.preHydrateDocumentList(params.aid),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.tsindex e1bdef3964d..1c5ce570e2b 100644--- a/src/services/agentDocument.test.ts+++ b/src/services/agentDocument.test.ts@@ -33,6 +33,25 @@ vi.mock('@/libs/trpc/client', () => ({},}));+// Every SWR key / matcher handed to `mutate`, so a test can ask whether a+// replica sync key (or a plain `agent:*` SWR key) was revalidated.+const revalidated = () => vi.mocked(mutate).mock.calls.map((call) => call[0]);+const matchesReplica = (key: unknown[]) =>+ revalidated().some((entry) => typeof entry === 'function' && entry(key));+const agentDocumentListSyncKey = (agentId: string) => [+ 'replica:sync',+ 'agentDocumentList',+ 1,+ cacheScope.get(),+ agentId,+ {},+];+const legacyAgentDocumentKeys = () =>+ revalidated().filter(+ (entry) =>+ Array.isArray(entry) && typeof entry[0] === 'string' && entry[0].startsWith('agent:'),+ );+describe('AgentDocumentService', () => {beforeEach(() => {queryMock.mockResolvedValue({ ok: true });@@ -53,7 +72,8 @@ describe('AgentDocumentService', () => {title: 'title',});- expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);+ expect(matchesReplica(agentDocumentListSyncKey('agent-1'))).toBe(true);+ expect(legacyAgentDocumentKeys()).toEqual([]);});it('should revalidate agent documents after removeDocument', async () => {@@ -64,28 +84,27 @@ describe('AgentDocumentService', () => {topicId: 'topic-1',});- expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);- // `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 page and notebook replicas- // also push function matchers for their own sync keys.- const matchers = vi- .mocked(mutate)- .mock.calls.map((call) => call[0])- .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);- expect(listMatcher!(['agent:documentsList', 'agent-1', 'ws-1'])).toBe(true);- expect(listMatcher!(['agent:documentsList', 'other-agent'])).toBe(false);- expect(listMatcher!(['agent:documents', 'agent-1'])).toBe(false);- expect(mutate).toHaveBeenCalledWith(['agent:documentEditor', 'agent-1', 'doc-1']);+ // The agent's document list is a replica keyed by agent: the per-agent sync+ // key refreshes, other agents' entries do not, and no plain `agent:*` SWR+ // key is revalidated any more.+ expect(matchesReplica(agentDocumentListSyncKey('agent-1'))).toBe(true);+ expect(matchesReplica(agentDocumentListSyncKey('other-agent'))).toBe(false);+ expect(legacyAgentDocumentKeys()).toEqual([]);+ // The reader replica of the touched document refreshes too.+ expect(+ matchesReplica([+ 'replica:sync',+ 'agentDocumentReader',+ 1,+ cacheScope.get(),+ 'agent-1/page-doc-1',+ { agentId: 'agent-1', documentId: 'page-doc-1' },+ ]),+ ).toBe(true);// The page domain is a replica, so its list and by-id copies sync through// `replica:sync` keys and refresh through the scoped matcher instead of the// removed `page:*` SWR keys.const scope = cacheScope.get();- const matchesReplica = (key: unknown[]) => matchers.some((matcher) => matcher(key));expect(matchesReplica(['replica:sync', 'pageDetail', 1, scope, 'page-doc-1', {}])).toBe(true);// `revalidateReplica` without an entry key covers every entry of the// resource…@@ -110,7 +129,8 @@ describe('AgentDocumentService', () => {rule: {},});- expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);+ expect(matchesReplica(agentDocumentListSyncKey('agent-1'))).toBe(true);+ expect(legacyAgentDocumentKeys()).toEqual([]);});it('should fetch target agent documents when cache is missing', async () => {diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex c88c0fc9ba1..693058ec467 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -22,8 +22,6 @@ const getStringField = (value: unknown, field: 'documentId' | 'id') => {return typeof fieldValue === 'string' ? fieldValue : undefined;};-const getAgentDocumentId = (value: unknown) => getStringField(value, 'id');-const getDocumentId = (value: unknown) => getStringField(value, 'documentId');interface AgentDocumentToolContext {@@ -86,7 +84,6 @@ class AgentDocumentService {associateDocument = async (params: { agentId: string; documentId: string }) => {const result = await lambdaClient.agentDocument.associateDocument.mutate(params);await invalidateDocumentMutation({- agentDocumentId: getAgentDocumentId(result),agentId: params.agentId,cause: 'agent-document',documentId: params.documentId,@@ -98,7 +95,6 @@ class AgentDocumentService {importFile = async (params: { agentId: string; fileId: string; parentId?: string | null }) => {const result = await lambdaClient.agentDocument.importFile.mutate(params);await invalidateDocumentMutation({- agentDocumentId: getAgentDocumentId(result),agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -118,7 +114,6 @@ class AgentDocumentService {) => {const result = await lambdaClient.agentDocument.createDocument.mutate(params);await invalidateDocumentMutation({- agentDocumentId: getAgentDocumentId(result),agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -139,7 +134,6 @@ class AgentDocumentService {) => {const result = await lambdaClient.agentDocument.createForTopic.mutate(params);await invalidateDocumentMutation({- agentDocumentId: getAgentDocumentId(result),agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -162,7 +156,6 @@ class AgentDocumentService {) => {const result = await lambdaClient.agentDocument.replaceDocumentContent.mutate(params);await invalidateDocumentMutation({- agentDocumentId: params.id,agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -199,7 +192,6 @@ class AgentDocumentService {) => {const result = await lambdaClient.agentDocument.modifyNodes.mutate(params);await invalidateDocumentMutation({- agentDocumentId: params.id,agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -227,7 +219,6 @@ class AgentDocumentService {withChildren,});await invalidateDocumentMutation({- agentDocumentId: id,agentId,cause: 'agent-document',documentId,@@ -242,7 +233,6 @@ class AgentDocumentService {) => {const result = await lambdaClient.agentDocument.copyDocument.mutate(params);await invalidateDocumentMutation({- agentDocumentId: getAgentDocumentId(result),agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -256,7 +246,6 @@ class AgentDocumentService {) => {const result = await lambdaClient.agentDocument.renameDocument.mutate(params);await invalidateDocumentMutation({- agentDocumentId: params.id,agentId: params.agentId,cause: 'agent-document',documentId: getDocumentId(result),@@ -279,7 +268,6 @@ class AgentDocumentService {// otherwise the next autosave from that stale editor would overwrite the// generated SKILL.md frontmatter/body via the document save path.await invalidateDocumentMutation({- agentDocumentId: result.index.agentDocumentId,agentId: params.agentId,cause: 'agent-document',documentId: result.index.documentId,diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.tsindex 6dc9d43555a..9e254fe9e60 100644--- a/src/services/document/invalidation.ts+++ b/src/services/document/invalidation.ts@@ -1,18 +1,20 @@import { revalidateReplica } from '@/libs/replica';import { mutate } from '@/libs/swr';import { portalKeys } from '@/libs/swr/keys';+import {+ agentDocumentListResource,+ agentDocumentReaderKey,+ agentDocumentReaderResource,+} from '@/store/agentDocument/projection';import { documentDetailResource } from '@/store/document/slices/document/projection';import { notebookDocumentsResource } from '@/store/notebook/projection';import { pageDetailResource, pageListResource } from '@/store/page/projection';import { agentDocumentSkillsResource } from '@/store/tool/slices/agentDocumentSkills/projection';-import { agentDocumentSWRKeys } from './swrKeys';-export type DocumentMutationCause ='agent-document' | 'document-service' | 'notebook' | 'page-title';export interface InvalidateDocumentMutationParams {- agentDocumentId?: string;agentId?: string;cause?: DocumentMutationCause;documentId?: string;@@ -24,14 +26,7 @@ export interface InvalidateDocumentMutationParams {export const invalidateDocumentMutation = async (params: InvalidateDocumentMutationParams,): Promise<void> => {- const {- agentDocumentId,- agentId,- documentId,- refreshDocumentEditor,- refreshPageDocuments,- topicId,- } = params;+ const { agentId, documentId, refreshDocumentEditor, refreshPageDocuments, topicId } = params;const revalidations: Promise<unknown>[] = [];if (documentId) {@@ -61,22 +56,22 @@ export const invalidateDocumentMutation = async (}if (agentId) {- revalidations.push(mutate(agentDocumentSWRKeys.documents(agentId)));- // Prefix match so every `agent:documentsList` variant (full list + any- // hot-path variant, in both personal and workspace scope where the workspace- // id is appended) revalidates together. The scoped `mutate` passes function- // keys through untouched, so this predicate sees the real cache key.- revalidations.push(- mutate((key) => Array.isArray(key) && key[0] === 'agent:documentsList' && key[1] === agentId),- );- // The slash-menu skill registry is a replica, so its sync lives outside the- // `agent:documentsList` SWR cache. Refresh it here too: a create / delete /- // convert-to-skill must reach the menu without waiting for a remount.+ // The agent's document list is a replica keyed by agent: one entry feeds the+ // working sidebar, the document page header, entity links and tool cards.+ revalidations.push(revalidateReplica(agentDocumentListResource, agentId));+ // The slash-menu skill registry is a replica of its own (a web-free list).+ // Refresh it here too: a create / delete / convert-to-skill must reach the+ // menu without waiting for a remount.revalidations.push(revalidateReplica(agentDocumentSkillsResource, agentId));}- if (agentId && agentDocumentId) {- revalidations.push(mutate(agentDocumentSWRKeys.readDocument(agentId, agentDocumentId)));+ if (agentId && documentId) {+ revalidations.push(+ revalidateReplica(+ agentDocumentReaderResource,+ agentDocumentReaderKey({ agentId, documentId }),+ ),+ );}const results = await Promise.allSettled(revalidations);diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.tsindex 5d0830b96af..3a01c1c6a52 100644--- a/src/services/document/swrKeys.ts+++ b/src/services/document/swrKeys.ts@@ -1,15 +1,7 @@// Domain-namespaced SWR key roots. See the central registry in `@/libs/swr/keys`.+// The agent's document list and the read-only reader are replicas+// (`@/store/agentDocument`), so they have no SWR key here.export const agentDocumentSWRKeys = {- documents: (agentId: string) => ['agent:documents', agentId] as const,- /**- * UI-side list: raw AgentDocumentWithRules (includes documentId, sourceType, createdAt).- * Kept separate from `documents` because the agent store writes mapAgentDocumentsToContext(...)- * under that key, which drops those fields.- */- documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,documentChatTopic: (agentId: string, documentId: string) =>['agent:documentChatTopic', agentId, documentId] as const,- readerDocument: (agentId: string, documentId: string) =>- ['agent:documentReader', agentId, documentId] as const,- readDocument: (agentId: string, id: string) => ['agent:documentEditor', agentId, id] as const,};diff --git a/src/spa/router/agentDocumentListLoader.ts b/src/spa/router/agentDocumentListLoader.tsnew file mode 100644index 00000000000..e278a284de5--- /dev/null+++ b/src/spa/router/agentDocumentListLoader.ts@@ -0,0 +1,14 @@+import type { LoaderFunctionArgs } from 'react-router';++/**+ * Route-table entry for the agent documents pre-paint hydrate.+ *+ * The real loader imports the agent document store. The route tables sit in the+ * entry chunk's static graph, so importing it directly would pull the store into+ * the first screen; resolving it on first use keeps it in the docs route's lazy+ * chunks, which load in parallel with this one.+ */+export const agentDocumentListLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/agent/docs/documentListLoader').then((module) =>+ module.agentDocumentListLoader(args),+ );diff --git a/src/spa/router/agentDocumentListLoader.wiring.test.ts b/src/spa/router/agentDocumentListLoader.wiring.test.tsnew file mode 100644index 00000000000..cff4c99ab3e--- /dev/null+++ b/src/spa/router/agentDocumentListLoader.wiring.test.ts@@ -0,0 +1,40 @@+// @vitest-environment happy-dom+import type { RouteObject } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { agentDocumentListLoader } from './agentDocumentListLoader';+import { desktopRoutes } from './desktopRouter.config';++const loaderModule = vi.hoisted(() => ({ evaluated: false }));++// Evaluating the real loader means the agent document store reached the entry+// chunk's first-screen graph.+vi.mock('@/routes/(main)/agent/docs/documentListLoader', () => {+ loaderModule.evaluated = true;+ return { agentDocumentListLoader: vi.fn(async () => null) };+});++const flatten = (routes: RouteObject[]): RouteObject[] =>+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);++describe('agent document list loader wiring', () => {+ it('does not load the store-backed loader while the route tables load', () => {+ expect(loaderModule.evaluated).toBe(false);+ });++ it('pre-hydrates the document list on the agent docs layout route', () => {+ const routes = flatten(desktopRoutes).filter((r) => r.path === 'docs' && r.children?.length);++ expect(routes.length).toBeGreaterThan(0);+ expect(routes.every((route) => route.loader === agentDocumentListLoader)).toBe(true);+ });++ it('delegates to the real loader with the route args on first use', async () => {+ const { agentDocumentListLoader: realLoader } =+ await import('@/routes/(main)/agent/docs/documentListLoader');+ const args = { params: { aid: 'agt_1' } };++ await expect(agentDocumentListLoader(args as never)).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalledWith(args);+ });+});diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 3795adcee1b..a26cce8dd0e 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -81,6 +81,7 @@ import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShelimport { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { activityListLoader } from '@/spa/router/activityListLoader';import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';+import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';import { channelDataLoader } from '@/spa/router/channelDataLoader';import { contextListLoader } from '@/spa/router/contextListLoader';import { identitiesListLoader } from '@/spa/router/identitiesListLoader';@@ -204,6 +205,8 @@ export const sharedMainAreaChildren: RouteObject[] = [() => import('@/routes/(main)/agent/docs/_layout'),'Desktop > Chat > DocumentLayout',),+ // Seed the persisted document list before the docs sidebar paints.+ loader: agentDocumentListLoader,path: 'docs',},{diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex 8665b450870..e148abfcc7b 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -10,7 +10,6 @@ import { setScopedMutate } from '@/libs/swr';import * as cacheScopeModule from '@/libs/swr/useCacheScope';import { getCacheScope } from '@/libs/swr/useCacheScope';import { agentService } from '@/services/agent';-import { agentDocumentService } from '@/services/agentDocument';import { useGlobalStore } from '@/store/global';import { useUserStore } from '@/store/user';import { type LobeAgentConfig } from '@/types/agent';@@ -34,13 +33,6 @@ vi.mock('@/services/agent', () => ({}));vi.mock('@/services/agentDocument', () => ({- agentDocumentService: {- listDocuments: vi.fn(),- },- agentDocumentSWRKeys: {- documents: (agentId: string) => ['agent:documents', agentId] as const,- documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,- },resolveAgentDocumentsContext: vi.fn(),}));@@ -335,31 +327,6 @@ describe('AgentSlice Actions', () => {});});- describe('useFetchAgentDocuments', () => {- it('should fetch agent documents via listDocuments', async () => {- const docs = [- {- documentId: 'doc-1',- filename: 'setup.md',- id: 'doc-1',- title: 'Setup',- },- ];- vi.mocked(agentDocumentService.listDocuments).mockResolvedValue(docs as any);-- const store = renderHook(() => useAgentStore(), { wrapper: withSWR });-- const { result } = renderHook(() => store.result.current.useFetchAgentDocuments('agent-1'), {- wrapper: withSWR,- });-- await waitFor(() => {- expect(result.current.data).toEqual(docs);- });- expect(agentDocumentService.listDocuments).toHaveBeenCalledWith({ agentId: 'agent-1' });- });- });-describe('useFetchAvailableAgents', () => {it('should sync fetched available agents into store cache', async () => {vi.mocked(agentService.queryAgents).mockResolvedValue([diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex dd58004457c..0221bfd1d09 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -27,12 +27,7 @@ import { agentConfigKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@/services/agent';import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';-import {- type AgentDocumentListItem,- agentDocumentService,- agentDocumentSWRKeys,- resolveAgentDocumentsContext,-} from '@/services/agentDocument';+import { resolveAgentDocumentsContext } from '@/services/agentDocument';import { aiAgentService } from '@/services/aiAgent';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';@@ -609,16 +604,6 @@ export class AgentSliceActionImpl {return this.#toAgentConfigSyncResult(sync, agentId);};- useFetchAgentDocuments = (agentId?: string | null): SWRResponse<AgentDocumentListItem[]> => {- return useClientDataSWRWithSync<AgentDocumentListItem[]>(- agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,- async () => agentDocumentService.listDocuments({ agentId: agentId! }),- {- revalidateOnFocus: false,- },- );- };-useFetchAvailableAgents = (enabled: boolean): SWRResponse<AvailableAgentItem[]> => {return useClientDataSWRWithSync<AvailableAgentItem[]>(enabled ? agentConfigKeys.available() : null,diff --git a/src/store/agentDocument/action.ts b/src/store/agentDocument/action.tsnew file mode 100644index 00000000000..6f3ad674759--- /dev/null+++ b/src/store/agentDocument/action.ts@@ -0,0 +1,140 @@+import { cacheScope, type ReplicaSyncResult } from '@/libs/replica';+import type { AgentDocumentListItem } from '@/services/agentDocument';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { type AgentDocumentState, initialState } from './initialState';+import { AgentDocumentPrivateAction } from './privateAction';+import { type AgentDocumentReaderParams } from './projection';+import { useAgentDocumentStore } from './store';++const n = setNamespace('agentDocument');++type Setter = StoreSetter<AgentDocumentState>;++type DocumentListEdit =+ | AgentDocumentListItem[]+ | ((prev: AgentDocumentListItem[] | undefined) => AgentDocumentListItem[] | undefined);++interface MutateDocumentListOptions {+ /** Re-sync from the server after the local edit. Defaults to `true`. */+ revalidate?: boolean;+}++interface UseFetchDocumentListOptions {+ /** Pause the sync (e.g. a panel hidden behind `<Activity>`). Defaults to `true`. */+ enabled?: boolean;+}++export class AgentDocumentActionImpl {+ readonly #get: () => AgentDocumentState;+ readonly #private: AgentDocumentPrivateAction;+ readonly #set: Setter;++ constructor(+ set: Setter,+ get: () => AgentDocumentState,+ privateAction: AgentDocumentPrivateAction,+ ) {+ this.#get = get;+ this.#set = set;+ this.#private = privateAction;+ }++ /**+ * Fetch orchestration for one agent's document list. Every consumer shares the+ * one entry, so mounting several of them costs one request. Read the rows with+ * `agentDocumentSelectors.getDocumentList`, not from the return value.+ */+ useFetchDocumentList = (+ agentId?: string | null,+ { enabled = true }: UseFetchDocumentListOptions = {},+ ): ReplicaSyncResult =>+ this.#private.list.useSync(agentId || null, { enabled, revalidateOnFocus: false });++ /**+ * Seed one agent's persisted list before anything mounts — the docs route+ * loader's pre-paint read, so the sidebar's first frame is the list rather+ * than its loading spinner. Resolves `true` when a persisted list landed.+ */+ preHydrateDocumentList = (agentId?: string | null): Promise<boolean> => {+ if (!agentId) return Promise.resolve(false);++ const scope = cacheScope.get();+ // The slot may still hold the previous identity's rows; drop them before seeding.+ this.#private.list.ensureScope(scope);+ return this.#private.list.hydrate(agentId, scope);+ };++ /**+ * Seed the reader's persisted body before the reader mounts — its route+ * loader's pre-paint read, so the first frame is the body rather than the+ * content spinner. Resolves `true` when a persisted body landed.+ */+ preHydrateReaderDocument = (params?: AgentDocumentReaderParams | null): Promise<boolean> => {+ if (!params?.agentId || !params.documentId) return Promise.resolve(false);++ const scope = cacheScope.get();+ this.#private.reader.ensureScope(scope);+ return this.#private.reader.hydrate(params, scope);+ };++ /** Fetch orchestration for the read-only reader; read it with `getReaderDocument`. */+ useFetchReaderDocument = (params?: AgentDocumentReaderParams | null): ReplicaSyncResult =>+ this.#private.reader.useSync(params?.agentId && params.documentId ? params : null, {+ revalidateOnFocus: false,+ });++ /**+ * The agent's list, loading it when no view has it yet (an entity link+ * clicked before the documents panel ever mounted). Joins a sync in flight.+ */+ fetchDocumentList = async (agentId: string): Promise<AgentDocumentListItem[] | undefined> => {+ const loaded = this.#get().agentDocumentListMap[agentId];+ if (loaded) return loaded;+ await this.#private.list.fetch(agentId);+ return this.#get().agentDocumentListMap[agentId];+ };++ /**+ * Re-sync one agent's list (or every loaded agent's). Writes go through the+ * agent-document service, which already refreshes this via the document+ * invalidation; this is for an explicit retry / refresh.+ */+ refreshDocumentList = async (agentId?: string): Promise<void> => {+ await this.#private.list.revalidate(agentId);+ };++ /**+ * Edit one agent's list on the client — an optimistic insert / rename / move /+ * delete or its rollback — then (unless `revalidate: false`) re-sync it. With+ * no edit it only re-syncs. The edit stays in memory: only a server answer is+ * persisted, so a reload never paints a write the server did not confirm.+ */+ mutateDocumentList = async (+ agentId: string,+ edit?: DocumentListEdit,+ { revalidate = true }: MutateDocumentListOptions = {},+ ): Promise<void> => {+ if (edit !== undefined) {+ this.#private.list.update(+ agentId,+ (prev) => (typeof edit === 'function' ? edit(prev) : edit),+ { persist: false },+ );+ }+ if (edit === undefined || revalidate) await this.#private.list.revalidate(agentId);+ };++ reset = (): void => {+ this.#set(initialState, false, n('reset'));+ };+}++const { getState, setState } = useAgentDocumentStore;++export const agentDocumentActions = new AgentDocumentActionImpl(+ setState,+ getState,+ new AgentDocumentPrivateAction(setState, getState),+);diff --git a/src/store/agentDocument/index.ts b/src/store/agentDocument/index.tsnew file mode 100644index 00000000000..2c1a08d5f89--- /dev/null+++ b/src/store/agentDocument/index.ts@@ -0,0 +1,10 @@+export { agentDocumentActions } from './action';+export { type AgentDocumentState } from './initialState';+export {+ type AgentDocumentReaderContent,+ type AgentDocumentReaderDetail,+ agentDocumentReaderKey,+ type AgentDocumentReaderParams,+} from './projection';+export { agentDocumentSelectors } from './selectors';+export { useAgentDocumentStore } from './store';diff --git a/src/store/agentDocument/initialState.ts b/src/store/agentDocument/initialState.tsnew file mode 100644index 00000000000..6d8153e5b2c--- /dev/null+++ b/src/store/agentDocument/initialState.ts@@ -0,0 +1,22 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type { AgentDocumentListItem } from '@/services/agentDocument';++import type { AgentDocumentReaderDetail } from './projection';++export interface AgentDocumentState {+ /** Full document list per agent (`agentDocumentListMap[agentId]`). */+ agentDocumentListMap: Record<string, AgentDocumentListItem[]>;+ /** Replica bookkeeping for `agentDocumentListMap`. */+ agentDocumentListReplica: ReplicaState<AgentDocumentListItem[]>;+ /** Reader documents (`agentDocumentReaderMap[agentDocumentReaderKey(params)]`). */+ agentDocumentReaderMap: Record<string, AgentDocumentReaderDetail>;+ /** Replica bookkeeping for `agentDocumentReaderMap`. */+ agentDocumentReaderReplica: ReplicaState<AgentDocumentReaderDetail>;+}++export const initialState: AgentDocumentState = {+ agentDocumentListMap: {},+ agentDocumentListReplica: createReplicaState(),+ agentDocumentReaderMap: {},+ agentDocumentReaderReplica: createReplicaState(),+};diff --git a/src/store/agentDocument/privateAction.ts b/src/store/agentDocument/privateAction.tsnew file mode 100644index 00000000000..a23fb402537--- /dev/null+++ b/src/store/agentDocument/privateAction.ts@@ -0,0 +1,56 @@+import { createReplicaSlice, recordLens } from '@/libs/replica';+import { type AgentDocumentListItem, agentDocumentService } from '@/services/agentDocument';+import type { StoreSetter } from '@/store/types';+import { isTrpcErrorCode } from '@/utils/trpcError';++import { type AgentDocumentState } from './initialState';+import {+ agentDocumentListResource,+ type AgentDocumentReaderDetail,+ agentDocumentReaderResource,+ toAgentDocumentReaderContent,+} from './projection';++type Setter = StoreSetter<AgentDocumentState>;++const READER_ACCESS_LOST = ['NOT_FOUND', 'FORBIDDEN', 'UNAUTHORIZED'] as const;++export class AgentDocumentPrivateAction {+ readonly list;+ readonly reader;++ constructor(set: Setter, get: () => AgentDocumentState) {+ this.list = createReplicaSlice(agentDocumentListResource, {+ actionPrefix: 'agentDocumentList',+ fetcher: (agentId) => agentDocumentService.listDocuments({ agentId }),+ get,+ set,+ stateKey: 'agentDocumentListReplica',+ view: recordLens<AgentDocumentState, AgentDocumentListItem[]>('agentDocumentListMap'),+ });+ this.reader = createReplicaSlice(agentDocumentReaderResource, {+ actionPrefix: 'agentDocumentReader',+ fetcher: async ({ agentId, documentId }) => {+ try {+ const document = await agentDocumentService.getReaderDocument({ agentId, documentId });+ return { document: toAgentDocumentReaderContent(document) };+ } catch (error) {+ // A deleted (or never-owned) document, or one this session may no+ // longer read, is an answer, not a failure: it must evict the body a+ // reload would otherwise paint before the server says no.+ if (READER_ACCESS_LOST.some((code) => isTrpcErrorCode(error, code))) {+ return { document: null, missingMessage: (error as Error).message };+ }+ throw error;+ }+ },+ get,+ set,+ stateKey: 'agentDocumentReaderReplica',+ // "Not found" is a page state: never persist it, and evict the body+ // persisted earlier so a reload cannot resurrect a deleted document.+ toPersisted: (data) => (data.document ? data : null),+ view: recordLens<AgentDocumentState, AgentDocumentReaderDetail>('agentDocumentReaderMap'),+ });+ }+}diff --git a/src/store/agentDocument/projection.ts b/src/store/agentDocument/projection.tsnew file mode 100644index 00000000000..c990a0d307f--- /dev/null+++ b/src/store/agentDocument/projection.ts@@ -0,0 +1,83 @@+import { defineReplica } from '@/libs/replica';+import type { AgentDocumentListItem } from '@/services/agentDocument';++/** Agents whose document list survives a reload, most recently used first. */+const MAX_PERSISTED_AGENT_DOCUMENT_LISTS = 30;+/** Reader documents whose body survives a reload, most recently used first. */+const MAX_PERSISTED_READER_DOCUMENTS = 20;++/**+ * One agent's full document list (documents, web clips and skill bundles),+ * keyed by `agentId` (`agentDocumentListMap[agentId]`).+ *+ * The working sidebar, the agent document page header, entity links and the+ * agent-documents tool cards all read this one entry, so the persisted copy+ * paints every one of them on a cold start and the network only confirms.+ * Rows carry metadata only (no body); the cap bounds how many agents' lists a+ * long-lived scope keeps on disk.+ */+export const agentDocumentListResource = defineReplica<string, AgentDocumentListItem[]>({+ key: (agentId) => agentId,+ name: 'agentDocumentList',+ persist: { maxEntries: MAX_PERSISTED_AGENT_DOCUMENT_LISTS },+ storage: 'indexedDB',+ version: 1,+});++export interface AgentDocumentReaderParams {+ agentId: string;+ documentId: string;+}++/**+ * Entry identity of one reader document. Document ids are only unique per+ * agent binding as far as the reader is concerned (the server checks the agent+ * owns it), so the agent is part of the key.+ */+export const agentDocumentReaderKey = ({ agentId, documentId }: AgentDocumentReaderParams) =>+ `${agentId}/${documentId}`;++/** What the read-only reader paints — the server row minus its editor state. */+export interface AgentDocumentReaderContent {+ content: string;+ filename: string;+ title: string;+}++/**+ * The value of one reader entry. Wrapped so "the server answered not found"+ * (`document: null`) is a value the page can settle on, distinct from "nothing+ * loaded yet" (no entry). The not-found marker is never persisted.+ */+export interface AgentDocumentReaderDetail {+ document: AgentDocumentReaderContent | null;+ /** The server's not-found message, shown in place of the body. */+ missingMessage?: string;+}++/** Keep only the fields the reader renders: the row also carries `editorData`. */+export const toAgentDocumentReaderContent = (doc: {+ content?: string | null;+ filename?: string | null;+ title?: string | null;+}): AgentDocumentReaderContent => ({+ content: doc.content ?? '',+ filename: doc.filename ?? '',+ title: doc.title ?? '',+});++/**+ * The standalone read-only agent document view, one entry per agent + document+ * (`agentDocumentReaderMap[agentDocumentReaderKey(params)]`). Bodies can be+ * large, so the cap keeps only the most recently read documents on disk.+ */+export const agentDocumentReaderResource = defineReplica<+ AgentDocumentReaderParams,+ AgentDocumentReaderDetail+>({+ key: agentDocumentReaderKey,+ name: 'agentDocumentReader',+ persist: { maxEntries: MAX_PERSISTED_READER_DOCUMENTS },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/agentDocument/replica.test.ts b/src/store/agentDocument/replica.test.tsnew file mode 100644index 00000000000..7adffa95073--- /dev/null+++ b/src/store/agentDocument/replica.test.ts@@ -0,0 +1,334 @@+/**+ * @vitest-environment happy-dom+ *+ * An agent's document list and the read-only reader are `@lobechat/replica`+ * resources: the persisted projection paints a cold start while the network+ * confirms it, client-side edits never reach storage, scopes stay isolated, and+ * the reader keeps only the fields it renders and forgets deleted documents.+ */+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 { useAgentDocumentItem } from '@/features/AgentDocumentPage/useAgentDocumentItem';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { type AgentDocumentListItem, agentDocumentService } from '@/services/agentDocument';++import { agentDocumentActions } from './action';+import { initialState } from './initialState';+import {+ agentDocumentListResource,+ type AgentDocumentReaderParams,+ agentDocumentReaderResource,+} from './projection';+import { agentDocumentSelectors } from './selectors';+import { useAgentDocumentStore } from './store';++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 AGENT_ID = 'agent-1';+const READER: AgentDocumentReaderParams = { agentId: AGENT_ID, documentId: 'docs_1' };++const row = (id: string, overrides: Partial<AgentDocumentListItem> = {}): AgentDocumentListItem =>+ ({+ category: 'document',+ documentId: `docs_${id}`,+ filename: `${id}.md`,+ id,+ parentId: null,+ title: id,+ ...overrides,+ }) as AgentDocumentListItem;++/** Never-resolving fetch: what the store holds can only have come from storage. */+const pending = () => new Promise<never>(() => {});++const list = () =>+ agentDocumentSelectors.getDocumentList(AGENT_ID)(useAgentDocumentStore.getState());+const reader = () =>+ agentDocumentSelectors.getReaderDocument(READER)(useAgentDocumentStore.getState());++const LIST_KEY = agentDocumentListResource.storageKey(AGENT_ID);+const READER_KEY = agentDocumentReaderResource.storageKey(READER);++describe('agent document replicas', () => {+ 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);+ };++ const storedList = async () =>+ (await agentDocumentListResource.storage!.get({ queryKey: LIST_KEY, scope }))?.data;+ const storedReader = async () =>+ (await agentDocumentReaderResource.storage!.get({ queryKey: READER_KEY, scope }))?.data;++ beforeEach(() => {+ useScope(`agent-doc-user-${randomUUID()}:personal`);+ useAgentDocumentStore.setState({ ...initialState });+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) => [+ agentDocumentListResource.storage!.remove({ queryKey: LIST_KEY, scope: value }),+ agentDocumentReaderResource.storage!.remove({ queryKey: READER_KEY, scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ describe('document list', () => {+ const renderSync = () =>+ renderHook(() => agentDocumentActions.useFetchDocumentList(AGENT_ID), { wrapper });++ it('caps how many agents keep a persisted list', () => {+ expect(agentDocumentListResource.maxPersistedEntries).toBe(30);+ });++ it('paints the persisted list before the network answers', async () => {+ await agentDocumentListResource.storage!.set(+ { queryKey: LIST_KEY, scope },+ { data: [row('a', { title: 'Cached' })], updatedAt: 1 },+ );+ vi.spyOn(agentDocumentService, 'listDocuments').mockImplementation(pending);++ renderSync();++ await waitFor(() => expect(list()).toHaveLength(1));+ expect(list()![0].title).toBe('Cached');+ });++ it('seeds the persisted list before anything mounts, for the docs route loader', async () => {+ await agentDocumentListResource.storage!.set(+ { queryKey: LIST_KEY, scope },+ { data: [row('a', { title: 'Cached' })], updatedAt: 1 },+ );+ const listDocuments = vi.spyOn(agentDocumentService, 'listDocuments');++ await expect(agentDocumentActions.preHydrateDocumentList(AGENT_ID)).resolves.toBe(true);++ // Already in the store when the sidebar first renders: no spinner frame.+ expect(list()![0].title).toBe('Cached');+ expect(listDocuments).not.toHaveBeenCalled();+ });++ it('leaves the list unloaded when nothing is persisted or no agent is routed', async () => {+ await expect(agentDocumentActions.preHydrateDocumentList(AGENT_ID)).resolves.toBe(false);+ await expect(agentDocumentActions.preHydrateDocumentList(undefined)).resolves.toBe(false);++ expect(list()).toBeUndefined();+ });++ it('persists the server answer for the next cold start', async () => {+ vi.spyOn(agentDocumentService, 'listDocuments').mockResolvedValue([row('a'), row('b')]);++ renderSync();++ await waitFor(() => expect(list()).toHaveLength(2));+ await waitFor(async () => expect(await storedList()).toHaveLength(2));+ expect(agentDocumentService.listDocuments).toHaveBeenCalledWith({ agentId: AGENT_ID });+ });++ it('keeps client-side edits in memory until the server confirms them', async () => {+ const listDocuments = vi+ .spyOn(agentDocumentService, 'listDocuments')+ .mockResolvedValue([row('a')]);+ renderSync();+ await waitFor(async () => expect(await storedList()).toHaveLength(1));++ // An optimistic insert shows at once but never reaches storage…+ await act(() =>+ agentDocumentActions.mutateDocumentList(AGENT_ID, (prev) => [...(prev ?? []), row('tmp')], {+ revalidate: false,+ }),+ );+ expect(list()!.map((doc) => doc.id)).toEqual(['a', 'tmp']);+ expect((await storedList())!.map((doc) => doc.id)).toEqual(['a']);++ // …until the server answers with the real row.+ listDocuments.mockResolvedValue([row('a'), row('b')]);+ await act(() => agentDocumentActions.mutateDocumentList(AGENT_ID));+ await waitFor(() => expect(list()!.map((doc) => doc.id)).toEqual(['a', 'b']));+ await waitFor(async () =>+ expect((await storedList())!.map((doc) => doc.id)).toEqual(['a', 'b']),+ );+ });++ it('drops the previous scope’s list on a cache-scope switch', async () => {+ const listDocuments = vi+ .spyOn(agentDocumentService, 'listDocuments')+ .mockResolvedValue([row('a')]);+ const { rerender } = renderSync();+ await waitFor(() => expect(list()).toHaveLength(1));++ useScope(`${scope.split(':')[0]}:ws-1`);+ listDocuments.mockImplementation(pending);+ rerender();++ expect(list()).toBeUndefined();+ });++ it('resolves the list on demand for a click that beats the first sync', async () => {+ vi.spyOn(agentDocumentService, 'listDocuments').mockResolvedValue([row('a')]);++ const docs = await agentDocumentActions.fetchDocumentList(AGENT_ID);++ expect(docs!.map((doc) => doc.id)).toEqual(['a']);+ });+ });++ describe('agent document page row', () => {+ it('paints the header row from the persisted list, without a loader', async () => {+ await agentDocumentListResource.storage!.set(+ { queryKey: LIST_KEY, scope },+ { data: [row('1', { title: 'Cached title' })], updatedAt: 1 },+ );+ vi.spyOn(agentDocumentService, 'listDocuments').mockImplementation(pending);++ const { result } = renderHook(() => useAgentDocumentItem(AGENT_ID, 'docs_1'), { wrapper });++ await waitFor(() => expect(result.current.item?.title).toBe('Cached title'));+ expect(result.current.isLoading).toBe(false);+ expect(result.current.isNotFound).toBe(false);+ });++ it('does not call a document missing from the persisted list "not found" before the server answers', async () => {+ // An earlier session persisted the list before this document existed.+ await agentDocumentListResource.storage!.set(+ { queryKey: LIST_KEY, scope },+ { data: [row('old')], updatedAt: 1 },+ );+ let answer!: (docs: AgentDocumentListItem[]) => void;+ vi.spyOn(agentDocumentService, 'listDocuments').mockImplementation(+ () => new Promise((resolve) => (answer = resolve)),+ );++ const { result } = renderHook(() => useAgentDocumentItem(AGENT_ID, 'docs_new'), {+ wrapper,+ });++ await waitFor(() => expect(list()).toHaveLength(1));+ expect(result.current.isNotFound).toBe(false);+ expect(result.current.isLoading).toBe(true);++ await act(async () => answer([row('old'), row('new')]));++ await waitFor(() => expect(result.current.item?.id).toBe('new'));+ expect(result.current.isNotFound).toBe(false);+ });++ it('reports not found once the server list lacks the document', async () => {+ vi.spyOn(agentDocumentService, 'listDocuments').mockResolvedValue([row('old')]);++ const { result } = renderHook(() => useAgentDocumentItem(AGENT_ID, 'docs_gone'), {+ wrapper,+ });++ await waitFor(() => expect(result.current.isNotFound).toBe(true));+ });+ });++ describe('reader', () => {+ const renderSync = () =>+ renderHook(() => agentDocumentActions.useFetchReaderDocument(READER), { wrapper });++ it('caps how many reader bodies persist', () => {+ expect(agentDocumentReaderResource.maxPersistedEntries).toBe(20);+ });++ it('paints the persisted body before the network answers', async () => {+ await agentDocumentReaderResource.storage!.set(+ { queryKey: READER_KEY, scope },+ {+ data: { document: { content: '# Cached', filename: 'a.md', title: 'A' } },+ updatedAt: 1,+ },+ );+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockImplementation(pending);++ renderSync();++ await waitFor(() => expect(reader()?.document?.content).toBe('# Cached'));+ });++ it('keeps only the rendered fields, never the editor state', async () => {+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockResolvedValue({+ content: '# Body',+ editorData: { root: { children: [] } },+ filename: 'a.md',+ id: 'row-1',+ title: 'A',+ } as any);++ renderSync();++ await waitFor(async () =>+ expect(await storedReader()).toEqual({+ document: { content: '# Body', filename: 'a.md', title: 'A' },+ }),+ );+ });++ it('evicts the persisted body of a document the server no longer has', async () => {+ await agentDocumentReaderResource.storage!.set(+ { queryKey: READER_KEY, scope },+ {+ data: { document: { content: '# Deleted', filename: 'a.md', title: 'A' } },+ updatedAt: 1,+ },+ );+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockRejectedValue(+ Object.assign(new Error('Agent document not found'), { data: { code: 'NOT_FOUND' } }),+ );++ renderSync();++ await waitFor(() => expect(reader()?.document).toBeNull());+ expect(reader()?.missingMessage).toBe('Agent document not found');+ await waitFor(async () => expect(await storedReader()).toBeUndefined());+ });++ it('evicts the persisted body once this session may no longer read it', async () => {+ await agentDocumentReaderResource.storage!.set(+ { queryKey: READER_KEY, scope },+ {+ data: { document: { content: '# Revoked', filename: 'a.md', title: 'A' } },+ updatedAt: 1,+ },+ );+ vi.spyOn(agentDocumentService, 'getReaderDocument').mockRejectedValue(+ Object.assign(new Error('Forbidden'), { data: { code: 'FORBIDDEN' } }),+ );++ renderSync();++ await waitFor(() => expect(reader()?.document).toBeNull());+ await waitFor(async () => expect(await storedReader()).toBeUndefined());+ });+ });+});diff --git a/src/store/agentDocument/selectors.ts b/src/store/agentDocument/selectors.tsnew file mode 100644index 00000000000..d2631d59918--- /dev/null+++ b/src/store/agentDocument/selectors.ts@@ -0,0 +1,38 @@+import type { AgentDocumentListItem } from '@/services/agentDocument';++import type { AgentDocumentState } from './initialState';+import {+ type AgentDocumentReaderDetail,+ agentDocumentReaderKey,+ type AgentDocumentReaderParams,+} from './projection';++/** One agent's document list, or `undefined` before its first paint. */+const getDocumentList =+ (agentId?: string | null) =>+ (s: AgentDocumentState): AgentDocumentListItem[] | undefined =>+ agentId ? s.agentDocumentListMap[agentId] : undefined;++/**+ * The list on screen is one the server answered this session (not only the+ * copy persisted by an earlier one). Absence of a row is only conclusive then:+ * a persisted list predates any document created since.+ */+const isDocumentListConfirmed =+ (agentId?: string | null) =>+ (s: AgentDocumentState): boolean => {+ if (!agentId) return false;+ return s.agentDocumentListReplica.entries[agentId]?.source === 'server';+ };++/** One reader entry, or `undefined` before its first paint. */+const getReaderDocument =+ (params?: AgentDocumentReaderParams | null) =>+ (s: AgentDocumentState): AgentDocumentReaderDetail | undefined =>+ params ? s.agentDocumentReaderMap[agentDocumentReaderKey(params)] : undefined;++export const agentDocumentSelectors = {+ getDocumentList,+ getReaderDocument,+ isDocumentListConfirmed,+};diff --git a/src/store/agentDocument/store.ts b/src/store/agentDocument/store.tsnew file mode 100644index 00000000000..68f5718bde9--- /dev/null+++ b/src/store/agentDocument/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { type AgentDocumentState, initialState } from './initialState';++const devtools = createDevtools('agentDocument');++export const useAgentDocumentStore = createWithEqualityFn<AgentDocumentState>()(+ devtools(() => initialState),+ shallow,+);++expose('agentDocument', useAgentDocumentStore);diff --git a/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.ts b/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.tsindex 05ccf4a18a3..d8df6ea7cfd 100644--- a/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.ts+++ b/src/store/tool/slices/agentDocumentSkills/documentInvalidation.test.ts@@ -1,7 +1,7 @@/*** Guards the migration's cross-layer wiring: an agent-document write must* revalidate the slash-menu skill registry, which now lives in a replica- * (`replica:sync` keys) instead of the `agent:documentsList` SWR entry.+ * (`replica:sync` keys) instead of the agent document list SWR entry.*/import { describe, expect, it, vi } from 'vitest';diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.tsindex dd353e7170e..7eac7d5bbe1 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -1,6 +1,7 @@import { unstable_batchedUpdates } from 'react-dom';import { useAgentStore } from '@/store/agent';+import { agentDocumentActions } from '@/store/agentDocument';import { useAgentGroupStore } from '@/store/agentGroup';import { useChatStore } from '@/store/chat';import { resetGatewayMuxRegistry } from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';@@ -47,7 +48,7 @@ const resetableStores: ResetableStoreApi[] = [useVideoStore,];-const resetableActions: ResetableStore[] = [pageActions];+const resetableActions: ResetableStore[] = [agentDocumentActions, pageActions];export interface StoreActions extends ResetableStore {}