🤯 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(page): enforce the per-page character limit on collaborative pages (#22277)
YuTengjinge08163e4ef49
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/documentCollab.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/documentCollab.test.tsindex b2cb8030ecf..a2d1d32a8e0 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/documentCollab.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/documentCollab.test.ts@@ -91,4 +91,33 @@ describe('documentProjection', () => {expect((await project({ documentId: 'doc_1', update: '' })).status).toBe(409);});++ it('answers 422 with the limit when the room grew the page past it', async () => {+ const { TRPCError } = await import('@trpc/server');+ persistPageState.mockRejectedValue(+ new TRPCError({+ cause: {+ data: {+ actual: 501_502,+ code: 'DocumentCharLimitExceeded',+ limit: 500_000,+ plan: 'plus',+ },+ },+ code: 'BAD_REQUEST',+ message: 'Document is too long',+ }),+ );++ const res = await project({ documentId: 'doc_1', update: '' });++ expect(res.status).toBe(422);+ expect(await res.json()).toEqual({+ actual: 501_502,+ code: 'DocumentCharLimitExceeded',+ error: 'Document is too long',+ limit: 500_000,+ plan: 'plus',+ });+ });});diff --git a/apps/server/src/router-hono/agent/handlers/documentCollab.ts b/apps/server/src/router-hono/agent/handlers/documentCollab.tsindex 1896064c645..b0847b401e0 100644--- a/apps/server/src/router-hono/agent/handlers/documentCollab.ts+++ b/apps/server/src/router-hono/agent/handlers/documentCollab.ts@@ -2,6 +2,7 @@ import debug from 'debug';import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';+import { getDocumentCharLimitErrorData } from '@/server/services/document/writeLimit';import { persistPageState, resolvePageAccess } from '@/server/services/pageCollab';import { PageProjectionRejectedError } from '@/server/services/pageCollab/persist';import { fromBase64 } from '@/server/services/pageCollab/roomClient';@@ -43,6 +44,12 @@ export async function documentProjection(c: Context): Promise<Response> {if (error instanceof PageProjectionRejectedError) {return c.json({ error: error.message }, 409);}+ // The room grew the page past its plan's limit. The stored page keeps its+ // last accepted version; the room relays the refusal to the people editing.+ const charLimit = getDocumentCharLimitErrorData(error);+ if (charLimit) {+ return c.json({ ...charLimit, error: (error as Error).message }, 422);+ }console.error('[document-projection] failed for %s:', body.documentId, error);return c.json({ error: (error as Error).message }, 500);}diff --git a/apps/server/src/services/document/__tests__/writeLimit.service.test.ts b/apps/server/src/services/document/__tests__/writeLimit.service.test.tsindex f0a886d9f61..aae8105a79a 100644--- a/apps/server/src/services/document/__tests__/writeLimit.service.test.ts+++ b/apps/server/src/services/document/__tests__/writeLimit.service.test.ts@@ -149,15 +149,30 @@ describe('DocumentService per-document character limit', () => {expect(documentModel.update).toHaveBeenCalled();});- it('skips room projections', async () => {+ // LOBE-15419: the room accepts browser edits without measuring them, so a+ // projection that grows the page past the limit must not reach the row.+ it('refuses a room projection that grows the page past the limit', async () => {+ refuse();++ await expect(+ service().updateDocument('doc-1', {+ content: 'x'.repeat(20),+ origin: 'room-projection',+ }),+ ).rejects.toMatchObject({ cause: { data: { code: 'DocumentCharLimitExceeded' } } });++ expect(documentModel.update).not.toHaveBeenCalled();+ });++ it('lets a room projection through when a system write grew the page', async () => {refuse();await service().updateDocument('doc-1', {content: 'x'.repeat(20),origin: 'room-projection',+ writeSource: 'system',});- expect(checkDocumentCharLimit).not.toHaveBeenCalled();expect(documentModel.update).toHaveBeenCalled();});diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex b6d8a0c15f1..21247b35987 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -823,15 +823,14 @@ export class DocumentService {const updates: Record<string, unknown> = {};- // Room projections persist what the room already accepted. Checked before- // anything is persisted. `restoreFromHistoryId` is not an exemption: the- // client sends it with a body the server does not match against the- // version, so only server-side restores opt out via `writeSource`.- // Editor data is measured too because it can arrive without `content`.- if (- (params.content !== undefined || editorDataParam !== undefined) &&- params.origin !== 'room-projection'- ) {+ // Checked before anything is persisted. Room projections are checked too:+ // the room accepts browser edits without measuring them, so the+ // projection is the only place a collaborative page's length is enforced+ // (LOBE-15419). `restoreFromHistoryId` is not an exemption: the client+ // sends it with a body the server does not match against the version, so+ // only server-side restores opt out via `writeSource`. Editor data is+ // measured too because it can arrive without `content`.+ if (params.content !== undefined || editorDataParam !== undefined) {await assertDocumentWriteWithinLimit({charCount: Math.max(params.content?.length ?? 0, countEditorDataText(editorDataParam)),previousCharCount: Math.max(diff --git a/apps/server/src/services/document/writeLimit.ts b/apps/server/src/services/document/writeLimit.tsindex 574e64cb752..34f51406f7f 100644--- a/apps/server/src/services/document/writeLimit.ts+++ b/apps/server/src/services/document/writeLimit.ts@@ -62,3 +62,13 @@ export const assertDocumentWriteWithinLimit = async ({message: formatDocumentCharLimitMessage(data),});};++/** Reads the refusal data of an error thrown by {@link assertDocumentWriteWithinLimit}. */+export const getDocumentCharLimitErrorData = (+ error: unknown,+): DocumentCharLimitErrorData | undefined => {+ if (!(error instanceof TRPCError)) return;+ const data = (error.cause as { data?: Partial<DocumentCharLimitErrorData> } | undefined)?.data;+ if (data?.code !== DOCUMENT_CHAR_LIMIT_EXCEEDED || typeof data.limit !== 'number') return;+ return data as DocumentCharLimitErrorData;+};diff --git a/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts b/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.tsindex 013af85dcfc..62f149bf1da 100644--- a/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts+++ b/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts@@ -1,6 +1,8 @@// @vitest-environment node+import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { persistPageState } from '../persist';import { RoomPageSessions } from '../roomSession';import type { PageWriter } from '../session';@@ -66,6 +68,7 @@ describe('RoomPageSessions character limit', () => {beforeEach(() => {pushUpdate.mockReset();fork.editor.export.mockReset();+ vi.mocked(persistPageState).mockReset();});it('refuses a commit that grows the page over the limit and pushes nothing', async () => {@@ -87,4 +90,33 @@ describe('RoomPageSessions character limit', () => {await expect(commitWith('system', 5, 500)).resolves.toBe(true);expect(pushUpdate).toHaveBeenCalledTimes(1);});++ it('persists under the writer source, so a system write is not refused by the projection', async () => {+ await commitWith('system', 5, 500);++ expect(vi.mocked(persistPageState).mock.calls[0][3]).toMatchObject({ writeSource: 'system' });+ });+});++describe('RoomPageSessions.persistAs character limit', () => {+ const openSession = async () => {+ fork.editor.export.mockReturnValue({ markdown: 'x' });+ return (await new RoomPageSessions({} as any, writerOf('user')).openLiveSession('doc_1'))!;+ };++ it('reports a version refused for its length instead of a saved one', async () => {+ const refusal = new TRPCError({+ cause: { data: { actual: 20, code: 'DocumentCharLimitExceeded', limit: 10 } },+ code: 'BAD_REQUEST',+ });+ vi.mocked(persistPageState).mockRejectedValue(refusal);++ await expect((await openSession()).persistAs('manual')).rejects.toBe(refusal);+ });++ it('keeps other persist failures quiet: the room still holds the edit', async () => {+ vi.mocked(persistPageState).mockRejectedValue(new Error('db down'));++ await expect((await openSession()).persistAs('manual')).resolves.toBeUndefined();+ });});diff --git a/apps/server/src/services/pageCollab/persist.ts b/apps/server/src/services/pageCollab/persist.tsindex 86e2f3de7a0..9dec19b55af 100644--- a/apps/server/src/services/pageCollab/persist.ts+++ b/apps/server/src/services/pageCollab/persist.ts@@ -1,5 +1,6 @@import { createHash } from 'node:crypto';+import type { DocumentWriteSource } from '@lobechat/types';import debug from 'debug';import type { LobeChatDatabase } from '@/database/type';@@ -49,7 +50,16 @@ export const persistPageState = async (db: LobeChatDatabase,documentId: string,state: Uint8Array,- options: { history?: DocumentHistoryAttribution; saveSource: DocumentHistorySaveSource },+ options: {+ history?: DocumentHistoryAttribution;+ saveSource: DocumentHistorySaveSource;+ /**+ * Who wrote the room's latest changes; decides whether the per-document+ * character limit applies. The room's own projection carries browser edits,+ * so it defaults to `user`.+ */+ writeSource?: DocumentWriteSource;+ },): Promise<boolean> => {const meta = await getResourceMeta(db, 'document', documentId);if (!meta) return false;@@ -77,6 +87,7 @@ export const persistPageState = async (editorData: editorData as unknown as Record<string, unknown>,history: options.history,origin: 'room-projection',+ writeSource: options.writeSource,...(writtenOutsideRoom? { breakAutosaveWindow: true, saveSource: 'system' as const }: { saveSource: options.saveSource }),diff --git a/apps/server/src/services/pageCollab/roomSession.ts b/apps/server/src/services/pageCollab/roomSession.tsindex 89637ad2786..cd66646a769 100644--- a/apps/server/src/services/pageCollab/roomSession.ts+++ b/apps/server/src/services/pageCollab/roomSession.ts@@ -4,7 +4,10 @@ import * as Y from 'yjs';import type { LobeChatDatabase } from '@/database/type';import { DocumentService } from '@/server/services/document';import type { DocumentHistorySaveSource } from '@/server/services/document/types';-import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';+import {+ assertDocumentWriteWithinLimit,+ getDocumentCharLimitErrorData,+} from '@/server/services/document/writeLimit';import { editorDataFromRow } from './editorData';import { openPageFork, PAGE_META_KEY, type PageFork, readPageTitle } from './fork';@@ -96,11 +99,25 @@ export class RoomPageSessions implements PageSessions {workspaceId: this.writer.workspaceId,});await room.pushUpdate(documentId, fork.diff(), { actor });- await this.persist(documentId, fork);+ try {+ await this.persist(documentId, fork);+ } catch (error) {+ // The room already holds the edit, and its next projection persists it.+ log('persist after commit failed for %s: %O', documentId, error);+ }return true;},draft: fork,- persistAs: (saveSource) => this.persist(documentId, fork, saveSource),+ // A version the user asked for: a body refused for its length must tell+ // them it was not saved, instead of reporting a saved version.+ persistAs: async (saveSource) => {+ try {+ await this.persist(documentId, fork, saveSource);+ } catch (error) {+ if (getDocumentCharLimitErrorData(error)) throw error;+ log('persist as %s failed for %s: %O', saveSource, documentId, error);+ }+ },setTitle: (next) => fork.doc.getMap(PAGE_META_KEY).set('title', next),title,};@@ -114,15 +131,11 @@ export class RoomPageSessions implements PageSessions {fork: PageFork,saveSource: DocumentHistorySaveSource = this.writer.saveSource,) {- try {- await persistPageState(this.db, documentId, Y.encodeStateAsUpdate(fork.doc), {- history: historyAttributionOf(this.writer),- saveSource,- });- } catch (error) {- // The room already holds the edit, and its next projection persists it.- log('persist after commit failed for %s: %O', documentId, error);- }+ await persistPageState(this.db, documentId, Y.encodeStateAsUpdate(fork.doc), {+ history: historyAttributionOf(this.writer),+ saveSource,+ writeSource: this.writer.writeSource,+ });}private async getStoredTitle(documentId: string) {diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.tsindex 19d30f19097..da4baa61ae6 100644--- a/packages/agent-gateway-client/src/mux/types.ts+++ b/packages/agent-gateway-client/src/mux/types.ts@@ -74,8 +74,23 @@ export type MuxDocServerMessage =}| { documentId: string; type: 'doc_update'; update: string }| { documentId: string; seq: number; type: 'doc_ack' }+ /** The room's page is stored again after a `char_limit_exceeded` refusal. */+ | { documentId: string; type: 'doc_char_limit_cleared' }| ({ documentId: string; type: 'doc_awareness' } & MuxDocAwarenessEntry)- | { code: string; documentId: string; message: string; type: 'doc_error' };+ | {+ /**+ * Length the room's page would have, with `code: 'char_limit_exceeded'`:+ * the server refused to store it for the plan's per-page limit.+ */+ actual?: number;+ code: string;+ documentId: string;+ /** Per-page character limit, with `code: 'char_limit_exceeded'`. */+ limit?: number;+ message: string;+ plan?: string;+ type: 'doc_error';+ };export interface DocumentChannelHandler {onMessage: (message: MuxDocServerMessage) => void;diff --git a/src/features/PageEditor/collab/provider.failure.test.ts b/src/features/PageEditor/collab/provider.failure.test.tsindex a5f7e13a9f9..3c587748965 100644--- a/src/features/PageEditor/collab/provider.failure.test.ts+++ b/src/features/PageEditor/collab/provider.failure.test.ts@@ -35,7 +35,13 @@ const synced = () => ({const setup = () => {const room = createMux();- const events = { onAccess: vi.fn(), onFailure: vi.fn(), onStatus: vi.fn() };+ const events = {+ onAccess: vi.fn(),+ onCharLimitCleared: vi.fn(),+ onCharLimitExceeded: vi.fn(),+ onFailure: vi.fn(),+ onStatus: vi.fn(),+ };const provider = new PageCollabProvider('doc_1', new Y.Doc(), room.mux as any, events);provider.connect();room.ready();@@ -68,6 +74,57 @@ describe('PageCollabProvider failures', () => {);});+ // LOBE-15419: the room relays the server's refusal to store an over-limit page.+ it('reports a page refused for its length without failing the join', () => {+ const { events, room } = setup();+ room.deliver(synced());++ room.deliver({+ actual: 501_502,+ code: 'char_limit_exceeded',+ documentId: 'doc_1',+ limit: 500_000,+ message: 'Document is too long',+ plan: 'plus',+ type: 'doc_error',+ });++ expect(events.onCharLimitExceeded).toHaveBeenCalledWith({+ actual: 501_502,+ limit: 500_000,+ plan: 'plus',+ });+ expect(events.onStatus).not.toHaveBeenCalledWith('error');+ expect(events.onFailure).not.toHaveBeenCalled();+ });++ // LOBE-15419: a page already over the limit is stored again once it stops growing.+ it('reports when the server stores a refused page again', () => {+ const { events, room } = setup();+ room.deliver(synced());++ room.deliver({ documentId: 'doc_1', type: 'doc_char_limit_cleared' });++ expect(events.onCharLimitCleared).toHaveBeenCalledTimes(1);+ expect(events.onFailure).not.toHaveBeenCalled();+ });++ it('does not fail a join when the refusal arrives before the first sync', () => {+ const { events, room } = setup();++ room.deliver({+ actual: 20,+ code: 'char_limit_exceeded',+ documentId: 'doc_1',+ limit: 10,+ message: '',+ type: 'doc_error',+ });++ expect(events.onCharLimitExceeded).toHaveBeenCalled();+ expect(events.onFailure).not.toHaveBeenCalled();+ });+it('keeps a view-only member in the room', () => {const { events, room } = setup();diff --git a/src/features/PageEditor/collab/provider.ts b/src/features/PageEditor/collab/provider.tsindex ba97a38b65b..40f8e0fc50a 100644--- a/src/features/PageEditor/collab/provider.ts+++ b/src/features/PageEditor/collab/provider.ts@@ -31,9 +31,29 @@ export const PAGE_ROOM_SYNC_TIMEOUT_MS = 10_000;export const AWARENESS_RENEW_INTERVAL_MS = 15_000;export const AWARENESS_TIMEOUT_MS = 30_000;+/** The server refused to store the room's page for the plan's per-page character limit. */+export interface PageCollabCharLimitRefusal {+ actual: number;+ limit: number;+ plan?: string;+}++/** `doc_error` code the room sends when the server refuses its page for its length. */+export const PAGE_ROOM_CHAR_LIMIT_CODE = 'char_limit_exceeded';+export interface PageCollabProviderEvents {onAccess?: (access: PageCollabAccess) => void;onBootstrap?: () => void;+ /**+ * The server stored the room's page again after refusing it. A page already+ * over the limit is stored when it does not grow, so only the server knows.+ */+ onCharLimitCleared?: () => void;+ /**+ * The page grew past the plan's per-page limit: the room keeps the edits, but+ * the stored page stays at its last accepted version until it is shortened.+ */+ onCharLimitExceeded?: (refusal: PageCollabCharLimitRefusal) => void;onFailure?: (failure: PageCollabFailure) => void;onPendingChange?: (pending: number) => void;onReset?: (reason: PageCollabResetReason) => void;@@ -344,6 +364,11 @@ export class PageCollabProvider extends Emitter {return;}+ case 'doc_char_limit_cleared': {+ this.events.onCharLimitCleared?.();+ return;+ }+case 'doc_error': {// Our doc now holds a second copy of the page; the room refuses it until we rejoin with a fresh one.if (message.code === 'bootstrap_conflict') {@@ -353,6 +378,19 @@ export class PageCollabProvider extends Emitter {}return;}+ // Not a join failure: the room still syncs, only storing the page is refused.+ if (message.code === PAGE_ROOM_CHAR_LIMIT_CODE) {+ if (typeof message.limit === 'number') {+ this.events.onCharLimitExceeded?.({+ actual: message.actual ?? 0,+ limit: message.limit,+ plan: message.plan,+ });+ } else {+ console.warn('[PageCollabProvider] char limit refusal without a limit', message);+ }+ return;+ }// A view-only member is still in the room; only their writes are refused.if (message.code === 'read_only' || message.code === 'forbidden') {this.events.onAccess?.('view');diff --git a/src/features/PageEditor/collab/usePageCollab.ts b/src/features/PageEditor/collab/usePageCollab.tsindex a52e90df82d..ba3795ad8cf 100644--- a/src/features/PageEditor/collab/usePageCollab.ts+++ b/src/features/PageEditor/collab/usePageCollab.ts@@ -86,6 +86,10 @@ export const usePageCollab = (documentId: string | undefined, onReset?: () => voconst editor = storeApi.getState().editor;if (editor) void useDocumentStore.getState().onEditorInit(editor, documentId!);},+ // Like a refused autosave: the banner and save status say it, without a toast.+ onCharLimitExceeded: (refusal) =>+ useDocumentStore.getState().setCharLimitRefusal(documentId!, refusal),+ onCharLimitCleared: () => useDocumentStore.getState().clearCharLimitRefusal(documentId!),onPendingChange: (pending) => setCollab({ pending }),onReset: (reason) => {const editor = storeApi.getState().editor;diff --git a/src/store/document/slices/editor/action.charLimit.test.ts b/src/store/document/slices/editor/action.charLimit.test.tsindex 259c9409754..260594cee36 100644--- a/src/store/document/slices/editor/action.charLimit.test.ts+++ b/src/store/document/slices/editor/action.charLimit.test.ts@@ -11,6 +11,7 @@ vi.mock('@/services/document', () => ({documentService: {acquireDocumentLock: vi.fn().mockResolvedValue({ holderId: null, lockedByOther: false }),releaseDocumentLock: vi.fn().mockResolvedValue(undefined),+ snapshotPageVersion: vi.fn().mockResolvedValue(true),getDocumentById: vi.fn().mockResolvedValue({content: '# Test',id: 'doc-1',@@ -172,4 +173,103 @@ describe('DocumentStore - Editor Actions (plan character limit)', () => {plan: 'free',});});++ // LOBE-15419: a room page's body never goes through performSave, so the room+ // relays the server's refusal and the page shows it the same way.+ describe('room pages', () => {+ const roomRefusal = { actual: 501_502, limit: 500_000, plan: 'plus' };++ const initRoomDoc = (result: { current: ReturnType<typeof useDocumentStore.getState> }) => {+ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ });+ result.current.setDocumentCollab('doc-1', true);+ });+ };++ it('fails the save status and stores the refusal the room relayed', () => {+ const { result } = renderHook(() => useDocumentStore());+ initRoomDoc(result);++ act(() => result.current.setCharLimitRefusal('doc-1', roomRefusal));++ const doc = result.current.documents['doc-1'];+ expect(doc.saveStatus).toBe('failed');+ expect(doc.charLimitError).toEqual(roomRefusal);+ expect(toast.error).not.toHaveBeenCalled();+ });++ it('clears the refusal once the page is back within the limit', () => {+ const { result } = renderHook(() => useDocumentStore());+ initRoomDoc(result);+ act(() => result.current.setCharLimitRefusal('doc-1', roomRefusal));++ act(() => result.current.handleContentChange());++ const doc = result.current.documents['doc-1'];+ expect(doc.charLimitError).toBeUndefined();+ expect(doc.saveStatus).toBe('idle');+ });++ it('keeps the refusal while the page is still over the limit', () => {+ const { result } = renderHook(() => useDocumentStore());+ initRoomDoc(result);+ act(() => result.current.setCharLimitRefusal('doc-1', { actual: 6, limit: 3 }));++ act(() => result.current.handleContentChange());++ expect(result.current.documents['doc-1'].saveStatus).toBe('failed');+ });++ // LOBE-15419: a page already over the limit is stored once it stops growing,+ // while it is still longer than the limit.+ it('clears the refusal when the server stores the still over-limit page', () => {+ const { result } = renderHook(() => useDocumentStore());+ initRoomDoc(result);+ act(() => result.current.setCharLimitRefusal('doc-1', { actual: 6, limit: 3 }));+ act(() => result.current.handleContentChange());++ act(() => result.current.clearCharLimitRefusal('doc-1'));++ const doc = result.current.documents['doc-1'];+ expect(doc.charLimitError).toBeUndefined();+ expect(doc.saveStatus).toBe('saved');+ });++ it('clears the refusal when a manual version of the over-limit page is stored', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initRoomDoc(result);+ act(() => result.current.setCharLimitRefusal('doc-1', { actual: 6, limit: 3 }));+ vi.mocked(documentService.snapshotPageVersion).mockResolvedValueOnce(undefined as any);++ await act(async () => {+ await result.current.saveVersion('doc-1');+ });++ const doc = result.current.documents['doc-1'];+ expect(doc.charLimitError).toBeUndefined();+ expect(doc.saveStatus).toBe('saved');+ });++ it('tells the user why a manual save of the room did nothing', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initRoomDoc(result);+ vi.mocked(documentService.snapshotPageVersion).mockRejectedValueOnce(limitError());++ await act(async () => {+ await result.current.saveVersion('doc-1');+ });++ expect(toast.error).toHaveBeenCalledTimes(1);+ expect(result.current.documents['doc-1'].charLimitError).toEqual({+ actual: 120,+ limit: 100,+ plan: 'free',+ });+ });+ });});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex 5ccbd006e19..b4c7b38fb39 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -16,7 +16,11 @@ import { setNamespace } from '@/utils/storeDebug';import { PAGE_SYNC_WAIT_MS, waitForPageSynced } from '../../collabRegistry';import type { DocumentStore } from '../../store';import { documentDetailResource } from '../document/projection';-import { getCharLimitRefusal, notifyCharLimitRefused } from './charLimit';+import {+ type DocumentCharLimitRefusal,+ getCharLimitRefusal,+ notifyCharLimitRefused,+} from './charLimit';import type { DocumentFormatFields } from './contentFormat';import { hasDocumentFormatFields, resolveDocumentContentFormat } from './contentFormat';import type { EditorContentState } from './initialState';@@ -112,6 +116,9 @@ export class EditorActionImpl {const editorData = editor.getDocument('json');if (doc.collab) {+ // The room persists the body on its own and reports only refusals, so+ // a page shortened back within the refused limit is saved again.+ const backWithinLimit = !!doc.charLimitError && markdown.length <= doc.charLimitError.limit;internal_dispatchDocument({id,@@ -122,6 +129,9 @@ export class EditorActionImpl {isDirty: false,lastSavedContent: markdown,lastSavedEditorData: editorData,+ ...(backWithinLimit+ ? { charLimitError: undefined, saveStatus: 'idle' as const }+ : {}),},},'handleContentChange/collab',@@ -281,7 +291,53 @@ export class EditorActionImpl {}await waitForPageSynced(documentId, PAGE_SYNC_WAIT_MS);- await documentService.snapshotPageVersion(documentId, 'manual');+ try {+ await documentService.snapshotPageVersion(documentId, 'manual');+ // The version stored the room's page, which may still be over the limit when it did not grow.+ this.#get().clearCharLimitRefusal(documentId);+ } catch (error) {+ const refusal = getCharLimitRefusal(+ error,+ (this.#get().documents[documentId]?.content ?? '').length,+ );+ if (!refusal) throw error;+ this.#get().setCharLimitRefusal(documentId, refusal);+ notifyCharLimitRefused(refusal);+ }+ };++ /**+ * The server stored a room page it had refused for its length. A page already+ * over the limit is stored once it does not grow, so the client cannot tell+ * this from the length alone.+ */+ clearCharLimitRefusal = (documentId: string): void => {+ if (!this.#get().documents[documentId]?.charLimitError) return;+ this.#get().internal_dispatchDocument(+ {+ id: documentId,+ type: 'updateDocument',+ value: { charLimitError: undefined, saveStatus: 'saved' },+ },+ n('clearCharLimitRefusal'),+ );+ };++ /**+ * Marks a room page as refused for the plan's per-page character limit: its+ * room keeps the edits, but the stored page stays at its last accepted+ * version until the page is shortened.+ */+ setCharLimitRefusal = (documentId: string, refusal: DocumentCharLimitRefusal): void => {+ if (!this.#get().documents[documentId]) return;+ this.#get().internal_dispatchDocument(+ {+ id: documentId,+ type: 'updateDocument',+ value: { charLimitError: refusal, saveStatus: 'failed' },+ },+ n('setCharLimitRefusal'),+ );};/**