Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(portal): persist portal documents and text file previews through @lobechat/replica (#20849)

Arvin Xuc3ee144e7102
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 83939f2c46e..908a2d60861 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -15,6 +15,10 @@ import type {
ProjectFileIndexResult as DeviceProjectFileIndexResult,
SkillDirectoryDeps,
} from '@lobechat/device-control';
+import {
+ outsideWorkspacePreviewFailure,
+ toLocalFilePreviewFailure,
+} from '@lobechat/device-control/file-preview';
import {
defaultGetProjectFileIndex,
defaultListProjectDirectory,
@@ -612,13 +616,13 @@ export default class LocalFileCtr extends ControllerModule {
});
if (!url) {
- return { error: 'File is outside the approved workspace', success: false };
+ return outsideWorkspacePreviewFailure();
}
return { success: true, url };
} catch (error) {
logger.error('Failed to create local file preview URL:', error);
- return { error: (error as Error).message, success: false };
+ return toLocalFilePreviewFailure(error);
}
}
@@ -702,7 +706,7 @@ export default class LocalFileCtr extends ControllerModule {
});
if (!preview) {
- return { error: 'File is outside the approved workspace', success: false };
+ return outsideWorkspacePreviewFailure();
}
return {
@@ -711,7 +715,7 @@ export default class LocalFileCtr extends ControllerModule {
};
} catch (error) {
logger.error('Failed to read local file preview:', error);
- return { error: (error as Error).message, success: false };
+ return toLocalFilePreviewFailure(error);
}
}
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index bc848a1f120..f9e33a5f8cf 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -287,11 +287,30 @@ describe('LocalFileCtr', () => {
});
expect(result).toEqual({
+ code: 'forbidden',
error: 'File is outside the approved workspace',
success: false,
});
});
+ it('marks a file that vanished before its preview URL exists as not found', async () => {
+ mockLocalFileProtocolManager.createPreviewUrl.mockRejectedValue(
+ Object.assign(
+ new Error("ENOENT: no such file or directory, realpath '/workspace/gone.md'"),
+ {
+ code: 'ENOENT',
+ },
+ ),
+ );
+
+ const result = await localFileCtr.getLocalFilePreviewUrl({
+ path: '/workspace/gone.md',
+ workingDirectory: '/workspace',
+ });
+
+ expect(result).toMatchObject({ code: 'not_found', success: false });
+ });
+
it('should forward image-only preview URL constraints', async () => {
mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue(
'localfile://file/workspace/image.png?token=abc',
@@ -479,6 +498,7 @@ describe('LocalFileCtr', () => {
});
expect(result).toEqual({
+ code: 'forbidden',
error: 'File is outside the approved workspace',
success: false,
});
diff --git a/packages/device-control/src/__tests__/filePreview.test.ts b/packages/device-control/src/__tests__/filePreview.test.ts
index 9d76b91dd29..15cfa7489e5 100644
--- a/packages/device-control/src/__tests__/filePreview.test.ts
+++ b/packages/device-control/src/__tests__/filePreview.test.ts
@@ -9,6 +9,7 @@ import {
defaultGetLocalFilePreview,
defaultReadExternalAssetForPublish,
EXTERNAL_PUBLISH_ASSET_MAX_BYTES,
+ toLocalFilePreviewFailure,
} from '../filePreview';
const mockedHome = vi.hoisted(() => ({ dir: '' }));
@@ -134,12 +135,31 @@ describe('defaultGetLocalFilePreview', () => {
expect(result).toEqual({ error: 'File is not an image', success: false });
});
+ it('marks a deleted file as a terminal not-found failure', async () => {
+ const result = await defaultGetLocalFilePreview({
+ path: path.join(root, 'deleted.md'),
+ workingDirectory: root,
+ });
+ expect(result).toMatchObject({ code: 'not_found', success: false });
+ });
+
+ it('classifies only deleted / denied errors as terminal', () => {
+ const errno = (code: string) => Object.assign(new Error(code), { code });
+ expect(toLocalFilePreviewFailure(errno('ENOENT'))).toMatchObject({ code: 'not_found' });
+ expect(toLocalFilePreviewFailure(errno('EACCES'))).toMatchObject({ code: 'forbidden' });
+ expect(toLocalFilePreviewFailure(errno('EBUSY'))).toEqual({ error: 'EBUSY', success: false });
+ });
+
it('refuses to read a file outside the working directory', async () => {
const result = await defaultGetLocalFilePreview({
path: path.join(outside, 'secret.txt'),
workingDirectory: root,
});
- expect(result).toEqual({ error: 'File is outside the approved workspace', success: false });
+ expect(result).toEqual({
+ code: 'forbidden',
+ error: 'File is outside the approved workspace',
+ success: false,
+ });
});
it('errors when the working directory is missing', async () => {
diff --git a/packages/device-control/src/filePreview.ts b/packages/device-control/src/filePreview.ts
index 2f9eb2b8940..0006a373188 100644
--- a/packages/device-control/src/filePreview.ts
+++ b/packages/device-control/src/filePreview.ts
@@ -11,6 +11,7 @@ import type {
ExternalAssetForPublishParams,
ExternalAssetForPublishResult,
LocalFilePreview,
+ LocalFilePreviewFailureCode,
LocalFilePreviewResult,
LocalFilePreviewUrlParams,
} from './types';
@@ -92,6 +93,33 @@ const expandHomePath = (target: string): string => {
return target;
};
+/**
+ * Terminal reason of a filesystem failure while previewing a file, or
+ * `undefined` for one worth retrying (I/O error, busy, …). Shared with the
+ * desktop preview protocol so both transports classify the same way.
+ */
+export const localFilePreviewFailureCode = (
+ error: unknown,
+): LocalFilePreviewFailureCode | undefined => {
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
+ if (code === 'ENOENT' || code === 'ENOTDIR') return 'not_found';
+ if (code === 'EACCES' || code === 'EPERM') return 'forbidden';
+ return undefined;
+};
+
+/** A preview read refused because the file resolves outside the approved roots. */
+export const outsideWorkspacePreviewFailure = (): LocalFilePreviewResult => ({
+ code: 'forbidden',
+ error: 'File is outside the approved workspace',
+ success: false,
+});
+
+/** The failed result for a thrown preview error, with its terminal code if any. */
+export const toLocalFilePreviewFailure = (error: unknown): LocalFilePreviewResult => {
+ const code = localFilePreviewFailureCode(error);
+ return { ...(code && { code }), error: (error as Error).message, success: false };
+};
+
/** Resolve the real path, tolerating non-existent targets. */
const safeRealpath = async (target: string): Promise<string> => {
try {
@@ -119,16 +147,30 @@ export const defaultGetLocalFilePreview = async (
return { error: 'Missing working directory', success: false };
}
- const realRoot = await safeRealpath(expandHomePath(workingDirectory));
- const realFile = await safeRealpath(expandHomePath(filePath));
- const withinRoot = realFile === realRoot || realFile.startsWith(`${realRoot}${path.sep}`);
- if (!withinRoot) {
- return { error: 'File is outside the approved workspace', success: false };
+ const isWithin = (target: string, base: string) =>
+ target === base || target.startsWith(`${base}${path.sep}`);
+ const lexicalRoot = path.resolve(expandHomePath(workingDirectory));
+ const realRoot = await safeRealpath(lexicalRoot);
+ const lexicalFile = path.resolve(expandHomePath(filePath));
+ let realFile: string;
+ try {
+ realFile = await realpath(lexicalFile);
+ } catch (error) {
+ const failure = localFilePreviewFailureCode(error);
+ // A deleted file has no real path to contain; judge it by where it was.
+ if (
+ failure === 'not_found' &&
+ (isWithin(lexicalFile, lexicalRoot) || isWithin(lexicalFile, realRoot))
+ )
+ return { code: 'not_found', error: (error as Error).message, success: false };
+ realFile = lexicalFile;
}
+ const withinRoot = isWithin(realFile, realRoot);
+ if (!withinRoot) return outsideWorkspacePreviewFailure();
const stats = await stat(realFile);
if (!stats.isFile()) {
- return { error: 'Path is not a file', success: false };
+ return { code: 'not_found', error: 'Path is not a file', success: false };
}
// Oversized documents can only ever produce the content-less fallback —
@@ -158,7 +200,7 @@ export const defaultGetLocalFilePreview = async (
return { preview: serializePreviewFile(buffer, contentType), success: true };
} catch (error) {
- return { error: (error as Error).message, success: false };
+ return toLocalFilePreviewFailure(error);
}
};
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index a704fe068d9..0e20cccbae8 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -14,6 +14,7 @@ export {
defaultGetLocalFilePreview,
defaultReadExternalAssetForPublish,
EXTERNAL_PUBLISH_ASSET_MAX_BYTES,
+ localFilePreviewFailureCode,
} from './filePreview';
export { getKimiCodeQuota, type GetKimiCodeQuotaParams } from './kimiCodeQuota';
export {
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 28c0aab2736..73b87f1a164 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -157,7 +157,16 @@ export type LocalFilePreview =
| LocalFilePreviewText
| LocalFilePreviewUnsupported;
+/** Terminal reasons a file preview failed (see `LocalFilePreviewResult.code`). */
+export type LocalFilePreviewFailureCode = 'forbidden' | 'not_found';
+
export interface LocalFilePreviewResult {
+ /**
+ * Set when the failure is terminal for this file: `not_found` (deleted /
+ * moved) or `forbidden` (outside the approved roots, permission denied).
+ * Absent for transient failures, so a cached preview survives those.
+ */
+ code?: LocalFilePreviewFailureCode;
error?: string;
preview?: LocalFilePreview;
success: boolean;
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index 28396a75332..50675410680 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -10,6 +10,7 @@ export * from './git';
export * from './heterogeneousAgent';
export * from './imessageBridge';
export * from './localDatabase';
+export * from './localFilePreviewFailure';
export * from './localSystem';
export * from './mcpInstall';
export * from './notification';
diff --git a/packages/electron-client-ipc/src/types/localFilePreviewFailure.ts b/packages/electron-client-ipc/src/types/localFilePreviewFailure.ts
new file mode 100644
index 00000000000..0692f139d02
--- /dev/null
+++ b/packages/electron-client-ipc/src/types/localFilePreviewFailure.ts
@@ -0,0 +1,13 @@
+/** Terminal reasons a file preview failed. */
+export type LocalFilePreviewFailureCode = 'forbidden' | 'not_found';
+
+/** The failure half of a local file preview result. */
+export interface LocalFilePreviewFailure {
+ /**
+ * Set when the failure is terminal for this file: `not_found` (deleted /
+ * moved) or `forbidden` (outside the approved roots, permission denied).
+ * Absent for transient failures, so a cached preview survives those.
+ */
+ code?: LocalFilePreviewFailureCode;
+ error?: string;
+}
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 98ebd9898f7..e20f90aa8df 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -1,3 +1,5 @@
+import type { LocalFilePreviewFailure } from './localFilePreviewFailure';
+
// Define types for local file operations
export interface LocalFileItem {
contentType?: string;
@@ -204,8 +206,7 @@ export interface LocalFilePreviewUrlParams {
workingDirectory: string;
}
-export interface LocalFilePreviewUrlResult {
- error?: string;
+export interface LocalFilePreviewUrlResult extends LocalFilePreviewFailure {
success: boolean;
url?: string;
}
@@ -244,8 +245,7 @@ export type LocalFilePreview =
| LocalFilePreviewText
| LocalFilePreviewUnsupported;
-export interface LocalFilePreviewResult {
- error?: string;
+export interface LocalFilePreviewResult extends LocalFilePreviewFailure {
preview?: LocalFilePreview;
success: boolean;
}
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index a8715acdbbf..baf0d4cbd63 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -1,5 +1,7 @@
import { z } from 'zod';
+import type { DeviceLocalFilePreviewFailure } from './deviceFilePreviewFailure';
+
/** Structured context for an unavailable logical device. */
export interface DeviceUnavailableErrorData {
/** Stable machine-readable availability code. */
@@ -849,8 +851,7 @@ export type DeviceLocalFilePreview =
* file preview result but carries binary image content as base64 so it can cross
* the Gateway/RPC boundary.
*/
-export interface DeviceLocalFilePreviewResult {
- error?: string;
+export interface DeviceLocalFilePreviewResult extends DeviceLocalFilePreviewFailure {
preview?: DeviceLocalFilePreview;
success: boolean;
}
diff --git a/packages/types/src/deviceFilePreviewFailure.ts b/packages/types/src/deviceFilePreviewFailure.ts
new file mode 100644
index 00000000000..9127679c100
--- /dev/null
+++ b/packages/types/src/deviceFilePreviewFailure.ts
@@ -0,0 +1,6 @@
+/** The failure half of a device file preview result. */
+export interface DeviceLocalFilePreviewFailure {
+ /** Terminal failure: the file is gone (`not_found`) or may not be read (`forbidden`). */
+ code?: 'forbidden' | 'not_found';
+ error?: string;
+}
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 8b9ecf2e851..91b863b8c5f 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -18,6 +18,7 @@ export * from './creds';
export * from './dashboard';
export * from './dbMigration';
export * from './device';
+export * from './deviceFilePreviewFailure';
export * from './deviceMetric';
export * from './discover';
export * from './document';
diff --git a/src/features/AgentDocumentPage/routeMeta.ts b/src/features/AgentDocumentPage/routeMeta.ts
index 37285d4700e..c5a6718c0af 100644
--- a/src/features/AgentDocumentPage/routeMeta.ts
+++ b/src/features/AgentDocumentPage/routeMeta.ts
@@ -3,21 +3,18 @@ import { FileTextIcon } from 'lucide-react';
import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';
import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
import { routeMeta } from '@/spa/router/routeMeta';
+import { useDocumentStore } from '@/store/document';
import { getIdFromIdentifier } from '@/utils/identifier';
const AgentDocumentDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
const routeWorkspaceId = useRouteWorkspaceId(params);
const documentId = params.docId ? getIdFromIdentifier(params.docId, 'docs') : '';
- // Deduped against the Document Header's SWR fetch (same key), so this adds
- // no extra request — it just surfaces the title into the breadcrumb.
- const { data } = useClientDataSWR(documentId ? portalKeys.documentHeader(documentId) : null, () =>
- documentService.getDocumentById(documentId),
- );
+ // Shares the document's replica entry with the page and portal views, so this
+ // adds no extra request and a reload paints the persisted title right away.
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data } = useFetchDocumentDetail(documentId || undefined);
const document = matchesRouteWorkspace(data?.workspaceId, routeWorkspaceId) ? data : undefined;
usePublishDynamicRouteMeta(
diff --git a/src/features/AgentGoals/ProcessControl/DeliverableReader.tsx b/src/features/AgentGoals/ProcessControl/DeliverableReader.tsx
index 0f4feadfa53..146630e0202 100644
--- a/src/features/AgentGoals/ProcessControl/DeliverableReader.tsx
+++ b/src/features/AgentGoals/ProcessControl/DeliverableReader.tsx
@@ -24,9 +24,7 @@ import { useTranslation } from 'react-i18next';
import { EntityLinkHostProvider, useEntityMarkdown } from '@/features/EntityLink';
import { isSafeExternalUrl } from '@/features/Work/descriptors';
import { useActivityTime } from '@/hooks/useActivityTime';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
+import { useDocumentStore } from '@/store/document';
import type { DeliverableItem } from './deliverableList';
import {
@@ -171,11 +169,10 @@ const SidebarItem = ({
const DocumentBody = ({ documentId }: { documentId: string }) => {
const markdownProps = useEntityMarkdown();
- const { data: document, isLoading } = useClientDataSWR(
- portalKeys.documentHeader(documentId),
- () => documentService.getDocumentById(documentId),
- );
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: document, isHydrated, isLoading } = useFetchDocumentDetail(documentId);
+ if (isLoading && !isHydrated) return null;
if (isLoading)
return (
<Flexbox className={styles.doc} data-testid={'deliverable-reader-loading'} gap={12}>
diff --git a/src/features/AgentGoals/ProcessControl/GoalResult.tsx b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
index 49961e1618f..23669913f86 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResult.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
@@ -5,9 +5,7 @@ import { useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useEntityMarkdown } from '@/features/EntityLink';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
+import { useDocumentStore } from '@/store/document';
import GoalAcceptanceHierarchy from './GoalAcceptanceHierarchy';
import { pickFinalDeliverable } from './goalAcceptanceReport';
@@ -41,11 +39,10 @@ import { useGoalResultData } from './useGoalResultData';
const FinalDocument = ({ documentId }: { documentId: string }) => {
// The graph carries only the document id; its content is read for the page.
const markdownProps = useEntityMarkdown();
- const { data: document, isLoading } = useClientDataSWR(
- portalKeys.documentHeader(documentId),
- () => documentService.getDocumentById(documentId),
- );
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: document, isHydrated, isLoading } = useFetchDocumentDetail(documentId);
+ if (isLoading && !isHydrated) return null;
if (isLoading)
return (
<Flexbox gap={10}>
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 6fc737d68ff..37b2fb2eee5 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -61,9 +61,9 @@ const mockDocumentMeta = vi.hoisted(() => ({
},
}));
-vi.mock('@/libs/swr', () => ({
- useClientDataSWR: () => ({ data: mockDocumentMeta.current }),
-}));
+const mockDocumentError = vi.hoisted(() => ({ current: undefined as Error | undefined }));
+/** The persisted row has been read; `false` = the replica is still hydrating. */
+const mockDocumentHydrated = vi.hoisted(() => ({ current: true }));
const mockUpdateDocument = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
@@ -119,8 +119,18 @@ const mockDocumentState = vi.hoisted(() => ({
'document-1': {},
},
internal_dispatchDocument: vi.fn(),
+ beginDocumentDetailPatch: vi.fn(() => vi.fn()),
performSave: vi.fn(),
updateSkillFrontmatter: vi.fn(),
+ // The document's replica entry, as the store's read hook reports it.
+ useFetchDocumentDetail: vi.fn(() => ({
+ data: mockDocumentMeta.current,
+ error: mockDocumentError.current,
+ isHydrated: mockDocumentHydrated.current,
+ isLoading: mockDocumentMeta.current === undefined && !mockDocumentError.current,
+ isValidating: false,
+ mutate: vi.fn(),
+ })),
},
}));
@@ -129,6 +139,20 @@ vi.mock('@/store/document', () => ({
}));
describe('DocumentBody', () => {
+ afterEach(() => {
+ mockDocumentError.current = undefined;
+ mockDocumentHydrated.current = true;
+ });
+
+ it('paints nothing while the persisted document is still being read', () => {
+ mockDocumentMeta.current = undefined as never;
+ mockDocumentHydrated.current = false;
+
+ const { container } = render(<DocumentBody />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
/** @example A file-backed document previews its upload and keeps the portal actions. */
it('shows the original upload without mounting either editor', () => {
// ROOT CAUSE:
@@ -156,6 +180,15 @@ describe('DocumentBody', () => {
vi.useRealTimers();
});
+ it('keeps the cached document on screen when the background refresh fails', () => {
+ mockDocumentMeta.current = { content: 'cached log', filename: 'topic_call.txt' };
+ mockDocumentError.current = new Error('Failed to fetch');
+
+ render(<DocumentBody />);
+
+ expect(screen.getByTestId('highlight-editor')).toHaveValue('cached log');
+ });
+
it('renders highlight editor for non-markdown files', () => {
mockDocumentMeta.current = { content: 'raw log content', filename: 'topic_call.txt' };
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index a3f7cbe3c8c..6e0c2baf448 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -20,9 +20,6 @@ import Loading from '@/components/Loading/CircleLoading';
import FileNotFound from '@/features/FileNotFound';
import { FileDocumentPreview } from '@/features/FileViewer/FileDocumentPreview';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
import { useDocumentStore } from '@/store/document';
import { getDocumentRenderMode } from '@/utils/documentRenderMode';
import {
@@ -176,16 +173,16 @@ interface HighlightEditorProps {
content: string;
documentId: string;
filename: string;
- onSaved: (newContent: string, updatedAt?: string) => void;
+ onSaveStart: () => (newContent: string, updatedAt?: string) => void;
updatedAt?: Date;
}
const HighlightEditor = memo<HighlightEditorProps>(
- ({ content, documentId, filename, onSaved, updatedAt }) => {
+ ({ content, documentId, filename, onSaveStart, updatedAt }) => {
const { editingValue, handleChange, handleSave } = useHighlightSave({
content,
documentId,
- onSaved,
+ onSaveStart,
updatedAt,
});
@@ -233,30 +230,27 @@ const DocumentBody = memo(() => {
);
const isSkillMarkdown = contentFormat === 'skillMarkdown';
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const beginDocumentDetailPatch = useDocumentStore((s) => s.beginDocumentDetailPatch);
const {
data: documentMeta,
error: documentError,
+ isHydrated: documentHydrated,
isLoading: documentLoading,
mutate: mutateDocumentMeta,
- } = useClientDataSWR(documentId ? portalKeys.documentHeader(documentId) : null, () =>
- documentService.getDocumentById(documentId!),
- );
+ } = useFetchDocumentDetail(documentId);
const renderMode = documentMeta
? getDocumentRenderMode(documentMeta)
: { mode: 'editor' as const };
- const handleHighlightSaved = useCallback(
- (saved: string, updatedAt?: string) => {
- mutateDocumentMeta(
- (prev) =>
- prev
- ? { ...prev, content: saved, ...(updatedAt ? { updatedAt: new Date(updatedAt) } : {}) }
- : prev,
- { revalidate: false },
- );
- },
- [mutateDocumentMeta],
- );
+ // Captured when the save starts, so a save that settles after an account /
+ // workspace switch never lands in the new identity's replica.
+ const handleHighlightSaveStart = useCallback(() => {
+ if (!documentId) return () => {};
+ const commit = beginDocumentDetailPatch(documentId);
+ return (saved: string, updatedAt?: string) =>
+ commit({ content: saved, ...(updatedAt ? { updatedAt: new Date(updatedAt) } : {}) });
+ }, [documentId, beginDocumentDetailPatch]);
const editorContent = (
<>
@@ -272,7 +266,7 @@ const DocumentBody = memo(() => {
filename={documentMeta?.filename ?? ''}
key={documentId}
updatedAt={documentMeta?.updatedAt}
- onSaved={handleHighlightSaved}
+ onSaveStart={handleHighlightSaveStart}
/>
) : (
<EditorCanvas />
@@ -280,8 +274,13 @@ const DocumentBody = memo(() => {
</>
);
- if (documentLoading) return <Loading />;
- if (documentError)
+ // The persisted row is still being read: paint nothing rather than a spinner
+ // that the cached document replaces a few frames later.
+ if (documentLoading) return documentHydrated ? <Loading /> : null;
+ // The document is a persisted replica (stale-while-revalidate): a transient
+ // refresh failure keeps the cached document on screen. A denial (FORBIDDEN /
+ // UNAUTHORIZED) purges the cached row, so it lands here with no data.
+ if (documentError && !documentMeta)
return (
<AsyncError
error={documentError}
diff --git a/src/features/Portal/Document/useHighlightSave.test.ts b/src/features/Portal/Document/useHighlightSave.test.ts
index 9d5fa2bbd64..48d3e3d4720 100644
--- a/src/features/Portal/Document/useHighlightSave.test.ts
+++ b/src/features/Portal/Document/useHighlightSave.test.ts
@@ -2,8 +2,6 @@ import { toast } from '@lobehub/ui';
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { portalKeys } from '@/libs/swr/keys';
-
import { useHighlightSave } from './useHighlightSave';
vi.mock('@lobehub/ui', async (importOriginal) => ({
@@ -40,7 +38,12 @@ describe('useHighlightSave', () => {
const onSaved = vi.fn();
const { result } = renderHook(() =>
- useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),
+ useHighlightSave({
+ content: 'before',
+ documentId: 'doc-1',
+ onSaveStart: () => onSaved,
+ updatedAt,
+ }),
);
act(() => result.current.handleChange('after'));
@@ -55,12 +58,45 @@ describe('useHighlightSave', () => {
expect(onSaved).toHaveBeenCalledWith('after', '2024-01-02T00:00:00.000Z');
});
+ it('starts the commit before the write is awaited', async () => {
+ let answer: (value: unknown) => void = () => {};
+ mockUpdateDocument.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const onSaved = vi.fn();
+ const onSaveStart = vi.fn(() => onSaved);
+
+ const { result } = renderHook(() =>
+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaveStart }),
+ );
+
+ act(() => result.current.handleChange('after'));
+ let save: Promise<void> = Promise.resolve();
+ act(() => {
+ save = result.current.handleSave();
+ });
+ await act(async () => {});
+
+ // The caller captures the identity the write runs under before it settles.
+ expect(onSaveStart).toHaveBeenCalledTimes(1);
+ expect(onSaved).not.toHaveBeenCalled();
+
+ await act(async () => {
+ answer({ updatedAt: '2024-01-02T00:00:00.000Z' });
+ await save;
+ });
+ expect(onSaved).toHaveBeenCalledWith('after', '2024-01-02T00:00:00.000Z');
+ });
+
it('omits expectedUpdatedAt when the row has no known version yet', async () => {
mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-02T00:00:00.000Z' });
const onSaved = vi.fn();
const { result } = renderHook(() =>
- useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt: undefined }),
+ useHighlightSave({
+ content: 'before',
+ documentId: 'doc-1',
+ onSaveStart: () => onSaved,
+ updatedAt: undefined,
+ }),
);
act(() => result.current.handleChange('after'));
@@ -79,7 +115,12 @@ describe('useHighlightSave', () => {
const onSaved = vi.fn();
const { result } = renderHook(() =>
- useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),
+ useHighlightSave({
+ content: 'before',
+ documentId: 'doc-1',
+ onSaveStart: () => onSaved,
+ updatedAt,
+ }),
);
act(() => result.current.handleChange('after'));
@@ -101,7 +142,12 @@ describe('useHighlightSave', () => {
const { result, rerender } = renderHook(
({ updatedAt }: { updatedAt: Date }) =>
- useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),
+ useHighlightSave({
+ content: 'before',
+ documentId: 'doc-1',
+ onSaveStart: () => onSaved,
+ updatedAt,
+ }),
{ initialProps: { updatedAt: new Date('2024-01-01T00:00:00.000Z') } },
);
@@ -122,14 +168,18 @@ describe('useHighlightSave', () => {
const onSaved = vi.fn();
const { result } = renderHook(() =>
- useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),
+ useHighlightSave({
+ content: 'before',
+ documentId: 'doc-1',
+ onSaveStart: () => onSaved,
+ updatedAt,
+ }),
);
act(() => result.current.handleChange('after'));
await act(() => result.current.handleSave());
expect(mockInvalidateDocumentMutation).toHaveBeenCalledWith({ documentId: 'doc-1' });
- expect(mockMutate).toHaveBeenCalledWith(portalKeys.documentHeader('doc-1'));
expect(toast.error).toHaveBeenCalled();
expect(onSaved).not.toHaveBeenCalled();
expect(result.current.editingValue).toBe('before');
@@ -137,7 +187,7 @@ describe('useHighlightSave', () => {
it('adopts a refreshed remote body instead of submitting the old draft with its version', async () => {
const onSaved = vi.fn();
const { result, rerender } = renderHook(
- (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaved }),
+ (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaveStart: () => onSaved }),
{ initialProps: { content: 'base', updatedAt: new Date('2024-01-01') } },
);
act(() => result.current.handleChange('local draft'));
@@ -149,7 +199,7 @@ describe('useHighlightSave', () => {
it('keeps the draft after a metadata-only remote refresh', async () => {
const { result, rerender } = renderHook(
- (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaved: vi.fn() }),
+ (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaveStart: () => vi.fn() }),
{ initialProps: { content: 'base', updatedAt: new Date('2024-01-01') } },
);
act(() => result.current.handleChange('local draft'));
@@ -176,7 +226,7 @@ describe('useHighlightSave', () => {
useHighlightSave({
content: 'base',
documentId: 'doc-1',
- onSaved: vi.fn(),
+ onSaveStart: () => vi.fn(),
updatedAt: new Date('2024-01-01'),
}),
);
@@ -222,7 +272,7 @@ describe('useHighlightSave', () => {
useHighlightSave({
content: 'base',
documentId: 'doc-1',
- onSaved: vi.fn(),
+ onSaveStart: () => vi.fn(),
updatedAt: new Date('2024-01-01'),
}),
);
@@ -259,7 +309,7 @@ describe('useHighlightSave', () => {
}),
);
const { result, rerender } = renderHook(
- (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaved: vi.fn() }),
+ (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaveStart: () => vi.fn() }),
{ initialProps: { content: 'base', updatedAt: new Date('2024-01-01') } },
);
act(() => result.current.handleChange('old draft'));
diff --git a/src/features/Portal/Document/useHighlightSave.ts b/src/features/Portal/Document/useHighlightSave.ts
index 6cb6c00400c..1df1267fa8c 100644
--- a/src/features/Portal/Document/useHighlightSave.ts
+++ b/src/features/Portal/Document/useHighlightSave.ts
@@ -6,8 +6,6 @@ import { debounce } from 'es-toolkit/compat';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { mutate } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import { invalidateDocumentMutation } from '@/services/document/invalidation';
@@ -17,7 +15,12 @@ const isConflictError = (error: unknown) =>
export interface UseHighlightSaveParams {
content: string;
documentId: string;
- onSaved: (content: string, updatedAt?: string) => void;
+ /**
+ * Called when a write starts; returns the commit for its confirmed result.
+ * The caller captures what the write belongs to (e.g. the active identity)
+ * before the request is awaited.
+ */
+ onSaveStart: () => (content: string, updatedAt?: string) => void;
updatedAt?: Date;
}
@@ -30,7 +33,7 @@ export interface UseHighlightSaveResult {
export const useHighlightSave = ({
content,
documentId,
- onSaved,
+ onSaveStart,
updatedAt,
}: UseHighlightSaveParams): UseHighlightSaveResult => {
const { t } = useTranslation('portal');
@@ -39,14 +42,14 @@ export const useHighlightSave = ({
const bufferRef = useRef(buffer);
const documentIdRef = useRef(documentId);
- const onSavedRef = useRef(onSaved);
+ const onSaveStartRef = useRef(onSaveStart);
const expectedUpdatedAtRef = useRef(updatedAt);
const baseContentRef = useRef(content);
const pendingSaveRef = useRef<Promise<void> | undefined>(undefined);
const tRef = useRef(t);
bufferRef.current = buffer;
documentIdRef.current = documentId;
- onSavedRef.current = onSaved;
+ onSaveStartRef.current = onSaveStart;
tRef.current = t;
const saveBuffer = useCallback(async (source: 'manual' | 'autosave') => {
@@ -54,6 +57,7 @@ export const useHighlightSave = ({
if (toWrite === undefined) return;
const expectedUpdatedAt = expectedUpdatedAtRef.current;
try {
+ const commitSaved = onSaveStartRef.current();
const result = await documentService.updateDocument({
content: toWrite,
id: documentIdRef.current,
@@ -66,7 +70,7 @@ export const useHighlightSave = ({
expectedUpdatedAtRef.current = savedAt;
}
baseContentRef.current = toWrite;
- onSavedRef.current(toWrite, result?.updatedAt);
+ commitSaved(toWrite, result?.updatedAt);
if (bufferRef.current === toWrite) {
bufferRef.current = undefined;
setBuffer(undefined);
@@ -77,9 +81,9 @@ export const useHighlightSave = ({
if (expectedUpdatedAtRef.current?.getTime() !== expectedUpdatedAt?.getTime()) return;
bufferRef.current = undefined;
setBuffer(undefined);
+ // Refreshes the document's replica entry, which the portal body reads.
await Promise.allSettled([
invalidateDocumentMutation({ documentId: documentIdRef.current }),
- mutate(portalKeys.documentHeader(documentIdRef.current)),
]);
toast.error(tRef.current('document.saveConflict'));
return;
diff --git a/src/features/Portal/Document/useMarkdownExport.test.ts b/src/features/Portal/Document/useMarkdownExport.test.ts
index ded4498737f..1680f23a26a 100644
--- a/src/features/Portal/Document/useMarkdownExport.test.ts
+++ b/src/features/Portal/Document/useMarkdownExport.test.ts
@@ -18,13 +18,12 @@ vi.mock('@lobehub/ui', () => ({
toast: { error: vi.fn(), success: mocks.toastSuccess },
}));
-vi.mock('@/libs/swr', () => ({
- useClientDataSWR: () => ({ data: mocks.documentMeta }),
-}));
-
vi.mock('@/store/document', () => ({
useDocumentStore: (selector: (s: unknown) => unknown) =>
- selector({ documents: { doc_1: { content: mocks.storeContent } } }),
+ selector({
+ documents: { doc_1: { content: mocks.storeContent } },
+ useFetchDocumentDetail: () => ({ data: mocks.documentMeta }),
+ }),
}));
describe('useMarkdownExport', () => {
diff --git a/src/features/Portal/Document/useMarkdownExport.ts b/src/features/Portal/Document/useMarkdownExport.ts
index f712087599b..faf5364bce1 100644
--- a/src/features/Portal/Document/useMarkdownExport.ts
+++ b/src/features/Portal/Document/useMarkdownExport.ts
@@ -4,9 +4,6 @@ import { isDesktop } from '@lobechat/const';
import { toast } from '@lobehub/ui';
import { useTranslation } from 'react-i18next';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
import { useDocumentStore } from '@/store/document';
import { getDocumentRenderMode } from '@/utils/documentRenderMode';
@@ -19,17 +16,15 @@ import { getDocumentRenderMode } from '@/utils/documentRenderMode';
export const useMarkdownExport = (documentId: string | undefined) => {
const { t } = useTranslation('file');
- // The editor canvas keeps the live buffer in the document store; the SWR
- // meta reflects the last persisted markdown. Prefer the store (fresher) —
- // including an intentionally emptied buffer — and fall back to the SWR copy
- // only while the editor has not produced a buffer for this document.
+ // The editor canvas keeps the live buffer in the document store; the detail
+ // replica reflects the last persisted markdown. Prefer the store (fresher) —
+ // including an intentionally emptied buffer — and fall back to the replica
+ // copy only while the editor has not produced a buffer for this document.
const storeContent = useDocumentStore((s) =>
documentId ? s.documents[documentId]?.content : undefined,
);
- const { data: documentMeta } = useClientDataSWR(
- documentId ? portalKeys.documentHeader(documentId) : null,
- () => documentService.getDocumentById(documentId!),
- );
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: documentMeta } = useFetchDocumentDetail(documentId);
if (!documentMeta || getDocumentRenderMode(documentMeta).mode === 'file') return;
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.test.ts b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
index 95f9aee29e2..a122da38f68 100644
--- a/src/features/Portal/Document/usePortalDocumentHeader.test.ts
+++ b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
@@ -1,5 +1,18 @@
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+/**
+ * @vitest-environment happy-dom
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { useDocumentStore } from '@/store/document';
+import { initialDocumentDetailSliceState } from '@/store/document/slices/document';
import {
resolvePortalDocumentPath,
@@ -19,25 +32,35 @@ const mockDocumentMeta = vi.hoisted(() => ({
},
}));
-const mockMutate = vi.hoisted(() => vi.fn());
-
-vi.mock('@/libs/swr', () => ({
- useClientDataSWR: () => ({
- data: mockDocumentMeta.current,
- isLoading: false,
- mutate: mockMutate,
- }),
-}));
-
const mockUpdateDocument = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const mockGetDocumentById = vi.hoisted(() => vi.fn());
vi.mock('@/services/document', () => ({
documentService: {
- getDocumentById: vi.fn(),
+ getDocumentById: mockGetDocumentById,
updateDocument: mockUpdateDocument,
},
}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => null,
+ useActiveWorkspaceId: () => null,
+}));
+
+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 mockInvalidate = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock('@/services/document/invalidation', () => ({
@@ -90,21 +113,45 @@ vi.mock('@/hooks/useAppOrigin', () => ({
useAppOrigin: () => 'https://app.lobehub.com',
}));
-/** Title the SWR cache holds after the most recent optimistic write/rollback. */
-const lastCachedTitle = () => mockMutate.mock.lastCall?.[0]({ title: '' }).title;
+/** Title the document's replica entry holds after the most recent optimistic write/rollback. */
+const lastCachedTitle = () =>
+ useDocumentStore.getState().documentDetailMap['document-1']?.document?.title;
+
+/** Mount the hook and wait for the document row to land in the replica. */
+const renderTitle = async () => {
+ const rendered = renderHook(() => usePortalDocumentTitle(), { wrapper });
+ await waitFor(() => expect(rendered.result.current.isLoading).toBe(false));
+ return rendered;
+};
describe('usePortalDocumentTitle', () => {
+ let scope = '';
+
beforeEach(() => {
mockDocumentMeta.current = { filename: '开营筹备清单.md', title: '开营筹备清单' };
mockChatState.current.portalStack[0].agentDocumentId = 'agent-document-1';
mockUpdateDocument.mockClear();
- mockMutate.mockClear();
mockInvalidate.mockClear();
toastError.mockClear();
+ mockGetDocumentById.mockReset();
+ mockGetDocumentById.mockImplementation(async () => ({
+ id: 'document-1',
+ ...mockDocumentMeta.current,
+ }));
+ // A fresh identity per test, so no persisted row carries over.
+ scope = `portal-title-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);
+ act(() => useDocumentStore.setState(initialDocumentDetailSliceState));
});
- it('exposes the saved title (title before filename) and unlocks renaming', () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('exposes the saved title (title before filename) and unlocks renaming', async () => {
+ const { result } = await renderTitle();
expect(result.current.savedTitle).toBe('开营筹备清单');
expect(result.current.metaLocked).toBe(false);
@@ -112,7 +159,7 @@ describe('usePortalDocumentTitle', () => {
});
it('saves a trimmed title through the document service', async () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
await act(async () => {
await result.current.saveTitle(' 开营筹备清单 V2 ');
@@ -126,7 +173,7 @@ describe('usePortalDocumentTitle', () => {
});
it('skips the write for an empty or unchanged title', async () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
await act(async () => {
await result.current.saveTitle(' ');
@@ -134,12 +181,12 @@ describe('usePortalDocumentTitle', () => {
});
expect(mockUpdateDocument).not.toHaveBeenCalled();
- expect(mockMutate).not.toHaveBeenCalled();
+ expect(lastCachedTitle()).toBe('开营筹备清单');
});
it('rolls the optimistic title back when the write fails', async () => {
mockUpdateDocument.mockRejectedValueOnce(new Error('network'));
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
// Rejects after rolling back, so the rename dialog stays open for a retry.
await act(async () => {
@@ -160,7 +207,7 @@ describe('usePortalDocumentTitle', () => {
}),
)
.mockResolvedValueOnce(undefined);
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
// First (slow) rename — fire it without awaiting.
void result.current.saveTitle('重命名一');
@@ -201,7 +248,7 @@ describe('usePortalDocumentTitle', () => {
}),
)
.mockResolvedValueOnce(undefined);
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
void result.current.saveTitle('重命名一');
const secondSave = result.current.saveTitle('重命名二');
@@ -224,7 +271,7 @@ describe('usePortalDocumentTitle', () => {
});
it('revalidates the agent-document list after a successful rename', async () => {
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
await act(async () => {
await result.current.saveTitle('开营筹备清单 V2');
@@ -243,7 +290,7 @@ describe('usePortalDocumentTitle', () => {
title: 'SKILL.md',
};
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
expect(result.current.metaLocked).toBe(true);
await act(async () => {
@@ -252,10 +299,10 @@ describe('usePortalDocumentTitle', () => {
expect(mockUpdateDocument).not.toHaveBeenCalled();
});
- it('is not loading for a loaded empty-title document', () => {
+ it('is not loading for a loaded empty-title document', async () => {
mockDocumentMeta.current = { filename: '', title: '' };
- const { result } = renderHook(() => usePortalDocumentTitle());
+ const { result } = await renderTitle();
expect(result.current.isLoading).toBe(false);
expect(result.current.savedTitle).toBe('');
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.ts b/src/features/Portal/Document/usePortalDocumentHeader.ts
index b4f509046e7..11112a55d6b 100644
--- a/src/features/Portal/Document/usePortalDocumentHeader.ts
+++ b/src/features/Portal/Document/usePortalDocumentHeader.ts
@@ -8,11 +8,10 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspa
import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useSingleton } from '@/hooks/useSingleton';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import { invalidateDocumentMutation } from '@/services/document/invalidation';
import { useAgentStore } from '@/store/agent';
+import { useDocumentStore } from '@/store/document';
import { getDocumentRenderMode } from '@/utils/documentRenderMode';
import { standardizeIdentifier } from '@/utils/identifier';
import { isSkillMarkdownDocument } from '@/utils/skillMarkdown';
@@ -31,13 +30,9 @@ export const usePortalDocumentTitle = () => {
const documentId = useResolvedDocumentId();
const agentId = useAgentStore((s) => s.activeAgentId);
- const {
- data: document,
- isLoading,
- mutate: mutateDocument,
- } = useClientDataSWR(documentId ? portalKeys.documentHeader(documentId) : null, () =>
- documentService.getDocumentById(documentId!),
- );
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const optimisticDocumentDetail = useDocumentStore((s) => s.optimisticDocumentDetail);
+ const { data: document, isLoading } = useFetchDocumentDetail(documentId);
const savedTitle = useMemo(
() => document?.title || document?.filename || '',
@@ -58,9 +53,9 @@ export const usePortalDocumentTitle = () => {
// 1. `saveChain` queues the SERVER calls — updateDocument mutations run
// in submit order, so a slow first request can never land after (and
// overwrite) a newer rename.
- // 2. `saveTicketRef` gates the CLIENT-side settlement — only the newest
- // save may touch the SWR cache, so a rejected older request cannot roll
- // back a newer intent.
+ // 2. The replica's optimistic overlays settle the CLIENT state — a rejected
+ // older request rolls back only its own overlay, never a newer intent —
+ // and `saveTicketRef` keeps the follow-up (refresh / toast) to the newest.
const saveChain = useSingleton(() => ({ current: Promise.resolve() as Promise<unknown> }));
const saveTicketRef = useRef(0);
@@ -70,46 +65,34 @@ export const usePortalDocumentTitle = () => {
// Empty or unchanged titles are not written.
if (metaLocked || !nextTitle || nextTitle === savedTitle || !documentId) return;
- // Claim the newest save; only this ticket may settle the client state.
+ // Claim the newest save; only this ticket may run the follow-up.
const ticket = ++saveTicketRef.current;
- const previousTitle = savedTitle;
-
- // Optimistic update, then reconcile with the server response.
- mutateDocument((prev) => (prev ? { ...prev, title: nextTitle } : prev), {
- revalidate: false,
- });
// Queue the server write behind any in-flight rename so the server sees
// the titles in the order the user submitted them — a slow first request
// can no longer land last and overwrite the newer title.
const write = saveChain.current
.catch(() => undefined)
- .then(() =>
- documentService.updateDocument({ id: documentId, title: nextTitle }).then((result) => {
- if (ticket !== saveTicketRef.current) return result;
- // Revalidate the caches other surfaces read titles from
- // (working-sidebar tree, standalone document page read
- // the agent document-list replica), mirroring the full-page editor's
- // post-rename list refresh.
- void invalidateDocumentMutation({ agentId: agentId ?? undefined, documentId });
- return result;
- }),
- );
+ .then(() => documentService.updateDocument({ id: documentId, title: nextTitle }));
saveChain.current = write;
try {
- await write;
+ // Optimistic update, then reconcile with the server response.
+ await optimisticDocumentDetail(documentId, { title: nextTitle }, () => write);
+ if (ticket !== saveTicketRef.current) return;
+ // Revalidate the caches other surfaces read titles from
+ // (working-sidebar tree, standalone document page read the agent
+ // document-list replica), mirroring the full-page editor's
+ // post-rename list refresh.
+ void invalidateDocumentMutation({ agentId: agentId ?? undefined, documentId });
} catch (error) {
if (ticket !== saveTicketRef.current) return;
toast.error(t('operationFailed', { ns: 'common' }));
- mutateDocument((prev) => (prev ? { ...prev, title: previousTitle } : prev), {
- revalidate: false,
- });
// Reject so the rename dialog stays open with the typed title for a
// retry instead of closing as if the write had landed.
throw error;
}
},
- [agentId, documentId, metaLocked, mutateDocument, savedTitle, saveChain, t],
+ [agentId, documentId, metaLocked, optimisticDocumentDetail, savedTitle, saveChain, t],
);
return {
diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsx
index 25474267228..62ff6a1a165 100644
--- a/src/features/Portal/LocalFile/Body.test.tsx
+++ b/src/features/Portal/LocalFile/Body.test.tsx
@@ -2,7 +2,6 @@ import { render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { localFileKeys } from '@/libs/swr/keys';
import { createLocalFileScopeKey, createLocalFileTabId } from '@/store/chat/slices/portal/helpers';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
@@ -95,6 +94,28 @@ vi.mock('@/services/projectFile', () => ({
projectFileService: mockProjectFileService,
}));
+const mockUseFetchPreview = vi.hoisted(() => vi.fn());
+const mockPreview = vi.hoisted(() => ({ current: undefined as unknown }));
+
+vi.mock('@/store/localFilePreview', () => ({
+ useLocalFilePreview: (target: unknown) => (target ? mockPreview.current : undefined),
+ useLocalFilePreviewStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ beginSave: vi.fn(() => vi.fn()),
+ refreshPreview: vi.fn(),
+ useFetchPreview: mockUseFetchPreview,
+ }),
+}));
+
+const syncResult = (overrides: Record<string, unknown> = {}) => ({
+ error: undefined,
+ isHydrated: true,
+ isLoading: false,
+ isValidating: false,
+ revalidate: vi.fn(),
+ ...overrides,
+});
+
vi.mock('@/utils/skillMarkdown', () => ({
parseSkillMarkdownFrontmatter: (content: string) => ({ body: content }),
parseSkillMarkdownMetadata: () => [],
@@ -227,10 +248,10 @@ describe('LocalFile Body', () => {
mockIsHtmlFile.mockReset();
mockIsHtmlFile.mockReturnValue(false);
mockUseClientDataSWR.mockClear();
- mockUseClientDataSWR.mockReturnValue({
- isLoading: true,
- mutate: vi.fn(),
- });
+ mockUseClientDataSWR.mockReturnValue({ isLoading: true, mutate: vi.fn() });
+ mockPreview.current = undefined;
+ mockUseFetchPreview.mockReset();
+ mockUseFetchPreview.mockReturnValue(syncResult({ isLoading: true }));
});
it('closes the LocalFile portal when the current project has no visible local-file tabs', async () => {
@@ -275,31 +296,61 @@ describe('LocalFile Body', () => {
expect(screen.getByTestId('loading')).toBeInTheDocument();
expect(mockClearPortalStack).not.toHaveBeenCalled();
- expect(mockUseClientDataSWR).toHaveBeenCalledWith(
- localFileKeys.preview({
+ expect(mockUseFetchPreview).toHaveBeenCalledWith(
+ {
allowExternalFile: true,
+ deviceId: undefined,
filePath: '/tmp/worktree-switcher-demo.html',
+ sandboxTopicId: undefined,
workingDirectory: '/tmp',
- }),
- expect.any(Function),
- { revalidateOnFocus: false },
+ },
+ true,
);
+ });
- // The toolbar breadcrumb registers its own SWR call, so pick the preview
- // fetcher by its key rather than by position.
- const previewCall = mockUseClientDataSWR.mock.calls.findLast((call) =>
- String(call[0]).includes('/tmp/worktree-switcher-demo.html'),
- );
- void (previewCall?.[1] as () => Promise<unknown>)();
- expect(mockProjectFileService.getLocalFilePreview).toHaveBeenCalledWith({
- allowExternalFile: true,
- deviceId: undefined,
- path: '/tmp/worktree-switcher-demo.html',
- workingDirectory: '/tmp',
- });
+ it('paints nothing — not a spinner — while the persisted preview is still being read', () => {
+ mockChatState.current = createChatState('topic-a');
+ mockUseFetchPreview.mockReturnValue(syncResult({ isHydrated: false, isLoading: true }));
+
+ render(<Body />);
+
+ expect(screen.queryByTestId('loading')).toBeNull();
+ expect(screen.queryByText('workingPanel.localFile.error')).toBeNull();
});
- it('requests workspace resources for a desktop HTML file and passes its base URL to preview', () => {
+ it('paints the persisted text preview before the refresh answers', () => {
+ mockChatState.current = createChatState('topic-a');
+ mockPreview.current = { content: 'cached', contentType: 'text/plain', type: 'text' };
+ mockUseFetchPreview.mockReturnValue(syncResult({ isValidating: true }));
+
+ render(<Body />);
+
+ expect(screen.getByTestId('code-editor')).toBeInTheDocument();
+ expect(screen.queryByTestId('loading')).toBeNull();
+ });
+
+ it('keeps a cached text preview on screen when the background refresh fails', () => {
+ mockChatState.current = createChatState('topic-a');
+ mockPreview.current = { content: 'cached', contentType: 'text/plain', type: 'text' };
+ mockUseFetchPreview.mockReturnValue(syncResult({ error: new Error('Failed to fetch') }));
+
+ render(<Body />);
+
+ expect(screen.getByTestId('code-editor')).toBeInTheDocument();
+ expect(screen.queryByText('workingPanel.localFile.error')).toBeNull();
+ });
+
+ it('surfaces a refresh failure over a cached non-text preview', () => {
+ mockChatState.current = createChatState('topic-a');
+ mockPreview.current = { blob: new Blob(['png']), contentType: 'image/png', type: 'image' };
+ mockUseFetchPreview.mockReturnValue(syncResult({ error: new Error('File not found') }));
+
+ render(<Body />);
+
+ expect(screen.getByText('workingPanel.localFile.error')).toBeInTheDocument();
+ });
+
+ it('passes the HTML preview its resource base URL', () => {
const htmlFileId = createLocalFileTabId({
filePath: '/project-a/pages/index.html',
workingDirectory: '/project-a',
@@ -317,33 +368,16 @@ describe('LocalFile Body', () => {
},
],
};
- mockUseClientDataSWR.mockReturnValue({
- data: {
- content: '<link rel="stylesheet" href="../assets/app.css">',
- contentType: 'text/html',
- resourceBaseUrl: 'localfile://preview-session/pages/',
- type: 'text',
- },
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- });
+ mockPreview.current = {
+ content: '<link rel="stylesheet" href="../assets/app.css">',
+ contentType: 'text/html',
+ resourceBaseUrl: 'localfile://preview-session/pages/',
+ type: 'text',
+ };
+ mockUseFetchPreview.mockReturnValue(syncResult());
render(<Body />);
- // The toolbar breadcrumb registers its own SWR call, so pick the preview
- // fetcher by its key rather than by position.
- const previewCall = mockUseClientDataSWR.mock.calls.findLast((call) =>
- String(call[0]).includes('/project-a/pages/index.html'),
- );
- void (previewCall?.[1] as () => Promise<unknown>)();
- expect(mockProjectFileService.getLocalFilePreview).toHaveBeenCalledWith({
- allowExternalFile: undefined,
- deviceId: undefined,
- path: '/project-a/pages/index.html',
- resourceScope: 'workspace',
- workingDirectory: '/project-a',
- });
expect(screen.getByTitle('html-preview')).toHaveAttribute(
'data-base-url',
'localfile://preview-session/pages/',
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index e779cd353f7..4e190daaf4d 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -23,14 +23,11 @@ import {
PublishHtmlArtifactProvider,
PublishHtmlArtifactTrigger,
} from '@/features/Portal/LocalFile/PublishHtmlArtifactButton';
-import { useClientDataSWR } from '@/libs/swr';
-import { localFileKeys } from '@/libs/swr/keys';
-import { cloudSandboxService } from '@/services/cloudSandbox';
import { localFileService } from '@/services/electron/localFileService';
-import { type LocalFilePreview, projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { createLocalFileTabId } from '@/store/chat/slices/portal/helpers';
+import { useLocalFilePreview, useLocalFilePreviewStore } from '@/store/localFilePreview';
import {
parseSkillMarkdownFrontmatter,
parseSkillMarkdownMetadata,
@@ -150,7 +147,8 @@ interface TextPreviewPaneProps {
ext: string;
filePath: string;
onReload?: () => Promise<unknown> | void;
- onSaved?: (savedContent: string) => void;
+ /** Called when a save starts; returns the commit for the saved body. */
+ onSaveStart?: () => (savedContent: string) => void;
readOnly?: boolean;
reloading?: boolean;
resourceBaseUrl?: string;
@@ -167,7 +165,7 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
ext,
filePath,
onReload,
- onSaved,
+ onSaveStart,
readOnly = false,
reloading = false,
resourceBaseUrl,
@@ -210,12 +208,13 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
if (readOnly) return;
try {
+ const commitSaved = onSaveStart?.();
const saved = await saveLocalFile({ deviceId, filePath, workingDirectory });
if (saved === undefined) return;
// Update SWR cache BEFORE clearing the buffer, otherwise React will
// briefly render with buffer cleared but content still stale, causing
// CodeMirror to setValue and reset the cursor.
- onSaved?.(saved);
+ commitSaved?.(saved);
setLocalFileBuffer(tabId, undefined);
} catch {
/* swallow — surfacing handled elsewhere if needed */
@@ -223,7 +222,7 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(
}, [
deviceId,
filePath,
- onSaved,
+ onSaveStart,
readOnly,
saveLocalFile,
setLocalFileBuffer,
@@ -403,32 +402,6 @@ interface ActiveFileViewProps {
workingDirectory: string;
}
-/**
- * Live-read a text file from the topic's cloud sandbox via the `readLocalFile`
- * sandbox tool. There is no durable copy anywhere — a recycled sandbox (or any
- * tool failure) rejects, surfacing the sandbox-unavailable empty state.
- */
-const fetchSandboxFilePreview = async (
- path: string,
- topicId: string,
-): Promise<LocalFilePreview> => {
- // `readLocalFile` defaults an omitted range to the first 200 lines — always
- // request the whole file for previews so long files don't render truncated.
- const result = await cloudSandboxService.callTool(
- 'readLocalFile',
- { fullContent: true, path },
- { topicId },
- );
- if (!result.success || typeof result.result?.content !== 'string')
- throw new Error(result.error?.message || 'Failed to read sandbox file');
-
- return {
- content: result.result.content,
- contentType: result.result.mimeType || 'text/plain',
- type: 'text',
- };
-};
-
const ActiveFileView = memo<ActiveFileViewProps>(
({
activeTopicId,
@@ -442,52 +415,38 @@ const ActiveFileView = memo<ActiveFileViewProps>(
const filename = filePath.split('/').at(-1) ?? '';
const enabled = sandboxTopicId ? true : Boolean(workingDirectory) && (!!deviceId || isDesktop);
- const resourceScope =
- !sandboxTopicId && !deviceId && isHtmlFile({ path: filePath }) ? 'workspace' : undefined;
- const {
- data: preview,
- error,
- isLoading,
- isValidating,
- mutate,
- } = useClientDataSWR<LocalFilePreview>(
- enabled
- ? localFileKeys.preview({
- allowExternalFile: allowExternalFilePreview,
- deviceId,
- filePath,
- ...(resourceScope && { resourceScope }),
- ...(sandboxTopicId && { sandboxTopicId }),
- workingDirectory,
- })
- : null,
- () =>
- sandboxTopicId
- ? fetchSandboxFilePreview(filePath, sandboxTopicId)
- : projectFileService.getLocalFilePreview({
- allowExternalFile: allowExternalFilePreview,
- deviceId,
- path: filePath,
- ...(resourceScope && { resourceScope }),
- workingDirectory,
- }),
- { revalidateOnFocus: false },
+ const target = useMemo(
+ () => ({
+ allowExternalFile: allowExternalFilePreview,
+ deviceId,
+ filePath,
+ sandboxTopicId,
+ workingDirectory,
+ }),
+ [allowExternalFilePreview, deviceId, filePath, sandboxTopicId, workingDirectory],
);
+ const [useFetchPreview, beginSave, refreshPreview] = useLocalFilePreviewStore((s) => [
+ s.useFetchPreview,
+ s.beginSave,
+ s.refreshPreview,
+ ]);
+ const { error, isHydrated, isLoading, isValidating } = useFetchPreview(target, enabled);
+ const preview = useLocalFilePreview(enabled ? target : undefined);
- const handleSavedContent = useCallback(
- (saved: string) => {
- mutate((prev) => (prev && prev.type === 'text' ? { ...prev, content: saved } : prev), {
- revalidate: false,
- });
- },
- [mutate],
- );
+ const handleSaveStart = useCallback(() => beginSave(target), [beginSave, target]);
- const handleReload = useCallback(() => mutate(), [mutate]);
+ const handleReload = useCallback(() => refreshPreview(target), [refreshPreview, target]);
- if (isLoading) return <Loading />;
+ // The persisted preview is still being read: paint nothing rather than a
+ // spinner that the cached text replaces a few frames later.
+ if (isLoading) return isHydrated ? <Loading /> : null;
- if (error || !preview) {
+ // Text previews are persisted (stale-while-revalidate): a transiently failed
+ // background refresh keeps the cached text, while a deleted / denied file
+ // evicts it in the store (so `preview` is gone). Any other preview type surfaces the error
+ // (a deleted file / disconnected device), and so does a sandbox — a recycled
+ // sandbox has no file left to show.
+ if (!preview || (error && (sandboxTopicId || preview.type !== 'text'))) {
return (
<Center height={'100%'} width={'100%'}>
<Empty
@@ -564,7 +523,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(
sandboxTopicId={sandboxTopicId}
workingDirectory={workingDirectory}
onReload={handleReload}
- onSaved={handleSavedContent}
+ onSaveStart={handleSaveStart}
/>
);
},
diff --git a/src/features/Portal/LocalFile/useMoreMenu.ts b/src/features/Portal/LocalFile/useMoreMenu.ts
index 98ee9b36c8a..6cc71aa4b7a 100644
--- a/src/features/Portal/LocalFile/useMoreMenu.ts
+++ b/src/features/Portal/LocalFile/useMoreMenu.ts
@@ -2,6 +2,7 @@ import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMo
import { mutate as globalMutate } from '@/libs/swr';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useLocalFilePreviewStore } from '@/store/localFilePreview';
import { matchLocalFilePreviewKey } from './previewKeyMatcher';
@@ -13,6 +14,14 @@ export const useLocalFileMoreMenu = (): PortalMoreMenuConfig | undefined => {
// A local file has no server id or shareable URL — its handle is the path.
return {
copyPath: file.filePath,
- refresh: () => globalMutate(matchLocalFilePreviewKey(file)),
+ // The portal body's preview is a replica; inline image previews of the same
+ // file (markdown images, chat-input tags) are plain SWR queries.
+ refresh: () =>
+ Promise.all([
+ useLocalFilePreviewStore
+ .getState()
+ .refreshPreview({ ...file, allowExternalFile: file.allowExternalFilePreview }),
+ globalMutate(matchLocalFilePreviewKey(file)),
+ ]),
};
};
diff --git a/src/features/ResourceManager/components/Explorer/FileDetailPanel/PagePreview.tsx b/src/features/ResourceManager/components/Explorer/FileDetailPanel/PagePreview.tsx
index 7a5007de00f..a3d5cb69489 100644
--- a/src/features/ResourceManager/components/Explorer/FileDetailPanel/PagePreview.tsx
+++ b/src/features/ResourceManager/components/Explorer/FileDetailPanel/PagePreview.tsx
@@ -3,9 +3,7 @@
import { Center, Empty, Flexbox, Markdown, Skeleton } from '@lobehub/ui';
import { memo } from 'react';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
+import { useDocumentStore } from '@/store/document';
interface PagePreviewProps {
id: string;
@@ -16,10 +14,10 @@ interface PagePreviewProps {
* file URL, so render the document's Markdown content instead of FileViewer.
*/
const PagePreview = memo<PagePreviewProps>(({ id }) => {
- const { data: document, isLoading } = useClientDataSWR(portalKeys.documentHeader(id), () =>
- documentService.getDocumentById(id),
- );
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: document, isHydrated, isLoading } = useFetchDocumentDetail(id);
+ if (isLoading && !isHydrated) return null;
if (isLoading)
return (
<Flexbox padding={24}>
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 773a37ea7bf..88f3d33c7b0 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -894,14 +894,6 @@ export const forkKeys = {
source: def('fork:source', (identifier: string) => ['fork:source', identifier]),
};
-// ---- portal -------------------------------------------------------------
-export const portalKeys = {
- documentHeader: def('portal:documentHeader', (documentId: string) => [
- 'portal:documentHeader',
- documentId,
- ]),
-};
-
// ---- local file ---------------------------------------------------------
export const localFileKeys = {
gitWorkingTreeFiles: def(
@@ -1117,7 +1109,6 @@ export const swrKeys = {
ollama: ollamaKeys,
onboarding: onboardingKeys,
openInApp: openInAppKeys,
- portal: portalKeys,
ragEval: ragEvalKeys,
recent: recentKeys,
recommendations: recommendationsKeys,
diff --git a/src/services/document/invalidation.test.ts b/src/services/document/invalidation.test.ts
index d1dcda8b5f0..b465913c250 100644
--- a/src/services/document/invalidation.test.ts
+++ b/src/services/document/invalidation.test.ts
@@ -1,21 +1,32 @@
+import { replicaKeys } from '@lobechat/replica';
import { act, renderHook, waitFor } from '@testing-library/react';
import useSWR from 'swr';
import { describe, expect, it, vi } from 'vitest';
-import { portalKeys } from '@/libs/swr/keys';
+import { documentDetailResource } from '@/store/document/slices/document/projection';
import { invalidateDocumentMutation } from './invalidation';
vi.mock('@/libs/swr', async () => ({ mutate: (await import('swr')).mutate }));
+// The sync query the portal / page views mount for one document's replica entry.
+const documentDetailSyncKey = (documentId: string) =>
+ replicaKeys.sync(
+ documentDetailResource.name,
+ documentDetailResource.version,
+ documentDetailResource.scope.get(),
+ documentId,
+ documentId,
+ );
+
describe('invalidateDocumentMutation', () => {
it('refreshes mounted Portal content and title after a document write', async () => {
let row = { content: 'Before', title: 'Old title' };
const fetcher = vi.fn(async () => row);
const otherFetcher = vi.fn(async () => ({ content: 'Other document' }));
const { result } = renderHook(() => ({
- document: useSWR(portalKeys.documentHeader('changed-document'), fetcher),
- other: useSWR(portalKeys.documentHeader('untouched-document'), otherFetcher),
+ document: useSWR(documentDetailSyncKey('changed-document'), fetcher),
+ other: useSWR(documentDetailSyncKey('untouched-document'), otherFetcher),
}));
await waitFor(() => expect(result.current.document.data?.title).toBe('Old title'));
await waitFor(() => expect(result.current.other.data?.content).toBe('Other document'));
diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.ts
index 9e254fe9e60..d76e077ec5b 100644
--- a/src/services/document/invalidation.ts
+++ b/src/services/document/invalidation.ts
@@ -1,6 +1,4 @@
import { revalidateReplica } from '@/libs/replica';
-import { mutate } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
import {
agentDocumentListResource,
agentDocumentReaderKey,
@@ -40,7 +38,6 @@ export const invalidateDocumentMutation = async (
// refresh them here or a rename / move would not reach the Pages sidebar or
// the page header until a remount.
revalidations.push(revalidateReplica(pageDetailResource, documentId));
- revalidations.push(mutate(portalKeys.documentHeader(documentId)));
}
if (documentId || refreshPageDocuments) {
diff --git a/src/services/electron/localFileService.test.ts b/src/services/electron/localFileService.test.ts
index e4a6f7d15a8..71c133571aa 100644
--- a/src/services/electron/localFileService.test.ts
+++ b/src/services/electron/localFileService.test.ts
@@ -1,6 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { localFileService } from './localFileService';
+import {
+ isTerminalLocalFileError,
+ LocalFileResponseError,
+ localFileService,
+} from './localFileService';
const mockLocalSystem = vi.hoisted(() => ({
getExternalAssetForPublishUrl: vi.fn(),
@@ -56,6 +60,45 @@ describe('localFileService', () => {
});
});
+ it('reports the preview protocol status so a deleted / denied file is terminal', async () => {
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ success: true,
+ url: 'localfile://preview/gone.md',
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () => ({ headers: { get: vi.fn() }, ok: false, status: 404 }) as unknown as Response,
+ ),
+ );
+
+ const error = await localFileService
+ .getLocalFilePreview({ path: '/repo/gone.md', workingDirectory: '/repo' })
+ .catch((reason: unknown) => reason);
+
+ expect(error).toBeInstanceOf(LocalFileResponseError);
+ expect((error as LocalFileResponseError).status).toBe(404);
+ expect(isTerminalLocalFileError(error)).toBe(true);
+ expect(isTerminalLocalFileError(new LocalFileResponseError(403))).toBe(true);
+ expect(isTerminalLocalFileError(new LocalFileResponseError(500))).toBe(false);
+ expect(isTerminalLocalFileError(new Error('Failed to load local file: 404'))).toBe(false);
+ });
+
+ it('treats a file that vanished before its preview URL exists as terminal', async () => {
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ code: 'not_found',
+ error: 'ENOENT: no such file or directory',
+ success: false,
+ });
+
+ const error = await localFileService
+ .getLocalFilePreview({ path: '/repo/gone.md', workingDirectory: '/repo' })
+ .catch((reason: unknown) => reason);
+
+ expect(isTerminalLocalFileError(error)).toBe(true);
+ expect((error as LocalFileResponseError).status).toBe(404);
+ });
+
it('returns the entry directory as the HTML workspace resource base URL', async () => {
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 0e70470ef62..5935de2b212 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -161,6 +161,38 @@ const normalizeContentType = (contentType: string | null): string =>
const isTextPreviewMimeType = (mimeType: string): boolean =>
mimeType.startsWith('text/') || TEXT_PREVIEW_MIME_TYPES.has(mimeType);
+/**
+ * The desktop preview protocol answered with an HTTP error. `status` tells a
+ * terminal answer (404 gone, 403 denied) from a transient one, so a cached
+ * preview can be dropped only when the file is really gone or denied.
+ */
+export class LocalFileResponseError extends Error {
+ readonly status: number;
+
+ constructor(status: number, message?: string) {
+ super(message || `Failed to load local file: ${status}`);
+ this.name = 'LocalFileResponseError';
+ this.status = status;
+ }
+}
+
+/**
+ * The error for a failed preview result: a terminal `code` (set by the desktop
+ * main process or a remote device) becomes a {@link LocalFileResponseError} with
+ * the matching status, anything else stays a plain (transient) error.
+ */
+export const localFilePreviewResultError = (
+ result: { code?: 'forbidden' | 'not_found'; error?: string },
+ fallback: string,
+): Error =>
+ result.code
+ ? new LocalFileResponseError(result.code === 'not_found' ? 404 : 403, result.error)
+ : new Error(result.error || fallback);
+
+/** The file no longer exists or may no longer be read (deleted, moved, denied). */
+export const isTerminalLocalFileError = (error: unknown): boolean =>
+ error instanceof LocalFileResponseError && (error.status === 403 || error.status === 404);
+
const fetchLocalFilePreview = async (
url: string,
accept?: LocalFilePreviewUrlParams['accept'],
@@ -169,7 +201,7 @@ const fetchLocalFilePreview = async (
const response = await fetch(url);
if (!response.ok) {
- throw new Error(`Failed to load local file: ${response.status}`);
+ throw new LocalFileResponseError(response.status);
}
const contentType = normalizeContentType(response.headers.get('content-type'));
@@ -344,7 +376,7 @@ class LocalFileService {
const result = await ensureElectronIpc().localSystem.getLocalFilePreviewUrl(params);
if (!result.success || !result.url) {
- throw new Error(result.error || 'Missing local file preview URL');
+ throw localFilePreviewResultError(result, 'Missing local file preview URL');
}
return fetchLocalFilePreview(result.url, params.accept, params.resourceScope);
@@ -375,7 +407,7 @@ class LocalFileService {
}
const response = await fetch(result.url, { signal });
- if (!response.ok) throw new Error(`Failed to load local file: ${response.status}`);
+ if (!response.ok) throw new LocalFileResponseError(response.status);
if (isOversizedVideo(response)) {
void response.body?.cancel().catch(() => {});
return { ok: false, reason: 'oversized' };
diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.ts
index c32f63ce3a6..da4f081e530 100644
--- a/src/services/projectFile.test.ts
+++ b/src/services/projectFile.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { localFileKeys } from '@/libs/swr/keys';
+import { isTerminalLocalFileError } from '@/services/electron/localFileService';
import { projectFileService, refreshProjectFiles } from './projectFile';
@@ -54,7 +55,8 @@ vi.mock('@/libs/trpc/client', () => ({
},
}));
-vi.mock('@/services/electron/localFileService', () => ({
+vi.mock('@/services/electron/localFileService', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
localFileService: mockLocalFileService,
}));
@@ -68,6 +70,33 @@ describe('projectFileService', () => {
vi.unstubAllGlobals();
});
+ it('keeps a remote device’s terminal failure code (deleted / denied file)', async () => {
+ mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
+ code: 'not_found',
+ error: 'ENOENT: no such file or directory',
+ success: false,
+ });
+
+ const error = await projectFileService
+ .getLocalFilePreview({
+ deviceId: 'device-1',
+ path: '/repo/gone.md',
+ workingDirectory: '/repo',
+ })
+ .catch((reason: unknown) => reason);
+ expect(isTerminalLocalFileError(error)).toBe(true);
+
+ // A gateway / disconnect failure carries no code and stays transient.
+ mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
+ error: 'Device offline',
+ success: false,
+ });
+ const transient = await projectFileService
+ .getLocalFilePreview({ deviceId: 'device-1', path: '/repo/a.md', workingDirectory: '/repo' })
+ .catch((reason: unknown) => reason);
+ expect(isTerminalLocalFileError(transient)).toBe(false);
+ });
+
it('gets remote local-file preview through device RPC', async () => {
mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
preview: {
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index 10d1a53acdc..b0f58905e7c 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -18,7 +18,11 @@ import { isAbsolute, relative, resolve } from 'pathe';
import { mutate } from '@/libs/swr';
import { localFileKeys } from '@/libs/swr/keys';
import { lambdaClient } from '@/libs/trpc/client';
-import { type LocalFilePreview, localFileService } from '@/services/electron/localFileService';
+import {
+ type LocalFilePreview,
+ localFilePreviewResultError,
+ localFileService,
+} from '@/services/electron/localFileService';
import { sandboxStorageService } from '@/services/sandboxStorage';
export type { LocalFilePreview } from '@/services/electron/localFileService';
@@ -264,7 +268,7 @@ class ProjectFileService {
});
if (!result.success || !result.preview) {
- throw new Error(result.error || 'Missing local file preview');
+ throw localFilePreviewResultError(result, 'Missing local file preview');
}
if (params.accept === 'image' && result.preview.type !== 'image') {
diff --git a/src/store/document/index.ts b/src/store/document/index.ts
index 911ac11b690..80ac39fd324 100644
--- a/src/store/document/index.ts
+++ b/src/store/document/index.ts
@@ -11,6 +11,7 @@ export type {
DocumentDetail,
DocumentDetailSliceState,
InitDocumentParams,
+ UseFetchDocumentDetailResult,
UseFetchDocumentOptions,
UseFetchDocumentResult,
} from './slices/document';
diff --git a/src/store/document/slices/document/action.detailView.test.ts b/src/store/document/slices/document/action.detailView.test.ts
new file mode 100644
index 00000000000..016b09bb812
--- /dev/null
+++ b/src/store/document/slices/document/action.detailView.test.ts
@@ -0,0 +1,306 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Read-only views (portal document, goal result / deliverable reader, resource
+ * page preview) read the document detail replica without an editor through
+ * `useFetchDocumentDetail`: they share the editor's persisted row, paint it
+ * after a reload and fold renames / saves into the same entry.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { documentService } from '@/services/document';
+
+import { useDocumentStore } from '../../store';
+import { documentDetailResource } from './projection';
+import { detailSliceState, documentRow, pending, storedRow, wrapper } from './testUtils';
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => null,
+ useActiveWorkspaceId: () => null,
+}));
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ getDocumentById: vi.fn(),
+ updateDocument: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/page', () => ({
+ pageActions: { upsertDocument: vi.fn() },
+}));
+
+describe('document detail without an editor (portal / goal / preview views)', () => {
+ 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 renderDetail = (documentId: string) =>
+ renderHook(() => useDocumentStore.getState().useFetchDocumentDetail(documentId), { wrapper });
+
+ beforeEach(() => {
+ useScope(`document-detail-user-${randomUUID()}:personal`);
+ act(() => useDocumentStore.setState(detailSliceState()));
+ vi.mocked(documentService.getDocumentById).mockReset();
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].map((value) =>
+ documentDetailResource.storage!.remove({ queryKey: 'doc-1', scope: value }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('bounds the persisted documents it shares with the editor', () => {
+ expect(documentDetailResource.maxPersistedEntries).toBeGreaterThan(0);
+ });
+
+ it('paints the persisted document after a reload, then swaps in the refreshed row', async () => {
+ // A previous session left this row behind; the network is slow.
+ await documentDetailResource.storage!.set(
+ { queryKey: 'doc-1', scope },
+ { data: { document: documentRow({ title: 'Cached title' }) }, updatedAt: 1 },
+ );
+ let answer: (row: unknown) => void = () => {};
+ vi.mocked(documentService.getDocumentById).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as any,
+ );
+
+ const { result } = renderDetail('doc-1');
+
+ await waitFor(() => expect(result.current.data?.title).toBe('Cached title'));
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.isHydrated).toBe(true);
+ expect(result.current.isValidating).toBe(true);
+
+ await act(async () => {
+ answer(
+ documentRow({ title: 'Fresh title', updatedAt: new Date('2026-01-03T00:00:00.000Z') }),
+ );
+ });
+
+ await waitFor(() => expect(result.current.data?.title).toBe('Fresh title'));
+ await waitFor(async () =>
+ expect((await storedRow('doc-1', scope))?.data.document?.title).toBe('Fresh title'),
+ );
+ });
+
+ it.each(['FORBIDDEN', 'UNAUTHORIZED'])(
+ 'purges the cached document when the refresh is denied (%s)',
+ async (code) => {
+ await documentDetailResource.storage!.set(
+ { queryKey: 'doc-1', scope },
+ { data: { document: documentRow({ title: 'Revoked' }) }, updatedAt: 1 },
+ );
+ let deny: (error: unknown) => void = () => {};
+ vi.mocked(documentService.getDocumentById).mockImplementation(
+ () => new Promise((_, reject) => (deny = reject)) as any,
+ );
+
+ const { result } = renderDetail('doc-1');
+ await waitFor(() => expect(result.current.data?.title).toBe('Revoked'));
+
+ await act(async () => {
+ deny(Object.assign(new Error(code), { data: { code } }));
+ });
+
+ await waitFor(() => expect(result.current.data).toBeUndefined());
+ expect(result.current.error).toBeDefined();
+ await waitFor(async () => expect(await storedRow('doc-1', scope)).toBeUndefined());
+ },
+ );
+
+ it('keeps the cached document when the refresh fails transiently', async () => {
+ await documentDetailResource.storage!.set(
+ { queryKey: 'doc-1', scope },
+ { data: { document: documentRow({ title: 'Cached' }) }, updatedAt: 1 },
+ );
+ vi.mocked(documentService.getDocumentById).mockRejectedValue(new Error('Failed to fetch'));
+
+ const { result } = renderDetail('doc-1');
+
+ await waitFor(() => expect(result.current.error).toBeDefined());
+ expect(result.current.data?.title).toBe('Cached');
+ expect((await storedRow('doc-1', scope))?.data.document?.title).toBe('Cached');
+ });
+
+ it('reports loading only once the persisted row is known to be absent', async () => {
+ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);
+
+ const { result } = renderDetail('doc-1');
+
+ await waitFor(() => expect(result.current.isHydrated).toBe(true));
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('rolls an optimistic rename back when the server rejects it', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({ title: 'Old' }) as any,
+ );
+ const { result } = renderDetail('doc-1');
+ await waitFor(() => expect(result.current.data?.title).toBe('Old'));
+
+ let reject: (error: Error) => void = () => {};
+ let rename: Promise<unknown> = Promise.resolve();
+ act(() => {
+ rename = useDocumentStore
+ .getState()
+ .optimisticDocumentDetail(
+ 'doc-1',
+ { title: 'New' },
+ () => new Promise((_, fail) => (reject = fail)),
+ );
+ });
+ expect(result.current.data?.title).toBe('New');
+
+ await act(async () => {
+ reject(new Error('rename failed'));
+ await rename.catch(() => undefined);
+ });
+ expect(result.current.data?.title).toBe('Old');
+ });
+
+ it('folds a confirmed save into the entry without a refetch', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({ content: 'before' }) as any,
+ );
+ const { result } = renderDetail('doc-1');
+ await waitFor(() => expect(result.current.data?.content).toBe('before'));
+ const calls = vi.mocked(documentService.getDocumentById).mock.calls.length;
+
+ act(() =>
+ useDocumentStore.getState().beginDocumentDetailPatch('doc-1')({
+ content: 'saved',
+ updatedAt: new Date('2026-01-04T00:00:00.000Z'),
+ }),
+ );
+
+ expect(result.current.data?.content).toBe('saved');
+ expect(vi.mocked(documentService.getDocumentById).mock.calls.length).toBe(calls);
+ await waitFor(async () =>
+ expect((await storedRow('doc-1', scope))?.data.document?.content).toBe('saved'),
+ );
+ });
+
+ it('drops a save that settles under another identity', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({ content: 'before' }) as any,
+ );
+ const { result } = renderDetail('doc-1');
+ await waitFor(() => expect(result.current.data?.content).toBe('before'));
+ const previous = scope;
+
+ // The save starts in one identity…
+ const commit = useDocumentStore.getState().beginDocumentDetailPatch('doc-1');
+ // …and settles after a switch, while the old row is still in memory.
+ useScope(`document-detail-user-${randomUUID()}:personal`);
+ act(() => commit({ content: 'saved-by-previous-identity' }));
+
+ expect(result.current.data?.content).not.toBe('saved-by-previous-identity');
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(await storedRow('doc-1', scope)).toBeUndefined();
+ expect((await storedRow('doc-1', previous))?.data.document?.content).not.toBe(
+ 'saved-by-previous-identity',
+ );
+ });
+
+ it('does not let a rename confirmed after an identity switch hold back the new scope’s read', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({ title: 'Old' }) as any,
+ );
+ const { rerender, result } = renderDetail('doc-1');
+ await waitFor(() => expect(result.current.data?.title).toBe('Old'));
+
+ // A rename starts under this identity…
+ let confirm: () => void = () => {};
+ let rename: Promise<unknown> = Promise.resolve();
+ act(() => {
+ rename = useDocumentStore
+ .getState()
+ .optimisticDocumentDetail(
+ 'doc-1',
+ { title: 'Renamed' },
+ () => new Promise<void>((resolve) => (confirm = resolve)),
+ );
+ });
+
+ // …the user switches identity, and that identity reads the same id.
+ let answer: (row: unknown) => void = () => {};
+ vi.mocked(documentService.getDocumentById).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as any,
+ );
+ const nextScope = `document-detail-user-${randomUUID()}:personal`;
+ // That identity has its own persisted copy, hydrated before its read answers.
+ await documentDetailResource.storage!.set(
+ { queryKey: 'doc-1', scope: nextScope },
+ { data: { document: documentRow({ title: 'Other identity (cached)' }) }, updatedAt: 1 },
+ );
+ useScope(nextScope);
+ rerender();
+ await waitFor(() => expect(result.current.data?.title).toBe('Other identity (cached)'));
+ await waitFor(() => expect(documentService.getDocumentById).toHaveBeenCalledTimes(2));
+
+ // The old rename settles first, then the new identity's read answers.
+ await act(async () => {
+ confirm();
+ await rename.catch(() => undefined);
+ });
+ await act(async () => {
+ answer(documentRow({ title: 'Other identity (fresh)' }));
+ });
+
+ await waitFor(() => expect(result.current.data?.title).toBe('Other identity (fresh)'));
+ });
+
+ it('keeps a confirmed rename over a read that started before it', async () => {
+ await documentDetailResource.storage!.set(
+ { queryKey: 'doc-1', scope },
+ { data: { document: documentRow({ title: 'Old' }) }, updatedAt: 1 },
+ );
+ let answer: (row: unknown) => void = () => {};
+ vi.mocked(documentService.getDocumentById).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as any,
+ );
+ const { result } = renderDetail('doc-1');
+ await waitFor(() => expect(result.current.data?.title).toBe('Old'));
+
+ // The mount-time read is still in flight when the rename is confirmed.
+ await act(async () => {
+ await useDocumentStore
+ .getState()
+ .optimisticDocumentDetail('doc-1', { title: 'New' }, () => Promise.resolve());
+ });
+ expect(result.current.data?.title).toBe('New');
+
+ // …then it settles with the pre-rename row (same `updatedAt`).
+ await act(async () => {
+ answer(documentRow({ title: 'Old' }));
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(result.current.data?.title).toBe('New');
+ await waitFor(async () =>
+ expect((await storedRow('doc-1', scope))?.data.document?.title).toBe('New'),
+ );
+ });
+});
diff --git a/src/store/document/slices/document/action.test.ts b/src/store/document/slices/document/action.test.ts
index cff9b0115fb..d9b701c92a8 100644
--- a/src/store/document/slices/document/action.test.ts
+++ b/src/store/document/slices/document/action.test.ts
@@ -9,19 +9,22 @@
import { randomUUID } from 'node:crypto';
import { act, render, renderHook, waitFor } from '@testing-library/react';
-import type { PropsWithChildren } from 'react';
-import { createElement, useEffect } from 'react';
-import { SWRConfig, useSWRConfig } from 'swr';
+import { createElement } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheScope, replicaSWRDriver } from '@/libs/replica';
-import { setScopedMutate } from '@/libs/swr/mutate';
import { documentService } from '@/services/document';
-import { initialEditorState } from '@/store/document/slices/editor';
import { useDocumentStore } from '../../store';
-import { initialDocumentDetailSliceState } from './initialState';
-import { documentDetailResource } from './projection';
+import { documentDetailResource, MAX_PERSISTED_DOCUMENT_DETAILS } from './projection';
+import {
+ baseEditorData,
+ detailSliceState,
+ documentRow,
+ pending,
+ storedRow,
+ wrapper,
+} from './testUtils';
const mocks = vi.hoisted(() => ({
activeWorkspaceId: null as string | null,
@@ -44,37 +47,6 @@ vi.mock('@/store/page', () => ({
pageActions: { upsertDocument: mocks.upsertDocument },
}));
-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 baseEditorData = {
- root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },
-};
-
-/** A document row as the server returns it. */
-const documentRow = (overrides: Record<string, unknown> = {}) =>
- ({
- content: '# Server',
- editorData: baseEditorData,
- id: 'doc-1',
- updatedAt: new Date('2026-01-02T00:00:00.000Z'),
- ...overrides,
- }) as any;
-
-/** Never-resolving fetch: the first frame can only come from storage. */
-const pending = () => new Promise<never>(() => {});
-
const createEditor = () => ({
getDocument: vi.fn((type: string) => {
if (type === 'markdown') return '# Draft';
@@ -95,11 +67,6 @@ const renderDocument = (
{ wrapper },
);
-const storedRow = (documentId: string, scope: string) =>
- documentDetailResource.storage!.get({ queryKey: documentId, scope });
-
-const detailSliceState = () => ({ ...initialEditorState, ...initialDocumentDetailSliceState });
-
describe('document detail replica', () => {
const scopes = new Set<string>();
let scope = '';
@@ -357,6 +324,61 @@ describe('document detail replica', () => {
expect(useDocumentStore.getState().documents['doc-2']).toBeUndefined();
});
+ it('drops an editor entry whose detail entry was evicted before the scope reset', async () => {
+ vi.mocked(documentService.getDocumentById).mockImplementation(
+ async (id: string) => documentRow({ id }) as any,
+ );
+ const first = renderDocument('doc-1', createEditor());
+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());
+ first.unmount();
+ act(() => useDocumentStore.setState({ activeDocumentId: undefined }));
+
+ // Opening more documents than the persisted cap evicts the unmounted doc-1
+ // detail entry, while its editor row stays behind.
+ for (let index = 0; index <= MAX_PERSISTED_DOCUMENT_DETAILS; index += 1) {
+ await act(async () => {
+ await useDocumentStore.getState().prefetchDocument(`doc-extra-${index}`);
+ });
+ }
+ await waitFor(() =>
+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toBeUndefined(),
+ );
+ expect(useDocumentStore.getState().documents['doc-1']).toBeDefined();
+
+ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);
+ useScope(`document-user-${randomUUID()}:personal`);
+ const next = renderDocument('doc-2', createEditor());
+ next.rerender();
+
+ await waitFor(() => expect(useDocumentStore.getState().documentDetailMap).toEqual({}));
+ // Reopening doc-1 in the new identity must not find the old body loaded.
+ expect(useDocumentStore.getState().documents['doc-1']).toBeUndefined();
+ });
+
+ it('drops editor rows created outside the replica (highlight editor) on a scope reset', async () => {
+ vi.mocked(documentService.getDocumentById).mockImplementation(
+ async (id: string) => documentRow({ id }) as any,
+ );
+ // The highlight editor mirrors its buffer with `addDocument`, never through
+ // `useFetchDocument`, so no detail entry is tied to this row.
+ act(() =>
+ useDocumentStore.getState().internal_dispatchDocument({
+ id: 'doc-highlight',
+ type: 'addDocument',
+ value: { content: 'previous identity', lastSavedContent: 'previous identity' } as any,
+ }),
+ );
+ const mounted = renderDocument('doc-2', createEditor());
+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-2']).toBeDefined());
+
+ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);
+ useScope(`document-user-${randomUUID()}:personal`);
+ mounted.rerender();
+
+ await waitFor(() => expect(useDocumentStore.getState().documentDetailMap).toEqual({}));
+ expect(useDocumentStore.getState().documents['doc-highlight']).toBeUndefined();
+ });
+
it('keeps no previous-identity editor state when the new scope’s fetch fails', async () => {
vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);
const editor = createEditor();
diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.ts
index 76d85117493..0bc5937af38 100644
--- a/src/store/document/slices/document/action.ts
+++ b/src/store/document/slices/document/action.ts
@@ -12,6 +12,7 @@ import { pageActions } from '@/store/page';
import type { StoreSetter } from '@/store/types';
import { isSkillMarkdownDocument, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';
import { setNamespace } from '@/utils/storeDebug';
+import { isTrpcErrorCode } from '@/utils/trpcError';
import type { DocumentStore } from '../../store';
import { useDocumentStore } from '../../store';
@@ -80,6 +81,12 @@ export interface UseFetchDocumentResult {
mutate: () => Promise<unknown>;
}
+/** Result of `useFetchDocumentDetail`; `data` is read from the replica view. */
+export interface UseFetchDocumentDetailResult extends UseFetchDocumentResult {
+ /** The persisted row has been read (or there was none to read). */
+ isHydrated: boolean;
+}
+
const detailLens = recordLens<DocumentStore, DocumentDetail>('documentDetailMap');
type Setter = StoreSetter<DocumentStore>;
@@ -114,6 +121,16 @@ export class DocumentActionImpl {
if ((this.#adoptions.get(id) ?? 0) !== adoptedBefore && current) return current;
return this.#keepNewerDetail(id, { document });
},
+ effects: {
+ // The server now denies this document (access revoked, session ended):
+ // the cached copy must stop rendering — on screen and after a reload.
+ // Transient failures keep it (stale-while-revalidate).
+ onError: (error, _id, { key, scope }) => {
+ if (!key) return;
+ if (isTrpcErrorCode(error, 'FORBIDDEN') || isTrpcErrorCode(error, 'UNAUTHORIZED'))
+ this.#detail.remove(key, scope);
+ },
+ },
get,
set,
stateKey: 'documentDetailReplica',
@@ -125,6 +142,18 @@ export class DocumentActionImpl {
});
}
+ /**
+ * Advance the adoption generation of `documentId` for a write confirmed under
+ * `scope`. A write that settles after an account / workspace switch is dropped
+ * by the replica, so it must not advance the guard either: a read of the same
+ * id already in flight under the new identity would otherwise discard its
+ * fresh response for the hydrated row.
+ */
+ #countAdoption = (documentId: string, scope: string): void => {
+ if (scope !== documentDetailResource.scope.get()) return;
+ this.#adoptions.set(documentId, (this.#adoptions.get(documentId) ?? 0) + 1);
+ };
+
/**
* Scope reset (account / workspace switch): drop the projection together with
* every editor entry derived from it, in the same commit.
@@ -137,11 +166,15 @@ export class DocumentActionImpl {
* never flushed under the new one.
*/
#clearDetailView = (state: DocumentStore): Partial<DocumentStore> => {
- const derivedIds = Object.keys(state.documentDetailMap).filter((id) => state.documents[id]);
- if (derivedIds.length === 0) return detailLens.clear(state);
+ // Every editor row, not only those whose detail entry is still in the map:
+ // a bounded replica evicts unmounted entries (`persist.maxEntries`) and the
+ // highlight editor creates its row directly (`addDocument`), yet each row
+ // still holds the previous identity's body.
+ const editorIds = Object.keys(state.documents);
+ if (editorIds.length === 0) return detailLens.clear(state);
const documents = { ...state.documents };
- for (const id of derivedIds) {
+ for (const id of editorIds) {
this.#cleanupDebouncedSave(id);
delete documents[id];
}
@@ -459,6 +492,79 @@ export class DocumentActionImpl {
};
};
+ /**
+ * Read one document's server row without mounting an editor — the portal
+ * header / body switch, the agent-document breadcrumb, goal deliverables and
+ * the resource preview. It shares the editor's replica entry, so every view of
+ * a document paints from the same persisted projection on a reload and one
+ * network sync confirms them all.
+ *
+ * `isLoading` keeps SWR's meaning (no value and no error yet). Check
+ * `isHydrated` before showing a loading state: until the persisted row has
+ * been read, "no value" may only mean "not read yet".
+ */
+ useFetchDocumentDetail = (documentId: string | undefined): UseFetchDocumentDetailResult => {
+ const document = useDocumentStore((s) =>
+ documentId ? s.documentDetailMap[documentId]?.document : undefined,
+ );
+ const sync = this.#detail.useSync(documentId);
+
+ return {
+ data: document,
+ error: sync.error,
+ isHydrated: sync.isHydrated,
+ isLoading: !!documentId && document === undefined && sync.error == null,
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+ };
+ };
+
+ /**
+ * Start a server write (e.g. a highlight-editor save) of one document and
+ * return the commit that folds its confirmed result into the replica entry,
+ * so the views reading it — and the next reload — show the saved revision
+ * without a refetch. A read already in flight started before the write and
+ * is not allowed to replace it.
+ *
+ * The identity (user / workspace scope) is captured here, before the request:
+ * a write that settles after an account / workspace switch belongs to the
+ * previous identity, so the commit is a no-op instead of planting that
+ * document in the new scope's memory and IndexedDB partition.
+ */
+ beginDocumentDetailPatch = (documentId: string): ((patch: Partial<DocumentItem>) => void) => {
+ const scope = documentDetailResource.scope.get();
+ return (patch) => {
+ if (documentDetailResource.scope.get() !== scope) return;
+ const current = this.#get().documentDetailMap[documentId]?.document;
+ if (!current) return;
+ this.internal_adoptDocumentDetail(documentId, { ...current, ...patch }, scope);
+ };
+ };
+
+ /**
+ * Show `patch` on the document right away while `serverCall` runs. A failed
+ * call rolls back to the confirmed row plus any other write still in flight,
+ * so an older rejected rename never undoes a newer one.
+ */
+ optimisticDocumentDetail = <TResult>(
+ documentId: string,
+ patch: Partial<DocumentItem>,
+ serverCall: () => Promise<TResult>,
+ ): Promise<TResult> =>
+ this.#detail.optimistic(
+ documentId,
+ (detail) => (detail.document ? { document: { ...detail.document, ...patch } } : detail),
+ async () => {
+ const scope = documentDetailResource.scope.get();
+ const result = await serverCall();
+ // Confirmed: a read started before this write may return the pre-write
+ // row with the same `updatedAt`, so count it as an adoption (see
+ // `#adoptions`) — that read keeps the committed entry instead.
+ this.#countAdoption(documentId, scope);
+ return result;
+ },
+ );
+
/**
* Warm the replica for a document the user is about to open (hover prefetch),
* so navigation paints the editor from the projection instead of a skeleton.
@@ -492,7 +598,7 @@ export class DocumentActionImpl {
document: DocumentItem | null,
scope?: string,
): void => {
- this.#adoptions.set(documentId, (this.#adoptions.get(documentId) ?? 0) + 1);
+ this.#countAdoption(documentId, scope ?? documentDetailResource.scope.get());
this.#detail.replace(documentId, { document }, scope);
};
}
diff --git a/src/store/document/slices/document/index.ts b/src/store/document/slices/document/index.ts
index 9acdf228c6b..443e9f93e76 100644
--- a/src/store/document/slices/document/index.ts
+++ b/src/store/document/slices/document/index.ts
@@ -2,6 +2,7 @@ export {
createDocumentSlice,
type DocumentAction,
type InitDocumentParams,
+ type UseFetchDocumentDetailResult,
type UseFetchDocumentOptions,
type UseFetchDocumentResult,
} from './action';
diff --git a/src/store/document/slices/document/projection.ts b/src/store/document/slices/document/projection.ts
index 2e21c4a3743..fa5d3acca99 100644
--- a/src/store/document/slices/document/projection.ts
+++ b/src/store/document/slices/document/projection.ts
@@ -15,15 +15,24 @@ export interface DocumentDetail {
document: DocumentItem | null;
}
+/** How many document rows survive a reload (`persist.maxEntries`). */
+export const MAX_PERSISTED_DOCUMENT_DETAILS = 50;
+
/**
* One document detail per entry, keyed by the document id it was opened with.
* Persisted to IndexedDB: on a reload the editor's first frame comes from the
* projection and the network only confirms it. The "not found" marker is never
* persisted — it is a page state, not a document.
+ *
+ * Read-only views (portal, goal deliverables, resource preview) share these
+ * rows, so the persisted set is bounded: the least recently used documents
+ * beyond {@link MAX_PERSISTED_DOCUMENT_DETAILS} are evicted (open ones are
+ * pinned by their mounted sync) and simply refetch on the next visit.
*/
export const documentDetailResource = defineReplica<string, DocumentDetail>({
key: (id) => id,
name: 'documentDetail',
+ persist: { maxEntries: MAX_PERSISTED_DOCUMENT_DETAILS },
storage: 'indexedDB',
version: 1,
});
diff --git a/src/store/document/slices/document/testUtils.ts b/src/store/document/slices/document/testUtils.ts
new file mode 100644
index 00000000000..277a30263a2
--- /dev/null
+++ b/src/store/document/slices/document/testUtils.ts
@@ -0,0 +1,53 @@
+/**
+ * Shared fixtures of the document detail replica suites (`action*.test.ts`):
+ * the SWR provider with the app's scoped mutate, server-shaped rows and the
+ * persisted-row reader.
+ */
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { initialEditorState } from '@/store/document/slices/editor';
+
+import { initialDocumentDetailSliceState } from './initialState';
+import { documentDetailResource } from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+export const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+export const baseEditorData = {
+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },
+};
+
+/** A document row as the server returns it. */
+export const documentRow = (overrides: Record<string, unknown> = {}) =>
+ ({
+ content: '# Server',
+ editorData: baseEditorData,
+ id: 'doc-1',
+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),
+ ...overrides,
+ }) as any;
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+export const pending = () => new Promise<never>(() => {});
+
+export const storedRow = (documentId: string, scope: string) =>
+ documentDetailResource.storage!.get({ queryKey: documentId, scope });
+
+export const detailSliceState = () => ({
+ ...initialEditorState,
+ ...initialDocumentDetailSliceState,
+});
diff --git a/src/store/localFilePreview/index.test.ts b/src/store/localFilePreview/index.test.ts
new file mode 100644
index 00000000000..f8422fa6ddd
--- /dev/null
+++ b/src/store/localFilePreview/index.test.ts
@@ -0,0 +1,442 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The local-file portal preview is a replica: a reload paints the last text
+ * preview from IndexedDB while the device / sandbox confirms it. Only text
+ * previews under the size cap are persisted, without the short-lived
+ * `resourceBaseUrl` token; Blob-backed and oversized previews stay in memory.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { cloudSandboxService } from '@/services/cloudSandbox';
+import { LocalFileResponseError } from '@/services/electron/localFileService';
+import { projectFileService } from '@/services/projectFile';
+
+import {
+ initialLocalFilePreviewState,
+ localFilePreviewKey,
+ localFilePreviewResource,
+ type LocalFilePreviewTarget,
+ MAX_PERSISTED_PREVIEW_CHARS,
+ MAX_PERSISTED_PREVIEWS,
+ useLocalFilePreview,
+ useLocalFilePreviewStore,
+} from './index';
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => null,
+ useActiveWorkspaceId: () => null,
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: { getLocalFilePreview: vi.fn() },
+}));
+
+vi.mock('@/services/cloudSandbox', () => ({
+ cloudSandboxService: { callTool: vi.fn() },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const NOTES: LocalFilePreviewTarget = {
+ deviceId: 'device-a',
+ filePath: '/repo/notes.md',
+ workingDirectory: '/repo',
+};
+
+const textPreview = (content: string, extra: Record<string, unknown> = {}) =>
+ ({ content, contentType: 'text/markdown', type: 'text', ...extra }) as const;
+
+const renderPreview = (target: LocalFilePreviewTarget) =>
+ renderHook(
+ () => ({
+ preview: useLocalFilePreview(target),
+ sync: useLocalFilePreviewStore.getState().useFetchPreview(target),
+ }),
+ { wrapper },
+ );
+
+describe('local file preview replica', () => {
+ const scopes = new Set<string>();
+ const keys = 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 storedRow = (target: LocalFilePreviewTarget) => {
+ const key = localFilePreviewKey(target);
+ keys.add(key);
+ return localFilePreviewResource.storage!.get({ queryKey: key, scope });
+ };
+
+ const seedRow = (target: LocalFilePreviewTarget, data: unknown) => {
+ const key = localFilePreviewKey(target);
+ keys.add(key);
+ return localFilePreviewResource.storage!.set({ queryKey: key, scope }, {
+ data,
+ updatedAt: 1,
+ } as never);
+ };
+
+ beforeEach(() => {
+ useScope(`local-file-user-${randomUUID()}:personal`);
+ act(() => useLocalFilePreviewStore.setState(initialLocalFilePreviewState));
+ vi.mocked(projectFileService.getLocalFilePreview).mockReset();
+ vi.mocked(cloudSandboxService.callTool).mockReset();
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ [...keys].map((key) =>
+ localFilePreviewResource.storage!.remove({ queryKey: key, scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ keys.clear();
+ vi.restoreAllMocks();
+ });
+
+ it('paints the persisted text preview after a reload, then swaps in the fresh read', async () => {
+ await seedRow(NOTES, textPreview('# v1'));
+ let answer: (preview: unknown) => void = () => {};
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as never,
+ );
+
+ const { result } = renderPreview(NOTES);
+
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('# v1')));
+ expect(result.current.sync.isLoading).toBe(false);
+ expect(result.current.sync.isValidating).toBe(true);
+ expect(projectFileService.getLocalFilePreview).toHaveBeenCalledWith({
+ allowExternalFile: undefined,
+ deviceId: 'device-a',
+ path: '/repo/notes.md',
+ workingDirectory: '/repo',
+ });
+
+ await act(async () => {
+ answer(textPreview('# v2'));
+ });
+
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('# v2')));
+ await waitFor(async () => expect((await storedRow(NOTES))?.data).toEqual(textPreview('# v2')));
+ });
+
+ it('keys previews by device and working directory', async () => {
+ const otherDevice = { ...NOTES, deviceId: 'device-b' };
+ await seedRow(NOTES, textPreview('device a'));
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise(() => {}) as never,
+ );
+
+ const { result } = renderPreview(otherDevice);
+
+ await waitFor(() => expect(result.current.sync.isHydrated).toBe(true));
+ expect(result.current.preview).toBeUndefined();
+ expect(result.current.sync.isLoading).toBe(true);
+ expect(localFilePreviewKey(NOTES)).not.toBe(localFilePreviewKey(otherDevice));
+ expect(localFilePreviewKey(NOTES)).not.toBe(
+ localFilePreviewKey({ ...NOTES, workingDirectory: '/other' }),
+ );
+ });
+
+ it.each(['local', 'sandbox:build'])(
+ 'reads a device whose id is %s from that device, not a reserved source',
+ async (deviceId) => {
+ const target = { ...NOTES, deviceId };
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue(
+ textPreview('on device') as never,
+ );
+
+ const { result } = renderPreview(target);
+
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('on device')));
+ expect(projectFileService.getLocalFilePreview).toHaveBeenCalledWith({
+ allowExternalFile: undefined,
+ deviceId,
+ path: '/repo/notes.md',
+ workingDirectory: '/repo',
+ });
+ expect(cloudSandboxService.callTool).not.toHaveBeenCalled();
+ expect(localFilePreviewKey(target)).not.toBe(
+ localFilePreviewKey({ ...NOTES, deviceId: undefined }),
+ );
+ },
+ );
+
+ it('never persists the preview token URL', async () => {
+ const html = { ...NOTES, filePath: '/repo/index.html' };
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue(
+ textPreview('<p>hi</p>', {
+ contentType: 'text/html',
+ resourceBaseUrl: 'localfile://session-token/',
+ }) as never,
+ );
+
+ const { result } = renderPreview(html);
+
+ await waitFor(() =>
+ expect(result.current.preview).toMatchObject({
+ resourceBaseUrl: 'localfile://session-token/',
+ }),
+ );
+ await waitFor(async () =>
+ expect((await storedRow(html))?.data).toEqual({
+ content: '<p>hi</p>',
+ contentType: 'text/html',
+ type: 'text',
+ }),
+ );
+ });
+
+ it('keeps image previews in memory only', async () => {
+ const image = { ...NOTES, filePath: '/repo/logo.png' };
+ const blob = new Blob(['png'], { type: 'image/png' });
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue({
+ blob,
+ contentType: 'image/png',
+ type: 'image',
+ } as never);
+
+ const { result } = renderPreview(image);
+
+ await waitFor(() => expect(result.current.preview).toMatchObject({ type: 'image' }));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(await storedRow(image)).toBeUndefined();
+ });
+
+ it('drops the stored row once a file grows past the cap', async () => {
+ await seedRow(NOTES, textPreview('small'));
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue(
+ textPreview('x'.repeat(MAX_PERSISTED_PREVIEW_CHARS + 1)) as never,
+ );
+
+ const { result } = renderPreview(NOTES);
+
+ await waitFor(() =>
+ expect((result.current.preview as { content: string } | undefined)?.content.length).toBe(
+ MAX_PERSISTED_PREVIEW_CHARS + 1,
+ ),
+ );
+ await waitFor(async () => expect(await storedRow(NOTES)).toBeUndefined());
+ });
+
+ it('reads sandbox files through the sandbox tool', async () => {
+ const sandbox = {
+ filePath: '/workspace/a.txt',
+ sandboxTopicId: 'topic-1',
+ workingDirectory: '',
+ };
+ vi.mocked(cloudSandboxService.callTool).mockResolvedValue({
+ result: { content: 'from sandbox', mimeType: 'text/plain' },
+ success: true,
+ } as never);
+
+ const { result } = renderPreview(sandbox);
+
+ await waitFor(() =>
+ expect(result.current.preview).toEqual({
+ content: 'from sandbox',
+ contentType: 'text/plain',
+ type: 'text',
+ }),
+ );
+ expect(cloudSandboxService.callTool).toHaveBeenCalledWith(
+ 'readLocalFile',
+ { fullContent: true, path: '/workspace/a.txt' },
+ { topicId: 'topic-1' },
+ );
+ expect(projectFileService.getLocalFilePreview).not.toHaveBeenCalled();
+ });
+
+ it('keeps sandbox previews out of durable storage', async () => {
+ const sandbox = {
+ filePath: '/workspace/a.txt',
+ sandboxTopicId: 'topic-1',
+ workingDirectory: '',
+ };
+ // A row left behind by an older build must not paint a recycled sandbox's file.
+ await seedRow(sandbox, textPreview('stale sandbox copy'));
+ let answer: (value: unknown) => void = () => {};
+ vi.mocked(cloudSandboxService.callTool).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as never,
+ );
+
+ const { result } = renderPreview(sandbox);
+
+ await waitFor(() => expect(result.current.sync.isHydrated).toBe(true));
+ expect(result.current.preview).toBeUndefined();
+
+ await act(async () => {
+ answer({ result: { content: 'from sandbox', mimeType: 'text/plain' }, success: true });
+ });
+ await waitFor(() => expect(result.current.preview).toMatchObject({ content: 'from sandbox' }));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect((await storedRow(sandbox))?.data).toEqual(textPreview('stale sandbox copy'));
+ });
+
+ it('bounds the number of persisted previews per scope', () => {
+ expect(localFilePreviewResource.maxPersistedEntries).toBe(MAX_PERSISTED_PREVIEWS);
+ expect(MAX_PERSISTED_PREVIEWS).toBeGreaterThan(0);
+ });
+
+ it('folds a saved body into the preview and its stored row', async () => {
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue(
+ textPreview('before') as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('before')));
+
+ act(() => useLocalFilePreviewStore.getState().beginSave(NOTES)('after'));
+
+ expect(result.current.preview).toEqual(textPreview('after'));
+ await waitFor(async () => expect((await storedRow(NOTES))?.data).toEqual(textPreview('after')));
+ });
+
+ it('does not let a read started before a save replace the saved content', async () => {
+ await seedRow(NOTES, textPreview('v1'));
+ let answer: (preview: unknown) => void = () => {};
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('v1')));
+
+ // The mount-time read is still in flight when the user saves.
+ act(() => useLocalFilePreviewStore.getState().beginSave(NOTES)('saved'));
+ // …and it settles afterwards with the pre-save file.
+ await act(async () => {
+ answer(textPreview('v1'));
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(result.current.preview).toEqual(textPreview('saved'));
+ await waitFor(async () => expect((await storedRow(NOTES))?.data).toEqual(textPreview('saved')));
+ });
+
+ it('keeps the fresh read metadata (HTML base URL) when a save races it', async () => {
+ const PAGE: LocalFilePreviewTarget = {
+ filePath: '/repo/index.html',
+ workingDirectory: '/repo',
+ };
+ // The persisted copy carries no short-lived `resourceBaseUrl`.
+ await seedRow(PAGE, textPreview('<p>v1</p>', { contentType: 'text/html' }));
+ let answer: (preview: unknown) => void = () => {};
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)) as never,
+ );
+ const { result } = renderPreview(PAGE);
+ await waitFor(() => expect(result.current.preview?.type).toBe('text'));
+
+ act(() => useLocalFilePreviewStore.getState().beginSave(PAGE)('<p>saved</p>'));
+ await act(async () => {
+ answer(
+ textPreview('<p>v1</p>', {
+ contentType: 'text/html',
+ resourceBaseUrl: 'lobe-local://preview/token/',
+ }),
+ );
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ expect(result.current.preview).toEqual(
+ textPreview('<p>saved</p>', {
+ contentType: 'text/html',
+ resourceBaseUrl: 'lobe-local://preview/token/',
+ }),
+ );
+ });
+
+ it.each([404, 403])('evicts the cached text when the file read answers %i', async (status) => {
+ await seedRow(NOTES, textPreview('# obsolete'));
+ let fail: (error: unknown) => void = () => {};
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((_, reject) => (fail = reject)) as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('# obsolete')));
+
+ await act(async () => {
+ fail(new LocalFileResponseError(status));
+ });
+
+ await waitFor(() => expect(result.current.preview).toBeUndefined());
+ expect(result.current.sync.error).toBeInstanceOf(LocalFileResponseError);
+ await waitFor(async () => expect(await storedRow(NOTES)).toBeUndefined());
+ });
+
+ it('keeps the cached text when the file read fails transiently', async () => {
+ await seedRow(NOTES, textPreview('# cached'));
+ let fail: (error: unknown) => void = () => {};
+ vi.mocked(projectFileService.getLocalFilePreview).mockImplementation(
+ () => new Promise((_, reject) => (fail = reject)) as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('# cached')));
+
+ await act(async () => {
+ fail(new LocalFileResponseError(500));
+ });
+ await waitFor(() => expect(result.current.sync.error).toBeInstanceOf(LocalFileResponseError));
+
+ expect(result.current.preview).toEqual(textPreview('# cached'));
+ expect((await storedRow(NOTES))?.data).toEqual(textPreview('# cached'));
+ });
+
+ it('drops a save that settles under another identity', async () => {
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue(
+ textPreview('before') as never,
+ );
+ const { result } = renderPreview(NOTES);
+ await waitFor(() => expect(result.current.preview).toEqual(textPreview('before')));
+
+ // The save starts under this identity…
+ const commit = useLocalFilePreviewStore.getState().beginSave(NOTES);
+ // …and settles after an account / workspace switch.
+ useScope(`local-file-user-${randomUUID()}:personal`);
+ act(() => commit('saved under the previous identity'));
+
+ expect(result.current.preview).toEqual(textPreview('before'));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(await storedRow(NOTES)).toBeUndefined();
+ });
+});
diff --git a/src/store/localFilePreview/index.ts b/src/store/localFilePreview/index.ts
new file mode 100644
index 00000000000..5415552c9cd
--- /dev/null
+++ b/src/store/localFilePreview/index.ts
@@ -0,0 +1,193 @@
+import type { StoreApi } from 'zustand';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn, type UseBoundStoreWithEqualityFn } from 'zustand/traditional';
+
+import { isHtmlFile } from '@/components/HtmlPreview/fileType';
+import {
+ cacheScope,
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { cloudSandboxService } from '@/services/cloudSandbox';
+import { isTerminalLocalFileError } from '@/services/electron/localFileService';
+import { type LocalFilePreview, projectFileService } from '@/services/projectFile';
+
+import {
+ localFilePreviewKey,
+ localFilePreviewResource,
+ type LocalFilePreviewTarget,
+ localFilePreviewTargetFromKey,
+ toPersistedLocalFilePreview,
+} from './projection';
+
+export {
+ isPersistableLocalFilePreviewKey,
+ localFilePreviewKey,
+ localFilePreviewResource,
+ type LocalFilePreviewTarget,
+ MAX_PERSISTED_PREVIEW_CHARS,
+ MAX_PERSISTED_PREVIEWS,
+ toPersistedLocalFilePreview,
+} from './projection';
+
+/**
+ * Live-read a text file from the topic's cloud sandbox via the `readLocalFile`
+ * sandbox tool. There is no durable copy anywhere — a recycled sandbox (or any
+ * tool failure) rejects, surfacing the sandbox-unavailable empty state.
+ */
+const fetchSandboxFilePreview = async (
+ path: string,
+ topicId: string,
+): Promise<LocalFilePreview> => {
+ // `readLocalFile` defaults an omitted range to the first 200 lines — always
+ // request the whole file for previews so long files don't render truncated.
+ const result = await cloudSandboxService.callTool(
+ 'readLocalFile',
+ { fullContent: true, path },
+ { topicId },
+ );
+ if (!result.success || typeof result.result?.content !== 'string')
+ throw new Error(result.error?.message || 'Failed to read sandbox file');
+
+ return {
+ content: result.result.content,
+ contentType: result.result.mimeType || 'text/plain',
+ type: 'text',
+ };
+};
+
+const fetchLocalFilePreview = (key: string): Promise<LocalFilePreview> => {
+ const { allowExternalFile, deviceId, filePath, sandboxTopicId, workingDirectory } =
+ localFilePreviewTargetFromKey(key);
+ if (sandboxTopicId) return fetchSandboxFilePreview(filePath, sandboxTopicId);
+
+ // A local HTML file resolves its relative URLs against sibling files.
+ const resourceScope = !deviceId && isHtmlFile({ path: filePath }) ? 'workspace' : undefined;
+ return projectFileService.getLocalFilePreview({
+ allowExternalFile,
+ deviceId,
+ path: filePath,
+ ...(resourceScope && { resourceScope }),
+ workingDirectory,
+ });
+};
+
+/** What `useFetchPreview` reports; the preview itself is read with `useLocalFilePreview`. */
+export interface LocalFilePreviewSyncResult extends ReplicaSyncResult {
+ /** No preview yet (neither persisted nor fetched) and no error. */
+ isLoading: boolean;
+}
+
+export interface LocalFilePreviewStoreState {
+ /** Previews by {@link localFilePreviewKey}. */
+ previewMap: Record<string, LocalFilePreview>;
+ /** Replica bookkeeping for `previewMap`. */
+ previewReplica: ReplicaState<LocalFilePreview>;
+}
+
+interface LocalFilePreviewStore extends LocalFilePreviewStoreState {
+ /**
+ * Start a save of `target`: captures the identity (user / workspace scope) the
+ * save runs under and returns the commit that folds the saved text body into
+ * the preview, so a reload paints the saved file. The commit is a no-op once
+ * another identity is active — the body belongs to the scope that wrote it.
+ */
+ beginSave: (target: LocalFilePreviewTarget) => (content: string) => void;
+ /** Re-read the file from its device / sandbox. */
+ refreshPreview: (target: LocalFilePreviewTarget) => Promise<unknown>;
+ /** Fetch orchestration only; read the preview with `useLocalFilePreview`. */
+ useFetchPreview: (
+ target: LocalFilePreviewTarget | undefined,
+ enabled?: boolean,
+ ) => LocalFilePreviewSyncResult;
+}
+
+export const initialLocalFilePreviewState: LocalFilePreviewStoreState = {
+ previewMap: {},
+ previewReplica: createReplicaState(),
+};
+
+/**
+ * Annotated for the same reason as `useProjectDirectoryStore`: `useFetchPreview`
+ * reads this store inside its initializer, which would otherwise make the
+ * equality-fn overload infer its type circularly.
+ */
+export const useLocalFilePreviewStore: UseBoundStoreWithEqualityFn<
+ StoreApi<LocalFilePreviewStore>
+> = createWithEqualityFn<LocalFilePreviewStore>()((set, get) => {
+ /**
+ * Saves folded into each preview (by key). A read started before a save may
+ * still hold the pre-save file; once the save lands it must not replace the
+ * confirmed content — the same guard as the document detail's adoptions.
+ */
+ const saveGenerations = new Map<string, number>();
+
+ const previews = createReplicaSlice(localFilePreviewResource, {
+ actionPrefix: 'localFilePreview/previews',
+ fetcher: async (key) => {
+ const savedBefore = saveGenerations.get(key) ?? 0;
+ const preview = await fetchLocalFilePreview(key);
+ const current = get().previewMap[key];
+ if ((saveGenerations.get(key) ?? 0) === savedBefore || !current) return preview;
+ // A save landed while this read was in flight: keep the saved body, but
+ // take the rest of the fresh read — notably the `resourceBaseUrl` an HTML
+ // preview needs for its relative assets (never persisted, so the cached
+ // copy has none).
+ return preview.type === 'text' && current.type === 'text'
+ ? { ...preview, content: current.content }
+ : current;
+ },
+ effects: {
+ // The file was deleted or may no longer be read (desktop protocol 404 /
+ // 403): drop the cached text — on screen and in IndexedDB — so the portal
+ // reports it instead of rehydrating the obsolete body after a reload.
+ // Transient failures keep it (stale-while-revalidate).
+ onError: (error, _key, { key, scope }) => {
+ if (key && isTerminalLocalFileError(error)) previews.remove(key, scope);
+ },
+ },
+ get,
+ set,
+ stateKey: 'previewReplica',
+ toPersisted: toPersistedLocalFilePreview,
+ view: recordLens<LocalFilePreviewStore, LocalFilePreview>('previewMap'),
+ });
+
+ return {
+ ...initialLocalFilePreviewState,
+
+ beginSave: (target) => {
+ const key = localFilePreviewKey(target);
+ const scope = cacheScope.get();
+ return (content) => {
+ // The write settled after an account / workspace switch: `update` writes
+ // the active scope, which would plant this file body in another identity.
+ if (cacheScope.get() !== scope) return;
+ saveGenerations.set(key, (saveGenerations.get(key) ?? 0) + 1);
+ previews.update(key, (preview) =>
+ preview?.type === 'text' ? { ...preview, content } : preview,
+ );
+ };
+ },
+ refreshPreview: (target) => previews.revalidate(localFilePreviewKey(target)),
+ useFetchPreview: (target, enabled = true) => {
+ const key = target ? localFilePreviewKey(target) : undefined;
+ // The file's content is not something the user expects to change on a
+ // tab refocus; reloads are explicit (toolbar / `…` menu).
+ const sync = previews.useSync(key, { enabled, revalidateOnFocus: false });
+ const hasPreview = useLocalFilePreviewStore((state) =>
+ key ? state.previewMap[key] !== undefined : false,
+ );
+ return { ...sync, isLoading: enabled && !!key && !hasPreview && sync.error == null };
+ },
+ };
+}, shallow);
+
+/** The preview of one file, or `undefined` while nothing is loaded for it. */
+export const useLocalFilePreview = (target: LocalFilePreviewTarget | undefined) =>
+ useLocalFilePreviewStore((state) =>
+ target ? state.previewMap[localFilePreviewKey(target)] : undefined,
+ );
diff --git a/src/store/localFilePreview/projection.ts b/src/store/localFilePreview/projection.ts
new file mode 100644
index 00000000000..23a47af4dba
--- /dev/null
+++ b/src/store/localFilePreview/projection.ts
@@ -0,0 +1,111 @@
+import { defineReplica } from '@/libs/replica';
+import type { LocalFilePreview } from '@/services/projectFile';
+
+/** One file the local-file portal previews: where it lives and how it was opened. */
+export interface LocalFilePreviewTarget {
+ /** A user-picked file outside the approved workspace roots. */
+ allowExternalFile?: boolean;
+ /** Remote device the file lives on; absent = this machine. */
+ deviceId?: string;
+ filePath: string;
+ /** Read live from this topic's cloud sandbox instead of a filesystem. */
+ sandboxTopicId?: string;
+ workingDirectory: string;
+}
+
+/**
+ * Largest text preview (UTF-16 code units) kept across reloads. A huge log or
+ * generated file stays memory-only and simply refetches.
+ */
+export const MAX_PERSISTED_PREVIEW_CHARS = 256 * 1024;
+
+/** How many file previews survive a reload (`persist.maxEntries`). */
+export const MAX_PERSISTED_PREVIEWS = 30;
+
+/**
+ * Entry key of one preview: source (sandbox / device / this machine) +
+ * working directory + path, plus the external-file flag that changes what the
+ * read is allowed to reach. A string, so two mounts of the same tab share one
+ * entry and one sync query.
+ *
+ * The source kind and its id are separate fields: a device id is user-chosen
+ * (`lh connect --device-id`), so a device named `local` or `sandbox:x` must
+ * still decode as that device rather than this machine or a sandbox.
+ */
+export const localFilePreviewKey = ({
+ allowExternalFile,
+ deviceId,
+ filePath,
+ sandboxTopicId,
+ workingDirectory,
+}: LocalFilePreviewTarget): string =>
+ JSON.stringify([
+ ...(sandboxTopicId
+ ? ['sandbox', sandboxTopicId]
+ : deviceId
+ ? ['device', deviceId]
+ : ['local', null]),
+ workingDirectory,
+ filePath,
+ allowExternalFile ? 'external' : 'workspace',
+ ]);
+
+/** The target a {@link localFilePreviewKey} was built from (fetcher side). */
+export const localFilePreviewTargetFromKey = (key: string): LocalFilePreviewTarget => {
+ const [kind, id, workingDirectory, filePath, access] = JSON.parse(key) as [
+ 'device' | 'local' | 'sandbox',
+ string | null,
+ string,
+ string,
+ string,
+ ];
+ return {
+ allowExternalFile: access === 'external' || undefined,
+ deviceId: kind === 'device' ? (id ?? undefined) : undefined,
+ filePath,
+ sandboxTopicId: kind === 'sandbox' ? (id ?? undefined) : undefined,
+ workingDirectory,
+ };
+};
+
+/**
+ * What of a preview survives a reload: text previews only, up to
+ * {@link MAX_PERSISTED_PREVIEW_CHARS}. Images / documents hold Blobs and video /
+ * binary placeholders are cheap to recompute, so they stay memory-only.
+ * `resourceBaseUrl` embeds a short-lived desktop preview token, so it is never
+ * stored; the background refresh brings a fresh one.
+ *
+ * `null` = do not persist, and drop a row stored earlier (a file that grew past
+ * the cap or turned binary must not come back on the next boot).
+ */
+export const toPersistedLocalFilePreview = (preview: LocalFilePreview): LocalFilePreview | null =>
+ preview.type === 'text' && preview.content.length <= MAX_PERSISTED_PREVIEW_CHARS
+ ? { content: preview.content, contentType: preview.contentType, type: 'text' }
+ : null;
+
+/**
+ * Whether a preview may touch storage. A cloud-sandbox file is a live read with
+ * no durable copy anywhere — once the sandbox is recycled the file is gone — so
+ * its content must not outlive the session in IndexedDB. Sandbox previews stay
+ * memory-only (no persist, no hydrate).
+ */
+export const isPersistableLocalFilePreviewKey = (key: string): boolean =>
+ !localFilePreviewTargetFromKey(key).sandboxTopicId;
+
+/**
+ * File previews of the local-file portal, one entry per opened file. Previews
+ * of files on this machine or a device are persisted to IndexedDB under the
+ * user / workspace scope, so a reload paints the last text the portal showed
+ * while the device confirms it. At most {@link MAX_PERSISTED_PREVIEWS} rows are
+ * kept per scope (least recently used evicted), and rows hydrate per opened
+ * file, not at startup.
+ */
+export const localFilePreviewResource = defineReplica<string, LocalFilePreview>({
+ key: (key) => key,
+ name: 'localFilePreview',
+ persist: { maxEntries: MAX_PERSISTED_PREVIEWS },
+ persistKey: isPersistableLocalFilePreviewKey,
+ storage: 'indexedDB',
+ // v2: the key splits the source kind from its id; v1 rows are dropped.
+ version: 2,
+});