Skip to content

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

🐛 fix(page-collab): keep one Yjs tree per page with durable rooms and conditional server writes (#22695)

Innei3e750d654b4b
diff --git a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
index 8ef5368900e..1bee21212d0 100644
--- a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
+++ b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
@@ -20,6 +20,8 @@ interface MockGlobalConfigOptions {
agentGatewayUrl?: string;
appUrl?: string;
enableAgentGateway?: boolean;
+ enablePageCollab?: boolean;
+ enableWorkspacePageCollab?: boolean;
toolNameMaxLengthEnv?: string;
}
@@ -49,6 +51,9 @@ const mockGlobalConfigDependencies = (
...(options.enableAgentGateway === undefined
? {}
: { ENABLE_AGENT_GATEWAY: options.enableAgentGateway }),
+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',
+ ENABLE_PAGE_COLLAB: options.enablePageCollab,
+ ENABLE_WORKSPACE_PAGE_COLLAB: options.enableWorkspacePageCollab,
},
getAppConfig: vi.fn(() => ({
DEFAULT_AGENT_CONFIG: '',
@@ -205,6 +210,17 @@ describe('getServerGlobalConfig', () => {
});
});
+ it('should tell clients which page collaboration flag is on', async () => {
+ const gateway = { agentGatewayUrl: 'https://gateway.test.com' };
+
+ await expect(
+ loadServerConfig(true, { ...gateway, enableWorkspacePageCollab: true }),
+ ).resolves.toMatchObject({ enablePageCollab: false, enableWorkspacePageCollab: true });
+ await expect(
+ loadServerConfig(true, { ...gateway, enablePageCollab: true }),
+ ).resolves.toMatchObject({ enablePageCollab: true, enableWorkspacePageCollab: false });
+ });
+
it('should declare gateway protocol 2 only where the v2 socket exists', async () => {
// The business gateway serves `/v2/ws`; `lobehub/lobehub-gateway`, which is
// what a self-hosted deployment runs, serves only `/ws`.
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index 7f654c3fdd6..d3b018d3837 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -19,7 +19,10 @@ import { parseSSOProviders } from '@/libs/better-auth/utils/server';
import { OIDC_ISSUER_PATH } from '@/libs/oidc-provider/routes';
import { parseSystemAgent } from '@/server/globalConfig/parseSystemAgent';
import { isLlmRelayDeploymentReady } from '@/server/modules/AgentRuntime/llmRelay/deployment';
-import { isPageCollabEnabled } from '@/server/services/pageCollab/config';
+import {
+ isLegacyPageCollabEnabled,
+ isWorkspacePageCollabEnabled,
+} from '@/server/services/pageCollab/config';
import { getSandboxDeployment } from '@/server/services/sandbox/deployment';
import { type GlobalServerConfig } from '@/types/serverConfig';
import { cleanObject } from '@/utils/object';
@@ -184,8 +187,9 @@ export const getServerGlobalConfig = async () => {
enableMarketTrustedClient: !!(
appEnv.MARKET_TRUSTED_CLIENT_SECRET && appEnv.MARKET_TRUSTED_CLIENT_ID
),
- enablePageCollab: enableGatewayMode && isPageCollabEnabled(),
+ enablePageCollab: enableGatewayMode && isLegacyPageCollabEnabled(),
enableUploadFileToServer: !!fileEnv.S3_SECRET_ACCESS_KEY,
+ enableWorkspacePageCollab: enableGatewayMode && isWorkspacePageCollabEnabled(),
enableMultimodalUnderstanding: !!(
toolsEnv.MULTIMODAL_UNDERSTANDING_PROVIDER && toolsEnv.MULTIMODAL_UNDERSTANDING_MODEL
),
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.ts
index a2d1d32a8e0..4e1e58e9cad 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
@@ -1,25 +1,45 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { documentAccess, documentProjection } from '../documentCollab';
+import {
+ documentAccess,
+ documentProjection,
+ documentRoomStatus,
+ documentSeed,
+} from '../documentCollab';
-const { persistPageState, resolvePageAccess } = vi.hoisted(() => ({
- persistPageState: vi.fn(),
- resolvePageAccess: vi.fn(),
-}));
+const { buildPageSeed, getPageRoomStatus, persistPageState, resolveRoomAccess } = vi.hoisted(
+ () => ({
+ buildPageSeed: vi.fn(),
+ getPageRoomStatus: vi.fn(),
+ persistPageState: vi.fn(),
+ resolveRoomAccess: vi.fn(),
+ }),
+);
+
+vi.mock('@/server/services/pageCollab/seed', () => ({ buildPageSeed, getPageRoomStatus }));
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: async () => ({}) }));
-vi.mock('@/server/services/pageCollab', () => ({ persistPageState, resolvePageAccess }));
+vi.mock('@/server/services/pageCollab', () => ({ persistPageState, resolveRoomAccess }));
-const buildContext = (options: { body?: unknown; query?: Record<string, string> }) =>
- ({
+const buildContext = (options: {
+ body?: unknown;
+ bytes?: Uint8Array;
+ headers?: Record<string, string>;
+ query?: Record<string, string>;
+}) => {
+ const headers = new Headers(options.headers);
+ return {
json: (b: any, status = 200) => Response.json(b, { status }),
req: {
+ arrayBuffer: async () => options.bytes?.slice().buffer ?? new ArrayBuffer(0),
+ header: (name: string) => headers.get(name) ?? undefined,
json: async () => options.body,
query: (name: string) => options.query?.[name],
},
- }) as any;
+ } as any;
+};
describe('documentAccess', () => {
beforeEach(() => vi.clearAllMocks());
@@ -28,18 +48,18 @@ describe('documentAccess', () => {
const res = await documentAccess(buildContext({ query: { documentId: 'doc_1' } }));
expect(res.status).toBe(400);
- expect(resolvePageAccess).not.toHaveBeenCalled();
+ expect(resolveRoomAccess).not.toHaveBeenCalled();
});
it('returns the user access to the page', async () => {
- resolvePageAccess.mockResolvedValue('view');
+ resolveRoomAccess.mockResolvedValue('view');
const res = await documentAccess(
buildContext({ query: { documentId: 'doc_1', userId: 'u1' } }),
);
expect(await res.json()).toEqual({ access: 'view' });
- expect(resolvePageAccess).toHaveBeenCalledWith({}, 'u1', 'doc_1');
+ expect(resolveRoomAccess).toHaveBeenCalledWith({}, 'u1', 'doc_1');
});
});
@@ -79,17 +99,70 @@ describe('documentProjection', () => {
});
});
- it('answers 404 for a page that no longer exists', async () => {
+ it('answers 404 DOCUMENT_NOT_FOUND for a page that no longer exists', async () => {
persistPageState.mockResolvedValue(false);
- expect((await project({ documentId: 'doc_1', update: '' })).status).toBe(404);
+ const res = await project({ documentId: 'doc_1', update: '' });
+
+ expect(res.status).toBe(404);
+ expect(await res.json()).toMatchObject({ code: 'DOCUMENT_NOT_FOUND' });
});
- it('answers 409 when the projection would erase blocks the room holds', async () => {
+ it('answers 409 PROJECTION_REJECTED when the projection would erase blocks the room holds', async () => {
const { PageProjectionRejectedError } = await import('@/server/services/pageCollab/persist');
persistPageState.mockRejectedValue(new PageProjectionRejectedError('doc_1'));
- expect((await project({ documentId: 'doc_1', update: '' })).status).toBe(409);
+ const res = await project({ documentId: 'doc_1', update: '' });
+
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'PROJECTION_REJECTED' });
+ });
+
+ it('persists a binary room state sent with its document, epoch and actors outside the body', async () => {
+ const res = await documentProjection(
+ buildContext({
+ bytes: new Uint8Array([4, 5, 6]),
+ headers: {
+ 'Content-Type': 'application/octet-stream',
+ 'X-Room-Actors': JSON.stringify(['u1', 'agent:u1']),
+ 'X-Room-Size-Bytes': '3',
+ },
+ query: { documentId: 'doc_1', epoch: 'e1' },
+ }),
+ );
+
+ expect(res.status).toBe(200);
+ expect(persistPageState).toHaveBeenCalledWith({}, 'doc_1', new Uint8Array([4, 5, 6]), {
+ history: { editorIds: ['u1'] },
+ saveSource: 'autosave',
+ });
+ });
+
+ it('requires a document for a binary projection', async () => {
+ const res = await documentProjection(
+ buildContext({
+ bytes: new Uint8Array([4]),
+ headers: { 'Content-Type': 'application/octet-stream' },
+ query: {},
+ }),
+ );
+
+ expect(res.status).toBe(400);
+ expect(persistPageState).not.toHaveBeenCalled();
+ });
+
+ it('answers 413 DOC_TOO_LARGE for a room state over what a projection may carry', async () => {
+ const res = await documentProjection(
+ buildContext({
+ bytes: new Uint8Array(4 * 1024 * 1024 + 1),
+ headers: { 'Content-Type': 'application/octet-stream' },
+ query: { documentId: 'doc_1' },
+ }),
+ );
+
+ expect(res.status).toBe(413);
+ expect(await res.json()).toMatchObject({ code: 'DOC_TOO_LARGE' });
+ expect(persistPageState).not.toHaveBeenCalled();
});
it('answers 422 with the limit when the room grew the page past it', async () => {
@@ -121,3 +194,64 @@ describe('documentProjection', () => {
});
});
});
+
+describe('documentSeed', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ const seed = (documentId?: string) =>
+ documentSeed(buildContext({ query: documentId ? { documentId } : {} }));
+
+ it('requires a document', async () => {
+ expect((await seed()).status).toBe(400);
+ });
+
+ it('returns the seed as binary Yjs with the page workspace', async () => {
+ buildPageSeed.mockResolvedValue({
+ status: 'ok',
+ update: new Uint8Array([7, 8, 9]),
+ workspaceId: 'ws_1',
+ });
+
+ const res = await seed('doc_1');
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get('Content-Type')).toBe('application/octet-stream');
+ expect(res.headers.get('X-Workspace-Id')).toBe('ws_1');
+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([7, 8, 9]));
+ });
+
+ it('answers 404 DOCUMENT_NOT_FOUND for a missing page', async () => {
+ buildPageSeed.mockResolvedValue({ status: 'not_found' });
+
+ const res = await seed('doc_1');
+
+ expect(res.status).toBe(404);
+ expect(await res.json()).toMatchObject({ code: 'DOCUMENT_NOT_FOUND' });
+ });
+
+ it('answers 403 ROOM_NOT_ALLOWED for a page outside any workspace', async () => {
+ buildPageSeed.mockResolvedValue({ status: 'not_allowed' });
+
+ const res = await seed('doc_1');
+
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: 'ROOM_NOT_ALLOWED' });
+ });
+});
+
+describe('documentRoomStatus', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('requires a document', async () => {
+ expect((await documentRoomStatus(buildContext({ query: {} }))).status).toBe(400);
+ });
+
+ it('returns whether the page exists and is in a workspace', async () => {
+ getPageRoomStatus.mockResolvedValue({ exists: true, inWorkspace: false, workspaceId: null });
+
+ const res = await documentRoomStatus(buildContext({ query: { documentId: 'doc_1' } }));
+
+ expect(await res.json()).toEqual({ exists: true, inWorkspace: false, workspaceId: null });
+ expect(getPageRoomStatus).toHaveBeenCalledWith({}, 'doc_1');
+ });
+});
diff --git a/apps/server/src/router-hono/agent/handlers/documentCollab.ts b/apps/server/src/router-hono/agent/handlers/documentCollab.ts
index b0847b401e0..00fd3a28740 100644
--- a/apps/server/src/router-hono/agent/handlers/documentCollab.ts
+++ b/apps/server/src/router-hono/agent/handlers/documentCollab.ts
@@ -3,9 +3,10 @@ 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 { persistPageState, resolveRoomAccess } from '@/server/services/pageCollab';
import { PageProjectionRejectedError } from '@/server/services/pageCollab/persist';
import { fromBase64 } from '@/server/services/pageCollab/roomClient';
+import { buildPageSeed, getPageRoomStatus } from '@/server/services/pageCollab/seed';
const log = debug('lobe-server:agent:document-collab');
@@ -14,35 +15,105 @@ export async function documentAccess(c: Context): Promise<Response> {
const userId = c.req.query('userId');
if (!documentId || !userId) return c.json({ error: 'documentId and userId are required' }, 400);
- const access = await resolvePageAccess(await getServerDB(), userId, documentId);
+ const access = await resolveRoomAccess(await getServerDB(), userId, documentId);
return c.json({ access });
}
-export async function documentProjection(c: Context): Promise<Response> {
+export async function documentSeed(c: Context): Promise<Response> {
+ const documentId = c.req.query('documentId');
+ if (!documentId) return c.json({ code: 'INVALID', error: 'documentId is required' }, 400);
+
+ const seed = await buildPageSeed(await getServerDB(), documentId);
+ if (seed.status !== 'ok') {
+ return seed.status === 'not_found'
+ ? c.json({ code: 'DOCUMENT_NOT_FOUND', error: 'Document not found' }, 404)
+ : c.json({ code: 'ROOM_NOT_ALLOWED', error: 'Only workspace pages have rooms' }, 403);
+ }
+ return new Response(Buffer.from(seed.update), {
+ headers: { 'Content-Type': 'application/octet-stream', 'X-Workspace-Id': seed.workspaceId },
+ });
+}
+
+export async function documentRoomStatus(c: Context): Promise<Response> {
+ const documentId = c.req.query('documentId');
+ if (!documentId) return c.json({ code: 'INVALID', error: 'documentId is required' }, 400);
+
+ return c.json(await getPageRoomStatus(await getServerDB(), documentId));
+}
+
+// Above this a projection could not have passed the platform's request cap
+// anyway; the room's own cap is lower.
+const MAX_PROJECTION_BYTES = 4 * 1024 * 1024;
+const PROJECTION_SIZE_WARNING_BYTES = 1.5 * 1024 * 1024;
+
+interface ProjectionRequest {
+ actors?: unknown;
+ documentId?: string;
+ epoch?: string;
+ sizeBytes?: number;
+ update?: Uint8Array;
+}
+
+const parseActors = (value: string | undefined) => {
+ if (!value) return undefined;
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return undefined;
+ }
+};
+
+// The room sends binary Yjs; a room released before that sends base64 JSON.
+const readProjection = async (c: Context): Promise<ProjectionRequest> => {
+ if (c.req.header('Content-Type')?.startsWith('application/octet-stream')) {
+ const sizeHeader = Number(c.req.header('X-Room-Size-Bytes'));
+ return {
+ actors: parseActors(c.req.header('X-Room-Actors')),
+ documentId: c.req.query('documentId'),
+ epoch: c.req.query('epoch'),
+ sizeBytes: Number.isFinite(sizeHeader) ? sizeHeader : undefined,
+ update: new Uint8Array(await c.req.arrayBuffer()),
+ };
+ }
+
const body = (await c.req.json().catch(() => null)) as {
- /** Users whose updates reached the room since its last projection. */
actors?: unknown;
documentId?: string;
epoch?: string;
- update?: string;
+ update?: unknown;
} | null;
- if (!body?.documentId || typeof body.update !== 'string') {
- return c.json({ error: 'documentId and update are required' }, 400);
+ return {
+ actors: body?.actors,
+ documentId: body?.documentId,
+ epoch: body?.epoch,
+ update: typeof body?.update === 'string' ? fromBase64(body.update) : undefined,
+ };
+};
+
+export async function documentProjection(c: Context): Promise<Response> {
+ const { actors, documentId, epoch, sizeBytes, update } = await readProjection(c);
+ if (!documentId || !update) {
+ return c.json({ code: 'INVALID', error: 'documentId and update are required' }, 400);
+ }
+ if (update.byteLength > MAX_PROJECTION_BYTES) {
+ return c.json({ code: 'DOC_TOO_LARGE', error: 'Room state is too large to project' }, 413);
+ }
+ const roomBytes = sizeBytes ?? update.byteLength;
+ if (roomBytes >= PROJECTION_SIZE_WARNING_BYTES) {
+ console.warn('[document-projection] room %s holds %d bytes', documentId, roomBytes);
}
try {
- const projected = await persistPageState(
- await getServerDB(),
- body.documentId,
- fromBase64(body.update),
- { history: { editorIds: roomEditorIds(body.actors) }, saveSource: 'autosave' },
- );
- if (!projected) return c.json({ error: 'Document not found' }, 404);
+ const projected = await persistPageState(await getServerDB(), documentId, update, {
+ history: { editorIds: roomEditorIds(actors) },
+ saveSource: 'autosave',
+ });
+ if (!projected) return c.json({ code: 'DOCUMENT_NOT_FOUND', error: 'Document not found' }, 404);
return c.json({ ok: true });
} catch (error) {
- log('projection failed for %s (epoch %s): %O', body.documentId, body.epoch, error);
+ log('projection failed for %s (epoch %s): %O', documentId, epoch, error);
if (error instanceof PageProjectionRejectedError) {
- return c.json({ error: error.message }, 409);
+ return c.json({ code: 'PROJECTION_REJECTED', 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.
@@ -50,8 +121,8 @@ export async function documentProjection(c: Context): Promise<Response> {
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);
+ console.error('[document-projection] failed for %s:', documentId, error);
+ return c.json({ code: 'INTERNAL', error: (error as Error).message }, 500);
}
}
diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.ts
index 3751b5f7ddf..f35f65a12b4 100644
--- a/apps/server/src/router-hono/agent/index.ts
+++ b/apps/server/src/router-hono/agent/index.ts
@@ -7,7 +7,12 @@ import { botCallback } from './handlers/botCallback';
import { botReplay } from './handlers/botReplay';
import { botWakeFlush } from './handlers/botWakeFlush';
import { channelAdvance, channelCallback } from './handlers/channel';
-import { documentAccess, documentProjection } from './handlers/documentCollab';
+import {
+ documentAccess,
+ documentProjection,
+ documentRoomStatus,
+ documentSeed,
+} from './handlers/documentCollab';
import { execAgent } from './handlers/execAgent';
import { finalizeAbandoned } from './handlers/finalizeAbandoned';
import { gatewayCallback } from './handlers/gatewayCallback';
@@ -64,6 +69,8 @@ app.get('/llm-relay/:callId/payload', llmRelayPayload);
app.post('/llm-relay/:callId/chunks', llmRelayChunks);
app.get('/document-access', serviceTokenAuth(), documentAccess);
app.post('/document-projection', serviceTokenAuth(), documentProjection);
+app.post('/document-seed', serviceTokenAuth(), documentSeed);
+app.get('/document-room-status', serviceTokenAuth(), documentRoomStatus);
// POST /api/agent/finalize-abandoned — watchdog reverse-trigger finalize
app.post('/finalize-abandoned', serviceTokenAuth(), finalizeAbandoned);
diff --git a/apps/server/src/routers/lambda/__tests__/document.test.ts b/apps/server/src/routers/lambda/__tests__/document.test.ts
index f20fbdd121d..ef8f631d24f 100644
--- a/apps/server/src/routers/lambda/__tests__/document.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/document.test.ts
@@ -6,6 +6,7 @@ import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';
import { TransferErrorCode } from '@/types/transferError';
const mocks = vi.hoisted(() => ({
+ dropPageRooms: vi.fn(),
assertContentsNotInRestrictedKnowledgeBase: vi.fn(),
assertCanEditResource: vi.fn(),
assertCanPerformResourceAction: vi.fn(),
@@ -32,6 +33,8 @@ const mocks = vi.hoisted(() => ({
vi.mock('@/business/server/document-mention/notifyActivity', () => ({
notifyDocumentMention: mocks.notifyDocumentMention,
}));
+vi.mock('@/server/services/pageCollab/notify', () => ({ dropPageRooms: mocks.dropPageRooms }));
+
vi.mock('@/database/models/rbac', () => ({
RbacModel: { getWorkspaceUsersPermissions: mocks.getWorkspaceUsersPermissions },
}));
@@ -152,6 +155,20 @@ describe('documentRouter transferDocument', () => {
});
});
+ it('drops the rooms of pages moved out of the workspace', async () => {
+ mocks.transferTo.mockResolvedValueOnce({ documentIds: ['doc-1', 'doc-2'], fileIds: [] });
+ const caller = documentRouter.createCaller({
+ serverDB: {},
+ userId: 'member-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'owner',
+ } as any);
+
+ await caller.transferDocument({ documentId: 'doc-1', targetWorkspaceId: null });
+
+ expect(mocks.dropPageRooms).toHaveBeenCalledWith(['doc-1', 'doc-2']);
+ });
+
it("lets a member move another creator's visible document between visible parents", async () => {
const caller = documentRouter.createCaller({
serverDB: {},
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 70e8d29b891..b67e2a7019d 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -26,6 +26,7 @@ import {
snapshotPageThroughRoom,
updateDocumentThroughRoom,
} from '@/server/services/pageCollab/bodyWriter';
+import { dropPageRooms } from '@/server/services/pageCollab/notify';
import {
assertCanPerformResourceAction,
buildResourcePermissionState,
@@ -758,6 +759,7 @@ export const documentRouter = router({
result.documentIds.map((id) => sourcePermissionModel.removeAll('document', id)),
);
}
+ if (ctx.workspaceId && !input.targetWorkspaceId) dropPageRooms(result.documentIds);
if (input.targetWorkspaceId && input.targetVisibility === 'public') {
const targetPermissionModel = new ResourcePermissionModel(
ctx.serverDB,
diff --git a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts
index 6dfda8cd17b..3814717b622 100644
--- a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts
+++ b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
| undefined
>
>(),
+ assertCanWriteBody: vi.fn<(id: string, lockOwnerId?: string) => Promise<void>>(),
runWithDocumentLock: vi.fn(function <T>(_id: string, fn: (lockOwnerId?: string) => Promise<T>) {
return fn('server:lock-owner');
}),
diff --git a/apps/server/src/services/document/__tests__/assertCanWriteBody.test.ts b/apps/server/src/services/document/__tests__/assertCanWriteBody.test.ts
new file mode 100644
index 00000000000..0a0587e275d
--- /dev/null
+++ b/apps/server/src/services/document/__tests__/assertCanWriteBody.test.ts
@@ -0,0 +1,64 @@
+import { type LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DocumentModel } from '@/database/models/document';
+import { FileModel } from '@/database/models/file';
+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
+
+import { DocumentService } from '../index';
+
+const lock = vi.hoisted(() => ({ canWrite: vi.fn() }));
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));
+vi.mock('@/database/models/document');
+vi.mock('@/database/models/file');
+vi.mock('@/database/models/knowledgeBase');
+vi.mock('../../file');
+vi.mock('../history');
+vi.mock('../../editLock', () => ({
+ EditLockService: class {
+ canWrite = lock.canWrite;
+ },
+}));
+
+describe('DocumentService.assertCanWriteBody', () => {
+ const documentModel = { findById: vi.fn() };
+
+ beforeEach(() => {
+ lock.canWrite.mockReset();
+ documentModel.findById.mockResolvedValue({ visibility: 'public', workspaceId: 'ws-1' });
+ vi.mocked(DocumentModel).mockImplementation(function () {
+ return documentModel as any;
+ });
+ vi.mocked(FileModel).mockImplementation(function () {
+ return {} as any;
+ });
+ vi.mocked(KnowledgeBaseModel).mockImplementation(function () {
+ return {} as any;
+ });
+ });
+
+ const service = () => new DocumentService({} as LobeChatDatabase, 'user-1', 'ws-1');
+
+ it('refuses a workspace page whose lock another session holds', async () => {
+ lock.canWrite.mockResolvedValue(false);
+
+ await expect(service().assertCanWriteBody('doc-1', 'page:doc-1:b')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(lock.canWrite).toHaveBeenCalledWith('document', 'doc-1', 'page:doc-1:b');
+ });
+
+ it('allows the session that holds the lock', async () => {
+ lock.canWrite.mockResolvedValue(true);
+
+ await expect(service().assertCanWriteBody('doc-1', 'page:doc-1:b')).resolves.toBeUndefined();
+ });
+
+ it('skips the lock on a private page, which has no collaborators', async () => {
+ documentModel.findById.mockResolvedValue({ visibility: 'private', workspaceId: 'ws-1' });
+
+ await expect(service().assertCanWriteBody('doc-1', 'page:doc-1:b')).resolves.toBeUndefined();
+ expect(lock.canWrite).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/document/__tests__/deleteDocument.rooms.test.ts b/apps/server/src/services/document/__tests__/deleteDocument.rooms.test.ts
new file mode 100644
index 00000000000..897ac6b56c7
--- /dev/null
+++ b/apps/server/src/services/document/__tests__/deleteDocument.rooms.test.ts
@@ -0,0 +1,60 @@
+import { type LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DocumentModel } from '@/database/models/document';
+import { FileModel } from '@/database/models/file';
+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
+
+import { dropPageRooms } from '../../pageCollab/notify';
+import { DocumentService } from '../index';
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));
+vi.mock('@/database/models/document');
+vi.mock('@/database/models/file');
+vi.mock('@/database/models/knowledgeBase');
+vi.mock('../../file');
+vi.mock('../history');
+vi.mock('../../pageCollab/notify', () => ({ dropPageRooms: vi.fn() }));
+
+describe('DocumentService.deleteDocument — collaboration rooms', () => {
+ const documentModel = { delete: vi.fn(), findById: vi.fn() };
+
+ beforeEach(() => {
+ vi.mocked(dropPageRooms).mockClear();
+ vi.mocked(DocumentModel).mockImplementation(function () {
+ return documentModel as any;
+ });
+ vi.mocked(FileModel).mockImplementation(function () {
+ return {} as any;
+ });
+ vi.mocked(KnowledgeBaseModel).mockImplementation(function () {
+ return {} as any;
+ });
+ });
+
+ it('drops the collaboration room of a deleted workspace page', async () => {
+ documentModel.findById.mockResolvedValue({
+ fileId: null,
+ fileType: 'custom/document',
+ id: 'doc-1',
+ workspaceId: 'ws-1',
+ });
+
+ await new DocumentService({} as LobeChatDatabase, 'user-1', 'ws-1').deleteDocument('doc-1');
+
+ expect(vi.mocked(dropPageRooms)).toHaveBeenCalledWith(['doc-1']);
+ });
+
+ it('leaves rooms alone when deleting a personal page', async () => {
+ documentModel.findById.mockResolvedValue({
+ fileId: null,
+ fileType: 'custom/document',
+ id: 'doc-1',
+ workspaceId: null,
+ });
+
+ await new DocumentService({} as LobeChatDatabase, 'user-1').deleteDocument('doc-1');
+
+ expect(vi.mocked(dropPageRooms)).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index b06a15f759d..5cd223190fc 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -32,6 +32,7 @@ import { type LobeDocument } from '@/types/document';
import { EditLockService } from '../editLock';
import { FileService } from '../file';
+import { dropPageRooms } from '../pageCollab/notify';
import { publishResourceEvent } from '../resourceEvents';
import { countEditorDataText } from './editorData';
import { DocumentHistoryService } from './history';
@@ -188,6 +189,17 @@ export class DocumentService {
return Boolean(this.workspaceId && doc?.workspaceId && doc.visibility !== 'private');
}
+ async assertCanWriteBody(id: string, lockOwnerId?: string) {
+ const document = await this.documentModel.findById(id);
+ if (!this.isCollaborativeDocument(document)) return;
+ if (await this.editLockService.canWrite('document', id, lockOwnerId)) return;
+ throw new TRPCError({
+ cause: { data: { code: 'DocumentLocked' } },
+ code: 'CONFLICT',
+ message: 'Document is being edited by another user',
+ });
+ }
+
private async deleteFileRecordAndStorage(fileId: string) {
const file = await this.fileModel.delete(fileId);
if (!file?.url || file.url.startsWith('internal://')) return;
@@ -700,7 +712,9 @@ export class DocumentService {
}
// Finally delete the document itself
- return this.documentModel.delete(id);
+ const deleted = await this.documentModel.delete(id);
+ if (document.workspaceId) dropPageRooms([id]);
+ return deleted;
}
/**
diff --git a/apps/server/src/services/pageCollab/__tests__/access.test.ts b/apps/server/src/services/pageCollab/__tests__/access.test.ts
index 304bece6f78..8c34222942c 100644
--- a/apps/server/src/services/pageCollab/__tests__/access.test.ts
+++ b/apps/server/src/services/pageCollab/__tests__/access.test.ts
@@ -1,13 +1,19 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolvePageAccess } from '../index';
+import { resolvePageAccess, resolveRoomAccess } from '../index';
-const { allowed, meta } = vi.hoisted(() => ({
+const { allowed, legacy, meta } = vi.hoisted(() => ({
allowed: new Set<string>(),
+ legacy: { value: true },
meta: { value: null as null | { userId: string; workspaceId: string | null } },
}));
+vi.mock('../config', () => ({
+ isLegacyPageCollabEnabled: () => legacy.value,
+ isPageCollabEnabled: () => true,
+}));
+
vi.mock('@/server/services/resourcePermission', () => ({
canPerformResourceAction: async ({ action }: { action: string }) => allowed.has(action),
getResourceMeta: async () => meta.value,
@@ -42,3 +48,29 @@ describe('resolvePageAccess', () => {
expect(await resolvePageAccess({} as any, 'u2', 'doc_1')).toBe('edit');
});
});
+
+describe('resolveRoomAccess', () => {
+ beforeEach(() => {
+ allowed.clear();
+ legacy.value = true;
+ meta.value = { userId: 'u1', workspaceId: null };
+ });
+
+ it('keeps an older client editing a personal page in its room while it still joins one', async () => {
+ expect(await resolveRoomAccess({} as any, 'u1', 'doc_1')).toBe('edit');
+ });
+
+ it('keeps every client out of a personal page room once only workspace pages have rooms', async () => {
+ legacy.value = false;
+
+ expect(await resolveRoomAccess({} as any, 'u1', 'doc_1')).toBe('none');
+ });
+
+ it('follows page access for a workspace page', async () => {
+ legacy.value = false;
+ meta.value = { userId: 'u1', workspaceId: 'ws_1' };
+ allowed.add('view');
+
+ expect(await resolveRoomAccess({} as any, 'u2', 'doc_1')).toBe('view');
+ });
+});
diff --git a/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts b/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts
index 04587fcb1bf..c892c5e7049 100644
--- a/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts
+++ b/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts
@@ -7,8 +7,10 @@ import { updateDocumentThroughRoom, writePageBodyThroughRoom } from '../bodyWrit
import { openPageFork, projectPageState } from '../fork';
const room = vi.hoisted(() => ({ bootstrapped: true, doc: null as any, pushes: [] as any[] }));
-const env = vi.hoisted(() => ({ ENABLE_PAGE_COLLAB: true }));
+const env = vi.hoisted(() => ({ ENABLE_PAGE_COLLAB: true, ENABLE_WORKSPACE_PAGE_COLLAB: false }));
+const stored = vi.hoisted(() => ({ workspaceId: undefined as string | undefined }));
const persisted = vi.hoisted(() => [] as any[]);
+const lock = vi.hoisted(() => ({ heldByOther: false }));
vi.mock('@/envs/app', () => ({ appEnv: env }));
@@ -40,7 +42,7 @@ vi.mock('@/server/services/pageCollab/persist', () => ({
vi.mock('@/server/services/document', () => ({
DocumentService: class {
- getDocumentById = async () => ({ title: 'Page' });
+ getDocumentById = async () => ({ title: 'Page', workspaceId: stored.workspaceId });
},
}));
@@ -67,6 +69,8 @@ const markdownOfRoom = async () =>
describe('writePageBodyThroughRoom', () => {
beforeEach(async () => {
env.ENABLE_PAGE_COLLAB = true;
+ env.ENABLE_WORKSPACE_PAGE_COLLAB = false;
+ stored.workspaceId = undefined;
room.bootstrapped = true;
room.pushes = [];
persisted.length = 0;
@@ -134,6 +138,27 @@ describe('writePageBodyThroughRoom', () => {
).toBe(false);
});
+ it('writes a personal page to its row once only workspace pages have rooms', async () => {
+ env.ENABLE_PAGE_COLLAB = false;
+ env.ENABLE_WORKSPACE_PAGE_COLLAB = true;
+
+ expect(
+ await writePageBodyThroughRoom({} as any, 'doc_1', { markdown: 'replaced\n' }, writer),
+ ).toBe(false);
+ expect(room.pushes).toEqual([]);
+ });
+
+ it('writes a workspace page through its room once only workspace pages have rooms', async () => {
+ env.ENABLE_PAGE_COLLAB = false;
+ env.ENABLE_WORKSPACE_PAGE_COLLAB = true;
+ stored.workspaceId = 'ws_1';
+
+ expect(
+ await writePageBodyThroughRoom({} as any, 'doc_1', { markdown: 'replaced\n' }, writer),
+ ).toBe(true);
+ expect(room.pushes).toHaveLength(1);
+ });
+
it('pushes nothing when the body already matches the room', async () => {
await writePageBodyThroughRoom(
{} as any,
@@ -166,12 +191,51 @@ describe('writePageBodyThroughRoom titles', () => {
describe('updateDocumentThroughRoom', () => {
beforeEach(async () => {
env.ENABLE_PAGE_COLLAB = true;
+ lock.heldByOther = false;
room.bootstrapped = true;
room.pushes = [];
await seedRoom('para one\n');
});
- const service = () => ({ updateDocument: vi.fn(async (id: string) => ({ id }) as any) });
+ it('refuses a save from outside the room while someone else holds the page lock', async () => {
+ lock.heldByOther = true;
+ const documents = service();
+
+ await expect(
+ updateDocumentThroughRoom(
+ {} as any,
+ documents,
+ 'doc_1',
+ { content: 'para ONE\n', lockOwnerId: 'page:doc_1:b' },
+ { userId: 'u1' },
+ ),
+ ).rejects.toThrow('being edited by another user');
+
+ expect(room.pushes).toEqual([]);
+ expect(documents.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('lets a writer without a lock session, like the CLI, merge into the room', async () => {
+ lock.heldByOther = true;
+ const documents = service();
+
+ await updateDocumentThroughRoom(
+ {} as any,
+ documents,
+ 'doc_1',
+ { content: 'para ONE\n' },
+ { userId: 'u1' },
+ );
+
+ expect(await markdownOfRoom()).toBe('para ONE\n');
+ });
+
+ const service = () => ({
+ assertCanWriteBody: vi.fn(async () => {
+ if (lock.heldByOther) throw new Error('Document is being edited by another user');
+ }),
+ updateDocument: vi.fn(async (id: string) => ({ id }) as any),
+ });
it('keeps the body off the row when the room took it', async () => {
const documents = service();
diff --git a/apps/server/src/services/pageCollab/__tests__/concurrentWriters.test.ts b/apps/server/src/services/pageCollab/__tests__/concurrentWriters.test.ts
new file mode 100644
index 00000000000..0de57c9173c
--- /dev/null
+++ b/apps/server/src/services/pageCollab/__tests__/concurrentWriters.test.ts
@@ -0,0 +1,170 @@
+// @vitest-environment node
+import { createHeadlessEditor } from '@lobehub/editor/headless';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as Y from 'yjs';
+
+import { writePageBodyThroughRoom } from '../bodyWriter';
+import { openPageFork, projectPageState } from '../fork';
+import { PageRoomStaleBaseError } from '../roomClient';
+
+const env = vi.hoisted(() => ({
+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',
+ AGENT_GATEWAY_URL: 'https://gateway.test',
+ ENABLE_PAGE_COLLAB: true,
+}));
+
+vi.mock('@/envs/app', () => ({ appEnv: env }));
+
+vi.mock('@/server/services/pageCollab/persist', () => ({ persistPageState: async () => true }));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: class {
+ getDocumentById = async () => ({ title: 'Page', workspaceId: 'ws_1' });
+ },
+}));
+
+const toBase64 = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64');
+const fromBase64 = (value: string) => new Uint8Array(Buffer.from(value, 'base64'));
+
+// The gateway's room: `staleReads` stands in for other server instances that
+// read the room before the latest server write reached it.
+const room = {
+ doc: new Y.Doc(),
+ serverWriteSeq: 0,
+ 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: toBase64(stale ? stale.state : Y.encodeStateAsUpdate(room.doc)),
+ });
+ }
+
+ if (url.pathname === '/api/documents/update') {
+ const body = JSON.parse(String(init?.body));
+ if (
+ typeof body.baseServerWriteSeq === 'number' &&
+ body.baseServerWriteSeq < room.serverWriteSeq
+ ) {
+ return Response.json({ code: 'STALE_BASE', ok: false }, { status: 409 });
+ }
+ Y.applyUpdate(room.doc, fromBase64(body.update));
+ room.serverWriteSeq++;
+ return Response.json({ epoch: 'e1', ok: true });
+ }
+
+ return new Response('not found', { status: 404 });
+};
+
+const writer = { saveSource: 'llm_call' as const, userId: 'u1', writeSource: 'system' as const };
+
+const editorDataOf = (markdown: string) => {
+ const editor = createHeadlessEditor();
+ editor.hydrateMarkdown(markdown, { keepId: true });
+ const { editorData } = editor.export();
+ editor.destroy();
+ return editorData;
+};
+
+const seedRoom = async (markdown: string) => {
+ const seed = await openPageFork(undefined, markdown ? editorDataOf(markdown) : undefined);
+ room.doc = new Y.Doc();
+ Y.applyUpdate(room.doc, seed.diff());
+ seed.destroy();
+};
+
+const markdownOfRoom = async () =>
+ (await projectPageState(Y.encodeStateAsUpdate(room.doc))).markdown;
+
+const write = (markdown: string) =>
+ writePageBodyThroughRoom({} as any, 'doc_1', { editorData: editorDataOf(markdown) }, writer);
+
+const readStaleFor = (reads: number) => {
+ room.stale = { reads, seq: room.serverWriteSeq, state: Y.encodeStateAsUpdate(room.doc) };
+};
+
+const writeBothFromOneRead = async (first: string, second: string) => {
+ readStaleFor(2);
+ await write(first);
+ await write(second);
+ room.stale = null;
+};
+
+describe('two server writers that read the same room state', () => {
+ beforeEach(() => {
+ room.serverWriteSeq = 0;
+ room.stale = null;
+ vi.stubGlobal('fetch', vi.fn(gateway));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('control: sequential writers that each read the latest room state', async () => {
+ await seedRoom('## Purpose\n\npara one\n');
+
+ await write('## Purpose v2\n\npara one\n');
+ await write('## Purpose v2\n\npara one\n');
+
+ expect(await markdownOfRoom()).toBe('## Purpose v2\n\npara one\n');
+ });
+
+ it('writing the same body twice keeps one copy', async () => {
+ await seedRoom('## Purpose\n\npara one\n');
+
+ await writeBothFromOneRead('## Purpose v2\n\npara one\n', '## Purpose v2\n\npara one\n');
+
+ expect(await markdownOfRoom()).toBe('## Purpose v2\n\npara one\n');
+ });
+
+ it('writing different bodies keeps one of them, not both merged', async () => {
+ await seedRoom('## Purpose\n\npara one\n');
+
+ await writeBothFromOneRead('## Purpose A\n\npara one\n', '## Purpose B\n\npara one\n');
+
+ expect(['## Purpose A\n\npara one\n', '## Purpose B\n\npara one\n']).toContain(
+ await markdownOfRoom(),
+ );
+ });
+
+ it('two writers filling an empty page keep one copy of the page', async () => {
+ await seedRoom('');
+ const page = '# Plan\n\nfirst paragraph\n\nsecond paragraph\n';
+
+ await writeBothFromOneRead(page, page);
+
+ expect(await markdownOfRoom()).toBe(page);
+ });
+
+ it('two writers appending to a stub page keep one copy of the new content', async () => {
+ await seedRoom('# Plan\n');
+ const page = '# Plan\n\nfirst paragraph\n\nsecond paragraph\n';
+
+ await writeBothFromOneRead(page, page);
+
+ expect(await markdownOfRoom()).toBe(page);
+ });
+
+ it('gives up with the stale-base error when every read stays stale, leaving the room untouched', async () => {
+ await seedRoom('# Plan\n');
+ await write('# Plan\n\nlatest\n');
+ readStaleFor(Number.POSITIVE_INFINITY);
+ room.stale!.seq = 0;
+
+ await expect(write('# Plan\n\nfrom a stale read\n')).rejects.toBeInstanceOf(
+ PageRoomStaleBaseError,
+ );
+ room.stale = null;
+
+ expect(await markdownOfRoom()).toBe('# Plan\n\nlatest\n');
+ });
+});
diff --git a/apps/server/src/services/pageCollab/__tests__/notify.test.ts b/apps/server/src/services/pageCollab/__tests__/notify.test.ts
new file mode 100644
index 00000000000..501ac41b758
--- /dev/null
+++ b/apps/server/src/services/pageCollab/__tests__/notify.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { dropPageRooms } from '../notify';
+
+const { env, scheduled } = vi.hoisted(() => ({
+ env: {
+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',
+ AGENT_GATEWAY_URL: 'https://gateway.test',
+ ENABLE_PAGE_COLLAB: false,
+ ENABLE_WORKSPACE_PAGE_COLLAB: true,
+ },
+ scheduled: [] as Promise<unknown>[],
+}));
+
+vi.mock('@/envs/app', () => ({ appEnv: env }));
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({
+ afterUnscoped: (work: () => Promise<unknown>) => {
+ scheduled.push(work());
+ },
+}));
+
+const settle = () => Promise.all(scheduled);
+
+describe('dropPageRooms', () => {
+ let answers: number[];
+ let calls: { method?: string; url: string }[];
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout'] });
+ env.ENABLE_WORKSPACE_PAGE_COLLAB = true;
+ scheduled.length = 0;
+ answers = [];
+ calls = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL, init?: RequestInit) => {
+ calls.push({ method: init?.method, url: String(input) });
+ return new Response(null, { status: answers.shift() ?? 200 });
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ const run = async () => {
+ const done = settle();
+ await vi.runAllTimersAsync();
+ await done;
+ };
+
+ it('tells the gateway to drop each page room after the response', async () => {
+ dropPageRooms(['doc_1', 'doc_2']);
+ await run();
+
+ expect(calls).toEqual([
+ { method: 'DELETE', url: 'https://gateway.test/api/documents/room?documentId=doc_1' },
+ { method: 'DELETE', url: 'https://gateway.test/api/documents/room?documentId=doc_2' },
+ ]);
+ });
+
+ it('retries a failed drop, then gives up without failing the caller', async () => {
+ answers = [503, 503, 503, 503];
+
+ dropPageRooms(['doc_1']);
+ await run();
+
+ expect(calls).toHaveLength(3);
+ });
+
+ it('stops retrying once the gateway accepts the drop', async () => {
+ answers = [503, 200];
+
+ dropPageRooms(['doc_1']);
+ await run();
+
+ expect(calls).toHaveLength(2);
+ });
+
+ it('does nothing without page collaboration', async () => {
+ env.ENABLE_WORKSPACE_PAGE_COLLAB = false;
+
+ dropPageRooms(['doc_1']);
+ await run();
+
+ expect(calls).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/pageCollab/__tests__/persist.test.ts b/apps/server/src/services/pageCollab/__tests__/persist.test.ts
index 5c7dcc78f2b..ecff8d7b9f5 100644
--- a/apps/server/src/services/pageCollab/__tests__/persist.test.ts
+++ b/apps/server/src/services/pageCollab/__tests__/persist.test.ts
@@ -3,12 +3,18 @@ import { createHeadlessEditor } from '@lobehub/editor/headless';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import * as Y from 'yjs';
-import { openPageFork } from '../fork';
-import { persistPageState } from '../persist';
+import { openPageFork, PAGE_META_KEY } from '../fork';
+import { PageProjectionRejectedError, persistPageState } from '../persist';
+import { emptyEditorData } from '../seed';
const { redisStore, store } = vi.hoisted(() => ({
redisStore: new Map<string, string>(),
- store: { row: null as any, updates: [] as any[] },
+ store: {
+ calls: [] as string[],
+ row: null as any,
+ savedHistories: [] as any[],
+ updates: [] as any[],
+ },
}));
vi.mock('@/server/services/redis', () => ({
@@ -29,7 +35,13 @@ vi.mock('@/server/services/resourcePermission', () => ({
vi.mock('@/server/services/document', () => ({
DocumentService: class {
getDocumentById = async () => store.row;
+ trySaveCurrentDocumentHistory = async (id: string, saveSource: string) => {
+ store.calls.push('saveHistory');
+ store.savedHistories.push({ editorData: store.row.editorData, id, saveSource });
+ return { historyId: 'h1', savedAt: new Date() };
+ };
updateDocument = async (_id: string, params: any) => {
+ store.calls.push('update');
store.updates.push(params);
store.row = { ...store.row, editorData: params.editorData };
return { historyAppended: true, updatedAt: new Date() };
@@ -47,12 +59,30 @@ const roomOf = async (markdown: string) => {
return state;
};
+const emptyRoom = async (titles: string[] = []) => {
+ const fork = await openPageFork(undefined, emptyEditorData());
+ for (const title of titles) fork.doc.getMap(PAGE_META_KEY).set('title', title);
+ const state = Y.encodeStateAsUpdate(fork.doc);
+ fork.destroy();
+ return state;
+};
+
+const clearedRoom = async (markdown: string) => {
+ const doc = new Y.Doc();
+ Y.applyUpdate(doc, await roomOf(markdown));
+ const root = doc.get('root', Y.XmlText);
+ root.delete(0, root.length);
+ return Y.encodeStateAsUpdate(doc);
+};
+
const persist = (state: Uint8Array) =>
persistPageState({} as any, 'doc_1', state, { saveSource: 'autosave' });
describe('persistPageState', () => {
beforeEach(() => {
redisStore.clear();
+ store.calls = [];
+ store.savedHistories = [];
store.updates = [];
store.row = { content: 'old\n', editorData: null, title: 'Page' };
});
@@ -100,4 +130,69 @@ describe('persistPageState', () => {
expect(store.updates[1].saveSource).toBe('autosave');
});
+
+ it('keeps the previous body as its own version before a projection that drops most of it', async () => {
+ const previous = { root: { children: [{ type: 'paragraph' }], type: 'root' } };
+ store.row = {
+ ...store.row,
+ content: `# Plan\n\n${'a long paragraph that the room is about to lose. '.repeat(8)}\n`,
+ editorData: previous,
+ };
+
+ await persist(await roomOf('# Plan\n'));
+
+ expect(store.calls).toEqual(['saveHistory', 'update']);
+ expect(store.savedHistories).toEqual([
+ { editorData: previous, id: 'doc_1', saveSource: 'system' },
+ ]);
+ expect(store.updates[0].saveSource).toBe('autosave');
+ });
+
+ it('writes a projection that keeps most of the body without an extra version', async () => {
+ store.row = { ...store.row, content: '# Plan\n\nfirst\n' };
+
+ await persist(await roomOf('# Plan\n\nfirst\n\nsecond\n'));
+
+ expect(store.calls).toEqual(['update']);
+ });
+
+ describe('a room that never held the stored body', () => {
+ beforeEach(() => {
+ store.row = { content: '# Report\n\nfindings\n', editorData: null, title: 'Page' };
+ });
+
+ it('refuses an empty room over a stored body', async () => {
+ await expect(persist(await emptyRoom())).rejects.toBeInstanceOf(PageProjectionRejectedError);
+ expect(store.calls).toEqual([]);
+ });
+
+ it('refuses a room that was never bootstrapped', async () => {
+ await expect(persist(Y.encodeStateAsUpdate(new Y.Doc()))).rejects.toBeInstanceOf(
+ PageProjectionRejectedError,
+ );
+ expect(store.calls).toEqual([]);
+ });
+
+ it('refuses an empty room whose only edits renamed the page', async () => {
+ await expect(persist(await emptyRoom(['Draft', 'Report']))).rejects.toBeInstanceOf(
+ PageProjectionRejectedError,
+ );
+ expect(store.calls).toEqual([]);
+ });
+
+ it('writes a page someone cleared in the room', async () => {
+ await persist(await clearedRoom('# Report\n\nfindings\n'));
+
+ expect(store.updates).toHaveLength(1);
+ expect(store.updates[0].content.trim()).toBe('');
+ });
+
+ it('writes an empty room over an empty stored page', async () => {
+ store.row = { ...store.row, content: '' };
+
+ await persist(await emptyRoom());
+
+ expect(store.updates).toHaveLength(1);
+ });
+ });
});
diff --git a/apps/server/src/services/pageCollab/__tests__/roomBootstrap.test.ts b/apps/server/src/services/pageCollab/__tests__/roomBootstrap.test.ts
new file mode 100644
index 00000000000..9a829c1400a
--- /dev/null
+++ b/apps/server/src/services/pageCollab/__tests__/roomBootstrap.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as Y from 'yjs';
+
+import { projectPageState } from '../fork';
+import { RoomPageSessions } from '../roomSession';
+
+vi.mock('@/envs/app', () => ({
+ appEnv: {
+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',
+ AGENT_GATEWAY_URL: 'https://gateway.test',
+ ENABLE_WORKSPACE_PAGE_COLLAB: true,
+ },
+}));
+
+vi.mock('@/server/services/pageCollab/persist', () => ({ persistPageState: async () => true }));
+
+vi.mock('@/server/services/document/writeLimit', () => ({
+ assertDocumentWriteWithinLimit: async () => {},
+ getDocumentCharLimitErrorData: () => undefined,
+}));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: class {
+ getDocumentById = async () => ({
+ content: '',
+ editorData: null,
+ title: 'Empty page',
+ workspaceId: 'ws_1',
+ });
+ },
+}));
+
+const toBase64 = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64');
+const fromBase64 = (value: string) => new Uint8Array(Buffer.from(value, 'base64'));
+
+// A durable room with no tree yet: it takes one bootstrap and refuses anything
+// else, so an unflagged root cannot become a second tree beside a later seed.
+const room = { bootstrapped: false, doc: new Y.Doc() };
+
+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') {
+ return Response.json({
+ bootstrapped: room.bootstrapped,
+ epoch: 'e1',
+ serverWriteSeq: 0,
+ update: toBase64(Y.encodeStateAsUpdate(room.doc)),
+ });
+ }
+ const body = JSON.parse(String(init?.body));
+ if (body.bootstrap === true && room.bootstrapped) {
+ return Response.json({ code: 'bootstrap_conflict', ok: false }, { status: 409 });
+ }
+ if (!room.bootstrapped && body.bootstrap !== true) {
+ return Response.json({ code: 'not_bootstrapped', ok: false }, { status: 409 });
+ }
+ Y.applyUpdate(room.doc, fromBase64(body.update));
+ room.bootstrapped = true;
+ return Response.json({ ok: true });
+};
+
+const writer = { saveSource: 'llm_call' as const, userId: 'u1', writeSource: 'system' as const };
+
+describe('RoomPageSessions on a room that has no tree yet', () => {
+ beforeEach(() => {
+ room.bootstrapped = false;
+ room.doc = new Y.Doc();
+ vi.stubGlobal('fetch', vi.fn(gateway));
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('bootstraps an empty page with an empty root, so an agent can write into it', async () => {
+ const session = await new RoomPageSessions({} as any, writer).openSession('doc_1');
+ session.setTitle('Plan');
+ await session.commit();
+ session.draft.destroy();
+
+ expect(room.bootstrapped).toBe(true);
+ expect(room.doc.get('root', Y.XmlText).length).toBeGreaterThan(0);
+ expect((await projectPageState(Y.encodeStateAsUpdate(room.doc))).title).toBe('Plan');
+ });
+});
diff --git a/apps/server/src/services/pageCollab/__tests__/roomRefusals.test.ts b/apps/server/src/services/pageCollab/__tests__/roomRefusals.test.ts
new file mode 100644
index 00000000000..4fb28b0111f
--- /dev/null
+++ b/apps/server/src/services/pageCollab/__tests__/roomRefusals.test.ts
@@ -0,0 +1,81 @@
+// @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 { writePageBodyThroughRoom } from '../bodyWriter';
+import { openPageFork } from '../fork';
+
+vi.mock('@/envs/app', () => ({
+ appEnv: {
+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',
+ AGENT_GATEWAY_URL: 'https://gateway.test',
+ ENABLE_PAGE_COLLAB: true,
+ },
+}));
+
+vi.mock('@/server/services/pageCollab/persist', () => ({ persistPageState: async () => true }));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: class {
+ getDocumentById = async () => ({ title: 'Page', workspaceId: 'ws_1' });
+ },
+}));
+
+const editorDataOf = (markdown: string) => {
+ const editor = createHeadlessEditor();
+ editor.hydrateMarkdown(markdown, { keepId: true });
+ const { editorData } = editor.export();
+ editor.destroy();
+ return editorData;
+};
+
+const writer = { saveSource: 'llm_call' as const, userId: 'u1', writeSource: 'system' as const };
+
+describe('a room that refuses a server write', () => {
+ let state: Uint8Array;
+
+ beforeEach(async () => {
+ const seed = await openPageFork(undefined, editorDataOf('# Plan\n'));
+ const doc = new Y.Doc();
+ Y.applyUpdate(doc, seed.diff());
+ seed.destroy();
+ state = Y.encodeStateAsUpdate(doc);
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL) => {
+ const url = new URL(String(input));
+ if (url.pathname === '/api/documents/state') {
+ return Response.json({
+ bootstrapped: true,
+ epoch: 'e1',
+ serverWriteSeq: 0,
+ update: Buffer.from(state).toString('base64'),
+ });
+ }
+ return Response.json({ code: 'DOC_TOO_LARGE', ok: false }, { status: 413 });
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('reports a page over the size cap as PAYLOAD_TOO_LARGE with a reason the agent can read', async () => {
+ const write = writePageBodyThroughRoom(
+ {} as any,
+ 'doc_1',
+ { editorData: editorDataOf('# Plan\n\nmore\n') },
+ writer,
+ );
+
+ await expect(write).rejects.toBeInstanceOf(TRPCError);
+ await expect(write).rejects.toMatchObject({
+ code: 'PAYLOAD_TOO_LARGE',
+ message: expect.stringMatching(/too large/i),
+ });
+ });
+});
diff --git a/apps/server/src/services/pageCollab/__tests__/seed.test.ts b/apps/server/src/services/pageCollab/__tests__/seed.test.ts
new file mode 100644
index 00000000000..d17a04513f1
--- /dev/null
+++ b/apps/server/src/services/pageCollab/__tests__/seed.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment node
+import { createHeadlessEditor } from '@lobehub/editor/headless';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import * as Y from 'yjs';
+
+import { projectPageState } from '../fork';
+import { buildPageSeed, getPageRoomStatus } from '../seed';
+
+const rows = vi.hoisted(() => new Map<string, any>());
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ getResourceMeta: async (_db: unknown, _type: string, id: string) => {
+ const row = rows.get(id);
+ return row ? { userId: row.userId, workspaceId: row.workspaceId } : undefined;
+ },
+}));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: class {
+ getDocumentById = async (id: string) => rows.get(id);
+ },
+}));
+
+const editorDataOf = (markdown: string) => {
+ const editor = createHeadlessEditor();
+ editor.hydrateMarkdown(markdown, { keepId: true });
+ const { editorData } = editor.export();
+ editor.destroy();
+ return editorData;
+};
+
+const page = (overrides: Record<string, unknown>) => ({
+ content: null,
+ editorData: null,
+ title: 'Plan',
+ userId: 'u1',
+ workspaceId: 'ws_1',
+ ...overrides,
+});
+
+describe('buildPageSeed', () => {
+ beforeEach(() => rows.clear());
+
+ it('builds the room state from the stored body and title of a workspace page', async () => {
+ rows.set('doc_1', page({ editorData: editorDataOf('# Plan\n\nfirst paragraph\n') }));
+
+ const seed = await buildPageSeed({} as any, 'doc_1');
+
+ expect(seed.status).toBe('ok');
+ if (seed.status !== 'ok') return;
+ expect(seed.workspaceId).toBe('ws_1');
+ const projected = await projectPageState(seed.update);
+ expect(projected.markdown).toBe('# Plan\n\nfirst paragraph\n');
+ expect(projected.title).toBe('Plan');
+ });
+
+ it('recovers the body from Markdown for a row saved without editor data', async () => {
+ rows.set('doc_1', page({ content: 'only markdown\n' }));
+
+ const seed = await buildPageSeed({} as any, 'doc_1');
+
+ expect(seed.status).toBe('ok');
+ if (seed.status !== 'ok') return;
+ expect((await projectPageState(seed.update)).markdown).toBe('only markdown\n');
+ });
+
+ it('gives an empty page a root, so no later writer creates a second one', async () => {
+ rows.set('doc_1', page({}));
+
+ const seed = await buildPageSeed({} as any, 'doc_1');
+
+ expect(seed.status).toBe('ok');
+ if (seed.status !== 'ok') return;
+ const doc = new Y.Doc();
+ Y.applyUpdate(doc, seed.update);
+ expect(doc.get('root', Y.XmlText).length).toBeGreaterThan(0);
+ });
+
+ it('refuses a personal page', async () => {
+ rows.set('doc_1', page({ workspaceId: null }));
+
+ expect(await buildPageSeed({} as any, 'doc_1')).toEqual({ status: 'not_allowed' });
+ });
+
+ it('reports a missing page', async () => {
+ expect(await buildPageSeed({} as any, 'doc_404')).toEqual({ status: 'not_found' });
+ });
+});
+
+describe('getPageRoomStatus', () => {
+ beforeEach(() => rows.clear());
+
+ it('reports whether the page exists and belongs to a workspace', async () => {
+ rows.set('doc_ws', page({}));
+ rows.set('doc_personal', page({ workspaceId: null }));
+
+ expect(await getPageRoomStatus({} as any, 'doc_ws')).toEqual({
+ exists: true,
+ inWorkspace: true,
+ workspaceId: 'ws_1',
+ });
+ expect(await getPageRoomStatus({} as any, 'doc_personal')).toEqual({
+ exists: true,
+ inWorkspace: false,
+ workspaceId: null,
+ });
+ expect(await getPageRoomStatus({} as any, 'doc_404')).toEqual({
+ exists: false,
+ inWorkspace: false,
+ workspaceId: null,
+ });
+ });
+});
diff --git a/apps/server/src/services/pageCollab/__tests__/sessions.test.ts b/apps/server/src/services/pageCollab/__tests__/sessions.test.ts
index 2823c07629c..1ca2fbceacd 100644
--- a/apps/server/src/services/pageCollab/__tests__/sessions.test.ts
+++ b/apps/server/src/services/pageCollab/__tests__/sessions.test.ts
@@ -3,8 +3,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createPageSessions } from '../index';
-const { allowed, meta, roomOpen, roomOpenLive, row, storedOpen } = vi.hoisted(() => ({
+const { allowed, legacy, meta, roomOpen, roomOpenLive, row, storedOpen } = vi.hoisted(() => ({
allowed: new Set<string>(),
+ legacy: { value: true },
meta: { value: null as null | { userId: string; workspaceId: string | null } },
roomOpen: vi.fn(),
roomOpenLive: vi.fn(),
@@ -23,7 +24,10 @@ vi.mock('@/server/services/document', () => ({
},
}));
-vi.mock('../config', () => ({ isPageCollabEnabled: () => true }));
+vi.mock('../config', () => ({
+ isLegacyPageCollabEnabled: () => legacy.value,
+ isPageCollabEnabled: () => true,
+}));
vi.mock('../roomSession', () => ({
RoomPageSessions: class {
@@ -48,6 +52,7 @@ const writer = {
describe('createPageSessions', () => {
beforeEach(() => {
allowed.clear();
+ legacy.value = true;
meta.value = { userId: 'u1', workspaceId: 'ws_1' };
row.value = { fileType: 'custom/document', id: 'doc_1', workspaceId: 'ws_1' };
roomOpen.mockReset();
@@ -109,4 +114,16 @@ describe('createPageSessions', () => {
expect(roomOpen).not.toHaveBeenCalled();
expect(storedOpen).not.toHaveBeenCalled();
});
+
+ it('ignores rooms on a personal page once older clients no longer join them', async () => {
+ legacy.value = false;
+ meta.value = { userId: 'u2', workspaceId: null };
+ row.value = { fileType: 'custom/document', id: 'doc_1', workspaceId: null };
+ roomOpenLive.mockResolvedValue({ commit: vi.fn() });
+
+ await createPageSessions({} as any, { ...writer, workspaceId: undefined }).openSession('doc_1');
+
+ expect(roomOpenLive).not.toHaveBeenCalled();
+ expect(storedOpen).toHaveBeenCalledWith('doc_1', undefined);
+ });
});
diff --git a/apps/server/src/services/pageCollab/bodyWriter.ts b/apps/server/src/services/pageCollab/bodyWriter.ts
index 7e2f24ab96f..47484713c77 100644
--- a/apps/server/src/services/pageCollab/bodyWriter.ts
+++ b/apps/server/src/services/pageCollab/bodyWriter.ts
@@ -11,12 +11,13 @@ import {
createDocumentHeadlessEditor,
withHeadlessEditorLock,
} from '@/server/services/agentDocuments/headlessEditor';
-import type { DocumentService } from '@/server/services/document';
+import { DocumentService } from '@/server/services/document';
import type { UpdateDocumentParams, UpdateDocumentResult } from '@/server/services/document/types';
-import { isPageCollabEnabled } from './config';
+import { isLegacyPageCollabEnabled, isPageCollabEnabled } from './config';
import type { SerializedEditor } from './editorData';
import { runPageExclusive } from './queue';
+import { PageRoomStaleBaseError } from './roomClient';
import { RoomPageSessions } from './roomSession';
import type { PageWriter } from './session';
@@ -27,6 +28,24 @@ export interface PageBody {
title?: string;
}
+// 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;
+const STALE_BASE_BACKOFF_MS = 40;
+
+// Only workspace pages have rooms, unless older clients may still hold one open
+// on a personal page; a write around that room would be projected over.
+const mayHaveRoom = async (db: LobeChatDatabase, documentId: string, writer: PageWriter) => {
+ if (!isPageCollabEnabled()) return false;
+ if (isLegacyPageCollabEnabled()) return true;
+ const row = await new DocumentService(db, writer.userId, writer.workspaceId).getDocumentById(
+ documentId,
+ );
+ return !!row?.workspaceId;
+};
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
const toHeadlessOperation = (operation: ModifyOperation): HeadlessLiteXMLOperation => {
if (operation.action === 'modify') return { action: 'replace', litexml: operation.litexml };
return operation as HeadlessLiteXMLOperation;
@@ -77,9 +96,9 @@ export const writePageBodyThroughRoom = async (
body: PageBody,
writer: PageWriter,
): Promise<boolean> => {
- if (!isPageCollabEnabled()) return false;
+ if (!(await mayHaveRoom(db, documentId, writer))) return false;
- return runPageExclusive(documentId, () =>
+ const writeOnce = () =>
withHeadlessEditorLock(async () => {
const session = await new RoomPageSessions(db, writer).openLiveSession(documentId);
if (!session) return false;
@@ -95,8 +114,20 @@ export const writePageBodyThroughRoom = async (
} finally {
session.draft.destroy();
}
- }),
- );
+ });
+
+ return runPageExclusive(documentId, async () => {
+ for (let retry = 0; ; retry++) {
+ try {
+ return await writeOnce();
+ } catch (error) {
+ if (!(error instanceof PageRoomStaleBaseError) || retry >= MAX_STALE_BASE_RETRIES) {
+ throw error;
+ }
+ await sleep(STALE_BASE_BACKOFF_MS * (retry + 1) * (0.5 + Math.random()));
+ }
+ }
+ });
};
/**
@@ -106,7 +137,7 @@ export const writePageBodyThroughRoom = async (
*/
export const updateDocumentThroughRoom = async (
db: LobeChatDatabase,
- service: Pick<DocumentService, 'updateDocument'>,
+ service: Pick<DocumentService, 'assertCanWriteBody' | 'updateDocument'>,
documentId: string,
params: UpdateDocumentParams,
writer: Omit<PageWriter, 'saveSource' | 'writeSource'>,
@@ -117,6 +148,10 @@ export const updateDocumentThroughRoom = async (
return service.updateDocument(documentId, params);
}
+ // An editor outside the room carries its lock session. The room's members share
+ // the page lock, so this save must not merge over their edits while they hold it.
+ if (params.lockOwnerId) await service.assertCanWriteBody(documentId, params.lockOwnerId);
+
const routed = await writePageBodyThroughRoom(
db,
documentId,
@@ -151,7 +186,7 @@ export const snapshotPageThroughRoom = async (
documentId: string,
writer: PageWriter,
): Promise<boolean> => {
- if (!isPageCollabEnabled()) return false;
+ if (!(await mayHaveRoom(db, documentId, writer))) return false;
return runPageExclusive(documentId, () =>
withHeadlessEditorLock(async () => {
diff --git a/apps/server/src/services/pageCollab/config.ts b/apps/server/src/services/pageCollab/config.ts
index bf0314623a0..f6d6f79bd08 100644
--- a/apps/server/src/services/pageCollab/config.ts
+++ b/apps/server/src/services/pageCollab/config.ts
@@ -2,5 +2,14 @@ import { appEnv } from '@/envs/app';
import { createPageRoomClient } from './roomClient';
-/** Pages edit through live rooms only where the deployment's gateway has them (Cloud). */
-export const isPageCollabEnabled = () => !!appEnv.ENABLE_PAGE_COLLAB && !!createPageRoomClient();
+const hasRoomGateway = () => !!createPageRoomClient();
+
+// Clients released before workspace-only rooms join a room for every page while
+// this is on; it stays on until those clients are switched off.
+export const isLegacyPageCollabEnabled = () => !!appEnv.ENABLE_PAGE_COLLAB && hasRoomGateway();
+
+export const isWorkspacePageCollabEnabled = () =>
+ !!appEnv.ENABLE_WORKSPACE_PAGE_COLLAB && hasRoomGateway();
+
+export const isPageCollabEnabled = () =>
+ isLegacyPageCollabEnabled() || isWorkspacePageCollabEnabled();
diff --git a/apps/server/src/services/pageCollab/fork.ts b/apps/server/src/services/pageCollab/fork.ts
index 2cd9179d64e..568e06ba331 100644
--- a/apps/server/src/services/pageCollab/fork.ts
+++ b/apps/server/src/services/pageCollab/fork.ts
@@ -137,6 +137,20 @@ const countRoomBlocks = (doc: Y.Doc) =>
.toDelta()
.filter((op: { insert: unknown }) => typeof op.insert !== 'string').length;
+// A body someone emptied leaves tombstones under the root; a room whose body
+// never arrived has none. Renames replace the meta map's value, so they do not count.
+const hasErasedBody = (state: Uint8Array) => {
+ const doc = new Y.Doc();
+ Y.applyUpdate(doc, state);
+ const meta = doc.getMap(PAGE_META_KEY);
+ for (const structs of doc.store.clients.values()) {
+ for (const struct of structs) {
+ if (struct.deleted && !(struct instanceof Y.Item && struct.parent === meta)) return true;
+ }
+ }
+ return false;
+};
+
export const projectPageState = async (state: Uint8Array) => {
const fork = await openPageFork(state);
try {
@@ -145,6 +159,7 @@ export const projectPageState = async (state: Uint8Array) => {
(exported.editorData as SerializedEditor | undefined)?.root?.children?.length ?? 0;
return {
...exported,
+ erasedBody: hasErasedBody(state),
/** The room holds blocks the binding did not export: projecting would erase them. */
lostBlocks: exportedBlocks === 0 && countRoomBlocks(fork.doc) > 0,
title: readPageTitle(fork.doc),
diff --git a/apps/server/src/services/pageCollab/index.ts b/apps/server/src/services/pageCollab/index.ts
index cf00cef8c42..76d05840f79 100644
--- a/apps/server/src/services/pageCollab/index.ts
+++ b/apps/server/src/services/pageCollab/index.ts
@@ -5,7 +5,7 @@ import { DocumentService } from '@/server/services/document';
import { canPerformResourceAction, getResourceMeta } from '@/server/services/resourcePermission';
import { isSkillMarkdownDocument } from '@/utils/skillMarkdown';
-import { isPageCollabEnabled } from './config';
+import { isLegacyPageCollabEnabled, isPageCollabEnabled } from './config';
import { DbPageSessions } from './dbSession';
import { RoomPageSessions } from './roomSession';
import { type PageSessions, PageUnsupportedError, type PageWriter } from './session';
@@ -29,6 +29,9 @@ export const createPageSessions = (db: LobeChatDatabase, writer: PageWriter): Pa
if (!row) throw new Error(`Page document not found: ${documentId}`);
if (row.fileType === HTML_DOCUMENT_FILE_TYPE) throw new PageUnsupportedError();
if (!room || isSkillMarkdownDocument(row)) return stored.openSession(documentId, options);
+ if (!row.workspaceId && !isLegacyPageCollabEnabled()) {
+ return stored.openSession(documentId, options);
+ }
// The room reads and persists with the gateway token and the page owner's
// scope, so the writer's own permission is the only gate in front of it.
@@ -69,6 +72,19 @@ export const resolvePageAccess = async (
return (await can('view')) ? 'view' : 'none';
};
+// The gateway asks this before letting someone into a page's room.
+export const resolveRoomAccess = async (
+ db: LobeChatDatabase,
+ userId: string,
+ documentId: string,
+): Promise<PageAccess> => {
+ if (!isLegacyPageCollabEnabled()) {
+ const meta = await getResourceMeta(db, 'document', documentId);
+ if (!meta?.workspaceId) return 'none';
+ }
+ return resolvePageAccess(db, userId, documentId);
+};
+
export { isPageCollabEnabled } from './config';
export { editorDataFromRow } from './editorData';
export { openPageFork, projectPageState } from './fork';
diff --git a/apps/server/src/services/pageCollab/notify.ts b/apps/server/src/services/pageCollab/notify.ts
new file mode 100644
index 00000000000..92df8efbf42
--- /dev/null
+++ b/apps/server/src/services/pageCollab/notify.ts
@@ -0,0 +1,38 @@
+import debug from 'debug';
+
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
+
+import { isPageCollabEnabled } from './config';
+import { createPageRoomClient, type PageRoomClient } from './roomClient';
+
+const log = debug('lobe-server:page-collab:notify');
+
+const ATTEMPTS = 3;
+const RETRY_MS = 500;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const dropWithRetry = async (room: PageRoomClient, documentId: string) => {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await room.dropRoom(documentId);
+ return;
+ } catch (error) {
+ log('dropping room %s failed (attempt %d): %O', documentId, attempt, error);
+ if (attempt >= ATTEMPTS) return;
+ await sleep(RETRY_MS * 3 ** (attempt - 1));
+ }
+ }
+};
+
+// The gateway's daily patrol is the backstop, so a drop that never lands only
+// keeps a room around a little longer.
+export const dropPageRooms = (documentIds: string[]) => {
+ if (documentIds.length === 0 || !isPageCollabEnabled()) return;
+ const room = createPageRoomClient();
+ if (!room) return;
+
+ afterUnscoped(async () => {
+ for (const documentId of documentIds) await dropWithRetry(room, documentId);
+ });
+};
diff --git a/apps/server/src/services/pageCollab/persist.ts b/apps/server/src/services/pageCollab/persist.ts
index 9dec19b55af..06ccfd3150d 100644
--- a/apps/server/src/services/pageCollab/persist.ts
+++ b/apps/server/src/services/pageCollab/persist.ts
@@ -35,8 +35,8 @@ const bodyDigest = (editorData: unknown) =>
.digest('hex');
export class PageProjectionRejectedError extends Error {
- constructor(documentId: string) {
- super(`Refusing to persist page ${documentId}: the room holds blocks the projection lost`);
+ constructor(documentId: string, reason = 'the room holds blocks the projection lost') {
+ super(`Refusing to persist page ${documentId}: ${reason}`);
this.name = 'PageProjectionRejectedError';
}
}
@@ -64,7 +64,7 @@ export const persistPageState = async (
const meta = await getResourceMeta(db, 'document', documentId);
if (!meta) return false;
- const { editorData, lostBlocks, markdown, title } = await withHeadlessEditorLock(() =>
+ const { editorData, erasedBody, lostBlocks, markdown, title } = await withHeadlessEditorLock(() =>
projectPageState(state),
);
// A binding that fails to read the room exports an empty page; writing it
@@ -75,6 +75,12 @@ export const persistPageState = async (
const row = await service.getDocumentById(documentId);
if (!row) return false;
+ // An empty room that never erased anything never received the stored body,
+ // e.g. a seed whose body push was lost. Projecting it would blank the page.
+ if (!markdown.trim() && !erasedBody && row.content?.trim()) {
+ throw new PageProjectionRejectedError(documentId, 'the room never received the stored body');
+ }
+
// Every known writer of a room page's body goes through its room. A body that
// changed since the last projection was written around it anyway; keep that
// version as its own `system` entry in the history before the room replaces it.
@@ -82,6 +88,19 @@ export const persistPageState = async (
const writtenOutsideRoom = lastProjected !== null && lastProjected !== bodyDigest(row.editorData);
if (writtenOutsideRoom) log('page %s body was written outside its room', documentId);
+ // A projection that drops most of the body may be a real delete or a room
+ // that lost its content; either way the previous body stays recoverable.
+ const previousLength = row.content?.length ?? 0;
+ if (previousLength > 0 && markdown.length * 2 < previousLength) {
+ console.warn(
+ '[page-collab] room %s shrank the page from %d to %d characters',
+ documentId,
+ previousLength,
+ markdown.length,
+ );
+ await service.trySaveCurrentDocumentHistory(documentId, 'system');
+ }
+
await service.updateDocument(documentId, {
content: toStoredMarkdown(row, markdown),
editorData: editorData as unknown as Record<string, unknown>,
diff --git a/apps/server/src/services/pageCollab/roomClient.ts b/apps/server/src/services/pageCollab/roomClient.ts
index 66626c5292a..fb884c70458 100644
--- a/apps/server/src/services/pageCollab/roomClient.ts
+++ b/apps/server/src/services/pageCollab/roomClient.ts
@@ -1,8 +1,12 @@
+import { TRPCError } from '@trpc/server';
+
import { appEnv } from '@/envs/app';
export interface PageRoomState {
bootstrapped: boolean;
epoch: string;
+ // Absent from a gateway that predates conditional server writes.
+ serverWriteSeq?: number;
update: Uint8Array;
}
@@ -13,6 +17,23 @@ export class PageRoomConflictError extends Error {
}
}
+export class PageRoomStaleBaseError extends Error {
+ constructor() {
+ super('Page room changed after this writer read it');
+ this.name = 'PageRoomStaleBaseError';
+ }
+}
+
+export const PAGE_TOO_LARGE_MESSAGE =
+ 'This page is too large to store more content. Remove some content from the page, or ask support to trim its history.';
+
+export class PageRoomTooLargeError extends TRPCError {
+ constructor() {
+ super({ code: 'PAYLOAD_TOO_LARGE', message: PAGE_TOO_LARGE_MESSAGE });
+ this.name = 'PageRoomTooLargeError';
+ }
+}
+
export const toBase64 = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64');
export const fromBase64 = (value: string) => new Uint8Array(Buffer.from(value, 'base64'));
@@ -27,22 +48,44 @@ export class PageRoomClient {
url.searchParams.set('documentId', documentId);
const res = await fetch(url, { headers: this.headers() });
if (!res.ok) throw new Error(`Page room state failed: ${res.status}`);
- const body = (await res.json()) as { bootstrapped: boolean; epoch: string; update: string };
- return { bootstrapped: body.bootstrapped, epoch: body.epoch, update: fromBase64(body.update) };
+ const body = (await res.json()) as {
+ bootstrapped: boolean;
+ epoch: string;
+ serverWriteSeq?: number;
+ update: string;
+ };
+ return {
+ bootstrapped: body.bootstrapped,
+ epoch: body.epoch,
+ serverWriteSeq: typeof body.serverWriteSeq === 'number' ? body.serverWriteSeq : undefined,
+ update: fromBase64(body.update),
+ };
}
async pushUpdate(
documentId: string,
update: Uint8Array,
- options: { actor?: string; bootstrap?: boolean } = {},
+ options: { actor?: string; baseServerWriteSeq?: number; bootstrap?: boolean } = {},
): Promise<void> {
const res = await fetch(new URL('/api/documents/update', this.baseUrl), {
body: JSON.stringify({ documentId, update: toBase64(update), ...options }),
headers: { ...this.headers(), 'Content-Type': 'application/json' },
method: 'POST',
});
+ if (res.ok) return;
+
+ const code = await errorCodeOf(res);
+ if (code === 'STALE_BASE') throw new PageRoomStaleBaseError();
+ if (code === 'DOC_TOO_LARGE') throw new PageRoomTooLargeError();
if (res.status === 409) throw new PageRoomConflictError();
- if (!res.ok) throw new Error(`Page room update failed: ${res.status}`);
+ throw new Error(`Page room update failed: ${res.status}`);
+ }
+
+ async dropRoom(documentId: string): Promise<void> {
+ const url = new URL('/api/documents/room', this.baseUrl);
+ url.searchParams.set('documentId', documentId);
+ const res = await fetch(url, { headers: this.headers(), method: 'DELETE' });
+ if (!res.ok) throw new Error(`Page room drop failed: ${res.status}`);
}
private headers() {
@@ -50,6 +93,11 @@ export class PageRoomClient {
}
}
+const errorCodeOf = async (res: Response) => {
+ const body = (await res.json().catch(() => null)) as { code?: unknown } | null;
+ return typeof body?.code === 'string' ? body.code : undefined;
+};
+
const toHttpBase = (url: string) => url.replace(/^ws(s?):\/\//, 'http$1://');
export const createPageRoomClient = (): PageRoomClient | null => {
diff --git a/apps/server/src/services/pageCollab/roomSession.ts b/apps/server/src/services/pageCollab/roomSession.ts
index cd66646a769..be9b868ad3c 100644
--- a/apps/server/src/services/pageCollab/roomSession.ts
+++ b/apps/server/src/services/pageCollab/roomSession.ts
@@ -18,6 +18,7 @@ import {
PageRoomConflictError,
type PageRoomState,
} from './roomClient';
+import { emptyEditorData } from './seed';
import {
historyAttributionOf,
type PageSession,
@@ -98,7 +99,10 @@ export class RoomPageSessions implements PageSessions {
userId: this.writer.userId,
workspaceId: this.writer.workspaceId,
});
- await room.pushUpdate(documentId, fork.diff(), { actor });
+ await room.pushUpdate(documentId, fork.diff(), {
+ actor,
+ baseServerWriteSeq: state.serverWriteSeq,
+ });
try {
await this.persist(documentId, fork);
} catch (error) {
@@ -148,10 +152,7 @@ export class RoomPageSessions implements PageSessions {
const row = await this.documentService.getDocumentById(documentId);
if (!row) throw new Error(`Page document not found: ${documentId}`);
- const editorData = editorDataFromRow(row);
- if (!editorData) return;
-
- const seed = await openPageFork(undefined, editorData);
+ const seed = await openPageFork(undefined, editorDataFromRow(row) ?? emptyEditorData());
if (row.title) seed.doc.getMap(PAGE_META_KEY).set('title', row.title);
try {
await room.pushUpdate(documentId, seed.diff(), { actor: 'bootstrap', bootstrap: true });
diff --git a/apps/server/src/services/pageCollab/seed.ts b/apps/server/src/services/pageCollab/seed.ts
new file mode 100644
index 00000000000..7c1f6a6317a
--- /dev/null
+++ b/apps/server/src/services/pageCollab/seed.ts
@@ -0,0 +1,78 @@
+import * as Y from 'yjs';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { withHeadlessEditorLock } from '@/server/services/agentDocuments/headlessEditor';
+import { DocumentService } from '@/server/services/document';
+import { getResourceMeta } from '@/server/services/resourcePermission';
+
+import { editorDataFromRow, type SerializedEditor } from './editorData';
+import { openPageFork, PAGE_META_KEY } from './fork';
+
+export type PageSeed =
+ | { status: 'ok'; update: Uint8Array; workspaceId: string }
+ | { status: 'not_allowed' | 'not_found' };
+
+export interface PageRoomStatus {
+ exists: boolean;
+ inWorkspace: boolean;
+ workspaceId: string | null;
+}
+
+// The room asks for its seed once, so it is the only tree the page ever has;
+// an empty page still needs a root, or the next writer would create a second one.
+export const emptyEditorData = (): SerializedEditor =>
+ ({
+ root: {
+ children: [
+ {
+ children: [],
+ direction: null,
+ format: '',
+ indent: 0,
+ textFormat: 0,
+ textStyle: '',
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ direction: null,
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+ }) as unknown as SerializedEditor;
+
+export const buildPageSeed = async (
+ db: LobeChatDatabase,
+ documentId: string,
+): Promise<PageSeed> => {
+ const meta = await getResourceMeta(db, 'document', documentId);
+ if (!meta) return { status: 'not_found' };
+ if (!meta.workspaceId) return { status: 'not_allowed' };
+
+ const row = await new DocumentService(db, meta.userId, meta.workspaceId).getDocumentById(
+ documentId,
+ );
+ if (!row) return { status: 'not_found' };
+ const workspaceId = meta.workspaceId;
+
+ return withHeadlessEditorLock(async () => {
+ const seed = await openPageFork(undefined, editorDataFromRow(row) ?? emptyEditorData());
+ try {
+ if (row.title) seed.doc.getMap(PAGE_META_KEY).set('title', row.title);
+ return { status: 'ok', update: Y.encodeStateAsUpdate(seed.doc), workspaceId };
+ } finally {
+ seed.destroy();
+ }
+ });
+};
+
+export const getPageRoomStatus = async (
+ db: LobeChatDatabase,
+ documentId: string,
+): Promise<PageRoomStatus> => {
+ const meta = await getResourceMeta(db, 'document', documentId);
+ const workspaceId = meta?.workspaceId ?? null;
+ return { exists: !!meta, inWorkspace: !!workspaceId, workspaceId };
+};
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index b96277a4382..ec5e5becd4e 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -295,6 +295,10 @@
"pageEditor.charLimit.nearTitle": "This page has {{actual}} of {{limit}} characters allowed per page on your plan.",
"pageEditor.charLimit.overDescription": "Changes cannot be saved while the page is over the limit. Shorten the page or upgrade your plan.",
"pageEditor.chooseIcon": "Choose Icon",
+ "pageEditor.collab.deleted.description": "It was deleted or moved out of this workspace. Return to the page list to keep working.",
+ "pageEditor.collab.deleted.title": "This page is no longer available here",
+ "pageEditor.collab.nearFull.description": "It's close to its size limit. Remove content you no longer need, or move some of it to a new page.",
+ "pageEditor.collab.nearFull.title": "This page is almost full",
"pageEditor.collab.notSynced": "Your latest page edits are still syncing, so the Agent may not see them yet.",
"pageEditor.collab.offlineRestore.content": "The page was reloaded from the server while you were offline, and your unsynced edits are not in it. Put your version back?",
"pageEditor.collab.offlineRestore.discard": "Keep the current page",
@@ -312,6 +316,8 @@
"pageEditor.collab.status.connecting": "Connecting…",
"pageEditor.collab.status.error": "Couldn't sync this page.",
"pageEditor.collab.status.offline": "Offline. Edits sync when you reconnect.",
+ "pageEditor.collab.tooLarge.description": "It reached its size limit. Contact support to trim it or restore an earlier version.",
+ "pageEditor.collab.tooLarge.title": "This page is too large to edit",
"pageEditor.comments.anchor.add": "Comment",
"pageEditor.comments.anchor.addToLine": "Comment on this line",
"pageEditor.comments.anchor.label": "Quoted text:",
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index ae23778754c..22147dec1f5 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -34,6 +34,8 @@
"features.messageTextSelectionActions.title": "Message Text Selection Actions",
"features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.",
"features.oauthApps.title": "OAuth Apps",
+ "features.pageCollab.desc": "Edit workspace pages together in real time and see who else is on the page. When off, pages still save normally and show teammates' changes after a refresh.",
+ "features.pageCollab.title": "Live Page Collaboration",
"features.projects.desc": "Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.",
"features.projects.title": "Project Workspaces",
"features.selfLearning.desc": "Agents learn from your conversations in the background and review their day each night. See the results under Memory → Self-evolving.",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 6b81b93eff7..5cb7daf836a 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -295,6 +295,10 @@
"pageEditor.charLimit.nearTitle": "此页面已有 {{actual}} 个字符,当前套餐每页上限为 {{limit}} 个字符。",
"pageEditor.charLimit.overDescription": "超出上限期间,改动无法保存。请缩短页面内容,或升级套餐。",
"pageEditor.chooseIcon": "选择图标",
+ "pageEditor.collab.deleted.description": "页面已被删除或移出此工作区。请返回页面列表继续工作。",
+ "pageEditor.collab.deleted.title": "此页面已不在这里",
+ "pageEditor.collab.nearFull.description": "页面已接近大小上限。请删除不再需要的内容,或把部分内容移到新页面。",
+ "pageEditor.collab.nearFull.title": "此页面快满了",
"pageEditor.collab.notSynced": "你最近的页面修改还在同步,Agent 可能暂时看不到。",
"pageEditor.collab.offlineRestore.content": "离线期间页面已从服务器重新加载,你未同步的修改不在其中。要恢复你的版本吗?",
"pageEditor.collab.offlineRestore.discard": "保留当前页面",
@@ -312,6 +316,8 @@
"pageEditor.collab.status.connecting": "连接中…",
"pageEditor.collab.status.error": "页面同步失败。",
"pageEditor.collab.status.offline": "已离线,重新连接后会自动同步。",
+ "pageEditor.collab.tooLarge.description": "页面已达到大小上限。请联系支持团队精简页面,或恢复到较早的版本。",
+ "pageEditor.collab.tooLarge.title": "页面过大,无法继续编辑",
"pageEditor.comments.anchor.add": "评论",
"pageEditor.comments.anchor.addToLine": "评论这一行",
"pageEditor.comments.anchor.label": "引用原文:",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index 87977b36ee4..fe587c64252 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -34,6 +34,8 @@
"features.messageTextSelectionActions.title": "消息文本选择操作",
"features.oauthApps.desc": "在个人和工作区设置中显示 OAuth 应用管理入口。此功能默认隐藏。",
"features.oauthApps.title": "OAuth 应用",
+ "features.pageCollab.desc": "在工作区页面中与成员实时共同编辑,并看到谁正在同一页面。关闭时页面照常保存,成员的修改在刷新后可见。",
+ "features.pageCollab.title": "页面实时协作",
"features.projects.desc": "将长期目标组织到独立工作空间中,并集中管理相关智能体、资料库与任务。",
"features.projects.title": "项目工作空间",
"features.selfLearning.desc": "让 Agent 在后台从对话中学习,并在每晚复盘。在「记忆 → 自进化」中查看结果。",
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index 2543895ec0f..7b4b19f610a 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -21,6 +21,7 @@ export type {
MuxAgentEventMessage,
MuxClientMessage,
MuxDocAwarenessEntry,
+ MuxDocCapacity,
MuxDocClientMessage,
MuxDocServerMessage,
MuxErrorMessage,
diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.ts
index da4baa61ae6..bf75503bb9f 100644
--- a/packages/agent-gateway-client/src/mux/types.ts
+++ b/packages/agent-gateway-client/src/mux/types.ts
@@ -60,12 +60,17 @@ export interface MuxDocAwarenessEntry {
state: Record<string, unknown> | null;
}
+/** How close the room's page is to its size cap; `full` refuses anything that adds content. */
+export type MuxDocCapacity = 'full' | 'near_full' | 'ok';
+
export type MuxDocServerMessage =
| {
access: 'edit' | 'view';
awareness?: MuxDocAwarenessEntry[];
bootstrap: boolean;
bootstrapped: boolean;
+ /** Absent from gateways that predate the size cap. */
+ capacity?: MuxDocCapacity;
documentId: string;
epoch: string;
reset: boolean;
@@ -73,6 +78,7 @@ export type MuxDocServerMessage =
update: string;
}
| { documentId: string; type: 'doc_update'; update: string }
+ | { capacity: MuxDocCapacity; documentId: string; type: 'doc_capacity' }
| { 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' }
diff --git a/packages/database/src/models/__tests__/documentTransfer.test.ts b/packages/database/src/models/__tests__/documentTransfer.test.ts
index 0cf846fd373..0512915e714 100644
--- a/packages/database/src/models/__tests__/documentTransfer.test.ts
+++ b/packages/database/src/models/__tests__/documentTransfer.test.ts
@@ -7,6 +7,7 @@ import {
DOCUMENT_FOLDER_TYPE,
documentCommentMentions,
documentComments,
+ documentHistories,
documentLikes,
documents,
files,
@@ -15,6 +16,7 @@ import {
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { DOCUMENT_TRANSFER_FOREIGN_ROWS, DocumentModel } from '../document';
+import { DocumentHistoryModel } from '../documentHistory';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -323,6 +325,55 @@ describe('DocumentModel.transferTo', () => {
.where(eq(documentCommentMentions.commentId, comment!.id)),
).toHaveLength(0);
});
+ it('brings the version history along into the target workspace', async () => {
+ const personal = new DocumentModel(serverDB, userId);
+ const folder = await createFolder(personal, 'Versioned Folder', 'versioned-folder');
+ const page = await createPage(personal, 'Versioned', 'versioned-page', folder.id);
+ const personalHistory = new DocumentHistoryModel(serverDB, userId);
+ await personalHistory.create({
+ documentId: page.id,
+ editorData: { root: { children: [], type: 'root' } },
+ saveSource: 'manual',
+ savedAt: new Date('2026-01-01T00:00:00.000Z'),
+ });
+
+ await personal.transferTo(folder.id, wsId1, userId);
+
+ const inWorkspace = await new DocumentHistoryModel(serverDB, userId, wsId1).listByDocumentId(
+ page.id,
+ );
+ expect(inWorkspace.map(({ saveSource }) => saveSource)).toEqual(['manual']);
+ expect(await personalHistory.listByDocumentId(page.id)).toHaveLength(0);
+ });
+
+ it("brings a workspace page's versions to its new owner on a personal transfer", async () => {
+ const ws = new DocumentModel(serverDB, userId, wsId1);
+ const page = await createPage(ws, 'Shared versions', 'shared-versions');
+ await serverDB.insert(documentHistories).values([
+ {
+ documentId: page.id,
+ editorData: { root: { children: [], type: 'root' } },
+ saveSource: 'autosave',
+ savedAt: new Date('2026-01-01T00:00:00.000Z'),
+ userId,
+ workspaceId: wsId1,
+ },
+ {
+ documentId: page.id,
+ editorData: { root: { children: [], type: 'root' } },
+ saveSource: 'autosave',
+ savedAt: new Date('2026-01-02T00:00:00.000Z'),
+ userId: otherUserId,
+ workspaceId: wsId1,
+ },
+ ]);
+
+ await ws.transferTo(page.id, null, userId);
+
+ expect(await new DocumentHistoryModel(serverDB, userId).listByDocumentId(page.id)).toHaveLength(
+ 2,
+ );
+ });
});
describe('DocumentModel.copyToWorkspace', () => {
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index 5c1b27e067c..36645335589 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -27,6 +27,7 @@ import {
DOCUMENT_FOLDER_TYPE,
documentCommentMentions,
documentComments,
+ documentHistories,
documentLikes,
documents,
files,
@@ -808,6 +809,18 @@ export class DocumentModel {
.set({ ...ownershipUpdate, ...visibilityUpdate })
.where(inArray(files.parentId, ids));
+ // History reads filter on the denormalized scope. A workspace target
+ // filters on `workspace_id` alone, so authors keep their attribution; a
+ // personal target reads `user_id = owner`, so the new owner takes every version.
+ await (trx as LobeChatDatabase)
+ .update(documentHistories)
+ .set(
+ targetWorkspaceId
+ ? { workspaceId: targetWorkspaceId }
+ : { userId: targetUserId, workspaceId: null },
+ )
+ .where(inArray(documentHistories.documentId, ids));
+
return { documentIds: ids };
});
};
diff --git a/packages/env/src/app.ts b/packages/env/src/app.ts
index 25fb6be72ec..e982b87a928 100644
--- a/packages/env/src/app.ts
+++ b/packages/env/src/app.ts
@@ -86,6 +86,7 @@ export const getAppConfig = () => {
* save over HTTP and the page agent writes back to the stored row.
*/
ENABLE_PAGE_COLLAB: z.boolean().optional(),
+ ENABLE_WORKSPACE_PAGE_COLLAB: z.boolean().optional(),
/**
* Server-to-server Agent Gateway endpoint, e.g. a Docker Compose service
* name the browser cannot resolve. Falls back to AGENT_GATEWAY_URL.
@@ -153,6 +154,7 @@ export const getAppConfig = () => {
AGENT_GATEWAY_SERVICE_TOKEN: process.env.AGENT_GATEWAY_SERVICE_TOKEN,
ENABLE_AGENT_GATEWAY: process.env.ENABLE_AGENT_GATEWAY === '1',
ENABLE_PAGE_COLLAB: process.env.ENABLE_PAGE_COLLAB === '1',
+ ENABLE_WORKSPACE_PAGE_COLLAB: process.env.ENABLE_WORKSPACE_PAGE_COLLAB === '1',
AGENT_GATEWAY_URL: process.env.AGENT_GATEWAY_URL,
AGENT_GATEWAY_PROTOCOL: process.env.AGENT_GATEWAY_PROTOCOL || undefined,
AGENT_GATEWAY_INTERNAL_URL: process.env.AGENT_GATEWAY_INTERNAL_URL || undefined,
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index e5f025645bb..a908dc8cb5f 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -336,6 +336,12 @@ export default {
'pageEditor.charLimit.overDescription':
'Changes cannot be saved while the page is over the limit. Shorten the page or upgrade your plan.',
'pageEditor.chooseIcon': 'Choose Icon',
+ 'pageEditor.collab.deleted.description':
+ 'It was deleted or moved out of this workspace. Return to the page list to keep working.',
+ 'pageEditor.collab.deleted.title': 'This page is no longer available here',
+ 'pageEditor.collab.nearFull.description':
+ "It's close to its size limit. Remove content you no longer need, or move some of it to a new page.",
+ 'pageEditor.collab.nearFull.title': 'This page is almost full',
'pageEditor.collab.notSynced':
'Your latest page edits are still syncing, so the Agent may not see them yet.',
'pageEditor.collab.offlineRestore.content':
@@ -355,6 +361,9 @@ export default {
'pageEditor.collab.status.connecting': 'Connecting…',
'pageEditor.collab.status.error': "Couldn't sync this page.",
'pageEditor.collab.status.offline': 'Offline. Edits sync when you reconnect.',
+ 'pageEditor.collab.tooLarge.description':
+ 'It reached its size limit. Contact support to trim it or restore an earlier version.',
+ 'pageEditor.collab.tooLarge.title': 'This page is too large to edit',
'pageEditor.comments.anchor.add': 'Comment',
'pageEditor.comments.anchor.addToLine': 'Comment on this line',
'pageEditor.comments.anchor.label': 'Quoted text:',
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index ab4e2a6834a..51f77766299 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -51,6 +51,9 @@ export default {
'features.oauthApps.desc':
'Show OAuth app management in personal and workspace settings. This feature is hidden by default.',
'features.oauthApps.title': 'OAuth Apps',
+ 'features.pageCollab.desc':
+ "Edit workspace pages together in real time and see who else is on the page. When off, pages still save normally and show teammates' changes after a refresh.",
+ 'features.pageCollab.title': 'Live Page Collaboration',
'features.projects.desc':
'Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.',
'features.projects.title': 'Project Workspaces',
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 81300b953bf..711cdbf9ab5 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -206,6 +206,8 @@ export interface GlobalServerConfig {
/** Pages collaborate live through the gateway's document rooms (LobeHub Cloud). */
enablePageCollab?: boolean;
enableUploadFileToServer?: boolean;
+ /** Workspace pages collaborate live through the gateway's durable rooms (LobeHub Cloud). */
+ enableWorkspacePageCollab?: boolean;
image?: PartialDeep<UserImageConfig>;
/**
* Whether the server can relay an LLM call to a browser tab (Agent Gateway
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index fe1d3769438..e10b5b30911 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -178,6 +178,10 @@ export const UserLabSchema = z.object({
* enable artifact deployment features (publish artifacts to a hosted URL)
*/
enableArtifactDeployment: z.boolean().optional(),
+ /**
+ * edit workspace pages together in a live collaboration room
+ */
+ enablePageCollab: z.boolean().optional(),
/**
* run Claude Code hetero sessions through the Claude Agent SDK instead of CLI spawn
*/
diff --git a/src/features/PageEditor/EditingIndicator.test.tsx b/src/features/PageEditor/EditingIndicator.test.tsx
index e261ebc58b2..1d142a31d41 100644
--- a/src/features/PageEditor/EditingIndicator.test.tsx
+++ b/src/features/PageEditor/EditingIndicator.test.tsx
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import EditingIndicator from './EditingIndicator';
const mockPage: { current: Record<string, unknown> } = { current: {} };
+const lock = vi.hoisted(() => ({ lockedByOther: false }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -25,11 +26,12 @@ vi.mock('@/store/document/slices/editor', () => ({
}));
vi.mock('@/business/client/hooks/useAuthorInfo', () => ({ useAuthorInfo: () => undefined }));
-vi.mock('./usePageLockedByOther', () => ({ usePageLockedByOther: () => false }));
+vi.mock('./usePageLockedByOther', () => ({ usePageLockedByOther: () => lock.lockedByOther }));
vi.mock('./usePageLockedBySelf', () => ({ usePageLockedBySelf: () => false }));
describe('EditingIndicator while the agent edits', () => {
beforeEach(() => {
+ lock.lockedByOther = false;
mockPage.current = { documentId: 'doc-1', isWorkspacePage: true };
});
@@ -46,4 +48,17 @@ describe('EditingIndicator while the agent edits', () => {
expect(screen.queryByText('pageEditor.agentEditing')).not.toBeInTheDocument();
});
+
+ it('says who is editing when someone outside the room holds the lock', () => {
+ lock.lockedByOther = true;
+ mockPage.current = {
+ ...mockPage.current,
+ collab: { status: 'synced' },
+ lockHolderId: 'user-2',
+ };
+
+ render(<EditingIndicator />);
+
+ expect(screen.getByText('pageEditor.editMode.lockedBySomeone')).toBeInTheDocument();
+ });
});
diff --git a/src/features/PageEditor/EditingIndicator.tsx b/src/features/PageEditor/EditingIndicator.tsx
index e137c1e335b..9123c7ccb6a 100644
--- a/src/features/PageEditor/EditingIndicator.tsx
+++ b/src/features/PageEditor/EditingIndicator.tsx
@@ -84,7 +84,7 @@ const EditingIndicator = memo(() => {
</Flexbox>
);
}
- if (collabStatus || !isWorkspacePage) return null;
+ if (!isWorkspacePage || (collabStatus && !isLockedByOther)) return null;
const locked = isLockedByOther || isLockedBySelf || saveBlockedByLock;
diff --git a/src/features/PageEditor/LockedAlert.tsx b/src/features/PageEditor/LockedAlert.tsx
index b6dae80bca4..74af64ef605 100644
--- a/src/features/PageEditor/LockedAlert.tsx
+++ b/src/features/PageEditor/LockedAlert.tsx
@@ -33,7 +33,7 @@ const LockedAlert = memo(() => {
);
const holder = useAuthorInfo(lockHolderId ?? undefined);
- if (!isWorkspacePage || inCollab) return null;
+ if (!isWorkspacePage || (inCollab && !isLockedByOther)) return null;
if (!isLockedByOther && !isLockedBySelf && !saveBlockedByLock) return null;
// Same user, different session (other tab / unreleased prior mount): show a
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index 6270c508f49..8aa47a64eeb 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -16,6 +16,7 @@ import { pageActions } from '@/store/page';
import { StyleSheet } from '@/utils/styles';
import { focusEditorAtBlankPoint } from './blankAreaClick';
+import CollabBlockedBanner from './collab/CollabBlockedBanner';
import { usePageCollabEligible, usePageCollabEnabled } from './collab/usePageCollab';
import DocumentComments from './DocumentComments';
import BlockCommentMarker from './DocumentComments/BlockCommentMarker';
@@ -410,6 +411,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {
<LockedAlert />
{/* Plan page-size limit: refused-save notice and near-limit warning. */}
<CharLimitBanner sticky documentId={documentId} />
+ <CollabBlockedBanner />
<EditorCanvas askCopilotTarget={askCopilotTarget} />
<BlockCommentMarker hostRef={editorContentRef} />
{documentId && <DocumentLikes documentId={documentId} key={documentId} />}
diff --git a/src/features/PageEditor/collab/CollabBlockedBanner.test.tsx b/src/features/PageEditor/collab/CollabBlockedBanner.test.tsx
new file mode 100644
index 00000000000..a8fdc7b3685
--- /dev/null
+++ b/src/features/PageEditor/collab/CollabBlockedBanner.test.tsx
@@ -0,0 +1,76 @@
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import CollabBlockedBanner from './CollabBlockedBanner';
+
+const editorState = vi.hoisted(() => ({ value: {} as Record<string, unknown> }));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('../store', () => ({
+ usePageEditorStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector(editorState.value),
+}));
+
+describe('CollabBlockedBanner', () => {
+ beforeEach(() => {
+ editorState.value = { collab: { access: 'edit', pending: 0, status: 'synced' } };
+ });
+
+ it('renders nothing while the room accepts edits', () => {
+ const { container } = render(<CollabBlockedBanner />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('tells the reader a page at its size cap is read-only', () => {
+ editorState.value = {
+ collab: { access: 'edit', blocked: 'too_large', pending: 0, status: 'synced' },
+ };
+
+ render(<CollabBlockedBanner />);
+
+ expect(screen.getByText('pageEditor.collab.tooLarge.title')).toBeInTheDocument();
+ expect(screen.getByText('pageEditor.collab.tooLarge.description')).toBeInTheDocument();
+ });
+
+ it('tells the reader the page was deleted', () => {
+ editorState.value = {
+ collab: { access: 'edit', blocked: 'deleted', pending: 0, status: 'connecting' },
+ };
+
+ render(<CollabBlockedBanner />);
+
+ expect(screen.getByText('pageEditor.collab.deleted.title')).toBeInTheDocument();
+ });
+
+ it('warns the reader a page close to its size cap is almost full, while it stays editable', () => {
+ editorState.value = {
+ collab: { access: 'edit', capacity: 'near_full', pending: 0, status: 'synced' },
+ };
+
+ render(<CollabBlockedBanner />);
+
+ expect(screen.getByText('pageEditor.collab.nearFull.title')).toBeInTheDocument();
+ expect(screen.getByText('pageEditor.collab.nearFull.description')).toBeInTheDocument();
+ });
+
+ it('shows only the read-only notice once a nearly full page is blocked', () => {
+ editorState.value = {
+ collab: {
+ access: 'edit',
+ blocked: 'too_large',
+ capacity: 'near_full',
+ pending: 0,
+ status: 'synced',
+ },
+ };
+
+ render(<CollabBlockedBanner />);
+
+ expect(screen.getByText('pageEditor.collab.tooLarge.title')).toBeInTheDocument();
+ expect(screen.queryByText('pageEditor.collab.nearFull.title')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/PageEditor/collab/CollabBlockedBanner.tsx b/src/features/PageEditor/collab/CollabBlockedBanner.tsx
new file mode 100644
index 00000000000..b41adb95559
--- /dev/null
+++ b/src/features/PageEditor/collab/CollabBlockedBanner.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import { type CSSProperties, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { NoticeAlert } from '@/components/NoticeAlert';
+
+import { usePageEditorStore } from '../store';
+
+const BANNER_STYLE: CSSProperties = {
+ insetBlockStart: 0,
+ marginBlock: 8,
+ position: 'sticky',
+ zIndex: 2,
+};
+
+const NOTICE = {
+ deleted: {
+ description: 'pageEditor.collab.deleted.description',
+ title: 'pageEditor.collab.deleted.title',
+ type: 'warning',
+ },
+ near_full: {
+ description: 'pageEditor.collab.nearFull.description',
+ title: 'pageEditor.collab.nearFull.title',
+ type: 'warning',
+ },
+ too_large: {
+ description: 'pageEditor.collab.tooLarge.description',
+ title: 'pageEditor.collab.tooLarge.title',
+ type: 'error',
+ },
+} as const;
+
+const CollabBlockedBanner = memo(() => {
+ const { t } = useTranslation('file');
+ const notice = usePageEditorStore((s) => {
+ if (s.collab?.blocked) return s.collab.blocked;
+ return s.collab?.capacity === 'near_full' ? 'near_full' : undefined;
+ });
+ if (!notice) return null;
+
+ return (
+ <NoticeAlert
+ showIcon
+ description={t(NOTICE[notice].description)}
+ key={notice}
+ style={BANNER_STYLE}
+ title={t(NOTICE[notice].title)}
+ type={NOTICE[notice].type}
+ />
+ );
+});
+
+CollabBlockedBanner.displayName = 'CollabBlockedBanner';
+
+export default CollabBlockedBanner;
diff --git a/src/features/PageEditor/collab/provider.test.ts b/src/features/PageEditor/collab/provider.test.ts
index d1b5072f916..2f38544d9d3 100644
--- a/src/features/PageEditor/collab/provider.test.ts
+++ b/src/features/PageEditor/collab/provider.test.ts
@@ -141,6 +141,36 @@ describe('PageCollabProvider', () => {
expect(onPendingChange).toHaveBeenLastCalledWith(0);
});
+ it('reports a local edit once synced, but not what the editor writes while syncing or bootstrapping', async () => {
+ const { deliver, mux, ready } = createMux();
+ const doc = new Y.Doc();
+ const onLocalEdit = vi.fn();
+ const onBootstrap = vi.fn(() => doc.getText('t').insert(0, 'from db'));
+ const provider = new PageCollabProvider('doc_1', doc, mux as any, { onBootstrap, onLocalEdit });
+ provider.on('sync', () => doc.getText('t').insert(0, 'root paragraph'));
+
+ provider.connect();
+ ready();
+ deliver(
+ synced({
+ bootstrap: true,
+ bootstrapped: false,
+ update: b64(Y.encodeStateAsUpdate(new Y.Doc())),
+ }),
+ );
+ await Promise.resolve();
+ deliver({ documentId: 'doc_1', seq: 1, type: 'doc_ack' });
+ deliver({
+ documentId: 'doc_1',
+ type: 'doc_update',
+ update: b64(Y.encodeStateAsUpdate(roomWith('remote'))),
+ });
+ expect(onLocalEdit).not.toHaveBeenCalled();
+
+ doc.getText('t').insert(0, 'typed');
+ expect(onLocalEdit).toHaveBeenCalledOnce();
+ });
+
it('does not echo remote updates back to the room', () => {
const { deliver, mux, ready, sent } = createMux();
const provider = new PageCollabProvider('doc_1', new Y.Doc(), mux as any);
@@ -368,4 +398,93 @@ describe('PageCollabProvider', () => {
expect(onReset).toHaveBeenCalledOnce();
expect(onReset).toHaveBeenCalledWith('bootstrap_conflict');
});
+
+ it('reports a page at its size cap as blocked, staying in the room', () => {
+ const { deliver, mux, ready } = createMux();
+ const onBlocked = vi.fn();
+ const onStatus = vi.fn();
+ const provider = new PageCollabProvider('doc_1', new Y.Doc(), mux as any, {
+ onBlocked,
+ onStatus,
+ });
+
+ provider.connect();
+ ready();
+ deliver(synced());
+ deliver({
+ code: 'doc_too_large',
+ documentId: 'doc_1',
+ message: 'too large',
+ type: 'doc_error',
+ });
+
+ expect(onBlocked).toHaveBeenCalledWith('too_large');
+ expect(onStatus).not.toHaveBeenCalledWith('error');
+ });
+
+ it('reports a deleted page as blocked instead of a sync failure', () => {
+ const { deliver, mux, ready } = createMux();
+ const onBlocked = vi.fn();
+ const onFailure = vi.fn();
+ const provider = new PageCollabProvider('doc_1', new Y.Doc(), mux as any, {
+ onBlocked,
+ onFailure,
+ });
+
+ provider.connect();
+ ready();
+ deliver({ code: 'doc_deleted', documentId: 'doc_1', message: 'deleted', type: 'doc_error' });
+
+ expect(onBlocked).toHaveBeenCalledWith('deleted');
+ expect(onFailure).not.toHaveBeenCalled();
+ });
+
+ describe('room capacity', () => {
+ const open = (events: Record<string, unknown>) => {
+ const harness = createMux();
+ new PageCollabProvider('doc_1', new Y.Doc(), harness.mux as any, events).connect();
+ harness.ready();
+ return harness;
+ };
+
+ it('opens a page the room already counts as full read-only, before anyone types', () => {
+ const onBlocked = vi.fn();
+ const { deliver } = open({ onBlocked });
+
+ deliver(synced({ capacity: 'full' }));
+
+ expect(onBlocked).toHaveBeenCalledWith('too_large');
+ });
+
+ it('reports how full the page is on sync and whenever the room says it changed', () => {
+ const onCapacity = vi.fn();
+ const { deliver } = open({ onCapacity });
+
+ deliver(synced({ capacity: 'near_full' }));
+ deliver({ capacity: 'ok', documentId: 'doc_1', type: 'doc_capacity' });
+
+ expect(onCapacity.mock.calls).toEqual([['near_full'], ['ok']]);
+ });
+
+ it('turns the page read-only when the room says it became full', () => {
+ const onBlocked = vi.fn();
+ const { deliver } = open({ onBlocked });
+
+ deliver(synced({ capacity: 'near_full' }));
+ deliver({ capacity: 'full', documentId: 'doc_1', type: 'doc_capacity' });
+
+ expect(onBlocked).toHaveBeenCalledWith('too_large');
+ });
+
+ it('reads a sync from a gateway that does not report capacity as no news', () => {
+ const onBlocked = vi.fn();
+ const onCapacity = vi.fn();
+ const { deliver } = open({ onBlocked, onCapacity });
+
+ deliver(synced());
+
+ expect(onCapacity).not.toHaveBeenCalled();
+ expect(onBlocked).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/features/PageEditor/collab/provider.ts b/src/features/PageEditor/collab/provider.ts
index 40f8e0fc50a..b1441d138b7 100644
--- a/src/features/PageEditor/collab/provider.ts
+++ b/src/features/PageEditor/collab/provider.ts
@@ -2,6 +2,7 @@ import type {
DocumentChannel,
GatewayMuxClient,
GatewayMuxStatus,
+ MuxDocCapacity,
MuxDocServerMessage,
} from '@lobechat/agent-gateway-client';
import * as Y from 'yjs';
@@ -41,9 +42,18 @@ export interface PageCollabCharLimitRefusal {
/** `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 type PageCollabBlockedReason = 'deleted' | 'too_large';
+
+const BLOCKED_REASON: Record<string, PageCollabBlockedReason> = {
+ doc_deleted: 'deleted',
+ doc_too_large: 'too_large',
+};
+
export interface PageCollabProviderEvents {
onAccess?: (access: PageCollabAccess) => void;
+ onBlocked?: (reason: PageCollabBlockedReason) => void;
onBootstrap?: () => void;
+ onCapacity?: (capacity: MuxDocCapacity) => 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.
@@ -55,6 +65,8 @@ export interface PageCollabProviderEvents {
*/
onCharLimitExceeded?: (refusal: PageCollabCharLimitRefusal) => void;
onFailure?: (failure: PageCollabFailure) => void;
+ /** This member changed the page, as opposed to the editor syncing or bootstrapping it. */
+ onLocalEdit?: () => void;
onPendingChange?: (pending: number) => void;
onReset?: (reason: PageCollabResetReason) => void;
onStatus?: (status: PageCollabStatus) => void;
@@ -166,6 +178,7 @@ export class PageCollabProvider extends Emitter {
private bootstrapping = false;
private conflicted = false;
private synced = false;
+ private acceptsEdits = false;
// The hub refuses anything for the document until its subscribe settles, and a
// refusal before the first sync fails the join.
private subscribed = false;
@@ -274,6 +287,7 @@ export class PageCollabProvider extends Emitter {
private handleLocalUpdate = (update: Uint8Array, origin: unknown) => {
if (origin === this) return;
+ if (this.acceptsEdits && !this.bootstrapping) this.events.onLocalEdit?.();
const seq = ++this.seq;
this.pending.add(seq);
this.events.onPendingChange?.(this.pending.size);
@@ -294,6 +308,7 @@ export class PageCollabProvider extends Emitter {
this.waitingForBootstrap = false;
this.emit('status', { status: 'connected' });
this.emit('sync', true);
+ this.acceptsEdits = true;
this.events.onStatus?.('synced');
}
@@ -315,6 +330,11 @@ export class PageCollabProvider extends Emitter {
this.handleLocalUpdate(update, null);
}
+ private reportCapacity(capacity: MuxDocCapacity) {
+ this.events.onCapacity?.(capacity);
+ if (capacity === 'full') this.events.onBlocked?.('too_large');
+ }
+
private handleMessage = (message: MuxDocServerMessage) => {
switch (message.type) {
case 'doc_synced': {
@@ -334,6 +354,7 @@ export class PageCollabProvider extends Emitter {
this.awareness.setLocalState(this.awareness.getLocalState());
}
this.resendPending();
+ if (message.capacity) this.reportCapacity(message.capacity);
if (message.bootstrap || message.bootstrapped) {
// The binding seeds an empty root as soon as it hears `sync`, before
// the bootstrap below runs; that write is part of our bootstrap too.
@@ -369,6 +390,11 @@ export class PageCollabProvider extends Emitter {
return;
}
+ case 'doc_capacity': {
+ this.reportCapacity(message.capacity);
+ 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') {
@@ -391,6 +417,12 @@ export class PageCollabProvider extends Emitter {
}
return;
}
+ // Not a sync failure: retrying cannot help, the page stays read-only.
+ const blocked = BLOCKED_REASON[message.code];
+ if (blocked) {
+ this.events.onBlocked?.(blocked);
+ 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/roomLock.ts b/src/features/PageEditor/collab/roomLock.ts
new file mode 100644
index 00000000000..f3041c691b5
--- /dev/null
+++ b/src/features/PageEditor/collab/roomLock.ts
@@ -0,0 +1,6 @@
+// Members editing in a page's room share the page's edit lock, so a member
+// editing outside the room is locked out; room members never lock each other.
+export const ROOM_LOCK_OWNER_PREFIX = 'room:';
+
+export const isRoomLockOwner = (ownerId: string | null | undefined) =>
+ !!ownerId?.startsWith(ROOM_LOCK_OWNER_PREFIX);
diff --git a/src/features/PageEditor/collab/usePageCollab.ts b/src/features/PageEditor/collab/usePageCollab.ts
index 948ebaa5ce5..db6cea6d6a3 100644
--- a/src/features/PageEditor/collab/usePageCollab.ts
+++ b/src/features/PageEditor/collab/usePageCollab.ts
@@ -12,7 +12,7 @@ import { registerPageCollab } from '@/store/document/collabRegistry';
import { pageActions } from '@/store/page';
import { getServerConfigStoreState } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
+import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
import { usePageEditorStore, useStoreApi } from '../store';
import { getPresenceColor, type PresenceAwarenessData } from './presence';
@@ -37,12 +37,15 @@ const MAX_AWARENESS_AVATAR_LENGTH = 512;
// exist only where the server enables page collaboration (LobeHub Cloud).
const readGatewayUrl = () => {
const serverConfig = getServerConfigStoreState()?.serverConfig;
- return serverConfig?.agentGatewayUrl && serverConfig.enablePageCollab
+ return serverConfig?.agentGatewayUrl && serverConfig.enableWorkspacePageCollab
? serverConfig.agentGatewayUrl
: undefined;
};
-export const usePageCollabEnabled = () => !!readGatewayUrl();
+export const usePageCollabEnabled = () => {
+ const labEnabled = useUserStore(labPreferSelectors.enablePageCollab);
+ return labEnabled && !!readGatewayUrl();
+};
/**
* Whether this document edits through a room. Only workspace pages do: a
@@ -88,6 +91,8 @@ export const usePageCollab = (documentId: string | undefined, onReset?: () => vo
const provider = new PageCollabProvider(documentId!, doc, getGatewayMux({ gatewayUrl }), {
onAccess: (access) => setCollab({ access }),
+ onBlocked: (blocked) => setCollab({ blocked }),
+ onCapacity: (capacity) => setCollab({ capacity }),
onBootstrap: () => {
const editor = storeApi.getState().editor;
if (editor) void useDocumentStore.getState().onEditorInit(editor, documentId!);
@@ -96,6 +101,9 @@ export const usePageCollab = (documentId: string | undefined, onReset?: () => vo
onCharLimitExceeded: (refusal) =>
useDocumentStore.getState().setCharLimitRefusal(documentId!, refusal),
onCharLimitCleared: () => useDocumentStore.getState().clearCharLimitRefusal(documentId!),
+ onLocalEdit: () => {
+ if (!storeApi.getState().collab?.edited) setCollab({ edited: true });
+ },
onPendingChange: (pending) => setCollab({ pending }),
onReset: (reason) => {
const editor = storeApi.getState().editor;
diff --git a/src/features/PageEditor/collab/usePageCollabEligible.test.ts b/src/features/PageEditor/collab/usePageCollabEligible.test.ts
index 5bb409409ab..b9014763e90 100644
--- a/src/features/PageEditor/collab/usePageCollabEligible.test.ts
+++ b/src/features/PageEditor/collab/usePageCollabEligible.test.ts
@@ -2,16 +2,24 @@ import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useDocumentStore } from '@/store/document';
+import { useUserStore } from '@/store/user';
import { usePageCollabEligible } from './usePageCollab';
+const serverConfig = vi.hoisted(() => ({
+ value: {} as Record<string, unknown>,
+}));
+
vi.mock('@/store/serverConfig', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
- getServerConfigStoreState: () => ({
- serverConfig: { agentGatewayUrl: 'wss://gateway.example.com', enablePageCollab: true },
- }),
+ getServerConfigStoreState: () => ({ serverConfig: serverConfig.value }),
}));
+const setPageCollabLab = (enablePageCollab: boolean) =>
+ useUserStore.setState((s) => ({
+ preference: { ...s.preference, lab: { ...s.preference.lab, enablePageCollab } },
+ }));
+
const loadDocument = (workspaceId: string | null) =>
useDocumentStore.setState({
documentDetailMap: { doc_1: { document: { id: 'doc_1', workspaceId } as any } as any },
@@ -20,7 +28,19 @@ const loadDocument = (workspaceId: string | null) =>
describe('usePageCollabEligible', () => {
beforeEach(() => {
+ serverConfig.value = {
+ agentGatewayUrl: 'wss://gateway.example.com',
+ enableWorkspacePageCollab: true,
+ };
useDocumentStore.setState({ documentDetailMap: {}, documents: {} });
+ setPageCollabLab(true);
+ });
+
+ it('keeps a workspace page out of rooms until the user turns on the lab', () => {
+ setPageCollabLab(false);
+ loadDocument('ws_1');
+
+ expect(renderHook(() => usePageCollabEligible('doc_1')).result.current).toBe(false);
});
it('puts a workspace page in a room', () => {
@@ -38,4 +58,11 @@ describe('usePageCollabEligible', () => {
it('leaves the room path only once the page is known to be personal', () => {
expect(renderHook(() => usePageCollabEligible('doc_1')).result.current).toBe(true);
});
+
+ it('stays out of rooms when only the flag for older clients is on', () => {
+ serverConfig.value = { agentGatewayUrl: 'wss://gateway.example.com', enablePageCollab: true };
+ loadDocument('ws_1');
+
+ expect(renderHook(() => usePageCollabEligible('doc_1')).result.current).toBe(false);
+ });
});
diff --git a/src/features/PageEditor/store/initialState.ts b/src/features/PageEditor/store/initialState.ts
index 3c10da8b68f..d9f7d066829 100644
--- a/src/features/PageEditor/store/initialState.ts
+++ b/src/features/PageEditor/store/initialState.ts
@@ -37,8 +37,12 @@ export interface PublicState {
export interface PageCollabState {
access: 'edit' | 'view';
+ blocked?: 'deleted' | 'too_large';
/** The room's body reached the editor; until then the page shows the stored copy. */
bodyReady?: boolean;
+ capacity?: 'full' | 'near_full' | 'ok';
+ /** This member edited the page in the room; from then on the room holds the page's edit lock. */
+ edited?: boolean;
pending: number;
/** Joins the room again after it failed to sync. */
retry?: () => void;
diff --git a/src/features/PageEditor/useDocumentLock.test.ts b/src/features/PageEditor/useDocumentLock.test.ts
index c8196a3ab39..0ffe19220a5 100644
--- a/src/features/PageEditor/useDocumentLock.test.ts
+++ b/src/features/PageEditor/useDocumentLock.test.ts
@@ -5,6 +5,8 @@ import { useDocumentStore } from '@/store/document';
import { useDocumentLock } from './useDocumentLock';
+const editLockCalls = vi.hoisted(() => ({ value: [] as any[] }));
+
const mockPageState: {
current: Record<string, unknown>;
} = { current: {} };
@@ -26,14 +28,17 @@ vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
}));
vi.mock('@/features/EditLock', () => ({
- useEditLock: () => ({
- expiresAt: null,
- health: 'healthy',
- holderId: null,
- lockedByOther: false,
- ownerId: undefined,
- pending: false,
- }),
+ useEditLock: (options: any) => {
+ editLockCalls.value.push(options);
+ return {
+ expiresAt: null,
+ health: 'healthy',
+ holderId: null,
+ lockedByOther: false,
+ ownerId: undefined,
+ pending: false,
+ };
+ },
}));
vi.mock('@/libs/swr', () => ({
@@ -126,3 +131,39 @@ describe('useDocumentLock — lockOwnerId publication into the document store',
expect(useDocumentStore.getState().documents['doc-1'].lockOwnerId).toBeUndefined();
});
});
+
+describe('useDocumentLock — inside a collaboration room', () => {
+ beforeEach(() => {
+ editLockCalls.value = [];
+ mockPageState.current = {
+ collab: { access: 'edit', pending: 0, status: 'synced' },
+ documentId: 'doc-1',
+ isWorkspacePage: true,
+ lockExpiresAt: null,
+ lockOwnerId: undefined,
+ setLockHealth: vi.fn(),
+ setLockOwnerId: vi.fn(),
+ setLockPending: vi.fn(),
+ setLockState: vi.fn(),
+ };
+ });
+
+ it('takes the lock as the room once this member edits, so editors outside the room are locked out', () => {
+ mockPageState.current.collab = { access: 'edit', edited: true, pending: 0, status: 'synced' };
+
+ renderHook(() => useDocumentLock());
+
+ const options = editLockCalls.value.at(-1);
+ expect(options.enabled).toBe(true);
+ expect(options.isDirty).toBe(true);
+ expect(options.ownerId).toMatch(/^room:doc-1:/);
+ });
+
+ it('only watches the lock while this member has not edited', () => {
+ renderHook(() => useDocumentLock());
+
+ const options = editLockCalls.value.at(-1);
+ expect(options.enabled).toBe(true);
+ expect(options.isDirty).toBe(false);
+ });
+});
diff --git a/src/features/PageEditor/useDocumentLock.ts b/src/features/PageEditor/useDocumentLock.ts
index 42858f16ef2..49bc2168f52 100644
--- a/src/features/PageEditor/useDocumentLock.ts
+++ b/src/features/PageEditor/useDocumentLock.ts
@@ -11,6 +11,7 @@ import { useDocumentStore } from '@/store/document';
import { documentDetailResource } from '@/store/document/slices/document/projection';
import { editorSelectors } from '@/store/document/slices/editor';
+import { isRoomLockOwner, ROOM_LOCK_OWNER_PREFIX } from './collab/roomLock';
import { usePageEditorStore } from './store';
import { usePageLockedByOther } from './usePageLockedByOther';
@@ -21,13 +22,13 @@ const documentLockClient: EditLockClient = {
release: (id, ownerId) => documentService.releaseDocumentLock(id, ownerId),
};
-const createLockOwnerId = (documentId: string) => {
+const createLockOwnerId = (documentId: string, inRoom: boolean) => {
const randomId =
typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2)}`;
- return `page:${documentId}:${randomId}`;
+ return `${inRoom ? ROOM_LOCK_OWNER_PREFIX : 'page:'}${documentId}:${randomId}`;
};
/**
@@ -72,14 +73,12 @@ export const useDocumentLock = () => {
'document',
isWorkspacePage && documentId ? documentId : undefined,
);
- // A collaboration room merges concurrent edits, so it never takes the lock.
const inRoom = usePageEditorStore((s) => !!s.collab);
- const workspacePage = Boolean(
- documentId && canEdit && canEditResource && isWorkspacePage && !inRoom,
- );
+ const editedInRoom = usePageEditorStore((s) => !!s.collab?.edited);
+ const workspacePage = Boolean(documentId && canEdit && canEditResource && isWorkspacePage);
const ownerId = useMemo(
- () => (documentId ? createLockOwnerId(documentId) : undefined),
- [documentId],
+ () => (documentId ? createLockOwnerId(documentId, inRoom) : undefined),
+ [documentId, inRoom],
);
useEffect(() => {
@@ -107,7 +106,7 @@ export const useDocumentLock = () => {
const lock = useEditLock({
client: documentLockClient,
enabled: workspacePage,
- isDirty,
+ isDirty: inRoom ? editedInRoom : isDirty,
ownerId,
pollWhileViewing: false,
resourceId: documentId,
@@ -123,9 +122,12 @@ export const useDocumentLock = () => {
setLockPending(lock.pending);
}, [lock.pending, setLockPending]);
+ // Another room member holding the lock is the room holding it, not a lost lease.
+ const health =
+ inRoom && lock.lockedByOther && isRoomLockOwner(lock.ownerId) ? 'healthy' : lock.health;
useEffect(() => {
- setLockHealth(lock.health);
- }, [lock.health, setLockHealth]);
+ setLockHealth(health);
+ }, [health, setLockHealth]);
// After recovering from a lost lease, refresh the document so we don't paint
// over edits another member made while we were disconnected. The existing
@@ -136,10 +138,10 @@ export const useDocumentLock = () => {
useEffect(() => {
const recovered = prevHealthRef.current === 'lost' && lock.health === 'healthy';
prevHealthRef.current = lock.health;
- if (recovered && documentId) {
+ if (recovered && documentId && !inRoom) {
void revalidateReplica(documentDetailResource, documentId);
}
- }, [lock.health, documentId]);
+ }, [lock.health, documentId, inRoom]);
// Re-hydrate content whenever the lock flips — on open if already held, or when
// another member takes/releases it (events land in the store via the bridge or
@@ -147,7 +149,8 @@ export const useDocumentLock = () => {
// version is newer). Prevents a stale snapshot from clobbering their edits.
const wasLockedByOtherRef = useRef(false);
useEffect(() => {
- if (!workspacePage || !documentId) {
+ // The room streams the body, so there is no stored copy to refresh.
+ if (!workspacePage || !documentId || inRoom) {
wasLockedByOtherRef.current = false;
return;
}
@@ -156,7 +159,7 @@ export const useDocumentLock = () => {
if (isLockedByOther || tookOver || saveBlockedByLock) {
void revalidateReplica(documentDetailResource, documentId);
}
- }, [workspacePage, documentId, isLockedByOther, saveBlockedByLock]);
+ }, [workspacePage, documentId, inRoom, isLockedByOther, saveBlockedByLock]);
// Recovery: once the lock has resolved and the server confirms we can write
// again, drop any stale save-block from an earlier CONFLICT. Without this the
diff --git a/src/features/PageEditor/usePageEditable.test.ts b/src/features/PageEditor/usePageEditable.test.ts
new file mode 100644
index 00000000000..82763b90d84
--- /dev/null
+++ b/src/features/PageEditor/usePageEditable.test.ts
@@ -0,0 +1,56 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { usePageEditable } from './usePageEditable';
+
+const editorState = vi.hoisted(() => ({ value: {} as Record<string, unknown> }));
+const lock = vi.hoisted(() => ({ lockedByOther: false }));
+
+vi.mock('./store', () => ({
+ usePageEditorStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector(editorState.value),
+}));
+
+vi.mock('./usePageLockedByOther', () => ({ usePageLockedByOther: () => lock.lockedByOther }));
+
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+
+vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
+ useResourceAccess: () => ({ canEditResource: true }),
+}));
+
+describe('usePageEditable in a collaboration room', () => {
+ beforeEach(() => {
+ lock.lockedByOther = false;
+ editorState.value = {
+ collab: { access: 'edit', pending: 0, status: 'synced' },
+ documentId: 'doc_1',
+ isWorkspacePage: true,
+ };
+ });
+
+ it('lets an editor type once the room synced', () => {
+ expect(renderHook(() => usePageEditable()).result.current).toBe(true);
+ });
+
+ it('turns the page read-only while the room blocks it', () => {
+ editorState.value = {
+ ...editorState.value,
+ collab: { access: 'edit', blocked: 'too_large', pending: 0, status: 'synced' },
+ };
+
+ expect(renderHook(() => usePageEditable()).result.current).toBe(false);
+ });
+
+ it('turns the page read-only while someone editing outside the room holds the lock', () => {
+ lock.lockedByOther = true;
+
+ expect(renderHook(() => usePageEditable()).result.current).toBe(false);
+ });
+
+ it('stays read-only until the lock check settles', () => {
+ editorState.value = { ...editorState.value, isLockPending: true };
+
+ expect(renderHook(() => usePageEditable()).result.current).toBe(false);
+ });
+});
diff --git a/src/features/PageEditor/usePageEditable.ts b/src/features/PageEditor/usePageEditable.ts
index f8e450c3c10..d50e67964b8 100644
--- a/src/features/PageEditor/usePageEditable.ts
+++ b/src/features/PageEditor/usePageEditable.ts
@@ -50,6 +50,9 @@ export const usePageEditable = (): boolean => {
hasEditPermission &&
canEditResource &&
collab.access === 'edit' &&
+ !collab.blocked &&
+ !isLockedByOther &&
+ !isLockPending &&
(collab.status === 'synced' || collab.status === 'offline')
);
}
diff --git a/src/features/PageEditor/usePageLockedByOther.test.ts b/src/features/PageEditor/usePageLockedByOther.test.ts
index 96dcb99bf2b..c310e12742e 100644
--- a/src/features/PageEditor/usePageLockedByOther.test.ts
+++ b/src/features/PageEditor/usePageLockedByOther.test.ts
@@ -70,4 +70,42 @@ describe('isLockedByOtherSession', () => {
}),
).toBe(false);
});
+
+ describe('collaboration rooms', () => {
+ it('is not locked for a room session when another room member holds the lock', () => {
+ expect(
+ isLockedByOtherSession({
+ holderId: 'user-2',
+ holderOwnerId: 'room:doc-1:peer',
+ inRoom: true,
+ myOwnerId: 'room:doc-1:me',
+ myUserId: 'user-1',
+ }),
+ ).toBe(false);
+ });
+
+ it('is locked for a room session when someone editing outside the room holds the lock', () => {
+ expect(
+ isLockedByOtherSession({
+ holderId: 'user-2',
+ holderOwnerId: 'page:doc-1:other',
+ inRoom: true,
+ myOwnerId: 'room:doc-1:me',
+ myUserId: 'user-1',
+ }),
+ ).toBe(true);
+ });
+
+ it('is locked outside the room while the room holds the lock', () => {
+ expect(
+ isLockedByOtherSession({
+ holderId: 'user-2',
+ holderOwnerId: 'room:doc-1:peer',
+ inRoom: false,
+ myOwnerId: 'page:doc-1:me',
+ myUserId: 'user-1',
+ }),
+ ).toBe(true);
+ });
+ });
});
diff --git a/src/features/PageEditor/usePageLockedByOther.ts b/src/features/PageEditor/usePageLockedByOther.ts
index 005530870ee..938e53a0b52 100644
--- a/src/features/PageEditor/usePageLockedByOther.ts
+++ b/src/features/PageEditor/usePageLockedByOther.ts
@@ -3,6 +3,7 @@
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
+import { isRoomLockOwner } from './collab/roomLock';
import { usePageEditorStore } from './store';
interface LockedByOtherSessionInput {
@@ -10,6 +11,8 @@ interface LockedByOtherSessionInput {
holderId: string | null | undefined;
/** Edit-session id of the current holder (null for legacy/unknown). */
holderOwnerId: string | null | undefined;
+ /** This session edits through the page's collaboration room. */
+ inRoom?: boolean;
/** This page instance's own edit-session id. */
myOwnerId: string | undefined;
myUserId: string | undefined;
@@ -29,10 +32,12 @@ interface LockedByOtherSessionInput {
export const isLockedByOtherSession = ({
holderId,
holderOwnerId,
+ inRoom,
myOwnerId,
myUserId,
}: LockedByOtherSessionInput): boolean => {
if (!holderId) return false;
+ if (inRoom && isRoomLockOwner(holderOwnerId)) return false;
if (holderId !== myUserId) return true;
return Boolean(holderOwnerId && myOwnerId && holderOwnerId !== myOwnerId);
@@ -49,10 +54,12 @@ export const usePageLockedByOther = (): boolean => {
const lockHolderOwnerId = usePageEditorStore((s) => s.lockHolderOwnerId);
const myOwnerId = usePageEditorStore((s) => s.lockOwnerId);
const myUserId = useUserStore(userProfileSelectors.userId);
+ const inRoom = usePageEditorStore((s) => !!s.collab);
return isLockedByOtherSession({
holderId: lockHolderId,
holderOwnerId: lockHolderOwnerId,
+ inRoom,
myOwnerId,
myUserId,
});
diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.ts
index ed3b46ffa17..82cc48738cf 100644
--- a/src/features/Settings/labs/features.ts
+++ b/src/features/Settings/labs/features.ts
@@ -27,6 +27,7 @@ type LabFeatureI18nKey =
| 'imessage'
| 'messageTextSelectionActions'
| 'oauthApps'
+ | 'pageCollab'
| 'projects'
| 'selfLearning'
| 'topicBugReport';
@@ -135,6 +136,14 @@ const ALL_LAB_FEATURES: LabFeatureItem[] = [
searchKeywords: ['artifact', 'deploy', 'publish'],
stage: 'beta',
},
+ {
+ businessOnly: true,
+ flag: 'enablePageCollab',
+ i18nKey: 'pageCollab',
+ searchKeywords: ['collaboration', 'co-editing', 'realtime', 'live editing', 'page'],
+ stage: 'alpha',
+ workspaceOnly: true,
+ },
{
desktopOnly: true,
flag: 'enableDesktopSplitView',
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index c09f7e7a26d..e595822e4ae 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -28,7 +28,8 @@ export const serverConfigSelectors = {
s.featureFlags.enableAgentKnowledgeSpace === true,
enableMarketTrustedClient: (s: ServerConfigStore) =>
s.serverConfig.enableMarketTrustedClient || false,
- enablePageCollab: (s: ServerConfigStore) => s.serverConfig.enablePageCollab || false,
+ enableWorkspacePageCollab: (s: ServerConfigStore) =>
+ s.serverConfig.enableWorkspacePageCollab || false,
enableUploadFileToServer: (s: ServerConfigStore) => s.serverConfig.enableUploadFileToServer,
/** Workspaces are available to this user (business deployment + per-user `workspace` flag). */
enableWorkspace: (s: ServerConfigStore) =>
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 98e2784dbea..172b4853759 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -23,6 +23,7 @@ export const labPreferSelectors = {
s.preference.lab?.enableMessageTextSelectionActions ??
DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??
false,
+ enablePageCollab: (s: UserState): boolean => s.preference.lab?.enablePageCollab ?? false,
enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,
enableSelfLearning: (s: UserState): boolean => s.preference.lab?.enableSelfLearning ?? false,
enableProjects: (s: UserState): boolean => s.preference.lab?.enableProjects ?? false,