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(portal-document): drop the chat-to-edit footer and move export into the ⋯ menu (#20927)

Arvin Xuc2b9dc5f69ad
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index cfbfb8419d6..9a1fc211c4d 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "لا يوجد مستند مفتوح",
"agentDocument.linkCopied": "تم نسخ الرابط",
"agentDocument.openAsPage": "افتح كصفحة كاملة",
- "agentDocument.portal.chatWithDocument": "الدردشة لتعديل",
"agentDocument.portal.export": "تصدير",
"agentDocument.portal.titlePlaceholder": "مستند بدون عنوان",
"agentDocument.portal.viewAll": "عرض جميع المستندات",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 0c491bde8f2..de196df49a3 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Няма отворен документ",
"agentDocument.linkCopied": "Връзката е копирана",
"agentDocument.openAsPage": "Отвори като цяла страница",
- "agentDocument.portal.chatWithDocument": "Чат за редактиране",
"agentDocument.portal.export": "Експортиране",
"agentDocument.portal.titlePlaceholder": "Без заглавие",
"agentDocument.portal.viewAll": "Преглед на всички документи",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 8e204f190f7..c89e224e97d 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Kein Dokument geöffnet",
"agentDocument.linkCopied": "Link kopiert",
"agentDocument.openAsPage": "Als vollständige Seite öffnen",
- "agentDocument.portal.chatWithDocument": "Chat zum Bearbeiten",
"agentDocument.portal.export": "Exportieren",
"agentDocument.portal.titlePlaceholder": "Unbenanntes Dokument",
"agentDocument.portal.viewAll": "Alle Dokumente anzeigen",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 6b4cd761fcc..21ae56c22a9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "No document open",
"agentDocument.linkCopied": "Link copied",
"agentDocument.openAsPage": "Open as full page",
- "agentDocument.portal.chatWithDocument": "Chat to edit",
"agentDocument.portal.export": "Export",
"agentDocument.portal.titlePlaceholder": "Untitled document",
"agentDocument.portal.viewAll": "View all documents",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 2ddd16b8b6f..7cbc79f073b 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Ningún documento abierto",
"agentDocument.linkCopied": "Enlace copiado",
"agentDocument.openAsPage": "Abrir como página completa",
- "agentDocument.portal.chatWithDocument": "Chatear para editar",
"agentDocument.portal.export": "Exportar",
"agentDocument.portal.titlePlaceholder": "Documento sin título",
"agentDocument.portal.viewAll": "Ver todos los documentos",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index 9191e9bd412..ec8ad88582d 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "هیچ سندی باز نیست",
"agentDocument.linkCopied": "لینک کپی شد",
"agentDocument.openAsPage": "باز کردن به صورت صفحه کامل",
- "agentDocument.portal.chatWithDocument": "گفتگو برای ویرایش",
"agentDocument.portal.export": "صادر کردن",
"agentDocument.portal.titlePlaceholder": "سند بدون عنوان",
"agentDocument.portal.viewAll": "مشاهده همه اسناد",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index 25f12a52743..056e51e8fbb 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Aucun document ouvert",
"agentDocument.linkCopied": "Lien copié",
"agentDocument.openAsPage": "Ouvrir en pleine page",
- "agentDocument.portal.chatWithDocument": "Discuter pour modifier",
"agentDocument.portal.export": "Exporter",
"agentDocument.portal.titlePlaceholder": "Document sans titre",
"agentDocument.portal.viewAll": "Voir tous les documents",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index 263fc6c7276..29c2c1968b8 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Nessun documento aperto",
"agentDocument.linkCopied": "Link copiato",
"agentDocument.openAsPage": "Apri come pagina intera",
- "agentDocument.portal.chatWithDocument": "Chat per modificare",
"agentDocument.portal.export": "Esporta",
"agentDocument.portal.titlePlaceholder": "Documento senza titolo",
"agentDocument.portal.viewAll": "Visualizza tutti i documenti",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 387b49cc28f..e775d6ce50f 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "ドキュメントが開かれていません",
"agentDocument.linkCopied": "リンクがコピーされました",
"agentDocument.openAsPage": "全画面で開く",
- "agentDocument.portal.chatWithDocument": "編集のためにチャット",
"agentDocument.portal.export": "エクスポート",
"agentDocument.portal.titlePlaceholder": "無題のドキュメント",
"agentDocument.portal.viewAll": "すべてのドキュメントを表示",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index 11ba47d60ec..f07897a2ddf 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "열린 문서 없음",
"agentDocument.linkCopied": "링크가 복사되었습니다",
"agentDocument.openAsPage": "전체 페이지로 열기",
- "agentDocument.portal.chatWithDocument": "편집을 위한 채팅",
"agentDocument.portal.export": "내보내기",
"agentDocument.portal.titlePlaceholder": "제목 없는 문서",
"agentDocument.portal.viewAll": "모든 문서 보기",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 9395e0c0547..e666fa710d6 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Geen document geopend",
"agentDocument.linkCopied": "Link gekopieerd",
"agentDocument.openAsPage": "Openen als volledige pagina",
- "agentDocument.portal.chatWithDocument": "Chat om te bewerken",
"agentDocument.portal.export": "Exporteren",
"agentDocument.portal.titlePlaceholder": "Naamloos document",
"agentDocument.portal.viewAll": "Alle documenten bekijken",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 11a17a1df3b..03d707f93c1 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Brak otwartego dokumentu",
"agentDocument.linkCopied": "Link skopiowany",
"agentDocument.openAsPage": "Otwórz jako pełną stronę",
- "agentDocument.portal.chatWithDocument": "Czat do edycji",
"agentDocument.portal.export": "Eksportuj",
"agentDocument.portal.titlePlaceholder": "Nieoznakowany dokument",
"agentDocument.portal.viewAll": "Zobacz wszystkie dokumenty",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 8db32f2b900..f2b65e22c39 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Nenhum documento aberto",
"agentDocument.linkCopied": "Link copiado",
"agentDocument.openAsPage": "Abrir como página inteira",
- "agentDocument.portal.chatWithDocument": "Conversar para editar",
"agentDocument.portal.export": "Exportar",
"agentDocument.portal.titlePlaceholder": "Documento sem título",
"agentDocument.portal.viewAll": "Ver todos os documentos",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 5cf28a403f8..87e4ad04723 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Документ не открыт",
"agentDocument.linkCopied": "Ссылка скопирована",
"agentDocument.openAsPage": "Открыть на всю страницу",
- "agentDocument.portal.chatWithDocument": "Чат для редактирования",
"agentDocument.portal.export": "Экспорт",
"agentDocument.portal.titlePlaceholder": "Безымянный документ",
"agentDocument.portal.viewAll": "Просмотреть все документы",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index a4e794af182..0b93fc7be18 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Açık belge yok",
"agentDocument.linkCopied": "Bağlantı kopyalandı",
"agentDocument.openAsPage": "Tam sayfa olarak aç",
- "agentDocument.portal.chatWithDocument": "Düzenlemek için sohbet et",
"agentDocument.portal.export": "Dışa aktar",
"agentDocument.portal.titlePlaceholder": "Adsız belge",
"agentDocument.portal.viewAll": "Tüm belgeleri görüntüle",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 20c25d78ae1..bbf8a31b0eb 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "Không có tài liệu nào được mở",
"agentDocument.linkCopied": "Liên kết đã được sao chép",
"agentDocument.openAsPage": "Mở dưới dạng trang đầy đủ",
- "agentDocument.portal.chatWithDocument": "Trò chuyện để chỉnh sửa",
"agentDocument.portal.export": "Xuất",
"agentDocument.portal.titlePlaceholder": "Tài liệu chưa có tiêu đề",
"agentDocument.portal.viewAll": "Xem tất cả tài liệu",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 3cf1f9444ea..eca7f137db3 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "未打开任何文档",
"agentDocument.linkCopied": "链接已复制",
"agentDocument.openAsPage": "打开整页",
- "agentDocument.portal.chatWithDocument": "对话编辑",
"agentDocument.portal.export": "导出",
"agentDocument.portal.titlePlaceholder": "未命名文稿",
"agentDocument.portal.viewAll": "查看全部文稿",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index aad72638fe7..f93916dfc01 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -32,7 +32,6 @@
"agentDocument.emptyTitle": "未開啟任何文件",
"agentDocument.linkCopied": "連結已複製",
"agentDocument.openAsPage": "以完整頁面開啟",
- "agentDocument.portal.chatWithDocument": "聊天以編輯",
"agentDocument.portal.export": "匯出",
"agentDocument.portal.titlePlaceholder": "未命名文件",
"agentDocument.portal.viewAll": "查看所有文件",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d23e2ad8727..7e3ce3ce7f4 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -213,7 +213,6 @@ export default {
'agentDocument.openAsPage': 'Open as full page',
'agentDocument.portal.viewAll': 'View all documents',
'agentDocument.portal.titlePlaceholder': 'Untitled document',
- 'agentDocument.portal.chatWithDocument': 'Chat to edit',
'agentDocument.portal.export': 'Export',
'agentNotFound.desc':
'This agent does not exist or is no longer accessible — it may have been deleted or set to private by its owner.',
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 9bb10f5c026..db3a4f6caf4 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -86,20 +86,6 @@ vi.mock('@/features/FloatingChatPanel', () => ({
default: () => <div data-testid="floating-chat-panel" />,
}));
-vi.mock('./FooterActions', () => ({
- default: ({ fileBacked }: { fileBacked?: boolean }) => (
- <div data-testid="footer-actions">
- {!fileBacked && <button data-testid="footer-export" type={'button'} />}
- </div>
- ),
-}));
-// The body no longer resolves a doc-anchored topic itself — the footer's chat
-// entry calls `getOrCreateChatTopic` on demand. Keep the mock registered so the
-// historical test comments below still name the right constraint owner.
-vi.mock('@/features/FloatingChatPanel/useDocumentChatTopic', () => ({
- useDocumentChatTopic: () => ({ error: undefined, isLoading: false, topicId: undefined }),
-}));
-
const mockChatState = vi.hoisted(() => ({
current: {
activeTopicId: 'topic-1',
@@ -152,25 +138,9 @@ describe('DocumentBody', () => {
render(<DocumentBody />);
/** @example The original file id reaches the read-only preview. */
expect(screen.getByTestId('original-file-preview').dataset.fileId).toBe('file-original');
- /** @example Neither editor mounts. The portal footer (chat to edit / export)
- replaces the inline conversation panel this PR's body used to render. */
+ /** @example Neither editor mounts. */
expect(screen.queryByTestId('highlight-editor')).toBeNull();
expect(screen.queryByTestId('editor-canvas')).toBeNull();
- expect(screen.getByTestId('footer-actions')).toBeTruthy();
- });
-
- it('hides the markdown export for a file-backed preview', () => {
- // ROOT CAUSE:
- // A file-backed document's markdown `content` is empty — its data lives
- // behind `fileId` — so exporting here would download an empty `.md`
- // instead of the displayed file. Mirrors the standalone page menu, which
- // already filters out export when `fileBacked` is set.
- mockDocumentMeta.current = { content: '', fileId: 'file-original', filename: 'source.unknown' };
- render(<DocumentBody />);
- /** @example The footer stays (chat-to-edit still applies)… */
- expect(screen.getByTestId('footer-actions')).toBeTruthy();
- /** @example …but the markdown export button is gone. */
- expect(screen.queryByTestId('footer-export')).toBeNull();
});
beforeEach(() => {
@@ -186,43 +156,6 @@ describe('DocumentBody', () => {
vi.useRealTimers();
});
- it('renders the footer actions for an agent document', () => {
- render(<DocumentBody />);
-
- expect(screen.getByTestId('footer-actions')).toBeDefined();
- });
-
- it('holds the footer until the document is agent-bound', () => {
- // The useDocumentChatTopic hook is not mounted by the body anymore — the
- // footer's own chat entry resolves the topic on demand. The comment above
- // the original panel tests is kept for history: the NOT_FOUND constraint
- // now lives in ./FooterActions instead of the body's render gate.
- mockChatState.current.portalStack[0].agentDocumentId = undefined;
-
- render(<DocumentBody />);
-
- expect(screen.queryByTestId('footer-actions')).toBeNull();
- });
-
- it('does not render footer actions without an active agent', () => {
- mockAgentState.current.activeAgentId = undefined;
-
- render(<DocumentBody />);
-
- expect(screen.queryByTestId('footer-actions')).toBeNull();
- });
-
- // A plain notebook document is opened as `openDocument(document.id)` — no
- // agentDocumentId. It has no `agent_documents` row, so the footer's
- // `getOrCreateChatTopic` would throw NOT_FOUND. The footer must not render.
- it('does not render footer actions for a plain document with no agentDocumentId', () => {
- mockChatState.current.portalStack[0].agentDocumentId = undefined;
-
- render(<DocumentBody />);
-
- expect(screen.queryByTestId('footer-actions')).toBeNull();
- });
-
it('renders highlight editor for non-markdown files', () => {
mockDocumentMeta.current = { content: 'raw log content', filename: 'topic_call.txt' };
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index 005f68a36af..ea24262396d 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -17,7 +17,6 @@ import WideScreenContainer from '@/features/WideScreenContainer';
import { useClientDataSWR } from '@/libs/swr';
import { portalKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
-import { useAgentStore } from '@/store/agent';
import { useDocumentStore } from '@/store/document';
import { getDocumentRenderMode } from '@/utils/documentRenderMode';
import {
@@ -25,13 +24,8 @@ import {
parseSkillMarkdownFrontmatterFields,
} from '@/utils/skillMarkdown';
-import {
- useDocumentViewFullPage,
- useResolvedAgentDocumentId,
- useResolvedDocumentId,
-} from './documentViewContext';
+import { useDocumentViewFullPage, useResolvedDocumentId } from './documentViewContext';
import EditorCanvas from './EditorCanvas';
-import FooterActions from './FooterActions';
import SkillFrontmatterCard from './SkillFrontmatterCard';
import TodoList from './TodoList';
import { useHighlightSave } from './useHighlightSave';
@@ -225,14 +219,7 @@ HighlightEditor.displayName = 'HighlightEditor';
const DocumentBody = memo(() => {
const documentId = useResolvedDocumentId();
- const agentDocumentId = useResolvedAgentDocumentId();
const fullPage = useDocumentViewFullPage();
- const activeAgentId = useAgentStore((s) => s.activeAgentId);
- // `agentDocumentId` is what marks this as an *agent* document: only the agent-doc
- // openers pass it. The notebook opens plain topic documents with the id alone, and
- // the footer's chat entry (which resolves a doc-anchored topic) must stay out of
- // the way there — `getOrCreateChatTopic` throws NOT_FOUND without the binding row.
- const footerEligible = !fullPage && !!activeAgentId && !!documentId && !!agentDocumentId;
const [skillFrontmatter, contentFormat] = useDocumentStore((s) =>
documentId
? [s.documents[documentId]?.skillFrontmatter ?? '', s.documents[documentId]?.contentFormat]
@@ -308,20 +295,6 @@ const DocumentBody = memo(() => {
)}
</div>
{renderMode.mode !== 'file' && <TodoList />}
- {/* The compact portal closes with two entry buttons instead of an inline
- conversation: "chat to edit" opens the doc-anchored chat on the right
- panel, "export" downloads the markdown. The full-page route keeps its
- own layout (the working sidebar already provides chat), and plain
- notebook documents have no `agent_documents` row to anchor a chat
- topic, so the footer only renders for agent documents. */}
- {footerEligible && (
- <FooterActions
- agentId={activeAgentId}
- documentId={documentId}
- fileBacked={renderMode.mode === 'file'}
- title={documentMeta?.title ?? documentMeta?.filename ?? undefined}
- />
- )}
</Flexbox>
);
});
diff --git a/src/features/Portal/Document/FooterActions.tsx b/src/features/Portal/Document/FooterActions.tsx
deleted file mode 100644
index 5481220fa0a..00000000000
--- a/src/features/Portal/Document/FooterActions.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-'use client';
-
-import { isDesktop } from '@lobechat/const';
-import { Flexbox } from '@lobehub/ui';
-import { Button, toast } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { Download, MessageSquareText } from 'lucide-react';
-import { memo, useCallback, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { agentDocumentService } from '@/services/agentDocument';
-import { documentService } from '@/services/document';
-import { useChatStore } from '@/store/chat';
-import { useDocumentStore } from '@/store/document';
-
-const styles = createStaticStyles(({ css }) => ({
- root: css`
- display: flex;
- flex-shrink: 0;
- gap: 8px;
-
- padding-block: 12px;
- padding-block-end: calc(12px + env(safe-area-inset-bottom));
- padding-inline: 16px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
-
- background: ${cssVar.colorBgContainer};
- `,
-}));
-
-interface FooterActionsProps {
- agentId: string;
- documentId: string;
- /**
- * File-backed documents keep their data behind `fileId` with an empty
- * markdown `content`, so the Markdown export would download an empty file.
- * Mirrors the standalone page menu, which filters out export when
- * `fileBacked` is set.
- */
- fileBacked?: boolean;
- title?: string;
-}
-
-/**
- * Compact portal footer: two entry buttons that replace the inline
- * conversation input. "Chat to edit" jumps the main conversation to the
- * doc-anchored chat topic (created on demand via `getOrCreateChatTopic`);
- * "Export" downloads the current markdown content.
- */
-const FooterActions = memo<FooterActionsProps>(({ agentId, documentId, fileBacked, title }) => {
- const { t } = useTranslation(['chat', 'file', 'common']);
-
- const switchTopic = useChatStore((s) => s.switchTopic);
- const clearPortalStack = useChatStore((s) => s.clearPortalStack);
-
- // The editor canvas keeps the live buffer in the document store; the SWR
- // meta reflects the last persisted markdown. Prefer the store (fresher) —
- // including an intentionally emptied buffer — and fall back to the SWR copy
- // only while the editor has not produced a buffer for this document.
- const storeContent = useDocumentStore((s) => s.documents[documentId]?.content);
- const { data: documentMeta } = useClientDataSWR(
- documentId ? portalKeys.documentHeader(documentId) : null,
- () => documentService.getDocumentById(documentId!),
- );
- const markdown = storeContent ?? documentMeta?.content ?? '';
-
- // A pending guard, not just visual: the server's lookup-then-create is not
- // atomic, so concurrent double-clicks can create two document topics.
- const [switching, setSwitching] = useState(false);
-
- const handleChatToEdit = useCallback(async () => {
- if (switching) return;
- setSwitching(true);
- try {
- const result = await agentDocumentService.getOrCreateChatTopic({ agentId, documentId });
- // Return to the main conversation anchored on this document's chat topic —
- // the portal closes so the topic surface takes over.
- clearPortalStack();
- await switchTopic(result.topicId);
- } catch {
- toast.error(t('operationFailed', { ns: 'common' }));
- } finally {
- setSwitching(false);
- }
- }, [agentId, clearPortalStack, documentId, switchTopic, switching, t]);
-
- const handleExport = useCallback(async () => {
- const content = markdown;
- const fileName = `${title || 'Untitled'}.md`;
- try {
- if (isDesktop) {
- const { desktopExportService } = await import('@/services/electron/desktopExportService');
- await desktopExportService.exportMarkdown({ content, fileName });
- } else {
- const blob = new Blob([content], { type: 'text/markdown' });
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
- anchor.href = url;
- anchor.download = fileName;
- document.body.append(anchor);
- anchor.click();
- anchor.remove();
- URL.revokeObjectURL(url);
- toast.success(t('pageEditor.exportSuccess', { ns: 'file' }));
- }
- } catch {
- toast.error(t('pageEditor.exportError', { ns: 'file' }));
- }
- }, [markdown, t, title]);
-
- return (
- <Flexbox horizontal className={styles.root} gap={8}>
- <Button
- block
- icon={MessageSquareText}
- loading={switching}
- type={'default'}
- onClick={() => void handleChatToEdit()}
- >
- {t('agentDocument.portal.chatWithDocument', { ns: 'chat' })}
- </Button>
- {!fileBacked && (
- <Button block icon={Download} type={'default'} onClick={() => void handleExport()}>
- {t('agentDocument.portal.export', { ns: 'chat' })}
- </Button>
- )}
- </Flexbox>
- );
-});
-
-FooterActions.displayName = 'PortalDocumentFooterActions';
-
-export default FooterActions;
diff --git a/src/features/Portal/Document/useMarkdownExport.test.ts b/src/features/Portal/Document/useMarkdownExport.test.ts
new file mode 100644
index 00000000000..6432bf6a71f
--- /dev/null
+++ b/src/features/Portal/Document/useMarkdownExport.test.ts
@@ -0,0 +1,79 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useMarkdownExport } from './useMarkdownExport';
+
+const mocks = vi.hoisted(() => ({
+ documentMeta: undefined as Record<string, unknown> | undefined,
+ storeContent: undefined as string | undefined,
+ toastSuccess: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ isDesktop: false,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ toast: { error: vi.fn(), success: mocks.toastSuccess },
+}));
+
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: () => ({ data: mocks.documentMeta }),
+}));
+
+vi.mock('@/store/document', () => ({
+ useDocumentStore: (selector: (s: unknown) => unknown) =>
+ selector({ documents: { doc_1: { content: mocks.storeContent } } }),
+}));
+
+describe('useMarkdownExport', () => {
+ beforeEach(() => {
+ mocks.documentMeta = { content: 'saved', filename: 'brief.md', title: 'Launch Brief' };
+ mocks.storeContent = undefined;
+ vi.clearAllMocks();
+ });
+
+ it('is unavailable until the document loads', () => {
+ mocks.documentMeta = undefined;
+ const { result } = renderHook(() => useMarkdownExport('doc_1'));
+
+ expect(result.current).toBeUndefined();
+ });
+
+ // A file-backed document keeps its data behind `fileId`; its markdown is empty.
+ it('is unavailable for a file-backed document', () => {
+ mocks.documentMeta = { content: '', fileId: 'file_1', filename: 'source.pdf' };
+ 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');
+ vi.stubGlobal('URL', { createObjectURL, revokeObjectURL: vi.fn() });
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
+
+ const { result } = renderHook(() => useMarkdownExport('doc_1'));
+ await act(() => result.current!());
+
+ const anchor = click.mock.contexts[0] as HTMLAnchorElement;
+ expect(anchor.download).toBe('Launch Brief.md');
+ expect(await createObjectURL.mock.calls[0][0].text()).toBe('live edit');
+ expect(mocks.toastSuccess).toHaveBeenCalledOnce();
+ vi.unstubAllGlobals();
+ });
+
+ it('does not double the extension of a title that already ends in .md', async () => {
+ mocks.documentMeta = { content: 'saved', filename: 'notes.md', title: 'Week 10 notes.md' };
+ vi.stubGlobal('URL', { createObjectURL: vi.fn(() => 'blob:doc'), revokeObjectURL: vi.fn() });
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
+
+ const { result } = renderHook(() => useMarkdownExport('doc_1'));
+ await act(() => result.current!());
+
+ expect((click.mock.contexts.at(-1) as HTMLAnchorElement).download).toBe('Week 10 notes.md');
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/src/features/Portal/Document/useMarkdownExport.ts b/src/features/Portal/Document/useMarkdownExport.ts
new file mode 100644
index 00000000000..a15237016fe
--- /dev/null
+++ b/src/features/Portal/Document/useMarkdownExport.ts
@@ -0,0 +1,61 @@
+'use client';
+
+import { isDesktop } from '@lobechat/const';
+import { toast } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { portalKeys } from '@/libs/swr/keys';
+import { documentService } from '@/services/document';
+import { useDocumentStore } from '@/store/document';
+import { getDocumentRenderMode } from '@/utils/documentRenderMode';
+
+/**
+ * Downloads the portal document as Markdown. Returns `undefined` until the
+ * 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).
+ */
+export const useMarkdownExport = (documentId: string | undefined) => {
+ const { t } = useTranslation('file');
+
+ // The editor canvas keeps the live buffer in the document store; the SWR
+ // meta reflects the last persisted markdown. Prefer the store (fresher) —
+ // including an intentionally emptied buffer — and fall back to the SWR copy
+ // only while the editor has not produced a buffer for this document.
+ const storeContent = useDocumentStore((s) =>
+ documentId ? s.documents[documentId]?.content : undefined,
+ );
+ const { data: documentMeta } = useClientDataSWR(
+ documentId ? portalKeys.documentHeader(documentId) : null,
+ () => documentService.getDocumentById(documentId!),
+ );
+
+ if (!documentMeta || getDocumentRenderMode(documentMeta).mode === 'file') return;
+
+ return async () => {
+ const content = storeContent ?? documentMeta.content ?? '';
+ const baseName = documentMeta.title || documentMeta.filename || 'Untitled';
+ // Agent-written titles often carry the extension already (`notes.md`).
+ const fileName = /\.md$/i.test(baseName) ? baseName : `${baseName}.md`;
+ try {
+ if (isDesktop) {
+ const { desktopExportService } = await import('@/services/electron/desktopExportService');
+ await desktopExportService.exportMarkdown({ content, fileName });
+ return;
+ }
+ const blob = new Blob([content], { type: 'text/markdown' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = fileName;
+ document.body.append(anchor);
+ anchor.click();
+ anchor.remove();
+ URL.revokeObjectURL(url);
+ toast.success(t('pageEditor.exportSuccess'));
+ } catch {
+ toast.error(t('pageEditor.exportError'));
+ }
+ };
+};
diff --git a/src/features/Portal/Document/useMoreMenu.test.ts b/src/features/Portal/Document/useMoreMenu.test.ts
index 2409867c996..83d44292a18 100644
--- a/src/features/Portal/Document/useMoreMenu.test.ts
+++ b/src/features/Portal/Document/useMoreMenu.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
closeDocument: vi.fn(),
confirmModal: vi.fn(),
documentId: 'doc_1' as string | undefined,
+ exportMarkdown: vi.fn() as (() => Promise<void>) | undefined,
isLoading: false,
metaLocked: false,
openRenameModal: vi.fn(),
@@ -47,6 +48,10 @@ vi.mock('./titleContext', () => ({
}),
}));
+vi.mock('./useMarkdownExport', () => ({
+ useMarkdownExport: () => mocks.exportMarkdown,
+}));
+
vi.mock('./usePortalDocumentHeader', () => ({
TITLE_MAX_LENGTH: 100,
usePortalDocumentHeaderActions: () => ({
@@ -63,6 +68,7 @@ describe('useDocumentMoreMenu', () => {
vi.clearAllMocks();
mocks.agentDocumentId = 'adoc_1';
mocks.documentId = 'doc_1';
+ mocks.exportMarkdown = vi.fn();
mocks.isLoading = false;
mocks.metaLocked = false;
mocks.url = 'https://app.lobehub.com/agent/agt_1/docs/doc_1';
@@ -156,4 +162,20 @@ describe('useDocumentMoreMenu', () => {
expect(result.current).toBeUndefined();
});
+
+ it('offers the markdown export as a menu action', () => {
+ const { result } = renderHook(() => useDocumentMoreMenu());
+ const item = result.current?.extraItems?.[0] as { key: string; onClick: () => void };
+
+ expect(item.key).toBe('export');
+ item.onClick();
+ expect(mocks.exportMarkdown).toHaveBeenCalledOnce();
+ });
+
+ it('leaves the export out when the document cannot be exported', () => {
+ mocks.exportMarkdown = undefined;
+ const { result } = renderHook(() => useDocumentMoreMenu());
+
+ expect(result.current?.extraItems).toBeUndefined();
+ });
});
diff --git a/src/features/Portal/Document/useMoreMenu.ts b/src/features/Portal/Document/useMoreMenu.tsx
similarity index 85%
rename from src/features/Portal/Document/useMoreMenu.ts
rename to src/features/Portal/Document/useMoreMenu.tsx
index 521110f131a..6195fcb740b 100644
--- a/src/features/Portal/Document/useMoreMenu.ts
+++ b/src/features/Portal/Document/useMoreMenu.tsx
@@ -1,4 +1,6 @@
+import { Icon } from '@lobehub/ui';
import { confirmModal, toast } from '@lobehub/ui/base-ui';
+import { DownloadIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { openRenameModal } from '@/components/RenameModal';
@@ -7,6 +9,7 @@ import { agentDocumentService } from '@/services/agentDocument';
import { useChatStore } from '@/store/chat';
import { usePortalDocumentTitleState } from './titleContext';
+import { useMarkdownExport } from './useMarkdownExport';
import { TITLE_MAX_LENGTH, usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
@@ -14,6 +17,7 @@ export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
const { isLoading, metaLocked, savedTitle, saveTitle } = usePortalDocumentTitleState();
const { agentDocumentId, agentId, documentId, refresh, url } = usePortalDocumentHeaderActions();
const closeDocument = useChatStore((s) => s.closeDocument);
+ const exportMarkdown = useMarkdownExport(documentId);
if (!documentId || isLoading) return;
@@ -59,6 +63,16 @@ 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,
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.