🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(openapi): read and write Lexical editorData on /api/v1/documents (#23668)
Innei491f47fddac5
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex f7fff72a4b5..3eacc801c78 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -362,6 +362,11 @@ export const RedisKeys = {* Full key: lobechat:page_projection:v1:{documentId}*/pageProjection: (documentId: string): string => `page_projection:v1:${documentId}`,+ /**+ * Yjs state vector of the room state a page's stored body was last written from.+ * Full key: lobechat:page_room_state:v1:{documentId}+ */+ pageRoomState: (documentId: string): string => `page_room_state:v1:${documentId}`,},/*** Send-path cache scope — see {@link RedisKeyNamespace.SEND_PATH_CACHE}.diff --git a/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts b/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.tsindex c892c5e7049..a3066cabcf6 100644--- a/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts+++ b/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts@@ -6,9 +6,17 @@ import * as Y from 'yjs';import { updateDocumentThroughRoom, writePageBodyThroughRoom } from '../bodyWriter';import { openPageFork, projectPageState } from '../fork';-const room = vi.hoisted(() => ({ bootstrapped: true, doc: null as any, pushes: [] as any[] }));+const room = vi.hoisted(() => ({+ bootstrapped: true,+ doc: null as any,+ pushes: [] as any[],+ serverWriteSeq: undefined as number | undefined,+}));const env = vi.hoisted(() => ({ ENABLE_PAGE_COLLAB: true, ENABLE_WORKSPACE_PAGE_COLLAB: false }));-const stored = vi.hoisted(() => ({ workspaceId: undefined as string | undefined }));+const stored = vi.hoisted(() => ({+ updatedAt: new Date('2026-11-23T10:00:00.000Z'),+ workspaceId: undefined as string | undefined,+}));const persisted = vi.hoisted(() => [] as any[]);const lock = vi.hoisted(() => ({ heldByOther: false }));@@ -23,6 +31,7 @@ vi.mock('@/server/services/pageCollab/roomClient', async (importOriginal) => {getState: async () => ({bootstrapped: room.bootstrapped,epoch: 'e1',+ serverWriteSeq: room.serverWriteSeq,update: Yjs.encodeStateAsUpdate(room.doc),}),pushUpdate: async (_id: string, update: Uint8Array, options: any) => {@@ -42,10 +51,19 @@ vi.mock('@/server/services/pageCollab/persist', () => ({vi.mock('@/server/services/document', () => ({DocumentService: class {- getDocumentById = async () => ({ title: 'Page', workspaceId: stored.workspaceId });+ getDocumentById = async () => ({+ title: 'Page',+ updatedAt: stored.updatedAt,+ workspaceId: stored.workspaceId,+ });},}));+// Without Redis the stored version alone decides; conditionalWrites.test covers the room state.+vi.mock('@/server/services/redis', () => ({+ redisService: { pageCollab: { lastPersistedRoomState: async () => undefined } },+}));+const writer = { saveSource: 'system' as const, userId: 'u1', writeSource: 'system' as const };const editorDataOf = (markdown: string) => {@@ -73,6 +91,7 @@ describe('writePageBodyThroughRoom', () => {stored.workspaceId = undefined;room.bootstrapped = true;room.pushes = [];+ room.serverWriteSeq = undefined;persisted.length = 0;await seedRoom('para one\n\npara two\n');});@@ -194,6 +213,7 @@ describe('updateDocumentThroughRoom', () => {lock.heldByOther = false;room.bootstrapped = true;room.pushes = [];+ room.serverWriteSeq = undefined;await seedRoom('para one\n');});@@ -237,7 +257,8 @@ describe('updateDocumentThroughRoom', () => {updateDocument: vi.fn(async (id: string) => ({ id }) as any),});- it('keeps the body off the row when the room took it', async () => {+ it('keeps the body and its version off the row when the room took it', async () => {+ room.serverWriteSeq = 0;const documents = service();await updateDocumentThroughRoom(@@ -246,7 +267,7 @@ describe('updateDocumentThroughRoom', () => {'doc_1',{content: 'para ONE\n',- expectedUpdatedAt: new Date(),+ expectedUpdatedAt: new Date(stored.updatedAt),metadata: { tag: 'x' },saveSource: 'restore',title: 'T',diff --git a/apps/server/src/services/pageCollab/__tests__/conditionalWrites.test.ts b/apps/server/src/services/pageCollab/__tests__/conditionalWrites.test.tsnew file mode 100644index 00000000000..8aea4858cdc--- /dev/null+++ b/apps/server/src/services/pageCollab/__tests__/conditionalWrites.test.ts@@ -0,0 +1,286 @@+// @vitest-environment node+import { createHeadlessEditor } from '@lobehub/editor/headless';+import { TRPCError } from '@trpc/server';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as Y from 'yjs';++import type { LobeChatDatabase } from '@/database/type';+import type { DocumentService } from '@/server/services/document';++import { updateDocumentThroughRoom, writePageBodyThroughRoom } from '../bodyWriter';+import { openPageFork, projectPageState } from '../fork';++// Nothing on these paths reaches the database: the document service, persist and Redis are mocked.+const db = {} as unknown as LobeChatDatabase;++const env = vi.hoisted(() => ({+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',+ AGENT_GATEWAY_URL: 'https://gateway.test',+ ENABLE_PAGE_COLLAB: true,+}));++// The stored page, and the room state it was last written from.+const stored = vi.hoisted(() => ({+ failPersist: false,+ persistedRoomState: null as Uint8Array | null,+ redisDown: false,+ updatedAt: new Date('2026-11-23T10:00:00.000Z'),+}));++vi.mock('@/envs/app', () => ({ appEnv: env }));++vi.mock('@/server/services/document', () => ({+ DocumentService: class {+ getDocumentById = async () => ({+ title: 'Page',+ updatedAt: stored.updatedAt,+ workspaceId: 'ws_1',+ });+ },+}));++vi.mock('@/server/services/redis', () => ({+ redisService: {+ pageCollab: {+ lastPersistedRoomState: async () =>+ stored.redisDown ? undefined : stored.persistedRoomState,+ },+ },+}));++// What the real persist does to the row and the remembered room state.+vi.mock('@/server/services/pageCollab/persist', async () => {+ // `vi.mock` factories are hoisted above the static imports, so `yjs` is loaded here.+ const Yjs = await import('yjs');+ return {+ persistPageState: async (_db: unknown, _id: string, state: Uint8Array) => {+ if (stored.failPersist) throw new Error('database unavailable');+ stored.updatedAt = new Date(stored.updatedAt.getTime() + 1000);+ stored.persistedRoomState = Yjs.encodeStateVectorFromUpdate(state);+ return true;+ },+ };+});++const room = {+ doc: new Y.Doc(),+ pushes: 0,+ serverWriteSeq: 0 as number | undefined,+ stale: null as { reads: number; seq: number; state: Uint8Array } | null,+};++const gateway = async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url);++ if (url.pathname === '/api/documents/state') {+ const stale = room.stale && room.stale.reads > 0 ? room.stale : null;+ if (stale) stale.reads--;+ return Response.json({+ bootstrapped: true,+ epoch: 'e1',+ serverWriteSeq: stale ? stale.seq : room.serverWriteSeq,+ update: Buffer.from(stale ? stale.state : Y.encodeStateAsUpdate(room.doc)).toString('base64'),+ });+ }++ if (url.pathname === '/api/documents/update') {+ const body = JSON.parse(String(init?.body));+ if (+ typeof body.baseServerWriteSeq === 'number' &&+ room.serverWriteSeq !== undefined &&+ body.baseServerWriteSeq < room.serverWriteSeq+ ) {+ return Response.json({ code: 'STALE_BASE', ok: false }, { status: 409 });+ }+ Y.applyUpdate(room.doc, new Uint8Array(Buffer.from(body.update, 'base64')));+ room.pushes++;+ if (room.serverWriteSeq !== undefined) room.serverWriteSeq++;+ return Response.json({ epoch: 'e1', ok: true });+ }++ return new Response('not found', { status: 404 });+};++const writer = { saveSource: 'system' as const, userId: 'u1', writeSource: 'user' as const };++const editorDataOf = (markdown: string) => {+ const editor = createHeadlessEditor();+ editor.hydrateMarkdown(markdown, { keepId: true });+ const { editorData } = editor.export();+ editor.destroy();+ return editorData;+};++const roomState = () => Y.encodeStateAsUpdate(room.doc);++// A room the stored page was seeded from: the remembered state is the room's.+const seedRoom = async (markdown: string) => {+ const seed = await openPageFork(undefined, editorDataOf(markdown));+ room.doc = new Y.Doc();+ Y.applyUpdate(room.doc, seed.diff());+ seed.destroy();+ stored.persistedRoomState = Y.encodeStateVectorFromUpdate(roomState());+};++// An edit someone made in the room that has not reached the stored page yet.+const typeInRoom = async (markdown: string) => {+ const other = await openPageFork(roomState());+ other.editor.hydrateEditorData(editorDataOf(markdown), { keepId: true });+ Y.applyUpdate(room.doc, other.diff());+ other.destroy();+};++const markdownOfRoom = async () => (await projectPageState(roomState())).markdown;++const readVersion = () => new Date(stored.updatedAt);++const service: Pick<DocumentService, 'assertCanWriteBody' | 'updateDocument'> = {+ assertCanWriteBody: async () => {},+ updateDocument: async (id) => ({ historyAppended: false, id, updatedAt: stored.updatedAt }),+};++const save = (markdown: string, expectedUpdatedAt: Date) =>+ updateDocumentThroughRoom(+ db,+ service,+ 'doc_1',+ { content: markdown, editorData: editorDataOf(markdown), expectedUpdatedAt },+ { userId: 'u1', workspaceId: 'ws_1' },+ );++const expectVersionMismatch = async (write: Promise<unknown>) => {+ const error = await write.then(+ () => undefined,+ (reason: unknown) => reason,+ );+ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({+ cause: { data: { code: 'DocumentVersionMismatch' } },+ code: 'CONFLICT',+ });+};++describe('a write that names the stored version it was made against', () => {+ beforeEach(async () => {+ room.pushes = 0;+ room.serverWriteSeq = 0;+ room.stale = null;+ stored.failPersist = false;+ stored.redisDown = false;+ stored.updatedAt = new Date('2026-11-23T10:00:00.000Z');+ await seedRoom('para one\n');+ vi.stubGlobal('fetch', vi.fn(gateway));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('goes into the room while the page is still at that version', async () => {+ await save('para one\n\nadded\n', readVersion());++ expect(await markdownOfRoom()).toBe('para one\n\nadded\n');+ });++ it('lets only the first of two saves made from the same read through', async () => {+ const base = readVersion();++ const [first, second] = await Promise.allSettled([+ save('first\n', base),+ save('second\n', base),+ ]);++ expect(first.status).toBe('fulfilled');+ expect(second.status).toBe('rejected');+ await expectVersionMismatch(Promise.reject((second as PromiseRejectedResult).reason));+ expect(await markdownOfRoom()).toBe('first\n');+ });++ it('answers a conflict when another server wrote the room after it was read, instead of retrying', async () => {+ const base = readVersion();+ // Another instance wrote the room; its save has not reached the stored page yet.+ room.stale = { reads: 1, seq: 0, state: roomState() };+ await typeInRoom('from another instance\n');+ room.serverWriteSeq = 1;++ await expectVersionMismatch(save('mine\n', base));+ expect(await markdownOfRoom()).toBe('from another instance\n');+ });++ it('stores what the room holds beyond the stored page, answers a conflict, and takes a save made from that version', async () => {+ const base = readVersion();+ await typeInRoom('typed in the browser\n');++ await expectVersionMismatch(save('mine\n', base));+ expect(room.pushes).toBe(0);+ expect(stored.updatedAt.getTime()).toBeGreaterThan(base.getTime());+ expect(await markdownOfRoom()).toBe('typed in the browser\n');++ await save('mine\n', readVersion());+ expect(await markdownOfRoom()).toBe('mine\n');+ });++ it('treats a room nobody recorded the same way', async () => {+ const base = readVersion();+ stored.persistedRoomState = null;++ await expectVersionMismatch(save('mine\n', base));+ expect(room.pushes).toBe(0);++ await save('mine\n', readVersion());+ expect(await markdownOfRoom()).toBe('mine\n');+ });++ it('does not take a room write whose save to the stored page failed as that version', async () => {+ const base = readVersion();+ stored.failPersist = true;+ await save('first\n', base);+ stored.failPersist = false;++ await expectVersionMismatch(save('second\n', base));+ expect(await markdownOfRoom()).toBe('first\n');+ });++ it('answers a conflict when the stored page moved on', async () => {+ const base = readVersion();+ stored.updatedAt = new Date(base.getTime() + 5000);++ await expectVersionMismatch(save('mine\n', base));+ expect(room.pushes).toBe(0);+ });++ it('falls back to the stored version alone without Redis', async () => {+ stored.redisDown = true;+ const base = readVersion();++ await save('mine\n', base);+ expect(await markdownOfRoom()).toBe('mine\n');++ await expectVersionMismatch(save('stale\n', base));+ });++ it('refuses when the room cannot make conditional server writes', async () => {+ room.serverWriteSeq = undefined;++ await expect(save('mine\n', readVersion())).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ expect(room.pushes).toBe(0);+ });++ it('still retries a stale room for a write that names no version', async () => {+ room.stale = { reads: 1, seq: 0, state: roomState() };+ await typeInRoom('para one\n\nfrom another instance\n');+ room.serverWriteSeq = 1;++ const written = await writePageBodyThroughRoom(+ db,+ 'doc_1',+ { markdown: 'para one\n\nfrom another instance\n\nmine\n' },+ { ...writer, saveSource: 'system' },+ );++ expect(written).toBe(true);+ expect(await markdownOfRoom()).toBe('para one\n\nfrom another instance\n\nmine\n');+ });+});diff --git a/apps/server/src/services/pageCollab/__tests__/persist.test.ts b/apps/server/src/services/pageCollab/__tests__/persist.test.tsindex ecff8d7b9f5..62cb8d8b45f 100644--- a/apps/server/src/services/pageCollab/__tests__/persist.test.ts+++ b/apps/server/src/services/pageCollab/__tests__/persist.test.ts@@ -7,8 +7,9 @@ import { openPageFork, PAGE_META_KEY } from '../fork';import { PageProjectionRejectedError, persistPageState } from '../persist';import { emptyEditorData } from '../seed';-const { redisStore, store } = vi.hoisted(() => ({+const { redisStore, roomStates, store } = vi.hoisted(() => ({redisStore: new Map<string, string>(),+ roomStates: new Map<string, Uint8Array>(),store: {calls: [] as string[],row: null as any,@@ -24,6 +25,9 @@ vi.mock('@/server/services/redis', () => ({rememberProjectedBody: async (id: string, digest: string) => {redisStore.set(id, digest);},+ rememberPersistedRoomState: async (id: string, stateVector: Uint8Array) => {+ roomStates.set(id, stateVector);+ },},},}));@@ -81,6 +85,7 @@ const persist = (state: Uint8Array) =>describe('persistPageState', () => {beforeEach(() => {redisStore.clear();+ roomStates.clear();store.calls = [];store.savedHistories = [];store.updates = [];@@ -94,6 +99,20 @@ describe('persistPageState', () => {expect(store.updates.map((update) => update.saveSource)).toEqual(['autosave', 'autosave']);});+ it('remembers the room state the stored page now shows', async () => {+ const state = await roomOf('one\n');++ await persist(state);++ expect(roomStates.get('doc_1')).toEqual(Y.encodeStateVectorFromUpdate(state));+ });++ it('remembers no room state for a projection it refuses', async () => {+ await expect(persist(await emptyRoom())).rejects.toBeInstanceOf(PageProjectionRejectedError);++ expect(roomStates.has('doc_1')).toBe(false);+ });+it('keeps a body written around the room as its own version before replacing it', async () => {await persist(await roomOf('one\n'));// Something wrote the row without going through the room.diff --git a/apps/server/src/services/pageCollab/bodyWriter.ts b/apps/server/src/services/pageCollab/bodyWriter.tsindex 47484713c77..4ca97d8fbcd 100644--- a/apps/server/src/services/pageCollab/bodyWriter.ts+++ b/apps/server/src/services/pageCollab/bodyWriter.ts@@ -4,6 +4,8 @@ import {type ModifyOperation,} from '@lobechat/editor-runtime';import type { HeadlessEditor, HeadlessLiteXMLOperation } from '@lobehub/editor/headless';+import { TRPCError } from '@trpc/server';+import * as Y from 'yjs';import type { LobeChatDatabase } from '@/database/type';import { isValidEditorData } from '@/libs/editor/isValidEditorData';@@ -13,12 +15,13 @@ import {} from '@/server/services/agentDocuments/headlessEditor';import { DocumentService } from '@/server/services/document';import type { UpdateDocumentParams, UpdateDocumentResult } from '@/server/services/document/types';+import { redisService } from '@/server/services/redis';import { isLegacyPageCollabEnabled, isPageCollabEnabled } from './config';import type { SerializedEditor } from './editorData';import { runPageExclusive } from './queue';import { PageRoomStaleBaseError } from './roomClient';-import { RoomPageSessions } from './roomSession';+import { type RoomPageSession, RoomPageSessions } from './roomSession';import type { PageWriter } from './session';export interface PageBody {@@ -28,6 +31,15 @@ export interface PageBody {title?: string;}+export interface PageBodyWriteOptions {+ /**+ * Write only while the page is still at this stored version (`updatedAt`). It+ * is checked against the room the body lands in, on every attempt; otherwise+ * the write rejects with `DocumentVersionMismatch`, as a row write would.+ */+ expectedUpdatedAt?: Date;+}+// A stale base means another server instance wrote the room after this one// read it; writing anyway would merge both block replacements as duplicates.const MAX_STALE_BASE_RETRIES = 5;@@ -80,6 +92,57 @@ const applyBody = async (editor: HeadlessEditor, body: PageBody) => {}};+const versionMismatch = () =>+ new TRPCError({+ cause: { data: { code: 'DocumentVersionMismatch' } },+ code: 'CONFLICT',+ message: 'Document has been updated by another session',+ });++/**+ * The room is at the stored version when the stored page still is and the room+ * holds nothing the page does not show: it is still at the state the page was+ * last written from. Runs where the body is about to enter the room, so a write+ * queued behind another, or retried, sees what came before it.+ */+const assertRoomAtVersion = async (+ db: LobeChatDatabase,+ documentId: string,+ session: RoomPageSession,+ expectedUpdatedAt: Date,+ writer: PageWriter,+) => {+ // The push is what makes the check hold against another server instance.+ if (session.serverWriteSeq === undefined) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'This page is open in a room that cannot take conditional writes; send no version',+ });+ }++ // Without Redis nobody can tell what the room holds beyond the stored page.+ const written = await redisService.pageCollab.lastPersistedRoomState(documentId);+ if (written !== undefined) {+ const read = Y.decodeStateVector(session.stateVector);+ const recorded = written && Y.decodeStateVector(written);+ const roomIsStored =+ !!recorded &&+ recorded.size === read.size &&+ [...read].every(([client, clock]) => recorded.get(client) === clock);+ if (!roomIsStored) {+ // Edits typed in the room that the stored page does not show yet (or a room+ // nobody recorded). Storing them gives the caller a version to read them at.+ await session.projectAsRead();+ throw versionMismatch();+ }+ }++ const row = await new DocumentService(db, writer.userId, writer.workspaceId).getDocumentById(+ documentId,+ );+ if (row?.updatedAt?.getTime() !== expectedUpdatedAt.getTime()) throw versionMismatch();+};+/*** Writes a page body that a server-side writer (the CLI, an agent tool, a* rollback, a client that predates rooms) would otherwise put straight into the@@ -95,6 +158,7 @@ export const writePageBodyThroughRoom = async (documentId: string,body: PageBody,writer: PageWriter,+ { expectedUpdatedAt }: PageBodyWriteOptions = {},): Promise<boolean> => {if (!(await mayHaveRoom(db, documentId, writer))) return false;@@ -104,6 +168,9 @@ export const writePageBodyThroughRoom = async (if (!session) return false;try {+ if (expectedUpdatedAt) {+ await assertRoomAtVersion(db, documentId, session, expectedUpdatedAt, writer);+ }if (body.editorData !== undefined || body.markdown !== undefined) {await applyBody(session.draft.editor, body);}@@ -124,6 +191,9 @@ export const writePageBodyThroughRoom = async (if (!(error instanceof PageRoomStaleBaseError) || retry >= MAX_STALE_BASE_RETRIES) {throw error;}+ // Another server wrote the room after this one read it: the page is past+ // the version the caller named, whatever the stored page says yet.+ if (expectedUpdatedAt) throw versionMismatch();await sleep(STALE_BASE_BACKOFF_MS * (retry + 1) * (0.5 + Math.random()));}}@@ -161,11 +231,12 @@ export const updateDocumentThroughRoom = async (saveSource: params.saveSource ?? 'system',writeSource: params.writeSource ?? 'user',},+ { expectedUpdatedAt: params.expectedUpdatedAt },);if (!routed) return service.updateDocument(documentId, params);- // The room merged and persisted the body (and title); the version predicate- // guarded a row write that no longer happens.+ // The room took the body (and title) under the version predicate, and its write+ // moved the stored version on: the rest of the update lands on the new one.const {content: _content,editorData: _editorData,diff --git a/apps/server/src/services/pageCollab/persist.ts b/apps/server/src/services/pageCollab/persist.tsindex 06ccfd3150d..868bd162ddc 100644--- a/apps/server/src/services/pageCollab/persist.ts+++ b/apps/server/src/services/pageCollab/persist.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';import type { DocumentWriteSource } from '@lobechat/types';import debug from 'debug';+import * as Y from 'yjs';import type { LobeChatDatabase } from '@/database/type';import { withHeadlessEditorLock } from '@/server/services/agentDocuments/headlessEditor';@@ -113,5 +114,10 @@ export const persistPageState = async (...(title ? { title } : {}),});await redisService.pageCollab.rememberProjectedBody(documentId, bodyDigest(editorData));+ // A conditional write accepts the room only while it is still at this state.+ await redisService.pageCollab.rememberPersistedRoomState(+ documentId,+ Y.encodeStateVectorFromUpdate(state),+ );return true;};diff --git a/apps/server/src/services/pageCollab/roomSession.ts b/apps/server/src/services/pageCollab/roomSession.tsindex be9b868ad3c..009a165f6a1 100644--- a/apps/server/src/services/pageCollab/roomSession.ts+++ b/apps/server/src/services/pageCollab/roomSession.ts@@ -31,6 +31,15 @@ const log = debug('lobe-server:page-collab:room');export interface RoomPageSession extends PageSession {/** Stores the room's current state as a version, edited or not. */persistAs: (saveSource: DocumentHistorySaveSource) => Promise<void>;+ /**+ * Stores the room as this session read it, the way the room's own projection+ * does: an autosave of whatever its collaborators typed, attributed to nobody.+ */+ projectAsRead: () => Promise<void>;+ /** The room's server-write sequence when read; absent from a gateway without conditional writes. */+ readonly serverWriteSeq?: number;+ /** The Yjs state vector of the room as this session read it. */+ readonly stateVector: Uint8Array;}export class PageCollabUnavailableError extends Error {@@ -122,7 +131,15 @@ export class RoomPageSessions implements PageSessions {log('persist as %s failed for %s: %O', saveSource, documentId, error);}},+ projectAsRead: async () => {+ await persistPageState(this.db, documentId, state.update, { saveSource: 'autosave' });+ },+ serverWriteSeq: state.serverWriteSeq,setTitle: (next) => fork.doc.getMap(PAGE_META_KEY).set('title', next),+ // Only a conditional write reads it.+ get stateVector() {+ return Y.encodeStateVectorFromUpdate(state.update);+ },title,};}diff --git a/apps/server/src/services/redis/pageCollab.ts b/apps/server/src/services/redis/pageCollab.tsindex c812d9710c3..d2c7ac034a7 100644--- a/apps/server/src/services/redis/pageCollab.ts+++ b/apps/server/src/services/redis/pageCollab.ts@@ -29,4 +29,33 @@ export const pageCollab = {.set(RedisKeys.lobechat.pageProjection(documentId), digest, { ex: PROJECTION_TTL_SECONDS }).catch(() => undefined);},++ /**+ * The state vector of the room state the stored page was last written from. A+ * room still at that state holds nothing the stored page does not show. `null`+ * when none is recorded (never written, or expired); `undefined` when Redis is+ * unavailable, so nobody can tell.+ */+ async lastPersistedRoomState(documentId: string): Promise<Uint8Array | null | undefined> {+ const redis = await getClient();+ if (!redis) return undefined;+ try {+ const value = await redis.get(RedisKeys.lobechat.pageRoomState(documentId));+ return value ? new Uint8Array(Buffer.from(value, 'base64')) : null;+ } catch {+ return undefined;+ }+ },++ async rememberPersistedRoomState(documentId: string, stateVector: Uint8Array): Promise<void> {+ const redis = await getClient();+ if (!redis) return;+ await redis+ .set(+ RedisKeys.lobechat.pageRoomState(documentId),+ Buffer.from(stateVector).toString('base64'),+ { ex: PROJECTION_TTL_SECONDS },+ )+ .catch(() => undefined);+ },};diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex ba055fc01a5..4f700d01bdb 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -1060,6 +1060,15 @@ components:type:- string- "null"+ editorData:+ anyOf:+ - type: object+ propertyNames:+ type: string+ additionalProperties: {}+ - type: "null"+ description: Lexical editor state (`SerializedEditorState`) of the body; `null`+ for folders, HTML pages and pages saved without one.required:- createdAt- fileType@@ -1069,6 +1078,7 @@ components:- title- updatedAt- content+ - editorDataadditionalProperties: falseEvalRun:type: object@@ -16413,8 +16423,8 @@ paths:post:operationId: documents.createdescription: >-- Creates a page from Markdown, or a folder with `fileType:- "custom/folder"`.+ Creates a page from Markdown or Lexical `editorData`, or a folder with+ `fileType: "custom/folder"`.**API key scopes:** `knowledge:write`.@@ -16560,6 +16570,31 @@ paths:description: Markdown body. Omit for a folder.type: stringmaxLength: 10000000+ editorData:+ type: object+ properties:+ root:+ type: object+ properties:+ children:+ minItems: 1+ type: array+ items: {}+ type:+ type: string+ const: root+ required:+ - children+ - type+ additionalProperties: {}+ required:+ - root+ additionalProperties: {}+ description: Lexical editor state (`SerializedEditorState`) with a non-empty+ `root`, at most 50000000 characters serialized. Replaces the+ whole body. When `content` is omitted, the server exports+ the Markdown body from it. Not accepted for folders or HTML+ pages (`custom/html`).fileType:description: "`custom/folder` creates a folder; defaults to a page(`custom/document`)."@@ -16581,6 +16616,10 @@ paths:/api/v1/documents/{id}:get:operationId: documents.get+ description: |-+ Returns the Markdown `content` and the Lexical `editorData` of the body.++ **API key scopes:** `knowledge:read`.summary: Get a documenttags:- documents@@ -16718,12 +16757,14 @@ paths:minLength: 1required: true- $ref: "#/components/parameters/WorkspaceId"- description: "**API key scopes:** `knowledge:read`."patch:operationId: documents.updatedescription: >-- Replaces the title and/or the whole Markdown body. A page open in the- editor receives the write through its live room.+ Replaces the title and/or the whole body, sent as Markdown `content` or+ Lexical `editorData`. A page open in the editor receives the write+ through its live room. Send `ifUpdatedAt` to get 409 instead of+ overwriting an edit made since the client last read the page; a page+ someone else is editing also answers 409.**API key scopes:** `knowledge:write`.@@ -16822,6 +16863,21 @@ paths:$ref: "#/components/headers/RateLimitRemaining"X-RateLimit-Reset:$ref: "#/components/headers/RateLimitReset"+ "409":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource conflict+ headers:+ X-Request-Id:+ $ref: "#/components/headers/RequestId"+ X-RateLimit-Limit:+ $ref: "#/components/headers/RateLimitLimit"+ X-RateLimit-Remaining:+ $ref: "#/components/headers/RateLimitRemaining"+ X-RateLimit-Reset:+ $ref: "#/components/headers/RateLimitReset""429":content:application/json:@@ -16872,9 +16928,44 @@ paths:type: objectproperties:content:- description: Markdown body; replaces the whole body.+ description: Markdown body; replaces the whole body. Sent with `editorData`, it+ is stored as that state’s Markdown.type: stringmaxLength: 10000000+ editorData:+ type: object+ properties:+ root:+ type: object+ properties:+ children:+ minItems: 1+ type: array+ items: {}+ type:+ type: string+ const: root+ required:+ - children+ - type+ additionalProperties: {}+ required:+ - root+ additionalProperties: {}+ description: Lexical editor state (`SerializedEditorState`) with a non-empty+ `root`, at most 50000000 characters serialized. Replaces the+ whole body. When `content` is omitted, the server exports+ the Markdown body from it. Not accepted for folders or HTML+ pages (`custom/html`).+ ifUpdatedAt:+ description: The `updatedAt` the client last read. When the stored `updatedAt`+ differs, nothing is written and the API answers 409+ `conflict`; the error’s `details` entry for+ `json.ifUpdatedAt` carries the stored `updatedAt` as its+ message.+ type: string+ format: date-time+ pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$title:type: stringminLength: 1diff --git a/packages/openapi/src/routes/documents.route.test.ts b/packages/openapi/src/routes/documents.route.test.tsindex 5375e1a89ca..75182c6c98d 100644--- a/packages/openapi/src/routes/documents.route.test.ts+++ b/packages/openapi/src/routes/documents.route.test.ts@@ -49,6 +49,14 @@ const requestAs = (scopes: string[], path: string, init?: { body?: unknown; meth});};+const editorData = {+ root: {+ children: [{ children: [], type: 'paragraph', version: 1 }],+ type: 'root',+ version: 1,+ },+};+describe('POST /documents', () => {it('creates a page for a key that may write knowledge', async () => {const res = await requestAs(['knowledge:write'], '/', {@@ -68,6 +76,15 @@ describe('POST /documents', () => {expect(res.status).toBe(201);});+ it('creates a page from Lexical editor data', async () => {+ const res = await requestAs(['knowledge:write'], '/', {+ body: { editorData, title: 'Weekly sync' },+ method: 'POST',+ });++ expect(res.status).toBe(201);+ });+it('rejects a read-only key', async () => {const res = await requestAs(['knowledge:read'], '/', {body: { title: 'Weekly sync' },@@ -106,6 +123,42 @@ describe('PATCH /documents/:id', () => {expect(res.status).toBe(200);});+ it('replaces the body with Lexical editor data, guarded by ifUpdatedAt', async () => {+ const res = await requestAs(['knowledge:write'], '/doc-1', {+ body: { editorData, ifUpdatedAt: '2026-11-19T02:00:00.000Z' },+ method: 'PATCH',+ });++ expect(res.status).toBe(200);+ });++ it('rejects editor data that is not a Lexical state', async () => {+ const res = await requestAs(['knowledge:write'], '/doc-1', {+ body: { editorData: { content: '# New body', type: 'doc' } },+ method: 'PATCH',+ });++ expect(res.status).toBe(400);+ });++ it('rejects an ifUpdatedAt that is not a timestamp', async () => {+ const res = await requestAs(['knowledge:write'], '/doc-1', {+ body: { content: '# New body', ifUpdatedAt: 'yesterday' },+ method: 'PATCH',+ });++ expect(res.status).toBe(400);+ });++ it('rejects an ifUpdatedAt with nothing to update', async () => {+ const res = await requestAs(['knowledge:write'], '/doc-1', {+ body: { ifUpdatedAt: '2026-11-19T02:00:00.000Z' },+ method: 'PATCH',+ });++ expect(res.status).toBe(400);+ });+it('rejects an empty update', async () => {const res = await requestAs(['knowledge:write'], '/doc-1', { body: {}, method: 'PATCH' });diff --git a/packages/openapi/src/routes/documents.route.ts b/packages/openapi/src/routes/documents.route.tsindex d9abf7bae94..e24ea2ea6a1 100644--- a/packages/openapi/src/routes/documents.route.ts+++ b/packages/openapi/src/routes/documents.route.ts@@ -54,7 +54,8 @@ DocumentRoutes.post('/',routeDoc({data: DocumentSchema,- description: 'Creates a page from Markdown, or a folder with `fileType: "custom/folder"`.',+ description:+ 'Creates a page from Markdown or Lexical `editorData`, or a folder with `fileType: "custom/folder"`.',// 404: the parent folder does not exist or is not visible.errors: [404],status: 201,@@ -70,7 +71,13 @@ DocumentRoutes.post(/** GET /api/v1/documents/:id */DocumentRoutes.get('/:id',- routeDoc({ data: DocumentSchema, errors: [404], summary: 'Get a document', tags: ['documents'] }),+ routeDoc({+ data: DocumentSchema,+ description: 'Returns the Markdown `content` and the Lexical `editorData` of the body.',+ errors: [404],+ summary: 'Get a document',+ tags: ['documents'],+ }),requireAuth,documentRead,zValidator('param', DocumentIdParamSchema),@@ -83,8 +90,9 @@ DocumentRoutes.patch(routeDoc({data: DocumentSchema,description:- 'Replaces the title and/or the whole Markdown body. A page open in the editor receives the write through its live room.',- errors: [404],+ 'Replaces the title and/or the whole body, sent as Markdown `content` or Lexical `editorData`. A page open in the editor receives the write through its live room. Send `ifUpdatedAt` to get 409 instead of overwriting an edit made since the client last read the page; a page someone else is editing also answers 409.',+ // 409: `ifUpdatedAt` is stale, or another member holds the page's edit lock.+ errors: [404, 409],summary: 'Update a document',tags: ['documents'],}),diff --git a/packages/openapi/src/services/document.service.test.ts b/packages/openapi/src/services/document.service.test.tsindex d27263c935e..bd301749988 100644--- a/packages/openapi/src/services/document.service.test.ts+++ b/packages/openapi/src/services/document.service.test.ts@@ -1,7 +1,12 @@+import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { LobeChatDatabase } from '@/database/type';-import { updateDocumentFromInput } from '@/server/services/document/writeFlow';+import { exportEditorDataSnapshot } from '@/server/services/agentDocuments/headlessEditor';+import {+ createDocumentFromInput,+ updateDocumentFromInput,+} from '@/server/services/document/writeFlow';import { getDocumentForViewer } from '@/server/services/documentAccess';import { DocumentRestService } from './document.service';@@ -19,15 +24,37 @@ vi.mock('@/server/services/document/writeFlow', () => ({createDocumentFromInput: vi.fn(),updateDocumentFromInput: vi.fn(),}));+vi.mock('@/server/services/agentDocuments/headlessEditor', () => ({+ exportEditorDataSnapshot: vi.fn(),+}));+vi.mock('@/server/routers/lambda/_schema/documentHistory', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ DOCUMENT_EDITOR_DATA_MAX_LENGTH: 2000,+}));vi.mock('@/server/services/documentAccess', () => ({ getDocumentForViewer: vi.fn() }));vi.mock('@/server/services/knowledgeBaseAccess', () => ({assertContentsNotInRestrictedKnowledgeBase: vi.fn(),getRestrictedKnowledgeBaseIds: vi.fn(async () => []),}));+const editorData = {+ root: {+ children: [+ {+ children: [{ text: 'New body', type: 'text', version: 1 }],+ type: 'paragraph',+ version: 1,+ },+ ],+ type: 'root',+ version: 1,+ },+};+const storedDocument = {content: 'New body',createdAt: new Date('2026-11-19T01:00:00Z'),+ editorData,fileType: 'custom/document',id: 'doc-1',parentId: 'folder-1',@@ -41,8 +68,10 @@ const service = () => new DocumentRestService({} as LobeChatDatabase, 'user-1');describe('DocumentRestService', () => {beforeEach(() => {findById.mockReset();+ vi.mocked(createDocumentFromInput).mockReset();vi.mocked(updateDocumentFromInput).mockReset();vi.mocked(getDocumentForViewer).mockReset();+ vi.mocked(exportEditorDataSnapshot).mockReset();});it('answers 404 for an update to a document that no longer exists, without writing', async () => {@@ -60,7 +89,7 @@ describe('DocumentRestService', () => {await expect(service().getDocument('doc-gone')).rejects.toMatchObject({ status: 404 });});- it('returns the stored Markdown after a full update', async () => {+ it('returns the stored Markdown and editor data after a full update', async () => {findById.mockResolvedValue(storedDocument);vi.mocked(getDocumentForViewer).mockResolvedValue(storedDocument as never);@@ -76,6 +105,7 @@ describe('DocumentRestService', () => {expect(document).toEqual({content: 'New body',createdAt: '2026-11-19T01:00:00.000Z',+ editorData,fileType: 'custom/document',id: 'doc-1',parentId: 'folder-1',@@ -84,4 +114,165 @@ describe('DocumentRestService', () => {updatedAt: '2026-11-19T02:00:00.000Z',});});++ it('returns null editor data for a page without Lexical state', async () => {+ vi.mocked(getDocumentForViewer).mockResolvedValue({+ ...storedDocument,+ editorData: { content: 'legacy', type: 'doc' },+ } as never);++ const document = await service().getDocument('doc-1');++ expect(document.editorData).toBeNull();+ });++ describe('editorData writes', () => {+ it('stores editor data sent alone with the Markdown the editor exports from it', async () => {+ findById.mockResolvedValue(storedDocument);+ vi.mocked(getDocumentForViewer).mockResolvedValue(storedDocument as never);+ vi.mocked(exportEditorDataSnapshot).mockResolvedValue({+ content: 'New body\n',+ editorData,+ });++ await service().updateDocument('doc-1', { editorData });++ expect(exportEditorDataSnapshot).toHaveBeenCalledWith({ editorData });+ expect(updateDocumentFromInput).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ content: 'New body\n',+ editorData: JSON.stringify(editorData),+ id: 'doc-1',+ }),+ );+ });++ it('keeps the Markdown sent with editor data instead of exporting it', async () => {+ findById.mockResolvedValue(storedDocument);+ vi.mocked(getDocumentForViewer).mockResolvedValue(storedDocument as never);++ await service().updateDocument('doc-1', { content: 'Client body', editorData });++ expect(exportEditorDataSnapshot).not.toHaveBeenCalled();+ expect(updateDocumentFromInput).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ content: 'Client body',+ editorData: JSON.stringify(editorData),+ }),+ );+ });++ it('rejects editor data for an HTML page without writing', async () => {+ findById.mockResolvedValue({ ...storedDocument, fileType: 'custom/html' });++ await expect(service().updateDocument('doc-1', { editorData })).rejects.toMatchObject({+ code: 'bad_request',+ status: 400,+ });+ expect(updateDocumentFromInput).not.toHaveBeenCalled();+ });++ it('rejects editor data longer than the serialized limit without writing', async () => {+ findById.mockResolvedValue(storedDocument);+ const longText = 'x'.repeat(2000);+ const oversized = {+ root: { ...editorData.root, children: [{ text: longText, type: 'text', version: 1 }] },+ };++ await expect(+ service().updateDocument('doc-1', { editorData: oversized }),+ ).rejects.toMatchObject({+ code: 'validation_error',+ details: [expect.objectContaining({ path: 'json.editorData' })],+ status: 400,+ });+ expect(updateDocumentFromInput).not.toHaveBeenCalled();+ });++ it('creates a page from editor data sent alone', async () => {+ vi.mocked(exportEditorDataSnapshot).mockResolvedValue({+ content: 'New body\n',+ editorData,+ });+ vi.mocked(createDocumentFromInput).mockResolvedValue(storedDocument as never);++ await service().createDocument({ editorData, title: 'Weekly sync' });++ expect(createDocumentFromInput).toHaveBeenCalledWith(expect.anything(), {+ content: 'New body\n',+ editorData: JSON.stringify(editorData),+ title: 'Weekly sync',+ });+ });++ it('rejects editor data for a new folder', async () => {+ await expect(+ service().createDocument({ editorData, fileType: 'custom/folder', title: 'Minutes' }),+ ).rejects.toMatchObject({ status: 400 });+ expect(createDocumentFromInput).not.toHaveBeenCalled();+ });+ });++ describe('ifUpdatedAt', () => {+ it('answers 409 with the stored updatedAt when the page changed since, without writing', async () => {+ findById.mockResolvedValue(storedDocument);++ await expect(+ service().updateDocument('doc-1', {+ content: 'Stale body',+ ifUpdatedAt: '2026-11-19T01:30:00.000Z',+ }),+ ).rejects.toMatchObject({+ code: 'conflict',+ details: [{ message: '2026-11-19T02:00:00.000Z', path: 'json.ifUpdatedAt' }],+ status: 409,+ });+ expect(updateDocumentFromInput).not.toHaveBeenCalled();+ });++ it('writes with the version predicate when the page is unchanged', async () => {+ findById.mockResolvedValue(storedDocument);+ vi.mocked(getDocumentForViewer).mockResolvedValue(storedDocument as never);++ await service().updateDocument('doc-1', {+ content: 'New body',+ ifUpdatedAt: '2026-11-19T02:00:00.000Z',+ });++ expect(updateDocumentFromInput).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ content: 'New body',+ expectedUpdatedAt: new Date('2026-11-19T02:00:00.000Z'),+ }),+ );+ expect(vi.mocked(updateDocumentFromInput).mock.calls[0][1]).not.toHaveProperty('ifUpdatedAt');+ });++ it('answers 409 when another save lands between the check and the write', async () => {+ findById+ .mockResolvedValueOnce(storedDocument)+ .mockResolvedValueOnce({ ...storedDocument, updatedAt: new Date('2026-11-19T03:00:00Z') });+ vi.mocked(updateDocumentFromInput).mockRejectedValue(+ new TRPCError({+ cause: { data: { code: 'DocumentVersionMismatch' } } as never,+ code: 'CONFLICT',+ message: 'Document has been updated by another session',+ }),+ );++ await expect(+ service().updateDocument('doc-1', {+ content: 'New body',+ ifUpdatedAt: '2026-11-19T02:00:00.000Z',+ }),+ ).rejects.toMatchObject({+ code: 'conflict',+ details: [{ message: '2026-11-19T03:00:00.000Z', path: 'json.ifUpdatedAt' }],+ status: 409,+ });+ });+ });});diff --git a/packages/openapi/src/services/document.service.ts b/packages/openapi/src/services/document.service.tsindex 7b7ee1ce280..98bc1357b33 100644--- a/packages/openapi/src/services/document.service.ts+++ b/packages/openapi/src/services/document.service.ts@@ -1,5 +1,11 @@+import { CUSTOM_FOLDER_FILE_TYPE, HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { TRPCError } from '@trpc/server';+import { DocumentModel } from '@/database/models/document';import type { LobeChatDatabase } from '@/database/type';+import { isValidEditorData } from '@/libs/editor/isValidEditorData';+import { DOCUMENT_EDITOR_DATA_MAX_LENGTH } from '@/server/routers/lambda/_schema/documentHistory';+import { exportEditorDataSnapshot } from '@/server/services/agentDocuments/headlessEditor';import { DocumentService } from '@/server/services/document';import {createDocumentFromInput,@@ -23,10 +29,11 @@ import type {UpdateDocumentRequest,} from '../types/document.type';-/** The stored fields this API exposes; `content` is absent from list rows. */+/** The stored fields this API exposes; `content` and `editorData` are absent from list rows. */interface DocumentRow {content?: string | null;createdAt: Date;+ editorData?: unknown;fileType: string;id: string;parentId: string | null;@@ -48,17 +55,63 @@ const toSummary = (row: DocumentRow): DocumentSummary => ({const toPublicDocument = (row: DocumentRow): PublicDocument => ({...toSummary(row),content: row.content ?? null,+ // Older CLI builds stored `{ type: 'doc', content }`; only Lexical state is editor data.+ editorData: isValidEditorData(row.editorData) ? row.editorData : null,});const notFound = (id: string) => new ApiException(404, 'not_found', `Document not found: ${id}`);+/** `ifUpdatedAt` no longer names the stored version; the detail carries the one that does. */+const versionConflict = (updatedAt: Date) =>+ new ApiException(+ 409,+ 'conflict',+ 'Document was updated after ifUpdatedAt; read it again before saving',+ [{ message: updatedAt.toISOString(), path: 'json.ifUpdatedAt' }],+ );++/**+ * The body fields a write hands to the shared write flow, which takes editor+ * state serialized. Editor data sent without Markdown gets the Markdown the+ * editor exports from it, so `content` never lags behind the rich text.+ */+const toBodyWrite = async (+ { content, editorData }: { content?: string; editorData?: Record<string, unknown> },+ fileType: string | undefined,+): Promise<{ content?: string; editorData?: string }> => {+ if (editorData === undefined) return { content };++ // An HTML page's body is its content alone, and a folder has no body; the+ // write flow would drop or keep the state silently, so refuse it here.+ if (fileType === HTML_DOCUMENT_FILE_TYPE || fileType === CUSTOM_FOLDER_FILE_TYPE) {+ throw new ApiException(+ 400,+ 'bad_request',+ `A ${fileType} document carries no editorData; send Markdown content instead`,+ );+ }++ const serialized = JSON.stringify(editorData);+ if (serialized.length > DOCUMENT_EDITOR_DATA_MAX_LENGTH) {+ const message = `Serialized editorData exceeds ${DOCUMENT_EDITOR_DATA_MAX_LENGTH} characters`;+ throw new ApiException(400, 'validation_error', `Invalid request: ${message}`, [+ { message, path: 'json.editorData' },+ ]);+ }++ return {+ content: content ?? (await exportEditorDataSnapshot({ editorData })).content,+ editorData: serialized,+ };+};+/*** Documents REST service.** Writes go through the same create/update flow as the in-app editor* (`@/server/services/document/writeFlow`): slug parents, the parent- * visibility check, Markdown → editor data and writing into an open page's- * live room are not re-implemented here.+ * visibility check, Markdown → editor data, the HTML-page rule and writing+ * into an open page's live room are not re-implemented here.*/export class DocumentRestService extends BaseService {private readonly documentModel: DocumentModel;@@ -109,16 +162,46 @@ export class DocumentRestService extends BaseService {}async createDocument(body: CreateDocumentRequest): Promise<PublicDocument> {- const document = await createDocumentFromInput(this.context, body);+ const { editorData, ...input } = body;+ const bodyWrite = await toBodyWrite({ content: input.content, editorData }, input.fileType);+ const document = await createDocumentFromInput(this.context, { ...input, ...bodyWrite });return toPublicDocument(document);}async updateDocument(id: string, body: UpdateDocumentRequest): Promise<PublicDocument> {+ const { editorData, ifUpdatedAt, ...input } = body;// The document service reports a missing row as a plain error; answer 404.- if (!(await this.documentModel.findById(id))) throw notFound(id);+ const current = await this.documentModel.findById(id);+ if (!current) throw notFound(id);++ // An early answer for a version that is already stale. The write enforces it+ // itself, on the row or in the page's live room, where it cannot race.+ const expectedUpdatedAt = ifUpdatedAt === undefined ? undefined : new Date(ifUpdatedAt);+ if (expectedUpdatedAt && current.updatedAt.getTime() !== expectedUpdatedAt.getTime()) {+ throw versionConflict(current.updatedAt);+ }- await updateDocumentFromInput(this.context, { ...body, id });+ const bodyWrite = await toBodyWrite({ content: input.content, editorData }, current.fileType);+ try {+ await updateDocumentFromInput(this.context, {+ ...input,+ ...bodyWrite,+ expectedUpdatedAt,+ id,+ });+ } catch (error) {+ // Another save landed before the write, or the page's live room held edits+ // the stored page did not show yet (the write stored them first).+ const versionMismatch =+ error instanceof TRPCError &&+ error.code === 'CONFLICT' &&+ (error.cause as { data?: { code?: string } } | undefined)?.data?.code ===+ 'DocumentVersionMismatch';+ const latest = versionMismatch ? await this.documentModel.findById(id) : undefined;+ if (latest) throw versionConflict(latest.updatedAt);+ throw error;+ }return this.getDocument(id);}diff --git a/packages/openapi/src/types/document.type.ts b/packages/openapi/src/types/document.type.tsindex d0deae9c355..e77cb92387e 100644--- a/packages/openapi/src/types/document.type.ts+++ b/packages/openapi/src/types/document.type.ts@@ -1,6 +1,9 @@import { z } from 'zod';-import { DOCUMENT_CONTENT_MAX_LENGTH } from '@/server/routers/lambda/_schema/documentHistory';+import {+ DOCUMENT_CONTENT_MAX_LENGTH,+ DOCUMENT_EDITOR_DATA_MAX_LENGTH,+} from '@/server/routers/lambda/_schema/documentHistory';import { CursorPaginationQuerySchema, paginatedListSchema } from '../helpers/pagination';import { dateTimeSchema } from './common.type';@@ -24,6 +27,25 @@ export type DocumentListQuery = z.infer<typeof DocumentListQuerySchema>;// ==================== Request Schemas ====================+/**+ * Lexical editor state (`SerializedEditorState`), the shape the web editor+ * saves: a `root` node with at least one child. Nodes are stored as sent, so+ * node types the server does not know survive the round trip.+ */+const EditorDataInputSchema = z+ .looseObject({+ root: z.looseObject({+ children: z.array(z.unknown()).min(1),+ type: z.literal('root'),+ }),+ })+ .describe(+ 'Lexical editor state (`SerializedEditorState`) with a non-empty `root`, at most ' ++ `${DOCUMENT_EDITOR_DATA_MAX_LENGTH} characters serialized. Replaces the whole body. ` ++ 'When `content` is omitted, the server exports the Markdown body from it. ' ++ 'Not accepted for folders or HTML pages (`custom/html`).',+ );+export const CreateDocumentRequestSchema = z.object({content: z@@ -31,6 +53,7 @@ export const CreateDocumentRequestSchema = z.max(DOCUMENT_CONTENT_MAX_LENGTH).optional().describe('Markdown body. Omit for a folder.'),+ editorData: EditorDataInputSchema.optional(),fileType: z.string().min(1)@@ -48,13 +71,24 @@ export const UpdateDocumentRequestSchema = z.string().max(DOCUMENT_CONTENT_MAX_LENGTH).optional()- .describe('Markdown body; replaces the whole body.'),+ .describe(+ 'Markdown body; replaces the whole body. Sent with `editorData`, it is stored as that state’s Markdown.',+ ),+ editorData: EditorDataInputSchema.optional(),+ ifUpdatedAt: z.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'The `updatedAt` the client last read. When the stored `updatedAt` differs, nothing is written and the API answers 409 `conflict`; the error’s `details` entry for `json.ifUpdatedAt` carries the stored `updatedAt` as its message.',+ ),title: z.string().min(1).optional(),}).strict()- .refine((value) => value.content !== undefined || value.title !== undefined, {- message: 'Provide content or title',- });+ .refine(+ (value) =>+ value.content !== undefined || value.editorData !== undefined || value.title !== undefined,+ { message: 'Provide content, editorData or title' },+ );export type UpdateDocumentRequest = z.infer<typeof UpdateDocumentRequestSchema>;// ==================== Response Schemas ====================@@ -76,7 +110,16 @@ export const DocumentSummarySchema = zexport type DocumentSummary = z.infer<typeof DocumentSummarySchema>;export const DocumentSchema = z- .object({ ...documentSummaryShape, content: z.string().nullable().describe('Markdown body.') })+ .object({+ ...documentSummaryShape,+ content: z.string().nullable().describe('Markdown body.'),+ editorData: z+ .record(z.string(), z.unknown())+ .nullable()+ .describe(+ 'Lexical editor state (`SerializedEditorState`) of the body; `null` for folders, HTML pages and pages saved without one.',+ ),+ }).strict().meta({ id: 'Document' });export type PublicDocument = z.infer<typeof DocumentSchema>;diff --git a/packages/sdk/src/generated/sdk.gen.ts b/packages/sdk/src/generated/sdk.gen.tsindex cdf30d3fda2..7876ec0e53e 100644--- a/packages/sdk/src/generated/sdk.gen.ts+++ b/packages/sdk/src/generated/sdk.gen.ts@@ -577,7 +577,7 @@ export class Documents extends HeyApiClient {/*** Create a document*- * Creates a page from Markdown, or a folder with `fileType: "custom/folder"`.+ * Creates a page from Markdown or Lexical `editorData`, or a folder with `fileType: "custom/folder"`.** **API key scopes:** `knowledge:write`.*/@@ -593,6 +593,8 @@ export class Documents extends HeyApiClient {/*** Get a document*+ * Returns the Markdown `content` and the Lexical `editorData` of the body.+ ** **API key scopes:** `knowledge:read`.*/public get<ThrowOnError extends boolean = false>(options: Options<GetApiV1DocumentsByIdData, ThrowOnError>): RequestResult<GetApiV1DocumentsByIdResponses, GetApiV1DocumentsByIdErrors, ThrowOnError> {@@ -606,7 +608,7 @@ export class Documents extends HeyApiClient {/*** Update a document*- * Replaces the title and/or the whole Markdown body. A page open in the editor receives the write through its live room.+ * Replaces the title and/or the whole body, sent as Markdown `content` or Lexical `editorData`. A page open in the editor receives the write through its live room. Send `ifUpdatedAt` to get 409 instead of overwriting an edit made since the client last read the page; a page someone else is editing also answers 409.** **API key scopes:** `knowledge:write`.*/diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.tsindex 85bfc016a04..56a00adc6b2 100644--- a/packages/sdk/src/generated/types.gen.ts+++ b/packages/sdk/src/generated/types.gen.ts@@ -317,6 +317,12 @@ export type Document = {* Markdown body.*/content: string | null;+ /**+ * Lexical editor state (`SerializedEditorState`) of the body; `null` for folders, HTML pages and pages saved without one.+ */+ editorData: {+ [key: string]: unknown;+ } | null;};export type EvalRun = {@@ -5396,6 +5402,17 @@ export type PostApiV1DocumentsData = {* Markdown body. Omit for a folder.*/content?: string;+ /**+ * Lexical editor state (`SerializedEditorState`) with a non-empty `root`, at most 50000000 characters serialized. Replaces the whole body. When `content` is omitted, the server exports the Markdown body from it. Not accepted for folders or HTML pages (`custom/html`).+ */+ editorData?: {+ root: {+ children: Array<unknown>;+ type: 'root';+ [key: string]: unknown;+ };+ [key: string]: unknown;+ };/*** `custom/folder` creates a folder; defaults to a page (`custom/document`).*/@@ -5525,9 +5542,24 @@ export type GetApiV1DocumentsByIdResponse = GetApiV1DocumentsByIdResponses[keyofexport type PatchApiV1DocumentsByIdData = {body: {/**- * Markdown body; replaces the whole body.+ * Markdown body; replaces the whole body. Sent with `editorData`, it is stored as that state’s Markdown.*/content?: string;+ /**+ * Lexical editor state (`SerializedEditorState`) with a non-empty `root`, at most 50000000 characters serialized. Replaces the whole body. When `content` is omitted, the server exports the Markdown body from it. Not accepted for folders or HTML pages (`custom/html`).+ */+ editorData?: {+ root: {+ children: Array<unknown>;+ type: 'root';+ [key: string]: unknown;+ };+ [key: string]: unknown;+ };+ /**+ * The `updatedAt` the client last read. When the stored `updatedAt` differs, nothing is written and the API answers 409 `conflict`; the error’s `details` entry for `json.ifUpdatedAt` carries the stored `updatedAt` as its message.+ */+ ifUpdatedAt?: string;title?: string;};headers?: {@@ -5560,6 +5592,10 @@ export type PatchApiV1DocumentsByIdErrors = {* Resource not found*/404: ApiError;+ /**+ * Resource conflict+ */+ 409: ApiError;/*** Rate limit exceeded*/