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.

✨ feat(openapi): add /api/v1/documents to create, read, list and replace documents (#23463)

Innei6c257ed50341
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index b67e2a7019d..0d7f7870745 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -1,7 +1,6 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
-import { notifyDocumentMention } from '@/business/server/document-mention/notifyActivity';
import { businessFileTransferStorageCheck } from '@/business/server/lambda-routers/file';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
@@ -11,7 +10,6 @@ import { ChunkModel } from '@/database/models/chunk';
import { DOCUMENT_TRANSFER_FOREIGN_ROWS, DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
-import { RbacModel } from '@/database/models/rbac';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { WorkModel } from '@/database/models/work';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
@@ -19,21 +17,21 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DocumentService } from '@/server/services/document';
import { resolveDocumentWrite } from '@/server/services/document/editorData';
-import { canViewDocumentContent, getDocumentForViewer } from '@/server/services/documentAccess';
+import {
+ assertCanCreateUnderParent,
+ createDocumentFromInput,
+ updateDocumentFromInput,
+} from '@/server/services/document/writeFlow';
+import { getDocumentForViewer } from '@/server/services/documentAccess';
import { FileService } from '@/server/services/file';
import { resolvePageAccess } from '@/server/services/pageCollab';
-import {
- snapshotPageThroughRoom,
- updateDocumentThroughRoom,
-} from '@/server/services/pageCollab/bodyWriter';
+import { snapshotPageThroughRoom } from '@/server/services/pageCollab/bodyWriter';
import { dropPageRooms } from '@/server/services/pageCollab/notify';
import {
assertCanPerformResourceAction,
buildResourcePermissionState,
- getResourceMeta,
} from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
-import { after } from '@/server/utils/scheduleAfterResponse';
import { TransferErrorCode } from '@/types/transferError';
import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
@@ -52,96 +50,12 @@ import {
updateDocumentInputSchema,
} from './_schema/documentHistory';
-/**
- * Creating a child or moving a row requires the parent to be visible in the
- * caller's workspace. Resource writes are role-gated at the procedure layer;
- * creator ownership and General Access do not further narrow ordinary Member
- * operations.
- */
-const assertCanCreateUnderParent = async (
- ctx: {
- serverDB: Parameters<typeof getResourceMeta>[0];
- userId: string;
- workspaceId?: string | null;
- },
- parentId: string | undefined,
-) => {
- if (!ctx.workspaceId || !parentId) return;
- const meta = await getResourceMeta(ctx.serverDB, 'document', parentId);
- if (
- !meta ||
- meta.workspaceId !== ctx.workspaceId ||
- (meta.visibility === 'private' && meta.userId !== ctx.userId)
- ) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Parent document not found' });
- }
- await assertContentsNotInRestrictedKnowledgeBase(ctx, [parentId]);
-};
-
const getFreeDocumentHistorySince = () => {
const now = Date.now();
return new Date(now - FREE_DOCUMENT_HISTORY_WINDOW_DAYS * 24 * 60 * 60 * 1000);
};
-/**
- * Ping members newly @-mentioned in the document body. Runs after the response
- * and re-checks each recipient against the document's General access, so a
- * chip for someone outside a private page never leaks its existence. The
- * business slot is a no-op outside Cloud.
- */
-const notifyDocumentMentionsBestEffort = (
- ctx: { serverDB: Parameters<typeof getResourceMeta>[0]; userId: string; workspaceId: string },
- params: { documentId: string; mentionedUserIds: string[]; savedAt: Date },
-) => {
- const recipientUserIds = [...new Set(params.mentionedUserIds)].filter(
- (userId) => userId !== ctx.userId,
- );
- if (recipientUserIds.length === 0) return;
-
- after(async () => {
- try {
- const [meta, permissionsByUserId] = await Promise.all([
- getResourceMeta(ctx.serverDB, 'document', params.documentId),
- RbacModel.getWorkspaceUsersPermissions({
- db: ctx.serverDB,
- requireMembership: true,
- userIds: recipientUserIds,
- workspaceId: ctx.workspaceId,
- }),
- ]);
- if (!meta) return;
-
- await Promise.all(
- recipientUserIds.map(async (recipientUserId) => {
- const grantedPermissions = permissionsByUserId.get(recipientUserId);
- if (!grantedPermissions) return;
-
- const canView = await canViewDocumentContent({
- db: ctx.serverDB,
- grantedPermissions,
- meta,
- resourceId: params.documentId,
- userId: recipientUserId,
- workspaceId: ctx.workspaceId,
- });
- if (!canView) return;
-
- await notifyDocumentMention({
- actorUserId: ctx.userId,
- documentId: params.documentId,
- recipientUserId,
- savedAt: params.savedAt,
- workspaceId: ctx.workspaceId,
- });
- }),
- );
- } catch (error) {
- console.error('[document] Failed to send mention notification', error);
- }
- });
-};
-
/**
* Credit a document written inside an agent run to that run as a Work version,
* so run consumers (a Goal harvesting a Task's deliverables) can find it. Agents
@@ -223,37 +137,7 @@ export const documentRouter = router({
)
.mutation(async ({ ctx, input }) => {
const { operationId, ...documentInput } = input;
- // Resolve parentId if it's a slug
- let resolvedParentId = documentInput.parentId;
- if (documentInput.parentId) {
- const docBySlug = await ctx.documentModel.findBySlug(documentInput.parentId);
- if (docBySlug) {
- resolvedParentId = docBySlug.id;
- }
- }
-
- await assertCanCreateUnderParent(ctx, resolvedParentId);
-
- const { content, editorData } = await resolveDocumentWrite({
- content: documentInput.content,
- editorData: documentInput.editorData ? JSON.parse(documentInput.editorData) : undefined,
- fileType: documentInput.fileType,
- title: documentInput.title,
- });
- const document = await ctx.documentService.createDocument({
- ...documentInput,
- content,
- editorData,
- parentId: resolvedParentId,
- });
- if (ctx.workspaceId && document.visibility !== 'private') {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
- 'document',
- document.id,
- DEFAULT_RESOURCE_ACCESS_LEVELS.document,
- ctx.userId,
- );
- }
+ const document = await createDocumentFromInput(ctx, documentInput);
await registerRunDocumentWork(ctx, {
changeType: 'created',
documentId: document.id,
@@ -596,73 +480,20 @@ export const documentRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
- await assertContentsNotInRestrictedKnowledgeBase(ctx, [input.id]);
-
- const { id, editorData: editorDataString, operationId, ...params } = input;
- // A content-only write (the CLI) sends no editorData and often no fileType
- // or title; the stored fileType decides whether to build editorData from
- // Markdown, and the stored title names the heading to drop from it.
- // An HTML page never gets any (the service drops editorData sent for one).
- const needsStoredDocument =
- params.content !== undefined &&
- !editorDataString &&
- (params.fileType === undefined || params.title === undefined);
- const currentDocument =
- input.parentId !== undefined || needsStoredDocument
- ? await ctx.documentModel.findById(input.id)
- : undefined;
-
- // A move mutates both the source and destination trees as well as the
- // document. Only check when the parent really changes: several editor
- // paths include the current parentId in ordinary metadata/autosave
- // updates. `null` is an explicit detach and still leaves the source.
- if (input.parentId !== undefined) {
- const currentParentId = currentDocument?.parentId ?? null;
- const nextParentId = input.parentId ?? null;
- if (currentParentId !== nextParentId) {
- if (currentParentId) await assertCanCreateUnderParent(ctx, currentParentId);
- if (nextParentId) await assertCanCreateUnderParent(ctx, nextParentId);
- }
- }
-
- const { content, editorData } = await resolveDocumentWrite({
- content: params.content,
- editorData: editorDataString ? JSON.parse(editorDataString) : undefined,
- fileType: params.fileType ?? currentDocument?.fileType,
- title: params.title ?? currentDocument?.title ?? undefined,
- });
- // A page with a live room projects the room over its row, so the body
- // (from the CLI or a client that predates rooms) goes into the room.
- const result = await updateDocumentThroughRoom(
- ctx.serverDB,
- ctx.documentService,
- id,
- { ...params, content, editorData },
- { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },
- );
+ const { operationId, ...updateInput } = input;
+ const result = await updateDocumentFromInput(ctx, updateInput);
// Only a change to what the document says is a new deliverable version;
// a move or a file-type change is not.
- if (result && (params.content !== undefined || params.title !== undefined)) {
+ if (result && (input.content !== undefined || input.title !== undefined)) {
await registerRunDocumentWork(ctx, {
changeType: 'updated',
- documentId: id,
+ documentId: input.id,
operationId,
toolName: 'updateDocument',
});
}
- if (ctx.workspaceId && result?.addedMentionUserIds && result.savedAt) {
- notifyDocumentMentionsBestEffort(
- { serverDB: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
- {
- documentId: id,
- mentionedUserIds: result.addedMentionUserIds,
- savedAt: result.savedAt,
- },
- );
- }
-
return result;
}),
diff --git a/apps/server/src/services/document/__tests__/writeFlow.test.ts b/apps/server/src/services/document/__tests__/writeFlow.test.ts
new file mode 100644
index 00000000000..eaa351279fc
--- /dev/null
+++ b/apps/server/src/services/document/__tests__/writeFlow.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getResourceMeta, type ResourceMeta } from '@/server/services/resourcePermission';
+
+import { createDocumentFromInput, type DocumentWriteContext } from '../writeFlow';
+
+vi.mock('@/business/server/document-mention/notifyActivity', () => ({
+ notifyDocumentMention: vi.fn(),
+}));
+vi.mock('@/server/services/knowledgeBaseAccess', () => ({
+ assertContentsNotInRestrictedKnowledgeBase: vi.fn(),
+}));
+vi.mock('@/server/services/resourcePermission', () => ({ getResourceMeta: vi.fn() }));
+vi.mock('@/database/models/resourcePermission', () => ({
+ ResourcePermissionModel: class {
+ setAccessLevel = vi.fn();
+ },
+}));
+vi.mock('../editorData', () => ({
+ resolveDocumentWrite: async ({ content }: { content?: string }) => ({
+ content,
+ editorData: content === undefined ? undefined : { root: {} },
+ }),
+}));
+
+const buildContext = (workspaceId?: string) => {
+ const createDocument = vi.fn(async (params: { parentId?: string; title: string }) => ({
+ id: 'doc-new',
+ parentId: params.parentId ?? null,
+ title: params.title,
+ visibility: 'private',
+ }));
+ const findBySlug = vi.fn(async (slug: string) =>
+ slug === 'meeting-minutes' ? { id: 'folder-id' } : undefined,
+ );
+ const ctx = {
+ documentModel: { findBySlug },
+ documentService: { createDocument },
+ serverDB: {},
+ userId: 'user-1',
+ workspaceId,
+ } as unknown as DocumentWriteContext;
+
+ return { createDocument, ctx };
+};
+
+describe('createDocumentFromInput', () => {
+ beforeEach(() => {
+ vi.mocked(getResourceMeta).mockReset();
+ });
+
+ it('creates inside a folder addressed by its slug', async () => {
+ const { createDocument, ctx } = buildContext();
+
+ await createDocumentFromInput(ctx, {
+ content: '# Weekly sync',
+ parentId: 'meeting-minutes',
+ title: 'Weekly sync',
+ });
+
+ expect(createDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ editorData: { root: {} }, parentId: 'folder-id' }),
+ );
+ });
+
+ it('creates inside a folder addressed by its id', async () => {
+ const { createDocument, ctx } = buildContext();
+
+ await createDocumentFromInput(ctx, { parentId: 'folder-id', title: 'Weekly sync' });
+
+ expect(createDocument).toHaveBeenCalledWith(expect.objectContaining({ parentId: 'folder-id' }));
+ });
+
+ it('refuses a workspace parent the caller cannot see, before writing', async () => {
+ const { createDocument, ctx } = buildContext('ws-1');
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'someone-else',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ } satisfies ResourceMeta);
+
+ await expect(
+ createDocumentFromInput(ctx, { parentId: 'folder-id', title: 'Weekly sync' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(createDocument).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index 2d4ad8ba080..d0c1aeb452a 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -20,7 +20,7 @@ import { and, eq, sql } from 'drizzle-orm';
import isEqual from 'fast-deep-equal';
import { MAX_FILE_PARSE_SIZE } from '@/const/file';
-import { DocumentModel, type DocumentQuerySortBy } from '@/database/models/document';
+import { DocumentModel, type QueryDocumentParams } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
@@ -318,16 +318,7 @@ export class DocumentService {
/**
* Query documents with pagination
*/
- async queryDocuments(params?: {
- creator?: 'others' | 'self';
- current?: number;
- excludeKnowledgeBaseIds?: string[];
- fileTypes?: string[];
- pageSize?: number;
- sortBy?: DocumentQuerySortBy;
- sourceTypes?: string[];
- standaloneOnly?: boolean;
- }) {
+ async queryDocuments(params?: QueryDocumentParams) {
return this.documentModel.query(params);
}
diff --git a/apps/server/src/services/document/writeFlow.ts b/apps/server/src/services/document/writeFlow.ts
new file mode 100644
index 00000000000..09e16a9c7cc
--- /dev/null
+++ b/apps/server/src/services/document/writeFlow.ts
@@ -0,0 +1,234 @@
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+
+import { notifyDocumentMention } from '@/business/server/document-mention/notifyActivity';
+import type { DocumentModel } from '@/database/models/document';
+import { RbacModel } from '@/database/models/rbac';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { canViewDocumentContent } from '@/server/services/documentAccess';
+import { assertContentsNotInRestrictedKnowledgeBase } from '@/server/services/knowledgeBaseAccess';
+import { updateDocumentThroughRoom } from '@/server/services/pageCollab/bodyWriter';
+import { getResourceMeta } from '@/server/services/resourcePermission';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import type { DocumentService } from '.';
+import { resolveDocumentWrite } from './editorData';
+import type { UpdateDocumentParams, UpdateDocumentResult } from './types';
+
+/**
+ * The create and update paths every document writer shares: the in-app tRPC
+ * router and the public `/api/v1/documents` API. Keeping them here means slug
+ * parents, parent visibility, Markdown → editor data, live-room writes and
+ * mention notifications cannot drift between the two.
+ */
+export interface DocumentWriteContext {
+ documentModel: DocumentModel;
+ documentService: DocumentService;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/**
+ * Creating a child or moving a row requires the parent to be visible in the
+ * caller's workspace. Resource writes are role-gated at the procedure layer;
+ * creator ownership and General Access do not further narrow ordinary Member
+ * operations.
+ */
+export const assertCanCreateUnderParent = async (
+ ctx: Pick<DocumentWriteContext, 'serverDB' | 'userId' | 'workspaceId'>,
+ parentId: string | undefined,
+) => {
+ if (!ctx.workspaceId || !parentId) return;
+ const meta = await getResourceMeta(ctx.serverDB, 'document', parentId);
+ if (
+ !meta ||
+ meta.workspaceId !== ctx.workspaceId ||
+ (meta.visibility === 'private' && meta.userId !== ctx.userId)
+ ) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Parent document not found' });
+ }
+ await assertContentsNotInRestrictedKnowledgeBase(ctx, [parentId]);
+};
+
+/**
+ * Ping members newly @-mentioned in the document body. Runs after the response
+ * and re-checks each recipient against the document's General access, so a
+ * chip for someone outside a private page never leaks its existence. The
+ * business slot is a no-op outside Cloud.
+ */
+const notifyDocumentMentionsBestEffort = (
+ ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId: string },
+ params: { documentId: string; mentionedUserIds: string[]; savedAt: Date },
+) => {
+ const recipientUserIds = [...new Set(params.mentionedUserIds)].filter(
+ (userId) => userId !== ctx.userId,
+ );
+ if (recipientUserIds.length === 0) return;
+
+ after(async () => {
+ try {
+ const [meta, permissionsByUserId] = await Promise.all([
+ getResourceMeta(ctx.serverDB, 'document', params.documentId),
+ RbacModel.getWorkspaceUsersPermissions({
+ db: ctx.serverDB,
+ requireMembership: true,
+ userIds: recipientUserIds,
+ workspaceId: ctx.workspaceId,
+ }),
+ ]);
+ if (!meta) return;
+
+ // One permission read and one notification write per recipient; a page can
+ // mention many members, so bound the fan-out instead of opening them all at once.
+ await pMap(
+ recipientUserIds,
+ async (recipientUserId) => {
+ const grantedPermissions = permissionsByUserId.get(recipientUserId);
+ if (!grantedPermissions) return;
+
+ const canView = await canViewDocumentContent({
+ db: ctx.serverDB,
+ grantedPermissions,
+ meta,
+ resourceId: params.documentId,
+ userId: recipientUserId,
+ workspaceId: ctx.workspaceId,
+ });
+ if (!canView) return;
+
+ await notifyDocumentMention({
+ actorUserId: ctx.userId,
+ documentId: params.documentId,
+ recipientUserId,
+ savedAt: params.savedAt,
+ workspaceId: ctx.workspaceId,
+ });
+ },
+ { concurrency: 5 },
+ );
+ } catch (error) {
+ console.error('[document] Failed to send mention notification', error);
+ }
+ });
+};
+
+export interface CreateDocumentInput {
+ content?: string;
+ /** Serialized editor JSON; when absent the Markdown `content` is converted. */
+ editorData?: string;
+ fileType?: string;
+ knowledgeBaseId?: string;
+ metadata?: Record<string, any>;
+ /** A folder id, or a folder slug. */
+ parentId?: string;
+ slug?: string;
+ title: string;
+ visibility?: 'private' | 'public';
+}
+
+export const createDocumentFromInput = async (
+ ctx: DocumentWriteContext,
+ input: CreateDocumentInput,
+) => {
+ let resolvedParentId = input.parentId;
+ if (input.parentId) {
+ const docBySlug = await ctx.documentModel.findBySlug(input.parentId);
+ if (docBySlug) resolvedParentId = docBySlug.id;
+ }
+
+ await assertCanCreateUnderParent(ctx, resolvedParentId);
+
+ const { content, editorData } = await resolveDocumentWrite({
+ content: input.content,
+ editorData: input.editorData ? JSON.parse(input.editorData) : undefined,
+ fileType: input.fileType,
+ title: input.title,
+ });
+ const document = await ctx.documentService.createDocument({
+ ...input,
+ content,
+ editorData,
+ parentId: resolvedParentId,
+ });
+ if (ctx.workspaceId && document.visibility !== 'private') {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'document',
+ document.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ ctx.userId,
+ );
+ }
+ return document;
+};
+
+export interface UpdateDocumentInput extends Omit<UpdateDocumentParams, 'editorData'> {
+ /** Serialized editor JSON; when absent the Markdown `content` is converted. */
+ editorData?: string;
+ id: string;
+}
+
+export const updateDocumentFromInput = async (
+ ctx: DocumentWriteContext,
+ input: UpdateDocumentInput,
+): Promise<UpdateDocumentResult> => {
+ await assertContentsNotInRestrictedKnowledgeBase(ctx, [input.id]);
+
+ const { id, editorData: editorDataString, ...params } = input;
+ // A content-only write (the CLI) sends no editorData and often no fileType
+ // or title; the stored fileType decides whether to build editorData from
+ // Markdown, and the stored title names the heading to drop from it.
+ // An HTML page never gets any (the service drops editorData sent for one).
+ const needsStoredDocument =
+ params.content !== undefined &&
+ !editorDataString &&
+ (params.fileType === undefined || params.title === undefined);
+ const currentDocument =
+ input.parentId !== undefined || needsStoredDocument
+ ? await ctx.documentModel.findById(input.id)
+ : undefined;
+
+ // A move mutates both the source and destination trees as well as the
+ // document. Only check when the parent really changes: several editor
+ // paths include the current parentId in ordinary metadata/autosave
+ // updates. `null` is an explicit detach and still leaves the source.
+ if (input.parentId !== undefined) {
+ const currentParentId = currentDocument?.parentId ?? null;
+ const nextParentId = input.parentId ?? null;
+ if (currentParentId !== nextParentId) {
+ if (currentParentId) await assertCanCreateUnderParent(ctx, currentParentId);
+ if (nextParentId) await assertCanCreateUnderParent(ctx, nextParentId);
+ }
+ }
+
+ const { content, editorData } = await resolveDocumentWrite({
+ content: params.content,
+ editorData: editorDataString ? JSON.parse(editorDataString) : undefined,
+ fileType: params.fileType ?? currentDocument?.fileType,
+ title: params.title ?? currentDocument?.title ?? undefined,
+ });
+ // A page with a live room projects the room over its row, so the body
+ // (from the CLI or a client that predates rooms) goes into the room.
+ const result = await updateDocumentThroughRoom(
+ ctx.serverDB,
+ ctx.documentService,
+ id,
+ { ...params, content, editorData },
+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },
+ );
+
+ if (ctx.workspaceId && result?.addedMentionUserIds && result.savedAt) {
+ notifyDocumentMentionsBestEffort(
+ { serverDB: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ documentId: id,
+ mentionedUserIds: result.addedMentionUserIds,
+ savedAt: result.savedAt,
+ },
+ );
+ }
+
+ return result;
+};
diff --git a/packages/database/src/models/__tests__/document.queryParent.test.ts b/packages/database/src/models/__tests__/document.queryParent.test.ts
new file mode 100644
index 00000000000..5a467e287cf
--- /dev/null
+++ b/packages/database/src/models/__tests__/document.queryParent.test.ts
@@ -0,0 +1,64 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { documents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { DocumentModel } from '../document';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'doc-query-parent-user';
+
+const insertDocument = async (
+ id: string,
+ parentId: string | null,
+ fileType = 'custom/document',
+) => {
+ await serverDB.insert(documents).values({
+ fileType,
+ id,
+ parentId,
+ source: 'document',
+ sourceType: 'api',
+ title: id,
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await insertDocument('folder', null, 'custom/folder');
+ await insertDocument('subfolder', 'folder', 'custom/folder');
+ await insertDocument('child-1', 'folder');
+ await insertDocument('child-2', 'folder');
+ await insertDocument('grandchild', 'subfolder');
+ await insertDocument('root-page', null);
+});
+
+afterEach(async () => {
+ await serverDB.delete(documents);
+ await serverDB.delete(users);
+});
+
+describe('DocumentModel.query — parentId', () => {
+ it('lists only the direct children of the folder', async () => {
+ const result = await new DocumentModel(serverDB, userId).query({ parentId: 'folder' });
+
+ expect(result.items.map((item) => item.id).sort()).toEqual(['child-1', 'child-2', 'subfolder']);
+ expect(result.total).toBe(3);
+ });
+
+ it('pages by an explicit offset with the same total', async () => {
+ const model = new DocumentModel(serverDB, userId);
+ const first = await model.query({ pageSize: 2, parentId: 'folder', sortBy: 'title' });
+ const rest = await model.query({ offset: 2, pageSize: 2, parentId: 'folder', sortBy: 'title' });
+
+ expect(first.items.map((item) => item.id)).toEqual(['child-1', 'child-2']);
+ expect(rest.items.map((item) => item.id)).toEqual(['subfolder']);
+ expect(rest.total).toBe(3);
+ });
+});
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index 36645335589..fe639032d37 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -61,7 +61,11 @@ export interface QueryDocumentParams {
*/
excludeKnowledgeBaseIds?: string[];
fileTypes?: string[];
+ /** Rows to skip; overrides `current * pageSize` for cursor-backed callers. */
+ offset?: number;
pageSize?: number;
+ /** Keep only the direct children of this folder. */
+ parentId?: string;
/**
* Row order: `updatedAt` (default) and `createdAt` list the newest first,
* `title` lists A→Z. Ties fall back to the id so offset pages never overlap.
@@ -198,6 +202,8 @@ export class DocumentModel {
pageSize = 9999,
excludeKnowledgeBaseIds,
fileTypes,
+ offset: explicitOffset,
+ parentId,
sortBy = 'updatedAt',
sourceTypes,
standaloneOnly,
@@ -205,9 +211,10 @@ export class DocumentModel {
items: DocumentItem[];
total: number;
}> => {
- const offset = current * pageSize;
+ const offset = explicitOffset ?? current * pageSize;
const conditions = [this.readScope()];
+ if (parentId) conditions.push(eq(documents.parentId, parentId));
if (fileTypes?.length) {
conditions.push(inArray(documents.fileType, fileTypes));
}
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index cf9d5e4a6d0..7b414b17e17 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -967,6 +967,80 @@ components:
- order
- role
additionalProperties: false
+ DocumentSummary:
+ type: object
+ properties:
+ createdAt:
+ type: string
+ format: date-time
+ fileType:
+ type: string
+ id:
+ type: string
+ parentId:
+ type:
+ - string
+ - "null"
+ slug:
+ type:
+ - string
+ - "null"
+ title:
+ type:
+ - string
+ - "null"
+ updatedAt:
+ type: string
+ format: date-time
+ required:
+ - createdAt
+ - fileType
+ - id
+ - parentId
+ - slug
+ - title
+ - updatedAt
+ additionalProperties: false
+ Document:
+ type: object
+ properties:
+ createdAt:
+ type: string
+ format: date-time
+ fileType:
+ type: string
+ id:
+ type: string
+ parentId:
+ type:
+ - string
+ - "null"
+ slug:
+ type:
+ - string
+ - "null"
+ title:
+ type:
+ - string
+ - "null"
+ updatedAt:
+ type: string
+ format: date-time
+ content:
+ description: Markdown body.
+ type:
+ - string
+ - "null"
+ required:
+ - createdAt
+ - fileType
+ - id
+ - parentId
+ - slug
+ - title
+ - updatedAt
+ - content
+ additionalProperties: false
EvalRun:
type: object
properties:
@@ -15128,6 +15202,611 @@ paths:
minLength: 1
required:
- agentIds
+ /api/v1/documents:
+ get:
+ operationId: getApiV1Documents
+ summary: List documents
+ tags:
+ - documents
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ type: object
+ properties:
+ items:
+ type: array
+ items:
+ $ref: "#/components/schemas/DocumentSummary"
+ hasMore:
+ $ref: "#/components/schemas/PageHasMore"
+ nextCursor:
+ $ref: "#/components/schemas/PageNextCursor"
+ total:
+ $ref: "#/components/schemas/PageTotal"
+ required:
+ - items
+ - hasMore
+ - nextCursor
+ - total
+ additionalProperties: false
+ message:
+ type: string
+ success:
+ type: boolean
+ const: true
+ timestamp:
+ type: string
+ format: date-time
+ required:
+ - data
+ - success
+ - timestamp
+ additionalProperties: false
+ description: Successful response
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ Retry-After:
+ $ref: "#/components/headers/RetryAfter"
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ parameters:
+ - in: query
+ name: cursor
+ schema:
+ type: string
+ minLength: 1
+ maxLength: 512
+ description: Opaque cursor from the previous page's `nextCursor`. Omit for the
+ first page.
+ - in: query
+ name: limit
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 100
+ description: Page size, 1–100. Defaults to 20.
+ - in: query
+ name: parentId
+ schema:
+ type: string
+ minLength: 1
+ description: Only list the direct children of this folder (id or slug).
+ post:
+ operationId: postApiV1Documents
+ description: 'Creates a page from Markdown, or a folder with `fileType:
+ "custom/folder"`.'
+ summary: Create a document
+ tags:
+ - documents
+ responses:
+ "201":
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ $ref: "#/components/schemas/Document"
+ message:
+ type: string
+ success:
+ type: boolean
+ const: true
+ timestamp:
+ type: string
+ format: date-time
+ required:
+ - data
+ - success
+ - timestamp
+ additionalProperties: false
+ description: Successful response
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ Idempotent-Replayed:
+ $ref: "#/components/headers/IdempotentReplayed"
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ Retry-After:
+ $ref: "#/components/headers/RetryAfter"
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ content:
+ description: Markdown body. Omit for a folder.
+ type: string
+ maxLength: 10000000
+ fileType:
+ description: "`custom/folder` creates a folder; defaults to a page
+ (`custom/document`)."
+ type: string
+ minLength: 1
+ parentId:
+ description: Folder to create in (id or slug).
+ type: string
+ minLength: 1
+ title:
+ type: string
+ minLength: 1
+ required:
+ - title
+ additionalProperties: false
+ parameters:
+ - $ref: "#/components/parameters/IdempotencyKey"
+ /api/v1/documents/{id}:
+ get:
+ operationId: getApiV1DocumentsById
+ summary: Get a document
+ tags:
+ - documents
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ $ref: "#/components/schemas/Document"
+ message:
+ type: string
+ success:
+ type: boolean
+ const: true
+ timestamp:
+ type: string
+ format: date-time
+ required:
+ - data
+ - success
+ - timestamp
+ additionalProperties: false
+ description: Successful response
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ Retry-After:
+ $ref: "#/components/headers/RetryAfter"
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: string
+ minLength: 1
+ required: true
+ patch:
+ operationId: patchApiV1DocumentsById
+ description: Replaces the title and/or the whole Markdown body. A page open in
+ the editor receives the write through its live room.
+ summary: Update a document
+ tags:
+ - documents
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ $ref: "#/components/schemas/Document"
+ message:
+ type: string
+ success:
+ type: boolean
+ const: true
+ timestamp:
+ type: string
+ format: date-time
+ required:
+ - data
+ - success
+ - timestamp
+ additionalProperties: false
+ description: Successful response
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ Retry-After:
+ $ref: "#/components/headers/RetryAfter"
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ headers:
+ X-Request-Id:
+ $ref: "#/components/headers/RequestId"
+ X-RateLimit-Limit:
+ $ref: "#/components/headers/RateLimitLimit"
+ X-RateLimit-Remaining:
+ $ref: "#/components/headers/RateLimitRemaining"
+ X-RateLimit-Reset:
+ $ref: "#/components/headers/RateLimitReset"
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: string
+ minLength: 1
+ required: true
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ content:
+ description: Markdown body; replaces the whole body.
+ type: string
+ maxLength: 10000000
+ title:
+ type: string
+ minLength: 1
+ additionalProperties: false
/api/v1/eval/runs:
post:
operationId: postApiV1EvalRuns
diff --git a/packages/openapi/src/controllers/document.controller.ts b/packages/openapi/src/controllers/document.controller.ts
new file mode 100644
index 00000000000..ec68fbcd38d
--- /dev/null
+++ b/packages/openapi/src/controllers/document.controller.ts
@@ -0,0 +1,69 @@
+import type { Context } from 'hono';
+
+import { BaseController } from '../common/base.controller';
+import { DocumentRestService } from '../services/document.service';
+import type {
+ CreateDocumentRequest,
+ DocumentIdParam,
+ DocumentListQuery,
+ UpdateDocumentRequest,
+} from '../types/document.type';
+
+/** Documents controller — list, read, create and replace documents. */
+export class DocumentController extends BaseController {
+ private async service(c: Context): Promise<DocumentRestService> {
+ return new DocumentRestService(
+ await this.getDatabase(),
+ this.getUserId(c),
+ this.getWorkspaceId(c),
+ );
+ }
+
+ /** GET /api/v1/documents */
+ async listDocuments(c: Context): Promise<Response> {
+ try {
+ const query = this.getQuery<DocumentListQuery>(c);
+ const service = await this.service(c);
+ return this.list(c, 'items', await service.listDocuments(query), {
+ message: 'Document list retrieved successfully',
+ pagination: query,
+ });
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
+ /** GET /api/v1/documents/:id */
+ async getDocument(c: Context): Promise<Response> {
+ try {
+ const { id } = this.getParams<DocumentIdParam>(c);
+ const service = await this.service(c);
+ return this.success(c, await service.getDocument(id), 'Document retrieved successfully');
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
+ /** POST /api/v1/documents */
+ async createDocument(c: Context): Promise<Response> {
+ try {
+ const body = await this.getBody<CreateDocumentRequest>(c);
+ const service = await this.service(c);
+ return this.success(c, await service.createDocument(body), 'Document created', 201);
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
+ /** PATCH /api/v1/documents/:id */
+ async updateDocument(c: Context): Promise<Response> {
+ try {
+ const { id } = this.getParams<DocumentIdParam>(c);
+ const body = await this.getBody<UpdateDocumentRequest>(c);
+ const service = await this.service(c);
+ return this.success(c, await service.updateDocument(id, body), 'Document updated');
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+}
diff --git a/packages/openapi/src/routes/documents.route.test.ts b/packages/openapi/src/routes/documents.route.test.ts
new file mode 100644
index 00000000000..5375e1a89ca
--- /dev/null
+++ b/packages/openapi/src/routes/documents.route.test.ts
@@ -0,0 +1,143 @@
+import type { Context } from 'hono';
+import { Hono } from 'hono';
+import { describe, expect, it, vi } from 'vitest';
+
+import DocumentRoutes from './documents.route';
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));
+vi.mock('@/database/models/rbac', () => ({
+ RbacModel: class {
+ hasAnyPermission = async () => true;
+ },
+}));
+vi.mock('../middleware/auth', () => ({
+ requireAuth: async (_c: Context, next: () => Promise<void>) => next(),
+}));
+vi.mock('../controllers/document.controller', () => ({
+ DocumentController: class {
+ createDocument(c: Context) {
+ return c.json({ data: { id: 'doc-1' }, success: true }, 201);
+ }
+ getDocument(c: Context) {
+ return c.json({ data: { id: 'doc-1' }, success: true });
+ }
+ listDocuments(c: Context) {
+ return c.json({ data: { items: [] }, success: true });
+ }
+ updateDocument(c: Context) {
+ return c.json({ data: { id: 'doc-1' }, success: true });
+ }
+ },
+}));
+
+const requestAs = (scopes: string[], path: string, init?: { body?: unknown; method?: string }) => {
+ const app = new Hono();
+
+ app.use('*', async (c, next) => {
+ c.set('userId' as never, 'user-1' as never);
+ c.set('authType' as never, 'apikey' as never);
+ c.set('apiKeyScopes' as never, scopes as never);
+ await next();
+ });
+ app.route('/', DocumentRoutes);
+
+ return app.request(path, {
+ ...(init?.body === undefined
+ ? {}
+ : { body: JSON.stringify(init.body), headers: { 'content-type': 'application/json' } }),
+ method: init?.method ?? 'GET',
+ });
+};
+
+describe('POST /documents', () => {
+ it('creates a page for a key that may write knowledge', async () => {
+ const res = await requestAs(['knowledge:write'], '/', {
+ body: { content: '# Weekly sync', title: 'Weekly sync' },
+ method: 'POST',
+ });
+
+ expect(res.status).toBe(201);
+ });
+
+ it('creates a folder inside a folder', async () => {
+ const res = await requestAs(['knowledge:write'], '/', {
+ body: { fileType: 'custom/folder', parentId: 'docs_root', title: 'Meeting minutes' },
+ method: 'POST',
+ });
+
+ expect(res.status).toBe(201);
+ });
+
+ it('rejects a read-only key', async () => {
+ const res = await requestAs(['knowledge:read'], '/', {
+ body: { title: 'Weekly sync' },
+ method: 'POST',
+ });
+
+ expect(res.status).toBe(403);
+ });
+
+ it('rejects a document without a title', async () => {
+ const res = await requestAs(['knowledge:write'], '/', {
+ body: { content: 'body only' },
+ method: 'POST',
+ });
+
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects fields the API does not open, such as visibility', async () => {
+ const res = await requestAs(['knowledge:write'], '/', {
+ body: { title: 'Weekly sync', visibility: 'public' },
+ method: 'POST',
+ });
+
+ expect(res.status).toBe(400);
+ });
+});
+
+describe('PATCH /documents/:id', () => {
+ it('replaces the title and body', async () => {
+ const res = await requestAs(['knowledge:write'], '/doc-1', {
+ body: { content: '# New body', title: 'Weekly sync' },
+ method: 'PATCH',
+ });
+
+ expect(res.status).toBe(200);
+ });
+
+ it('rejects an empty update', async () => {
+ const res = await requestAs(['knowledge:write'], '/doc-1', { body: {}, method: 'PATCH' });
+
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a read-only key', async () => {
+ const res = await requestAs(['knowledge:read'], '/doc-1', {
+ body: { title: 'Weekly sync' },
+ method: 'PATCH',
+ });
+
+ expect(res.status).toBe(403);
+ });
+});
+
+describe('GET /documents', () => {
+ it('lists the children of a folder for a read key', async () => {
+ const res = await requestAs(['knowledge:read'], '/?parentId=folder-1&limit=20');
+
+ expect(res.status).toBe(200);
+ });
+
+ it('rejects a key that holds no knowledge scope', async () => {
+ const res = await requestAs(['chat:read'], '/doc-1');
+
+ expect(res.status).toBe(403);
+ });
+
+ it('rejects a page size over 100', async () => {
+ const res = await requestAs(['knowledge:read'], '/?limit=500');
+
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/packages/openapi/src/routes/documents.route.ts b/packages/openapi/src/routes/documents.route.ts
new file mode 100644
index 00000000000..d9abf7bae94
--- /dev/null
+++ b/packages/openapi/src/routes/documents.route.ts
@@ -0,0 +1,98 @@
+import { Hono } from 'hono';
+
+import { getAllScopePermissions } from '@/utils/rbac';
+
+import { routeDoc } from '../common/openapi';
+import { zValidator } from '../common/validator';
+import { DocumentController } from '../controllers/document.controller';
+import { requireAuth } from '../middleware/auth';
+import { requireAnyPermission } from '../middleware/permission-check';
+import {
+ CreateDocumentRequestSchema,
+ DocumentIdParamSchema,
+ DocumentListQuerySchema,
+ DocumentListResponseSchema,
+ DocumentSchema,
+ UpdateDocumentRequestSchema,
+} from '../types/document.type';
+
+/**
+ * Document routes: create, read, list and replace pages and folders.
+ *
+ * Reads and writes are gated by the same `document:*` permissions as the
+ * in-app document surface, and every write goes through the shared document
+ * write flow. History, locks, publishing, visibility and transfers stay
+ * in-app only.
+ */
+const DocumentRoutes = new Hono();
+
+const documentRead = requireAnyPermission(
+ getAllScopePermissions('DOCUMENT_READ'),
+ 'You do not have permission to view documents',
+);
+const documentCreate = requireAnyPermission(
+ getAllScopePermissions('DOCUMENT_CREATE'),
+ 'You do not have permission to create documents',
+);
+const documentUpdate = requireAnyPermission(
+ getAllScopePermissions('DOCUMENT_UPDATE'),
+ 'You do not have permission to update documents',
+);
+
+/** GET /api/v1/documents */
+DocumentRoutes.get(
+ '/',
+ routeDoc({ data: DocumentListResponseSchema, summary: 'List documents', tags: ['documents'] }),
+ requireAuth,
+ documentRead,
+ zValidator('query', DocumentListQuerySchema),
+ async (c) => new DocumentController().listDocuments(c),
+);
+
+/** POST /api/v1/documents */
+DocumentRoutes.post(
+ '/',
+ routeDoc({
+ data: DocumentSchema,
+ description: 'Creates a page from Markdown, or a folder with `fileType: "custom/folder"`.',
+ // 404: the parent folder does not exist or is not visible.
+ errors: [404],
+ status: 201,
+ summary: 'Create a document',
+ tags: ['documents'],
+ }),
+ requireAuth,
+ documentCreate,
+ zValidator('json', CreateDocumentRequestSchema),
+ async (c) => new DocumentController().createDocument(c),
+);
+
+/** GET /api/v1/documents/:id */
+DocumentRoutes.get(
+ '/:id',
+ routeDoc({ data: DocumentSchema, errors: [404], summary: 'Get a document', tags: ['documents'] }),
+ requireAuth,
+ documentRead,
+ zValidator('param', DocumentIdParamSchema),
+ async (c) => new DocumentController().getDocument(c),
+);
+
+/** PATCH /api/v1/documents/:id */
+DocumentRoutes.patch(
+ '/:id',
+ routeDoc({
+ data: DocumentSchema,
+ description:
+ 'Replaces the title and/or the whole Markdown body. A page open in the editor receives the write through its live room.',
+ errors: [404],
+ summary: 'Update a document',
+ tags: ['documents'],
+ }),
+ requireAuth,
+ documentUpdate,
+ zValidator('param', DocumentIdParamSchema),
+ zValidator('json', UpdateDocumentRequestSchema),
+ async (c) => new DocumentController().updateDocument(c),
+);
+
+export default DocumentRoutes;
diff --git a/packages/openapi/src/routes/index.ts b/packages/openapi/src/routes/index.ts
index 022c80b342f..a3d1f0ac41d 100644
--- a/packages/openapi/src/routes/index.ts
+++ b/packages/openapi/src/routes/index.ts
@@ -5,6 +5,7 @@ import ApiKeysRoutes from './api-keys.route';
import AudioRoutes from './audio.route';
import ChatRoutes from './chat.route';
import ChatGroupsRoutes from './chat-groups.route';
+import DocumentsRoutes from './documents.route';
import EvalRoutes from './eval.route';
import FileRoutes from './files.route';
import GoalsRoutes from './goals.route';
@@ -37,6 +38,7 @@ export default {
'audio': AudioRoutes,
'chat': ChatRoutes,
'chat-groups': ChatGroupsRoutes,
+ 'documents': DocumentsRoutes,
'eval': EvalRoutes,
'plugins': PluginsRoutes,
'files': FileRoutes,
diff --git a/packages/openapi/src/services/document.service.test.ts b/packages/openapi/src/services/document.service.test.ts
new file mode 100644
index 00000000000..d27263c935e
--- /dev/null
+++ b/packages/openapi/src/services/document.service.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { updateDocumentFromInput } from '@/server/services/document/writeFlow';
+import { getDocumentForViewer } from '@/server/services/documentAccess';
+
+import { DocumentRestService } from './document.service';
+
+const findById = vi.fn();
+
+vi.mock('@/database/models/rbac', () => ({ RbacModel: class {} }));
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: class {
+ findById = findById;
+ },
+}));
+vi.mock('@/server/services/document', () => ({ DocumentService: class {} }));
+vi.mock('@/server/services/document/writeFlow', () => ({
+ createDocumentFromInput: vi.fn(),
+ updateDocumentFromInput: vi.fn(),
+}));
+vi.mock('@/server/services/documentAccess', () => ({ getDocumentForViewer: vi.fn() }));
+vi.mock('@/server/services/knowledgeBaseAccess', () => ({
+ assertContentsNotInRestrictedKnowledgeBase: vi.fn(),
+ getRestrictedKnowledgeBaseIds: vi.fn(async () => []),
+}));
+
+const storedDocument = {
+ content: 'New body',
+ createdAt: new Date('2026-11-19T01:00:00Z'),
+ fileType: 'custom/document',
+ id: 'doc-1',
+ parentId: 'folder-1',
+ slug: null,
+ title: 'Weekly sync',
+ updatedAt: new Date('2026-11-19T02:00:00Z'),
+};
+
+const service = () => new DocumentRestService({} as LobeChatDatabase, 'user-1');
+
+describe('DocumentRestService', () => {
+ beforeEach(() => {
+ findById.mockReset();
+ vi.mocked(updateDocumentFromInput).mockReset();
+ vi.mocked(getDocumentForViewer).mockReset();
+ });
+
+ it('answers 404 for an update to a document that no longer exists, without writing', async () => {
+ findById.mockResolvedValue(undefined);
+
+ await expect(service().updateDocument('doc-gone', { title: 'x' })).rejects.toMatchObject({
+ status: 404,
+ });
+ expect(updateDocumentFromInput).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 for a document the caller cannot read', async () => {
+ vi.mocked(getDocumentForViewer).mockResolvedValue(undefined);
+
+ await expect(service().getDocument('doc-gone')).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('returns the stored Markdown after a full update', async () => {
+ findById.mockResolvedValue(storedDocument);
+ vi.mocked(getDocumentForViewer).mockResolvedValue(storedDocument as never);
+
+ const document = await service().updateDocument('doc-1', {
+ content: 'New body',
+ title: 'Weekly sync',
+ });
+
+ expect(updateDocumentFromInput).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ content: 'New body', id: 'doc-1', title: 'Weekly sync' }),
+ );
+ expect(document).toEqual({
+ content: 'New body',
+ createdAt: '2026-11-19T01:00:00.000Z',
+ fileType: 'custom/document',
+ id: 'doc-1',
+ parentId: 'folder-1',
+ slug: null,
+ title: 'Weekly sync',
+ updatedAt: '2026-11-19T02:00:00.000Z',
+ });
+ });
+});
diff --git a/packages/openapi/src/services/document.service.ts b/packages/openapi/src/services/document.service.ts
new file mode 100644
index 00000000000..7b7ee1ce280
--- /dev/null
+++ b/packages/openapi/src/services/document.service.ts
@@ -0,0 +1,125 @@
+import { DocumentModel } from '@/database/models/document';
+import type { LobeChatDatabase } from '@/database/type';
+import { DocumentService } from '@/server/services/document';
+import {
+ createDocumentFromInput,
+ type DocumentWriteContext,
+ updateDocumentFromInput,
+} from '@/server/services/document/writeFlow';
+import { getDocumentForViewer } from '@/server/services/documentAccess';
+import {
+ assertContentsNotInRestrictedKnowledgeBase,
+ getRestrictedKnowledgeBaseIds,
+} from '@/server/services/knowledgeBaseAccess';
+
+import { BaseService } from '../common/base.service';
+import { ApiException } from '../common/errors';
+import { resolvePagination } from '../helpers/pagination';
+import type {
+ CreateDocumentRequest,
+ DocumentListQuery,
+ DocumentSummary,
+ PublicDocument,
+ UpdateDocumentRequest,
+} from '../types/document.type';
+
+/** The stored fields this API exposes; `content` is absent from list rows. */
+interface DocumentRow {
+ content?: string | null;
+ createdAt: Date;
+ fileType: string;
+ id: string;
+ parentId: string | null;
+ slug: string | null;
+ title: string | null;
+ updatedAt: Date;
+}
+
+const toSummary = (row: DocumentRow): DocumentSummary => ({
+ createdAt: row.createdAt.toISOString(),
+ fileType: row.fileType,
+ id: row.id,
+ parentId: row.parentId ?? null,
+ slug: row.slug ?? null,
+ title: row.title ?? null,
+ updatedAt: row.updatedAt.toISOString(),
+});
+
+const toPublicDocument = (row: DocumentRow): PublicDocument => ({
+ ...toSummary(row),
+ content: row.content ?? null,
+});
+
+const notFound = (id: string) => new ApiException(404, 'not_found', `Document not found: ${id}`);
+
+/**
+ * Documents REST service.
+ *
+ * Writes go through the same create/update flow as the in-app editor
+ * (`@/server/services/document/writeFlow`): slug parents, the parent
+ * visibility check, Markdown → editor data and writing into an open page's
+ * live room are not re-implemented here.
+ */
+export class DocumentRestService extends BaseService {
+ private readonly documentModel: DocumentModel;
+ private readonly documentService: DocumentService;
+
+ constructor(db: LobeChatDatabase, userId: string | null, workspaceId?: string) {
+ super(db, userId, workspaceId);
+ this.documentModel = new DocumentModel(db, this.userId, workspaceId);
+ this.documentService = new DocumentService(db, this.userId, workspaceId);
+ }
+
+ private get context(): DocumentWriteContext {
+ return {
+ documentModel: this.documentModel,
+ documentService: this.documentService,
+ serverDB: this.db,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+ }
+
+ async listDocuments(query: DocumentListQuery) {
+ const { limit, offset } = resolvePagination(query);
+ let parentId = query.parentId;
+ if (parentId) {
+ const folderBySlug = await this.documentModel.findBySlug(parentId);
+ if (folderBySlug) parentId = folderBySlug.id;
+ }
+ // Pages in restricted (member No-access) libraries stay out of listings,
+ // the same exclusion the in-app sidebar applies.
+ const excludeKnowledgeBaseIds = await getRestrictedKnowledgeBaseIds(this.context);
+ const { items, total } = await this.documentService.queryDocuments({
+ excludeKnowledgeBaseIds,
+ offset,
+ pageSize: limit,
+ parentId,
+ });
+
+ return { items: items.map(toSummary), total };
+ }
+
+ async getDocument(id: string): Promise<PublicDocument> {
+ await assertContentsNotInRestrictedKnowledgeBase(this.context, [id]);
+ const document = await getDocumentForViewer(this.context, id);
+ if (!document) throw notFound(id);
+
+ return toPublicDocument(document);
+ }
+
+ async createDocument(body: CreateDocumentRequest): Promise<PublicDocument> {
+ const document = await createDocumentFromInput(this.context, body);
+
+ return toPublicDocument(document);
+ }
+
+ async updateDocument(id: string, body: UpdateDocumentRequest): Promise<PublicDocument> {
+ // The document service reports a missing row as a plain error; answer 404.
+ if (!(await this.documentModel.findById(id))) throw notFound(id);
+
+ await updateDocumentFromInput(this.context, { ...body, id });
+
+ return this.getDocument(id);
+ }
+}
diff --git a/packages/openapi/src/types/document.type.ts b/packages/openapi/src/types/document.type.ts
new file mode 100644
index 00000000000..d0deae9c355
--- /dev/null
+++ b/packages/openapi/src/types/document.type.ts
@@ -0,0 +1,86 @@
+import { z } from 'zod';
+
+import { DOCUMENT_CONTENT_MAX_LENGTH } from '@/server/routers/lambda/_schema/documentHistory';
+
+import { CursorPaginationQuerySchema, paginatedListSchema } from '../helpers/pagination';
+import { dateTimeSchema } from './common.type';
+
+// ==================== Path / Query Schemas ====================
+
+export const DocumentIdParamSchema = z.object({
+ id: z.string().min(1),
+});
+export type DocumentIdParam = z.infer<typeof DocumentIdParamSchema>;
+
+export const DocumentListQuerySchema = z.object({
+ ...CursorPaginationQuerySchema.shape,
+ parentId: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('Only list the direct children of this folder (id or slug).'),
+});
+export type DocumentListQuery = z.infer<typeof DocumentListQuerySchema>;
+
+// ==================== Request Schemas ====================
+
+export const CreateDocumentRequestSchema = z
+ .object({
+ content: z
+ .string()
+ .max(DOCUMENT_CONTENT_MAX_LENGTH)
+ .optional()
+ .describe('Markdown body. Omit for a folder.'),
+ fileType: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('`custom/folder` creates a folder; defaults to a page (`custom/document`).'),
+ parentId: z.string().min(1).optional().describe('Folder to create in (id or slug).'),
+ title: z.string().min(1),
+ })
+ .strict();
+export type CreateDocumentRequest = z.infer<typeof CreateDocumentRequestSchema>;
+
+export const UpdateDocumentRequestSchema = z
+ .object({
+ content: z
+ .string()
+ .max(DOCUMENT_CONTENT_MAX_LENGTH)
+ .optional()
+ .describe('Markdown body; replaces the whole body.'),
+ title: z.string().min(1).optional(),
+ })
+ .strict()
+ .refine((value) => value.content !== undefined || value.title !== undefined, {
+ message: 'Provide content or title',
+ });
+export type UpdateDocumentRequest = z.infer<typeof UpdateDocumentRequestSchema>;
+
+// ==================== Response Schemas ====================
+
+const documentSummaryShape = {
+ createdAt: dateTimeSchema,
+ fileType: z.string(),
+ id: z.string(),
+ parentId: z.string().nullable(),
+ slug: z.string().nullable(),
+ title: z.string().nullable(),
+ updatedAt: dateTimeSchema,
+};
+
+export const DocumentSummarySchema = z
+ .object(documentSummaryShape)
+ .strict()
+ .meta({ id: 'DocumentSummary' });
+export type DocumentSummary = z.infer<typeof DocumentSummarySchema>;
+
+export const DocumentSchema = z
+ .object({ ...documentSummaryShape, content: z.string().nullable().describe('Markdown body.') })
+ .strict()
+ .meta({ id: 'Document' });
+export type PublicDocument = z.infer<typeof DocumentSchema>;
+
+export const DocumentListResponseSchema = paginatedListSchema(DocumentSummarySchema, {
+ total: true,
+});