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(documents): drop the body heading that repeats the title on Markdown writes (#21553)

LiJianff1b24cfab57
diff --git a/apps/server/src/routers/lambda/document.test.ts b/apps/server/src/routers/lambda/document.test.ts
index 43812e637c5..a44f6a3e521 100644
--- a/apps/server/src/routers/lambda/document.test.ts
+++ b/apps/server/src/routers/lambda/document.test.ts
@@ -8,6 +8,7 @@ import { documentRouter } from './document';
const mocks = vi.hoisted(() => ({
createDocument: vi.fn(),
+ createDocuments: vi.fn(),
findDocumentById: vi.fn(),
findOwnOperationById: vi.fn(),
getDocumentById: vi.fn(),
@@ -39,6 +40,7 @@ vi.mock('@/server/services/document', () => ({
DocumentService: vi.fn().mockImplementation(function () {
return {
createDocument: mocks.createDocument,
+ createDocuments: mocks.createDocuments,
getDocumentById: mocks.getDocumentById,
updateDocument: mocks.updateDocument,
};
@@ -241,3 +243,69 @@ describe('HTML document writes', () => {
);
});
});
+
+/**
+ * Regression: `lh doc create --title X` with a body that opens with `# X`
+ * rendered the title twice on the page — once as the page header, once as
+ * the body H1. Only agent documents dropped that heading.
+ */
+describe('Markdown writes drop the heading that repeats the title', () => {
+ const title = 'rc 与 device — 讨论纪要(2026-10-20)';
+ const content = `# ${title}\n\n来源:eval 频道\n`;
+
+ beforeEach(() => {
+ for (const mock of Object.values(mocks)) mock.mockReset();
+ mocks.createDocument.mockResolvedValue({ id: 'doc-1', visibility: 'private' });
+ mocks.createDocuments.mockResolvedValue([]);
+ mocks.updateDocument.mockResolvedValue({ id: 'doc-1' });
+ });
+
+ it('on create', async () => {
+ await (await caller()).createDocument({ content, title });
+
+ expect(mocks.createDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '来源:eval 频道\n', title }),
+ );
+ });
+
+ it('on batch create', async () => {
+ await (await caller()).createDocuments({ documents: [{ content, title }] });
+
+ expect(mocks.createDocuments).toHaveBeenCalledWith([
+ expect.objectContaining({ content: '来源:eval 频道\n', title }),
+ ]);
+ });
+
+ it('on a content-only edit, against the stored title', async () => {
+ mocks.findDocumentById.mockResolvedValue({ fileType: 'custom/document', id: 'doc-1', title });
+
+ await (await caller()).updateDocument({ content, id: 'doc-1' });
+
+ expect(mocks.updateDocument).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.objectContaining({ content: '来源:eval 频道\n' }),
+ );
+ });
+
+ it('keeps an opening heading that names something else', async () => {
+ await (await caller()).createDocument({ content: '# Background\n\nbody', title });
+
+ expect(mocks.createDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '# Background\n\nbody' }),
+ );
+ });
+
+ it('keeps an editor save, which sends its own editorData, as written', async () => {
+ const editorData = { root: { children: [{ type: 'heading' }], type: 'root' } };
+
+ await (
+ await caller()
+ ).updateDocument({ content, editorData: JSON.stringify(editorData), id: 'doc-1' });
+
+ expect(mocks.findDocumentById).not.toHaveBeenCalled();
+ expect(mocks.updateDocument).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.objectContaining({ content, editorData }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 3672c143e0d..21f5298bb0b 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -18,7 +18,7 @@ import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DocumentService } from '@/server/services/document';
-import { resolveDocumentEditorData } from '@/server/services/document/editorData';
+import { resolveDocumentWrite } from '@/server/services/document/editorData';
import { canViewDocumentContent, getDocumentForViewer } from '@/server/services/documentAccess';
import { FileService } from '@/server/services/file';
import {
@@ -226,13 +226,15 @@ export const documentRouter = router({
await assertCanCreateUnderParent(ctx, resolvedParentId);
- const editorData = await resolveDocumentEditorData({
+ 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,
});
@@ -285,14 +287,16 @@ export const documentRouter = router({
}
}
- const editorData = await resolveDocumentEditorData({
+ const { content, editorData } = await resolveDocumentWrite({
content: doc.content,
editorData: doc.editorData ? JSON.parse(doc.editorData) : undefined,
fileType: doc.fileType,
+ title: doc.title,
});
return {
...doc,
+ content,
editorData,
parentId: resolvedParentId,
};
@@ -559,13 +563,16 @@ export const documentRouter = router({
await assertContentsNotInRestrictedKnowledgeBase(ctx, [input.id]);
const { id, editorData: editorDataString, operationId, ...params } = input;
- // A content-only write (the CLI) sends no editorData and names no fileType;
- // the stored fileType decides whether to build editorData from Markdown.
+ // 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 needsStoredFileType =
- params.content !== undefined && params.fileType === undefined && !editorDataString;
+ const needsStoredDocument =
+ params.content !== undefined &&
+ !editorDataString &&
+ (params.fileType === undefined || params.title === undefined);
const currentDocument =
- input.parentId !== undefined || needsStoredFileType
+ input.parentId !== undefined || needsStoredDocument
? await ctx.documentModel.findById(input.id)
: undefined;
@@ -582,13 +589,15 @@ export const documentRouter = router({
}
}
- const editorData = await resolveDocumentEditorData({
+ 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,
});
const result = await ctx.documentService.updateDocument(id, {
...params,
+ content,
editorData,
});
diff --git a/apps/server/src/services/document/editorData.test.ts b/apps/server/src/services/document/editorData.test.ts
index 24e9a8d3e64..3c789529bc7 100644
--- a/apps/server/src/services/document/editorData.test.ts
+++ b/apps/server/src/services/document/editorData.test.ts
@@ -4,18 +4,19 @@ import { describe, expect, it } from 'vitest';
import { isValidEditorData } from '@/libs/editor/isValidEditorData';
import { applyLiteXMLOperations, exportEditorDataSnapshot } from '../agentDocuments/headlessEditor';
-import { resolveDocumentEditorData } from './editorData';
+import { resolveDocumentWrite, stripTitleHeading } from './editorData';
-describe('resolveDocumentEditorData', () => {
+describe('resolveDocumentWrite', () => {
it('keeps valid Lexical editorData untouched', async () => {
const editorData = { root: { children: [{ type: 'paragraph' }], type: 'root' } };
- await expect(resolveDocumentEditorData({ content: 'x', editorData })).resolves.toBe(editorData);
+ const write = await resolveDocumentWrite({ content: 'x', editorData });
+ expect(write.editorData).toBe(editorData);
});
it('replaces the `{ type: "doc", content }` shape older CLI builds sent', async () => {
const content = '## Tick Log\n\n- tick 1\n';
- const editorData = await resolveDocumentEditorData({
+ const { editorData } = await resolveDocumentWrite({
content,
editorData: { content, type: 'doc' },
});
@@ -25,7 +26,7 @@ describe('resolveDocumentEditorData', () => {
it('builds editorData when only content is sent, so node ids stay stable across reads', async () => {
const content = '## Tick Log\n\n- tick 1\n';
- const editorData = await resolveDocumentEditorData({ content });
+ const { editorData } = await resolveDocumentWrite({ content });
const first = await exportEditorDataSnapshot({
editorData,
@@ -49,21 +50,73 @@ describe('resolveDocumentEditorData', () => {
});
it('leaves folders and metadata-only updates alone', async () => {
- await expect(
- resolveDocumentEditorData({ content: '', fileType: 'custom/folder' }),
- ).resolves.toBeUndefined();
- await expect(resolveDocumentEditorData({})).resolves.toBeUndefined();
+ await expect(resolveDocumentWrite({ content: '', fileType: 'custom/folder' })).resolves.toEqual(
+ { content: '', editorData: undefined },
+ );
+ await expect(resolveDocumentWrite({})).resolves.toEqual({});
});
it('never builds or keeps editorData for an HTML document', async () => {
const content = '<!doctype html><html><body><h1>Report</h1></body></html>';
const editorData = { root: { children: [{ type: 'paragraph' }], type: 'root' } };
+ await expect(resolveDocumentWrite({ content, fileType: 'custom/html' })).resolves.toEqual({
+ content,
+ editorData: undefined,
+ });
await expect(
- resolveDocumentEditorData({ content, fileType: 'custom/html' }),
- ).resolves.toBeUndefined();
- await expect(
- resolveDocumentEditorData({ content, editorData, fileType: 'custom/html' }),
- ).resolves.toBeUndefined();
+ resolveDocumentWrite({ content, editorData, fileType: 'custom/html', title: 'Report' }),
+ ).resolves.toEqual({ content, editorData: undefined });
+ });
+
+ it('drops the heading that repeats the title from a Markdown write and its editorData', async () => {
+ const write = await resolveDocumentWrite({
+ content: '# rc 与 device — 讨论纪要\n\n来源:eval 频道\n',
+ title: 'rc 与 device — 讨论纪要',
+ });
+
+ expect(write.content).toBe('来源:eval 频道\n');
+ const snapshot = await exportEditorDataSnapshot({
+ editorData: write.editorData,
+ fallbackContent: write.content!,
+ litexml: true,
+ });
+ expect(snapshot.litexml).not.toContain('<h1');
+ });
+
+ it('keeps content saved together with editorData as the editor wrote it', async () => {
+ const editorData = { root: { children: [{ type: 'paragraph' }], type: 'root' } };
+ const content = '# Plan\n\nbody';
+
+ await expect(resolveDocumentWrite({ content, editorData, title: 'Plan' })).resolves.toEqual({
+ content,
+ editorData,
+ });
+ });
+});
+
+describe('stripTitleHeading', () => {
+ it('drops a heading equal to the title, ignoring case, spacing and closing hashes', () => {
+ expect(stripTitleHeading('# Weekly Report #\n\nbody', 'weekly report')).toBe('body');
+ });
+
+ it('drops a heading that differs from the title only by a suffix', () => {
+ expect(stripTitleHeading('# 任务验证未通过汇总\n\nbody', '任务验证未通过汇总(T-77)')).toBe(
+ 'body',
+ );
+ expect(stripTitleHeading('# Report (2026-10-20)\n\nbody', 'Report')).toBe('body');
+ });
+
+ it('keeps a heading that names something other than the title', () => {
+ const content = '# Background\n\nbody';
+
+ expect(stripTitleHeading(content, 'Launch plan')).toBe(content);
+ // A shared prefix that ends mid-word is a different name, not a suffix.
+ expect(stripTitleHeading('# Plan\n\nbody', 'Planning notes')).toBe('# Plan\n\nbody');
+ });
+
+ it('keeps deeper headings and content without a title', () => {
+ expect(stripTitleHeading('## Report\n\nbody', 'Report')).toBe('## Report\n\nbody');
+ expect(stripTitleHeading('# Report\n\nbody', undefined)).toBe('# Report\n\nbody');
});
});
diff --git a/apps/server/src/services/document/editorData.ts b/apps/server/src/services/document/editorData.ts
index 631cbff6b35..12eb50ba2f8 100644
--- a/apps/server/src/services/document/editorData.ts
+++ b/apps/server/src/services/document/editorData.ts
@@ -1,36 +1,90 @@
import { CUSTOM_FOLDER_FILE_TYPE, HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+import { extractMarkdownH1Title } from '@/database/models/agentDocuments';
import { isValidEditorData } from '@/libs/editor/isValidEditorData';
import { createMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';
-interface ResolveDocumentEditorDataParams {
+interface ResolveDocumentWriteParams {
content?: string;
editorData?: Record<string, any>;
fileType?: string;
+ /** The document title after this write; names the heading that repeats it. */
+ title?: string;
}
+interface ResolvedDocumentWrite {
+ content?: string;
+ editorData?: Record<string, any>;
+}
+
+const normalizeHeadingText = (value: string) =>
+ value
+ .replace(/\s+#+\s*$/, '')
+ .replaceAll(/\s+/g, ' ')
+ .trim()
+ .toLowerCase();
+
/**
- * Resolve the editorData to persist alongside a Markdown `content` write.
+ * Whether a leading heading only restates the title: the same text, or one is
+ * the other plus a suffix that starts at a word boundary, e.g. the title
+ * `Weekly Report (2026-10-20)` and the heading `Weekly Report`.
+ */
+const isTitleHeading = (heading: string, title: string) => {
+ const normalizedHeading = normalizeHeadingText(heading);
+ const normalizedTitle = normalizeHeadingText(title);
+ if (!normalizedHeading || !normalizedTitle) return false;
+ if (normalizedHeading === normalizedTitle) return true;
+
+ const [shorter, longer] =
+ normalizedHeading.length < normalizedTitle.length
+ ? [normalizedHeading, normalizedTitle]
+ : [normalizedTitle, normalizedHeading];
+ return longer.startsWith(shorter) && !/^[\p{L}\p{N}]/u.test(longer.slice(shorter.length));
+};
+
+/**
+ * Drop a leading `# Heading` that repeats the document title. The title already
+ * renders as the page header, so that heading reads as a second page title.
+ *
+ * Unlike agent documents, which always drop the first H1, a heading that names
+ * something else is kept: these writes also carry user-authored Markdown (verify
+ * instructions, pages saved from a message) whose opening heading is content.
+ */
+export const stripTitleHeading = (content: string, title?: string): string => {
+ if (!title) return content;
+
+ const { content: body, title: heading } = extractMarkdownH1Title(content);
+ return heading && isTitleHeading(heading, title) ? body : content;
+};
+
+/**
+ * Resolve the content and editorData to persist for a document write.
+ *
+ * Clients that cannot build Lexical state (the CLI, agent tools) send only
+ * Markdown content, and older CLI builds sent `{ type: 'doc', content }`.
+ * Persisting either leaves every reader to re-parse Markdown, which mints new
+ * node ids on each read, so the ids an agent reads are gone by the time it
+ * edits nodes by id. Build real Lexical state from the content instead; valid
+ * editorData is kept as-is, and so is the content it was saved with.
*
- * Clients that cannot build Lexical state (the CLI) send only content, and older
- * CLI builds sent `{ type: 'doc', content }`. Persisting either leaves every
- * reader to re-parse Markdown, which mints new node ids on each read, so the ids
- * an agent reads are gone by the time it edits nodes by id. Build real Lexical
- * state from the content instead; valid editorData is kept as-is.
+ * Content that is turned into editorData here comes from Markdown, so its
+ * leading title heading is dropped first (see {@link stripTitleHeading}).
*
* An HTML document's content is not Markdown and is never edited as rich text,
* so it carries no editorData at all.
*/
-export const resolveDocumentEditorData = async ({
+export const resolveDocumentWrite = async ({
content,
editorData,
fileType,
-}: ResolveDocumentEditorDataParams): Promise<Record<string, any> | undefined> => {
- if (fileType === HTML_DOCUMENT_FILE_TYPE) return undefined;
- if (isValidEditorData(editorData)) return editorData;
- if (content === undefined || fileType === CUSTOM_FOLDER_FILE_TYPE) return editorData;
+ title,
+}: ResolveDocumentWriteParams): Promise<ResolvedDocumentWrite> => {
+ if (fileType === HTML_DOCUMENT_FILE_TYPE) return { content, editorData: undefined };
+ if (isValidEditorData(editorData)) return { content, editorData };
+ if (content === undefined || fileType === CUSTOM_FOLDER_FILE_TYPE) return { content, editorData };
- const snapshot = await createMarkdownEditorSnapshot(content);
- return snapshot.editorData;
+ const body = stripTitleHeading(content, title);
+ const snapshot = await createMarkdownEditorSnapshot(body);
+ return { content: body, editorData: snapshot.editorData };
};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
index d7749118363..2ce0823c31d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
@@ -5,6 +5,7 @@ import type { ToolExecutionContext } from '../../types';
import { knowledgeBaseRuntime } from '../knowledgeBase';
const mocks = vi.hoisted(() => ({
+ createDocument: vi.fn(),
getAgentAssignedKnowledge: vi.fn(),
getEnabledKnowledgeBaseIds: vi.fn(),
getEnabledKnowledgeBaseIdsForTask: vi.fn(),
@@ -29,7 +30,11 @@ vi.mock('@/database/models/project', () => ({
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
vi.mock('@/database/repositories/knowledge', () => ({ KnowledgeRepo: vi.fn() }));
-vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn().mockImplementation(function () {
+ return { createDocument: mocks.createDocument };
+ }),
+}));
vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));
vi.mock('@/server/services/knowledgeBase', () => ({
@@ -115,3 +120,31 @@ describe('knowledgeBaseRuntime searchKnowledgeBase scope', () => {
);
});
});
+
+describe('knowledgeBaseRuntime createDocument', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createDocument.mockResolvedValue({ id: 'docs_1' });
+ });
+
+ /**
+ * Regression: the document title renders as the page header, so a body that
+ * opened with the same `# Title` showed it twice, and the page was stored
+ * with an empty `{}` editor state instead of one built from the Markdown.
+ */
+ it('drops the body heading that repeats the title and stores real editor state', async () => {
+ await createRuntime().createDocument({
+ content: '# Launch checklist\n\n- ship it\n',
+ knowledgeBaseId: 'kb_product',
+ title: 'Launch checklist',
+ });
+
+ expect(mocks.createDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: '- ship it\n',
+ editorData: expect.objectContaining({ root: expect.anything() }),
+ title: 'Launch checklist',
+ }),
+ );
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
index 8c4bc78713a..a72db22742c 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
@@ -7,6 +7,7 @@ import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { ProjectModel } from '@/database/models/project';
import { KnowledgeRepo } from '@/database/repositories/knowledge';
import { DocumentService } from '@/server/services/document';
+import { resolveDocumentWrite } from '@/server/services/document/editorData';
import { FileService } from '@/server/services/file';
import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';
@@ -155,9 +156,12 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
},
{
createDocument: async ({ content, fileType, knowledgeBaseId, parentId, title }) => {
+ // Same Markdown write as `lh doc create`: real editor state, and no
+ // body heading that repeats the title.
+ const write = await resolveDocumentWrite({ content, fileType, title });
const doc = await documentService.createDocument({
- content,
- editorData: {},
+ content: write.content,
+ editorData: write.editorData,
fileType,
knowledgeBaseId,
parentId,