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(document): render HTML page documents in a sandboxed frame (#21217)

Arvin Xu09731c55e727
diff --git a/apps/server/src/routers/lambda/document.test.ts b/apps/server/src/routers/lambda/document.test.ts
index 904ca4c9e40..43812e637c5 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(),
+ findDocumentById: vi.fn(),
findOwnOperationById: vi.fn(),
getDocumentById: vi.fn(),
getFileAccessUrl: vi.fn(),
@@ -29,7 +30,9 @@ vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
vi.mock('@/database/models/message', () => ({ MessageModel: vi.fn() }));
vi.mock('@/database/models/document', () => ({
- DocumentModel: vi.fn(),
+ DocumentModel: vi.fn().mockImplementation(function () {
+ return { findById: mocks.findDocumentById };
+ }),
DOCUMENT_TRANSFER_FOREIGN_ROWS: 'foreign',
}));
vi.mock('@/server/services/document', () => ({
@@ -196,3 +199,45 @@ describe('document work provenance', () => {
).resolves.toMatchObject({ id: 'doc-1' });
});
});
+
+describe('HTML document writes', () => {
+ const html = '<!doctype html><html><body><h1>Report</h1></body></html>';
+
+ beforeEach(() => {
+ for (const mock of Object.values(mocks)) mock.mockReset();
+ mocks.createDocument.mockResolvedValue({ id: 'doc-1', visibility: 'private' });
+ mocks.updateDocument.mockResolvedValue({ id: 'doc-1' });
+ });
+
+ it('creates an HTML page without parsing its content as Markdown', async () => {
+ await (
+ await caller()
+ ).createDocument({ content: html, fileType: 'custom/html', title: 'Report' });
+
+ expect(mocks.createDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ content: html, editorData: undefined, fileType: 'custom/html' }),
+ );
+ });
+
+ it('keeps a content-only edit of a stored HTML page out of the Markdown editor', async () => {
+ mocks.findDocumentById.mockResolvedValue({ fileType: 'custom/html', id: 'doc-1' });
+
+ await (await caller()).updateDocument({ content: html, id: 'doc-1' });
+
+ expect(mocks.updateDocument).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.objectContaining({ content: html, editorData: undefined }),
+ );
+ });
+
+ it('still builds editorData for a content-only edit of a Markdown page', async () => {
+ mocks.findDocumentById.mockResolvedValue({ fileType: 'custom/document', id: 'doc-1' });
+
+ await (await caller()).updateDocument({ content: '# Title', id: 'doc-1' });
+
+ expect(mocks.updateDocument).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.objectContaining({ editorData: expect.objectContaining({ root: expect.anything() }) }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 59dee1a3cdf..595badda457 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -556,12 +556,22 @@ 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 names no fileType;
+ // the stored fileType decides whether to build editorData from Markdown.
+ // An HTML page never gets any (the service drops editorData sent for one).
+ const needsStoredFileType =
+ params.content !== undefined && params.fileType === undefined && !editorDataString;
+ const currentDocument =
+ input.parentId !== undefined || needsStoredFileType
+ ? 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 currentDocument = await ctx.documentModel.findById(input.id);
const currentParentId = currentDocument?.parentId ?? null;
const nextParentId = input.parentId ?? null;
if (currentParentId !== nextParentId) {
@@ -570,11 +580,10 @@ export const documentRouter = router({
}
}
- const { id, editorData: editorDataString, operationId, ...params } = input;
const editorData = await resolveDocumentEditorData({
content: params.content,
editorData: editorDataString ? JSON.parse(editorDataString) : undefined,
- fileType: params.fileType,
+ fileType: params.fileType ?? currentDocument?.fileType,
});
const result = await ctx.documentService.updateDocument(id, {
...params,
diff --git a/apps/server/src/services/document/__tests__/htmlDocument.test.ts b/apps/server/src/services/document/__tests__/htmlDocument.test.ts
new file mode 100644
index 00000000000..44f025f5648
--- /dev/null
+++ b/apps/server/src/services/document/__tests__/htmlDocument.test.ts
@@ -0,0 +1,159 @@
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+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 { EditLockService } from '../../editLock';
+import { DocumentHistoryService } from '../history';
+import { DocumentService } from '../index';
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));
+vi.mock('@/database/models/document');
+vi.mock('@/database/models/file');
+vi.mock('../history');
+vi.mock('../../resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
+
+describe('DocumentService.updateDocument on an HTML document', () => {
+ const editorData = { root: { children: [{ type: 'paragraph' }], type: 'root' } };
+ const html = '<!doctype html><html><body><h1>Report</h1></body></html>';
+
+ let documentModel: { findById: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> };
+ let createHistory: ReturnType<typeof vi.fn>;
+ let service: DocumentService;
+
+ beforeEach(() => {
+ const db = {
+ transaction: vi.fn(async (callback: (tx: LobeChatDatabase) => Promise<unknown>) =>
+ callback(db),
+ ),
+ } as unknown as LobeChatDatabase;
+
+ documentModel = {
+ findById: vi.fn().mockResolvedValue({
+ editorData: null,
+ fileId: null,
+ fileType: HTML_DOCUMENT_FILE_TYPE,
+ id: 'doc-1',
+ updatedAt: new Date('2026-10-19T00:00:00.000Z'),
+ }),
+ update: vi.fn().mockResolvedValue(new Date('2026-10-19T01:00:00.000Z')),
+ };
+ createHistory = vi.fn();
+
+ vi.mocked(DocumentModel).mockImplementation(function () {
+ return documentModel as any;
+ });
+ vi.mocked(FileModel).mockImplementation(function () {
+ return {} as any;
+ });
+ vi.mocked(DocumentHistoryService).mockImplementation(function () {
+ return { createHistory } as any;
+ });
+
+ service = new DocumentService(db, 'user-1');
+ });
+
+ it('writes the HTML content but never rich-text editorData', async () => {
+ const result = await service.updateDocument('doc-1', { content: html, editorData });
+
+ const updates = documentModel.update.mock.calls[0][1];
+ expect(updates).toMatchObject({ content: html });
+ expect(updates).not.toHaveProperty('editorData');
+ expect(createHistory).not.toHaveBeenCalled();
+ expect(result.historyAppended).toBe(false);
+ });
+
+ it('drops editorData sent in the same write that turns a page into HTML', async () => {
+ documentModel.findById.mockResolvedValue({
+ editorData,
+ fileId: null,
+ fileType: 'custom/document',
+ id: 'doc-1',
+ updatedAt: new Date('2026-10-19T00:00:00.000Z'),
+ });
+
+ await service.updateDocument('doc-1', {
+ content: html,
+ editorData: { root: { children: [], type: 'root' } },
+ fileType: HTML_DOCUMENT_FILE_TYPE,
+ });
+
+ const updates = documentModel.update.mock.calls[0][1];
+ expect(updates).toMatchObject({
+ content: html,
+ editorData: null,
+ fileType: HTML_DOCUMENT_FILE_TYPE,
+ });
+ });
+
+ it('clears the rich-text editorData a page carried when only its type turns HTML', async () => {
+ documentModel.findById.mockResolvedValue({
+ editorData,
+ fileId: null,
+ fileType: 'custom/document',
+ id: 'doc-1',
+ updatedAt: new Date('2026-10-19T00:00:00.000Z'),
+ });
+
+ await service.updateDocument('doc-1', { fileType: HTML_DOCUMENT_FILE_TYPE });
+
+ // Left behind, the pre-HTML JSON would be what the editor loads (and saves)
+ // if the page is ever turned back into a rich-text page.
+ expect(documentModel.update.mock.calls[0][1]).toEqual({
+ editorData: null,
+ fileType: HTML_DOCUMENT_FILE_TYPE,
+ });
+ expect(createHistory).not.toHaveBeenCalled();
+ });
+
+ describe('on a shared workspace page another member is editing', () => {
+ const sharedPage = (fileType: string, pageEditorData: unknown) => ({
+ editorData: pageEditorData,
+ fileId: null,
+ fileType,
+ id: 'doc-1',
+ updatedAt: new Date('2026-10-19T00:00:00.000Z'),
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+
+ beforeEach(() => {
+ vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(false);
+ service = new DocumentService(
+ { transaction: async (callback: any) => callback({}) } as any,
+ 'user-1',
+ 'ws-1',
+ );
+ });
+
+ it.each([
+ [
+ 'turning their rich-text page into HTML',
+ sharedPage('custom/document', editorData),
+ HTML_DOCUMENT_FILE_TYPE,
+ ],
+ [
+ 'turning their HTML page into a rich-text page',
+ sharedPage(HTML_DOCUMENT_FILE_TYPE, null),
+ 'custom/document',
+ ],
+ ])('refuses %s, which replaces the body they are editing', async (_label, page, fileType) => {
+ documentModel.findById.mockResolvedValue(page);
+
+ await expect(service.updateDocument('doc-1', { fileType })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(documentModel.update).not.toHaveBeenCalled();
+ });
+
+ it('still lets a metadata-only edit of their HTML page through', async () => {
+ documentModel.findById.mockResolvedValue(sharedPage(HTML_DOCUMENT_FILE_TYPE, null));
+
+ await service.updateDocument('doc-1', { title: 'Renamed' });
+
+ expect(documentModel.update).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/document/editorData.test.ts b/apps/server/src/services/document/editorData.test.ts
index a594de2a399..24e9a8d3e64 100644
--- a/apps/server/src/services/document/editorData.test.ts
+++ b/apps/server/src/services/document/editorData.test.ts
@@ -54,4 +54,16 @@ describe('resolveDocumentEditorData', () => {
).resolves.toBeUndefined();
await expect(resolveDocumentEditorData({})).resolves.toBeUndefined();
});
+
+ 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(
+ resolveDocumentEditorData({ content, fileType: 'custom/html' }),
+ ).resolves.toBeUndefined();
+ await expect(
+ resolveDocumentEditorData({ content, editorData, fileType: 'custom/html' }),
+ ).resolves.toBeUndefined();
+ });
});
diff --git a/apps/server/src/services/document/editorData.ts b/apps/server/src/services/document/editorData.ts
index ba2829c578e..631cbff6b35 100644
--- a/apps/server/src/services/document/editorData.ts
+++ b/apps/server/src/services/document/editorData.ts
@@ -1,4 +1,4 @@
-import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+import { CUSTOM_FOLDER_FILE_TYPE, HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { isValidEditorData } from '@/libs/editor/isValidEditorData';
@@ -18,12 +18,16 @@ interface ResolveDocumentEditorDataParams {
* 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.
+ *
+ * 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 ({
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;
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index 4a0f807938c..bdd9c3b32f4 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -1,6 +1,10 @@
import { randomUUID } from 'node:crypto';
-import { CUSTOM_DOCUMENT_FILE_TYPE, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ HTML_DOCUMENT_FILE_TYPE,
+} from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import { type DocumentItem } from '@lobechat/database/schemas';
import { documents, files } from '@lobechat/database/schemas';
@@ -745,6 +749,14 @@ export class DocumentService {
}
}
+ // An HTML document's body is its content alone: rich-text editorData sent
+ // with it (or with the write that makes it HTML) is never persisted, and
+ // any the page carried before is cleared. Left behind, that pre-HTML JSON
+ // is what the editor would load and save if the page turned rich-text again.
+ const isHtmlDocument =
+ (params.fileType ?? currentDocument.fileType) === HTML_DOCUMENT_FILE_TYPE;
+ const editorDataParam = isHtmlDocument ? undefined : params.editorData;
+
// Accepted-view projections used only for historyAppended comparison and
// for the "before" snapshot written into history. The persisted editorData
// keeps any pending diff nodes — they're only normalized when the user
@@ -753,9 +765,7 @@ export class DocumentService {
(currentDocument.editorData ?? {}) as Record<string, any>,
);
const nextEditorDataAccepted =
- params.editorData === undefined
- ? undefined
- : normalizeEditorDataDiffNodes(params.editorData);
+ editorDataParam === undefined ? undefined : normalizeEditorDataDiffNodes(editorDataParam);
const historyAppended =
nextEditorDataAccepted !== undefined &&
!isEqual(nextEditorDataAccepted, currentEditorDataAccepted);
@@ -771,8 +781,13 @@ export class DocumentService {
// (title/emoji) pass through, since the autosave always re-sends the
// unchanged body. The lease auto-expires in Redis; when Redis is down this
// returns null (fail-open) so the lock can't block saving.
+ // Switching a page into or out of HTML replaces the body other members see
+ // (and clears its editorData), so it is a body change even with no content.
+ const htmlTypeChanged =
+ isHtmlDocument !== (currentDocument.fileType === HTML_DOCUMENT_FILE_TYPE);
const contentChanged =
historyAppended ||
+ htmlTypeChanged ||
(params.content !== undefined && params.content !== currentDocument.content);
if (contentChanged && this.isCollaborativeDocument(currentDocument)) {
const canWrite = await this.editLockService.canWrite('document', id, params.lockOwnerId);
@@ -793,8 +808,10 @@ export class DocumentService {
updates.totalLineCount = params.content.split('\n').length;
}
- if (params.editorData !== undefined) {
- updates.editorData = params.editorData;
+ if (editorDataParam !== undefined) {
+ updates.editorData = editorDataParam;
+ } else if (isHtmlDocument && currentDocument.editorData != null) {
+ updates.editorData = null;
}
if (params.fileType !== undefined) {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgent.htmlGuard.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgent.htmlGuard.test.ts
new file mode 100644
index 00000000000..35e4c10142b
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgent.htmlGuard.test.ts
@@ -0,0 +1,62 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { pageAgentRuntime } from '../pageAgent';
+
+const mocks = vi.hoisted(() => ({
+ findById: vi.fn(),
+ runWithDocumentLock: vi.fn(),
+ updateDocument: vi.fn(),
+}));
+
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: vi.fn().mockImplementation(function () {
+ return { findById: mocks.findById };
+ }),
+}));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn().mockImplementation(function () {
+ return {
+ runWithDocumentLock: mocks.runWithDocumentLock,
+ updateDocument: mocks.updateDocument,
+ };
+ }),
+}));
+
+const runtime = () =>
+ pageAgentRuntime.factory({ serverDB: {} as any, userId: 'user-1' } as any) as Record<
+ string,
+ (args: unknown, ctx: unknown) => Promise<any>
+ >;
+
+describe('page agent on an HTML page', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.runWithDocumentLock.mockImplementation((_id: string, fn: () => unknown) => fn());
+ mocks.findById.mockResolvedValue({
+ content: '<!doctype html><html><body><p>12</p></body></html>',
+ editorData: null,
+ fileType: 'custom/html',
+ id: 'doc-1',
+ title: 'Goal report',
+ });
+ });
+
+ it('refuses node edits instead of writing the page back as Markdown', async () => {
+ const result = await runtime().modifyNodes(
+ { operations: [{ action: 'remove', id: 'n1' }] },
+ { documentId: 'doc-1' },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toMatch(/HTML page/);
+ expect(mocks.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('refuses reads, which would hand the model the HTML parsed as Markdown', async () => {
+ const result = await runtime().getPageContent({ format: 'both' }, { documentId: 'doc-1' });
+
+ expect(result.success).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts
index 986a5a970fe..57b3ddd4000 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts
@@ -4,6 +4,7 @@ import {
type PageAgentInvocationContext,
type PageAgentRuntimeService,
} from '@lobechat/builtin-tool-page-agent/executionRuntime';
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { EditorRuntime, formatModifyNodesResult } from '@lobechat/editor-runtime';
import { type HeadlessEditor } from '@lobehub/editor/headless';
import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';
@@ -23,9 +24,14 @@ type EditorRuntimeEditorParam = Parameters<EditorRuntime['setEditor']>[0];
interface DocumentSnapshot {
content: string;
editorData: Record<string, unknown> | null;
+ fileType: string;
title: string;
}
+const HTML_PAGE_UNSUPPORTED =
+ 'This page is an HTML page: its body is one self-contained HTML document, not a node tree, ' +
+ 'so the page tools cannot read or edit it.';
+
interface InvocationEnv {
getTitle: () => string;
headless: HeadlessEditor;
@@ -123,6 +129,7 @@ const loadSnapshot = async (
return {
content: doc.content ?? '',
editorData: (doc.editorData ?? null) as Record<string, unknown> | null,
+ fileType: doc.fileType,
title: doc.title ?? 'Untitled',
};
};
@@ -207,6 +214,9 @@ const withEditor = async (
// (persist: false) never write, so they skip the lock.
const run = async (lockOwnerId?: string): Promise<HandlerOutput> => {
const snapshot = await loadSnapshot(documentModel, documentId);
+ // Hydrating an HTML page as Markdown and writing the export back would
+ // replace the page with Markdown; node APIs never run on one.
+ if (snapshot.fileType === HTML_DOCUMENT_FILE_TYPE) throw new Error(HTML_PAGE_UNSUPPORTED);
const env = buildEnv(snapshot, documentId);
try {
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index d4475524609..a272cd42b92 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -297,6 +297,7 @@
"pageEditor.lock.editingBySomeone": "Someone else is editing this page. Your changes can’t be saved right now.",
"pageEditor.menu.copyLink": "Copy Link",
"pageEditor.menu.export": "Export",
+ "pageEditor.menu.export.html": "HTML",
"pageEditor.menu.export.markdown": "Markdown",
"pageEditor.menu.exportDocument": "Export Page",
"pageEditor.menu.importDocument": "Import Page",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 2da6dde7cd0..5c97a393ebf 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -297,6 +297,7 @@
"pageEditor.lock.editingBySomeone": "其他人正在编辑此页面,你的更改暂时无法保存。",
"pageEditor.menu.copyLink": "复制链接",
"pageEditor.menu.export": "导出",
+ "pageEditor.menu.export.html": "HTML 格式",
"pageEditor.menu.export.markdown": "Markdown 格式",
"pageEditor.menu.exportDocument": "导出文稿",
"pageEditor.menu.importDocument": "导入文稿",
diff --git a/packages/const/src/agentDocument.ts b/packages/const/src/agentDocument.ts
index 56c0fcf63f1..fd26775afcd 100644
--- a/packages/const/src/agentDocument.ts
+++ b/packages/const/src/agentDocument.ts
@@ -13,6 +13,11 @@ export const AGENT_PLAN_FILE_TYPE = 'agent/plan';
export const VERIFY_INSTRUCTION_FILE_TYPE = 'verify/instruction';
export const CUSTOM_DOCUMENT_FILE_TYPE = 'custom/document';
export const CUSTOM_FOLDER_FILE_TYPE = 'custom/folder';
+/**
+ * A page whose `content` is a self-contained HTML document, rendered in a
+ * sandboxed frame instead of the rich-text editor. It never carries editorData.
+ */
+export const HTML_DOCUMENT_FILE_TYPE = 'custom/html';
export const MARKDOWN_MIME_TYPES = ['text/markdown', 'text/x-markdown'];
@@ -38,7 +43,11 @@ export const AGENT_ARTIFACT_SOURCE_TYPES = ['agent', 'agent-signal'] as const;
*/
export const PAGE_DOCUMENT_SOURCE_TYPES: string[] = ['file', 'api'];
-export const PAGE_DOCUMENT_FILE_TYPES: string[] = [CUSTOM_DOCUMENT_FILE_TYPE, 'application/pdf'];
+export const PAGE_DOCUMENT_FILE_TYPES: string[] = [
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ HTML_DOCUMENT_FILE_TYPE,
+ 'application/pdf',
+];
export const hasFilenameExtension = (filename: string): boolean =>
/(?:^|[^.])\.[^.]+$/.test(filename);
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 1df15b02edd..77928f2d3be 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -331,6 +331,7 @@ export default {
'Someone else is editing this page. Your changes can’t be saved right now.',
'pageEditor.menu.copyLink': 'Copy Link',
'pageEditor.menu.export': 'Export',
+ 'pageEditor.menu.export.html': 'HTML',
'pageEditor.menu.export.markdown': 'Markdown',
'pageEditor.menu.exportDocument': 'Export Page',
'pageEditor.menu.importDocument': 'Import Page',
diff --git a/src/components/HtmlPreview/HtmlDocumentFrame.tsx b/src/components/HtmlPreview/HtmlDocumentFrame.tsx
new file mode 100644
index 00000000000..6e9761f7b11
--- /dev/null
+++ b/src/components/HtmlPreview/HtmlDocumentFrame.tsx
@@ -0,0 +1,68 @@
+import { createStaticStyles, HtmlPreviewIframe } from '@lobehub/ui';
+import { useEffect, useRef, useState } from 'react';
+
+import { nextWidenBaseline } from './widenRemount';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ width: 100%;
+ `,
+ frame: css`
+ display: block;
+ width: 100%;
+ border: 0;
+ `,
+}));
+
+interface HtmlDocumentFrameProps {
+ content: string;
+ title?: string;
+}
+
+/**
+ * The body of an HTML page document. The page is model- or user-authored, so
+ * it runs in the preview's default sandbox (scripts, no same origin) and grows
+ * to its own height inside the surrounding scroll container. Its auto-height
+ * cannot shrink, so the frame is remounted when the container widens (e.g. a
+ * page opened from the narrow chat portal).
+ */
+const HtmlDocumentFrame = ({ content, title }: HtmlDocumentFrameProps) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [frameKey, setFrameKey] = useState(0);
+
+ useEffect(() => {
+ const node = containerRef.current;
+ if (!node || typeof ResizeObserver === 'undefined') return;
+
+ let baseline = node.clientWidth;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const observer = new ResizeObserver(() => {
+ const next = nextWidenBaseline(baseline, node.clientWidth);
+ baseline = next.baseline;
+ if (!next.remount) return;
+ // Wait for a layout transition to settle before measuring again.
+ clearTimeout(timer);
+ timer = setTimeout(() => setFrameKey((key) => key + 1), 150);
+ });
+ observer.observe(node);
+
+ return () => {
+ observer.disconnect();
+ clearTimeout(timer);
+ };
+ }, []);
+
+ return (
+ <div className={styles.container} ref={containerRef}>
+ <HtmlPreviewIframe
+ className={styles.frame}
+ content={content}
+ defaultHeight={480}
+ key={frameKey}
+ title={title || undefined}
+ />
+ </div>
+ );
+};
+
+export default HtmlDocumentFrame;
diff --git a/src/components/HtmlPreview/index.ts b/src/components/HtmlPreview/index.ts
index d0dccf57471..4826d714c90 100644
--- a/src/components/HtmlPreview/index.ts
+++ b/src/components/HtmlPreview/index.ts
@@ -1,4 +1,5 @@
export { applyHtmlPreviewBaseUrl } from './applyBaseUrl';
export { isHtmlFile } from './fileType';
+export { default as HtmlDocumentFrame } from './HtmlDocumentFrame';
export { default as InlineHtmlPreview } from './InlinePreview';
export { default as HtmlPreviewDrawer } from './PreviewDrawer';
diff --git a/src/components/HtmlPreview/widenRemount.test.ts b/src/components/HtmlPreview/widenRemount.test.ts
new file mode 100644
index 00000000000..1bd18d0473b
--- /dev/null
+++ b/src/components/HtmlPreview/widenRemount.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { nextWidenBaseline } from './widenRemount';
+
+describe('nextWidenBaseline', () => {
+ it('measures the frame again once the container is clearly wider', () => {
+ // Opened from the narrow chat portal, then shown as a full page.
+ expect(nextWidenBaseline(368, 650)).toEqual({ baseline: 650, remount: true });
+ });
+
+ it('lets a narrowing container grow the frame on its own', () => {
+ expect(nextWidenBaseline(650, 368)).toEqual({ baseline: 368, remount: false });
+ });
+
+ it('measures again after narrowing then widening back', () => {
+ const narrowed = nextWidenBaseline(650, 400);
+ expect(nextWidenBaseline(narrowed.baseline, 650)).toEqual({ baseline: 650, remount: true });
+ });
+
+ it('ignores sub-threshold jitter', () => {
+ expect(nextWidenBaseline(650, 660)).toEqual({ baseline: 650, remount: false });
+ });
+});
diff --git a/src/components/HtmlPreview/widenRemount.ts b/src/components/HtmlPreview/widenRemount.ts
new file mode 100644
index 00000000000..eaae9b949ef
--- /dev/null
+++ b/src/components/HtmlPreview/widenRemount.ts
@@ -0,0 +1,19 @@
+/** How much wider the container must get before the frame is measured again. */
+export const WIDEN_REMOUNT_THRESHOLD = 24;
+
+/**
+ * The preview's auto-height reports `documentElement.scrollHeight`, which never
+ * drops below the frame's current height: a frame first measured in a narrow
+ * container keeps that tall height after the container widens. Track the
+ * narrowest width since the frame mounted and ask for a fresh frame once the
+ * container is clearly wider than that. Narrowing needs nothing — the frame
+ * grows on its own.
+ */
+export const nextWidenBaseline = (
+ baseline: number,
+ width: number,
+): { baseline: number; remount: boolean } => {
+ if (width <= baseline) return { baseline: width, remount: false };
+ if (width - baseline >= WIDEN_REMOUNT_THRESHOLD) return { baseline: width, remount: true };
+ return { baseline, remount: false };
+};
diff --git a/src/features/AgentDocumentPage/Header/useMenu.tsx b/src/features/AgentDocumentPage/Header/useMenu.tsx
index da1f29ff8c1..f792efff916 100644
--- a/src/features/AgentDocumentPage/Header/useMenu.tsx
+++ b/src/features/AgentDocumentPage/Header/useMenu.tsx
@@ -9,10 +9,13 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { formatPageEditorInfoTime } from '@/features/PageEditor/formatPageEditorInfoTime';
+import { useIsHtmlPage } from '@/features/PageEditor/HtmlPageBody';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { agentDocumentService } from '@/services/agentDocument';
+import { useDocumentStore } from '@/store/document';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { exportHtmlDocument } from '@/utils/exportTextFile';
interface UseMenuParams {
agentDocumentId?: string;
@@ -46,6 +49,12 @@ export const useMenu = ({
const activeWorkspaceSlug = useActiveWorkspaceSlug();
const dateLocale = i18n.resolvedLanguage || i18n.language;
+ // An HTML page has no Markdown to export: it downloads as the page itself.
+ const isHtmlPage = useIsHtmlPage(documentId);
+ const htmlContent = useDocumentStore((s) =>
+ isHtmlPage ? s.documentDetailMap[documentId]?.document?.content : undefined,
+ );
+
const [wideScreen, toggleWideScreen] = useGlobalStore((s) => [
systemStatusSelectors.wideScreen(s),
s.toggleWideScreen,
@@ -86,6 +95,15 @@ export const useMenu = ({
}
};
+ const handleExportHtml = async () => {
+ try {
+ const result = await exportHtmlDocument(htmlContent ?? '', title);
+ if (result === 'downloaded') toast.success(t('pageEditor.exportSuccess'));
+ } catch {
+ toast.error(t('pageEditor.exportError'));
+ }
+ };
+
const handleDelete = () => {
if (!agentDocumentId) return;
confirmModal({
@@ -137,13 +155,21 @@ export const useMenu = ({
onClick: handleCopyLink,
},
{
- children: [
- {
- key: 'export-markdown',
- label: t('pageEditor.menu.export.markdown'),
- onClick: handleExportMarkdown,
- },
- ],
+ children: isHtmlPage
+ ? [
+ {
+ key: 'export-html',
+ label: t('pageEditor.menu.export.html'),
+ onClick: handleExportHtml,
+ },
+ ]
+ : [
+ {
+ key: 'export-markdown',
+ label: t('pageEditor.menu.export.markdown'),
+ onClick: handleExportMarkdown,
+ },
+ ],
icon: <Icon icon={Download} />,
key: 'export',
label: t('pageEditor.menu.export'),
@@ -186,6 +212,8 @@ export const useMenu = ({
documentId,
editor,
fileBacked,
+ htmlContent,
+ isHtmlPage,
lg,
dateLocale,
onDeleted,
diff --git a/src/features/PageEditor/Header/useMenu.test.tsx b/src/features/PageEditor/Header/useMenu.test.tsx
index 3654f624085..4b3a0123540 100644
--- a/src/features/PageEditor/Header/useMenu.test.tsx
+++ b/src/features/PageEditor/Header/useMenu.test.tsx
@@ -16,6 +16,7 @@ const resourcePermissionMock = vi.hoisted(() => ({
workspaceId: undefined as string | undefined,
}));
const wsNavigateMock = vi.hoisted(() => vi.fn());
+const documentStoreMock = vi.hoisted(() => ({ state: {} as Record<string, unknown> }));
const menuActionMocks = vi.hoisted(() => ({
handleCopyLink: vi.fn(),
handleDelete: vi.fn(),
@@ -35,6 +36,7 @@ vi.mock('react-i18next', () => ({
vi.mock('@lobechat/const', () => ({
CUSTOM_DOCUMENT_FILE_TYPE: 'custom/document',
+ HTML_DOCUMENT_FILE_TYPE: 'custom/html',
isDesktop: false,
}));
@@ -97,7 +99,8 @@ vi.mock('@/hooks/usePermission', () => ({
}));
vi.mock('@/store/document', () => ({
- useDocumentStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
+ useDocumentStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector(documentStoreMock.state),
}));
vi.mock('@/store/page', () => ({
@@ -174,9 +177,30 @@ describe('PageEditor header menu', () => {
permissionMock.edit_own_content = true;
resourcePermissionMock.canManage = false;
resourcePermissionMock.workspaceId = undefined;
+ documentStoreMock.state = { documentDetailMap: {} };
vi.clearAllMocks();
});
+ it('exports an HTML page as HTML and offers no editor history', () => {
+ const exportChildren = (items: ReturnType<typeof useMenu>['menuItems']) =>
+ (getMenuItem(items, 'export') as { children: { key: string }[] }).children.map(
+ (child) => child.key,
+ );
+
+ const { result: page } = renderHook(() => useMenu());
+ expect(exportChildren(page.current.menuItems)).toEqual(['export-markdown']);
+ expect(getMenuItem(page.current.menuItems, 'version-history')).toBeDefined();
+
+ documentStoreMock.state = {
+ documentDetailMap: { 'doc-1': { document: { fileType: 'custom/html', id: 'doc-1' } } },
+ };
+ const { result: htmlPage } = renderHook(() => useMenu());
+
+ expect(exportChildren(htmlPage.current.menuItems)).toEqual(['export-html']);
+ expect(getMenuItem(htmlPage.current.menuItems, 'version-history')).toBeUndefined();
+ expect(getMenuItem(htmlPage.current.menuItems, 'duplicate')).toBeDefined();
+ });
+
it('places the member-permission page entry in the overflow menu for managers', () => {
resourcePermissionMock.workspaceId = 'ws-1';
resourcePermissionMock.canManage = true;
diff --git a/src/features/PageEditor/Header/useMenu.tsx b/src/features/PageEditor/Header/useMenu.tsx
index b9c7c09b57b..9c6276836f7 100644
--- a/src/features/PageEditor/Header/useMenu.tsx
+++ b/src/features/PageEditor/Header/useMenu.tsx
@@ -29,8 +29,10 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { pageActions, pageSelectors, usePageStore } from '@/store/page';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { exportHtmlDocument } from '@/utils/exportTextFile';
import { formatPageEditorInfoTime } from '../formatPageEditorInfoTime';
+import { useIsHtmlPage } from '../HtmlPageBody';
import { usePageEditorStore, useStoreApi } from '../store';
/**
@@ -51,6 +53,8 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
const dateLocale = i18n.resolvedLanguage || i18n.language;
const documentId = usePageEditorStore((s) => s.documentId);
+ // An HTML page has no rich-text body: it exports as HTML and has no editor history.
+ const isHtmlPage = useIsHtmlPage(documentId);
const { allowed: canCreatePage } = usePermission('create_content');
const { allowed: canEditPage } = usePermission('edit_own_content');
@@ -206,6 +210,19 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
}
}, [storeApi, t]);
+ const htmlContent = useDocumentStore((s) =>
+ isHtmlPage && documentId ? s.documentDetailMap[documentId]?.document?.content : undefined,
+ );
+ const handleExportHtml = useCallback(async () => {
+ try {
+ const result = await exportHtmlDocument(htmlContent ?? '', storeApi.getState().title);
+ if (result === 'downloaded') toast.success(t('pageEditor.exportSuccess'));
+ } catch (error) {
+ console.error('Failed to export HTML:', error);
+ toast.error(t('pageEditor.exportError'));
+ }
+ }, [htmlContent, storeApi, t]);
+
const menuItems = useMemo<DropdownItem[]>(() => {
const items: DropdownItem[] = [
...(showViewModeSwitch
@@ -259,19 +276,23 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
state.handleCopyLink(t as any);
},
},
- {
- icon: <Icon icon={Clock3Icon} />,
- key: 'version-history',
- label: t('pageEditor.history.title'),
- onClick: () => {
- setRightPanelMode('history');
- if (onOpenHistory) {
- onOpenHistory();
- } else {
- togglePageAgentPanel(true);
- }
- },
- },
+ ...(isHtmlPage
+ ? []
+ : [
+ {
+ icon: <Icon icon={Clock3Icon} />,
+ key: 'version-history',
+ label: t('pageEditor.history.title'),
+ onClick: () => {
+ setRightPanelMode('history');
+ if (onOpenHistory) {
+ onOpenHistory();
+ } else {
+ togglePageAgentPanel(true);
+ }
+ },
+ } as DropdownItem,
+ ]),
{
danger: true,
disabled: !canEditPage,
@@ -299,13 +320,22 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
]
: []),
{
- children: [
- {
- key: 'export-markdown',
- label: t('pageEditor.menu.export.markdown'),
- onClick: handleExportMarkdown,
- },
- ],
+ // An HTML page has no Markdown to export: it downloads as the page itself.
+ children: isHtmlPage
+ ? [
+ {
+ key: 'export-html',
+ label: t('pageEditor.menu.export.html'),
+ onClick: handleExportHtml,
+ },
+ ]
+ : [
+ {
+ key: 'export-markdown',
+ label: t('pageEditor.menu.export.markdown'),
+ onClick: handleExportMarkdown,
+ },
+ ],
icon: <Icon icon={Download} />,
key: 'export',
label: t('pageEditor.menu.export'),
@@ -339,6 +369,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
}
return items;
}, [
+ isHtmlPage,
lastUpdatedTime,
authorName,
canCreatePage,
@@ -356,6 +387,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {
handleDuplicate,
handleMakePrivate,
handlePublish,
+ handleExportHtml,
handleExportMarkdown,
memberPermissionMenuItem,
transferMenuItems,
diff --git a/src/features/PageEditor/HtmlPageBody.tsx b/src/features/PageEditor/HtmlPageBody.tsx
new file mode 100644
index 00000000000..53539a83188
--- /dev/null
+++ b/src/features/PageEditor/HtmlPageBody.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+
+import { HtmlDocumentFrame } from '@/components/HtmlPreview';
+import { useDocumentStore } from '@/store/document';
+
+import { usePageEditorStore } from './store';
+
+/** Whether the loaded page is an HTML page rather than a rich-text one. */
+export const useIsHtmlPage = (documentId: string | undefined) =>
+ useDocumentStore(
+ (s) =>
+ !!documentId &&
+ s.documentDetailMap[documentId]?.document?.fileType === HTML_DOCUMENT_FILE_TYPE,
+ );
+
+/**
+ * Body of an HTML page: the stored HTML in a sandboxed frame instead of the
+ * rich-text editor. It still syncs the document into the document store, so
+ * title / emoji saves and remote updates keep working; the store never saves
+ * an HTML page's body.
+ */
+const HtmlPageBody = () => {
+ const documentId = usePageEditorStore((s) => s.documentId);
+ const editor = usePageEditorStore((s) => s.editor);
+ const useFetchDocument = useDocumentStore((s) => s.useFetchDocument);
+ const { data } = useFetchDocument(documentId, { editor, sourceType: 'page' });
+
+ if (!data) return null;
+
+ return <HtmlDocumentFrame content={data.content ?? ''} title={data.title ?? undefined} />;
+};
+
+export default HtmlPageBody;
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index 44a93acd441..565ad19a1c0 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -26,6 +26,7 @@ import DocumentLikes from './DocumentLikes';
import EditorCanvas from './EditorCanvas';
import { recallEditorScrollTop, rememberEditorScrollTop } from './editorScrollMemory';
import Header from './Header';
+import HtmlPageBody, { useIsHtmlPage } from './HtmlPageBody';
import LockedAlert from './LockedAlert';
import LockStatusBanner from './LockStatusBanner';
import { PageAgentProvider } from './PageAgentProvider';
@@ -159,6 +160,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {
const editable = usePageEditable();
const editor = usePageEditorStore((s) => s.editor);
const documentId = usePageEditorStore((s) => s.documentId);
+ const isHtmlPage = useIsHtmlPage(documentId);
const wideScreen = useGlobalStore(systemStatusSelectors.wideScreen);
const tableBleedInline = wideScreen
? `${TABLE_BASE_BLEED}px`
@@ -376,10 +378,10 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {
onScroll={handleEditorScroll}
>
<WideScreenContainer
- wrapperStyle={{ cursor: editable ? 'text' : 'default' }}
+ wrapperStyle={{ cursor: editable && !isHtmlPage ? 'text' : 'default' }}
onChange={notifyEditorLayoutChange}
onClick={() => {
- if (!editable) return;
+ if (!editable || isHtmlPage) return;
editor?.focus();
}}
@@ -399,8 +401,14 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {
{/* Prominent in-body notice when another member holds the lock; the
compact status badge lives in the Header (EditingIndicator). */}
<LockedAlert />
- <EditorCanvas askCopilotTarget={askCopilotTarget} />
- <BlockCommentMarker hostRef={editorContentRef} />
+ {isHtmlPage ? (
+ <HtmlPageBody />
+ ) : (
+ <>
+ <EditorCanvas askCopilotTarget={askCopilotTarget} />
+ <BlockCommentMarker hostRef={editorContentRef} />
+ </>
+ )}
{documentId && <DocumentLikes documentId={documentId} key={documentId} />}
<DocumentComments />
</Flexbox>
diff --git a/src/features/Pages/PageLayout/Body/List/Item/index.tsx b/src/features/Pages/PageLayout/Body/List/Item/index.tsx
index 9fed107f0ff..782fdde9724 100644
--- a/src/features/Pages/PageLayout/Body/List/Item/index.tsx
+++ b/src/features/Pages/PageLayout/Body/List/Item/index.tsx
@@ -1,5 +1,6 @@
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { Avatar, Icon } from '@lobehub/ui';
-import { FileTextIcon } from 'lucide-react';
+import { FileTextIcon, GlobeIcon } from 'lucide-react';
import { type MouseEvent } from 'react';
import { memo, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,6 +34,7 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {
const active = selectedPageId === pageId;
const title = document?.title || t('pageList.untitled');
const emoji = document?.metadata?.emoji;
+ const isHtmlPage = document?.fileType === HTML_DOCUMENT_FILE_TYPE;
const toggleEditing = useCallback(
(visible?: boolean) => {
@@ -71,13 +73,16 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {
pageActions.selectPage(pageId);
}, [pageId, activeWorkspaceSlug, addTab]);
- // Icon with emoji support
+ // Icon with emoji support; an HTML page reads as an artifact (the chat's HTML
+ // artifact icon) rather than a text page.
const icon = useMemo(() => {
if (emoji) {
return <Avatar avatar={emoji} size={28} />;
}
- return <Icon icon={FileTextIcon} size={{ size: 18, strokeWidth: 1.5 }} />;
- }, [emoji]);
+ return (
+ <Icon icon={isHtmlPage ? GlobeIcon : FileTextIcon} size={{ size: 18, strokeWidth: 1.5 }} />
+ );
+ }, [emoji, isHtmlPage]);
const dropdownMenu = useDropdownMenu({ pageId, toggleEditing });
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 37b2fb2eee5..4b4a7d9ecaa 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -207,6 +207,23 @@ describe('DocumentBody', () => {
expect(screen.queryByTestId('highlight-editor')).toBeNull();
});
+ it('renders an HTML page in a sandboxed frame without mounting either editor', () => {
+ mockDocumentMeta.current = {
+ content: '<!doctype html><html><body><h1>Goal report</h1></body></html>',
+ fileType: 'custom/html',
+ filename: 'Goal report',
+ title: 'Goal report',
+ };
+
+ const { container } = render(<DocumentBody />);
+
+ const frame = container.querySelector('iframe')!;
+ expect(frame.getAttribute('srcdoc')).toContain('<h1>Goal report</h1>');
+ expect(frame.getAttribute('sandbox')).not.toContain('allow-same-origin');
+ expect(screen.queryByTestId('editor-canvas')).toBeNull();
+ expect(screen.queryByTestId('highlight-editor')).toBeNull();
+ });
+
it('renders EditorCanvas for notebook documents that have no filename', () => {
mockDocumentMeta.current = {
content: '# notes',
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index 6e0c2baf448..de4920908b3 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
import CodeEditorPane from '@/components/CodeEditorPane';
+import { HtmlDocumentFrame } from '@/components/HtmlPreview';
import Loading from '@/components/Loading/CircleLoading';
import FileNotFound from '@/features/FileNotFound';
import { FileDocumentPreview } from '@/features/FileViewer/FileDocumentPreview';
@@ -259,6 +260,11 @@ const DocumentBody = memo(() => {
)}
{renderMode.mode === 'file' ? (
<FileDocumentPreview fileId={documentMeta?.fileId} />
+ ) : renderMode.mode === 'html' ? (
+ <HtmlDocumentFrame
+ content={documentMeta?.content ?? ''}
+ title={documentMeta?.title ?? undefined}
+ />
) : renderMode.mode === 'highlight' && documentId ? (
<HighlightEditor
content={documentMeta?.content ?? ''}
diff --git a/src/features/Portal/Document/useHtmlExport.ts b/src/features/Portal/Document/useHtmlExport.ts
new file mode 100644
index 00000000000..8bf6adcfaa3
--- /dev/null
+++ b/src/features/Portal/Document/useHtmlExport.ts
@@ -0,0 +1,34 @@
+'use client';
+
+import { toast } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { useDocumentStore } from '@/store/document';
+import { getDocumentRenderMode } from '@/utils/documentRenderMode';
+import { exportHtmlDocument } from '@/utils/exportTextFile';
+
+/**
+ * Downloads the portal document as a `.html` file. Returns `undefined` until
+ * the document has loaded, and for anything but an HTML page (those export as
+ * Markdown through `useMarkdownExport`).
+ */
+export const useHtmlExport = (documentId: string | undefined) => {
+ const { t } = useTranslation('file');
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: documentMeta } = useFetchDocumentDetail(documentId);
+
+ if (!documentMeta || getDocumentRenderMode(documentMeta).mode !== 'html') return;
+
+ return async () => {
+ try {
+ const result = await exportHtmlDocument(
+ documentMeta.content ?? '',
+ documentMeta.title || documentMeta.filename,
+ );
+ if (result === 'downloaded') toast.success(t('pageEditor.exportSuccess'));
+ } catch (error) {
+ console.error('[PortalDocument] Failed to export HTML:', error);
+ toast.error(t('pageEditor.exportError'));
+ }
+ };
+};
diff --git a/src/features/Portal/Document/useMarkdownExport.test.ts b/src/features/Portal/Document/useMarkdownExport.test.ts
index 1680f23a26a..89eab13c6ff 100644
--- a/src/features/Portal/Document/useMarkdownExport.test.ts
+++ b/src/features/Portal/Document/useMarkdownExport.test.ts
@@ -48,6 +48,13 @@ describe('useMarkdownExport', () => {
expect(result.current).toBeUndefined();
});
+ it('is unavailable for an HTML page, whose content is not Markdown', () => {
+ mocks.documentMeta = { content: '<html></html>', fileType: 'custom/html', title: 'Report' };
+ const { result } = renderHook(() => useMarkdownExport('doc_1'));
+
+ expect(result.current).toBeUndefined();
+ });
+
it('downloads the live editor buffer under the document title', async () => {
mocks.storeContent = 'live edit';
const createObjectURL = vi.fn((_blob: Blob) => 'blob:doc');
diff --git a/src/features/Portal/Document/useMarkdownExport.ts b/src/features/Portal/Document/useMarkdownExport.ts
index faf5364bce1..d1d90c3215d 100644
--- a/src/features/Portal/Document/useMarkdownExport.ts
+++ b/src/features/Portal/Document/useMarkdownExport.ts
@@ -12,6 +12,7 @@ import { getDocumentRenderMode } from '@/utils/documentRenderMode';
* document has loaded, and for a file-backed document: its data lives behind
* `fileId` with an empty markdown `content`, so the export would download an
* empty file (the standalone page menu hides export on the same condition).
+ * An HTML page's content is not Markdown, so it has no Markdown export either.
*/
export const useMarkdownExport = (documentId: string | undefined) => {
const { t } = useTranslation('file');
@@ -26,7 +27,8 @@ export const useMarkdownExport = (documentId: string | undefined) => {
const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
const { data: documentMeta } = useFetchDocumentDetail(documentId);
- if (!documentMeta || getDocumentRenderMode(documentMeta).mode === 'file') return;
+ const mode = documentMeta && getDocumentRenderMode(documentMeta).mode;
+ if (!documentMeta || mode === 'file' || mode === 'html') return;
return async () => {
const content = storeContent ?? documentMeta.content ?? '';
diff --git a/src/features/Portal/Document/useMoreMenu.test.ts b/src/features/Portal/Document/useMoreMenu.test.ts
index a0bfc0a54a1..20d22a67a6f 100644
--- a/src/features/Portal/Document/useMoreMenu.test.ts
+++ b/src/features/Portal/Document/useMoreMenu.test.ts
@@ -6,13 +6,17 @@ import { useDocumentMoreMenu } from './useMoreMenu';
const mocks = vi.hoisted(() => ({
agentDocumentId: 'adoc_1' as string | undefined,
agentId: 'agt_1',
+ clearPortalStack: vi.fn(),
closeDocument: vi.fn(),
confirmModal: vi.fn(),
documentId: 'doc_1' as string | undefined,
+ exportHtml: undefined as (() => Promise<void>) | undefined,
exportMarkdown: vi.fn() as (() => Promise<void>) | undefined,
isLoading: false,
metaLocked: false,
+ navigate: vi.fn(),
openRenameModal: vi.fn(),
+ path: '/agent/agt_1/docs/doc_1' as string | undefined,
refresh: vi.fn(),
removeDocument: vi.fn(),
saveTitle: vi.fn(),
@@ -37,7 +41,15 @@ vi.mock('@/services/agentDocument', () => ({
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (s: unknown) => unknown) =>
- selector({ closeDocument: mocks.closeDocument }),
+ selector({ clearPortalStack: mocks.clearPortalStack, closeDocument: mocks.closeDocument }),
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+
+vi.mock('./useHtmlExport', () => ({
+ useHtmlExport: () => mocks.exportHtml,
}));
vi.mock('./titleContext', () => ({
@@ -59,6 +71,7 @@ vi.mock('./usePortalDocumentHeader', () => ({
agentDocumentId: mocks.agentDocumentId,
agentId: mocks.agentId,
documentId: mocks.documentId,
+ path: mocks.path,
refresh: mocks.refresh,
url: mocks.url,
}),
@@ -69,7 +82,9 @@ describe('useDocumentMoreMenu', () => {
vi.clearAllMocks();
mocks.agentDocumentId = 'adoc_1';
mocks.documentId = 'doc_1';
+ mocks.exportHtml = undefined;
mocks.exportMarkdown = vi.fn();
+ mocks.path = '/agent/agt_1/docs/doc_1';
mocks.isLoading = false;
mocks.metaLocked = false;
mocks.url = 'https://app.lobehub.com/agent/agt_1/docs/doc_1';
@@ -164,19 +179,38 @@ describe('useDocumentMoreMenu', () => {
expect(result.current).toBeUndefined();
});
+ const extraItem = (menu: ReturnType<typeof useDocumentMoreMenu>, key: string) =>
+ menu?.extraItems?.find((item) => item && 'key' in item && item.key === key) as
+ { key: string; onClick: () => void } | undefined;
+
it('offers the markdown export as a menu action', () => {
const { result } = renderHook(() => useDocumentMoreMenu());
- const item = result.current?.extraItems?.[0] as { key: string; onClick: () => void };
+ extraItem(result.current, 'export')!.onClick();
- expect(item.key).toBe('export');
- item.onClick();
expect(mocks.exportMarkdown).toHaveBeenCalledOnce();
});
+ it('downloads an HTML page as HTML instead of Markdown', () => {
+ mocks.exportHtml = vi.fn();
+ const { result } = renderHook(() => useDocumentMoreMenu());
+ extraItem(result.current, 'export')!.onClick();
+
+ expect(mocks.exportHtml).toHaveBeenCalledOnce();
+ expect(mocks.exportMarkdown).not.toHaveBeenCalled();
+ });
+
it('leaves the export out when the document cannot be exported', () => {
mocks.exportMarkdown = undefined;
const { result } = renderHook(() => useDocumentMoreMenu());
- expect(result.current?.extraItems).toBeUndefined();
+ expect(extraItem(result.current, 'export')).toBeUndefined();
+ });
+
+ it('opens the document as a full page and closes the panel', () => {
+ const { result } = renderHook(() => useDocumentMoreMenu());
+ extraItem(result.current, 'open-as-page')!.onClick();
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_1/docs/doc_1');
+ expect(mocks.clearPortalStack).toHaveBeenCalledOnce();
});
});
diff --git a/src/features/Portal/Document/useMoreMenu.tsx b/src/features/Portal/Document/useMoreMenu.tsx
index b58b00db36d..eaa56e85af1 100644
--- a/src/features/Portal/Document/useMoreMenu.tsx
+++ b/src/features/Portal/Document/useMoreMenu.tsx
@@ -1,22 +1,30 @@
import { confirmModal, Icon, toast } from '@lobehub/ui';
-import { DownloadIcon } from 'lucide-react';
+import { DownloadIcon, Maximize2Icon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { openRenameModal } from '@/components/RenameModal';
import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { agentDocumentService } from '@/services/agentDocument';
import { useChatStore } from '@/store/chat';
import { usePortalDocumentTitleState } from './titleContext';
+import { useHtmlExport } from './useHtmlExport';
import { useMarkdownExport } from './useMarkdownExport';
import { TITLE_MAX_LENGTH, usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
const { t } = useTranslation(['chat', 'common']);
const { isLoading, metaLocked, savedTitle, saveTitle } = usePortalDocumentTitleState();
- const { agentDocumentId, agentId, documentId, refresh, url } = usePortalDocumentHeaderActions();
+ const { agentDocumentId, agentId, documentId, path, refresh, url } =
+ usePortalDocumentHeaderActions();
const closeDocument = useChatStore((s) => s.closeDocument);
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+ const navigate = useWorkspaceAwareNavigate();
const exportMarkdown = useMarkdownExport(documentId);
+ // An HTML page downloads as the page itself; it has no Markdown to export.
+ const exportHtml = useHtmlExport(documentId);
+ const exportDocument = exportHtml ?? exportMarkdown;
if (!documentId || isLoading) return;
@@ -62,16 +70,32 @@ export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
copyId: documentId,
copyLink: url,
delete: agentDocumentId ? deleteDocument : undefined,
- extraItems: exportMarkdown
- ? [
- {
- icon: <Icon icon={DownloadIcon} />,
- key: 'export',
- label: t('agentDocument.portal.export', { ns: 'chat' }),
- onClick: () => void exportMarkdown(),
- },
- ]
- : undefined,
+ extraItems: [
+ // The header's expand icon in words: open the document as a full page.
+ ...(path
+ ? [
+ {
+ icon: <Icon icon={Maximize2Icon} />,
+ key: 'open-as-page',
+ label: t('agentDocument.openAsPage', { ns: 'chat' }),
+ onClick: () => {
+ navigate(path);
+ clearPortalStack();
+ },
+ },
+ ]
+ : []),
+ ...(exportDocument
+ ? [
+ {
+ icon: <Icon icon={DownloadIcon} />,
+ key: 'export',
+ label: t('agentDocument.portal.export', { ns: 'chat' }),
+ onClick: () => void exportDocument(),
+ },
+ ]
+ : []),
+ ],
refresh,
// A dialog, like every other portal's rename — flipping the header title
// into an input from a menu reads as a stray focused text field.
diff --git a/src/services/electron/desktopExportService.tsx b/src/services/electron/desktopExportService.tsx
index 8b4137201ad..5acbc5118c4 100644
--- a/src/services/electron/desktopExportService.tsx
+++ b/src/services/electron/desktopExportService.tsx
@@ -15,13 +15,22 @@ export interface DesktopExportResult {
filePath?: string;
}
+export interface DesktopExportFileOptions extends DesktopExportOptions {
+ /** Save-dialog filter, e.g. `{ extensions: ['html'], name: 'HTML' }`. */
+ filter: { extensions: string[]; name: string };
+}
+
class DesktopExportService {
async exportMarkdown(options: DesktopExportOptions): Promise<DesktopExportResult> {
- const { content, dialogTitle, fileName, successTitle } = options;
+ return this.exportFile({ ...options, filter: { extensions: ['md'], name: 'Markdown' } });
+ }
+
+ async exportFile(options: DesktopExportFileOptions): Promise<DesktopExportResult> {
+ const { content, dialogTitle, fileName, filter, successTitle } = options;
const result = await localFileService.showSaveDialog({
defaultPath: fileName,
- filters: [{ extensions: ['md'], name: 'Markdown' }],
+ filters: [filter],
title: dialogTitle || i18next.t('pageEditor.exportDialogTitle', { ns: 'file' }),
});
diff --git a/src/store/document/slices/document/action.test.ts b/src/store/document/slices/document/action.test.ts
index 59500507739..b8295b02ad5 100644
--- a/src/store/document/slices/document/action.test.ts
+++ b/src/store/document/slices/document/action.test.ts
@@ -125,6 +125,24 @@ describe('document detail replica', () => {
expect(editor.setDocument).not.toHaveBeenCalled();
});
+ it('adopts a fetched HTML page as HTML, keeping the editor and its saves out of it', async () => {
+ const html = '<!doctype html><html><body>Report</body></html>';
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({ content: html, editorData: null, fileType: 'custom/html' }) as any,
+ );
+ const editor = createEditor();
+ renderDocument('doc-1', editor);
+
+ await waitFor(() =>
+ expect(useDocumentStore.getState().documents['doc-1']?.contentFormat).toBe('html'),
+ );
+ act(() => useDocumentStore.getState().handleContentChange());
+ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({
+ content: html,
+ isDirty: false,
+ });
+ });
+
it('adopts a newer server body over a dirty draft when the sync revalidates', async () => {
vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);
const editor = createEditor();
diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.ts
index 0bc5937af38..0baaa525515 100644
--- a/src/store/document/slices/document/action.ts
+++ b/src/store/document/slices/document/action.ts
@@ -10,12 +10,13 @@ import { createReplicaSlice, recordLens } from '@/libs/replica';
import { documentService } from '@/services/document';
import { pageActions } from '@/store/page';
import type { StoreSetter } from '@/store/types';
-import { isSkillMarkdownDocument, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';
+import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';
import { setNamespace } from '@/utils/storeDebug';
import { isTrpcErrorCode } from '@/utils/trpcError';
import type { DocumentStore } from '../../store';
import { useDocumentStore } from '../../store';
+import { resolveDocumentContentFormat } from '../editor/contentFormat';
import type { DocumentContentFormat, DocumentSourceType } from '../editor/initialState';
import type { DocumentDetail } from './projection';
import { documentDetailResource } from './projection';
@@ -404,7 +405,7 @@ export class DocumentActionImpl {
this.#get().initDocumentWithEditor({
autoSave,
content: document.content,
- contentFormat: isSkillMarkdownDocument(document) ? 'skillMarkdown' : 'markdown',
+ contentFormat: resolveDocumentContentFormat(document),
documentId,
editor,
editorData: document.editorData,
diff --git a/src/store/document/slices/editor/action.htmlDocument.test.ts b/src/store/document/slices/editor/action.htmlDocument.test.ts
new file mode 100644
index 00000000000..96addc97f60
--- /dev/null
+++ b/src/store/document/slices/editor/action.htmlDocument.test.ts
@@ -0,0 +1,149 @@
+import type { IEditor } from '@lobehub/editor';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { documentService } from '@/services/document';
+
+import { useDocumentStore } from '../../store';
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ updateDocument: vi.fn(),
+ },
+}));
+vi.mock('@/services/notebook', () => ({ notebookService: {} }));
+
+const HTML = '<!doctype html><html><body><h1>Report</h1></body></html>';
+
+/** The page editor instance exists for an HTML page, but no Lexical editor is mounted on it. */
+const makeUnmountedEditor = () => {
+ const editor = {
+ getDocument: vi.fn((format: string) =>
+ format === 'json' ? { root: { children: [], type: 'root' } } : '',
+ ),
+ setDocument: vi.fn(),
+ };
+ return { editor: editor as unknown as IEditor, spy: editor };
+};
+
+const seedHtmlPage = (editor: IEditor) => {
+ useDocumentStore.getState().initDocumentWithEditor({
+ autoSave: true,
+ content: HTML,
+ contentFormat: 'html',
+ documentId: 'page-1',
+ editor,
+ editorData: null,
+ sourceType: 'page',
+ updatedAt: new Date('2026-10-19T00:00:00Z'),
+ });
+};
+
+beforeEach(() => {
+ useDocumentStore.setState({
+ activeDocumentId: undefined,
+ documents: {},
+ documentDetailMap: {},
+ editor: undefined,
+ });
+ vi.mocked(documentService.updateDocument).mockReset().mockResolvedValue({
+ historyAppended: false,
+ id: 'page-1',
+ updatedAt: '2026-10-19T00:00:01Z',
+ });
+});
+
+describe('HTML page persistence', () => {
+ it('never loads the HTML into the rich-text editor', async () => {
+ const { editor, spy } = makeUnmountedEditor();
+ seedHtmlPage(editor);
+
+ await useDocumentStore.getState().onEditorInit(editor, 'page-1');
+
+ expect(spy.setDocument).not.toHaveBeenCalled();
+ });
+
+ it('never overwrites the HTML with the empty editor body on a manual or agent save', async () => {
+ const { editor } = makeUnmountedEditor();
+ seedHtmlPage(editor);
+
+ useDocumentStore.getState().handleContentChange();
+ await useDocumentStore.getState().performSave('page-1', undefined, { saveSource: 'manual' });
+ await useDocumentStore.getState().commitEditorMutation('page-1', { saveSource: 'llm_call' });
+
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ expect(useDocumentStore.getState().documents['page-1']).toMatchObject({
+ content: HTML,
+ isDirty: false,
+ });
+ });
+
+ it('still renames the page without sending a body', async () => {
+ const { editor } = makeUnmountedEditor();
+ seedHtmlPage(editor);
+
+ await useDocumentStore
+ .getState()
+ .performSave('page-1', { title: 'Goal report' }, { saveSource: 'autosave' });
+
+ const request = vi.mocked(documentService.updateDocument).mock.calls[0][0];
+ expect(request).toMatchObject({ id: 'page-1', title: 'Goal report' });
+ expect(request).not.toHaveProperty('content');
+ expect(request).not.toHaveProperty('editorData');
+ });
+
+ it('re-derives the format when a remote write turns an open Markdown page into HTML', async () => {
+ const { editor } = makeUnmountedEditor();
+ useDocumentStore.getState().initDocumentWithEditor({
+ autoSave: true,
+ content: HTML,
+ contentFormat: 'markdown',
+ documentId: 'page-1',
+ editor,
+ editorData: null,
+ sourceType: 'page',
+ updatedAt: new Date('2026-10-19T00:00:00Z'),
+ });
+
+ // Same body, only the type changed (`lh doc edit --file-type custom/html`).
+ useDocumentStore.getState().reconcileRemote('page-1', {
+ content: HTML,
+ editorData: null,
+ fileType: 'custom/html',
+ updatedAt: new Date('2026-10-19T00:00:05Z'),
+ });
+ expect(useDocumentStore.getState().documents['page-1'].contentFormat).toBe('html');
+
+ await useDocumentStore.getState().commitEditorMutation('page-1', { saveSource: 'llm_call' });
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('re-derives the format when a remote write turns an HTML page back into Markdown', () => {
+ const { editor } = makeUnmountedEditor();
+ seedHtmlPage(editor);
+
+ useDocumentStore.getState().reconcileRemote('page-1', {
+ content: '# Notes',
+ editorData: null,
+ fileType: 'custom/document',
+ updatedAt: new Date('2026-10-19T00:00:05Z'),
+ });
+
+ expect(useDocumentStore.getState().documents['page-1']).toMatchObject({
+ content: '# Notes',
+ contentFormat: 'markdown',
+ });
+ });
+
+ it('keeps the format when the remote row carries no type fields', () => {
+ const { editor } = makeUnmountedEditor();
+ seedHtmlPage(editor);
+
+ useDocumentStore.getState().reconcileRemote('page-1', {
+ content: HTML,
+ editorData: null,
+ updatedAt: new Date('2026-10-19T00:00:05Z'),
+ });
+
+ expect(useDocumentStore.getState().documents['page-1'].contentFormat).toBe('html');
+ });
+});
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index b05690119af..a85d0146240 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -15,6 +15,8 @@ import { setNamespace } from '@/utils/storeDebug';
import type { DocumentStore } from '../../store';
import { documentDetailResource } from '../document/projection';
+import type { DocumentFormatFields } from './contentFormat';
+import { hasDocumentFormatFields, resolveDocumentContentFormat } from './contentFormat';
import type { DocumentDispatch } from './reducer';
import { documentReducer } from './reducer';
@@ -35,7 +37,7 @@ export interface SaveExecutionOptions {
saveSource?: 'autosave' | 'manual' | 'restore' | 'system' | 'llm_call';
}
-export interface RemoteDocumentRow {
+export interface RemoteDocumentRow extends DocumentFormatFields {
content?: string | null;
editorData?: unknown;
updatedAt: Date | string;
@@ -91,7 +93,7 @@ export class EditorActionImpl {
if (!editor || !id || id !== activeDocumentId) return false;
const doc = documents[id];
- if (!doc) return false;
+ if (!doc || doc.contentFormat === 'html') return false;
try {
const editorMarkdown = (editor.getDocument('markdown') as unknown as string) || '';
@@ -211,10 +213,27 @@ export class EditorActionImpl {
const sameBody =
content === (doc.lastSavedContent ?? '') &&
isEqual(editorData, doc.lastSavedEditorData ?? null);
+ // A remote write can change the type alone (`lh doc edit --file-type`): the
+ // HTML guards and the SKILL.md frontmatter split must follow the new type.
+ const contentFormat = hasDocumentFormatFields(row)
+ ? resolveDocumentContentFormat(row)
+ : doc.contentFormat;
+ const formatChanged = contentFormat !== doc.contentFormat;
+ const skillFrontmatter =
+ contentFormat === 'skillMarkdown'
+ ? parseSkillMarkdownFrontmatter(content).frontmatter
+ : undefined;
if (sameBody) {
internal_dispatchDocument(
- { id: documentId, type: 'updateDocument', value: { lastUpdatedTime: updatedAt } },
+ {
+ id: documentId,
+ type: 'updateDocument',
+ value: {
+ lastUpdatedTime: updatedAt,
+ ...(formatChanged ? { contentFormat, skillFrontmatter } : {}),
+ },
+ },
n('reconcileRemote/rebased'),
);
return 'rebased';
@@ -227,10 +246,9 @@ export class EditorActionImpl {
type: 'updateDocument',
value: {
content,
+ contentFormat,
editorData,
- ...(doc.contentFormat === 'skillMarkdown'
- ? { skillFrontmatter: parseSkillMarkdownFrontmatter(content).frontmatter }
- : {}),
+ ...(contentFormat === 'skillMarkdown' || formatChanged ? { skillFrontmatter } : {}),
isDirty: false,
lastSavedContent: content,
lastSavedEditorData: editorData,
@@ -255,7 +273,7 @@ export class EditorActionImpl {
const doc = documents[documentId];
- if (!doc) return;
+ if (!doc || doc.contentFormat === 'html') return;
// Check if editorData is valid and non-empty
const editorDataRoot = (doc.editorData as { root?: { children?: unknown[] } } | null)?.root;
@@ -367,7 +385,8 @@ export class EditorActionImpl {
}).filter(([, value]) => value !== undefined),
)
: undefined;
- const metadataOnly = options?.metadataOnly === true;
+ // An HTML page's body is never edited here: only its title / emoji save.
+ const metadataOnly = options?.metadataOnly === true || doc.contentFormat === 'html';
if (metadataOnly && !hasMetadataChanges) return;
// Skip save if neither document content nor metadata changed
diff --git a/src/store/document/slices/editor/contentFormat.ts b/src/store/document/slices/editor/contentFormat.ts
new file mode 100644
index 00000000000..2a094e05bd8
--- /dev/null
+++ b/src/store/document/slices/editor/contentFormat.ts
@@ -0,0 +1,25 @@
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+
+import { isSkillMarkdownDocument } from '@/utils/skillMarkdown';
+
+import type { DocumentContentFormat } from './initialState';
+
+export interface DocumentFormatFields {
+ filename?: string | null;
+ fileType?: string | null;
+ title?: string | null;
+}
+
+/** The editor persistence format a server row calls for. */
+export const resolveDocumentContentFormat = (
+ document: DocumentFormatFields,
+): DocumentContentFormat => {
+ if (document.fileType === HTML_DOCUMENT_FILE_TYPE) return 'html';
+ return isSkillMarkdownDocument(document) ? 'skillMarkdown' : 'markdown';
+};
+
+/** Whether a row carries the fields its format is derived from. */
+export const hasDocumentFormatFields = (document: DocumentFormatFields): boolean =>
+ document.fileType !== undefined ||
+ document.filename !== undefined ||
+ document.title !== undefined;
diff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.ts
index 2658afccc47..370c108708f 100644
--- a/src/store/document/slices/editor/initialState.ts
+++ b/src/store/document/slices/editor/initialState.ts
@@ -7,7 +7,11 @@ import type { EditorState as LobehubEditorState } from '@lobehub/editor/react';
* Document source type - determines which service to use for persistence
*/
export type DocumentSourceType = 'notebook' | 'page';
-export type DocumentContentFormat = 'markdown' | 'skillMarkdown';
+/**
+ * - `html`: a self-contained HTML page. It is rendered in a sandboxed frame and
+ * never loaded into, read from or saved through the rich-text editor.
+ */
+export type DocumentContentFormat = 'html' | 'markdown' | 'skillMarkdown';
/**
* Editor content state for a single document
diff --git a/src/store/page/action.list.test.ts b/src/store/page/action.list.test.ts
index 031bd18bb62..25c96e970c4 100644
--- a/src/store/page/action.list.test.ts
+++ b/src/store/page/action.list.test.ts
@@ -125,13 +125,18 @@ describe('pageActions — useFetchDocuments', () => {
const [call] = await syncCalls('pageList');
vi.mocked(documentService.queryDocuments).mockResolvedValue({
- items: [row('docs_page'), row('upload_1', { fileType: 'text/plain' })],
- total: 2,
+ items: [
+ row('docs_page'),
+ row('docs_html', { fileType: 'custom/html' }),
+ row('upload_1', { fileType: 'text/plain' }),
+ ],
+ total: 3,
});
const page = (await call.fetcher()) as { items: LobeDocument[] };
- expect(page.items.map((item) => item.id)).toEqual(['docs_page']);
+ // An HTML page is a page too; an arbitrary upload is not.
+ expect(page.items.map((item) => item.id)).toEqual(['docs_page', 'docs_html']);
});
});
diff --git a/src/utils/__tests__/documentRenderMode.test.ts b/src/utils/__tests__/documentRenderMode.test.ts
index c788e2292c4..bae016079c2 100644
--- a/src/utils/__tests__/documentRenderMode.test.ts
+++ b/src/utils/__tests__/documentRenderMode.test.ts
@@ -96,4 +96,27 @@ describe('getDocumentRenderMode', () => {
mode: 'editor',
});
});
+
+ it('renders an HTML page in the HTML view, whatever its filename', () => {
+ expect(getDocumentRenderMode({ fileType: 'custom/html', filename: 'Goal report' })).toEqual({
+ mode: 'html',
+ });
+ /** @example A `.html` title does not turn the page into a source view. */
+ expect(getDocumentRenderMode({ fileType: 'custom/html', filename: 'report.html' })).toEqual({
+ mode: 'html',
+ });
+ /** @example A knowledge-base page carries a placeholder mirror file but keeps its body inline. */
+ expect(
+ getDocumentRenderMode({
+ fileId: 'kb-mirror',
+ fileType: 'custom/html',
+ filename: 'Goal report',
+ sourceType: 'api',
+ }),
+ ).toEqual({ mode: 'html' });
+ /** @example An uploaded HTML file has a MIME type and is still a file. */
+ expect(
+ getDocumentRenderMode({ fileId: 'file-1', fileType: 'text/html', filename: 'a.html' }),
+ ).toEqual({ mode: 'file' });
+ });
});
diff --git a/src/utils/__tests__/exportTextFile.test.ts b/src/utils/__tests__/exportTextFile.test.ts
new file mode 100644
index 00000000000..c964adff3cd
--- /dev/null
+++ b/src/utils/__tests__/exportTextFile.test.ts
@@ -0,0 +1,74 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { exportFileName, exportHtmlDocument } from '../exportTextFile';
+
+const mocks = vi.hoisted(() => ({ exportFile: vi.fn(), isDesktop: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ get isDesktop() {
+ return mocks.isDesktop;
+ },
+}));
+
+vi.mock('@/services/electron/desktopExportService', () => ({
+ desktopExportService: { exportFile: mocks.exportFile },
+}));
+
+describe('exportFileName', () => {
+ it('appends the extension once and names an untitled export', () => {
+ expect(exportFileName('Goal report', 'html')).toBe('Goal report.html');
+ expect(exportFileName('report.HTML', 'html')).toBe('report.HTML');
+ expect(exportFileName(' ', 'html')).toBe('Untitled.html');
+ });
+});
+
+describe('exportHtmlDocument', () => {
+ const HTML = '<!doctype html><html><body>Report</body></html>';
+
+ beforeEach(() => {
+ mocks.isDesktop = false;
+ mocks.exportFile.mockReset();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('downloads the page itself as a .html file in the browser', async () => {
+ const createObjectURL = vi.fn((_blob: Blob) => 'blob:report');
+ vi.stubGlobal('URL', { createObjectURL, revokeObjectURL: vi.fn() });
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
+
+ await expect(exportHtmlDocument(HTML, 'Goal report')).resolves.toBe('downloaded');
+
+ expect((click.mock.contexts[0] as HTMLAnchorElement).download).toBe('Goal report.html');
+ const blob = createObjectURL.mock.calls[0][0];
+ expect(blob.type).toBe('text/html');
+ expect(await blob.text()).toBe(HTML);
+ });
+
+ it('saves through the desktop dialog with an HTML filter', async () => {
+ mocks.isDesktop = true;
+ mocks.exportFile.mockResolvedValue({ canceled: false, filePath: '/tmp/Goal report.html' });
+
+ await expect(exportHtmlDocument(HTML, 'Goal report')).resolves.toBe('saved');
+
+ expect(mocks.exportFile).toHaveBeenCalledWith({
+ content: HTML,
+ fileName: 'Goal report.html',
+ filter: { extensions: ['html'], name: 'HTML' },
+ });
+ });
+
+ it('reports a canceled desktop save', async () => {
+ mocks.isDesktop = true;
+ mocks.exportFile.mockResolvedValue({ canceled: true });
+
+ await expect(exportHtmlDocument(HTML, null)).resolves.toBe('canceled');
+ });
+});
diff --git a/src/utils/documentRenderMode.ts b/src/utils/documentRenderMode.ts
index 76a72d42bfd..a35cf66519b 100644
--- a/src/utils/documentRenderMode.ts
+++ b/src/utils/documentRenderMode.ts
@@ -5,6 +5,7 @@ import {
CUSTOM_DOCUMENT_FILE_TYPE,
EDITOR_DOCUMENT_SOURCE_TYPES,
hasFilenameExtension,
+ HTML_DOCUMENT_FILE_TYPE,
MARKDOWN_DOCUMENT_FILE_TYPES,
} from '@lobechat/const';
@@ -22,7 +23,10 @@ interface DocumentRenderModeFields {
/** Content surface selected for an uploaded file or an editable document. */
export type DocumentRenderMode =
- { mode: 'editor' } | { language: string; mode: 'highlight' } | { mode: 'file' };
+ | { mode: 'editor' }
+ | { language: string; mode: 'highlight' }
+ | { mode: 'file' }
+ | { mode: 'html' };
const EDITOR_DOCUMENT_FILE_TYPES = new Set([
AGENT_DOCUMENT_FILE_TYPE,
@@ -47,9 +51,14 @@ const isEditorDocument = (document: DocumentRenderModeFields): boolean => {
* - Document metadata; file source attribution survives deletion of the original file.
*
* Returns:
- * - File preview, rich-text editor, or source editor mode.
+ * - File preview, rich-text editor, sandboxed HTML page, or source editor mode.
*/
export const getDocumentRenderMode = (document: DocumentRenderModeFields): DocumentRenderMode => {
+ // Only pages are created with this type (uploads carry a MIME type). A page in
+ // a knowledge base also has a placeholder mirror fileId, but its body stays in
+ // `content`, so the type wins over the upload check below.
+ if (document.fileType === HTML_DOCUMENT_FILE_TYPE) return { mode: 'html' };
+
// Keep deleted uploads in the file view even after their fileId FK is cleared.
if (document.fileId || document.sourceType === 'file') return { mode: 'file' };
diff --git a/src/utils/exportTextFile.ts b/src/utils/exportTextFile.ts
new file mode 100644
index 00000000000..56b01c505c2
--- /dev/null
+++ b/src/utils/exportTextFile.ts
@@ -0,0 +1,65 @@
+import { isDesktop } from '@lobechat/const';
+
+export interface ExportTextFileOptions {
+ /** File name before the extension; an existing matching extension is kept once. */
+ baseName: string;
+ content: string;
+ /** Extension without the dot, e.g. `html`. */
+ extension: string;
+ /** Save-dialog filter label, e.g. `HTML`. */
+ filterName: string;
+ mimeType: string;
+}
+
+/**
+ * - `saved`: the desktop save dialog wrote the file and showed its own toast.
+ * - `downloaded`: the browser download started; the caller confirms it.
+ * - `canceled`: the user closed the desktop save dialog.
+ */
+export type ExportTextFileResult = 'canceled' | 'downloaded' | 'saved';
+
+export const exportFileName = (baseName: string, extension: string) => {
+ const name = baseName.trim() || 'Untitled';
+ return name.toLowerCase().endsWith(`.${extension}`) ? name : `${name}.${extension}`;
+};
+
+/** Save text as a local file: the desktop save dialog, or a browser download. */
+export const exportTextFile = async ({
+ baseName,
+ content,
+ extension,
+ filterName,
+ mimeType,
+}: ExportTextFileOptions): Promise<ExportTextFileResult> => {
+ const fileName = exportFileName(baseName, extension);
+
+ if (isDesktop) {
+ const { desktopExportService } = await import('@/services/electron/desktopExportService');
+ const result = await desktopExportService.exportFile({
+ content,
+ fileName,
+ filter: { extensions: [extension], name: filterName },
+ });
+ return result.canceled ? 'canceled' : 'saved';
+ }
+
+ const url = URL.createObjectURL(new Blob([content], { type: mimeType }));
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = fileName;
+ document.body.append(anchor);
+ anchor.click();
+ anchor.remove();
+ URL.revokeObjectURL(url);
+ return 'downloaded';
+};
+
+/** Download an HTML page document as a self-contained `.html` file. */
+export const exportHtmlDocument = (content: string, title: string | null | undefined) =>
+ exportTextFile({
+ baseName: title || '',
+ content,
+ extension: 'html',
+ filterName: 'HTML',
+ mimeType: 'text/html',
+ });