🤯 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
🐛 fix(document): enforce one document version invariant across autosave, agent writes and Portal edits (#19757)
Inneie3772ea58187
diff --git a/apps/server/src/routers/lambda/_schema/documentHistory.ts b/apps/server/src/routers/lambda/_schema/documentHistory.tsindex 18f8d28a9f5..87aad3c969a 100644--- a/apps/server/src/routers/lambda/_schema/documentHistory.ts+++ b/apps/server/src/routers/lambda/_schema/documentHistory.ts@@ -103,6 +103,7 @@ export interface UpdateDocumentOutput {historyAppended: boolean;id: string;savedAt?: string;+ updatedAt: string;}export interface SaveDocumentHistoryInput {diff --git a/apps/server/src/services/document/__tests__/history.integration.test.ts b/apps/server/src/services/document/__tests__/history.integration.test.tsindex 7ba52307686..a30a62c0124 100644--- a/apps/server/src/services/document/__tests__/history.integration.test.ts+++ b/apps/server/src/services/document/__tests__/history.integration.test.ts@@ -215,8 +215,10 @@ describe('DocumentHistoryService', () => {});}- // Force document updatedAt to match the history savedAt- await documentModel.update(doc.id, { updatedAt: sharedDate });+ await serverDB+ .update(documents)+ .set({ updatedAt: sharedDate })+ .where(eq(documents.id, doc.id));const firstPage = await historyService.listDocumentHistory({documentId: doc.id,diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.tsindex c2902dc9159..f43ecd3978b 100644--- a/apps/server/src/services/document/__tests__/index.test.ts+++ b/apps/server/src/services/document/__tests__/index.test.ts@@ -784,7 +784,7 @@ describe('DocumentService', () => {it('should update content and recalculate char/line counts', async () => {const newContent = 'Updated\nContent';- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());const result = await service.updateDocument('doc-1', { content: newContent });@@ -798,12 +798,17 @@ describe('DocumentService', () => {}),);expect(mockDocumentHistoryService.createHistory).not.toHaveBeenCalled();- expect(result).toEqual({ historyAppended: false, id: 'doc-1' });+ expect(result).toEqual({+ historyAppended: false,+ id: 'doc-1',+ savedAt: undefined,+ updatedAt: expect.any(Date),+ });});it('should append history when editorData changes', async () => {const editorData = { blocks: [{ type: 'paragraph', text: 'Hello' }] };- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());const result = await service.updateDocument('doc-1', { editorData, saveSource: 'manual' });@@ -824,6 +829,24 @@ describe('DocumentService', () => {expect(result.savedAt).toBeInstanceOf(Date);});+ it('should return the updatedAt written to the row, matching the history savedAt', async () => {+ const editorData = { blocks: [{ type: 'paragraph', text: 'Hello' }] };+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));+ mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());++ const result = await service.updateDocument('doc-1', { editorData, saveSource: 'manual' });++ expect(mockDocumentModel.update).toHaveBeenCalledWith(+ 'doc-1',+ expect.not.objectContaining({ updatedAt: expect.anything() }),+ );+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(+ expect.objectContaining({ savedAt: result.updatedAt }),+ );+ expect(result.updatedAt).toEqual(new Date('2026-04-12T00:00:00.000Z'));+ expect(result.savedAt).toEqual(result.updatedAt);+ });+it('should persist raw editorData with diff nodes and normalize only the history snapshot', async () => {const editorData = {root: {@@ -844,7 +867,7 @@ describe('DocumentService', () => {],},};- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ editorData: createEditorDataWithDiffNode() }),);@@ -888,7 +911,7 @@ describe('DocumentService', () => {it('accepts the save when expectedUpdatedAt matches the stored row', async () => {const storedUpdatedAt = new Date('2026-04-11T00:00:00.000Z');- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());(mockDb as any).select = vi.fn(() => ({from: () => ({@@ -905,12 +928,17 @@ describe('DocumentService', () => {'doc-1',expect.objectContaining({ content: 'retry payload' }),);- expect(result).toEqual({ historyAppended: false, id: 'doc-1' });+ expect(result).toEqual({+ historyAppended: false,+ id: 'doc-1',+ savedAt: undefined,+ updatedAt: expect.any(Date),+ });});it('should skip history when editorData is unchanged', async () => {const editorData = { blocks: [] };- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());const result = await service.updateDocument('doc-1', { editorData });@@ -920,7 +948,27 @@ describe('DocumentService', () => {expect.objectContaining({ editorData }),);expect(mockDocumentHistoryService.createHistory).not.toHaveBeenCalled();- expect(result).toEqual({ historyAppended: false, id: 'doc-1' });+ expect(result).toEqual({+ historyAppended: false,+ id: 'doc-1',+ savedAt: undefined,+ updatedAt: expect.any(Date),+ });+ });++ it('should return the pre-existing updatedAt unchanged when nothing is written', async () => {+ const currentDocument = createCurrentDocument();+ mockDocumentModel.findById.mockResolvedValue(currentDocument);++ const result = await service.updateDocument('doc-1', { saveSource: 'manual' });++ expect(mockDocumentModel.update).not.toHaveBeenCalled();+ expect(result).toEqual({+ historyAppended: false,+ id: 'doc-1',+ savedAt: undefined,+ updatedAt: currentDocument.updatedAt,+ });});it('should report members newly mentioned by this save on the accepted view', async () => {@@ -943,7 +991,7 @@ describe('DocumentService', () => {type: 'root',},};- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ editorData: currentEditorData }),);@@ -965,7 +1013,7 @@ describe('DocumentService', () => {type: 'root',},};- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ editorData: currentEditorData }),);@@ -977,7 +1025,7 @@ describe('DocumentService', () => {});it('should update title and filename together', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { title: 'New Title' });@@ -992,7 +1040,7 @@ describe('DocumentService', () => {});it('should sync title update to associated file', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);@@ -1002,7 +1050,7 @@ describe('DocumentService', () => {});it('should sync parentId update to associated file', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);@@ -1012,7 +1060,7 @@ describe('DocumentService', () => {});it('should sync both title and parentId to file when both are updated', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);@@ -1025,7 +1073,7 @@ describe('DocumentService', () => {});it('should NOT update file when document has no associated file', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { title: 'New Title' });@@ -1035,7 +1083,7 @@ describe('DocumentService', () => {it('should update metadata', async () => {const metadata = { key: 'value' };- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { metadata });@@ -1047,7 +1095,7 @@ describe('DocumentService', () => {});it('should update fileType', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument());await service.updateDocument('doc-1', { fileType: 'text/markdown' });@@ -1059,7 +1107,7 @@ describe('DocumentService', () => {});it('should handle parentId null (moving to root)', async () => {- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ fileId: 'file-1' }));mockFileModel.update.mockResolvedValue(undefined);@@ -1091,7 +1139,7 @@ describe('DocumentService', () => {// Private rows are creator-only; a leftover lease from a publish →// unpublish flip must not turn every autosave into a CONFLICT loop.const wsService = new DocumentService(mockDb, userId, 'ws-1');- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ visibility: 'private', workspaceId: 'ws-1' }),);@@ -1105,7 +1153,7 @@ describe('DocumentService', () => {it('should allow a workspace save when no other member holds the lock', async () => {const wsService = new DocumentService(mockDb, userId, 'ws-1');- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ workspaceId: 'ws-1' }));vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(true);@@ -1116,7 +1164,7 @@ describe('DocumentService', () => {it('checks workspace body saves against the provided lock owner id', async () => {const wsService = new DocumentService(mockDb, userId, 'ws-1');- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ workspaceId: 'ws-1' }));const guardSpy = vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(true);@@ -1128,7 +1176,7 @@ describe('DocumentService', () => {it('allows a metadata-only save while another member holds the lock (only the body is locked)', async () => {const wsService = new DocumentService(mockDb, userId, 'ws-1');- mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });+ mockDocumentModel.update.mockResolvedValue(new Date('2026-04-12T00:00:00.000Z'));// Current body matches what the autosave re-sends — only title changes.mockDocumentModel.findById.mockResolvedValue(createCurrentDocument({ content: 'body', editorData: { blocks: [] }, workspaceId: 'ws-1' }),diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex 73a3761dd21..6af56a5fd81 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -754,23 +754,25 @@ export class DocumentService {// The lock lease is refreshed by the client heartbeat (acquireDocumentLock),// so a save does not need to touch it.- let savedAt: Date | undefined;+ const rowUpdated = Object.keys(updates).length > 0 || historyAppended;+ let updatedAt = currentDocument.updatedAt;+ if (rowUpdated) {+ const committedVersion = await documentModel.update(id, updates as Partial<DocumentItem>);+ if (!committedVersion) throw new Error(`Document not found: ${id}`);+ updatedAt = committedVersion;+ }+ const savedAt = historyAppended ? updatedAt : undefined;if (historyAppended) {- savedAt = new Date();await documentHistoryService.createHistory({breakAutosaveWindow: params.breakAutosaveWindow,documentId: id,editorData: currentEditorDataAccepted,saveSource: params.saveSource ?? 'autosave',- savedAt,+ savedAt: updatedAt,});}- 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;@@ -778,13 +780,14 @@ export class DocumentService {await fileModel.update(currentDocument.fileId, fileUpdates);}- changed = Object.keys(updates).length > 0 || historyAppended;+ changed = rowUpdated;return {...(addedMentionUserIds.length > 0 ? { addedMentionUserIds } : {}),historyAppended,id,savedAt,+ updatedAt,};});diff --git a/apps/server/src/services/document/types.ts b/apps/server/src/services/document/types.tsindex 7a6a4704d40..a2a447315da 100644--- a/apps/server/src/services/document/types.ts+++ b/apps/server/src/services/document/types.ts@@ -78,6 +78,7 @@ export interface UpdateDocumentResult {historyAppended: boolean;id: string;savedAt?: Date;+ updatedAt: Date;}export interface SaveDocumentHistoryResult {diff --git a/locales/en-US/portal.json b/locales/en-US/portal.jsonindex 2ea60ea72c3..abba5af8369 100644--- a/locales/en-US/portal.json+++ b/locales/en-US/portal.json@@ -30,6 +30,7 @@"artifacts.svg.copySuccess": "Image copied successfully","artifacts.svg.download.png": "Download as PNG","artifacts.svg.download.svg": "Download as SVG",+ "document.saveConflict": "This document was updated elsewhere. Refreshing to the latest version.","document.todos.allCompleted": "All tasks completed","document.todos.title": "Tasks","emptyArtifactList": "No Artifacts yet. Use Skills in the conversation, then come back here.",diff --git a/locales/zh-CN/portal.json b/locales/zh-CN/portal.jsonindex ecd61bd2e97..d5a469868f0 100644--- a/locales/zh-CN/portal.json+++ b/locales/zh-CN/portal.json@@ -30,6 +30,7 @@"artifacts.svg.copySuccess": "图片复制成功","artifacts.svg.download.png": "下载为 PNG","artifacts.svg.download.svg": "下载为 SVG",+ "document.saveConflict": "文档已在别处更新,正在刷新为最新版本","document.todos.allCompleted": "所有任务已完成","document.todos.title": "任务","emptyArtifactList": "当前 Artifacts 列表为空,请在会话中按需使用技能后再查看",diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex de1305ec54a..abe97e7f9a6 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -172,13 +172,14 @@ export interface AgentDocumentsRuntimeOptions {documentId: string;}) => MaybePromise<string | undefined>;/**- * Fired after a document-mutating tool call finishes (create / remove /- * rename / copy) so the host can invalidate client-side caches. This is the- * only refresh signal for the server-runtime path — where the tool executes- * on the gateway and the client service layer (which normally invalidates)- * never runs. Invoked from the executor's `onAfterCall` lifecycle hook.+ * Fired after a document-mutating tool call finishes so the host can+ * invalidate client-side caches. This is the only refresh signal for the+ * server-runtime path — where the tool executes on the gateway and the+ * client service layer (which normally invalidates) never runs. Invoked from+ * the executor's `onAfterCall` lifecycle hook. `documentId` is set only when+ * the call wrote the body or metadata of an existing `documents` row.*/- onDocumentsMutated?: () => MaybePromise<void>;+ onDocumentsMutated?: (params: { documentId?: string }) => MaybePromise<void>;}export class AgentDocumentsExecutionRuntime {@@ -194,8 +195,8 @@ export class AgentDocumentsExecutionRuntime {* mutation ran client- or server-side — covering the server-runtime path the* inline client service invalidation can't reach.*/- notifyMutated(): Promise<void> {- return Promise.resolve(this.options.onDocumentsMutated?.());+ notifyMutated(params: { documentId?: string } = {}): Promise<void> {+ return Promise.resolve(this.options.onDocumentsMutated?.(params));}private resolveAgentId(context?: AgentDocumentOperationContext) {diff --git a/packages/builtin-tool-agent-documents/src/executor/index.test.ts b/packages/builtin-tool-agent-documents/src/executor/index.test.tsindex 0201c463afb..91faeeec22b 100644--- a/packages/builtin-tool-agent-documents/src/executor/index.test.ts+++ b/packages/builtin-tool-agent-documents/src/executor/index.test.ts@@ -5,7 +5,7 @@ import { AgentDocumentsExecutionRuntime } from '../ExecutionRuntime';import { AgentDocumentsApiName } from '../types';import { AgentDocumentsExecutor } from './index';-const makeExecutor = (onDocumentsMutated: () => void) => {+const makeExecutor = (onDocumentsMutated: (params: { documentId?: string }) => void) => {// onAfterCall only reaches runtime.notifyMutated → options.onDocumentsMutated,// so the service methods are never touched here.const runtime = new AgentDocumentsExecutionRuntime({} as never, { onDocumentsMutated });@@ -28,7 +28,7 @@ describe('AgentDocumentsExecutor.onAfterCall', () => {await executor.onAfterCall(ctx(AgentDocumentsApiName.createDocument, true));- expect(onDocumentsMutated).toHaveBeenCalledTimes(1);+ expect(onDocumentsMutated).toHaveBeenCalledWith({ documentId: undefined });});it.each([@@ -44,6 +44,42 @@ describe('AgentDocumentsExecutor.onAfterCall', () => {expect(onDocumentsMutated).toHaveBeenCalledTimes(1);});+ it.each([+ AgentDocumentsApiName.replaceDocumentContent,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.renameDocument,+ ])('passes the written documentId for %s so the open editor revalidates', async (apiName) => {+ const onDocumentsMutated = vi.fn();+ const executor = makeExecutor(onDocumentsMutated);++ await executor.onAfterCall({+ ...ctx(apiName, true),+ result: { state: { documentId: 'doc-1' }, success: true },+ });++ expect(onDocumentsMutated).toHaveBeenCalledTimes(1);+ expect(onDocumentsMutated).toHaveBeenCalledWith({ documentId: 'doc-1' });+ });++ it.each([+ AgentDocumentsApiName.removeDocument,+ AgentDocumentsApiName.copyDocument,+ AgentDocumentsApiName.createDocument,+ ])(+ 'drops the documentId for %s so a deleted or unopened row is never revalidated',+ async (apiName) => {+ const onDocumentsMutated = vi.fn();+ const executor = makeExecutor(onDocumentsMutated);++ await executor.onAfterCall({+ ...ctx(apiName, true),+ result: { state: { documentId: 'doc-1' }, success: true },+ });++ expect(onDocumentsMutated).toHaveBeenCalledWith({ documentId: undefined });+ },+ );+it('skips notification when the call failed', async () => {const onDocumentsMutated = vi.fn();const executor = makeExecutor(onDocumentsMutated);@@ -53,10 +89,14 @@ describe('AgentDocumentsExecutor.onAfterCall', () => {expect(onDocumentsMutated).not.toHaveBeenCalled();});- it('skips notification for read-only / content-only calls that leave the list unchanged', async () => {+ it('skips notification for read-only calls and content writes without a documentId', async () => {const onDocumentsMutated = vi.fn();const executor = makeExecutor(onDocumentsMutated);+ await executor.onAfterCall({+ ...ctx(AgentDocumentsApiName.readDocument, true),+ result: { state: { documentId: 'doc-1' }, success: true },+ });await executor.onAfterCall(ctx(AgentDocumentsApiName.listDocuments, true));await executor.onAfterCall(ctx(AgentDocumentsApiName.replaceDocumentContent, true));diff --git a/packages/builtin-tool-agent-documents/src/executor/index.ts b/packages/builtin-tool-agent-documents/src/executor/index.tsindex f693c1c6fa0..87da941f7cd 100644--- a/packages/builtin-tool-agent-documents/src/executor/index.ts+++ b/packages/builtin-tool-agent-documents/src/executor/index.ts@@ -21,9 +21,7 @@ import {} from '../types';// APIs that change the document set the client list renders (membership or-// visible title). Content-only edits (replaceDocumentContent / modifyNodes) and-// read-only calls are excluded — they don't alter the list. Used by-// `onAfterCall` to decide when to refresh the client-side documents list.+// visible title). Read-only calls are excluded — they don't alter the list.const LIST_MUTATING_APIS = new Set<string>([AgentDocumentsApiName.createDocument,AgentDocumentsApiName.removeDocument,@@ -31,6 +29,15 @@ const LIST_MUTATING_APIS = new Set<string>([AgentDocumentsApiName.copyDocument,]);+// APIs that write the body or metadata of an existing `documents` row, so an+// editor holding that row must revalidate. Create / copy produce rows nobody+// has open yet and remove must not revalidate a deleted id.+const DOCUMENT_WRITING_APIS = new Set<string>([+ AgentDocumentsApiName.replaceDocumentContent,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.renameDocument,+]);+export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsApiName> {readonly identifier = AgentDocumentsIdentifier;protected readonly apiEnum = AgentDocumentsApiName;@@ -47,8 +54,16 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp// server-runtime path never touches the client store otherwise, so a created// doc wouldn't appear until a manual refresh.onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {- if (!LIST_MUTATING_APIS.has(apiName) || !result.success) return;- await this.runtime.notifyMutated();+ if (!result.success) return;++ const state = result.state as { documentId?: unknown } | undefined;+ const documentId =+ DOCUMENT_WRITING_APIS.has(apiName) && typeof state?.documentId === 'string'+ ? state.documentId+ : undefined;++ if (!documentId && !LIST_MUTATING_APIS.has(apiName)) return;+ await this.runtime.notifyMutated({ documentId });};listDocuments = async (diff --git a/packages/builtin-tool-lobe-agent/src/PlanRuntime/index.ts b/packages/builtin-tool-lobe-agent/src/PlanRuntime/index.tsindex c0e9671af10..0ce3f07aeae 100644--- a/packages/builtin-tool-lobe-agent/src/PlanRuntime/index.ts+++ b/packages/builtin-tool-lobe-agent/src/PlanRuntime/index.ts@@ -43,10 +43,9 @@ export interface PlanRuntimeService {topicId?: string,) => Promise<PlanDocument>;/**- * Silently update the plan document's metadata (used for todos sync).- * Should NOT trigger UI refresh on the client.+ * Update plan metadata (todos sync), forwarding its topic for client cache refresh.*/- updatePlanMetadata: (id: string, metadata: Record<string, any>) => Promise<void>;+ updatePlanMetadata: (id: string, metadata: Record<string, any>, topicId: string) => Promise<void>;}export interface PlanRuntimeContext {@@ -121,7 +120,7 @@ export class PlanExecutionRuntime {try {const plan = await this.service.findPlanByTopic(topicId);if (!plan) return;- await this.service.updatePlanMetadata(plan.id, { ...plan.metadata, todos });+ await this.service.updatePlanMetadata(plan.id, { ...plan.metadata, todos }, topicId);} catch (error) {console.warn('Failed to sync todos to plan:', error);}diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex abcef1aed89..c4476755a99 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -19,6 +19,12 @@ import {selectMediaFileItems,validateMediaUrls,} from '../../media';+import {+ type PlanDocument,+ PlanExecutionRuntime,+ type PlanRuntimeContext,+ type PlanRuntimeService,+} from '../../PlanRuntime';import type {AnalyzeMediaParams,AskUserQuestionArgs,@@ -32,12 +38,6 @@ import type {VentState,} from '../../types';import { LobeAgentApiName, VENT_CATEGORIES, VENT_SEVERITIES } from '../../types';-import {- type PlanDocument,- PlanExecutionRuntime,- type PlanRuntimeContext,- type PlanRuntimeService,-} from '../../PlanRuntime';import { getTodosFromContext } from './planTodoHelper';import { resolveClientMediaPayloadItems } from './resolveMediaUris';@@ -101,8 +101,10 @@ const clientPlanService: PlanRuntimeService = {return normalizePlanDoc(doc);},- updatePlanMetadata: async (id, metadata) => {+ updatePlanMetadata: async (id, metadata, topicId) => {await notebookService.updateDocument({ id, metadata });+ const { invalidateDocumentMutation } = await import('@/services/document/invalidation');+ await invalidateDocumentMutation({ cause: 'notebook', documentId: id, topicId });},};diff --git a/packages/builtin-tool-notebook/src/executor/index.test.ts b/packages/builtin-tool-notebook/src/executor/index.test.tsnew file mode 100644index 00000000000..81c1f64ad48--- /dev/null+++ b/packages/builtin-tool-notebook/src/executor/index.test.ts@@ -0,0 +1,57 @@+import type { ToolAfterCallContext } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { NotebookApiName } from '../types';+import { NotebookExecutor } from './index';++const afterCall = (+ apiName: string,+ result: ToolAfterCallContext['result'],+ topicId = 'topic-1',+): ToolAfterCallContext =>+ ({ apiName, identifier: 'lobe-notebook', params: {}, result, topicId }) as ToolAfterCallContext;++describe('NotebookExecutor.onAfterCall', () => {+ it('passes the updated document id and topic so the host revalidates the open editor', async () => {+ const onDocumentsMutated = vi.fn();+ const executor = new NotebookExecutor({} as never, { onDocumentsMutated });++ await executor.onAfterCall(+ afterCall(NotebookApiName.updateDocument, {+ state: { document: { id: 'doc-1' } },+ success: true,+ }),+ );++ expect(onDocumentsMutated).toHaveBeenCalledWith({ documentId: 'doc-1', topicId: 'topic-1' });+ });++ it.each([NotebookApiName.createDocument, NotebookApiName.deleteDocument])(+ 'revalidates only the topic list for %s',+ async (apiName) => {+ const onDocumentsMutated = vi.fn();+ const executor = new NotebookExecutor({} as never, { onDocumentsMutated });++ await executor.onAfterCall(+ afterCall(apiName, { state: { document: { id: 'doc-1' } }, success: true }),+ );++ expect(onDocumentsMutated).toHaveBeenCalledWith({ topicId: 'topic-1' });+ },+ );++ it('ignores reads and failed writes', async () => {+ const onDocumentsMutated = vi.fn();+ const executor = new NotebookExecutor({} as never, { onDocumentsMutated });++ await executor.onAfterCall(+ afterCall(NotebookApiName.getDocument, {+ state: { document: { id: 'doc-1' } },+ success: true,+ }),+ );+ await executor.onAfterCall(afterCall(NotebookApiName.updateDocument, { success: false }));++ expect(onDocumentsMutated).not.toHaveBeenCalled();+ });+});diff --git a/packages/builtin-tool-notebook/src/executor/index.ts b/packages/builtin-tool-notebook/src/executor/index.tsindex 4833c2c8577..1ffba0a0210 100644--- a/packages/builtin-tool-notebook/src/executor/index.ts+++ b/packages/builtin-tool-notebook/src/executor/index.ts@@ -11,7 +11,12 @@* still resolve on execution. New flows should use* `@lobechat/builtin-tool-agent-documents`.*/-import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';+import {+ BaseExecutor,+ type BuiltinToolContext,+ type BuiltinToolResult,+ type ToolAfterCallContext,+} from '@lobechat/types';import {type CreateDocumentArgs,@@ -45,17 +50,40 @@ export interface NotebookServiceApi {updateDocument: (params: UpdateDocumentParams) => Promise<any>;}+export interface NotebookExecutorOptions {+ onDocumentsMutated?: (params: { documentId?: string; topicId?: string }) => void | Promise<void>;+}+export class NotebookExecutor extends BaseExecutor<typeof NotebookApiName> {readonly identifier = NotebookIdentifier;protected readonly apiEnum = NotebookApiName;private notebookService: NotebookServiceApi;+ private options: NotebookExecutorOptions;- constructor(notebookService: NotebookServiceApi) {+ constructor(notebookService: NotebookServiceApi, options: NotebookExecutorOptions = {}) {super();this.notebookService = notebookService;+ this.options = options;}+ // Fires on `tool_end` for client- and server-run calls alike, so the host can+ // revalidate the topic list and, for an existing row, the open editor.+ onAfterCall = async ({ apiName, result, topicId }: ToolAfterCallContext): Promise<void> => {+ if (!result.success) return;++ if (apiName === NotebookApiName.createDocument || apiName === NotebookApiName.deleteDocument) {+ await this.options.onDocumentsMutated?.({ topicId });+ return;+ }++ if (apiName !== NotebookApiName.updateDocument) return;++ const state = result.state as { document?: { id?: unknown } } | undefined;+ const documentId = typeof state?.document?.id === 'string' ? state.document.id : undefined;+ await this.options.onDocumentsMutated?.({ documentId, topicId });+ };+/*** Create a new document*/diff --git a/packages/builtin-tool-page-agent/src/client/executor/index.test.ts b/packages/builtin-tool-page-agent/src/client/executor/index.test.tsindex d885483bbb9..616b91b0c08 100644--- a/packages/builtin-tool-page-agent/src/client/executor/index.test.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.test.ts@@ -5,6 +5,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { PageAgentIdentifier } from '../../types';import { PageAgentExecutor } from './index';+const { getDocumentStoreState, invalidateDocumentMutation } = vi.hoisted(() => ({+ getDocumentStoreState: vi.fn(),+ invalidateDocumentMutation: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/services/document/invalidation', () => ({ invalidateDocumentMutation }));+vi.mock('@/store/document', () => ({ getDocumentStoreState }));+describe('PageAgentExecutor', () => {let executor: PageAgentExecutor;let mockRuntime: EditorRuntime;@@ -12,8 +20,9 @@ describe('PageAgentExecutor', () => {beforeEach(() => {// Create mock runtime with all methods+ invalidateDocumentMutation.mockClear();+ getDocumentStoreState.mockClear();mockRuntime = {- applyServerSnapshot: vi.fn(),editTitle: vi.fn(),getCurrentDocId: vi.fn(() => 'doc-123'),getDebugSnapshot: vi.fn(() => ({})),@@ -304,8 +313,9 @@ describe('PageAgentExecutor', () => {});describe('onAfterCall', () => {- it('should ignore read-only getPageContent state without a document snapshot', async () => {+ it('ignores read-only getPageContent even though its state carries the documentId', async () => {await executor.onAfterCall({+ apiName: 'getPageContent',result: {state: {documentId: 'doc-123',@@ -317,25 +327,32 @@ describe('PageAgentExecutor', () => {},} as any);- expect(mockRuntime.applyServerSnapshot).not.toHaveBeenCalled();+ expect(invalidateDocumentMutation).not.toHaveBeenCalled();});- it('should apply server snapshots when a mutating tool returns document content', async () => {- await executor.onAfterCall({- result: {- state: {- documentContent: '# Updated',- documentId: 'doc-123',+ it.each(['initPage', 'editTitle', 'modifyNodes', 'replaceText'])(+ 'revalidates the written document after %s instead of pushing the snapshot into the editor',+ async (apiName) => {+ await executor.onAfterCall({+ apiName,+ result: {+ state: { documentContent: '# Updated', documentId: 'doc-123' },+ success: true,},- success: true,- },+ } as any);++ expect(invalidateDocumentMutation).toHaveBeenCalledWith({ documentId: 'doc-123' });+ expect(getDocumentStoreState).not.toHaveBeenCalled();+ },+ );++ it('skips failed calls', async () => {+ await executor.onAfterCall({+ apiName: 'modifyNodes',+ result: { state: { documentId: 'doc-123' }, success: false },} as any);- expect(mockRuntime.applyServerSnapshot).toHaveBeenCalledWith({- content: '# Updated',- editorData: undefined,- title: undefined,- });+ expect(invalidateDocumentMutation).not.toHaveBeenCalled();});});diff --git a/packages/builtin-tool-page-agent/src/client/executor/index.ts b/packages/builtin-tool-page-agent/src/client/executor/index.tsindex 610ccc83b29..9d449efea70 100644--- a/packages/builtin-tool-page-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.ts@@ -42,6 +42,13 @@ const PageAgentApiName = {replaceText: 'replaceText',} as const;+const DOCUMENT_WRITING_APIS = new Set<string>([+ PageAgentApiName.initPage,+ PageAgentApiName.editTitle,+ PageAgentApiName.modifyNodes,+ PageAgentApiName.replaceText,+]);+const summarizeError = (error: unknown) => {if (error instanceof Error) {return {@@ -125,66 +132,23 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {};}- /**- * Apply server-side execution result to the renderer.- *- * The page-agent tool now runs on the server (manifest `executors: ['server']`),- * but the renderer still owns the live Lexical instance and the in-memory- * document store. When the agent stream delivers `tool_end`, the gateway- * event handler routes here so we can:- * 1. Push the new `editorData`/`title` into the mounted editor via- * `EditorRuntime.applyServerSnapshot` (which skips the auto-save loop).- * 2. Mark `useDocumentStore` clean and update `lastSaved*` so the renderer- * does not re-save what the server just wrote.- *- * If the editor for this `documentId` is not currently mounted (e.g. user- * navigated away), we skip — next open will hydrate from the row directly.- */- onAfterCall = async ({ result }: ToolAfterCallContext): Promise<void> => {- if (!result.success) return;-- const state = result.state as- | {- documentContent?: unknown;- documentEditorData?: unknown;- documentId?: unknown;- documentTitle?: unknown;- }- | undefined- | null;- if (!state || typeof state !== 'object') return;-- const documentId = typeof state.documentId === 'string' ? state.documentId : undefined;- if (!documentId) return;+ // The page-agent tool runs on the server, so the renderer learns about the+ // write from `tool_end`. Revalidating the editor SWR key routes the server row+ // through DocumentStore.reconcileRemote, which is the single place that+ // decides whether the mounted editor adopts it; pushing the snapshot into the+ // editor here would hydrate twice and mark the store dirty in between.+ onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {+ if (!result.success || !DOCUMENT_WRITING_APIS.has(apiName)) return;- const content = typeof state.documentContent === 'string' ? state.documentContent : undefined;- const title = typeof state.documentTitle === 'string' ? state.documentTitle : undefined;- const editorData =- state.documentEditorData && typeof state.documentEditorData === 'object'- ? (state.documentEditorData as Record<string, unknown>)- : undefined;- const hasDocumentSnapshot =- typeof content === 'string' || typeof title === 'string' || !!editorData;-- if (!hasDocumentSnapshot) return;-- // Only push into the live editor when this runtime is bound to the same- // document the server just wrote. Otherwise the snapshot would overwrite- // a different page's editor — store-level sync still runs below.- if (this.runtime.isReady() && this.runtime.getCurrentDocId() === documentId) {- this.runtime.applyServerSnapshot({ content, editorData, title });- }+ const state = result.state as { documentId?: unknown } | undefined | null;+ const documentId = typeof state?.documentId === 'string' ? state.documentId : undefined;+ if (!documentId) return;- // Always reconcile the document store: even if the editor isn't mounted,- // the row was written and any cached projection should match.- // Dynamic import keeps the renderer-only store graph (zustand + tRPC- // client) out of this package's static import tree so server-side- // unit tests of `executor/server.ts` don't have to load it.try {- const { getDocumentStoreState } = await import('@/store/document');- getDocumentStoreState().applyServerSnapshot(documentId, { content, editorData, title });+ const { invalidateDocumentMutation } = await import('@/services/document/invalidation');+ await invalidateDocumentMutation({ documentId });} catch (error) {- log('[PageAgentExecutor] applyServerSnapshot store sync failed', error);+ log('[PageAgentExecutor] document revalidation failed', error);}};diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsindex e9a828ab616..d886e81934b 100644--- a/packages/database/src/models/__tests__/document.test.ts+++ b/packages/database/src/models/__tests__/document.test.ts@@ -531,6 +531,70 @@ describe('DocumentModel', () => {expect(unchanged?.content).toBe('Original content');});++ it('should return the committed updatedAt', async () => {+ const { documentId } = await createTestDocument(documentModel, fileModel, 'Original content');++ const updatedAt = await documentModel.update(documentId, { content: 'Updated content' });++ const found = await documentModel.findById(documentId);+ expect(updatedAt).toEqual(found?.updatedAt);+ });++ it('advances the version for concurrent writes even when callers send the same old timestamp', async () => {+ const { documentId } = await createTestDocument(documentModel, fileModel, 'Original content');+ const original = (await documentModel.findById(documentId))!;+ const versions = await Promise.all(+ Array.from({ length: 4 }, (_, index) =>+ documentModel.update(documentId, {+ content: `Write ${index}`,+ updatedAt: original.updatedAt,+ }),+ ),+ );+ const timestamps = versions.map((version) => version!.getTime()).sort((a, b) => a - b);+ expect(new Set(timestamps).size).toBe(4);+ expect(timestamps[0]).toBeGreaterThan(original.updatedAt.getTime());+ expect((await documentModel.findById(documentId))?.updatedAt.getTime()).toBe(timestamps[3]);+ });++ it('advances updatedAt from the database clock when the update omits it', async () => {+ const { documentId } = await createTestDocument(documentModel, fileModel, 'Original content');+ const original = (await documentModel.findById(documentId))!;++ await serverDB+ .update(documents)+ .set({ title: 'Renamed' })+ .where(eq(documents.id, documentId));++ const next = await documentModel.findById(documentId);+ expect(next?.title).toBe('Renamed');+ expect(next!.updatedAt.getTime()).toBeGreaterThan(original.updatedAt.getTime());+ });++ it('ignores a caller-supplied updatedAt and stores a newer database version', async () => {+ const { documentId } = await createTestDocument(documentModel, fileModel, 'Original content');+ const original = (await documentModel.findById(documentId))!;+ const supplied = new Date('2020-01-01T00:00:00.000Z');++ const updatedAt = await documentModel.update(documentId, {+ content: 'Updated content',+ updatedAt: supplied,+ });++ expect(updatedAt).toBeInstanceOf(Date);+ expect(updatedAt!.getTime()).toBeGreaterThan(original.updatedAt.getTime());+ expect(updatedAt!.getTime()).not.toBe(supplied.getTime());+ expect((await documentModel.findById(documentId))?.updatedAt).toEqual(updatedAt);+ });++ it('should return undefined when the row does not belong to the caller', async () => {+ const { documentId } = await createTestDocument(documentModel, fileModel, 'Original content');++ const updatedAt = await documentModel2.update(documentId, { content: 'Hacked content' });++ expect(updatedAt).toBeUndefined();+ });});describe('findBySlug', () => {@@ -672,6 +736,7 @@ describe('DocumentModel', () => {const { id: firstId } = await documentModel.create({content: 'First document',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),fileId: file.id,fileType: 'text/plain',source: file.url,@@ -682,6 +747,7 @@ describe('DocumentModel', () => {await documentModel.create({content: 'Second document',+ createdAt: new Date('2026-01-01T00:00:01.000Z'),fileId: file.id,fileType: 'text/plain',source: file.url,diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex 71dd2a365d1..09495156aea 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -579,7 +579,6 @@ export class AgentDocumentModel {title: params.title,totalCharCount: stats.totalCharCount,totalLineCount: stats.totalLineCount,- updatedAt,}).where(and(eq(documents.id, existing.documentId), this.documentOwnership()));diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex 65673d86eac..1f6e8370123 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -16,6 +16,7 @@ import {documents,files,knowledgeBaseFiles,+ nextDocumentUpdatedAt,works,} from '../schemas';import type { LobeChatDatabase } from '../type';@@ -343,16 +344,19 @@ export class DocumentModel {// visibility is intentionally not updatable via this path. The only legal// transition is `private → public` via `publishToWorkspace`; strip any// incoming value so callers can't sneak around the one-way rule.- const { metadata, visibility: _ignored, ...patch } = value;+ const { metadata, updatedAt: _updatedAt, visibility: _ignored, ...patch } = value;- return this.db+ const [row] = await this.db.update(documents).set({...patch,...(metadata !== undefined && { metadata: this.scopeMetadata(metadata) }),- updatedAt: new Date(),+ updatedAt: nextDocumentUpdatedAt(),})- .where(and(this.readScope(), eq(documents.id, id)));+ .where(and(this.readScope(), eq(documents.id, id)))+ .returning({ updatedAt: documents.updatedAt });++ return row?.updatedAt;};/**@@ -377,7 +381,7 @@ export class DocumentModel {return this.db.transaction(async (trx) => {const result = await (trx as LobeChatDatabase).update(documents)- .set({ updatedAt: new Date(), visibility })+ .set({ visibility }).where(and(eq(documents.id, rootId), this.ownership(), eq(documents.userId, this.userId))).returning({ fileId: documents.fileId, id: documents.id });@@ -609,7 +613,7 @@ export class DocumentModel {await (trx as LobeChatDatabase).update(documents)- .set({ ...ownershipUpdate, ...visibilityUpdate, updatedAt: new Date() })+ .set({ ...ownershipUpdate, ...visibilityUpdate }).where(inArray(documents.id, ids));if (targetWorkspaceId) {diff --git a/packages/database/src/models/knowledgeBase.ts b/packages/database/src/models/knowledgeBase.tsindex 04f59be682d..3204f24f68d 100644--- a/packages/database/src/models/knowledgeBase.ts+++ b/packages/database/src/models/knowledgeBase.ts@@ -112,7 +112,7 @@ export class KnowledgeBaseModel {await this.db.update(documents)- .set({ updatedAt: now, visibility: kb.visibility })+ .set({ visibility: kb.visibility }).where(and(documentLink,@@ -359,7 +359,7 @@ export class KnowledgeBaseModel {await trx.update(documents)- .set({ updatedAt: now, visibility })+ .set({ visibility }).where(and(documentLink,@@ -499,7 +499,7 @@ export class KnowledgeBaseModel {await trx.update(documents)- .set({ ...ownershipUpdate, ...visibilityUpdate, updatedAt: now })+ .set({ ...ownershipUpdate, ...visibilityUpdate }).where(documentWhere);return { id };diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.tsindex 7ca3d289315..b93172d60f0 100644--- a/packages/database/src/schemas/file.ts+++ b/packages/database/src/schemas/file.ts@@ -31,6 +31,9 @@ import { asyncTasks } from './asyncTask';import { users } from './user';import { workspaces } from './workspace';+export const nextDocumentUpdatedAt = () =>+ sql`GREATEST(date_trunc('milliseconds', clock_timestamp()), "documents"."updated_at" + interval '1 millisecond')`;+export const DOCUMENT_FOLDER_TYPE = 'custom/folder';/** File type used by the parent document for a managed skill bundle. */@@ -150,6 +153,10 @@ export const documents = pgTable(/** Recycle bin — see `schemas/trash.ts`. */...softDeleteColumns(),...timestamps,+ updatedAt: timestamptz('updated_at')+ .notNull()+ .defaultNow()+ .$onUpdate(() => nextDocumentUpdatedAt()),},(table) => [index('documents_source_idx').on(table.source),diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex e3386bcdded..2d8e9386528 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -187,55 +187,6 @@ export class EditorRuntime {}}- /**- * Apply a snapshot produced by the server-side PageAgent execution runtime- * onto the currently mounted editor. Skips persistence side-effects: the- * server already wrote the row, so calling `afterMutateHandler` here would- * loop the save path back through `commitEditorMutation`.- *- * `editorData` is the Lexical `SerializedEditorState` (or `null`/`undefined`- * when the server only changed metadata such as the title).- */- applyServerSnapshot(snapshot: {- content?: string;- editorData?: Record<string, unknown> | null;- title?: string;- }): boolean {- let applied = false;-- if (this.editor && snapshot.editorData) {- try {- this.editor.setDocument('json', JSON.stringify(snapshot.editorData), { keepId: true });- applied = true;- } catch (error) {- log('[EditorRuntime] applyServerSnapshot:editorData failed', error);- }- } else if (this.editor && typeof snapshot.content === 'string') {- try {- this.editor.setDocument('markdown', snapshot.content, { keepId: true });- applied = true;- } catch (error) {- log('[EditorRuntime] applyServerSnapshot:markdown failed', error);- }- }-- if (typeof snapshot.title === 'string' && this.titleSetter) {- try {- this.titleSetter(snapshot.title);- applied = true;- } catch (error) {- log('[EditorRuntime] applyServerSnapshot:title failed', error);- }- }-- log('[EditorRuntime] applyServerSnapshot', {- applied,- hasEditorData: !!snapshot.editorData,- hasTitle: typeof snapshot.title === 'string',- });- return applied;- }-/*** Get the current editor instance*/diff --git a/packages/locales/src/default/portal.ts b/packages/locales/src/default/portal.tsindex b57efabf2b2..f8e017db1a2 100644--- a/packages/locales/src/default/portal.ts+++ b/packages/locales/src/default/portal.ts@@ -38,6 +38,7 @@ export default {'artifacts.svg.copySuccess': 'Image copied successfully','artifacts.svg.download.png': 'Download as PNG','artifacts.svg.download.svg': 'Download as SVG',+ 'document.saveConflict': 'This document was updated elsewhere. Refreshing to the latest version.','document.todos.allCompleted': 'All tasks completed','document.todos.title': 'Tasks','emptyArtifactList': 'No Artifacts yet. Use Skills in the conversation, then come back here.',diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsxindex ca3b6e90988..7c05ee7d4b3 100644--- a/src/features/Portal/Document/Body.test.tsx+++ b/src/features/Portal/Document/Body.test.tsx@@ -261,7 +261,7 @@ describe('DocumentBody', () => {expect(screen.queryByTestId('highlight-editor')).toBeNull();});- it('autosaves highlight editor edits after the debounce window', () => {+ it('autosaves highlight editor edits after the debounce window', async () => {mockDocumentMeta.current = { content: 'before', filename: 'config.json' };render(<DocumentBody />);@@ -270,8 +270,8 @@ describe('DocumentBody', () => {fireEvent.change(editor, { target: { value: 'after' } });expect(mockUpdateDocument).not.toHaveBeenCalled();- act(() => {- vi.advanceTimersByTime(5000);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);});expect(mockUpdateDocument).toHaveBeenCalledWith({@@ -290,8 +290,9 @@ describe('DocumentBody', () => {fireEvent.change(editor, { target: { value: 'after' } });expect(mockUpdateDocument).not.toHaveBeenCalled();- unmount();- await Promise.resolve();+ await act(async () => {+ unmount();+ });expect(mockUpdateDocument).toHaveBeenCalledWith({content: 'after',@@ -305,8 +306,9 @@ describe('DocumentBody', () => {const { unmount } = render(<DocumentBody />);- unmount();- await Promise.resolve();+ await act(async () => {+ unmount();+ });expect(mockUpdateDocument).not.toHaveBeenCalled();});diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex daa44ed2770..406c71f1d68 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -1,13 +1,11 @@'use client';-import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';import { Flexbox, TextArea } from '@lobehub/ui';import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { debounce } from 'es-toolkit/compat';import { CheckIcon, PencilIcon, XIcon } from 'lucide-react';import type { ChangeEvent } from 'react';-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';@@ -37,6 +35,7 @@ import {} from './documentViewContext';import EditorCanvas from './EditorCanvas';import TodoList from './TodoList';+import { useHighlightSave } from './useHighlightSave';const styles = createStaticStyles(({ css }) => ({content: css`@@ -218,107 +217,30 @@ interface HighlightEditorProps {content: string;documentId: string;filename: string;- onSaved: (newContent: string) => void;+ onSaved: (newContent: string, updatedAt?: string) => void;+ updatedAt?: Date;}-const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, filename, onSaved }) => {- const [buffer, setBuffer] = useState<string | undefined>(undefined);- const editingValue = buffer ?? content;+const HighlightEditor = memo<HighlightEditorProps>(+ ({ content, documentId, filename, onSaved, updatedAt }) => {+ const { editingValue, handleChange, handleSave } = useHighlightSave({+ content,+ documentId,+ onSaved,+ updatedAt,+ });- const bufferRef = useRef(buffer);- const documentIdRef = useRef(documentId);- const onSavedRef = useRef(onSaved);- bufferRef.current = buffer;- documentIdRef.current = documentId;- onSavedRef.current = onSaved;-- const writeBuffer = useCallback(async (source: 'manual' | 'autosave') => {- const toWrite = bufferRef.current;- if (toWrite === undefined) return;- try {- await documentService.updateDocument({- content: toWrite,- id: documentIdRef.current,- saveSource: source,- });- // Update SWR cache before clearing the buffer so the editor's value prop- // never falls back to stale content, which would otherwise reset the cursor.- onSavedRef.current(toWrite);- if (bufferRef.current === toWrite) setBuffer(undefined);- } catch (error) {- console.error('[HighlightEditor] save failed:', error);- }- }, []);-- const debouncedAutoSave = useMemo(- () =>- debounce(() => writeBuffer('autosave'), EDITOR_DEBOUNCE_TIME, {- leading: false,- maxWait: EDITOR_MAX_WAIT,- trailing: true,- }),- [writeBuffer],- );-- const handleChange = useCallback(- (next: string) => {- const isDirty = next !== content;- setBuffer(isDirty ? next : undefined);- if (isDirty) debouncedAutoSave();- else debouncedAutoSave.cancel();- },- [content, debouncedAutoSave],- );-- const handleSave = useCallback(async () => {- debouncedAutoSave.cancel();- await writeBuffer('manual');- }, [debouncedAutoSave, writeBuffer]);-- const isMountedRef = useRef(false);-- useEffect(() => {- isMountedRef.current = true;- return () => {- isMountedRef.current = false;- debouncedAutoSave.cancel();- const pendingContent = bufferRef.current;- if (pendingContent === undefined) return;- const pendingDocumentId = documentIdRef.current;- // Defer the fire-and-forget save to a microtask so that StrictMode's synchronous- // unmount/remount in development does not trigger a save. If the component is- // immediately remounted, isMountedRef flips back to true before this runs.- queueMicrotask(() => {- if (isMountedRef.current) return;- void documentService.updateDocument({- content: pendingContent,- id: pendingDocumentId,- saveSource: 'autosave',- });- });- };- }, [debouncedAutoSave]);-- useEffect(() => {- const handler = (event: BeforeUnloadEvent) => {- if (bufferRef.current === undefined) return;- event.preventDefault();- event.returnValue = '';- };- window.addEventListener('beforeunload', handler);- return () => window.removeEventListener('beforeunload', handler);- }, []);-- return (- <CodeEditorPane- showStatusBar- filePath={filename}- value={editingValue}- onChange={handleChange}- onSave={handleSave}- />- );-});+ return (+ <CodeEditorPane+ showStatusBar+ filePath={filename}+ value={editingValue}+ onChange={handleChange}+ onSave={handleSave}+ />+ );+ },+);HighlightEditor.displayName = 'HighlightEditor';@@ -356,10 +278,14 @@ const DocumentBody = memo(() => {: { mode: 'editor' as const };const handleHighlightSaved = useCallback(- (saved: string) => {- mutateDocumentMeta((prev) => (prev ? { ...prev, content: saved } : prev), {- revalidate: false,- });+ (saved: string, updatedAt?: string) => {+ mutateDocumentMeta(+ (prev) =>+ prev+ ? { ...prev, content: saved, ...(updatedAt ? { updatedAt: new Date(updatedAt) } : {}) }+ : prev,+ { revalidate: false },+ );},[mutateDocumentMeta],);@@ -377,6 +303,7 @@ const DocumentBody = memo(() => {documentId={documentId}filename={documentMeta?.filename ?? ''}key={documentId}+ updatedAt={documentMeta?.updatedAt}onSaved={handleHighlightSaved}/>) : (diff --git a/src/features/Portal/Document/useHighlightSave.test.ts b/src/features/Portal/Document/useHighlightSave.test.tsnew file mode 100644index 00000000000..fbe5dff8475--- /dev/null+++ b/src/features/Portal/Document/useHighlightSave.test.ts@@ -0,0 +1,282 @@+import { toast } from '@lobehub/ui/base-ui';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { portalKeys } from '@/libs/swr/keys';++import { useHighlightSave } from './useHighlightSave';++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ ...(await import('~base-ui-stubs')).baseUiStubs,+}));++const mockUpdateDocument = vi.hoisted(() => vi.fn());++vi.mock('@/services/document', () => ({+ documentService: { updateDocument: mockUpdateDocument },+}));++const mockInvalidateDocumentMutation = vi.hoisted(() => vi.fn());++vi.mock('@/services/document/invalidation', () => ({+ invalidateDocumentMutation: mockInvalidateDocumentMutation,+}));++const mockMutate = vi.hoisted(() => vi.fn());++vi.mock('@/libs/swr', () => ({+ mutate: mockMutate,+}));++describe('useHighlightSave', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('forwards expectedUpdatedAt from the row it rendered from', async () => {+ const updatedAt = new Date('2024-01-01T00:00:00.000Z');+ mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-02T00:00:00.000Z' });+ const onSaved = vi.fn();++ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());++ expect(mockUpdateDocument).toHaveBeenCalledWith({+ content: 'after',+ expectedUpdatedAt: updatedAt,+ id: 'doc-1',+ saveSource: 'manual',+ });+ expect(onSaved).toHaveBeenCalledWith('after', '2024-01-02T00:00:00.000Z');+ });++ it('omits expectedUpdatedAt when the row has no known version yet', async () => {+ mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-02T00:00:00.000Z' });+ const onSaved = vi.fn();++ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt: undefined }),+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());++ expect(mockUpdateDocument).toHaveBeenCalledWith({+ content: 'after',+ id: 'doc-1',+ saveSource: 'manual',+ });+ });++ it('pins the next save to the version the previous save committed before the prop catches up', async () => {+ const updatedAt = new Date('2024-01-01T00:00:00.000Z');+ mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-02T00:00:00.000Z' });+ const onSaved = vi.fn();++ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());+ act(() => result.current.handleChange('after again'));+ await act(() => result.current.handleSave());++ expect(mockUpdateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: 'after again',+ expectedUpdatedAt: new Date('2024-01-02T00:00:00.000Z'),+ }),+ );+ });++ it('follows a new updatedAt prop after a save', async () => {+ mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-02T00:00:00.000Z' });+ const onSaved = vi.fn();++ const { result, rerender } = renderHook(+ ({ updatedAt }: { updatedAt: Date }) =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),+ { initialProps: { updatedAt: new Date('2024-01-01T00:00:00.000Z') } },+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());+ rerender({ updatedAt: new Date('2024-01-03T00:00:00.000Z') });+ act(() => result.current.handleChange('after again'));+ await act(() => result.current.handleSave());++ expect(mockUpdateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({ expectedUpdatedAt: new Date('2024-01-03T00:00:00.000Z') }),+ );+ });++ it('invalidates the document caches and toasts on CONFLICT', async () => {+ const updatedAt = new Date('2024-01-01T00:00:00.000Z');+ mockUpdateDocument.mockRejectedValue({ data: { code: 'CONFLICT' } });+ const onSaved = vi.fn();++ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaved, updatedAt }),+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());++ expect(mockInvalidateDocumentMutation).toHaveBeenCalledWith({ documentId: 'doc-1' });+ expect(mockMutate).toHaveBeenCalledWith(portalKeys.documentHeader('doc-1'));+ expect(toast.error).toHaveBeenCalled();+ expect(onSaved).not.toHaveBeenCalled();+ expect(result.current.editingValue).toBe('before');+ });+ it('adopts a refreshed remote body instead of submitting the old draft with its version', async () => {+ const onSaved = vi.fn();+ const { result, rerender } = renderHook(+ (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaved }),+ { initialProps: { content: 'base', updatedAt: new Date('2024-01-01') } },+ );+ act(() => result.current.handleChange('local draft'));+ rerender({ content: 'remote body', updatedAt: new Date('2024-01-02') });+ await act(() => result.current.handleSave());+ expect(result.current.editingValue).toBe('remote body');+ expect(mockUpdateDocument).not.toHaveBeenCalled();+ });++ it('keeps the draft after a metadata-only remote refresh', async () => {+ const { result, rerender } = renderHook(+ (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaved: vi.fn() }),+ { initialProps: { content: 'base', updatedAt: new Date('2024-01-01') } },+ );+ act(() => result.current.handleChange('local draft'));+ rerender({ content: 'base', updatedAt: new Date('2024-01-02') });+ await act(() => result.current.handleSave());+ expect(mockUpdateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: 'local draft',+ expectedUpdatedAt: new Date('2024-01-02'),+ }),+ );+ });++ it('serializes overlapping saves and preserves the newest edit', async () => {+ let resolveFirst!: (value: { updatedAt: string }) => void;+ mockUpdateDocument.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ );+ mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-03T00:00:00.000Z' });+ const { result } = renderHook(() =>+ useHighlightSave({+ content: 'base',+ documentId: 'doc-1',+ onSaved: vi.fn(),+ updatedAt: new Date('2024-01-01'),+ }),+ );+ act(() => result.current.handleChange('first'));+ let first!: Promise<void>;+ act(() => {+ first = result.current.handleSave();+ });+ await act(async () => {+ await Promise.resolve();+ });+ act(() => result.current.handleChange('second'));+ let second!: Promise<void>;+ act(() => {+ second = result.current.handleSave();+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(mockUpdateDocument).toHaveBeenCalledTimes(1);+ await act(async () => {+ resolveFirst({ updatedAt: '2024-01-02T00:00:00.000Z' });+ await Promise.all([first, second]);+ });+ expect(mockUpdateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: 'second',+ expectedUpdatedAt: new Date('2024-01-02'),+ }),+ );+ expect(toast.error).not.toHaveBeenCalled();+ });+ it('flushes the latest draft on unmount after an in-flight save', async () => {+ let resolveFirst!: (value: { updatedAt: string }) => void;+ mockUpdateDocument.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ );+ mockUpdateDocument.mockResolvedValue({ updatedAt: '2024-01-03T00:00:00.000Z' });+ const { result, unmount } = renderHook(() =>+ useHighlightSave({+ content: 'base',+ documentId: 'doc-1',+ onSaved: vi.fn(),+ updatedAt: new Date('2024-01-01'),+ }),+ );+ act(() => result.current.handleChange('first'));+ let first!: Promise<void>;+ act(() => {+ first = result.current.handleSave();+ });+ await act(async () => {+ await Promise.resolve();+ });+ act(() => result.current.handleChange('second'));+ unmount();+ await act(async () => {+ await Promise.resolve();+ resolveFirst({ updatedAt: '2024-01-02T00:00:00.000Z' });+ await first;+ await Promise.resolve();+ });+ expect(mockUpdateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: 'second',+ expectedUpdatedAt: new Date('2024-01-02'),+ }),+ );+ });++ it('ignores an old conflict after a newer remote row was adopted and edited', async () => {+ let rejectFirst!: (error: unknown) => void;+ mockUpdateDocument.mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ rejectFirst = reject;+ }),+ );+ const { result, rerender } = renderHook(+ (props) => useHighlightSave({ ...props, documentId: 'doc-1', onSaved: vi.fn() }),+ { initialProps: { content: 'base', updatedAt: new Date('2024-01-01') } },+ );+ act(() => result.current.handleChange('old draft'));+ let first!: Promise<void>;+ act(() => {+ first = result.current.handleSave();+ });+ await act(async () => {+ await Promise.resolve();+ });+ rerender({ content: 'remote', updatedAt: new Date('2024-01-02') });+ act(() => result.current.handleChange('new remote draft'));+ await act(async () => {+ rejectFirst({ data: { code: 'CONFLICT' } });+ await first;+ });+ expect(result.current.editingValue).toBe('new remote draft');+ expect(toast.error).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Portal/Document/useHighlightSave.ts b/src/features/Portal/Document/useHighlightSave.tsnew file mode 100644index 00000000000..48b9bf7778e--- /dev/null+++ b/src/features/Portal/Document/useHighlightSave.ts@@ -0,0 +1,166 @@+'use client';++import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';+import { toast } from '@lobehub/ui/base-ui';+import { debounce } from 'es-toolkit/compat';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { mutate } from '@/libs/swr';+import { portalKeys } from '@/libs/swr/keys';+import { documentService } from '@/services/document';+import { invalidateDocumentMutation } from '@/services/document/invalidation';++const isConflictError = (error: unknown) =>+ (error as { data?: { code?: string } })?.data?.code === 'CONFLICT';++export interface UseHighlightSaveParams {+ content: string;+ documentId: string;+ onSaved: (content: string, updatedAt?: string) => void;+ updatedAt?: Date;+}++export interface UseHighlightSaveResult {+ editingValue: string;+ handleChange: (next: string) => void;+ handleSave: () => Promise<void>;+}++export const useHighlightSave = ({+ content,+ documentId,+ onSaved,+ updatedAt,+}: UseHighlightSaveParams): UseHighlightSaveResult => {+ const { t } = useTranslation('portal');+ const [buffer, setBuffer] = useState<string | undefined>(undefined);+ const editingValue = buffer ?? content;++ const bufferRef = useRef(buffer);+ const documentIdRef = useRef(documentId);+ const onSavedRef = useRef(onSaved);+ const expectedUpdatedAtRef = useRef(updatedAt);+ const baseContentRef = useRef(content);+ const pendingSaveRef = useRef<Promise<void> | undefined>(undefined);+ const tRef = useRef(t);+ bufferRef.current = buffer;+ documentIdRef.current = documentId;+ onSavedRef.current = onSaved;+ tRef.current = t;++ const saveBuffer = useCallback(async (source: 'manual' | 'autosave') => {+ const toWrite = bufferRef.current;+ if (toWrite === undefined) return;+ const expectedUpdatedAt = expectedUpdatedAtRef.current;+ try {+ const result = await documentService.updateDocument({+ content: toWrite,+ id: documentIdRef.current,+ saveSource: source,+ ...(expectedUpdatedAt ? { expectedUpdatedAt } : {}),+ });+ if (result?.updatedAt) {+ const savedAt = new Date(result.updatedAt);+ if (expectedUpdatedAtRef.current && savedAt < expectedUpdatedAtRef.current) return;+ expectedUpdatedAtRef.current = savedAt;+ }+ baseContentRef.current = toWrite;+ onSavedRef.current(toWrite, result?.updatedAt);+ if (bufferRef.current === toWrite) {+ bufferRef.current = undefined;+ setBuffer(undefined);+ }+ } catch (error) {+ if (isConflictError(error)) {+ // A newer remote row already reconciled this request's base.+ if (expectedUpdatedAtRef.current?.getTime() !== expectedUpdatedAt?.getTime()) return;+ bufferRef.current = undefined;+ setBuffer(undefined);+ await Promise.allSettled([+ invalidateDocumentMutation({ documentId: documentIdRef.current }),+ mutate(portalKeys.documentHeader(documentIdRef.current)),+ ]);+ toast.error(tRef.current('document.saveConflict'));+ return;+ }+ console.error('[HighlightEditor] save failed:', error);+ }+ }, []);++ const writeBuffer = useCallback(+ (source: 'manual' | 'autosave') => {+ const run = (pendingSaveRef.current ?? Promise.resolve()).then(() => saveBuffer(source));+ pendingSaveRef.current = run;+ return run;+ },+ [saveBuffer],+ );++ const debouncedAutoSave = useMemo(+ () =>+ debounce(() => writeBuffer('autosave'), EDITOR_DEBOUNCE_TIME, {+ leading: false,+ maxWait: EDITOR_MAX_WAIT,+ trailing: true,+ }),+ [writeBuffer],+ );++ useEffect(() => {+ const knownVersion = expectedUpdatedAtRef.current;+ if (!updatedAt || (knownVersion && updatedAt <= knownVersion)) return;+ if (content !== baseContentRef.current) {+ debouncedAutoSave.cancel();+ bufferRef.current = undefined;+ setBuffer(undefined);+ }+ baseContentRef.current = content;+ expectedUpdatedAtRef.current = updatedAt;+ }, [content, updatedAt, debouncedAutoSave]);++ const handleChange = useCallback(+ (next: string) => {+ const isDirty = next !== baseContentRef.current;+ bufferRef.current = isDirty ? next : undefined;+ setBuffer(bufferRef.current);+ if (isDirty) debouncedAutoSave();+ else debouncedAutoSave.cancel();+ },+ [debouncedAutoSave],+ );++ const handleSave = useCallback(async () => {+ debouncedAutoSave.cancel();+ await writeBuffer('manual');+ }, [debouncedAutoSave, writeBuffer]);++ const isMountedRef = useRef(false);++ useEffect(() => {+ isMountedRef.current = true;+ return () => {+ isMountedRef.current = false;+ debouncedAutoSave.cancel();+ // Defer the fire-and-forget save to a microtask so that StrictMode's synchronous+ // unmount/remount in development does not trigger a save. If the component is+ // immediately remounted, isMountedRef flips back to true before this runs.+ queueMicrotask(() => {+ if (isMountedRef.current) return;+ void writeBuffer('autosave');+ });+ };+ }, [debouncedAutoSave, writeBuffer]);++ useEffect(() => {+ const handler = (event: BeforeUnloadEvent) => {+ if (bufferRef.current === undefined) return;+ event.preventDefault();+ event.returnValue = '';+ };+ window.addEventListener('beforeunload', handler);+ return () => window.removeEventListener('beforeunload', handler);+ }, []);++ return { editingValue, handleChange, handleSave };+};diff --git a/src/services/document/index.test.ts b/src/services/document/index.test.tsindex f378a4878e8..e0ca9b93a4b 100644--- a/src/services/document/index.test.ts+++ b/src/services/document/index.test.ts@@ -87,4 +87,13 @@ describe('DocumentService.updateDocument', () => {expect.objectContaining({ breakAutosaveWindow: true, id: 'doc-4' }),);});++ it('serializes updatedAt to an ISO string, matching savedAt serialization', async () => {+ const updatedAt = new Date('2026-04-11T00:00:05.000Z');+ mockMutate.mockResolvedValue({ historyAppended: false, id: 'doc-5', updatedAt });++ const result = await service.updateDocument({ id: 'doc-5', title: 'New Title' });++ expect(result.updatedAt).toBe(updatedAt.toISOString());+ });});diff --git a/src/services/document/index.ts b/src/services/document/index.tsindex e8873163e66..2fa4a89cbd5 100644--- a/src/services/document/index.ts+++ b/src/services/document/index.ts@@ -259,6 +259,8 @@ export class DocumentService {? result.savedAt.toISOString(): result.savedAt: undefined,+ updatedAt:+ result.updatedAt instanceof Date ? result.updatedAt.toISOString() : result.updatedAt,};}diff --git a/src/services/document/invalidation.test.ts b/src/services/document/invalidation.test.tsnew file mode 100644index 00000000000..d1dcda8b5f0--- /dev/null+++ b/src/services/document/invalidation.test.ts@@ -0,0 +1,32 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import useSWR from 'swr';+import { describe, expect, it, vi } from 'vitest';++import { portalKeys } from '@/libs/swr/keys';++import { invalidateDocumentMutation } from './invalidation';++vi.mock('@/libs/swr', async () => ({ mutate: (await import('swr')).mutate }));++describe('invalidateDocumentMutation', () => {+ it('refreshes mounted Portal content and title after a document write', async () => {+ let row = { content: 'Before', title: 'Old title' };+ const fetcher = vi.fn(async () => row);+ const otherFetcher = vi.fn(async () => ({ content: 'Other document' }));+ const { result } = renderHook(() => ({+ document: useSWR(portalKeys.documentHeader('changed-document'), fetcher),+ other: useSWR(portalKeys.documentHeader('untouched-document'), otherFetcher),+ }));+ await waitFor(() => expect(result.current.document.data?.title).toBe('Old title'));+ await waitFor(() => expect(result.current.other.data?.content).toBe('Other document'));+ const otherCalls = otherFetcher.mock.calls.length;++ row = { content: 'After tool write', title: 'Renamed by tool' };+ await act(async () => {+ await invalidateDocumentMutation({ documentId: 'changed-document' });+ });++ expect(result.current.document.data).toEqual(row);+ expect(otherFetcher).toHaveBeenCalledTimes(otherCalls);+ });+});diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.tsindex ef6c3182c1b..92c9e8f3e00 100644--- a/src/services/document/invalidation.ts+++ b/src/services/document/invalidation.ts@@ -1,4 +1,5 @@import { mutate } from '@/libs/swr';+import { portalKeys } from '@/libs/swr/keys';import { agentDocumentSWRKeys, documentSWRKeys, notebookSWRKeys } from './swrKeys';@@ -34,6 +35,7 @@ export const invalidateDocumentMutation = async (}revalidations.push(mutate(documentSWRKeys.pageDetail(documentId)));revalidations.push(mutate(documentSWRKeys.pageMeta(documentId)));+ revalidations.push(mutate(portalKeys.documentHeader(documentId)));}if (documentId || refreshPageDocuments) {diff --git a/src/store/document/slices/document/action.test.ts b/src/store/document/slices/document/action.test.tsnew file mode 100644index 00000000000..dd664c2b143--- /dev/null+++ b/src/store/document/slices/document/action.test.ts@@ -0,0 +1,243 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as SwrModule from '@/libs/swr';+import { useClientDataSWRWithSync } from '@/libs/swr';+import { documentService } from '@/services/document';+import { usePageStore } from '@/store/page';++import { useDocumentStore } from '../../store';++vi.mock('@/services/document', () => ({+ documentService: {+ getDocumentById: vi.fn(),+ updateDocument: vi.fn().mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }),+ },+}));++vi.mock('@/libs/swr', async (importOriginal) => {+ const actual = await importOriginal<typeof SwrModule>();+ return {+ ...actual,+ mutate: vi.fn().mockResolvedValue(undefined),+ useClientDataSWRWithSync: vi.fn(() => ({ data: undefined, isValidating: false })),+ };+});++vi.mock('@/store/page', () => ({+ usePageStore: { getState: vi.fn(() => ({ upsertDocument: vi.fn() })) },+}));++const createEditor = () => ({+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Draft';+ if (type === 'json') {+ return { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };+ }+ return null;+ }),+ getLexicalEditor: vi.fn(),+ setDocument: vi.fn(),+});++const baseEditorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+};++const captureOnData = (+ documentId: string,+ editor: any,+ options: { sourceType?: 'notebook' | 'page'; topicId?: string } = {},+) => {+ renderHook(() =>+ useDocumentStore.getState().useFetchDocument(documentId, { editor, ...options }),+ );+ const swrCall = vi.mocked(useClientDataSWRWithSync).mock.calls.at(-1);+ return swrCall?.[2]?.onData as (data: unknown) => void;+};++describe('useFetchDocument onData', () => {+ beforeEach(() => {+ vi.mocked(useClientDataSWRWithSync).mockClear();+ const state = useDocumentStore.getState();+ Object.keys(state.documents).forEach((id) => state.closeDocument(id));+ useDocumentStore.setState({+ activeDocumentId: undefined,+ editor: undefined,+ lastActiveTopicDocumentIdByTopicId: {},+ });+ });++ it('initializes a document the store has not loaded yet', () => {+ const editor = createEditor();+ const onData = captureOnData('doc-1', editor, { sourceType: 'notebook', topicId: 'topic-1' });++ act(() => {+ onData({+ content: '# Server',+ editorData: baseEditorData,+ id: 'doc-1',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ });++ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({+ content: '# Server',+ isDirty: false,+ lastUpdatedTime: new Date('2026-01-01T00:00:00.000Z'),+ });+ expect(useDocumentStore.getState().lastActiveTopicDocumentIdByTopicId).toEqual({+ 'topic-1': 'doc-1',+ });+ });++ it('adopts a newer server body over a dirty draft', () => {+ const editor = createEditor();+ const onData = captureOnData('doc-1', editor, { sourceType: 'notebook', topicId: 'topic-1' });++ act(() => {+ useDocumentStore.getState().initDocumentWithEditor({+ content: '# Old',+ documentId: 'doc-1',+ editor: editor as any,+ editorData: baseEditorData,+ sourceType: 'notebook',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ useDocumentStore.getState().handleContentChange();+ });+ expect(useDocumentStore.getState().documents['doc-1'].isDirty).toBe(true);+ useDocumentStore.setState({ lastActiveTopicDocumentIdByTopicId: {} });++ act(() => {+ onData({+ content: '# Agent write',+ editorData: baseEditorData,+ id: 'doc-1',+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({+ content: '# Agent write',+ isDirty: false,+ lastSavedContent: '# Agent write',+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ saveStatus: 'saved',+ });+ expect(useDocumentStore.getState().lastActiveTopicDocumentIdByTopicId).toEqual({+ 'topic-1': 'doc-1',+ });+ });++ it('keeps the dirty draft when only the server version moved', () => {+ const editor = createEditor();+ const onData = captureOnData('doc-1', editor, { sourceType: 'notebook' });++ act(() => {+ useDocumentStore.getState().initDocumentWithEditor({+ content: '# Old',+ documentId: 'doc-1',+ editor: editor as any,+ editorData: baseEditorData,+ sourceType: 'notebook',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ useDocumentStore.getState().handleContentChange();+ });++ act(() => {+ onData({+ content: '# Old',+ editorData: structuredClone(baseEditorData),+ id: 'doc-1',+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({+ content: '# Draft',+ isDirty: true,+ lastSavedContent: '# Old',+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ it('ignores a replayed cached row that is older than the version saved since', async () => {+ const editor = createEditor();+ const onData = captureOnData('doc-1', editor, { sourceType: 'notebook' });+ vi.mocked(documentService.updateDocument).mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-02T00:00:00.000Z',+ });++ act(() => {+ useDocumentStore.getState().initDocumentWithEditor({+ content: '# Old',+ documentId: 'doc-1',+ editor: editor as any,+ editorData: baseEditorData,+ sourceType: 'notebook',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ useDocumentStore.getState().handleContentChange();+ });+ await act(async () => {+ await useDocumentStore.getState().performSave('doc-1');+ });+ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({+ content: '# Draft',+ isDirty: false,+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ });++ act(() => {+ onData({+ content: '# Old',+ editorData: baseEditorData,+ id: 'doc-1',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ });++ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({+ content: '# Draft',+ isDirty: false,+ lastSavedContent: '# Draft',+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ it('mirrors page metadata into the page store on the reconcile path', () => {+ const upsertDocument = vi.fn();+ vi.mocked(usePageStore.getState).mockReturnValue({ upsertDocument } as any);+ const editor = createEditor();+ const onData = captureOnData('doc-1', editor, { sourceType: 'page' });+ const row = {+ content: '# Old',+ id: 'doc-1',+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ };++ act(() => {+ useDocumentStore.getState().initDocumentWithEditor({+ content: '# Old',+ documentId: 'doc-1',+ editor: editor as any,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ });+ act(() => {+ onData(row);+ });++ expect(upsertDocument).toHaveBeenCalledWith(row);+ expect(documentService.getDocumentById).not.toHaveBeenCalled();+ });+});diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.tsindex d3ad857ca55..1605cd3fa9d 100644--- a/src/store/document/slices/document/action.ts+++ b/src/store/document/slices/document/action.ts@@ -33,9 +33,9 @@ export interface InitDocumentParams {documentId: string;editor: IEditor;editorData?: unknown;-sourceType: DocumentSourceType;topicId?: string;+ updatedAt?: Date | string | null;}/**@@ -75,6 +75,10 @@ export class DocumentActionImpl {this.#get = get;}+ cancelDebouncedSave = (documentId: string): void => {+ this.#debouncedSaves.get(documentId)?.cancel();+ };+#getOrCreateDebouncedSave = (documentId: string) => {if (!this.#debouncedSaves.has(documentId)) {const debouncedFn = debounce(@@ -112,15 +116,17 @@ export class DocumentActionImpl {this.#cleanupDebouncedSave(documentId);}- const { activeDocumentId, internal_dispatchDocument } = this.#get();-- // Delete document via reducer- internal_dispatchDocument({ id: documentId, type: 'deleteDocument' });+ const { activeDocumentId, internal_dispatchDocument, getPendingSave } = this.#get();// Update activeDocumentId if neededif (activeDocumentId === documentId) {this.#set({ activeDocumentId: undefined }, false, n('closeDocument:clearActive'));}++ const remove = () => internal_dispatchDocument({ id: documentId, type: 'deleteDocument' });+ const pending = getPendingSave(documentId);+ if (pending) void pending.then(remove, remove);+ else remove();};/**@@ -148,6 +154,7 @@ export class DocumentActionImpl {editorData,sourceType,topicId,+ updatedAt,} = params;const { internal_dispatchDocument } = this.#get();@@ -171,25 +178,33 @@ export class DocumentActionImpl {sourceType,skillFrontmatter,topicId,+ ...(updatedAt+ ? {+ lastUpdatedTime: updatedAt instanceof Date ? updatedAt : new Date(updatedAt),+ }+ : {}),},});// Update activeDocumentId and editor+ this.#set(+ { activeDocumentId: documentId, editor },+ false,+ n('initDocumentWithEditor:setActive'),+ );+ if (sourceType === 'notebook' && topicId) this.#rememberTopicDocument(topicId, documentId);+ };++ #rememberTopicDocument = (topicId: string, documentId: string) => {this.#set({- activeDocumentId: documentId,- editor,- ...(sourceType === 'notebook' && topicId- ? {- lastActiveTopicDocumentIdByTopicId: {- ...this.#get().lastActiveTopicDocumentIdByTopicId,- [topicId]: documentId,- },- }- : {}),+ lastActiveTopicDocumentIdByTopicId: {+ ...this.#get().lastActiveTopicDocumentIdByTopicId,+ [topicId]: documentId,+ },},false,- n('initDocumentWithEditor:setActive'),+ n('rememberTopicDocument'),);};@@ -238,7 +253,17 @@ export class DocumentActionImpl {return;}- // Initialize document with editor+ if (this.#get().documents[documentId]) {+ this.#get().reconcileRemote(documentId, document);+ if (sourceType === 'notebook' && topicId) {+ this.#rememberTopicDocument(topicId, documentId);+ }+ if (sourceType === 'page') {+ usePageStore.getState().upsertDocument(document);+ }+ return;+ }+this.#get().initDocumentWithEditor({autoSave,content: document.content,@@ -246,9 +271,9 @@ export class DocumentActionImpl {documentId,editor,editorData: document.editorData,-sourceType,topicId: topicId ?? undefined,+ updatedAt: document.updatedAt,});// Mirror page metadata (title/emoji) into pageStore so PageExplorerdiff --git a/src/store/document/slices/editor/action.reconcile.test.ts b/src/store/document/slices/editor/action.reconcile.test.tsnew file mode 100644index 00000000000..437fa55ee1a--- /dev/null+++ b/src/store/document/slices/editor/action.reconcile.test.ts@@ -0,0 +1,658 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { documentService } from '@/services/document';++import { useDocumentStore } from '../../store';++// Mock services+vi.mock('@/services/document', () => ({+ documentService: {+ acquireDocumentLock: vi.fn().mockResolvedValue({ holderId: null, lockedByOther: false }),+ releaseDocumentLock: vi.fn().mockResolvedValue(undefined),+ getDocumentById: vi.fn().mockResolvedValue({+ content: '# Test',+ id: 'doc-1',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ }),+ updateDocument: vi.fn().mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }),+ },+}));++vi.mock('@/services/notebook', () => ({+ notebookService: {+ updateDocument: vi.fn().mockResolvedValue({}),+ },+}));++// Create mock editor+const createValidMockEditor = () => ({+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Test';+ if (type === 'json') {+ return { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };+ }+ return null;+ }),+ setDocument: vi.fn(),+});++describe('DocumentStore - Editor Actions (reconcile)', () => {+ beforeEach(() => {+ vi.mocked(documentService.updateDocument).mockReset().mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ });+ vi.mocked(documentService.acquireDocumentLock)+ .mockReset()+ .mockResolvedValue({ holderId: null, lockedByOther: false } as any);+ vi.mocked(documentService.getDocumentById)+ .mockReset()+ .mockResolvedValue({+ content: '# Test',+ id: 'doc-1',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ } as any);+ vi.mocked(documentService.releaseDocumentLock)+ .mockReset()+ .mockResolvedValue(undefined as any);++ // Reset store state before each test+ const { result } = renderHook(() => useDocumentStore());+ act(() => {+ // Clear all documents and reset editor+ const state = result.current;+ Object.keys(state.documents).forEach((id) => {+ state.closeDocument(id);+ });+ state.setEditorState(undefined);+ });+ // Reset editor separately (store internal state)+ useDocumentStore.setState({ editor: undefined });+ });++ describe('reconcileRemote', () => {+ const baseEditorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const initDirtyDoc = (result: { current: ReturnType<typeof useDocumentStore.getState> }) => {+ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Old',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ editorData: baseEditorData,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ result.current.triggerDebouncedSave('doc-1');+ });+ vi.mocked(documentService.updateDocument).mockClear();+ };++ it('is a no-op when the row version matches the known version', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);++ let outcome: string | undefined;+ act(() => {+ outcome = result.current.reconcileRemote('doc-1', {+ content: '# Something else',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ });++ expect(outcome).toBe('unchanged');+ expect(result.current.documents['doc-1']).toMatchObject({ content: '# Old', isDirty: true });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it('rebases the version and keeps the draft + pending autosave when only metadata moved', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);++ let outcome: string | undefined;+ act(() => {+ outcome = result.current.reconcileRemote('doc-1', {+ content: '# Old',+ editorData: structuredClone(baseEditorData),+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ expect(outcome).toBe('rebased');+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Old',+ isDirty: true,+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({ expectedUpdatedAt: new Date('2026-01-02T00:00:00.000Z') }),+ );+ vi.useRealTimers();+ });++ it('keeps adopted SKILL.md frontmatter in the next body save', async () => {+ const editor = createValidMockEditor();+ const store = useDocumentStore.getState();+ store.initDocumentWithEditor({+ content: '---\nname: test\ndescription: old\n---\n\n# Body',+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: editor as any,+ editorData: baseEditorData,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01'),+ });+ store.reconcileRemote('doc-1', {+ content: '---\nname: test\ndescription: remote\n---\n\n# Body',+ editorData: baseEditorData,+ updatedAt: new Date('2026-01-02'),+ });+ await store.performSave('doc-1');+ expect(documentService.updateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: '---\nname: test\ndescription: remote\n---\n\n# Test',+ }),+ );+ });++ it('drops malformed remote editorData instead of adopting it', () => {+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);++ act(() => {+ result.current.reconcileRemote('doc-1', {+ content: '# Agent write',+ editorData: { root: { children: [], type: 'root' } },+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Agent write',+ editorData: null,+ lastSavedEditorData: null,+ });+ });++ it('treats null and undefined editorData as the same body', () => {+ const { result } = renderHook(() => useDocumentStore());+ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Old',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ });++ let outcome: string | undefined;+ act(() => {+ outcome = result.current.reconcileRemote('doc-1', {+ content: '# Old',+ editorData: null,+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ expect(outcome).toBe('rebased');+ });++ it('adopts the remote body, clears dirty and cancels the pending autosave', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);+ const remoteEditorData = {+ root: { children: [{ children: [{ text: 'Agent' }], type: 'paragraph' }], type: 'root' },+ };++ let outcome: string | undefined;+ act(() => {+ outcome = result.current.reconcileRemote('doc-1', {+ content: '# Agent write',+ editorData: remoteEditorData,+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });++ expect(outcome).toBe('adopted');+ expect(documentService.updateDocument).not.toHaveBeenCalled();+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Agent write',+ editorData: remoteEditorData,+ isDirty: false,+ lastSavedContent: '# Agent write',+ lastSavedEditorData: remoteEditorData,+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ saveBlockedByLock: false,+ saveStatus: 'saved',+ });+ vi.useRealTimers();+ });+ });++ describe('performSave versioning', () => {+ it('sends the last known updatedAt as expectedUpdatedAt', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const updatedAt = new Date('2026-01-01T00:00:00.000Z');++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ updatedAt,+ });+ result.current.markDirty('doc-1');+ });++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({ expectedUpdatedAt: updatedAt, id: 'doc-1' }),+ );+ });++ it('omits expectedUpdatedAt when no version is known and adopts the server version', async () => {+ const { result } = renderHook(() => useDocumentStore());+ vi.mocked(documentService.updateDocument).mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-03-03T00:00:00.000Z',+ });++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ });+ result.current.markDirty('doc-1');+ });+ expect(result.current.documents['doc-1'].lastUpdatedTime).toBeNull();++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ const params = vi.mocked(documentService.updateDocument).mock.calls[0][0];+ expect('expectedUpdatedAt' in params).toBe(false);+ expect(result.current.documents['doc-1'].lastUpdatedTime).toEqual(+ new Date('2026-03-03T00:00:00.000Z'),+ );+ });++ it('does not roll the store back when the save result is older than the current version', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const remoteEditorData = {+ root: { children: [{ children: [{ text: 'Agent' }], type: 'paragraph' }], type: 'root' },+ };++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ vi.mocked(documentService.updateDocument).mockImplementationOnce(async () => {+ useDocumentStore.getState().reconcileRemote('doc-1', {+ content: '# Agent write',+ editorData: remoteEditorData,+ updatedAt: new Date('2026-01-03T00:00:00.000Z'),+ });+ return { historyAppended: false, id: 'doc-1', updatedAt: '2026-01-02T00:00:00.000Z' };+ });++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Agent write',+ isDirty: false,+ lastSavedContent: '# Agent write',+ lastUpdatedTime: new Date('2026-01-03T00:00:00.000Z'),+ saveStatus: 'saved',+ });+ });+ });+ describe('reconcileRemote ordering', () => {+ it('ignores a row older than the version the store already holds', () => {+ const { result } = renderHook(() => useDocumentStore());+ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Saved',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ });+ });++ let outcome: string | undefined;+ act(() => {+ outcome = result.current.reconcileRemote('doc-1', {+ content: '# Stale cache',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ });++ expect(outcome).toBe('unchanged');+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Saved',+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ });+ });+ });++ describe('performSave overlap', () => {+ const createMovingEditor = () => {+ const state = { markdown: '# First' };+ const editor = {+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return state.markdown;+ if (type === 'json') {+ return { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };+ }+ return null;+ }),+ setDocument: vi.fn(),+ } as any;+ return { editor, state };+ };++ const hangFirstSave = () => {+ type SaveResult = Awaited<ReturnType<typeof documentService.updateDocument>>;+ let resolveFirst!: (value: SaveResult) => void;+ const firstResult = new Promise<SaveResult>((resolve) => {+ resolveFirst = resolve;+ });+ vi.mocked(documentService.updateDocument)+ .mockImplementationOnce(() => firstResult)+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:02.000Z',+ });+ return () =>+ resolveFirst({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:01.000Z',+ });+ };++ it('waits for the in-flight save, then sends the later request with its own metadata and the committed version', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ const { editor, state } = createMovingEditor();+ const resolveFirst = hangFirstSave();++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Base',+ documentId: 'doc-1',+ editor,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ let first!: Promise<void>;+ let second!: Promise<void>;+ act(() => {+ first = result.current.performSave('doc-1', undefined, { saveSource: 'autosave' });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ state.markdown = '# Second';+ act(() => {+ result.current.handleContentChange();+ second = result.current.performSave(+ 'doc-1',+ { title: 'Renamed' },+ { saveSource: 'manual' },+ );+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolveFirst();+ await Promise.all([first, second]);+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(documentService.updateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: '# Second',+ expectedUpdatedAt: new Date('2026-01-01T00:00:01.000Z'),+ saveSource: 'manual',+ title: 'Renamed',+ }),+ );+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: false,+ lastSavedContent: '# Second',+ lastUpdatedTime: new Date('2026-01-01T00:00:02.000Z'),+ });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ vi.useRealTimers();+ });++ it('closeDocument flushes the pending autosave after the in-flight save and keeps the newer content', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ const { editor, state } = createMovingEditor();+ const resolveFirst = hangFirstSave();++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Base',+ documentId: 'doc-1',+ editor,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ let first!: Promise<void>;+ act(() => {+ first = result.current.performSave('doc-1', undefined, { saveSource: 'autosave' });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ state.markdown = '# Second';+ act(() => {+ result.current.handleContentChange();+ result.current.closeDocument('doc-1');+ });+ expect(result.current.activeDocumentId).toBeUndefined();+ expect(result.current.documents['doc-1']).toBeDefined();++ await act(async () => {+ resolveFirst();+ await first;+ await result.current.getPendingSave('doc-1');+ await Promise.resolve();+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(documentService.updateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: '# Second',+ expectedUpdatedAt: new Date('2026-01-01T00:00:01.000Z'),+ }),+ );+ expect(result.current.documents['doc-1']).toBeUndefined();+ vi.useRealTimers();+ });++ it('flushes A into A when the editor is reused for B while A saves are queued', async () => {+ vi.useFakeTimers();+ const { editor, state } = createMovingEditor();+ const store = useDocumentStore.getState();+ const resolveFirst = hangFirstSave();+ store.initDocumentWithEditor({+ content: '# Base',+ documentId: 'doc-1',+ editor,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ store.markDirty('doc-1');+ const first = store.performSave('doc-1');+ await vi.advanceTimersByTimeAsync(0);+ state.markdown = '# Second';+ store.handleContentChange();+ store.closeDocument('doc-1');+ state.markdown = '# B';+ store.initDocumentWithEditor({+ content: '# B',+ documentId: 'doc-2',+ editor,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ resolveFirst();+ await first;+ await store.getPendingSave('doc-1');+ expect(documentService.updateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({+ id: 'doc-1',+ content: '# Second',+ expectedUpdatedAt: new Date('2026-01-01T00:00:01.000Z'),+ }),+ );+ expect(useDocumentStore.getState().documents['doc-2'].content).toBe('# B');+ vi.useRealTimers();+ });++ it('does not replay an autosave for a document with autoSave disabled', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ const { editor, state } = createMovingEditor();+ const resolveFirst = hangFirstSave();++ act(() => {+ result.current.initDocumentWithEditor({+ autoSave: false,+ content: '# Base',+ documentId: 'doc-1',+ editor,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ let first!: Promise<void>;+ act(() => {+ first = result.current.performSave('doc-1', undefined, { saveSource: 'manual' });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ state.markdown = '# Second';+ act(() => result.current.handleContentChange());+ await act(async () => {+ resolveFirst();+ await first;+ await vi.advanceTimersByTimeAsync(5000);+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: true,+ lastSavedContent: '# First',+ });+ vi.useRealTimers();+ });++ it('re-arms the autosave when a CONFLICT leaves the draft unsaved on a personal doc', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useDocumentStore());+ const conflict = Object.assign(new Error('conflict'), { data: { code: 'CONFLICT' } });+ vi.mocked(documentService.updateDocument)+ .mockRejectedValueOnce(conflict)+ .mockRejectedValueOnce(conflict)+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-03T00:00:00.000Z',+ });++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ updatedAt: new Date('2025-12-31T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ await act(async () => {+ await result.current.performSave('doc-1', undefined, { saveSource: 'manual' });+ });+ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: true,+ saveStatus: 'idle',+ });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000);+ });+ expect(documentService.updateDocument).toHaveBeenCalledTimes(3);+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: false,+ saveStatus: 'saved',+ });+ vi.useRealTimers();+ });+ });+});diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.tsindex 6236ef4c44e..ea48f3cd53e 100644--- a/src/store/document/slices/editor/action.test.ts+++ b/src/store/document/slices/editor/action.test.ts@@ -16,7 +16,11 @@ vi.mock('@/services/document', () => ({id: 'doc-1',updatedAt: new Date('2026-01-01T00:00:00.000Z'),}),- updateDocument: vi.fn().mockResolvedValue({ historyAppended: false, id: 'doc-1' }),+ updateDocument: vi.fn().mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }),},}));@@ -52,6 +56,7 @@ describe('DocumentStore - Editor Actions', () => {vi.mocked(documentService.updateDocument).mockReset().mockResolvedValue({historyAppended: false,id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',});vi.mocked(documentService.acquireDocumentLock).mockReset()@@ -890,7 +895,7 @@ name: skill-nameexpect(result.current.documents['doc-1'].saveStatus).toBe('idle');});- it('marks the document lock-blocked (keeping unsaved content) when another editor holds the lock', async () => {+ it('keeps a personal doc dirty and unblocked when the rebased retry conflicts again', async () => {const { result } = renderHook(() => useDocumentStore());const mockEditor = createValidMockEditor() as any;@@ -904,17 +909,20 @@ name: skill-nameresult.current.markDirty('doc-1');});- const lockError = Object.assign(new Error('Document is being edited by another user'), {+ const conflict = Object.assign(new Error('Document has been updated by another session'), {data: { code: 'CONFLICT' },});- vi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError);+ vi.mocked(documentService.updateDocument)+ .mockRejectedValueOnce(conflict)+ .mockRejectedValueOnce(conflict);await act(async () => {await result.current.performSave('doc-1');});- expect(result.current.documents['doc-1'].saveBlockedByLock).toBe(true);- // Unsaved content is preserved, not silently dropped.+ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(documentService.releaseDocumentLock).not.toHaveBeenCalled();+ expect(result.current.documents['doc-1'].saveBlockedByLock).toBeFalsy();expect(result.current.documents['doc-1'].isDirty).toBe(true);expect(result.current.documents['doc-1'].saveStatus).toBe('idle');});@@ -947,6 +955,65 @@ name: skill-name);});+ it('keeps a valid version after an old-server response and recovers the next save', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const editor = createValidMockEditor() as any;+ const knownVersion = new Date('2026-01-01T00:00:00.000Z');+ const committedVersion = new Date('2026-01-01T00:00:05.000Z');+ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor,+ sourceType: 'page',+ updatedAt: knownVersion,+ });+ result.current.markDirty('doc-1');+ });+ // Legacy savedAt describes history, not necessarily the committed row version.+ vi.mocked(documentService.updateDocument).mockResolvedValueOnce({+ historyAppended: true,+ id: 'doc-1',+ savedAt: '2026-01-01T00:00:03.000Z',+ } as any);+ await act(async () => result.current.performSave('doc-1'));+ expect(result.current.documents['doc-1'].lastUpdatedTime).toEqual(knownVersion);++ vi.mocked(documentService.getDocumentById).mockResolvedValueOnce({+ content: '# Test',+ editorData: editor.getDocument('json'),+ id: 'doc-1',+ updatedAt: committedVersion,+ } as any);+ vi.mocked(documentService.updateDocument)+ .mockRejectedValueOnce(+ Object.assign(new Error('Stale version'), { data: { code: 'CONFLICT' } }),+ )+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:06.000Z',+ });+ editor.getDocument.mockImplementation((type: string) =>+ type === 'markdown' ? '# Next edit' : createValidMockEditor().getDocument(type),+ );+ await act(async () => result.current.performSave('doc-1'));+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ expectedUpdatedAt: knownVersion }),+ );+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(+ 3,+ expect.objectContaining({ content: '# Next edit', expectedUpdatedAt: committedVersion }),+ );+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: false,+ lastSavedContent: '# Next edit',+ lastUpdatedTime: new Date('2026-01-01T00:00:06.000Z'),+ saveStatus: 'saved',+ });+ });+it('reclaims the lock and retries once when a CONFLICT save is a self conflict', async () => {const { result } = renderHook(() => useDocumentStore());const mockEditor = createValidMockEditor() as any;@@ -972,7 +1039,11 @@ name: skill-name});vi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError)- .mockResolvedValueOnce({ historyAppended: false, id: 'doc-1' });+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ });await act(async () => {await result.current.performSave('doc-1');@@ -990,6 +1061,60 @@ name: skill-nameexpect(result.current.documents['doc-1'].saveStatus).toBe('saved');});+ it('reclaims and retries a self conflict when the server row is still the known version', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createValidMockEditor() as any;+ const knownVersion = new Date('2026-01-01T00:00:00.000Z');++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'page',+ updatedAt: knownVersion,+ });+ result.current.internal_dispatchDocument({+ id: 'doc-1',+ type: 'updateDocument',+ value: { lockOwnerId: 'owner-1' },+ });+ result.current.markDirty('doc-1');+ });++ const lockError = Object.assign(new Error('Document is being edited by another user'), {+ data: { code: 'CONFLICT' },+ });+ vi.mocked(documentService.updateDocument)+ .mockRejectedValueOnce(lockError)+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:05.000Z',+ });+ vi.mocked(documentService.getDocumentById).mockResolvedValueOnce({+ content: '# Test',+ id: 'doc-1',+ updatedAt: knownVersion,+ } as any);++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ expect(documentService.acquireDocumentLock).toHaveBeenCalledWith('doc-1', 'owner-1');+ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(documentService.updateDocument).toHaveBeenLastCalledWith(+ expect.objectContaining({ expectedUpdatedAt: knownVersion }),+ );+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: false,+ lastUpdatedTime: new Date('2026-01-01T00:00:05.000Z'),+ saveBlockedByLock: false,+ saveStatus: 'saved',+ });+ });+it('does not retry when the server holds a newer version (collaborator saved then released)', async () => {const { result } = renderHook(() => useDocumentStore());const mockEditor = createValidMockEditor() as any;@@ -1018,6 +1143,7 @@ name: skill-namevi.mocked(documentService.getDocumentById).mockResolvedValueOnce({content: '# Collaborator version',id: 'doc-1',+ updatedAt: new Date('2026-01-01T00:00:30.000Z'),} as any);await act(async () => {@@ -1026,8 +1152,52 @@ name: skill-nameexpect(documentService.acquireDocumentLock).not.toHaveBeenCalled();expect(documentService.updateDocument).toHaveBeenCalledTimes(1);- expect(result.current.documents['doc-1'].saveBlockedByLock).toBe(true);- expect(result.current.documents['doc-1'].isDirty).toBe(true);+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Collaborator version',+ isDirty: false,+ lastSavedContent: '# Collaborator version',+ lastUpdatedTime: new Date('2026-01-01T00:00:30.000Z'),+ saveBlockedByLock: true,+ saveStatus: 'idle',+ });+ });++ it('keeps the lock-block without reconciling when the server row carries no version', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createValidMockEditor() as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'page',+ });+ result.current.internal_dispatchDocument({+ id: 'doc-1',+ type: 'updateDocument',+ value: { lockOwnerId: 'owner-1' },+ });+ result.current.markDirty('doc-1');+ });++ const lockError = Object.assign(new Error('locked'), { data: { code: 'CONFLICT' } });+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError);+ vi.mocked(documentService.getDocumentById).mockResolvedValueOnce({+ content: '# Collaborator version',+ id: 'doc-1',+ } as any);++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Test',+ isDirty: true,+ saveBlockedByLock: true,+ });});it('does not retry a save that carries metadata (title/emoji cannot be version-checked)', async () => {@@ -1055,7 +1225,9 @@ name: skill-namevi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError);await act(async () => {- await result.current.performSave('doc-1', { title: 'Renamed while conflicted' });+ await expect(+ result.current.performSave('doc-1', { title: 'Renamed while conflicted' }),+ ).rejects.toBe(lockError);});// A collaborator may have changed only the title/emoji — the recovery's@@ -1272,7 +1444,7 @@ name: skill-nameexpect(result.current.documents['doc-1'].isDirty).toBe(true);});- it('does not attempt a lock reclaim when the document has no lock owner id', async () => {+ it('rebases and retries once without a lock reclaim when the document has no lock owner id', async () => {const { result } = renderHook(() => useDocumentStore());const mockEditor = createValidMockEditor() as any;@@ -1282,21 +1454,88 @@ name: skill-namedocumentId: 'doc-1',editor: mockEditor,sourceType: 'page',+ updatedAt: new Date('2025-12-31T00:00:00.000Z'),});result.current.markDirty('doc-1');});- const lockError = Object.assign(new Error('Document is being edited by another user'), {+ const conflict = Object.assign(new Error('Document has been updated by another session'), {data: { code: 'CONFLICT' },});- vi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError);+ vi.mocked(documentService.updateDocument)+ .mockRejectedValueOnce(conflict)+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-02T00:00:00.000Z',+ });await act(async () => {await result.current.performSave('doc-1');});expect(documentService.acquireDocumentLock).not.toHaveBeenCalled();- expect(result.current.documents['doc-1'].saveBlockedByLock).toBe(true);+ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ expectedUpdatedAt: new Date('2025-12-31T00:00:00.000Z') }),+ );+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ expectedUpdatedAt: new Date('2026-01-01T00:00:00.000Z') }),+ );+ expect(result.current.documents['doc-1']).toMatchObject({+ isDirty: false,+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ saveBlockedByLock: false,+ saveStatus: 'saved',+ });+ });++ it('adopts the remote body and reports saved when a personal doc conflicts with a newer row', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const mockEditor = createValidMockEditor() as any;+ const remoteEditorData = {+ root: { children: [{ children: [{ text: 'Agent' }], type: 'paragraph' }], type: 'root' },+ };++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: mockEditor,+ sourceType: 'page',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ const conflict = Object.assign(new Error('Document has been updated by another session'), {+ data: { code: 'CONFLICT' },+ });+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(conflict);+ vi.mocked(documentService.getDocumentById).mockResolvedValueOnce({+ content: '# Agent write',+ editorData: remoteEditorData,+ id: 'doc-1',+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ } as any);++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ expect(documentService.acquireDocumentLock).not.toHaveBeenCalled();+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Agent write',+ editorData: remoteEditorData,+ isDirty: false,+ lastSavedContent: '# Agent write',+ lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ saveStatus: 'saved',+ });+ expect(result.current.documents['doc-1'].saveBlockedByLock).toBeFalsy();});it('clears the lock-blocked flag after the next successful save', async () => {@@ -1310,11 +1549,20 @@ name: skill-nameeditor: mockEditor,sourceType: 'page',});+ result.current.internal_dispatchDocument({+ id: 'doc-1',+ type: 'updateDocument',+ value: { lockOwnerId: 'owner-1' },+ });result.current.markDirty('doc-1');});const lockError = Object.assign(new Error('locked'), { data: { code: 'CONFLICT' } });vi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError);+ vi.mocked(documentService.acquireDocumentLock).mockResolvedValueOnce({+ holderId: 'user-2',+ lockedByOther: true,+ } as any);await act(async () => {await result.current.performSave('doc-1');});@@ -1323,6 +1571,7 @@ name: skill-namevi.mocked(documentService.updateDocument).mockResolvedValue({historyAppended: false,id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',});act(() => {result.current.markDirty('doc-1');@@ -1346,11 +1595,20 @@ name: skill-nameeditor: mockEditor,sourceType: 'page',});+ result.current.internal_dispatchDocument({+ id: 'doc-1',+ type: 'updateDocument',+ value: { lockOwnerId: 'owner-1' },+ });result.current.markDirty('doc-1');});const lockError = Object.assign(new Error('locked'), { data: { code: 'CONFLICT' } });vi.mocked(documentService.updateDocument).mockRejectedValueOnce(lockError);+ vi.mocked(documentService.acquireDocumentLock).mockResolvedValueOnce({+ holderId: 'user-2',+ lockedByOther: true,+ } as any);await act(async () => {await result.current.performSave('doc-1');});@@ -1392,6 +1650,7 @@ name: skill-namevi.mocked(documentService.updateDocument).mockResolvedValue({historyAppended: false,id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',});act(() => {@@ -1486,6 +1745,7 @@ name: skill-namehistoryAppended: true,id: 'doc-1',savedAt: '2026-04-15T10:00:00.000Z',+ updatedAt: '2026-04-15T10:00:00.000Z',});act(() => {diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex 72303713597..a3486885edd 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -8,7 +8,9 @@ import { t } from 'i18next';import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';import { isValidEditorData } from '@/libs/editor/isValidEditorData';+import { mutate } from '@/libs/swr';import { documentService } from '@/services/document';+import { documentSWRKeys } from '@/services/document/swrKeys';import type { StoreSetter } from '@/store/types';import { composeSkillMarkdown, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import { setNamespace } from '@/utils/storeDebug';@@ -32,6 +34,14 @@ export interface SaveExecutionOptions {saveSource?: 'autosave' | 'manual' | 'restore' | 'system' | 'llm_call';}+export interface RemoteDocumentRow {+ content?: string | null;+ editorData?: unknown;+ updatedAt: Date | string;+}++export type ReconcileResult = 'unchanged' | 'rebased' | 'adopted';+type Setter = StoreSetter<DocumentStore>;export const createEditorSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>new EditorActionImpl(set, get, _api);@@ -39,6 +49,7 @@ export const createEditorSlice = (set: Setter, get: () => DocumentStore, _api?:export class EditorActionImpl {readonly #get: () => DocumentStore;readonly #set: Setter;+ readonly #inflightSaves = new Map<string, Promise<void>>();constructor(set: Setter, get: () => DocumentStore, _api?: unknown) {void _api;@@ -76,7 +87,7 @@ export class EditorActionImpl {const { editor, activeDocumentId, documents, internal_dispatchDocument } = this.#get();const id = documentId || activeDocumentId;- if (!editor || !id) return false;+ if (!editor || !id || id !== activeDocumentId) return false;const doc = documents[id];if (!doc) return false;@@ -184,47 +195,52 @@ export class EditorActionImpl {internal_dispatchDocument({ id: documentId, type: 'updateDocument', value: { isDirty: true } });};- /**- * Apply a snapshot returned by the server-side page-agent tool executor.- * The server has already written `documents.content` / `documents.editorData`,- * so this only updates in-memory store state to match: clears the dirty flag,- * advances `lastSaved*` and refreshes `lastUpdatedTime`. Editor-level Lexical- * application is handled by `EditorRuntime.applyServerSnapshot` upstream.- */- applyServerSnapshot = (- documentId: string,- snapshot: {- content?: string;- editorData?: Record<string, unknown>;- title?: string;- },- ): void => {+ reconcileRemote = (documentId: string, row: RemoteDocumentRow): ReconcileResult => {const { documents, internal_dispatchDocument } = this.#get();const doc = documents[documentId];- if (!doc) return;+ if (!doc) return 'unchanged';- const value: Record<string, unknown> = {- isDirty: false,- lastUpdatedTime: new Date(),- saveStatus: 'saved',- };-- if (typeof snapshot.content === 'string') {- value.content = snapshot.content;- value.lastSavedContent = snapshot.content;- }- if (snapshot.editorData && isValidEditorData(snapshot.editorData)) {- value.editorData = structuredClone(snapshot.editorData);- value.lastSavedEditorData = structuredClone(snapshot.editorData);+ const updatedAt = row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt);+ if (doc.lastUpdatedTime && updatedAt.getTime() <= doc.lastUpdatedTime.getTime()) {+ return 'unchanged';}- if (typeof snapshot.title === 'string') {- value.title = snapshot.title;++ const content = row.content ?? '';+ const editorData = isValidEditorData(row.editorData) ? row.editorData : null;+ const sameBody =+ content === (doc.lastSavedContent ?? '') &&+ isEqual(editorData, doc.lastSavedEditorData ?? null);++ if (sameBody) {+ internal_dispatchDocument(+ { id: documentId, type: 'updateDocument', value: { lastUpdatedTime: updatedAt } },+ n('reconcileRemote/rebased'),+ );+ return 'rebased';}+ this.#get().cancelDebouncedSave(documentId);internal_dispatchDocument(- { id: documentId, type: 'updateDocument', value: value as Partial<typeof doc> },- n('applyServerSnapshot'),+ {+ id: documentId,+ type: 'updateDocument',+ value: {+ content,+ editorData,+ ...(doc.contentFormat === 'skillMarkdown'+ ? { skillFrontmatter: parseSkillMarkdownFrontmatter(content).frontmatter }+ : {}),+ isDirty: false,+ lastSavedContent: content,+ lastSavedEditorData: editorData,+ lastUpdatedTime: updatedAt,+ saveBlockedByLock: false,+ saveStatus: 'saved',+ },+ },+ n('reconcileRemote/adopted'),);+ return 'adopted';};onEditorInit = async (editor: IEditor): Promise<void> => {@@ -290,18 +306,36 @@ export class EditorActionImpl {this.#set({ editor });};+ getPendingSave = (documentId: string): Promise<void> | undefined =>+ this.#inflightSaves.get(documentId);+performSave = async (documentId?: string,metadata?: SaveMetadata,options?: SaveExecutionOptions,): Promise<void> => {const id = documentId || this.#get().activeDocumentId;-if (!id) return;- const { editor, documents, internal_dispatchDocument } = this.#get();+ this.syncEditorContent(id, { triggerAutoSave: false });+ const previous = this.#inflightSaves.get(id) ?? Promise.resolve();+ const run = previous.catch(() => {}).then(() => this.#runSave(id, metadata, options));+ this.#inflightSaves.set(id, run);+ try {+ await run;+ } finally {+ if (this.#inflightSaves.get(id) === run) this.#inflightSaves.delete(id);+ }+ };++ #runSave = async (+ id: string,+ metadata?: SaveMetadata,+ options?: SaveExecutionOptions,+ ): Promise<void> => {+ const { documents, internal_dispatchDocument } = this.#get();const doc = documents[id];- if (!doc || !editor) return;+ if (!doc) return;const hasMetadataChanges = metadata?.emoji !== undefined || metadata?.title !== undefined;@@ -312,9 +346,8 @@ export class EditorActionImpl {internal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'saving' } });try {- const currentEditorMarkdown = (editor.getDocument('markdown') as unknown as string) || '';- const currentContent = this.getPersistedMarkdown(id, currentEditorMarkdown);- const currentEditorData = editor.getDocument('json');+ const currentContent = doc.content ?? '';+ const currentEditorData = doc.editorData;if (!isValidEditorData(currentEditorData)) {console.warn('[DocumentStore] Refusing to save invalid editorData:', currentEditorData);@@ -329,7 +362,7 @@ export class EditorActionImpl {documentService.updateDocument({content: currentContent,editorData: JSON.stringify(currentEditorData),- expectedUpdatedAt,+ ...(expectedUpdatedAt ? { expectedUpdatedAt } : {}),id,lockOwnerId: doc.lockOwnerId,metadata: metadata?.emoji ? { emoji: metadata.emoji } : undefined,@@ -340,68 +373,66 @@ export class EditorActionImpl {let result: Awaited<ReturnType<typeof requestSave>>;try {- result = await requestSave();+ result = await requestSave(doc.lastUpdatedTime ?? undefined);} catch (error) {- // Self-heal only plain content saves: a save carrying title/emoji or a- // history restore replays fields the recovery's content+editorData- // comparison cannot vouch for (a collaborator's metadata-only change- // would be silently overwritten), so those keep the plain CONFLICT flow.- if (hasMetadataChanges || options?.restoreFromHistoryId) throw error;- result = await this.retrySaveAfterLockReclaim(id, doc, error, requestSave);+ const canRetry = !hasMetadataChanges && !options?.restoreFromHistoryId;+ result = await this.retrySaveAfterReconcile(id, doc, error, requestSave, canRetry);+ }++ // Old servers omit updatedAt. Keep the known token; conflict reconciliation+ // refreshes it on the next save without trusting the history-only savedAt.+ const savedAt = result.updatedAt ? new Date(result.updatedAt) : undefined;+ const current = this.#get().documents[id];+ if (savedAt && current?.lastUpdatedTime && savedAt < current.lastUpdatedTime) {+ internal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'saved' } });+ return;}- // Mark as clean and update save statusinternal_dispatchDocument({id,type: 'updateDocument',value: {- content: currentContent,- editorData: structuredClone(currentEditorData),-- isDirty: false,+ isDirty:+ current?.content !== currentContent || !isEqual(current?.editorData, currentEditorData),lastSavedContent: currentContent,lastSavedEditorData: structuredClone(currentEditorData),- lastUpdatedTime: result.savedAt ? new Date(result.savedAt) : new Date(),+ ...(savedAt ? { lastUpdatedTime: savedAt } : {}),saveBlockedByLock: false,saveStatus: 'saved',},});++ if (this.#get().documents[id]?.isDirty && doc.autoSave !== false) {+ this.#get().triggerDebouncedSave(id);+ }} catch (error) {- // The server rejects writes to a workspace document another collaborator is- // actively editing (CONFLICT). Surface it as a lock block so the editor can- // flip to read-only at once instead of silently dropping the edit, and keep- // `isDirty` so the unsaved content stays visible to copy out.const errorCode = (error as { data?: { code?: string } })?.data?.code;- const lockBlocked = errorCode === 'CONFLICT';+ const conflicted = errorCode === 'CONFLICT';// A view-level workspace member has no edit right on this document// (FORBIDDEN). Tell the user instead of silently dropping the edit.if (errorCode === 'FORBIDDEN') {toast.error(t('permission.saveNoEditPermission', { ns: 'setting' }));}- if (!lockBlocked) console.error('[DocumentStore] Failed to save:', error);+ if (!conflicted) console.error('[DocumentStore] Failed to save:', error);+ const live = this.#get().documents[id];+ const lockBlocked = conflicted && !!live?.lockOwnerId;+ const adoptedRemote = conflicted && !lockBlocked && live?.isDirty === false;internal_dispatchDocument({id,type: 'updateDocument',- value: { saveBlockedByLock: lockBlocked || undefined, saveStatus: 'idle' },+ value: {+ saveBlockedByLock: lockBlocked || undefined,+ saveStatus: adoptedRemote ? 'saved' : 'idle',+ },});+ if (conflicted && !lockBlocked && live?.isDirty && live.autoSave !== false) {+ this.#get().triggerDebouncedSave(id);+ }+ if (hasMetadataChanges) throw error;}};- /**- * A CONFLICT save is usually a *self* conflict rather than another member- * editing: the debounced autosave racing the lazy first lock acquire, a ghost- * lease left behind when a refresh aborted the release request, or another- * window of the same user having reclaimed the lease under its own ownerId.- * Re-acquiring with our ownerId resolves all of those — the server claims a- * missing lease and legitimately reclaims a same-user one — so the save can- * be retried once. A lease genuinely held by ANOTHER member comes back as- * `lockedByOther`, and the original CONFLICT is rethrown so the existing- * `saveBlockedByLock` read-only flow stays intact. Before reclaiming, the- * server copy is compared against this session's last-known content so a- * collaborator's just-saved-then-released version can never be overwritten- * by the retry.- */- private retrySaveAfterLockReclaim = async <T>(+ private retrySaveAfterReconcile = async <T>(id: string,baseDoc: {lastSavedContent?: string;@@ -410,24 +441,11 @@ export class EditorActionImpl {},error: unknown,requestSave: (expectedUpdatedAt?: Date) => Promise<T>,+ canRetry: boolean,): Promise<T> => {const errorCode = (error as { data?: { code?: string } })?.data?.code;- const lockOwnerId = baseDoc.lockOwnerId;- if (errorCode !== 'CONFLICT' || !lockOwnerId) throw error;-- // The rejected lease may have belonged to ANOTHER member who saved and- // released it between our failed save and this recovery — reclaiming a- // now-free lease alone cannot tell that apart from a self conflict. Only- // retry when the server's stored version (content AND editorData) is still- // exactly the version THIS request was based on — `baseDoc` is the- // immutable store snapshot captured when the failed save started, not the- // live store, so an overlapping newer save from this same tab fails the- // check instead of being replayed over. The retried save is then pinned to- // that verified version via `expectedUpdatedAt`, which the server- // re-checks atomically inside the write transaction — a save landing at- // any point after this fetch fails the retry instead of being overwritten.- // Any mismatch keeps the original CONFLICT flow (read-only + rehydrate,- // unsaved content kept for copy-out).+ if (errorCode !== 'CONFLICT') throw error;+let latest: Awaited<ReturnType<typeof documentService.getDocumentById>>;try {latest = await documentService.getDocumentById(id);@@ -435,29 +453,42 @@ export class EditorActionImpl {throw error;}if (!latest?.updatedAt) throw error;- const isKnownVersion =- (latest.content ?? '') === (baseDoc.lastSavedContent ?? '') &&- isEqual(latest.editorData ?? null, baseDoc.lastSavedEditorData ?? null);- if (!isKnownVersion) throw error;- let lockedByOther: boolean;- try {- ({ lockedByOther } = await documentService.acquireDocumentLock(id, lockOwnerId));- } catch {- throw error;+ const outcome = this.reconcileRemote(id, latest);+ if (outcome === 'adopted') {+ void mutate(documentSWRKeys.editor(id), latest, { revalidate: false });+ }+ if (outcome === 'adopted' || !canRetry) throw error;++ // `baseDoc` is the store snapshot this request was built from; an+ // overlapping newer save from this tab may have moved the live base since,+ // in which case replaying this payload would roll that save back.+ const live = this.#get().documents[id];+ const sameBase =+ (live?.lastSavedContent ?? '') === (baseDoc.lastSavedContent ?? '') &&+ isEqual(live?.lastSavedEditorData ?? null, baseDoc.lastSavedEditorData ?? null);+ if (!sameBase) throw error;++ const { lockOwnerId } = baseDoc;+ if (lockOwnerId) {+ let lockedByOther: boolean;+ try {+ ({ lockedByOther } = await documentService.acquireDocumentLock(id, lockOwnerId));+ } catch {+ throw error;+ }+ if (lockedByOther) throw error;}- if (lockedByOther) throw error;try {return await requestSave(latest.updatedAt);} catch (retryError) {// The reclaim above transferred the lease to this session for a retry- // that then failed (e.g. the server-side version predicate caught an- // interleaved collaborator save). Keeping the stolen lease would make- // the lock recovery read this tab as the legitimate holder and clear- // the save block over a stale editor — release it so the lease goes- // back to whoever is actually editing.- void documentService.releaseDocumentLock(id, lockOwnerId).catch(() => {});+ // that then failed. Keeping the stolen lease would make the lock+ // recovery read this tab as the legitimate holder and clear the save+ // block over a stale editor — release it so the lease goes back to+ // whoever is actually editing.+ if (lockOwnerId) void documentService.releaseDocumentLock(id, lockOwnerId).catch(() => {});throw retryError;}};diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.tsindex ae8b63a6b3a..12ad12b445c 100644--- a/src/store/file/slices/document/action.test.ts+++ b/src/store/file/slices/document/action.test.ts@@ -133,6 +133,7 @@ describe('DocumentAction', () => {vi.mocked(documentService.updateDocument).mockResolvedValue({historyAppended: false,id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',});act(() => {@@ -182,7 +183,13 @@ describe('DocumentAction', () => {const existingResource = createResourceFixture();let resolveUpdate:- ((value: { historyAppended: boolean; id: string; savedAt?: string }) => void) | undefined;+ | ((value: {+ historyAppended: boolean;+ id: string;+ savedAt?: string;+ updatedAt: string;+ }) => void)+ | undefined;vi.mocked(documentService.updateDocument).mockImplementation(() =>new Promise((resolve) => {@@ -222,7 +229,7 @@ describe('DocumentAction', () => {title: 'Optimistic title',});- resolveUpdate?.({ historyAppended: false, id: 'doc-1' });+ resolveUpdate?.({ historyAppended: false, id: 'doc-1', updatedAt: '2026-01-01T00:00:00.000Z' });await act(async () => {await pendingUpdate;@@ -248,6 +255,7 @@ describe('DocumentAction', () => {vi.mocked(documentService.updateDocument).mockResolvedValue({historyAppended: false,id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',});act(() => {diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.test.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.test.tsnew file mode 100644index 00000000000..aec3959dbbc--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.test.ts@@ -0,0 +1,69 @@+import { AgentDocumentsApiName } from '@lobechat/builtin-tool-agent-documents';+import type { ToolAfterCallContext } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { invalidateSpy, getDocumentStoreStateSpy } = vi.hoisted(() => ({+ getDocumentStoreStateSpy: vi.fn(),+ invalidateSpy: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/services/document/invalidation', () => ({+ invalidateDocumentMutation: invalidateSpy,+}));+vi.mock('@/store/document', () => ({+ getDocumentStoreState: getDocumentStoreStateSpy,+}));+vi.mock('@/services/agentDocument', () => ({ agentDocumentService: {} }));+vi.mock('@/services/work', () => ({ workService: {} }));+vi.mock('@/store/agent', () => ({+ useAgentStore: { getState: () => ({ activeAgentId: 'agent-1' }) },+}));+vi.mock('@/store/electron', () => ({ useElectronStore: { getState: () => ({}) } }));+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ getActiveWorkspaceSlug: () => undefined,+}));++const afterCall = (apiName: string, documentId: string): ToolAfterCallContext =>+ ({+ apiName,+ identifier: 'lobe-agent-documents',+ params: {},+ result: { state: { documentId }, success: true },+ toolCallId: 'call_1',+ }) as ToolAfterCallContext;++describe('agentDocumentsExecutor host invalidation', () => {+ beforeEach(() => {+ invalidateSpy.mockClear();+ getDocumentStoreStateSpy.mockClear();+ });++ it('revalidates the editor key after a content write instead of touching the document store', async () => {+ const { agentDocumentsExecutor } = await import('./lobe-agent-documents');++ await agentDocumentsExecutor.onAfterCall!(+ afterCall(AgentDocumentsApiName.replaceDocumentContent, 'doc-1'),+ );++ expect(invalidateSpy).toHaveBeenCalledWith({+ agentId: 'agent-1',+ cause: 'agent-document',+ documentId: 'doc-1',+ });+ expect(getDocumentStoreStateSpy).not.toHaveBeenCalled();+ });++ it('does not revalidate the editor key of a removed document', async () => {+ const { agentDocumentsExecutor } = await import('./lobe-agent-documents');++ await agentDocumentsExecutor.onAfterCall!(+ afterCall(AgentDocumentsApiName.removeDocument, 'doc-1'),+ );++ expect(invalidateSpy).toHaveBeenCalledWith({+ agentId: 'agent-1',+ cause: 'agent-document',+ documentId: undefined,+ });+ });+});diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.tsindex b262900500f..58cc9f8878c 100644--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts@@ -279,11 +279,12 @@ const runtime = new AgentDocumentsExecutionRuntime(// Revalidate the documents list after the agent mutates it. `onAfterCall`// carries no agentId, so resolve the active chat agent — the one whose run// just produced the tool call. Covers the server-runtime path where the- // client service layer never invalidates.- onDocumentsMutated: async () => {+ // client service layer never invalidates. A written `documentId` also+ // revalidates the editor key so the open editor reconciles the server row.+ onDocumentsMutated: async ({ documentId }) => {const agentId = useAgentStore.getState().activeAgentId;- if (!agentId) return;- await invalidateDocumentMutation({ agentId, cause: 'agent-document' });+ if (!agentId && !documentId) return;+ await invalidateDocumentMutation({ agentId, cause: 'agent-document', documentId });},},);diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.ts b/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.tsnew file mode 100644index 00000000000..1abae0f78fb--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-agent-todos.test.ts@@ -0,0 +1,54 @@+import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client/executor';+import type { BuiltinToolContext } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import useSWR from 'swr';+import { describe, expect, it, vi } from 'vitest';++import { notebookSWRKeys } from '@/services/document/swrKeys';++const { row, updateDocument } = vi.hoisted(() => {+ const row = { current: { metadata: {} as Record<string, any> } };+ return {+ row,+ updateDocument: vi.fn(async ({ metadata }) => {+ row.current = { metadata };+ }),+ };+});++vi.mock('@/libs/swr', async () => ({ mutate: (await import('swr')).mutate }));+vi.mock('@/services/notebook', () => ({+ notebookService: {+ listDocuments: vi.fn().mockResolvedValue({+ data: [{ createdAt: new Date(), id: 'plan-1', metadata: {}, updatedAt: new Date() }],+ }),+ updateDocument,+ },+}));+vi.mock('@/store/notebook', () => ({ useNotebookStore: { getState: () => ({}) } }));++describe('lobeAgentExecutor plan todos sync', () => {+ it('revalidates the plan document after syncing todos into its metadata', async () => {+ const ctx = { currentTodos: [], topicId: 'topic-1' } as unknown as BuiltinToolContext;++ const { result: cache } = renderHook(() =>+ useSWR(notebookSWRKeys.documents('topic-1'), async () => row.current),+ );+ await waitFor(() => expect(cache.current.data).toBeDefined());+ let result: Awaited<ReturnType<typeof lobeAgentExecutor.createTodos>>;+ await act(async () => {+ result = await lobeAgentExecutor.createTodos({ adds: ['ship it'] }, ctx);+ });++ expect(result!.success).toBe(true);+ expect(updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'plan-1',+ metadata: expect.objectContaining({ todos: expect.anything() }),+ }),+ );+ expect(cache.current.data?.metadata.todos.items).toEqual([+ expect.objectContaining({ text: 'ship it' }),+ ]);+ });+});diff --git a/src/store/tool/slices/builtin/executors/lobe-notebook.ts b/src/store/tool/slices/builtin/executors/lobe-notebook.tsindex 8f2f5be41c7..c4d98e9e508 100644--- a/src/store/tool/slices/builtin/executors/lobe-notebook.ts+++ b/src/store/tool/slices/builtin/executors/lobe-notebook.ts@@ -6,7 +6,11 @@*/import { NotebookExecutor } from '@lobechat/builtin-tool-notebook/executor';+import { invalidateDocumentMutation } from '@/services/document/invalidation';import { notebookService } from '@/services/notebook';// Create executor instance with client-side service-export const notebookExecutor = new NotebookExecutor(notebookService);+export const notebookExecutor = new NotebookExecutor(notebookService, {+ onDocumentsMutated: ({ documentId, topicId }) =>+ invalidateDocumentMutation({ cause: 'notebook', documentId, topicId }),+});