🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(document): add history management and compare workflow (#13725)
Inneif1d615fa9f3d
diff --git a/.agents/skills/modal/SKILL.md b/.agents/skills/modal/SKILL.mdindex 16479734167..6d9bb936f6b 100644--- a/.agents/skills/modal/SKILL.md+++ b/.agents/skills/modal/SKILL.md@@ -1,64 +1,76 @@---name: modal-description: Modal imperative API guide. Use when creating modal dialogs using createModal from @lobehub/ui. Triggers on modal component implementation or dialog creation tasks.+description: MUST use when creating, editing, or writing modal dialogs or imperative modals. Prefer createModal / useModalContext / confirmModal from @lobehub/ui/base-ui; root @lobehub/ui is legacy (antd Modal). Covers patterns, ModalHost, and migration notes.user-invocable: false---# Modal Imperative API Guide-Use `createModal` from `@lobehub/ui` for imperative modal dialogs.+## Recommended: `@lobehub/ui/base-ui`-## Why Imperative?+New code should use the **base-ui** modal stack (headless primitives, not antd `Modal`):-| Mode | Characteristics | Recommended |-| ----------- | ------------------------------------- | ----------- |-| Declarative | Need `open` state, render `<Modal />` | ❌ |-| Imperative | Call function directly, no state | ✅ |+- `createModal`, `confirmModal`, `ModalHost` from `@lobehub/ui/base-ui`+- `useModalContext` from `@lobehub/ui/base-ui` inside modal **content**-## File Structure+Body slot: pass **`content`** (or `children`; runtime uses `content ?? children`).++### Global `ModalHost` (required)++Base-ui `createModal` renders through a **separate** host from the root package. The app must mount **`ModalHost`** from `@lobehub/ui/base-ui` once near the root (e.g. next to other global hosts). Without it, `createModal` calls will not appear.++If the project only mounts `ModalHost` from `@lobehub/ui`, add a second lazy `ModalHost` from `@lobehub/ui/base-ui` until all imperative modals are migrated.++### Why imperative?++| Mode | Characteristics | Recommended |+| ----------- | ------------------------------------ | ----------- |+| Declarative | `open` state + `<Modal />` | ❌ |+| Imperative | Call `createModal()`, no local state | ✅ |++### File structure```features/└── MyFeatureModal/- ├── index.tsx # Export createXxxModal- └── MyFeatureContent.tsx # Modal content+ ├── index.tsx # export createXxxModal+ └── MyFeatureContent.tsx # modal body```-## Implementation--### 1. Content Component (`MyFeatureContent.tsx`)+### 1. Content (`MyFeatureContent.tsx`)```tsx'use client';-import { useModalContext } from '@lobehub/ui';+import { useModalContext } from '@lobehub/ui/base-ui';import { useTranslation } from 'react-i18next';export const MyFeatureContent = () => {const { t } = useTranslation('namespace');- const { close } = useModalContext(); // Optional: get close method+ const { close } = useModalContext();- return <div>{/* Modal content */}</div>;+ return <div>{/* ... */}</div>;};```-### 2. Export createModal (`index.tsx`)+### 2. `createModal` (`index.tsx`)```tsx'use client';-import { createModal } from '@lobehub/ui';-import { t } from 'i18next'; // Note: use i18next, not react-i18next+import { createModal } from '@lobehub/ui/base-ui';+import { t } from 'i18next';import { MyFeatureContent } from './MyFeatureContent';export const createMyFeatureModal = () =>createModal({- allowFullscreen: true,- children: <MyFeatureContent />,- destroyOnHidden: false,+ content: <MyFeatureContent />,footer: null,- styles: { body: { overflow: 'hidden', padding: 0 } },+ maskClosable: true,+ styles: {+ content: { overflow: 'hidden', padding: 0 },+ },title: t('myFeature.title', { ns: 'setting' }),width: 'min(80%, 800px)',});@@ -76,27 +88,52 @@ const handleOpen = useCallback(() => {return <Button onClick={handleOpen}>Open</Button>;```-## i18n Handling+### i18n-- **Content component**: `useTranslation` hook (React context)-- **createModal params**: `import { t } from 'i18next'` (non-hook, imperative)+- **Content**: `useTranslation` in components.+- **`createModal` options**: `import { t } from 'i18next'` where hooks are unavailable.-## useModalContext Hook+### `useModalContext````tsxconst { close, setCanDismissByClickOutside } = useModalContext();```-## Common Config+### Common options (base-ui)++`ImperativeModalProps` builds on `BaseModalProps`: `title`, `width`, `maskClosable`, `open`, `onOpenChange`, `footer`, `styles` / `classNames` (keys: `backdrop`, `popup`, `header`, `title`, `close`, `content`, …).++| Property | Notes |+| -------------- | ---------------------------------------- |+| `content` | Main body (preferred name vs `children`) |+| `maskClosable` | Click outside to dismiss |+| `styles.*` | Semantic regions, not antd `styles.body` |++### Confirm-| Property | Type | Description |-| ----------------- | ------------------- | ------------------------ |-| `allowFullscreen` | `boolean` | Allow fullscreen mode |-| `destroyOnHidden` | `boolean` | Destroy content on close |-| `footer` | `ReactNode \| null` | Footer content |-| `width` | `string \| number` | Modal width |+```tsx+import { confirmModal } from '@lobehub/ui/base-ui';++confirmModal({+ title: '…',+ content: '…',+ okText: '…',+ cancelText: '…',+ onOk: async () => {},+});+```++---++## Legacy: `@lobehub/ui` (root)++Older call sites use **`createModal` from `@lobehub/ui`**, which is typed as **antd `Modal` props** (`children`, `allowFullscreen`, `getContainer`, `destroyOnHidden`, `styles.body`, etc.). Prefer migrating new work to **`@lobehub/ui/base-ui`**.++Examples (legacy): `src/features/SkillStore/index.tsx`, `src/features/LibraryModal/CreateNew/index.tsx`.++---## Examples-- `src/features/SkillStore/index.tsx`-- `src/features/LibraryModal/CreateNew/index.tsx`+- Base-ui (preferred): follow sections above; ensure **base-ui `ModalHost`** is mounted.+- Legacy: `src/features/SkillStore/index.tsx`, `src/features/LibraryModal/CreateNew/index.tsx`diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex c3100ca5cad..62483d18f9b 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -90,6 +90,32 @@"pageEditor.exportDialogTitle": "Export Page","pageEditor.exportError": "Failed to export the page","pageEditor.exportSuccess": "Page exported successfully",+ "pageEditor.history.backToCopilot": "Copilot",+ "pageEditor.history.compare": "Compare",+ "pageEditor.history.compareCurrentLabel": "Current",+ "pageEditor.history.compareDescription": "Compare the current content with the selected history state",+ "pageEditor.history.compareError": "Failed to load diff preview",+ "pageEditor.history.compareModalTitle": "Compare",+ "pageEditor.history.compareOldLabel": "Restore To",+ "pageEditor.history.compareTitle": "Version Diff",+ "pageEditor.history.current": "Current",+ "pageEditor.history.dayLabel.today": "Today",+ "pageEditor.history.dayLabel.yesterday": "Yesterday",+ "pageEditor.history.empty": "No version history yet",+ "pageEditor.history.itemVersionLabel": "v{{version}}",+ "pageEditor.history.restore": "Restore",+ "pageEditor.history.restoreConfirm.content": "Restore the page to how it was at {{savedAt}}? Your current content will be replaced and saved.",+ "pageEditor.history.restoreConfirm.title": "Restore from history",+ "pageEditor.history.restoreError": "Failed to restore from history",+ "pageEditor.history.saveSource.autosave": "Auto Save",+ "pageEditor.history.saveSource.llm_call": "AI Edit",+ "pageEditor.history.saveSource.manual": "Manual Save",+ "pageEditor.history.saveSource.restore": "Restore",+ "pageEditor.history.saveSource.system": "System",+ "pageEditor.history.title": "Version History",+ "pageEditor.history.versionCount_one": "{{count}} version",+ "pageEditor.history.versionCount_other": "{{count}} versions",+ "pageEditor.history.versionLabel": "v{{version}}","pageEditor.linkCopied": "Link copied","pageEditor.menu.copyLink": "Copy Link","pageEditor.menu.export": "Export",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex a477a06ac6f..18caf329529 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -90,6 +90,31 @@"pageEditor.exportDialogTitle": "导出页面","pageEditor.exportError": "页面导出失败","pageEditor.exportSuccess": "页面导出成功",+ "pageEditor.history.backToCopilot": "返回 Copilot",+ "pageEditor.history.compare": "对比",+ "pageEditor.history.compareCurrentLabel": "当前",+ "pageEditor.history.compareDescription": "对比当前内容与所选历史状态",+ "pageEditor.history.compareError": "加载差异预览失败",+ "pageEditor.history.compareModalTitle": "对比",+ "pageEditor.history.compareOldLabel": "回退到",+ "pageEditor.history.compareTitle": "版本差异",+ "pageEditor.history.current": "当前版本",+ "pageEditor.history.dayLabel.today": "今天",+ "pageEditor.history.dayLabel.yesterday": "昨天",+ "pageEditor.history.empty": "还没有可用的历史版本",+ "pageEditor.history.itemVersionLabel": "v{{version}}",+ "pageEditor.history.restore": "恢复",+ "pageEditor.history.restoreConfirm.content": "确定恢复到 {{savedAt}} 保存的内容吗?当前文稿将被替换并保存。",+ "pageEditor.history.restoreConfirm.title": "从历史恢复",+ "pageEditor.history.restoreError": "恢复失败",+ "pageEditor.history.saveSource.autosave": "自动保存",+ "pageEditor.history.saveSource.manual": "手动保存",+ "pageEditor.history.saveSource.restore": "恢复",+ "pageEditor.history.saveSource.system": "系统",+ "pageEditor.history.title": "版本历史",+ "pageEditor.history.versionCount_one": "共 {{count}} 个版本",+ "pageEditor.history.versionCount_other": "共 {{count}} 个版本",+ "pageEditor.history.versionLabel": "v{{version}}","pageEditor.linkCopied": "链接已复制","pageEditor.menu.copyLink": "复制链接","pageEditor.menu.export": "导出",diff --git a/package.json b/package.jsonindex 3622ab08d15..cdcd369cf0c 100644--- a/package.json+++ b/package.json@@ -340,6 +340,7 @@"ioredis": "^5.9.2","jose": "^6.1.3","js-sha256": "^0.11.1",+ "jsondiffpatch": "^0.7.3","jsonl-parse-stringify": "^1.0.3","klavis": "^2.15.0","langfuse": "^3.38.6",diff --git a/packages/database/src/models/documentHistory.ts b/packages/database/src/models/documentHistory.tsindex 33db361ef68..cd6c63208ae 100644--- a/packages/database/src/models/documentHistory.ts+++ b/packages/database/src/models/documentHistory.ts@@ -1,10 +1,11 @@-import { and, desc, eq, lt } from 'drizzle-orm';+import { and, desc, eq, lt, or } from 'drizzle-orm';import type { DocumentHistoryItem, NewDocumentHistory } from '../schemas';import { documentHistories, documents } from '../schemas';import type { LobeChatDatabase } from '../type';export interface QueryDocumentHistoryParams {+ beforeId?: string;beforeSavedAt?: Date;documentId: string;limit?: number;@@ -86,6 +87,7 @@ export class DocumentHistoryModel {};list = async ({+ beforeId,beforeSavedAt,documentId,limit = 50,@@ -96,7 +98,17 @@ export class DocumentHistoryModel {];if (beforeSavedAt !== undefined) {- conditions.push(lt(documentHistories.savedAt, beforeSavedAt));+ if (beforeId !== undefined) {+ const cursorCondition = or(+ lt(documentHistories.savedAt, beforeSavedAt),+ and(eq(documentHistories.savedAt, beforeSavedAt), lt(documentHistories.id, beforeId)),+ );+ if (cursorCondition) {+ conditions.push(cursorCondition);+ }+ } else {+ conditions.push(lt(documentHistories.savedAt, beforeSavedAt));+ }}return this.dbdiff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex e60b1cd758c..79ed89bc144 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -33,6 +33,7 @@ export class EditorRuntime {private titleSetter: ((title: string) => void) | null = null;private titleGetter: (() => string) | null = null;private currentDocId: string | undefined = undefined;+ private beforeMutateHandler: (() => void | Promise<void>) | null = null;/*** Set the current editor instance@@ -56,6 +57,14 @@ export class EditorRuntime {return this.currentDocId;}+ /**+ * Set a handler to be called before any mutating operation.+ * This can be used to save history or perform other pre-mutation tasks.+ */+ setBeforeMutateHandler(handler: (() => void | Promise<void>) | null) {+ this.beforeMutateHandler = handler;+ }+/*** Set the title setter and getter functions*/@@ -91,17 +100,23 @@ export class EditorRuntime {* @returns Raw result with nodeCount and extractedTitle*/async initPage(args: InitDocumentArgs): Promise<InitPageRuntimeResult> {+ try {+ await this.beforeMutateHandler?.();+ } catch {+ /* ignore pre-mutation errors */+ }const editor = this.getEditor();let markdown = args.markdown;let extractedTitle: string | undefined;// Check if markdown starts with a # title heading- const titleMatch = /^#\s+(.+)(?:\r?\n|$)/.exec(markdown);- if (titleMatch) {- extractedTitle = titleMatch[1].trim();+ if (markdown.startsWith('# ')) {+ const endOfLine = markdown.search(/\r?\n/);+ const titleLine = endOfLine === -1 ? markdown : markdown.slice(0, endOfLine);+ extractedTitle = titleLine.slice(2).trim();// Remove the title line from markdown- markdown = markdown.slice(titleMatch[0].length).trimStart();+ markdown = markdown.slice(titleLine.length).trimStart();// Set the title separately if title handlers are availableif (this.titleSetter) {@@ -126,6 +141,11 @@ export class EditorRuntime {* @returns Raw result with newTitle and previousTitle*/async editTitle(args: EditTitleArgs): Promise<EditTitleRuntimeResult> {+ try {+ await this.beforeMutateHandler?.();+ } catch {+ /* ignore pre-mutation errors */+ }const { setter, getter } = this.getTitleHandlers();const previousTitle = getter();@@ -193,6 +213,11 @@ export class EditorRuntime {* @returns Raw result with results, successCount and totalCount*/async modifyNodes(args: ModifyNodesArgs): Promise<ModifyNodesRuntimeResult> {+ try {+ await this.beforeMutateHandler?.();+ } catch {+ /* ignore pre-mutation errors */+ }const editor = this.getEditor();let { operations } = args;@@ -448,6 +473,11 @@ export class EditorRuntime {* @returns Raw result with modifiedNodeIds and replacementCount*/async replaceText(args: ReplaceTextArgs): Promise<ReplaceTextRuntimeResult> {+ try {+ await this.beforeMutateHandler?.();+ } catch {+ /* ignore pre-mutation errors */+ }const editor = this.getEditor();const { searchText, newText, useRegex = false, replaceAll = true, nodeIds } = args;@@ -531,8 +561,9 @@ export class EditorRuntime {// Build the updated LiteXML for this node// Extract attributes from the original fullMatch- const attrMatch = /<\w+\s+([^>]*)>/.exec(node.fullMatch);- const attributes = attrMatch ? attrMatch[1] : `id="${node.id}"`;+ const firstSpace = node.fullMatch.indexOf(' ');+ const attributes =+ firstSpace > 0 ? node.fullMatch.slice(firstSpace + 1, -1) : `id="${node.id}"`;const updatedLitexml = `<${node.tagName} ${attributes}>${newContent}</${node.tagName}>`;litexmlUpdates.push(updatedLitexml);diff --git a/packages/editor-runtime/src/__tests__/EditorRuntime.test.ts b/packages/editor-runtime/src/__tests__/EditorRuntime.test.tsindex df8518ed18f..e3312800210 100644--- a/packages/editor-runtime/src/__tests__/EditorRuntime.test.ts+++ b/packages/editor-runtime/src/__tests__/EditorRuntime.test.ts@@ -523,6 +523,66 @@ describe('EditorRuntime', () => {});});+ describe('beforeMutateHandler', () => {+ it('should call beforeMutateHandler before initPage', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ runtime.setBeforeMutateHandler(handler);++ await runtime.initPage({ markdown: 'Test content' });+ await moment();++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('should call beforeMutateHandler before editTitle', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ runtime.setBeforeMutateHandler(handler);++ await runtime.editTitle({ title: 'New Title' });++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('should call beforeMutateHandler before modifyNodes', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ runtime.setBeforeMutateHandler(handler);++ await runtime.modifyNodes({+ operations: [{ action: 'insert', afterId: 'root', litexml: '<p>Test</p>' }],+ });++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('should call beforeMutateHandler before replaceText', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ runtime.setBeforeMutateHandler(handler);++ await runtime.replaceText({ searchText: 'old', newText: 'new' });++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('should still proceed when beforeMutateHandler is not set', async () => {+ runtime.setBeforeMutateHandler(null);++ const result = await runtime.editTitle({ title: 'Another Title' });+ expect(result.newTitle).toBe('Another Title');+ });++ it('should still proceed when beforeMutateHandler throws', async () => {+ const handler = vi.fn().mockRejectedValue(new Error('Handler failed'));+ runtime.setBeforeMutateHandler(handler);++ // Should not throw; initPage should proceed+ const result = await runtime.initPage({ markdown: 'Test content' });+ await moment();++ expect(handler).toHaveBeenCalledTimes(1);+ expect(result.nodeCount).toBeGreaterThanOrEqual(0);+ });+ });+describe('getPageContentContext', () => {beforeEach(async () => {await runtime.initPage({ markdown: 'Test content for context' });diff --git a/src/const/documentHistory.ts b/src/const/documentHistory.tsnew file mode 100644index 00000000000..bbce4e863d0--- /dev/null+++ b/src/const/documentHistory.ts@@ -0,0 +1,13 @@+import type { DocumentHistorySaveSource } from '@/server/services/document/types';++export const DOCUMENT_HISTORY_QUERY_LIST_LIMIT = 50;++export const FREE_DOCUMENT_HISTORY_WINDOW_DAYS = 30;++export const DOCUMENT_HISTORY_SOURCE_LIMITS: Record<DocumentHistorySaveSource, number> = {+ autosave: 20,+ manual: 20,+ restore: 5,+ system: 5,+ llm_call: 5,+};diff --git a/src/features/EditorCanvas/DiffAllToolbar.tsx b/src/features/EditorCanvas/DiffAllToolbar.tsxindex 87e3e89841b..dd25e407532 100644--- a/src/features/EditorCanvas/DiffAllToolbar.tsx+++ b/src/features/EditorCanvas/DiffAllToolbar.tsx@@ -115,7 +115,7 @@ const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId }) => {const handleSave = async () => {markDirty(documentId);- await performSave();+ await performSave(undefined, undefined, { saveSource: 'manual' });};return (diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsxnew file mode 100644index 00000000000..e2e6b793408--- /dev/null+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx@@ -0,0 +1,98 @@+/**+ * @vitest-environment happy-dom+ */+import { act, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import DocumentIdMode from './DocumentIdMode';++const handleContentChangeStore = vi.fn();+const performSave = vi.fn();+const flushSave = vi.fn();+const onEditorInit = vi.fn().mockResolvedValue(undefined);+const useFetchDocument = vi.fn(() => ({ error: undefined }));++let saveHotkeyHandler: (() => void | Promise<void>) | undefined;++const mockDocumentStore = {+ flushSave,+ handleContentChange: handleContentChangeStore,+ onEditorInit,+ performSave,+ useFetchDocument,+};++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('zustand-utils', () => ({+ createStoreUpdater: () => () => undefined,+}));++vi.mock('@/hooks/useHotkeys', () => ({+ useSaveDocumentHotkey: vi.fn((handler: () => void | Promise<void>) => {+ saveHotkeyHandler = handler;+ }),+}));++vi.mock('@/store/document', () => ({+ useDocumentStore: Object.assign(+ vi.fn((selector: (state: typeof mockDocumentStore) => unknown) => selector(mockDocumentStore)),+ {+ getState: vi.fn(() => ({ documents: {} })),+ },+ ),+}));++vi.mock('@/store/document/slices/editor', () => ({+ editorSelectors: {+ isDirty: vi.fn(() => () => false),+ isDocumentLoading: vi.fn(() => () => false),+ },+}));++vi.mock('./InternalEditor', () => ({+ default: vi.fn(() => <div data-testid="internal-editor" />),+}));++vi.mock('./UnsavedChangesGuard', () => ({+ default: vi.fn(() => null),+}));++describe('DocumentIdMode', () => {+ beforeEach(() => {+ handleContentChangeStore.mockClear();+ performSave.mockClear();+ flushSave.mockClear();+ onEditorInit.mockClear();+ useFetchDocument.mockClear();+ saveHotkeyHandler = undefined;+ });++ it('should save with manual source when save hotkey is triggered', async () => {+ render(+ <DocumentIdMode+ documentId="doc-1"+ editor={+ {+ getLexicalEditor: vi.fn(() => ({})),+ } as any+ }+ />,+ );++ expect(screen.getByTestId('internal-editor')).toBeInTheDocument();+ expect(saveHotkeyHandler).toBeDefined();++ await act(async () => {+ await saveHotkeyHandler?.();+ });++ expect(handleContentChangeStore).toHaveBeenCalledTimes(1);+ expect(performSave).toHaveBeenCalledWith('doc-1', undefined, { saveSource: 'manual' });+ expect(flushSave).not.toHaveBeenCalled();+ });+});diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsxindex 436c3c28f22..7bc7bae9a33 100644--- a/src/features/EditorCanvas/DocumentIdMode.tsx+++ b/src/features/EditorCanvas/DocumentIdMode.tsx@@ -66,16 +66,20 @@ const DocumentIdMode = memo<DocumentIdModeProps>(storeUpdater('editor', editor);// Get document store actions- const [onEditorInit, handleContentChangeStore, useFetchDocument, performSave, flushSave] =+ const [onEditorInit, handleContentChangeStore, useFetchDocument, performSave] =useDocumentStore((s) => [s.onEditorInit,s.handleContentChange,s.useFetchDocument,s.performSave,- s.flushSave,]);- useSaveDocumentHotkey(flushSave);+ const handleManualSave = useCallback(async () => {+ handleContentChangeStore();+ await performSave(documentId, undefined, { saveSource: 'manual' });+ }, [documentId, handleContentChangeStore, performSave]);++ useSaveDocumentHotkey(handleManualSave);// Use SWR hook for document fetching (auto-initializes via onSuccess in DocumentStore)const { error } = useFetchDocument(documentId, { autoSave, editor, sourceType });@@ -89,7 +93,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(if (!shouldGuardUnsavedChanges) return true;handleContentChangeStore();- await performSave(documentId);+ await performSave(documentId, undefined, { saveSource: 'system' });const latestDocument = useDocumentStore.getState().documents[documentId];return latestDocument ? !latestDocument.isDirty : true;diff --git a/src/features/NavPanel/components/NavPanelDraggable.tsx b/src/features/NavPanel/components/NavPanelDraggable.tsxindex f2f44ed051f..ad2f689fa7d 100644--- a/src/features/NavPanel/components/NavPanelDraggable.tsx+++ b/src/features/NavPanel/components/NavPanelDraggable.tsx@@ -1,9 +1,10 @@'use client';-import { DraggablePanel } from '@lobehub/ui';+import { DraggablePanel, Freeze } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';+import { AnimatePresence, m, useIsPresent } from 'motion/react';import { type ReactNode } from 'react';-import { memo, Suspense, useMemo, useRef } from 'react';+import { memo, Suspense, useLayoutEffect, useMemo, useRef } from 'react';import { isDesktop } from '@/const/version';import { TOGGLE_BUTTON_ID } from '@/features/NavPanel/ToggleLeftPanelButton';@@ -11,11 +12,39 @@ import Footer from '@/routes/(main)/home/_layout/Footer';import { USER_DROPDOWN_ICON_ID } from '@/routes/(main)/home/_layout/Header/components/User';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { useUserStore } from '@/store/user';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';+import type { PanelSlideMotionDirection } from '@/utils/motion/panelSlideMotion';+import {+ isPanelLayerMotionDisabled,+ panelSlideMotionVariantsLeft,+} from '@/utils/motion/panelSlideMotion';import { isMacOS } from '@/utils/platform';import { useNavPanelSizeChangeHandler } from '../hooks/useNavPanel';import { BACK_BUTTON_ID } from './BackButton';+const getMotionDirectionByHistory = (+ history: string[],+ nextKey: string,+): PanelSlideMotionDirection => {+ const currentKey = history.at(-1);+ if (currentKey === nextKey) return 0;++ return history.includes(nextKey) ? -1 : 1;+};++interface ExitingFrozenContentProps {+ children: ReactNode;+}++const ExitingFrozenContent = memo<ExitingFrozenContentProps>(({ children }) => {+ const isPresent = useIsPresent();+ return <Freeze frozen={!isPresent}>{children}</Freeze>;+});++ExitingFrozenContent.displayName = 'ExitingFrozenContent';+const draggableStyles = createStaticStyles(({ css, cssVar }) => ({content: css`position: relative;@@ -110,6 +139,8 @@ export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent }systemStatusSelectors.showLeftPanel(s),s.toggleLeftPanel,]);+ const animationMode = useUserStore(userGeneralSettingsSelectors.animationMode);+ const shouldUseMotion = !isPanelLayerMotionDisabled(animationMode);const handleSizeChange = useNavPanelSizeChangeHandler();const defaultWidthRef = useRef(0);@@ -132,6 +163,35 @@ export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent }[],);+ const historyRef = useRef([activeContent.key]);+ const directionRef = useRef<PanelSlideMotionDirection>(0);++ const history = historyRef.current;+ const direction = shouldUseMotion ? getMotionDirectionByHistory(history, activeContent.key) : 0;+ if (direction !== 0) {+ directionRef.current = direction;+ }++ useLayoutEffect(() => {+ if (!shouldUseMotion) return;++ const snapshot = historyRef.current;+ const currentKey = snapshot.at(-1);+ const nextKey = activeContent.key;++ if (currentKey === nextKey) return;++ const existingIndex = snapshot.lastIndexOf(nextKey);+ if (existingIndex !== -1) {+ snapshot.splice(existingIndex + 1);+ return;+ }++ snapshot.push(nextKey);+ }, [activeContent.key, shouldUseMotion]);++ const motionDirection = shouldUseMotion ? directionRef.current : 0;+return (<DraggablePanelclassName={draggableStyles.panel}@@ -148,9 +208,26 @@ export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent }onSizeDragging={handleSizeChange}><div className={draggableStyles.inner}>- <div className={draggableStyles.layer} key={activeContent.key}>- {activeContent.node}- </div>+ {shouldUseMotion ? (+ <AnimatePresence custom={motionDirection} initial={false} mode="sync">+ <m.div+ animate="animate"+ className={draggableStyles.layer}+ custom={motionDirection}+ exit="exit"+ initial="initial"+ key={activeContent.key}+ transition={panelSlideMotionVariantsLeft.transition}+ variants={panelSlideMotionVariantsLeft}+ >+ <ExitingFrozenContent>{activeContent.node}</ExitingFrozenContent>+ </m.div>+ </AnimatePresence>+ ) : (+ <div className={draggableStyles.layer} key={activeContent.key}>+ {activeContent.node}+ </div>+ )}</div><Suspense><Footer />diff --git a/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx b/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsxindex d2d1738da66..766cdbd1fb9 100644--- a/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx+++ b/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx@@ -30,6 +30,7 @@ export const useAskCopilotItem = (editor: IEditor | undefined): ChatInputActionsconst { t } = useTranslation('common');const addSelectionContext = useFileStore((s) => s.addChatContextSelection);const pageId = usePageEditorStore((s) => s.documentId);+ const setRightPanelMode = usePageEditorStore((s) => s.setRightPanelMode);return useMemo(() => {if (!editor) return [];@@ -74,6 +75,7 @@ export const useAskCopilotItem = (editor: IEditor | undefined): ChatInputActions});// Open right panel if not opened+ setRightPanelMode('copilot');useGlobalStore.getState().toggleRightPanel(true);// Focus on chat input after a short delay to ensure panel is opened@@ -100,5 +102,5 @@ export const useAskCopilotItem = (editor: IEditor | undefined): ChatInputActionsonClick: () => {},},];- }, [addSelectionContext, editor, pageId, t]);+ }, [addSelectionContext, editor, pageId, setRightPanelMode, t]);};diff --git a/src/features/PageEditor/Header/index.tsx b/src/features/PageEditor/Header/index.tsxindex 70bf8d56c27..109dbfbec3c 100644--- a/src/features/PageEditor/Header/index.tsx+++ b/src/features/PageEditor/Header/index.tsx@@ -43,7 +43,6 @@ const Header = memo(() => {</Text></>)}- {/* Auto Save Status */}{documentId && <AutoSaveHint documentId={documentId} style={{ marginLeft: 6 }} />}</>}diff --git a/src/features/PageEditor/Header/useMenu.tsx b/src/features/PageEditor/Header/useMenu.tsxindex 836d69c1806..3c805bc5114 100644--- a/src/features/PageEditor/Header/useMenu.tsx+++ b/src/features/PageEditor/Header/useMenu.tsx@@ -4,7 +4,7 @@ import { Icon } from '@lobehub/ui';import { App } from 'antd';import { cssVar, useResponsive } from 'antd-style';import dayjs from 'dayjs';-import { CopyPlus, Download, Link2, Maximize2, Trash2 } from 'lucide-react';+import { Clock3Icon, CopyPlus, Download, Link2, Maximize2, Trash2 } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -33,8 +33,10 @@ export const useMenu = (): { menuItems: any[] } => {);const duplicateDocument = useFileStore((s) => s.duplicateDocument);+ const setRightPanelMode = usePageEditorStore((s) => s.setRightPanelMode);- const [wideScreen, toggleWideScreen] = useGlobalStore((s) => [+ const [toggleRightPanel, wideScreen, toggleWideScreen] = useGlobalStore((s) => [+ s.toggleRightPanel,systemStatusSelectors.wideScreen(s),s.toggleWideScreen,]);@@ -119,6 +121,15 @@ export const useMenu = (): { menuItems: any[] } => {state.handleCopyLink(t as any, message);},},+ {+ icon: <Icon icon={Clock3Icon} />,+ key: 'version-history',+ label: t('pageEditor.history.title'),+ onClick: () => {+ setRightPanelMode('history');+ toggleRightPanel(true);+ },+ },{danger: true,icon: <Icon icon={Trash2} />,@@ -175,8 +186,10 @@ export const useMenu = (): { menuItems: any[] } => {t,message,modal,+ setRightPanelMode,wideScreen,toggleWideScreen,+ toggleRightPanel,showViewModeSwitch,handleDuplicate,handleExportMarkdown,diff --git a/src/features/PageEditor/History/CompareModal/CompareContent.tsx b/src/features/PageEditor/History/CompareModal/CompareContent.tsxnew file mode 100644index 00000000000..8f7996c3775--- /dev/null+++ b/src/features/PageEditor/History/CompareModal/CompareContent.tsx@@ -0,0 +1,158 @@+'use client';++import { Button, Flexbox, Text } from '@lobehub/ui';+import { createStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import { RotateCcwIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type {+ DocumentHistoryListItem,+ DocumentHistorySaveSource,+} from '@/server/routers/lambda/_schema/documentHistory';++import DocumentHistoryDiff from '../DocumentHistoryDiff';+import { formatHistoryAbsoluteTime } from '../formatHistoryDate';+import HistorySidebar from './HistorySidebar';++const useStyles = createStyles(({ css, token }) => ({+ arrow: css`+ font-size: 12px;+ color: ${token.colorTextTertiary};+ `,+ badgeNew: css`+ display: inline-flex;+ gap: 4px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 8px;+ border-radius: 4px;++ font-size: 11px;+ font-weight: 600;+ line-height: 1.2;+ color: ${token.colorSuccess};++ background: ${token.colorSuccessBg};+ `,+ badgeOld: css`+ display: inline-flex;+ align-items: center;++ padding-block: 2px;+ padding-inline: 8px;+ border-radius: 4px;++ font-size: 11px;+ font-weight: 600;+ line-height: 1.2;+ color: ${token.colorError};++ background: ${token.colorErrorBg};+ `,+ cmpbar: css`+ display: flex;+ align-items: center;+ justify-content: space-between;++ padding-block: 10px;+ padding-inline: 16px;+ border-block-end: 1px solid ${token.colorBorderSecondary};++ background: ${token.colorBgLayout};+ `,+ diffArea: css`+ overflow: hidden;+ display: flex;+ flex: 1;+ flex-direction: column;++ min-width: 0;+ min-height: 0;+ `,+ diffBody: css`+ overflow: auto;+ flex: 1;+ min-height: 0;+ `,+ meta: css`+ margin-inline-start: 8px;+ font-size: 11px;+ line-height: 1.2;+ `,+ root: css`+ overflow: hidden;+ display: flex;++ width: 100%;+ height: 100%;++ background: ${cssVar.colorBgContainer};+ `,+}));++export interface CompareContentProps {+ documentId: string;+ initialHistoryId: string;+ items: DocumentHistoryListItem[];+ onRestore: (item: DocumentHistoryListItem) => void;+ saveSourceLabels: Record<DocumentHistorySaveSource, string>;+}++const CompareContent = memo<CompareContentProps>(+ ({ documentId, initialHistoryId, items, onRestore, saveSourceLabels }) => {+ const { t } = useTranslation('file');+ const { styles } = useStyles();++ const [selectedHistoryId, setSelectedHistoryId] = useState<string>(initialHistoryId);++ const selectedItem = useMemo(+ () => items.find((item) => item.id === selectedHistoryId) ?? null,+ [items, selectedHistoryId],+ );++ if (!selectedItem) return null;++ const canRestore = !selectedItem.isCurrent;++ return (+ <div className={styles.root}>+ <div className={styles.diffArea}>+ <div className={styles.cmpbar}>+ <Flexbox horizontal align={'center'} gap={4}>+ <span className={styles.badgeNew}>{t('pageEditor.history.compareCurrentLabel')}</span>+ <Text className={styles.arrow}>→</Text>+ <span className={styles.badgeOld}>+ {formatHistoryAbsoluteTime(selectedItem.savedAt)}+ </span>+ <Text className={styles.meta} type={'secondary'}>+ {dayjs(selectedItem.savedAt).fromNow()} ·{' '}+ {saveSourceLabels[selectedItem.saveSource]}+ </Text>+ </Flexbox>+ {canRestore && (+ <Button icon={RotateCcwIcon} size={'small'} onClick={() => onRestore(selectedItem)}>+ {t('pageEditor.history.restore')} {formatHistoryAbsoluteTime(selectedItem.savedAt)}+ </Button>+ )}+ </div>+ <div className={styles.diffBody}>+ <DocumentHistoryDiff documentId={documentId} historyId={selectedItem.id} />+ </div>+ </div>+ <HistorySidebar+ items={items}+ saveSourceLabels={saveSourceLabels}+ selectedHistoryId={selectedHistoryId}+ onSelect={setSelectedHistoryId}+ />+ </div>+ );+ },+);++CompareContent.displayName = 'CompareContent';++export default CompareContent;diff --git a/src/features/PageEditor/History/CompareModal/HistorySidebar.tsx b/src/features/PageEditor/History/CompareModal/HistorySidebar.tsxnew file mode 100644index 00000000000..0b635253c0e--- /dev/null+++ b/src/features/PageEditor/History/CompareModal/HistorySidebar.tsx@@ -0,0 +1,237 @@+'use client';++import { Flexbox, Tag, Text } from '@lobehub/ui';+import { createStyles, cssVar, cx } from 'antd-style';+import dayjs from 'dayjs';+import { memo, useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import type {+ DocumentHistoryListItem,+ DocumentHistorySaveSource,+} from '@/server/routers/lambda/_schema/documentHistory';++import { formatHistoryRowTime } from '../formatHistoryDate';++const useStyles = createStyles(({ css, token }) => ({+ container: css`+ overflow-y: auto;+ flex-shrink: 0;++ width: 232px;+ padding-block: 4px 12px;+ padding-inline: 8px;+ border-inline-start: 1px solid ${token.colorBorderSecondary};++ background: ${token.colorBgContainer};+ `,+ dot: css`+ position: absolute;+ inset-block-start: 9px;+ inset-inline-start: 5px;++ width: 8px;+ height: 8px;+ border: 1px solid ${token.colorBorder};+ border-radius: 999px;++ background: ${token.colorBgContainer};+ box-shadow: 0 0 0 2px ${token.colorBgContainer};+ `,+ dotCurrent: css`+ border-color: ${token.colorSuccess};+ background: ${token.colorSuccess};+ `,+ dotSelected: css`+ border-color: ${token.colorPrimary};+ background: ${token.colorPrimary};+ `,+ group: css`+ position: relative;+ `,+ groupHeader: css`+ position: sticky;+ z-index: 1;+ inset-block-start: 0;++ padding-block: 10px 6px;+ padding-inline-start: 24px;++ font-size: 11px;+ font-weight: 500;+ line-height: 1.2;++ background: ${token.colorBgContainer};+ `,+ item: css`+ cursor: pointer;++ padding-block: 4px;+ padding-inline: 8px;+ border-radius: 6px;++ transition: background ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut};++ &:hover {+ background: ${token.colorFillQuaternary};+ }+ `,+ itemCurrent: css`+ cursor: default;+ `,+ itemSelected: css`+ background: ${token.colorFillSecondary};++ &:hover {+ background: ${token.colorFillSecondary};+ }+ `,+ meta: css`+ overflow: hidden;++ font-size: 11px;+ line-height: 1.3;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ rail: css`+ position: absolute;+ inset-block: 2px;+ inset-inline-start: 8px;++ width: 1px;++ background: ${token.colorFillTertiary};+ `,+ row: css`+ position: relative;+ padding-inline-start: 24px;+ `,+ tag: css`+ height: 16px;+ padding-inline: 4px;+ font-size: 10px;+ `,+ time: css`+ font-size: 12px;+ font-weight: 600;+ line-height: 1.3;+ `,+}));++interface HistoryDayGroup {+ items: DocumentHistoryListItem[];+ key: string;+ label: string;+}++const createGroups = (+ items: DocumentHistoryListItem[],+ formatLabel: (savedAt: string) => string,+): HistoryDayGroup[] => {+ const groups = new Map<string, HistoryDayGroup>();++ for (const item of items) {+ const key = dayjs(item.savedAt).format('YYYY-MM-DD');+ const group = groups.get(key);++ if (group) {+ group.items.push(item);+ continue;+ }++ groups.set(key, {+ items: [item],+ key,+ label: formatLabel(item.savedAt),+ });+ }++ return [...groups.values()];+};++interface HistorySidebarProps {+ items: DocumentHistoryListItem[];+ onSelect: (historyId: string) => void;+ saveSourceLabels: Record<DocumentHistorySaveSource, string>;+ selectedHistoryId: string | null;+}++const HistorySidebar = memo<HistorySidebarProps>(+ ({ items, onSelect, saveSourceLabels, selectedHistoryId }) => {+ const { t } = useTranslation('file');+ const { styles } = useStyles();++ const formatLabel = useCallback(+ (savedAt: string) => {+ const d = dayjs(savedAt);+ if (d.isToday()) return t('pageEditor.history.dayLabel.today');+ if (d.isYesterday()) return t('pageEditor.history.dayLabel.yesterday');+ return d.format('MM-DD');+ },+ [t],+ );++ const groups = useMemo(() => createGroups(items, formatLabel), [formatLabel, items]);++ return (+ <div className={styles.container}>+ {groups.map((group) => (+ <Flexbox gap={0} key={group.key}>+ <div className={styles.groupHeader}>+ <Text type={'secondary'}>{group.label}</Text>+ </div>+ <div className={styles.group}>+ <div className={styles.rail} />+ {group.items.map((item) => {+ const isSelected = selectedHistoryId === item.id;+ const disabled = item.isCurrent;++ return (+ <div className={styles.row} key={item.id}>+ <div+ className={cx(+ styles.dot,+ item.isCurrent && styles.dotCurrent,+ !item.isCurrent && isSelected && styles.dotSelected,+ )}+ />+ <div+ className={cx(+ styles.item,+ item.isCurrent && styles.itemCurrent,+ !item.isCurrent && isSelected && styles.itemSelected,+ )}+ onClick={() => {+ if (disabled) return;+ onSelect(item.id);+ }}+ >+ <Flexbox gap={2}>+ <Flexbox horizontal align={'center'} gap={4}>+ <Text className={styles.time}>{formatHistoryRowTime(item.savedAt)}</Text>+ {item.isCurrent && (+ <Tag className={styles.tag} variant={'borderless'}>+ {t('pageEditor.history.current')}+ </Tag>+ )}+ </Flexbox>+ <Text className={styles.meta} type={'secondary'}>+ {dayjs(item.savedAt).fromNow()} · {saveSourceLabels[item.saveSource]}+ </Text>+ </Flexbox>+ </div>+ </div>+ );+ })}+ </div>+ </Flexbox>+ ))}+ </div>+ );+ },+);++HistorySidebar.displayName = 'HistorySidebar';++export default HistorySidebar;diff --git a/src/features/PageEditor/History/CompareModal/index.tsx b/src/features/PageEditor/History/CompareModal/index.tsxnew file mode 100644index 00000000000..df823d28b77--- /dev/null+++ b/src/features/PageEditor/History/CompareModal/index.tsx@@ -0,0 +1,24 @@+'use client';++import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';+import { t } from 'i18next';++import CompareContent, { type CompareContentProps } from './CompareContent';++export type OpenDocumentCompareModalProps = CompareContentProps;++export const openDocumentCompareModal = (props: OpenDocumentCompareModalProps): ModalInstance =>+ createModal({+ content: <CompareContent {...props} />,+ footer: null,+ styles: {+ content: {+ display: 'flex',+ height: 'min(72vh, 800px)',+ overflow: 'hidden',+ padding: 0,+ },+ },+ title: t('pageEditor.history.compareTitle', { ns: 'file' }),+ width: 'min(92vw, 1200px)',+ });diff --git a/src/features/PageEditor/History/DocumentHistoryDiff.tsx b/src/features/PageEditor/History/DocumentHistoryDiff.tsxnew file mode 100644index 00000000000..258da7b6c7f--- /dev/null+++ b/src/features/PageEditor/History/DocumentHistoryDiff.tsx@@ -0,0 +1,118 @@+'use client';++import type { LexicalDiffProps } from '@lobehub/editor/renderer';+import { LexicalDiff } from '@lobehub/editor/renderer';+import { Empty, Flexbox } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import type { SerializedEditorState } from 'lexical';+import { GitCompareArrowsIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import CircleLoading from '@/components/Loading/CircleLoading';+import { useClientDataSWR } from '@/libs/swr';+import type { CompareHistoryItemsOutput } from '@/server/routers/lambda/_schema/documentHistory';+import { documentService } from '@/services/document';+import { useDocumentStore } from '@/store/document';+import { editorSelectors } from '@/store/document/slices/editor';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow: hidden;+ display: flex;+ flex: 1;+ flex-direction: column;++ min-height: 0;++ background: ${cssVar.colorBgContainer};+ `,+ content: css`+ overflow: auto;+ flex: 1;+ min-height: 0;+ `,+ empty: css`+ padding: 24px;+ `,+}));++const isObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null;++const isSerializedEditorState = (value: unknown): value is SerializedEditorState =>+ isObject(value) && isObject(value.root) && Array.isArray(value.root.children);++const isSerializedRootNode = (value: unknown): value is SerializedEditorState['root'] =>+ isObject(value) && value.type === 'root' && Array.isArray(value.children);++const normalizeEditorState = (value: unknown): SerializedEditorState | null => {+ if (isSerializedEditorState(value)) return value;+ if (isSerializedRootNode(value)) return { root: value };++ return null;+};++interface DocumentHistoryDiffProps {+ documentId: string;+ historyId: string;+}++const DocumentHistoryDiff = memo<DocumentHistoryDiffProps>(({ documentId, historyId }) => {+ const { t } = useTranslation('file');+ const lastUpdatedTime = useDocumentStore(+ (s) => editorSelectors.lastUpdatedTime(documentId)(s) ?? null,+ );++ const { data, error, isLoading } = useClientDataSWR<CompareHistoryItemsOutput>(+ ['page-editor-document-history-compare', documentId, historyId, lastUpdatedTime],+ async () =>+ documentService.compareDocumentHistoryItems({+ documentId,+ fromHistoryId: 'head',+ toHistoryId: historyId,+ }),+ );++ const labels = useMemo<NonNullable<LexicalDiffProps['labels']>>(+ () => ({+ new: t('pageEditor.history.compareOldLabel'),+ old: t('pageEditor.history.compareCurrentLabel'),+ }),+ [t],+ );+ const normalizedValues = useMemo(() => {+ const oldValue = normalizeEditorState(data?.from.editorData);+ const newValue = normalizeEditorState(data?.to.editorData);++ return { newValue, oldValue };+ }, [data?.from.editorData, data?.to.editorData]);++ return (+ <Flexbox className={styles.container} flex={1} gap={0}>+ {isLoading && !data ? (+ <Flexbox align={'center'} className={styles.empty} justify={'center'}>+ <CircleLoading />;+ </Flexbox>+ ) : error || !data || !normalizedValues.oldValue || !normalizedValues.newValue ? (+ <Flexbox align={'center'} className={styles.empty} justify={'center'}>+ <Empty description={t('pageEditor.history.compareError')} icon={GitCompareArrowsIcon} />+ </Flexbox>+ ) : (+ <div className={styles.content}>+ <LexicalDiff+ appearance={'borderless'}+ labels={labels}+ newValue={normalizedValues.newValue}+ oldValue={normalizedValues.oldValue}+ variant="chat"+ />+ </div>+ )}+ </Flexbox>+ );+});++DocumentHistoryDiff.displayName = 'DocumentHistoryDiff';++export default DocumentHistoryDiff;diff --git a/src/features/PageEditor/History/HistoryItemsProvider.test.tsx b/src/features/PageEditor/History/HistoryItemsProvider.test.tsxnew file mode 100644index 00000000000..fc34bb58eeb--- /dev/null+++ b/src/features/PageEditor/History/HistoryItemsProvider.test.tsx@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import type { DocumentHistoryListItem } from '@/server/routers/lambda/_schema/documentHistory';++import { createStore } from './HistoryItemsProvider';++const createHistoryItem = (+ id: string,+ savedAt: string,+ overrides: Partial<DocumentHistoryListItem> = {},+): DocumentHistoryListItem => ({+ id,+ isCurrent: false,+ savedAt,+ saveSource: 'autosave',+ ...overrides,+});++describe('HistoryItemsProvider store', () => {+ it('should reuse unchanged history item references across refreshes', () => {+ const store = createStore();+ const items = [+ createHistoryItem('history-1', '2026-04-16T08:00:00.000Z'),+ createHistoryItem('history-2', '2026-04-16T07:00:00.000Z', { saveSource: 'manual' }),+ ];++ store.getState().setHistoryItems(items);++ const previousItemsById = store.getState().itemsById;++ store.getState().setHistoryItems(items.map((item) => ({ ...item })));++ const nextItemsById = store.getState().itemsById;++ expect(nextItemsById).toBe(previousItemsById);+ expect(nextItemsById['history-1']).toBe(previousItemsById['history-1']);+ expect(nextItemsById['history-2']).toBe(previousItemsById['history-2']);+ });++ it('should replace only the changed history item reference', () => {+ const store = createStore();+ const items = [+ createHistoryItem('history-1', '2026-04-16T08:00:00.000Z'),+ createHistoryItem('history-2', '2026-04-16T07:00:00.000Z', { saveSource: 'manual' }),+ ];++ store.getState().setHistoryItems(items);++ const previousItemsById = store.getState().itemsById;++ store.getState().setHistoryItems([{ ...items[0], isCurrent: true }, { ...items[1] }]);++ const nextItemsById = store.getState().itemsById;++ expect(nextItemsById['history-1']).not.toBe(previousItemsById['history-1']);+ expect(nextItemsById['history-2']).toBe(previousItemsById['history-2']);+ });+});diff --git a/src/features/PageEditor/History/HistoryItemsProvider.tsx b/src/features/PageEditor/History/HistoryItemsProvider.tsxnew file mode 100644index 00000000000..b8829b81374--- /dev/null+++ b/src/features/PageEditor/History/HistoryItemsProvider.tsx@@ -0,0 +1,124 @@+'use client';++import { type StoreApiWithSelector } from '@lobechat/types';+import type { PropsWithChildren } from 'react';+import { memo, useLayoutEffect } from 'react';+import { subscribeWithSelector } from 'zustand/middleware';+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';+import type { StateCreator } from 'zustand/vanilla';+import { createContext } from 'zustand-utils';++import type { DocumentHistoryListItem } from '@/server/routers/lambda/_schema/documentHistory';++interface State {+ itemsById: Record<string, DocumentHistoryListItem>;+ restoringHistoryId: string | null;+}++interface Action {+ setHistoryItems: (items: DocumentHistoryListItem[]) => void;+ setRestoringHistoryId: (historyId: string | null) => void;+}++type Store = State & Action;++const hasSameHistoryItem = (a: DocumentHistoryListItem, b: DocumentHistoryListItem) =>+ a.id === b.id &&+ a.isCurrent === b.isCurrent &&+ a.savedAt === b.savedAt &&+ a.saveSource === b.saveSource;++const buildItemsById = (+ items: DocumentHistoryListItem[],+ previousItemsById: Record<string, DocumentHistoryListItem>,+) => {+ const nextItemsById: Record<string, DocumentHistoryListItem> = {};+ let reusedCount = 0;++ for (const item of items) {+ const previousItem = previousItemsById[item.id];+ const nextItem = previousItem && hasSameHistoryItem(previousItem, item) ? previousItem : item;++ nextItemsById[item.id] = nextItem;++ if (nextItem === previousItem) {+ reusedCount += 1;+ }+ }++ if (Object.keys(previousItemsById).length !== items.length) {+ return nextItemsById;+ }++ return reusedCount === items.length ? previousItemsById : nextItemsById;+};++const store: StateCreator<Store, [['zustand/devtools', never]]> = (set, get) => ({+ itemsById: {},+ restoringHistoryId: null,++ setHistoryItems: (items) => {+ const nextItemsById = buildItemsById(items, get().itemsById);++ if (nextItemsById === get().itemsById) return;++ set({ itemsById: nextItemsById });+ },++ setRestoringHistoryId: (restoringHistoryId) => {+ if (get().restoringHistoryId === restoringHistoryId) return;++ set({ restoringHistoryId });+ },+});++export const createStore = () => createWithEqualityFn(subscribeWithSelector(store), shallow);++export const {+ Provider,+ useStore: useHistoryItemsStore,+ useStoreApi: useHistoryItemsStoreApi,+} = createContext<StoreApiWithSelector<Store>>();++export const historyItemSelectors = {+ isRestoring: (historyId: string) => (s: Store) => s.restoringHistoryId === historyId,+ itemById: (historyId: string) => (s: Store) => s.itemsById[historyId],+};++interface HistoryItemsStoreUpdaterProps {+ items: DocumentHistoryListItem[];+ restoringHistoryId: string | null;+}++const HistoryItemsStoreUpdater = memo<HistoryItemsStoreUpdaterProps>(+ ({ items, restoringHistoryId }) => {+ const storeApi = useHistoryItemsStoreApi();++ useLayoutEffect(() => {+ storeApi.getState().setHistoryItems(items);+ }, [items, storeApi]);++ useLayoutEffect(() => {+ storeApi.getState().setRestoringHistoryId(restoringHistoryId);+ }, [restoringHistoryId, storeApi]);++ return null;+ },+);++interface HistoryItemsProviderProps extends PropsWithChildren {+ items: DocumentHistoryListItem[];+ restoringHistoryId: string | null;+}++export const HistoryItemsProvider = memo<HistoryItemsProviderProps>(+ ({ children, items, restoringHistoryId }) => {+ return (+ <Provider createStore={createStore}>+ <HistoryItemsStoreUpdater items={items} restoringHistoryId={restoringHistoryId} />+ {children}+ </Provider>+ );+ },+);diff --git a/src/features/PageEditor/History/HistoryListItem.tsx b/src/features/PageEditor/History/HistoryListItem.tsxnew file mode 100644index 00000000000..84ac74f182f--- /dev/null+++ b/src/features/PageEditor/History/HistoryListItem.tsx@@ -0,0 +1,207 @@+'use client';++import { ActionIcon, Flexbox, Tag } from '@lobehub/ui';+import { Tooltip } from 'antd';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ArrowLeftRightIcon, RotateCcwIcon } from 'lucide-react';+import type { MouseEvent } from 'react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useEventCallback } from '@/hooks/useEventCallback';+import type { DocumentHistorySaveSource } from '@/server/routers/lambda/_schema/documentHistory';++import { formatHistoryAbsoluteTime, formatHistoryRowTime } from './formatHistoryDate';+import { historyItemSelectors, useHistoryItemsStore } from './HistoryItemsProvider';++type TagColor = 'default' | 'success' | 'purple' | 'geekblue' | 'gold' | 'processing';++const SOURCE_TAG_COLOR: Record<DocumentHistorySaveSource, TagColor> = {+ autosave: 'default',+ llm_call: 'purple',+ manual: 'success',+ restore: 'geekblue',+ system: 'gold',+};++const styles = createStaticStyles(({ css }) => ({+ actions: css`+ pointer-events: none;++ position: absolute;+ inset-block: 50%;+ inset-inline-end: 10px;+ transform: translateY(-50%);++ display: flex;+ gap: 2px;+ align-items: center;++ opacity: 0;++ transition: opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut};+ `,+ currentBadge: css`+ flex-shrink: 0;+ margin: 0;+ `,+ row: css`+ cursor: pointer;++ position: relative;++ display: flex;+ gap: 8px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 16px;++ transition: background ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut};++ &:hover,+ &:focus-within {+ background: ${cssVar.colorFillQuaternary};++ .history-source-tag {+ opacity: 0;+ }++ .history-actions {+ pointer-events: auto;+ opacity: 1;+ }+ }+ `,+ rowCurrent: css`+ cursor: default;++ &:hover,+ &:focus-within {+ background: transparent;++ .history-source-tag {+ opacity: 1;+ }+ }+ `,+ rowRight: css`+ position: relative;++ display: flex;+ flex-shrink: 0;+ gap: 8px;+ align-items: center;++ margin-inline-start: auto;+ `,+ rowTime: css`+ flex-shrink: 0;++ font-size: 13px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ line-height: 1;+ color: ${cssVar.colorText};+ `,+ rowTimeCurrent: css`+ font-size: 14px;+ color: ${cssVar.colorPrimary};+ `,+ sourceTag: css`+ flex-shrink: 0;+ margin: 0;+ transition: opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut};+ `,+}));++export interface HistoryListItemProps {+ historyId: string;+ onCompare: (historyId: string) => void;+ onRestore: (historyId: string) => void;+}++export const HistoryListItem = memo<HistoryListItemProps>(({ historyId, onCompare, onRestore }) => {+ const { t } = useTranslation(['common', 'file']);+ const item = useHistoryItemsStore(historyItemSelectors.itemById(historyId));+ const isRestoring = useHistoryItemsStore(historyItemSelectors.isRestoring(historyId));++ const handleCompare = useEventCallback(() => {+ onCompare(historyId);+ });++ const handleRestore = useEventCallback(() => {+ onRestore(historyId);+ });++ const handleStopPropagation = useEventCallback((event: MouseEvent) => {+ event.stopPropagation();+ });++ if (!item) return null;++ const timeLabel = formatHistoryRowTime(item.savedAt);+ const saveSourceLabel = t(`pageEditor.history.saveSource.${item.saveSource}`, { ns: 'file' });++ return (+ <div+ className={cx(styles.row, item.isCurrent && styles.rowCurrent)}+ onClick={item.isCurrent ? undefined : handleCompare}+ >+ <Tooltip title={formatHistoryAbsoluteTime(item.savedAt)}>+ <span className={cx(styles.rowTime, item.isCurrent && styles.rowTimeCurrent)}>+ {timeLabel}+ </span>+ </Tooltip>++ <div className={styles.rowRight}>+ {item.isCurrent && (+ <Tag+ className={styles.currentBadge}+ color={'processing'}+ size={'small'}+ variant={'borderless'}+ >+ {t('pageEditor.history.current', { ns: 'file' })}+ </Tag>+ )}++ {!item.isCurrent && (+ <Tag+ className={cx(styles.sourceTag, 'history-source-tag')}+ color={SOURCE_TAG_COLOR[item.saveSource]}+ size={'small'}+ variant={'borderless'}+ >+ {saveSourceLabel}+ </Tag>+ )}+ {!item.isCurrent && (+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.actions, 'history-actions')}+ gap={2}+ onClick={handleStopPropagation}+ >+ <ActionIcon+ icon={ArrowLeftRightIcon}+ size={{ blockSize: 26, borderRadius: '50%', size: 14 }}+ title={t('pageEditor.history.compare', { ns: 'file' })}+ onClick={handleCompare}+ />+ <ActionIcon+ icon={RotateCcwIcon}+ loading={isRestoring}+ size={{ blockSize: 26, borderRadius: '50%', size: 14 }}+ title={t('pageEditor.history.restore', { ns: 'file' })}+ onClick={handleRestore}+ />+ </Flexbox>+ )}+ </div>+ </div>+ );+});++HistoryListItem.displayName = 'HistoryListItem';diff --git a/src/features/PageEditor/History/formatHistoryDate.ts b/src/features/PageEditor/History/formatHistoryDate.tsnew file mode 100644index 00000000000..fbcee106e9d--- /dev/null+++ b/src/features/PageEditor/History/formatHistoryDate.ts@@ -0,0 +1,6 @@+import dayjs from 'dayjs';++export const formatHistoryAbsoluteTime = (savedAt: string) =>+ dayjs(savedAt).format('MMMM D, YYYY h:mm A');++export const formatHistoryRowTime = (savedAt: string) => dayjs(savedAt).format('h:mm A');diff --git a/src/features/PageEditor/History/index.tsx b/src/features/PageEditor/History/index.tsxnew file mode 100644index 00000000000..2567d5ff938--- /dev/null+++ b/src/features/PageEditor/History/index.tsx@@ -0,0 +1,287 @@+'use client';++import { Button, Empty, Flexbox, Text } from '@lobehub/ui';+import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';+import { App } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import { ArrowLeftIcon, Clock3Icon } from 'lucide-react';+import { memo, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import Loading from '@/components/Loading/BrandTextLoading';+import { DOCUMENT_HISTORY_QUERY_LIST_LIMIT } from '@/const/documentHistory';+import NavHeader from '@/features/NavHeader';+import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';+import { useEventCallback } from '@/hooks/useEventCallback';+import { useClientDataSWR } from '@/libs/swr';+import type {+ DocumentHistoryListItem,+ DocumentHistorySaveSource,+ ListHistoryOutput,+} from '@/server/routers/lambda/_schema/documentHistory';+import { documentService } from '@/services/document';+import { useDocumentStore } from '@/store/document';+import { editorSelectors } from '@/store/document/slices/editor';++import { selectors, usePageEditorStore } from '../store';+import { openDocumentCompareModal } from './CompareModal';+import { formatHistoryAbsoluteTime } from './formatHistoryDate';+import { HistoryItemsProvider } from './HistoryItemsProvider';+import { HistoryListItem } from './HistoryListItem';++interface HistoryDayGroup {+ historyIds: string[];+ key: string;+ label: string;+}++const styles = createStaticStyles(({ css }) => ({+ empty: css`+ height: 100%;+ padding: 24px;+ `,+ groupHeader: css`+ position: sticky;+ z-index: 1;+ inset-block-start: 0;++ display: flex;+ gap: 8px;+ align-items: baseline;++ padding-block: 14px 6px;+ padding-inline: 16px;+ border-block-end: 1px solid ${cssVar.colorSplit};++ background: ${cssVar.colorBgContainer};+ `,+ groupTitle: css`+ font-size: 12px;+ font-weight: 700;+ line-height: 1;+ color: ${cssVar.colorText};+ `,+ groupCount: css`+ font-size: 11px;+ line-height: 1;+ color: ${cssVar.colorTextTertiary};+ `,+ headerButton: css`+ padding-inline: 8px;+ `,+ list: css`+ overflow-y: auto;+ flex: 1;+ min-height: 0;+ padding-block: 0 20px;+ `,+}));++const HistoryPanel = memo(() => {+ const { t } = useTranslation(['common', 'file']);+ const { message } = App.useApp();++ const documentId = usePageEditorStore(selectors.documentId);+ const editor = usePageEditorStore(selectors.editor);+ const setRightPanelMode = usePageEditorStore((s) => s.setRightPanelMode);++ const markDirty = useDocumentStore((s) => s.markDirty);+ const performSave = useDocumentStore((s) => s.performSave);+ const lastUpdatedTime = useDocumentStore(+ (s) => editorSelectors.lastUpdatedTime(documentId!)(s) ?? null,+ );++ const [restoringHistoryId, setRestoringHistoryId] = useState<string | null>(null);+ const compareInstanceRef = useRef<ModalInstance | null>(null);++ const { data, isLoading } = useClientDataSWR<ListHistoryOutput>(+ documentId ? ['page-editor-document-history', documentId, lastUpdatedTime] : null,+ async () =>+ documentService.listDocumentHistory({+ documentId: documentId!,+ includeCurrent: true,+ limit: DOCUMENT_HISTORY_QUERY_LIST_LIMIT,+ }),+ { keepPreviousData: true },+ );++ const items = useMemo(() => data?.items ?? [], [data?.items]);+ const historyItemsById = useMemo<Record<string, DocumentHistoryListItem>>(() => {+ const nextItemsById: Record<string, DocumentHistoryListItem> = {};++ for (const item of items) {+ nextItemsById[item.id] = item;+ }++ return nextItemsById;+ }, [items]);++ const groups = useMemo<HistoryDayGroup[]>(() => {+ const now = dayjs();+ const todayLabel = t('pageEditor.history.dayLabel.today', { ns: 'file' });+ const yesterdayLabel = t('pageEditor.history.dayLabel.yesterday', { ns: 'file' });++ const map = new Map<string, HistoryDayGroup>();++ for (const item of items) {+ const d = dayjs(item.savedAt);+ const key = d.format('YYYY-MM-DD');+ const group = map.get(key);++ if (group) {+ group.historyIds.push(item.id);+ continue;+ }++ let label: string;+ if (d.isSame(now, 'day')) label = todayLabel;+ else if (d.isSame(now.subtract(1, 'day'), 'day')) label = yesterdayLabel;+ else label = d.format('MMMM D, YYYY');++ map.set(key, { historyIds: [item.id], key, label });+ }++ return [...map.values()];+ }, [items, t]);++ const saveSourceLabels = useMemo<Record<DocumentHistorySaveSource, string>>(+ () => ({+ autosave: t('pageEditor.history.saveSource.autosave', { ns: 'file' }),+ llm_call: t('pageEditor.history.saveSource.llm_call', { ns: 'file' }),+ manual: t('pageEditor.history.saveSource.manual', { ns: 'file' }),+ restore: t('pageEditor.history.saveSource.restore', { ns: 'file' }),+ system: t('pageEditor.history.saveSource.system', { ns: 'file' }),+ }),+ [t],+ );++ const handleRestore = useEventCallback((historyId: string, onSuccess?: () => void) => {+ const item = historyItemsById[historyId];++ if (!documentId || !editor || !item || item.isCurrent) return;++ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('pageEditor.history.restoreConfirm.content', {+ ns: 'file',+ savedAt: formatHistoryAbsoluteTime(item.savedAt),+ }),+ okText: t('pageEditor.history.restore', { ns: 'file' }),+ onOk: async () => {+ setRestoringHistoryId(historyId);++ try {+ const result = await documentService.getDocumentHistoryItem(+ { documentId, historyId },+ `page-editor-history-${documentId}`,+ );++ editor.setDocument('json', JSON.stringify(result.editorData));+ markDirty(documentId);+ await performSave(documentId, undefined, {+ restoreFromHistoryId: historyId,+ saveSource: 'restore',+ });+ onSuccess?.();+ } catch (error) {+ console.error('[PageEditor] Failed to restore history item:', error);+ message.error(t('pageEditor.history.restoreError', { ns: 'file' }));+ throw error;+ } finally {+ setRestoringHistoryId(null);+ }+ },+ title: t('pageEditor.history.restoreConfirm.title', { ns: 'file' }),+ });+ });++ const openCompareModal = useEventCallback((initialHistoryId: string) => {+ if (!documentId) return;++ compareInstanceRef.current?.destroy();++ const instance = openDocumentCompareModal({+ documentId,+ initialHistoryId,+ items,+ onRestore: (item) => handleRestore(item.id, () => instance.close()),+ saveSourceLabels,+ });+ compareInstanceRef.current = instance;+ });++ if (!documentId) return null;++ return (+ <Flexbox flex={1} height={'100%'}>+ <NavHeader+ showTogglePanelButton={false}+ left={+ <Text+ ellipsis={{ tooltipWhenOverflow: true }}+ style={{ fontSize: 13, fontWeight: 500, marginLeft: 8 }}+ type={'secondary'}+ >+ {t('pageEditor.history.title', { ns: 'file' })}+ </Text>+ }+ right={+ <>+ <Button+ className={styles.headerButton}+ icon={ArrowLeftIcon}+ size={'small'}+ type={'text'}+ onClick={() => setRightPanelMode('copilot')}+ >+ {t('pageEditor.history.backToCopilot', { ns: 'file' })}+ </Button>+ <ToggleRightPanelButton showActive={false} />+ </>+ }+ />++ {isLoading && !data ? (+ <Flexbox align={'center'} className={styles.empty} justify={'center'}>+ <Loading debugId={'DocumentHistoryPanel'} />+ </Flexbox>+ ) : items.length === 0 ? (+ <Flexbox align={'center'} className={styles.empty} justify={'center'}>+ <Empty description={t('pageEditor.history.empty', { ns: 'file' })} icon={Clock3Icon} />+ </Flexbox>+ ) : (+ <HistoryItemsProvider items={items} restoringHistoryId={restoringHistoryId}>+ <Flexbox className={styles.list} gap={0}>+ {groups.map((group) => (+ <Flexbox gap={0} key={group.key}>+ <div className={styles.groupHeader}>+ <span className={styles.groupTitle}>{group.label}</span>+ <span className={styles.groupCount}>+ {t('pageEditor.history.versionCount', {+ count: group.historyIds.length,+ ns: 'file',+ })}+ </span>+ </div>++ {group.historyIds.map((historyId) => (+ <HistoryListItem+ historyId={historyId}+ key={historyId}+ onCompare={openCompareModal}+ onRestore={handleRestore}+ />+ ))}+ </Flexbox>+ ))}+ </Flexbox>+ </HistoryItemsProvider>+ )}+ </Flexbox>+ );+});++HistoryPanel.displayName = 'HistoryPanel';++export default HistoryPanel;diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex b5d789e5db2..75b6c518ff4 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -12,12 +12,12 @@ import { useRegisterFilesHotkeys } from '@/hooks/useHotkeys';import { usePageStore } from '@/store/page';import { StyleSheet } from '@/utils/styles';-import Copilot from './Copilot';import EditorCanvas from './EditorCanvas';import Header from './Header';import { PageAgentProvider } from './PageAgentProvider';import { PageEditorProvider } from './PageEditorProvider';import PageTitle from './PageTitle';+import RightPanel from './RightPanel';import { usePageEditorStore } from './store';import TitleSection from './TitleSection';@@ -78,7 +78,7 @@ const PageEditorCanvas = memo(() => {</Flexbox>{documentId && <DiffAllToolbar documentId={documentId} editor={editor!} />}</Flexbox>- <Copilot />+ <RightPanel /></Flexbox></>);diff --git a/src/features/PageEditor/RightPanel/index.tsx b/src/features/PageEditor/RightPanel/index.tsxnew file mode 100644index 00000000000..5128ba7703d--- /dev/null+++ b/src/features/PageEditor/RightPanel/index.tsx@@ -0,0 +1,131 @@+'use client';++import { Freeze } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { AnimatePresence, m, useIsPresent } from 'motion/react';+import { type ReactNode } from 'react';+import { memo, useMemo, useRef } from 'react';++import RightPanel from '@/features/RightPanel';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';+import { useUserStore } from '@/store/user';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';+import type { PanelSlideMotionDirection } from '@/utils/motion/panelSlideMotion';+import {+ isPanelLayerMotionDisabled,+ panelSlideMotionVariantsLeft,+} from '@/utils/motion/panelSlideMotion';++import Conversation from '../Copilot/Conversation';+import HistoryPanel from '../History';+import { selectors, usePageEditorStore } from '../store';++const styles = createStaticStyles(({ css }) => ({+ inner: css`+ position: relative;++ overflow: hidden;+ display: flex;+ flex: 1;+ flex-direction: column;++ width: 100%;+ height: 100%;+ min-height: 0;+ `,+ layer: css`+ will-change: opacity, transform;++ position: absolute;+ inset: 0;++ overflow: hidden;+ display: flex;+ flex-direction: column;++ min-height: 100%;+ max-height: 100%;+ `,+}));++const ExitingFrozenContent = memo<{ children: ReactNode }>(({ children }) => {+ const isPresent = useIsPresent();++ return <Freeze frozen={!isPresent}>{children}</Freeze>;+});++ExitingFrozenContent.displayName = 'PageEditorExitingFrozenContent';++const PageEditorRightPanelContent = memo(() => {+ const rightPanelMode = usePageEditorStore(selectors.rightPanelMode);+ const animationMode = useUserStore(userGeneralSettingsSelectors.animationMode);+ const shouldUseMotion = !isPanelLayerMotionDisabled(animationMode);++ const previousModeRef = useRef(rightPanelMode);+ const directionRef = useRef<PanelSlideMotionDirection>(0);++ if (previousModeRef.current !== rightPanelMode) {+ directionRef.current = rightPanelMode === 'history' ? 1 : -1;+ previousModeRef.current = rightPanelMode;+ }++ const activeContent = useMemo(+ () => ({+ key: rightPanelMode,+ node: rightPanelMode === 'history' ? <HistoryPanel /> : <Conversation />,+ }),+ [rightPanelMode],+ );++ if (!shouldUseMotion) {+ return <div className={styles.layer}>{activeContent.node}</div>;+ }++ return (+ <AnimatePresence custom={directionRef.current} initial={false} mode="sync">+ <m.div+ animate="animate"+ className={styles.layer}+ custom={directionRef.current}+ exit="exit"+ initial="initial"+ key={activeContent.key}+ transition={panelSlideMotionVariantsLeft.transition}+ variants={panelSlideMotionVariantsLeft}+ >+ <ExitingFrozenContent>{activeContent.node}</ExitingFrozenContent>+ </m.div>+ </AnimatePresence>+ );+});++PageEditorRightPanelContent.displayName = 'PageEditorRightPanelContent';++const PageEditorRightPanel = memo(() => {+ const [width, updateSystemStatus] = useGlobalStore((s) => [+ systemStatusSelectors.pageAgentPanelWidth(s),+ s.updateSystemStatus,+ ]);++ return (+ <RightPanel+ defaultWidth={width}+ onSizeChange={(size) => {+ if (size?.width) {+ const nextWidth =+ typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;+ if (nextWidth) updateSystemStatus({ pageAgentPanelWidth: nextWidth });+ }+ }}+ >+ <div className={styles.inner}>+ <PageEditorRightPanelContent />+ </div>+ </RightPanel>+ );+});++PageEditorRightPanel.displayName = 'PageEditorRightPanel';++export default PageEditorRightPanel;diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex dae2ea81e47..0ddddd7ed2d 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -1,13 +1,17 @@'use client';+import debug from 'debug';import { memo, useEffect } from 'react';import { createStoreUpdater } from 'zustand-utils';+import { documentHistoryQueueService } from '@/services/documentHistoryQueue';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { type PublicState } from './store';import { usePageEditorStore, useStoreApi } from './store';+const log = debug('page:editor:store-updater');+type PageAgentEditor = NonNullable<Parameters<typeof pageAgentRuntime.setEditor>[0]>;export interface StoreUpdaterProps extends Partial<PublicState> {@@ -55,7 +59,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Initialize meta (title/emoji) with dirty trackinguseEffect(() => {initMeta(title, emoji);- }, [pageId, title, emoji]);+ }, [pageId, title, emoji, initMeta]);// Connect editor to page agent runtimeuseEffect(() => {@@ -75,10 +79,27 @@ const StoreUpdater = memo<StoreUpdaterProps>(pageAgentRuntime.setCurrentDocId(pageId);pageAgentRuntime.setTitleHandlers(storeApi.getState().setTitle, titleGetter);+ pageAgentRuntime.setBeforeMutateHandler(() => {+ if (!pageId) return;+ const editor = storeApi.getState().editor;+ if (!editor) return;+ try {+ const editorData = editor.getDocument('json');+ documentHistoryQueueService.enqueue({+ documentId: pageId,+ editorData: JSON.stringify(editorData),+ saveSource: 'llm_call',+ });+ } catch (error) {+ log('Failed to capture history snapshot before mutation: %o', error);+ }+ });return () => {pageAgentRuntime.setCurrentDocId(undefined);pageAgentRuntime.setTitleHandlers(null, null);+ pageAgentRuntime.setBeforeMutateHandler(null);+ void documentHistoryQueueService.flush();};}, [pageId, storeApi]);diff --git a/src/features/PageEditor/store/action.test.ts b/src/features/PageEditor/store/action.test.tsnew file mode 100644index 00000000000..103d7fff3c8--- /dev/null+++ b/src/features/PageEditor/store/action.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { createStore } from '.';++describe('PageEditorStore - rightPanelMode', () => {+ it('should default to copilot mode', () => {+ const store = createStore();++ expect(store.getState().rightPanelMode).toBe('copilot');+ });++ it('should switch to history mode', () => {+ const store = createStore();++ store.getState().setRightPanelMode('history');++ expect(store.getState().rightPanelMode).toBe('history');+ });+});diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.tsindex 4c605fba1ef..88ed49194a9 100644--- a/src/features/PageEditor/store/action.ts+++ b/src/features/PageEditor/store/action.ts@@ -6,7 +6,7 @@ import { type StateCreator } from 'zustand';import { useDocumentStore } from '@/store/document';import { useFileStore } from '@/store/file';-import { type State } from './initialState';+import { type RightPanelMode, type State } from './initialState';import { initialState } from './initialState';const log = debug('page:editor');@@ -24,6 +24,7 @@ export interface Action {initMeta: (title?: string, emoji?: string) => void;performMetaSave: () => Promise<void>;setEmoji: (emoji: string | undefined) => void;+ setRightPanelMode: (mode: RightPanelMode) => void;setTitle: (title: string) => void;triggerDebouncedMetaSave: () => void;}@@ -134,10 +135,14 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =try {// Trigger save via DocumentStore with metadata- await useDocumentStore.getState().performSave(documentId, {- emoji,- title,- });+ await useDocumentStore.getState().performSave(+ documentId,+ {+ emoji,+ title,+ },+ { saveSource: 'autosave' },+ );// Notify parent after successful saveif (title !== lastSavedTitle) {@@ -170,6 +175,10 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =}},+ setRightPanelMode: (rightPanelMode) => {+ set({ rightPanelMode });+ },+setTitle: (title: string) => {const { lastSavedTitle, triggerDebouncedMetaSave } = get();diff --git a/src/features/PageEditor/store/initialState.ts b/src/features/PageEditor/store/initialState.tsindex 9923972669d..874e4be2ed1 100644--- a/src/features/PageEditor/store/initialState.ts+++ b/src/features/PageEditor/store/initialState.ts@@ -1,6 +1,7 @@import { type IEditor } from '@lobehub/editor';export type MetaSaveStatus = 'idle' | 'saving' | 'saved';+export type RightPanelMode = 'copilot' | 'history';export interface PublicState {autoSave?: boolean;@@ -23,6 +24,7 @@ export interface State extends PublicState {lastSavedEmoji?: string;lastSavedTitle?: string;metaSaveStatus?: MetaSaveStatus;+ rightPanelMode: RightPanelMode;}export const initialState: State = {@@ -31,5 +33,6 @@ export const initialState: State = {emoji: undefined,isMetaDirty: false,metaSaveStatus: 'idle',+ rightPanelMode: 'copilot',title: undefined,};diff --git a/src/features/PageEditor/store/selectors.ts b/src/features/PageEditor/store/selectors.tsindex 9f65a9de944..3c55c9640dc 100644--- a/src/features/PageEditor/store/selectors.ts+++ b/src/features/PageEditor/store/selectors.ts@@ -4,5 +4,6 @@ export const selectors = {documentId: (s: Store) => s.documentId,editor: (s: Store) => s.editor,emoji: (s: Store) => s.emoji,+ rightPanelMode: (s: Store) => s.rightPanelMode,title: (s: Store) => s.title,};diff --git a/src/hooks/useHotkeys/filesScope.ts b/src/hooks/useHotkeys/filesScope.tsindex dd75c4af75f..e07889860e6 100644--- a/src/hooks/useHotkeys/filesScope.ts+++ b/src/hooks/useHotkeys/filesScope.ts@@ -6,13 +6,13 @@ import { useHotkeyById } from './useHotkeyById';/*** Save document hotkey (Cmd+S / Ctrl+S)- * @param flushSave - Function to flush pending saves+ * @param onSave - Callback invoked when the save hotkey is triggered*/-export const useSaveDocumentHotkey = (flushSave: () => void) => {+export const useSaveDocumentHotkey = (onSave: () => void | Promise<void>) => {return useHotkeyById(HotkeyEnum.SaveDocument,() => {- flushSave();+ void onSave();},{enableOnContentEditable: true,diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsxindex 50a8bad6562..9e73cb5ec48 100644--- a/src/layout/SPAGlobalProvider/index.tsx+++ b/src/layout/SPAGlobalProvider/index.tsx@@ -24,6 +24,9 @@ import type { SPAServerConfig } from '@/types/spaServerConfig';import Locale from './Locale';const ModalHost = lazy(() => import('@lobehub/ui').then((m) => ({ default: m.ModalHost })));+const BaseModalHost = lazy(() =>+ import('@lobehub/ui/base-ui').then((m) => ({ default: m.ModalHost })),+);const ToastHost = lazy(() => import('@lobehub/ui/base-ui').then((m) => ({ default: m.ToastHost })));const ContextMenuHost = lazy(() =>import('@lobehub/ui').then((m) => ({ default: m.ContextMenuHost })),@@ -66,6 +69,7 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {</TooltipGroup><Suspense><ModalHost />+ <BaseModalHost /><ToastHost /><ContextMenuHost /></Suspense>diff --git a/src/libs/editor/isValidEditorData.ts b/src/libs/editor/isValidEditorData.tsnew file mode 100644index 00000000000..02adf4153b5--- /dev/null+++ b/src/libs/editor/isValidEditorData.ts@@ -0,0 +1,6 @@+const isObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null;++export const isValidEditorData = (value: unknown): value is Record<string, unknown> => {+ return isObject(value) && Object.keys(value).length > 0;+};diff --git a/src/locales/default/file.ts b/src/locales/default/file.tsindex ff626982357..613868a6f1f 100644--- a/src/locales/default/file.ts+++ b/src/locales/default/file.ts@@ -99,6 +99,33 @@ export default {'pageEditor.exportDialogTitle': 'Export Page','pageEditor.exportError': 'Failed to export the page','pageEditor.exportSuccess': 'Page exported successfully',+ 'pageEditor.history.backToCopilot': 'Copilot',+ 'pageEditor.history.compare': 'Compare',+ 'pageEditor.history.compareCurrentLabel': 'Current',+ 'pageEditor.history.compareDescription':+ 'Comparing the current content with the selected history state',+ 'pageEditor.history.compareError': 'Failed to load diff preview',+ 'pageEditor.history.compareModalTitle': 'Compare',+ 'pageEditor.history.compareTitle': 'Version Diff',+ 'pageEditor.history.current': 'Current',+ 'pageEditor.history.dayLabel.today': 'Today',+ 'pageEditor.history.dayLabel.yesterday': 'Yesterday',+ 'pageEditor.history.empty': 'No version history yet',+ 'pageEditor.history.compareOldLabel': 'Restore To',+ 'pageEditor.history.restore': 'Restore',+ 'pageEditor.history.restoreError': 'Failed to restore from history',+ 'pageEditor.history.restoreConfirm.content':+ 'Restore the page to how it was at {{savedAt}}? Your current content will be replaced and saved.',+ 'pageEditor.history.restoreConfirm.title': 'Restore from history',+ 'pageEditor.history.saveSource.autosave': 'Auto Save',+ 'pageEditor.history.saveSource.llm_call': 'AI Edit',+ 'pageEditor.history.saveSource.manual': 'Manual Save',+ 'pageEditor.history.saveSource.restore': 'Restore',+ 'pageEditor.history.saveSource.system': 'System',+ 'pageEditor.history.title': 'Version History',+ 'pageEditor.history.versionCount_one': '{{count}} version',+ 'pageEditor.history.versionCount_other': '{{count}} versions',+'pageEditor.linkCopied': 'Link copied','pageEditor.menu.copyLink': 'Copy Link','pageEditor.menu.export': 'Export',diff --git a/src/server/routers/async/document.ts b/src/server/routers/async/document.tsnew file mode 100644index 00000000000..de35755f675--- /dev/null+++ b/src/server/routers/async/document.ts@@ -0,0 +1,5 @@+import { asyncRouter as router } from '@/libs/trpc/async';++export const documentRouter = router({+ // Document history compaction is no longer needed with the simplified history schema+});diff --git a/src/server/routers/async/index.ts b/src/server/routers/async/index.tsindex d32e409657c..ee577df6fbd 100644--- a/src/server/routers/async/index.ts+++ b/src/server/routers/async/index.ts@@ -1,11 +1,13 @@import { asyncRouter as router, publicProcedure } from '@/libs/trpc/async';+import { documentRouter } from './document';import { fileRouter } from './file';import { imageRouter } from './image';import { ragEvalRouter } from './ragEval';import { videoRouter } from './video';export const asyncRouter = router({+ document: documentRouter,file: fileRouter,healthcheck: publicProcedure.query(() => "i'm live!"),image: imageRouter,diff --git a/src/server/routers/lambda/_schema/documentHistory.ts b/src/server/routers/lambda/_schema/documentHistory.tsnew file mode 100644index 00000000000..6e01224f634--- /dev/null+++ b/src/server/routers/lambda/_schema/documentHistory.ts@@ -0,0 +1,150 @@+import { z } from 'zod';++export const documentHistorySaveSourceSchema = z.enum([+ 'autosave',+ 'manual',+ 'restore',+ 'system',+ 'llm_call',+]);++export const listDocumentHistoryInputSchema = z+ .object({+ beforeId: z.string().optional(),+ beforeSavedAt: z.string().datetime().optional(),+ documentId: z.string(),+ includeCurrent: z.boolean().optional(),+ limit: z.number().int().min(1).optional(),+ })+ .refine(+ (data) => (!data.beforeId && !data.beforeSavedAt) || (!!data.beforeId && !!data.beforeSavedAt),+ {+ message: 'beforeId and beforeSavedAt must be provided together',+ path: ['beforeSavedAt'],+ },+ );++export const getDocumentHistoryItemInputSchema = z.object({+ documentId: z.string(),+ historyId: z.string(),+});++export const compareDocumentHistoryItemsInputSchema = z.object({+ documentId: z.string(),+ fromHistoryId: z.string(),+ toHistoryId: z.string(),+});++export const updateDocumentInputSchema = z.object({+ content: z.string().optional(),+ editorData: z.string().optional(),+ fileType: z.string().optional(),+ id: z.string(),+ metadata: z.record(z.any()).optional(),+ parentId: z.string().nullable().optional(),+ restoreFromHistoryId: z.string().optional(),+ saveSource: documentHistorySaveSourceSchema.optional(),+ title: z.string().optional(),+});++export const saveDocumentHistoryInputSchema = z.object({+ documentId: z.string(),+ editorData: z.string(),+ saveSource: documentHistorySaveSourceSchema,+});++export interface DocumentHistoryListItem {+ id: string;+ isCurrent: boolean;+ savedAt: string;+ saveSource: DocumentHistorySaveSource;+}++export interface ListHistoryOutput {+ items: DocumentHistoryListItem[];+ nextBeforeId?: string;+ nextBeforeSavedAt?: string;+}++export interface GetHistoryItemOutput {+ editorData: Record<string, any> | null;+ id: string;+ isCurrent: boolean;+ savedAt: string;+ saveSource: DocumentHistorySaveSource;+}++export interface CompareHistoryItemState {+ editorData: Record<string, any> | null;+ id: string;+ isCurrent: boolean;+ savedAt: string;+ saveSource: DocumentHistorySaveSource;+}++export interface CompareHistoryItemsOutput {+ from: CompareHistoryItemState;+ to: CompareHistoryItemState;+}++export interface UpdateDocumentOutput {+ historyAppended: boolean;+ id: string;+ savedAt?: string;+}++export interface SaveDocumentHistoryInput {+ documentId: string;+ editorData: string;+ saveSource: DocumentHistorySaveSource;+}++export interface SaveDocumentHistoryOutput {+ savedAt: string;+}++export interface ListHistoryInput {+ beforeId?: string;+ beforeSavedAt?: string;+ documentId: string;+ includeCurrent?: boolean;+ limit?: number;+}++export interface GetHistoryItemInput {+ documentId: string;+ historyId: string;+}++export interface CompareHistoryItemsInput {+ documentId: string;+ fromHistoryId: string;+ toHistoryId: string;+}++export interface UpdateDocumentInput {+ content?: string;+ editorData?: string;+ fileType?: string;+ id: string;+ metadata?: Record<string, any>;+ parentId?: string | null;+ restoreFromHistoryId?: string;+ saveSource?: DocumentHistorySaveSource;+ title?: string;+}++export interface DocumentHistoryRouterService {+ compareDocumentHistoryItems: (+ params: CompareHistoryItemsInput,+ ) => Promise<CompareHistoryItemsOutput>;+ getDocumentHistoryItem: (params: GetHistoryItemInput) => Promise<GetHistoryItemOutput>;+ listDocumentHistory: (params: ListHistoryInput) => Promise<ListHistoryOutput>;+ saveDocumentHistory: (params: SaveDocumentHistoryInput) => Promise<SaveDocumentHistoryOutput>;+ updateDocument: (+ id: string,+ params: Omit<UpdateDocumentInput, 'id'>,+ ) => Promise<UpdateDocumentOutput>;+}++export type DocumentHistorySaveSource = z.infer<typeof documentHistorySaveSourceSchema>;diff --git a/src/server/routers/lambda/document.ts b/src/server/routers/lambda/document.tsindex 47eb8d575a4..d416c8ab2d9 100644--- a/src/server/routers/lambda/document.ts+++ b/src/server/routers/lambda/document.ts@@ -1,5 +1,6 @@import { z } from 'zod';+import { FREE_DOCUMENT_HISTORY_WINDOW_DAYS } from '@/const/documentHistory';import { ChunkModel } from '@/database/models/chunk';import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';@@ -8,6 +9,20 @@ import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { DocumentService } from '@/server/services/document';+import {+ compareDocumentHistoryItemsInputSchema,+ getDocumentHistoryItemInputSchema,+ listDocumentHistoryInputSchema,+ saveDocumentHistoryInputSchema,+ updateDocumentInputSchema,+} from './_schema/documentHistory';++const getFreeDocumentHistorySince = () => {+ const now = Date.now();++ return new Date(now - FREE_DOCUMENT_HISTORY_WINDOW_DAYS * 24 * 60 * 60 * 1000);+};+const documentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -117,6 +132,47 @@ export const documentRouter = router({return ctx.documentService.getDocumentById(input.id);}),+ listDocumentHistory: documentProcedure+ .input(listDocumentHistoryInputSchema)+ .query(async ({ ctx, input }) => {+ return ctx.documentService.listDocumentHistory(+ {+ ...input,+ beforeSavedAt: input.beforeSavedAt ? new Date(input.beforeSavedAt) : undefined,+ },+ {+ historySince: getFreeDocumentHistorySince(),+ },+ );+ }),++ getDocumentHistoryItem: documentProcedure+ .input(getDocumentHistoryItemInputSchema)+ .query(async ({ ctx, input }) => {+ return ctx.documentService.getDocumentHistoryItem(input, {+ historySince: getFreeDocumentHistorySince(),+ });+ }),++ compareDocumentHistoryItems: documentProcedure+ .input(compareDocumentHistoryItemsInputSchema)+ .query(async ({ ctx, input }) => {+ return ctx.documentService.compareDocumentHistoryItems(input, {+ historySince: getFreeDocumentHistorySince(),+ });+ }),++ saveDocumentHistory: documentProcedure+ .input(saveDocumentHistoryInputSchema)+ .mutation(async ({ ctx, input }) => {+ const editorData = JSON.parse(input.editorData);+ return ctx.documentService.saveDocumentHistory(+ input.documentId,+ editorData,+ input.saveSource,+ );+ }),+getFolderBreadcrumb: documentProcedure.input(z.object({ slug: z.string() })).query(async ({ ctx, input }) => {@@ -183,25 +239,16 @@ export const documentRouter = router({}),updateDocument: documentProcedure- .input(- z.object({- content: z.string().optional(),- editorData: z.string().optional(),- fileType: z.string().optional(),- id: z.string(),- metadata: z.record(z.any()).optional(),- parentId: z.string().nullable().optional(),- rawData: z.string().optional(),- title: z.string().optional(),- }),- )+ .input(updateDocumentInputSchema).mutation(async ({ ctx, input }) => {const { id, editorData: editorDataString, ...params } = input;// Parse editorData from JSON string to object if presentconst editorData = editorDataString ? JSON.parse(editorDataString) : undefined;- return ctx.documentService.updateDocument(id, {+ const result = await ctx.documentService.updateDocument(id, {...params,editorData,});++ return result;}),});diff --git a/src/server/services/document/__tests__/history.integration.test.ts b/src/server/services/document/__tests__/history.integration.test.tsnew file mode 100644index 00000000000..f2b6daa48e3--- /dev/null+++ b/src/server/services/document/__tests__/history.integration.test.ts@@ -0,0 +1,566 @@+// @vitest-environment node+import { documentHistories, documents, files, users } from '@lobechat/database/schemas';+import { and, desc, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { DOCUMENT_HISTORY_SOURCE_LIMITS } from '@/const/documentHistory';+import { getTestDB } from '@/database/core/getTestDB';+import { DocumentModel } from '@/database/models/document';+import { FileModel } from '@/database/models/file';+import type { LobeChatDatabase } from '@/database/type';++import { DocumentHistoryService } from '../history';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'document-history-service-test-user-id';+const userId2 = 'document-history-service-test-user-id-2';++const documentModel = new DocumentModel(serverDB, userId);+const fileModel = new FileModel(serverDB, userId);+const historyService = new DocumentHistoryService(serverDB, userId);+const historyService2 = new DocumentHistoryService(serverDB, userId2);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);+});++afterEach(async () => {+ await serverDB.delete(documentHistories);+ await serverDB.delete(documents);+ await serverDB.delete(files);+ await serverDB.delete(users);+});++const createTestDocument = async (content: string, editorData?: Record<string, any>) => {+ const { id: fileId } = await fileModel.create({+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'https://example.com/test.txt',+ });++ const doc = await documentModel.create({+ content,+ editorData,+ fileId,+ fileType: 'text/plain',+ filename: 'test.txt',+ source: 'api',+ sourceType: 'api',+ title: 'Test Document',+ totalCharCount: content.length,+ totalLineCount: content.split('\n').length,+ });++ return doc;+};++describe('DocumentHistoryService', () => {+ describe('createHistory & listDocumentHistory', () => {+ it('should create history entries and list them with head included', async () => {+ const doc = await createTestDocument('Hello');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 1 },+ saveSource: 'autosave',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 2 },+ saveSource: 'manual',+ savedAt: new Date('2026-04-02T10:00:00Z'),+ });++ const result = await historyService.listDocumentHistory({+ documentId: doc.id,+ includeCurrent: true,+ limit: 10,+ });++ expect(result.items).toHaveLength(3);+ expect(result.items[0].id).toBe('head');+ expect(result.items[0].isCurrent).toBe(true);+ expect(result.items[1].saveSource).toBe('manual');+ expect(result.items[2].saveSource).toBe('autosave');+ });++ it('should respect includeCurrent=false', async () => {+ const doc = await createTestDocument('Hello');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 1 },+ saveSource: 'autosave',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ const result = await historyService.listDocumentHistory({+ documentId: doc.id,+ includeCurrent: false,+ limit: 10,+ });++ expect(result.items).toHaveLength(1);+ expect(result.items[0].isCurrent).toBe(false);+ });++ it('should paginate correctly using beforeSavedAt and beforeId cursor', async () => {+ const doc = await createTestDocument('Hello');+ const baseDate = new Date('2026-04-01T10:00:00Z');++ // Create multiple history rows with the same savedAt to test id tie-breaker+ for (let i = 0; i < 5; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: i },+ saveSource: 'manual',+ savedAt: new Date(baseDate.getTime()),+ });+ }++ // Fetch all rows and sort by (savedAt DESC, id DESC) to know expected order+ const allRows = await serverDB+ .select({ id: documentHistories.id, savedAt: documentHistories.savedAt })+ .from(documentHistories)+ .where(eq(documentHistories.documentId, doc.id))+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id));++ const sortedIds = allRows.map((r) => r.id);+ expect(sortedIds).toHaveLength(5);++ const firstPage = await historyService.listDocumentHistory({+ documentId: doc.id,+ includeCurrent: false,+ limit: 2,+ });++ expect(firstPage.items.map((i) => i.id)).toEqual(sortedIds.slice(0, 2));+ expect(firstPage.nextBeforeSavedAt).toBeDefined();+ expect(firstPage.nextBeforeId).toBeDefined();++ const secondPage = await historyService.listDocumentHistory({+ beforeId: firstPage.nextBeforeId,+ beforeSavedAt: firstPage.nextBeforeSavedAt,+ documentId: doc.id,+ includeCurrent: false,+ limit: 2,+ });++ expect(secondPage.items.map((i) => i.id)).toEqual(sortedIds.slice(2, 4));+ expect(secondPage.nextBeforeSavedAt).toBeDefined();+ expect(secondPage.nextBeforeId).toBeDefined();++ const thirdPage = await historyService.listDocumentHistory({+ beforeId: secondPage.nextBeforeId,+ beforeSavedAt: secondPage.nextBeforeSavedAt,+ documentId: doc.id,+ includeCurrent: false,+ limit: 2,+ });++ expect(thirdPage.items.map((i) => i.id)).toEqual(sortedIds.slice(4, 5));+ expect(thirdPage.nextBeforeSavedAt).toBeUndefined();+ expect(thirdPage.nextBeforeId).toBeUndefined();+ });++ it('should not duplicate head when paginating with includeCurrent=true and same timestamp', async () => {+ const doc = await createTestDocument('Hello');+ const sharedDate = new Date('2026-04-01T10:00:00Z');++ // Create enough history rows so pagination has a second page+ for (let i = 0; i < 3; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: i },+ saveSource: 'manual',+ savedAt: sharedDate,+ });+ }++ // Force document updatedAt to match the history savedAt+ await documentModel.update(doc.id, { updatedAt: sharedDate });++ const firstPage = await historyService.listDocumentHistory({+ documentId: doc.id,+ includeCurrent: true,+ limit: 2,+ });++ expect(firstPage.items[0].id).toBe('head');+ expect(firstPage.items).toHaveLength(2);+ expect(firstPage.nextBeforeSavedAt).toBeDefined();+ expect(firstPage.nextBeforeId).toBeDefined();++ // Paginating past the first page should never include head again+ const secondPage = await historyService.listDocumentHistory({+ beforeId: firstPage.nextBeforeId,+ beforeSavedAt: firstPage.nextBeforeSavedAt,+ documentId: doc.id,+ includeCurrent: true,+ limit: 2,+ });++ for (const item of secondPage.items) {+ expect(item.id).not.toBe('head');+ }+ });++ it('should emit a cursor when limit=1 and includeCurrent=true', async () => {+ const doc = await createTestDocument('Hello');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 1 },+ saveSource: 'manual',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 2 },+ saveSource: 'manual',+ savedAt: new Date('2026-04-02T10:00:00Z'),+ });++ // limit=1 with includeCurrent=true is promoted to an effective limit of 2+ // so that head plus at least one history item can be returned without+ // creating a cursor that would skip a dropped row.+ const firstPage = await historyService.listDocumentHistory({+ documentId: doc.id,+ includeCurrent: true,+ limit: 1,+ });++ expect(firstPage.items[0].id).toBe('head');+ expect(firstPage.items).toHaveLength(2);+ expect(firstPage.nextBeforeSavedAt).toBeDefined();+ expect(firstPage.nextBeforeId).toBeDefined();++ const secondPage = await historyService.listDocumentHistory({+ beforeId: firstPage.nextBeforeId,+ beforeSavedAt: firstPage.nextBeforeSavedAt,+ documentId: doc.id,+ includeCurrent: true,+ limit: 1,+ });++ expect(secondPage.items[0].id).not.toBe('head');+ expect(secondPage.items).toHaveLength(1);+ });++ it('should filter out entries older than historySince', async () => {+ const doc = await createTestDocument('Hello');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 1 },+ saveSource: 'autosave',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 2 },+ saveSource: 'manual',+ savedAt: new Date('2026-04-10T10:00:00Z'),+ });++ const result = await historyService.listDocumentHistory(+ { documentId: doc.id, includeCurrent: true, limit: 10 },+ { historySince: new Date('2026-04-05T00:00:00Z') },+ );++ const historyItems = result.items.filter((i) => i.id !== 'head');+ expect(historyItems).toHaveLength(1);+ expect(historyItems[0].saveSource).toBe('manual');+ });++ it('should trim autosave history to 20 and manual history to 20 independently', async () => {+ const doc = await createTestDocument('Hello');++ for (let i = 0; i < 25; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: i },+ saveSource: 'autosave',+ savedAt: new Date(`2026-04-01T${String(i).padStart(2, '0')}:00:00Z`),+ });+ }++ for (let i = 0; i < 25; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: i + 100 },+ saveSource: 'manual',+ savedAt: new Date(`2026-04-02T${String(i).padStart(2, '0')}:00:00Z`),+ });+ }++ const autosaveRows = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(+ eq(documentHistories.documentId, doc.id),+ eq(documentHistories.saveSource, 'autosave'),+ ),+ )+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id));++ const manualRows = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(eq(documentHistories.documentId, doc.id), eq(documentHistories.saveSource, 'manual')),+ )+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id));++ expect(autosaveRows).toHaveLength(DOCUMENT_HISTORY_SOURCE_LIMITS.autosave);+ expect(manualRows).toHaveLength(DOCUMENT_HISTORY_SOURCE_LIMITS.manual);++ // Verify the newest items are retained (latest autosave should be v=24)+ const latestAutosave = await serverDB+ .select({ editorData: documentHistories.editorData })+ .from(documentHistories)+ .where(+ and(+ eq(documentHistories.documentId, doc.id),+ eq(documentHistories.saveSource, 'autosave'),+ ),+ )+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id))+ .limit(1);++ expect(latestAutosave[0].editorData).toEqual({ v: 24 });+ });++ it('should trim restore history to 5 and system history to 5 independently', async () => {+ const doc = await createTestDocument('Hello');++ for (let i = 0; i < 10; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { restore: i },+ saveSource: 'restore',+ savedAt: new Date(`2026-04-01T${String(i).padStart(2, '0')}:00:00Z`),+ });+ }++ for (let i = 0; i < 10; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { system: i },+ saveSource: 'system',+ savedAt: new Date(`2026-04-02T${String(i).padStart(2, '0')}:00:00Z`),+ });+ }++ const restoreRows = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(+ eq(documentHistories.documentId, doc.id),+ eq(documentHistories.saveSource, 'restore'),+ ),+ );++ const systemRows = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(eq(documentHistories.documentId, doc.id), eq(documentHistories.saveSource, 'system')),+ );++ expect(restoreRows).toHaveLength(DOCUMENT_HISTORY_SOURCE_LIMITS.restore);+ expect(systemRows).toHaveLength(DOCUMENT_HISTORY_SOURCE_LIMITS.system);+ });++ it('should handle large overflow trimming without error', async () => {+ const doc = await createTestDocument('Hello');++ // Seed 150 autosave rows to exercise the batch deletion path+ for (let i = 0; i < 150; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: i },+ saveSource: 'autosave',+ savedAt: new Date(2026, 3, 1, 0, i, 0),+ });+ }++ const remainingRows = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(+ eq(documentHistories.documentId, doc.id),+ eq(documentHistories.saveSource, 'autosave'),+ ),+ );++ expect(remainingRows).toHaveLength(DOCUMENT_HISTORY_SOURCE_LIMITS.autosave);+ });++ it('should trim llm_call history to 5 independently', async () => {+ const doc = await createTestDocument('Hello');++ for (let i = 0; i < 10; i++) {+ await historyService.createHistory({+ documentId: doc.id,+ editorData: { llm: i },+ saveSource: 'llm_call',+ savedAt: new Date(`2026-04-01T${String(i).padStart(2, '0')}:00:00Z`),+ });+ }++ const llmCallRows = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(+ eq(documentHistories.documentId, doc.id),+ eq(documentHistories.saveSource, 'llm_call'),+ ),+ );++ expect(llmCallRows).toHaveLength(DOCUMENT_HISTORY_SOURCE_LIMITS.llm_call);+ });+ });++ describe('getDocumentHistoryItem', () => {+ it('should resolve head as current document state', async () => {+ const doc = await createTestDocument('Head content', { blocks: [] });++ const result = await historyService.getDocumentHistoryItem({+ documentId: doc.id,+ historyId: 'head',+ });++ expect(result.id).toBe('head');+ expect(result.isCurrent).toBe(true);+ expect(result.editorData).toEqual({ blocks: [] });+ expect(result.saveSource).toBe('system');+ });++ it('should return null for head editorData when current document editorData is invalid', async () => {+ const doc = await createTestDocument('Head content', {});++ const result = await historyService.getDocumentHistoryItem({+ documentId: doc.id,+ historyId: 'head',+ });++ expect(result.id).toBe('head');+ expect(result.isCurrent).toBe(true);+ expect(result.editorData).toBeNull();+ expect(result.saveSource).toBe('system');+ });++ it('should return a persisted history item', async () => {+ const doc = await createTestDocument('Hello');+ const savedAt = new Date('2026-04-01T10:00:00Z');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { version: 42 },+ saveSource: 'manual',+ savedAt,+ });++ const [row] = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(eq(documentHistories.documentId, doc.id));++ const result = await historyService.getDocumentHistoryItem({+ documentId: doc.id,+ historyId: row!.id,+ });++ expect(result.id).toBe(row!.id);+ expect(result.isCurrent).toBe(false);+ expect(result.editorData).toEqual({ version: 42 });+ expect(result.saveSource).toBe('manual');+ });++ it('should throw when history item is older than historySince', async () => {+ const doc = await createTestDocument('Hello');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 1 },+ saveSource: 'autosave',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ const [row] = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(eq(documentHistories.documentId, doc.id));++ await expect(+ historyService.getDocumentHistoryItem(+ { documentId: doc.id, historyId: row!.id },+ { historySince: new Date('2026-04-05T00:00:00Z') },+ ),+ ).rejects.toThrow();+ });++ it('should throw for a historyId belonging to another user', async () => {+ const doc = await createTestDocument('Hello');++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { v: 1 },+ saveSource: 'autosave',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ const [row] = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(eq(documentHistories.documentId, doc.id));++ await expect(+ historyService2.getDocumentHistoryItem({+ documentId: doc.id,+ historyId: row!.id,+ }),+ ).rejects.toThrow();+ });+ });++ describe('compareDocumentHistoryItems', () => {+ it('should compare a history item against head', async () => {+ const doc = await createTestDocument('Current', { current: true });++ await historyService.createHistory({+ documentId: doc.id,+ editorData: { old: true },+ saveSource: 'manual',+ savedAt: new Date('2026-04-01T10:00:00Z'),+ });++ const [row] = await serverDB+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(eq(documentHistories.documentId, doc.id));++ const result = await historyService.compareDocumentHistoryItems({+ documentId: doc.id,+ fromHistoryId: row!.id,+ toHistoryId: 'head',+ });++ expect(result.from.editorData).toEqual({ old: true });+ expect(result.to.editorData).toEqual({ current: true });+ expect(result.to.isCurrent).toBe(true);+ });+ });+});diff --git a/src/server/services/document/__tests__/index.test.ts b/src/server/services/document/__tests__/index.test.tsindex 00bba30158b..db367fc0842 100644--- a/src/server/services/document/__tests__/index.test.ts+++ b/src/server/services/document/__tests__/index.test.ts@@ -5,11 +5,13 @@ import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';import { FileService } from '../../file';+import { DocumentHistoryService } from '../history';import { DocumentService } from '../index';vi.mock('@/database/models/document');vi.mock('@/database/models/file');vi.mock('../../file');+vi.mock('../history');vi.mock('@lobechat/file-loaders', () => ({loadFile: vi.fn(),}));@@ -23,6 +25,7 @@ describe('DocumentService', () => {let service: DocumentService;let mockDb: LobeChatDatabase;let mockDocumentModel: any;+ let mockDocumentHistoryService: any;let mockFileModel: any;let mockFileService: any;const userId = 'test-user-id';@@ -37,6 +40,9 @@ describe('DocumentService', () => {findMany: vi.fn().mockResolvedValue([]),},},+ transaction: vi.fn(async (callback: (tx: LobeChatDatabase) => Promise<unknown>) =>+ callback(mockDb),+ ),} as any;mockDocumentModel = {@@ -48,6 +54,13 @@ describe('DocumentService', () => {update: vi.fn(),};+ mockDocumentHistoryService = {+ compareDocumentHistoryItems: vi.fn(),+ createHistory: vi.fn(),+ getDocumentHistoryItem: vi.fn(),+ listDocumentHistory: vi.fn(),+ };+mockFileModel = {create: vi.fn(),delete: vi.fn(),@@ -60,6 +73,7 @@ describe('DocumentService', () => {};vi.mocked(DocumentModel).mockImplementation(() => mockDocumentModel);+ vi.mocked(DocumentHistoryService).mockImplementation(() => mockDocumentHistoryService);vi.mocked(FileModel).mockImplementation(() => mockFileModel);vi.mocked(FileService).mockImplementation(() => mockFileService);@@ -313,6 +327,86 @@ describe('DocumentService', () => {});});+ describe('document history', () => {+ it('should delegate listDocumentHistory to DocumentHistoryService', async () => {+ const mockResult = {+ items: [{ id: 'head', isCurrent: true, saveSource: 'system', savedAt: new Date() }],+ };+ mockDocumentHistoryService.listDocumentHistory.mockResolvedValue(mockResult);++ const result = await service.listDocumentHistory({ documentId: 'doc-1' });++ expect(mockDocumentHistoryService.listDocumentHistory).toHaveBeenCalledWith(+ {+ documentId: 'doc-1',+ },+ undefined,+ );+ expect(result).toEqual(mockResult);+ });++ it('should delegate getDocumentHistoryItem to DocumentHistoryService', async () => {+ const mockResult = {+ editorData: { blocks: [] },+ id: 'hist-1',+ isCurrent: true,+ saveSource: 'system',+ savedAt: new Date(),+ };+ mockDocumentHistoryService.getDocumentHistoryItem.mockResolvedValue(mockResult);++ const result = await service.getDocumentHistoryItem({+ documentId: 'doc-1',+ historyId: 'hist-1',+ });++ expect(mockDocumentHistoryService.getDocumentHistoryItem).toHaveBeenCalledWith(+ {+ documentId: 'doc-1',+ historyId: 'hist-1',+ },+ undefined,+ );+ expect(result).toEqual(mockResult);+ });++ it('should delegate compareDocumentHistoryItems to DocumentHistoryService', async () => {+ const mockResult = {+ from: {+ editorData: { blocks: [{ id: '1' }] },+ id: 'hist-1',+ isCurrent: false,+ saveSource: 'autosave',+ savedAt: new Date(),+ },+ to: {+ editorData: { blocks: [{ id: '2' }] },+ id: 'head',+ isCurrent: true,+ saveSource: 'system',+ savedAt: new Date(),+ },+ };+ mockDocumentHistoryService.compareDocumentHistoryItems.mockResolvedValue(mockResult);++ const result = await service.compareDocumentHistoryItems({+ documentId: 'doc-1',+ fromHistoryId: 'hist-1',+ toHistoryId: 'head',+ });++ expect(mockDocumentHistoryService.compareDocumentHistoryItems).toHaveBeenCalledWith(+ {+ documentId: 'doc-1',+ fromHistoryId: 'hist-1',+ toHistoryId: 'head',+ },+ undefined,+ );+ expect(result).toEqual(mockResult);+ });+ });+describe('deleteDocument', () => {it('should return early if document not found', async () => {mockDocumentModel.findById.mockResolvedValue(undefined);@@ -424,12 +518,20 @@ describe('DocumentService', () => {});describe('updateDocument', () => {+ const createCurrentDocument = (overrides: Record<string, unknown> = {}) => ({+ editorData: { blocks: [] },+ fileId: null,+ id: 'doc-1',+ updatedAt: new Date('2026-04-11T00:00:00.000Z'),+ ...overrides,+ });+it('should update content and recalculate char/line counts', async () => {const newContent = 'Updated\nContent';mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: null });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());- await service.updateDocument('doc-1', { content: newContent });+ const result = await service.updateDocument('doc-1', { content: newContent });expect(mockDocumentModel.update).toHaveBeenCalledWith('doc-1',@@ -439,24 +541,51 @@ describe('DocumentService', () => {totalLineCount: 2,}),);+ expect(mockDocumentHistoryService.createHistory).not.toHaveBeenCalled();+ expect(result).toEqual({ historyAppended: false, id: 'doc-1' });});- it('should update editorData', async () => {+ it('should append history when editorData changes', async () => {const editorData = { blocks: [{ type: 'paragraph', text: 'Hello' }] };mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: null });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());- await service.updateDocument('doc-1', { editorData });+ const result = await service.updateDocument('doc-1', { editorData, saveSource: 'manual' });expect(mockDocumentModel.update).toHaveBeenCalledWith('doc-1',expect.objectContaining({ editorData }),);+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(+ expect.objectContaining({+ documentId: 'doc-1',+ editorData: { blocks: [] },+ saveSource: 'manual',+ }),+ );+ expect(result.historyAppended).toBe(true);+ expect(result.id).toBe('doc-1');+ expect(result.savedAt).toBeInstanceOf(Date);+ });++ it('should skip history when editorData is unchanged', async () => {+ const editorData = { blocks: [] };+ mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());++ const result = await service.updateDocument('doc-1', { editorData });++ expect(mockDocumentModel.update).toHaveBeenCalledWith(+ 'doc-1',+ expect.objectContaining({ editorData }),+ );+ expect(mockDocumentHistoryService.createHistory).not.toHaveBeenCalled();+ expect(result).toEqual({ historyAppended: false, id: 'doc-1' });});it('should update title and filename together', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: null });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { title: 'New Title' });@@ -471,7 +600,7 @@ describe('DocumentService', () => {it('should sync title update to associated file', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: 'file-1' });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);await service.updateDocument('doc-1', { title: 'New Title' });@@ -481,7 +610,7 @@ describe('DocumentService', () => {it('should sync parentId update to associated file', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: 'file-1' });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);await service.updateDocument('doc-1', { parentId: 'new-parent' });@@ -491,7 +620,7 @@ describe('DocumentService', () => {it('should sync both title and parentId to file when both are updated', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: 'file-1' });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);await service.updateDocument('doc-1', { title: 'New Title', parentId: 'new-parent' });@@ -504,7 +633,7 @@ describe('DocumentService', () => {it('should NOT update file when document has no associated file', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: null });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { title: 'New Title' });@@ -514,7 +643,7 @@ describe('DocumentService', () => {it('should update metadata', async () => {const metadata = { key: 'value' };mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: null });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { metadata });@@ -526,7 +655,7 @@ describe('DocumentService', () => {it('should update fileType', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: null });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { fileType: 'text/markdown' });@@ -538,13 +667,49 @@ describe('DocumentService', () => {it('should handle parentId null (moving to root)', async () => {mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', fileId: 'file-1' });+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);await service.updateDocument('doc-1', { parentId: null });expect(mockFileModel.update).toHaveBeenCalledWith('file-1', { parentId: null });});++ it('should throw when document does not exist', async () => {+ mockDocumentModel.findById.mockResolvedValue(undefined);++ await expect(service.updateDocument('missing-doc', { title: 'Missing' })).rejects.toThrow(+ 'Document not found: missing-doc',+ );+ });+ });++ describe('saveDocumentHistory', () => {+ it('should create a history entry for an existing document', async () => {+ mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });+ mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);++ const result = await service.saveDocumentHistory('doc-1', { blocks: [] }, 'llm_call');++ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(+ expect.objectContaining({+ documentId: 'doc-1',+ editorData: { blocks: [] },+ saveSource: 'llm_call',+ savedAt: expect.any(Date),+ }),+ );+ expect(result.savedAt).toBeInstanceOf(Date);+ });++ it('should throw when document does not exist', async () => {+ mockDocumentModel.findById.mockResolvedValue(undefined);++ await expect(service.saveDocumentHistory('missing-doc', {}, 'manual')).rejects.toThrow(+ 'Document not found: missing-doc',+ );+ expect(mockDocumentHistoryService.createHistory).not.toHaveBeenCalled();+ });});describe('parseDocument', () => {diff --git a/src/server/services/document/diff/json.test.ts b/src/server/services/document/diff/json.test.tsnew file mode 100644index 00000000000..b980a1579c4--- /dev/null+++ b/src/server/services/document/diff/json.test.ts@@ -0,0 +1,133 @@+import { describe, expect, it } from 'vitest';++import type { JsonPatchDelta } from './json';+import { applyJsonPatch, createJsonPatch } from './json';++const createTextNode = (id: string, text: string) => ({+ detail: 0,+ format: 0,+ id,+ mode: 'normal',+ style: '',+ text,+ type: 'text',+ version: 1,+});++const createParagraphNode = (id: string, text?: string) => ({+ children: text ? [createTextNode(`${id}-text`, text)] : [],+ direction: null,+ format: 'start',+ id,+ indent: 0,+ textFormat: 0,+ textStyle: '',+ type: 'paragraph',+ version: 1,+});++const expectJsonPatch = (patch: JsonPatchDelta | undefined): JsonPatchDelta => {+ expect(patch).toBeDefined();++ return patch!;+};++describe('json diff', () => {+ it('should emit an array delta for semantically matched deletions', () => {+ const base = {+ root: {+ children: [+ createParagraphNode('1'),+ createParagraphNode('2'),+ createParagraphNode('3', 'tail'),+ ],+ },+ };+ const current = {+ root: {+ children: [createParagraphNode('1'), createParagraphNode('3', 'tail')],+ },+ };++ const patch = expectJsonPatch(createJsonPatch(base, current));++ expect(patch).toEqual({+ root: {+ children: {+ _1: [createParagraphNode('2'), 0, 0],+ _t: 'a',+ },+ },+ });+ expect(applyJsonPatch(base, patch)).toEqual(current);+ });++ it('should emit an array delta for semantically matched insertions', () => {+ const base = {+ root: {+ children: [createParagraphNode('1'), createParagraphNode('3', 'tail')],+ },+ };+ const current = {+ root: {+ children: [+ createParagraphNode('1'),+ createParagraphNode('2'),+ createParagraphNode('3', 'tail'),+ ],+ },+ };++ const patch = expectJsonPatch(createJsonPatch(base, current));++ expect(patch).toEqual({+ root: {+ children: {+ 1: [createParagraphNode('2')],+ _t: 'a',+ },+ },+ });+ expect(applyJsonPatch(base, patch)).toEqual(current);+ });++ it('should align rekeyed lexical nodes without degrading into array removals', () => {+ const base = {+ root: {+ children: [+ createParagraphNode('p-1', 'alpha'),+ createParagraphNode('p-2', 'beta'),+ createParagraphNode('p-3', 'gamma'),+ ],+ },+ };+ const current = {+ root: {+ children: [+ createParagraphNode('next-1', 'alpha'),+ createParagraphNode('next-2', 'beta updated'),+ createParagraphNode('next-3', 'gamma'),+ ],+ },+ };++ const patch = expectJsonPatch(createJsonPatch(base, current));+ const childDelta = (patch as Record<string, any>).root.children as Record<string, unknown>;++ expect(childDelta._t).toBe('a');+ expect(Object.keys(childDelta).filter((key) => key.startsWith('_') && key !== '_t')).toEqual(+ [],+ );+ expect(applyJsonPatch(base, patch)).toEqual(current);+ });++ it('should return undefined when two documents are identical', () => {+ const document = {+ root: {+ children: [createParagraphNode('1', 'alpha')],+ },+ };++ expect(createJsonPatch(document, document)).toBeUndefined();+ });+});diff --git a/src/server/services/document/diff/json.ts b/src/server/services/document/diff/json.tsnew file mode 100644index 00000000000..e91d06385e3--- /dev/null+++ b/src/server/services/document/diff/json.ts@@ -0,0 +1,67 @@+import { create, type Delta, patch as patchDelta } from 'jsondiffpatch';++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const createHashComparable = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(createHashComparable);+ }++ if (!isRecord(value)) return value;++ const comparable: Record<string, unknown> = {};++ for (const key of Object.keys(value).sort()) {+ if (key === 'id' || key === 'text') continue;++ comparable[key] = createHashComparable(value[key]);+ }++ return comparable;+};++const stableStringify = (value: unknown): string => {+ if (Array.isArray(value)) {+ return `[${value.map((item) => stableStringify(item)).join(',')}]`;+ }++ if (isRecord(value)) {+ return `{${Object.keys(value)+ .sort()+ .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`)+ .join(',')}}`;+ }++ return JSON.stringify(value);+};++const diffPatcher = create({+ arrays: {+ detectMove: false,+ includeValueOnMove: false,+ },+ cloneDiffValues: (value) => structuredClone(value),+ objectHash: (item) => stableStringify(createHashComparable(item)),+});++export type JsonPatchDelta = Exclude<Delta, undefined>;++export const createJsonPatch = (base: Record<string, any>, current: Record<string, any>) => {+ return diffPatcher.diff(base, current);+};++export const applyJsonPatch = (+ base: Record<string, any>,+ patch: JsonPatchDelta,+): Record<string, any> => {+ return patchDelta(structuredClone(base), patch) as Record<string, any>;+};++export const isOversizedJsonPatch = (+ patch: JsonPatchDelta,+ snapshot: Record<string, any>,+ threshold: number,+) => {+ return JSON.stringify(patch).length > JSON.stringify(snapshot).length * threshold;+};diff --git a/src/server/services/document/history.ts b/src/server/services/document/history.tsnew file mode 100644index 00000000000..64a101eee81--- /dev/null+++ b/src/server/services/document/history.ts@@ -0,0 +1,254 @@+import type { DocumentItem } from '@lobechat/database/schemas';+import { documentHistories, documents } from '@lobechat/database/schemas';+import { and, desc, eq, gte, inArray, lt, or } from 'drizzle-orm';++import {+ DOCUMENT_HISTORY_QUERY_LIST_LIMIT,+ DOCUMENT_HISTORY_SOURCE_LIMITS,+} from '@/const/documentHistory';+import { isValidEditorData } from '@/libs/editor/isValidEditorData';++import type {+ CompareDocumentHistoryItemsParams,+ CompareDocumentHistoryItemsResult,+ DatabaseLike,+ DocumentHistoryAccessOptions,+ DocumentHistoryItemResult,+ DocumentHistoryListItem,+ DocumentHistorySaveSource,+ GetDocumentHistoryItemParams,+ ListDocumentHistoryParams,+ ListDocumentHistoryResult,+} from './types';++const getDocumentEditorData = (document: DocumentItem | undefined): Record<string, any> | null => {+ const editorData = document?.editorData;++ return isValidEditorData(editorData) ? editorData : null;+};++export class DocumentHistoryService {+ private readonly db: DatabaseLike;+ private readonly userId: string;++ constructor(db: DatabaseLike, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ createHistory = async (params: {+ documentId: string;+ editorData: Record<string, any>;+ saveSource: DocumentHistorySaveSource;+ savedAt: Date;+ }) => {+ const [document] = await this.db+ .select({ id: documents.id })+ .from(documents)+ .where(and(eq(documents.id, params.documentId), eq(documents.userId, this.userId)))+ .limit(1);++ if (!document) {+ throw new Error('Document not found');+ }++ await this.db.insert(documentHistories).values({+ documentId: params.documentId,+ editorData: params.editorData,+ saveSource: params.saveSource,+ savedAt: params.savedAt,+ userId: this.userId,+ });++ await this.trimHistoryBySource(params.documentId, params.saveSource);+ };++ compareDocumentHistoryItems = async (+ params: CompareDocumentHistoryItemsParams,+ options?: DocumentHistoryAccessOptions,+ ): Promise<CompareDocumentHistoryItemsResult> => {+ const [from, to] = await Promise.all([+ this.getDocumentHistoryItem(+ { documentId: params.documentId, historyId: params.fromHistoryId },+ options,+ ),+ this.getDocumentHistoryItem(+ { documentId: params.documentId, historyId: params.toHistoryId },+ options,+ ),+ ]);++ return { from, to };+ };++ getDocumentHistoryItem = async (+ params: GetDocumentHistoryItemParams,+ options?: DocumentHistoryAccessOptions,+ ): Promise<DocumentHistoryItemResult> => {+ const headDocument = await this.findHeadDocument(params.documentId);++ if (!headDocument) {+ throw new Error(`Document not found: ${params.documentId}`);+ }++ // Treat 'head' as a special historyId representing the current document state+ if (params.historyId === 'head') {+ return {+ editorData: getDocumentEditorData(headDocument),+ id: 'head',+ isCurrent: true,+ saveSource: 'system',+ savedAt: headDocument.updatedAt,+ };+ }++ const historyRow = await this.db.query.documentHistories.findFirst({+ where: and(+ eq(documentHistories.id, params.historyId),+ eq(documentHistories.documentId, params.documentId),+ eq(documentHistories.userId, this.userId),+ options?.historySince ? gte(documentHistories.savedAt, options.historySince) : undefined,+ ),+ });++ if (!historyRow) {+ throw new Error(`Document history item not found: ${params.documentId}@${params.historyId}`);+ }++ return {+ editorData: historyRow.editorData as Record<string, any>,+ id: historyRow.id,+ isCurrent: false,+ saveSource: historyRow.saveSource as DocumentHistorySaveSource,+ savedAt: historyRow.savedAt,+ };+ };++ listDocumentHistory = async (+ params: ListDocumentHistoryParams,+ options?: DocumentHistoryAccessOptions,+ ): Promise<ListDocumentHistoryResult> => {+ const limit = Math.min(params.limit ?? DOCUMENT_HISTORY_QUERY_LIST_LIMIT, 100);+ const headDocument = await this.findHeadDocument(params.documentId);++ if (!headDocument) {+ return { items: [] };+ }++ const includeCurrent = params.includeCurrent ?? true;+ // Head is a synthetic "current" item that always sorts first.+ // Once pagination starts (beforeSavedAt is defined), head has already been passed.+ const shouldIncludeHead = includeCurrent && params.beforeSavedAt === undefined;++ // When head is included, it occupies one slot. To avoid dropping a history+ // row that would then be skipped by an exclusive cursor, we query enough+ // rows so that we can return (limit - 1) history items plus head while+ // basing the cursor on the last returned row (not a dropped one).+ const effectiveLimit = shouldIncludeHead ? Math.max(limit, 2) : limit;++ const historyRows = await this.db.query.documentHistories.findMany({+ limit: effectiveLimit,+ orderBy: [desc(documentHistories.savedAt), desc(documentHistories.id)],+ where: and(+ eq(documentHistories.documentId, params.documentId),+ eq(documentHistories.userId, this.userId),+ options?.historySince ? gte(documentHistories.savedAt, options.historySince) : undefined,+ params.beforeSavedAt !== undefined && params.beforeId !== undefined+ ? or(+ lt(documentHistories.savedAt, params.beforeSavedAt),+ and(+ eq(documentHistories.savedAt, params.beforeSavedAt),+ lt(documentHistories.id, params.beforeId),+ ),+ )+ : params.beforeSavedAt !== undefined+ ? lt(documentHistories.savedAt, params.beforeSavedAt)+ : undefined,+ ),+ });++ const items: DocumentHistoryListItem[] = [];++ if (shouldIncludeHead) {+ items.push({+ id: 'head',+ isCurrent: true,+ saveSource: 'system',+ savedAt: headDocument.updatedAt,+ });+ }++ const historyItems = historyRows.map((row) => ({+ id: row.id,+ isCurrent: false,+ saveSource: row.saveSource as DocumentHistorySaveSource,+ savedAt: row.savedAt,+ }));++ // If head consumed a slot and we fetched a full page of history rows,+ // drop the last history item so total count respects the limit.+ if (shouldIncludeHead && historyRows.length === effectiveLimit) {+ items.push(...historyItems.slice(0, -1));+ } else {+ items.push(...historyItems);+ }++ const hasMore = historyRows.length === effectiveLimit && historyRows.length > 0;++ // Cursor must be based on the last item actually returned, not a dropped row.+ // For head + full page, the last returned history row is the penultimate DB row.+ const lastRow = hasMore+ ? shouldIncludeHead+ ? historyRows.at(-2)+ : historyRows.at(-1)+ : undefined;++ return {+ items,+ nextBeforeId: lastRow?.id,+ nextBeforeSavedAt: lastRow?.savedAt,+ };+ };++ private findHeadDocument = async (documentId: string) => {+ return this.db.query.documents.findFirst({+ where: and(eq(documents.id, documentId), eq(documents.userId, this.userId)),+ });+ };++ private trimHistoryBySource = async (+ documentId: string,+ saveSource: DocumentHistorySaveSource,+ ) => {+ const limit = DOCUMENT_HISTORY_SOURCE_LIMITS[saveSource];+ const BATCH_SIZE = 100;++ const rowsToDelete = await this.db+ .select({ id: documentHistories.id })+ .from(documentHistories)+ .where(+ and(+ eq(documentHistories.documentId, documentId),+ eq(documentHistories.userId, this.userId),+ eq(documentHistories.saveSource, saveSource),+ ),+ )+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id))+ .offset(limit)+ .limit(BATCH_SIZE);++ if (rowsToDelete.length === 0) return;++ await this.db.delete(documentHistories).where(+ and(+ eq(documentHistories.documentId, documentId),+ eq(documentHistories.userId, this.userId),+ eq(documentHistories.saveSource, saveSource),+ inArray(+ documentHistories.id,+ rowsToDelete.map((r) => r.id),+ ),+ ),+ );+ };+}diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.tsindex a07cd3b5bc1..207327b72d7 100644--- a/src/server/services/document/index.ts+++ b/src/server/services/document/index.ts@@ -4,12 +4,26 @@ import { documents, files } from '@lobechat/database/schemas';import { loadFile } from '@lobechat/file-loaders';import debug from 'debug';import { and, eq } from 'drizzle-orm';+import isEqual from 'fast-deep-equal';import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';import { type LobeDocument } from '@/types/document';import { FileService } from '../file';+import { DocumentHistoryService } from './history';+import type {+ CompareDocumentHistoryItemsParams,+ CompareDocumentHistoryItemsResult,+ DocumentHistoryAccessOptions,+ DocumentHistorySaveSource,+ GetDocumentHistoryItemParams,+ ListDocumentHistoryParams,+ ListDocumentHistoryResult,+ SaveDocumentHistoryResult,+ UpdateDocumentParams,+ UpdateDocumentResult,+} from './types';const log = debug('lobe-chat:service:document');@@ -17,6 +31,7 @@ export class DocumentService {userId: string;private fileModel: FileModel;private documentModel: DocumentModel;+ private documentHistoryServiceInstance?: DocumentHistoryService;private fileServiceInstance?: FileService;private db: LobeChatDatabase;@@ -33,6 +48,12 @@ export class DocumentService {return this.fileServiceInstance;}+ private get documentHistoryService() {+ this.documentHistoryServiceInstance ??= new DocumentHistoryService(this.db, this.userId);++ return this.documentHistoryServiceInstance;+ }+/*** Create a document*/@@ -148,6 +169,51 @@ export class DocumentService {return this.documentModel.findById(id);}+ async listDocumentHistory(+ params: ListDocumentHistoryParams,+ options?: DocumentHistoryAccessOptions,+ ): Promise<ListDocumentHistoryResult> {+ return this.documentHistoryService.listDocumentHistory(params, options);+ }++ async getDocumentHistoryItem(+ params: GetDocumentHistoryItemParams,+ options?: DocumentHistoryAccessOptions,+ ) {+ return this.documentHistoryService.getDocumentHistoryItem(params, options);+ }++ async compareDocumentHistoryItems(+ params: CompareDocumentHistoryItemsParams,+ options?: DocumentHistoryAccessOptions,+ ): Promise<CompareDocumentHistoryItemsResult> {+ return this.documentHistoryService.compareDocumentHistoryItems(params, options);+ }++ /**+ * Save a document history snapshot explicitly.+ */+ async saveDocumentHistory(+ documentId: string,+ editorData: Record<string, any>,+ saveSource: DocumentHistorySaveSource,+ ): Promise<SaveDocumentHistoryResult> {+ const currentDocument = await this.documentModel.findById(documentId);+ if (!currentDocument) {+ throw new Error(`Document not found: ${documentId}`);+ }++ const savedAt = new Date();+ await this.documentHistoryService.createHistory({+ documentId,+ editorData,+ saveSource,+ savedAt,+ });++ return { savedAt };+ }+/*** Delete document (recursively deletes children if it's a folder)*/@@ -196,60 +262,81 @@ export class DocumentService {/*** Update document*/- async updateDocument(- id: string,- params: {- content?: string;- editorData?: Record<string, any>;- fileType?: string;- metadata?: Record<string, any>;- parentId?: string | null;- title?: string;- },- ) {- const updates: any = {};+ async updateDocument(id: string, params: UpdateDocumentParams): Promise<UpdateDocumentResult> {+ return this.db.transaction(async (tx) => {+ const transactionDb = tx as unknown as LobeChatDatabase;+ const documentModel = new DocumentModel(transactionDb, this.userId);+ const fileModel = new FileModel(transactionDb, this.userId);+ const documentHistoryService = new DocumentHistoryService(transactionDb, this.userId);++ const currentDocument = await documentModel.findById(id);+ if (!currentDocument) {+ throw new Error(`Document not found: ${id}`);+ }- if (params.content !== undefined) {- updates.content = params.content;- updates.totalCharCount = params.content.length;- updates.totalLineCount = params.content.split('\n').length;- }+ const currentEditorData = (currentDocument.editorData ?? {}) as Record<string, any>;+ const nextEditorData = params.editorData;+ const historyAppended =+ nextEditorData !== undefined && !isEqual(nextEditorData, currentEditorData);- if (params.editorData !== undefined) {- updates.editorData = params.editorData;- }+ const updates: Record<string, unknown> = {};- if (params.fileType !== undefined) {- updates.fileType = params.fileType;- }+ if (params.content !== undefined) {+ updates.content = params.content;+ updates.totalCharCount = params.content.length;+ updates.totalLineCount = params.content.split('\n').length;+ }- if (params.title !== undefined) {- updates.title = params.title;- updates.filename = params.title;- }+ if (params.editorData !== undefined) {+ updates.editorData = params.editorData;+ }- if (params.metadata !== undefined) {- updates.metadata = params.metadata;- }+ if (params.fileType !== undefined) {+ updates.fileType = params.fileType;+ }- if (params.parentId !== undefined) {- updates.parentId = params.parentId;- }+ if (params.title !== undefined) {+ updates.title = params.title;+ updates.filename = params.title;+ }++ if (params.metadata !== undefined) {+ updates.metadata = params.metadata;+ }- const result = await this.documentModel.update(id, updates);+ if (params.parentId !== undefined) {+ updates.parentId = params.parentId;+ }++ let savedAt: Date | undefined;- // If title was updated and this document has an associated file, update the file name too- if (params.title !== undefined || params.parentId !== undefined) {- const document = await this.documentModel.findById(id);- if (document?.fileId) {- const fileUpdates: any = {};+ if (historyAppended) {+ savedAt = new Date();+ await documentHistoryService.createHistory({+ documentId: id,+ editorData: currentEditorData,+ saveSource: params.saveSource ?? 'autosave',+ savedAt,+ });+ }++ if (Object.keys(updates).length > 0) {+ await documentModel.update(id, updates as Partial<DocumentItem>);+ }++ if ((params.title !== undefined || params.parentId !== undefined) && currentDocument.fileId) {+ const fileUpdates: Record<string, string | null> = {};if (params.title !== undefined) fileUpdates.name = params.title;if (params.parentId !== undefined) fileUpdates.parentId = params.parentId;- await this.fileModel.update(document.fileId, fileUpdates);+ await fileModel.update(currentDocument.fileId, fileUpdates);}- }- return result;+ return {+ historyAppended,+ id,+ savedAt,+ };+ });}/**diff --git a/src/server/services/document/types.ts b/src/server/services/document/types.tsnew file mode 100644index 00000000000..acd0a410964--- /dev/null+++ b/src/server/services/document/types.ts@@ -0,0 +1,75 @@+import type { LobeChatDatabase, Transaction } from '@/database/type';++export type DocumentHistorySaveSource = 'autosave' | 'manual' | 'restore' | 'system' | 'llm_call';++export interface CompareDocumentHistoryItemsParams {+ documentId: string;+ fromHistoryId: string;+ toHistoryId: string;+}++export interface CompareDocumentHistoryItemsResult {+ from: DocumentHistoryItemResult;+ to: DocumentHistoryItemResult;+}++export interface DocumentHistoryAccessOptions {+ historySince?: Date;+}++export interface DocumentHistoryListItem {+ id: string;+ isCurrent: boolean;+ savedAt: Date;+ saveSource: DocumentHistorySaveSource;+}++export interface DocumentHistoryItemResult {+ editorData: Record<string, any> | null;+ id: string;+ isCurrent: boolean;+ savedAt: Date;+ saveSource: DocumentHistorySaveSource;+}++export interface GetDocumentHistoryItemParams {+ documentId: string;+ historyId: string;+}++export interface ListDocumentHistoryParams {+ beforeId?: string;+ beforeSavedAt?: Date;+ documentId: string;+ includeCurrent?: boolean;+ limit?: number;+}++export interface ListDocumentHistoryResult {+ items: DocumentHistoryListItem[];+ nextBeforeId?: string;+ nextBeforeSavedAt?: Date;+}++export type DatabaseLike = LobeChatDatabase | Transaction;++export interface UpdateDocumentParams {+ content?: string;+ editorData?: Record<string, any>;+ fileType?: string;+ metadata?: Record<string, any>;+ parentId?: string | null;+ restoreFromHistoryId?: string;+ saveSource?: DocumentHistorySaveSource;+ title?: string;+}++export interface UpdateDocumentResult {+ historyAppended: boolean;+ id: string;+ savedAt?: Date;+}++export interface SaveDocumentHistoryResult {+ savedAt: Date;+}diff --git a/src/services/document/index.ts b/src/services/document/index.tsindex 11ef5b2f332..5c8221ea7b9 100644--- a/src/services/document/index.ts+++ b/src/services/document/index.ts@@ -1,9 +1,94 @@import { type DocumentItem } from '@lobechat/database/schemas';import { lambdaClient } from '@/libs/trpc/client';+import type {+ CompareHistoryItemsInput,+ CompareHistoryItemsOutput,+ GetHistoryItemInput,+ GetHistoryItemOutput,+ ListHistoryInput,+ ListHistoryOutput,+ SaveDocumentHistoryInput,+ SaveDocumentHistoryOutput,+ UpdateDocumentInput,+ UpdateDocumentOutput,+} from '@/server/routers/lambda/_schema/documentHistory';import { abortableRequest } from '../utils/abortableRequest';+const serializeSavedAt = (savedAt: Date | string) =>+ savedAt instanceof Date ? savedAt.toISOString() : savedAt;++type SerializedSavedAt<T extends { savedAt: Date | string }> = Omit<T, 'savedAt'> & {+ savedAt: string;+};++const serializeHistoryTimestamp = <T extends { savedAt: Date | string }>(+ result: T,+): SerializedSavedAt<T> => ({+ ...result,+ savedAt: serializeSavedAt(result.savedAt),+});++const serializeHistoryList = <+ T extends {+ items: Array<{+ id: string;+ isCurrent: boolean;+ saveSource: ListHistoryOutput['items'][number]['saveSource'];+ savedAt: Date | string;+ }>;+ nextBeforeSavedAt?: Date | string;+ },+>(+ result: T,+): ListHistoryOutput => ({+ ...result,+ items: result.items.map((item) => ({+ ...item,+ savedAt: serializeSavedAt(item.savedAt),+ })),+ nextBeforeSavedAt: result.nextBeforeSavedAt+ ? serializeSavedAt(result.nextBeforeSavedAt)+ : undefined,+});++const serializeHistoryItem = <+ T extends {+ editorData: GetHistoryItemOutput['editorData'];+ id: string;+ isCurrent: boolean;+ saveSource: GetHistoryItemOutput['saveSource'];+ savedAt: Date | string;+ },+>(+ result: T,+): GetHistoryItemOutput => serializeHistoryTimestamp(result);++const serializeHistoryComparison = <+ T extends {+ from: {+ editorData: CompareHistoryItemsOutput['from']['editorData'];+ id: string;+ isCurrent: boolean;+ saveSource: CompareHistoryItemsOutput['from']['saveSource'];+ savedAt: Date | string;+ };+ to: {+ editorData: CompareHistoryItemsOutput['to']['editorData'];+ id: string;+ isCurrent: boolean;+ saveSource: CompareHistoryItemsOutput['to']['saveSource'];+ savedAt: Date | string;+ };+ },+>(+ result: T,+): CompareHistoryItemsOutput => ({+ from: serializeHistoryTimestamp(result.from),+ to: serializeHistoryTimestamp(result.to),+});+export interface CreateDocumentParams {content?: string;editorData: string;@@ -15,14 +100,25 @@ export interface CreateDocumentParams {title: string;}-export interface UpdateDocumentParams {- content?: string;- editorData?: string;- fileType?: string;- id: string;- metadata?: Record<string, any>;- parentId?: string | null;- title?: string;+export interface ListDocumentHistoryParams extends ListHistoryInput {}++export interface GetDocumentHistoryItemParams extends GetHistoryItemInput {}++export interface CompareDocumentHistoryItemsParams extends CompareHistoryItemsInput {}++export interface UpdateDocumentParams extends UpdateDocumentInput {}++export interface DocumentHistoryClientSurface {+ compareDocumentHistoryItems: (+ params: CompareDocumentHistoryItemsParams,+ ) => Promise<CompareHistoryItemsOutput>;+ getDocumentHistoryItem: (+ params: GetDocumentHistoryItemParams,+ uniqueKey?: string,+ ) => Promise<GetHistoryItemOutput>;+ listDocumentHistory: (params: ListDocumentHistoryParams) => Promise<ListHistoryOutput>;+ saveDocumentHistory: (params: SaveDocumentHistoryInput) => Promise<SaveDocumentHistoryOutput>;+ updateDocument: (params: UpdateDocumentParams) => Promise<UpdateDocumentOutput>;}export class DocumentService {@@ -43,9 +139,39 @@ export class DocumentService {return lambdaClient.document.queryDocuments.query(params);}- /**- * Query page documents with standard filters for the page sidebar.- */+ async listDocumentHistory(params: ListDocumentHistoryParams): Promise<ListHistoryOutput> {+ const result = await lambdaClient.document.listDocumentHistory.query(params);++ return serializeHistoryList(result);+ }++ async getDocumentHistoryItem(+ params: GetDocumentHistoryItemParams,+ uniqueKey?: string,+ ): Promise<GetHistoryItemOutput> {+ if (uniqueKey) {+ return abortableRequest.execute(uniqueKey, async (signal) => {+ const result = await lambdaClient.document.getDocumentHistoryItem.query(params, {+ signal,+ });++ return serializeHistoryItem(result);+ });+ }++ const result = await lambdaClient.document.getDocumentHistoryItem.query(params);++ return serializeHistoryItem(result);+ }++ async compareDocumentHistoryItems(+ params: CompareDocumentHistoryItemsParams,+ ): Promise<CompareHistoryItemsOutput> {+ const result = await lambdaClient.document.compareDocumentHistoryItems.query(params);++ return serializeHistoryComparison(result);+ }+async getPageDocuments(pageSize: number = 20): Promise<DocumentItem[]> {const result = await this.queryDocuments({current: 0,@@ -83,9 +209,27 @@ export class DocumentService {await lambdaClient.document.deleteDocuments.mutate({ ids });}- async updateDocument(params: UpdateDocumentParams): Promise<void> {- await lambdaClient.document.updateDocument.mutate(params);+ async updateDocument(params: UpdateDocumentParams): Promise<UpdateDocumentOutput> {+ const result = await lambdaClient.document.updateDocument.mutate(params);++ return {+ ...result,+ savedAt: result.savedAt+ ? result.savedAt instanceof Date+ ? result.savedAt.toISOString()+ : result.savedAt+ : undefined,+ };+ }++ async saveDocumentHistory(params: SaveDocumentHistoryInput): Promise<SaveDocumentHistoryOutput> {+ const result = await lambdaClient.document.saveDocumentHistory.mutate(params);++ return {+ savedAt: result.savedAt instanceof Date ? result.savedAt.toISOString() : result.savedAt,+ };}}-export const documentService = new DocumentService();+export const documentService = new DocumentService() as DocumentService &+ DocumentHistoryClientSurface;diff --git a/src/services/documentHistoryQueue.ts b/src/services/documentHistoryQueue.tsnew file mode 100644index 00000000000..4f038897d34--- /dev/null+++ b/src/services/documentHistoryQueue.ts@@ -0,0 +1,48 @@+import debug from 'debug';++import { documentService } from '@/services/document';++const log = debug('page:editor:history-queue');++interface QueueItem {+ documentId: string;+ editorData: string;+ saveSource: 'llm_call';+}++class DocumentHistoryQueueService {+ private queue: QueueItem[] = [];+ private isProcessing = false;++ enqueue = (item: QueueItem) => {+ this.queue.push(item);+ void this.drain();+ };++ drain = async () => {+ if (this.isProcessing) return;+ this.isProcessing = true;++ while (this.queue.length > 0) {+ const item = this.queue.shift();+ if (!item) continue;+ try {+ await documentService.saveDocumentHistory({+ documentId: item.documentId,+ editorData: item.editorData,+ saveSource: item.saveSource,+ });+ } catch (error) {+ log('Failed to save history: %o', error);+ }+ }++ this.isProcessing = false;+ };++ flush = async () => {+ await this.drain();+ };+}++export const documentHistoryQueueService = new DocumentHistoryQueueService();diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.tsindex 29cdcdb3d55..7901c2e3170 100644--- a/src/store/document/slices/document/action.ts+++ b/src/store/document/slices/document/action.ts@@ -29,6 +29,7 @@ export interface InitDocumentParams {documentId: string;editor: IEditor;editorData?: unknown;+sourceType: DocumentSourceType;topicId?: string;}@@ -71,7 +72,7 @@ export class DocumentActionImpl {const debouncedFn = debounce(async () => {try {- await this.#get().performSave(documentId);+ await this.#get().performSave(documentId, undefined, { saveSource: 'autosave' });} catch (error) {console.error('[DocumentStore] Failed to auto-save:', error);}@@ -130,7 +131,7 @@ export class DocumentActionImpl {* Content is loaded into editor via onEditorInit when Editor component is ready.*/initDocumentWithEditor = (params: InitDocumentParams): void => {- const { documentId, sourceType, content, editorData, topicId, autoSave, editor } = params;+ const { autoSave, content, documentId, editor, editorData, sourceType, topicId } = params;const { internal_dispatchDocument } = this.#get();@@ -142,6 +143,7 @@ export class DocumentActionImpl {autoSave,content: content ?? undefined,editorData,+lastSavedContent: content ?? undefined,lastSavedEditorData: editorData,sourceType,@@ -209,6 +211,7 @@ export class DocumentActionImpl {documentId,editor,editorData: document.editorData,+sourceType,});},diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.tsindex 064ef272bfc..75fb5e7ebcc 100644--- a/src/store/document/slices/editor/action.test.ts+++ b/src/store/document/slices/editor/action.test.ts@@ -2,13 +2,14 @@ import { act, renderHook } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';+import { documentService } from '@/services/document';import { useDocumentStore } from '../../store';// Mock servicesvi.mock('@/services/document', () => ({documentService: {- updateDocument: vi.fn().mockResolvedValue({}),+ updateDocument: vi.fn().mockResolvedValue({ historyAppended: false, id: 'doc-1' }),},}));@@ -30,6 +31,11 @@ const createMockEditor = () => ({describe('DocumentStore - Editor Actions', () => {beforeEach(() => {+ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ });+// Reset store state before each testconst { result } = renderHook(() => useDocumentStore());act(() => {@@ -136,6 +142,23 @@ describe('DocumentStore - Editor Actions', () => {// Should NOT call setDocument - that happens in onEditorInitexpect(mockEditor.setDocument).not.toHaveBeenCalled();});++ it('should initialize document with editor data', () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;+ const editorData = { blocks: [{ type: 'paragraph' }] };++ act(() => {+ result.current.initDocumentWithEditor({+ documentId: 'doc-1',+ editor: mockEditor,+ editorData,+ sourceType: 'page',+ });+ });++ expect(result.current.documents['doc-1'].editorData).toEqual(editorData);+ });});describe('onEditorInit', () => {@@ -300,7 +323,7 @@ describe('DocumentStore - Editor Actions', () => {const mockEditor = {getDocument: vi.fn((type: string) => {if (type === 'markdown') return '# Test';- if (type === 'json') return { type: 'doc', version: 2 };+ if (type === 'json') return { type: 'doc', updated: true };return null;}),setDocument: vi.fn(),@@ -311,7 +334,7 @@ describe('DocumentStore - Editor Actions', () => {content: '# Test',documentId: 'doc-1',editor: mockEditor,- editorData: { type: 'doc', version: 1 },+ editorData: { type: 'doc' },sourceType: 'page',});});@@ -324,7 +347,7 @@ describe('DocumentStore - Editor Actions', () => {expect(result.current.documents['doc-1']).toMatchObject({content: '# Test',- editorData: { type: 'doc', version: 2 },+ editorData: { type: 'doc', updated: true },isDirty: true,});});@@ -391,4 +414,111 @@ describe('DocumentStore - Editor Actions', () => {}).not.toThrow();});});++ describe('performSave', () => {+ it('should reject saving when editorData is an empty object', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = {+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Test';+ if (type === 'json') return {};+ return null;+ }),+ setDocument: vi.fn(),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'page',+ });+ result.current.markDirty('doc-1');+ });+ vi.mocked(documentService.updateDocument).mockClear();++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ expect(documentService.updateDocument).not.toHaveBeenCalled();+ expect(result.current.documents['doc-1'].isDirty).toBe(true);+ expect(result.current.documents['doc-1'].saveStatus).toBe('idle');+ });++ it('should save metadata-only updates when history is not appended', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;++ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ });++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'page',+ });+ });++ await act(async () => {+ await result.current.performSave(+ 'doc-1',+ { title: 'Updated Title' },+ { saveSource: 'autosave' },+ );+ });++ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'doc-1',+ saveSource: 'autosave',+ title: 'Updated Title',+ }),+ );+ expect(result.current.documents['doc-1'].isDirty).toBe(false);+ });++ it('should pass restore metadata through updateDocument', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createMockEditor() as any;++ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: true,+ id: 'doc-1',+ savedAt: '2026-04-15T10:00:00.000Z',+ });++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'page',+ });+ result.current.markDirty('doc-1');+ });++ await act(async () => {+ await result.current.performSave('doc-1', undefined, {+ restoreFromHistoryId: 'hist-2',+ saveSource: 'restore',+ });+ });++ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({+ content: '# Test',+ id: 'doc-1',+ restoreFromHistoryId: 'hist-2',+ saveSource: 'restore',+ }),+ );+ expect(result.current.documents['doc-1'].isDirty).toBe(false);+ });+ });});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex f0b9da0d886..659df2b82bf 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -5,6 +5,7 @@ import type { EditorState as LobehubEditorState } from '@lobehub/editor/react';import isEqual from 'fast-deep-equal';import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';+import { isValidEditorData } from '@/libs/editor/isValidEditorData';import { documentService } from '@/services/document';import type { StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';@@ -23,6 +24,11 @@ export interface SaveMetadata {title?: string;}+export interface SaveExecutionOptions {+ restoreFromHistoryId?: string;+ saveSource?: 'autosave' | 'manual' | 'restore' | 'system' | 'llm_call';+}+type Setter = StoreSetter<DocumentStore>;export const createEditorSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>new EditorActionImpl(set, get, _api);@@ -143,7 +149,11 @@ export class EditorActionImpl {this.#set({ editor });};- performSave = async (documentId?: string, metadata?: SaveMetadata): Promise<void> => {+ performSave = async (+ documentId?: string,+ metadata?: SaveMetadata,+ options?: SaveExecutionOptions,+ ): Promise<void> => {const id = documentId || this.#get().activeDocumentId;if (!id) return;@@ -152,8 +162,10 @@ export class EditorActionImpl {const doc = documents[id];if (!doc || !editor) return;- // Skip save if no changes- if (!doc.isDirty) return;+ const hasMetadataChanges = metadata?.emoji !== undefined || metadata?.title !== undefined;++ // Skip save if neither document content nor metadata changed+ if (!doc.isDirty && !hasMetadataChanges) return;// Update save statusinternal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'saving' } });@@ -162,12 +174,20 @@ export class EditorActionImpl {const currentContent = (editor.getDocument('markdown') as unknown as string) || '';const currentEditorData = editor.getDocument('json');+ if (!isValidEditorData(currentEditorData)) {+ console.warn('[DocumentStore] Refusing to save invalid editorData:', currentEditorData);+ internal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'idle' } });+ return;+ }+// Save document- await documentService.updateDocument({+ const result = await documentService.updateDocument({content: currentContent,editorData: JSON.stringify(currentEditorData),id,metadata: metadata?.emoji ? { emoji: metadata.emoji } : undefined,+ restoreFromHistoryId: options?.restoreFromHistoryId,+ saveSource: options?.saveSource,title: metadata?.title,});@@ -177,10 +197,11 @@ export class EditorActionImpl {type: 'updateDocument',value: {editorData: structuredClone(currentEditorData),+isDirty: false,lastSavedContent: currentContent,lastSavedEditorData: structuredClone(currentEditorData),- lastUpdatedTime: new Date(),+ lastUpdatedTime: result.savedAt ? new Date(result.savedAt) : new Date(),saveStatus: 'saved',},});diff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.tsindex c5aa5bb2424..262c2619299 100644--- a/src/store/document/slices/editor/initialState.ts+++ b/src/store/document/slices/editor/initialState.ts@@ -26,6 +26,7 @@ export interface EditorContentState {* Editor JSON data (BlockNote format)*/editorData: any;+/*** Whether there are unsaved changes*/@@ -87,6 +88,7 @@ export const createInitialEditorContentState = (): EditorContentState => ({content: '',editorData: null,+isDirty: false,lastSavedContent: '',lastSavedEditorData: null,diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.tsindex b2e1be095d4..dca6f7015d8 100644--- a/src/store/file/slices/document/action.test.ts+++ b/src/store/file/slices/document/action.test.ts@@ -127,7 +127,10 @@ describe('DocumentAction', () => {const existingDocument = createDocumentFixture();const existingResource = createResourceFixture();- vi.mocked(documentService.updateDocument).mockResolvedValue(undefined);+ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ });act(() => {useStore.setState(@@ -175,10 +178,12 @@ describe('DocumentAction', () => {const existingDocument = createDocumentFixture();const existingResource = createResourceFixture();- let resolveUpdate: (() => void) | undefined;+ let resolveUpdate:+ | ((value: { historyAppended: boolean; id: string; savedAt?: string }) => void)+ | undefined;vi.mocked(documentService.updateDocument).mockImplementation(() =>- new Promise<void>((resolve) => {+ new Promise((resolve) => {resolveUpdate = resolve;}),);@@ -215,7 +220,7 @@ describe('DocumentAction', () => {title: 'Optimistic title',});- resolveUpdate?.();+ resolveUpdate?.({ historyAppended: false, id: 'doc-1' });await act(async () => {await pendingUpdate;diff --git a/src/utils/motion/panelSlideMotion.ts b/src/utils/motion/panelSlideMotion.tsnew file mode 100644index 00000000000..d5b1e890afe--- /dev/null+++ b/src/utils/motion/panelSlideMotion.ts@@ -0,0 +1,36 @@+/** Slide direction for panel content swap: -1 = back, 0 = none, 1 = forward */+export type PanelSlideMotionDirection = -1 | 0 | 1;++const OFFSET_PX = 8;++const transition = {+ duration: 0.28,+ ease: [0.4, 0, 0.2, 1],+} as const;++function createPanelSlideMotionVariants(horizontalSign: 1 | -1) {+ return {+ animate: { opacity: 1, x: 0 },+ exit: (direction: PanelSlideMotionDirection) => ({+ opacity: 0,+ x: -direction * OFFSET_PX * horizontalSign,+ }),+ initial: (direction: PanelSlideMotionDirection) => ({+ opacity: 0,+ x: direction * OFFSET_PX * horizontalSign,+ }),+ transition,+ } as const;+}++/**+ * Left-docked panel (e.g. main nav): forward / back along the natural reading axis of that strip.+ */+export const panelSlideMotionVariantsLeft = createPanelSlideMotionVariants(1);++/**+ * Right-docked panel (e.g. page editor side panel): same timing as left, horizontal slide mirrored.+ */+export const panelSlideMotionVariantsRight = createPanelSlideMotionVariants(-1);++export const isPanelLayerMotionDisabled = (animationMode?: string) => animationMode === 'disabled';