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 title editing and footer chat-to-edit/export actions (#19582)

Arvin Xu12c4d79df5d6
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 33fd1b781e7..623508bf38c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -32,6 +32,10 @@
"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",
"agentNotFound.desc": "This agent does not exist or is no longer accessible — it may have been deleted or set to private by its owner.",
"agentNotFound.title": "Agent Unavailable",
"agentProfile.files_one": "{{count}} file",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 918cd85f568..9334688406d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -32,6 +32,10 @@
"agentDocument.emptyTitle": "未打开任何文档",
"agentDocument.linkCopied": "链接已复制",
"agentDocument.openAsPage": "打开整页",
+ "agentDocument.portal.chatWithDocument": "对话编辑",
+ "agentDocument.portal.export": "导出",
+ "agentDocument.portal.titlePlaceholder": "未命名文稿",
+ "agentDocument.portal.viewAll": "查看全部文稿",
"agentNotFound.desc": "该助理不存在或您已无权访问,可能已被删除或被其所有者设为私人。",
"agentNotFound.title": "助理不可用",
"agentProfile.files_one": "{{count}} 个文件",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d54511b5148..cf5113ca9fb 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -81,6 +81,10 @@ export default {
'agentDocument.emptyTitle': 'No document open',
'agentDocument.linkCopied': 'Link copied',
'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.',
'permission.configAccess.agentChatOnly':
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 7c05ee7d4b3..9bb10f5c026 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -86,25 +86,18 @@ vi.mock('@/features/FloatingChatPanel', () => ({
default: () => <div data-testid="floating-chat-panel" />,
}));
-const docChatTopicState = vi.hoisted(() => ({
- current: {
- error: undefined as Error | undefined,
- isLoading: false,
- topicId: 'doc-topic-1' as string | undefined,
- },
+vi.mock('./FooterActions', () => ({
+ default: ({ fileBacked }: { fileBacked?: boolean }) => (
+ <div data-testid="footer-actions">
+ {!fileBacked && <button data-testid="footer-export" type={'button'} />}
+ </div>
+ ),
}));
-// Record the params so a test can assert the topic lookup never fires — passing
-// `undefined` is what keeps `getOrCreateChatTopic` from hitting the network.
-const docChatTopicCalls = vi.hoisted(() => ({ current: [] as Record<string, unknown>[] }));
+// 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', () => ({
- // Mirror the real hook's `enabled` gate: with either id missing it never fetches,
- // so it can only ever return `topicId: undefined`.
- useDocumentChatTopic: (params: Record<string, unknown>) => {
- docChatTopicCalls.current.push(params);
- if (!params.agentId || !params.documentId)
- return { error: undefined, isLoading: false, topicId: undefined };
- return docChatTopicState.current;
- },
+ useDocumentChatTopic: () => ({ error: undefined, isLoading: false, topicId: undefined }),
}));
const mockChatState = vi.hoisted(() => ({
@@ -139,6 +132,7 @@ const mockDocumentState = vi.hoisted(() => ({
documents: {
'document-1': {},
},
+ internal_dispatchDocument: vi.fn(),
performSave: vi.fn(),
updateSkillFrontmatter: vi.fn(),
},
@@ -149,7 +143,7 @@ vi.mock('@/store/document', () => ({
}));
describe('DocumentBody', () => {
- /** @example A file-backed document previews its upload and retains document chat. */
+ /** @example A file-backed document previews its upload and keeps the portal actions. */
it('shows the original upload without mounting either editor', () => {
// ROOT CAUSE:
// File-backed documents used the empty content field as an editable document.
@@ -158,10 +152,25 @@ 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, while document chat stays available. */
+ /** @example Neither editor mounts. The portal footer (chat to edit / export)
+ replaces the inline conversation panel this PR's body used to render. */
expect(screen.queryByTestId('highlight-editor')).toBeNull();
expect(screen.queryByTestId('editor-canvas')).toBeNull();
- expect(screen.getByTestId('floating-chat-panel')).toBeTruthy();
+ 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(() => {
@@ -169,12 +178,7 @@ describe('DocumentBody', () => {
mockChatState.current.portalStack[0].agentDocumentId = 'agent-document-1';
mockDocumentMeta.current = { content: '', filename: 'doc.md' };
mockUpdateDocument.mockClear();
- docChatTopicCalls.current = [];
- docChatTopicState.current = {
- error: undefined,
- isLoading: false,
- topicId: 'doc-topic-1',
- };
+ mockDocumentState.current.internal_dispatchDocument.mockClear();
vi.useFakeTimers();
});
@@ -182,51 +186,41 @@ describe('DocumentBody', () => {
vi.useRealTimers();
});
- it('renders FloatingChatPanel once the doc topic resolves', () => {
+ it('renders the footer actions for an agent document', () => {
render(<DocumentBody />);
- expect(screen.getByTestId('floating-chat-panel')).toBeDefined();
+ expect(screen.getByTestId('footer-actions')).toBeDefined();
});
- it('holds the panel until the doc-anchored topic id resolves', () => {
- docChatTopicState.current = { error: undefined, isLoading: true, topicId: undefined };
+ 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('floating-chat-panel')).toBeNull();
+ expect(screen.queryByTestId('footer-actions')).toBeNull();
});
- it('does not render FloatingChatPanel without an active agent', () => {
+ it('does not render footer actions without an active agent', () => {
mockAgentState.current.activeAgentId = undefined;
render(<DocumentBody />);
- expect(screen.queryByTestId('floating-chat-panel')).toBeNull();
+ 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 `getOrCreateChatTopic`
- // would throw NOT_FOUND. The panel must not render *and* must not look up a topic.
- it('does not render FloatingChatPanel for a plain document with no agentDocumentId', () => {
+ // 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('floating-chat-panel')).toBeNull();
- expect(docChatTopicCalls.current.length).toBeGreaterThan(0);
- for (const call of docChatTopicCalls.current) {
- expect(call.agentId).toBeUndefined();
- expect(call.documentId).toBeUndefined();
- }
- });
-
- it('looks up the doc topic for an agent document', () => {
- render(<DocumentBody />);
-
- expect(docChatTopicCalls.current.at(-1)).toMatchObject({
- agentId: 'agent-1',
- documentId: 'document-1',
- });
+ expect(screen.queryByTestId('footer-actions')).toBeNull();
});
it('renders highlight editor for non-markdown files', () => {
@@ -312,4 +306,33 @@ describe('DocumentBody', () => {
expect(mockUpdateDocument).not.toHaveBeenCalled();
});
+
+ it('mirrors the live highlight buffer into the document store for export', () => {
+ mockDocumentMeta.current = { content: 'before', filename: 'config.json' };
+
+ render(<DocumentBody />);
+ const editor = screen.getByTestId('highlight-editor');
+
+ // Initial mount mirrors the persisted content into the store record
+ // (the mock record already exists, so this is an update).
+ expect(mockDocumentState.current.internal_dispatchDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'document-1',
+ type: 'updateDocument',
+ value: { content: 'before' },
+ }),
+ );
+
+ fireEvent.change(editor, { target: { value: 'after' } });
+
+ // The typed buffer becomes the store content immediately, so a concurrent
+ // Export downloads the text on screen instead of the last saved copy.
+ expect(mockDocumentState.current.internal_dispatchDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'document-1',
+ type: 'updateDocument',
+ value: { content: 'after' },
+ }),
+ );
+ });
});
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index 406c71f1d68..4f8009a2347 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -13,8 +13,6 @@ import CodeEditorPane from '@/components/CodeEditorPane';
import Loading from '@/components/Loading/CircleLoading';
import FileNotFound from '@/features/FileNotFound';
import { FileDocumentPreview } from '@/features/FileViewer/FileDocumentPreview';
-import FloatingChatPanel from '@/features/FloatingChatPanel';
-import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useClientDataSWR } from '@/libs/swr';
import { portalKeys } from '@/libs/swr/keys';
@@ -34,6 +32,7 @@ import {
useResolvedDocumentId,
} from './documentViewContext';
import EditorCanvas from './EditorCanvas';
+import FooterActions from './FooterActions';
import TodoList from './TodoList';
import { useHighlightSave } from './useHighlightSave';
@@ -230,6 +229,26 @@ const HighlightEditor = memo<HighlightEditorProps>(
updatedAt,
});
+ // Mirror the live buffer into the document store so consumers outside this
+ // component (the portal footer's Export) read the text currently on screen,
+ // not the last persisted SWR copy. `addDocument` upserts: the highlight
+ // editor path never goes through `useFetchDocument`, so the record may not
+ // exist yet. `lastSavedContent` stays at the persisted value so this mirror
+ // never marks the document dirty or triggers a save on its own.
+ const dispatchDocument = useDocumentStore((s) => s.internal_dispatchDocument);
+ const docExists = useDocumentStore((s) => !!s.documents[documentId]);
+ useEffect(() => {
+ dispatchDocument(
+ docExists
+ ? { id: documentId, type: 'updateDocument', value: { content: editingValue } }
+ : {
+ id: documentId,
+ type: 'addDocument',
+ value: { content: editingValue, lastSavedContent: content, sourceType: 'notebook' },
+ },
+ );
+ }, [content, dispatchDocument, docExists, documentId, editingValue]);
+
return (
<CodeEditorPane
showStatusBar
@@ -251,13 +270,9 @@ const DocumentBody = memo(() => {
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
- // `getOrCreateChatTopic` throws NOT_FOUND on those (no `agent_documents` row), so
- // the panel — and its topic lookup — must stay out of the way there.
- const panelEligible = !fullPage && !!activeAgentId && !!documentId && !!agentDocumentId;
- const { topicId: docChatTopicId } = useDocumentChatTopic({
- agentId: panelEligible ? activeAgentId : undefined,
- documentId: panelEligible ? documentId : undefined,
- });
+ // 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]
@@ -333,17 +348,18 @@ const DocumentBody = memo(() => {
)}
</div>
{renderMode.mode !== 'file' && <TodoList />}
- {/* The full-page route hosts its own panel through `AgentDocumentPage`, so
- the in-portal panel only renders for the compact view. Both call sites
- drive a doc-anchored chat topic via `useDocumentChatTopic`, so the panel
- renders once that topic id resolves. */}
- {panelEligible && docChatTopicId && (
- <FloatingChatPanel
- agentDocumentId={agentDocumentId}
+ {/* 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 ?? undefined}
- key={`${activeAgentId}:${docChatTopicId}:${documentId ?? 'none'}`}
- topicId={docChatTopicId}
+ documentId={documentId}
+ fileBacked={renderMode.mode === 'file'}
+ title={documentMeta?.title ?? documentMeta?.filename ?? undefined}
/>
)}
</Flexbox>
diff --git a/src/features/Portal/Document/CopyLinkMenuItem.tsx b/src/features/Portal/Document/CopyLinkMenuItem.tsx
new file mode 100644
index 00000000000..a7d82921136
--- /dev/null
+++ b/src/features/Portal/Document/CopyLinkMenuItem.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { Link2 } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
+
+/**
+ * Copy-link action for the document portal header. Hidden entirely when the
+ * viewer lacks the agent-documents binding that proves the active agent owns
+ * the document (plain notebook documents have no agent route to link to).
+ */
+const CopyLinkMenuItem = memo(() => {
+ const { t } = useTranslation(['chat', 'file', 'common']);
+ const { agentDocumentId, copyLink } = usePortalDocumentHeaderActions();
+
+ if (!agentDocumentId) return null;
+
+ const label = t('pageEditor.menu.copyLink', { ns: 'file' });
+
+ return <ActionIcon icon={Link2} size={'small'} title={label} onClick={() => void copyLink()} />;
+});
+
+CopyLinkMenuItem.displayName = 'PortalDocumentCopyLink';
+
+export default CopyLinkMenuItem;
diff --git a/src/features/Portal/Document/FooterActions.tsx b/src/features/Portal/Document/FooterActions.tsx
new file mode 100644
index 00000000000..5481220fa0a
--- /dev/null
+++ b/src/features/Portal/Document/FooterActions.tsx
@@ -0,0 +1,135 @@
+'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/Header.tsx b/src/features/Portal/Document/Header.tsx
index 9a4bd778897..a9358f12e52 100644
--- a/src/features/Portal/Document/Header.tsx
+++ b/src/features/Portal/Document/Header.tsx
@@ -1,32 +1,151 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { Skeleton, Text } from '@lobehub/ui/base-ui';
-import { cx } from 'antd-style';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
-import { oneLineEllipsis } from '@/styles';
-import { getDocumentRenderMode } from '@/utils/documentRenderMode';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { ActionIcon, type DropdownItem, DropdownMenu, Skeleton, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronRight, MoreHorizontal, Pencil } from 'lucide-react';
+import { type ChangeEvent, memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import AutoSaveHint from './AutoSaveHint';
-import { useResolvedDocumentId } from './documentViewContext';
+import CopyLinkMenuItem from './CopyLinkMenuItem';
+import { TITLE_MAX_LENGTH, usePortalDocumentTitle } from './usePortalDocumentHeader';
+
+const styles = createStaticStyles(({ css }) => ({
+ root: css`
+ flex: 1;
+ min-width: 0;
+ `,
+ separator: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ title: css`
+ cursor: text;
+ font-size: 13px;
+ font-weight: 600;
+ `,
+ titleInput: css`
+ flex: 1;
+
+ min-width: 0;
+ padding: 0;
+ border: none;
+
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ text-align: start;
+
+ background: transparent;
+
+ /* Keep a token-based focus ring for keyboard users; the native outline
+ is suppressed only in favor of this replacement. */
+ outline: none;
+
+ &:focus-visible {
+ border-radius: ${cssVar.borderRadiusSM};
+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBorder};
+ }
+ `,
+ crumbButton: css`
+ cursor: pointer;
+
+ flex-shrink: 0;
+
+ padding: 0;
+ border: none;
+
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: none;
-const Header = () => {
- const documentId = useResolvedDocumentId();
+ transition: color ${cssVar.motionDurationFast} ${cssVar.motionEaseInOut};
- const { data: document, isLoading } = useClientDataSWR(
- documentId ? portalKeys.documentHeader(documentId) : null,
- () => documentService.getDocumentById(documentId!),
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+
+ &:focus-visible {
+ border-radius: ${cssVar.borderRadiusSM};
+ outline: none;
+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBorder};
+ }
+ `,
+ crumbLabel: css`
+ flex-shrink: 0;
+ font-size: 13px;
+ `,
+}));
+
+interface HeaderProps {
+ /** Navigate to the documents index on breadcrumb click (agent route has one). */
+ onOpenDocumentsIndex?: () => void;
+}
+
+const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
+ const { t } = useTranslation(['chat', 'file', 'common']);
+ const {
+ cancelEdit,
+ commitEdit,
+ draft,
+ editing,
+ isLoading,
+ metaLocked,
+ setDraft,
+ startEdit,
+ syncIdleDraft,
+ titleFallback,
+ } = usePortalDocumentTitle();
+
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Follow the SWR source while idle; never clobber a draft mid-typing.
+ useEffect(() => {
+ syncIdleDraft(editing);
+ }, [editing, syncIdleDraft]);
+
+ const beginEdit = useCallback(() => {
+ startEdit();
+ // The input mounts during this render; focus once it exists.
+ requestAnimationFrame(() => inputRef.current?.focus());
+ }, [startEdit]);
+
+ const handleTitleKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ // blur commits; Escape restores first so the blur writes nothing new.
+ event.preventDefault();
+ inputRef.current?.blur();
+ } else if (event.key === 'Escape') {
+ // Cancel BEFORE blurring: blur fires `commitEdit` synchronously with
+ // the still-edited draft, so the cancel flag is what turns that commit
+ // into a no-op instead of persisting the cancelled title.
+ event.preventDefault();
+ cancelEdit();
+ inputRef.current?.blur();
+ }
+ },
+ [cancelEdit],
);
- const title = document?.filename || document?.title;
- const isReadonly = !!document && getDocumentRenderMode(document).mode !== 'editor';
+ const menuItems = useMemo<DropdownItem[]>(() => {
+ const items: DropdownItem[] = [];
+
+ if (!metaLocked) {
+ items.push({
+ icon: <Icon icon={Pencil} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: beginEdit,
+ });
+ }
- if (!documentId) return null;
+ return items;
+ }, [beginEdit, metaLocked, t]);
- if (isLoading || !title) {
+ if (isLoading) {
return (
<Flexbox
horizontal
@@ -44,19 +163,67 @@ const Header = () => {
}
return (
- <Flexbox horizontal align={'center'} flex={1} gap={12} justify={'space-between'} width={'100%'}>
- <Flexbox flex={1}>
- <Text className={cx(oneLineEllipsis)} type={'secondary'}>
- {title}
- </Text>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.root}
+ flex={1}
+ gap={6}
+ justify={'space-between'}
+ width={'100%'}
+ >
+ <Flexbox horizontal align={'center'} flex={1} gap={4} style={{ minWidth: 0 }}>
+ {/* Navigable crumb gets a real button (keyboard reachable); a plain
+ notebook document renders a noninteractive label with no affordance. */}
+ {onOpenDocumentsIndex ? (
+ <button className={styles.crumbButton} type={'button'} onClick={onOpenDocumentsIndex}>
+ {t('menu.allPages', { ns: 'file' })}
+ </button>
+ ) : (
+ <Text className={styles.crumbLabel} color={cssVar.colorTextQuaternary}>
+ {t('menu.allPages', { ns: 'file' })}
+ </Text>
+ )}
+ <Icon className={styles.separator} icon={ChevronRight} size={14} />
+ {editing ? (
+ <input
+ className={styles.titleInput}
+ maxLength={TITLE_MAX_LENGTH}
+ ref={inputRef}
+ value={draft}
+ onBlur={commitEdit}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft(event.target.value)}
+ onKeyDown={handleTitleKeyDown}
+ />
+ ) : (
+ <Text
+ className={styles.title}
+ ellipsis={{ tooltip: draft || titleFallback }}
+ style={{ minWidth: 0 }}
+ onClick={metaLocked ? undefined : beginEdit}
+ >
+ {draft || titleFallback}
+ </Text>
+ )}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {!metaLocked && <AutoSaveHint />}
+ <CopyLinkMenuItem />
+ {menuItems.length > 0 && (
+ <DropdownMenu
+ iconSpaceMode={'group'}
+ items={menuItems}
+ placement={'bottomRight'}
+ popupProps={{ style: { minWidth: 200 } }}
+ >
+ <ActionIcon icon={MoreHorizontal} size={'small'} />
+ </DropdownMenu>
+ )}
</Flexbox>
- {!isReadonly && (
- <Flexbox horizontal align={'center'} gap={8}>
- <AutoSaveHint />
- </Flexbox>
- )}
</Flexbox>
);
-};
+});
+
+Header.displayName = 'PortalDocumentHeader';
export default Header;
diff --git a/src/features/Portal/Document/PortalHeader.tsx b/src/features/Portal/Document/PortalHeader.tsx
index af5fb236e9b..38a983d9791 100644
--- a/src/features/Portal/Document/PortalHeader.tsx
+++ b/src/features/Portal/Document/PortalHeader.tsx
@@ -6,13 +6,16 @@ import { Maximize2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
+import {
+ buildAgentDocumentPath,
+ buildAgentDocumentsPath,
+} from '@/features/AgentDocumentPage/navigation';
import PortalChromeHeader from '@/features/Portal/components/Header';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
-import { useResolvedDocumentId } from './documentViewContext';
+import { useResolvedAgentDocumentId, useResolvedDocumentId } from './documentViewContext';
import DocumentTitle from './Header';
/**
@@ -41,8 +44,25 @@ const OpenAsPageAction = memo(() => {
);
});
-const PortalHeader = () => (
- <PortalChromeHeader rightExtra={<OpenAsPageAction />} title={<DocumentTitle />} />
-);
+const PortalHeader = () => {
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ // Discriminate on the resolved agent-documents binding, not `agentId` alone:
+ // a plain notebook document can be open while an agent happens to be active,
+ // and that agent's index is not this document's home.
+ const agentDocumentId = useResolvedAgentDocumentId();
+ const navigate = useWorkspaceAwareNavigate();
+
+ // Agent documents have a documents index to land on; plain notebook
+ // documents keep a non-navigating crumb label.
+ const openDocumentsIndex =
+ agentId && agentDocumentId ? () => navigate(buildAgentDocumentsPath(agentId)) : undefined;
+
+ return (
+ <PortalChromeHeader
+ rightExtra={<OpenAsPageAction />}
+ title={<DocumentTitle onOpenDocumentsIndex={openDocumentsIndex} />}
+ />
+ );
+};
export default PortalHeader;
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.test.ts b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
new file mode 100644
index 00000000000..74527c366f7
--- /dev/null
+++ b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
@@ -0,0 +1,374 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { usePortalDocumentHeaderActions, usePortalDocumentTitle } from './usePortalDocumentHeader';
+
+const mockDocumentMeta = vi.hoisted(() => ({
+ current: {
+ filename: '开营筹备清单.md',
+ title: '开营筹备清单',
+ } as {
+ content?: string;
+ fileType?: string | null;
+ filename?: string | null;
+ title?: string | null;
+ },
+}));
+
+const mockMutate = vi.hoisted(() => vi.fn());
+
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: () => ({
+ data: mockDocumentMeta.current,
+ isLoading: false,
+ mutate: mockMutate,
+ }),
+}));
+
+const mockUpdateDocument = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ getDocumentById: vi.fn(),
+ updateDocument: mockUpdateDocument,
+ },
+}));
+
+const mockInvalidate = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
+vi.mock('@/services/document/invalidation', () => ({
+ invalidateDocumentMutation: mockInvalidate,
+}));
+
+const mockAgentState = vi.hoisted(() => ({
+ current: {
+ activeAgentId: 'agent-1' as string | undefined,
+ },
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: any) => selector(mockAgentState.current),
+}));
+
+const mockChatState = vi.hoisted(() => ({
+ current: {
+ portalStack: [
+ {
+ agentDocumentId: 'agent-document-1' as string | undefined,
+ documentId: 'document-1',
+ type: 'document',
+ },
+ ],
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: any) => selector(mockChatState.current),
+}));
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+const clipboardWrite = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+
+ return {
+ ...actual,
+ toast: { error: toastError, success: toastSuccess },
+ };
+});
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => undefined,
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({
+ useAppOrigin: () => 'https://app.lobehub.com',
+}));
+
+describe('usePortalDocumentTitle', () => {
+ beforeEach(() => {
+ mockDocumentMeta.current = { filename: '开营筹备清单.md', title: '开营筹备清单' };
+ mockChatState.current.portalStack[0].agentDocumentId = 'agent-document-1';
+ mockUpdateDocument.mockClear();
+ mockMutate.mockClear();
+ mockInvalidate.mockClear();
+ toastError.mockClear();
+ });
+
+ it('exposes the saved title (title before filename) and unlocks editing', () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ expect(result.current.savedTitle).toBe('开营筹备清单');
+ expect(result.current.metaLocked).toBe(false);
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('commits a renamed title through the document service', async () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('开营筹备清单 V2'));
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+
+ expect(mockUpdateDocument).toHaveBeenCalledWith({
+ id: 'document-1',
+ title: '开营筹备清单 V2',
+ });
+ expect(result.current.editing).toBe(false);
+ });
+
+ it('rolls the optimistic title back when the write fails', async () => {
+ mockUpdateDocument.mockRejectedValueOnce(new Error('network'));
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('开营筹备清单 V2'));
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+
+ expect(toastError).toHaveBeenCalled();
+ expect(result.current.draft).toBe('开营筹备清单');
+ });
+
+ it('serializes overlapping saves: a stale rejected rename cannot roll back a newer one', async () => {
+ let rejectFirst!: (e: Error) => void;
+ mockUpdateDocument
+ .mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectFirst = reject;
+ }),
+ )
+ .mockResolvedValueOnce(undefined);
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ // First (slow) rename — its promise never resolves until the stale reject
+ // below, so fire it without awaiting.
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('重命名一'));
+ void result.current.commitEdit();
+
+ // A newer rename lands first (fast server response).
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('重命名二'));
+ const secondCommit = result.current.commitEdit();
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // The server calls are queued, not concurrent: while the first rename is
+ // in flight only its write has reached the service.
+ expect(mockUpdateDocument).toHaveBeenCalledTimes(1);
+ expect(mockUpdateDocument).toHaveBeenCalledWith({ id: 'document-1', title: '重命名一' });
+
+ // The older request now REJECTS — it must not touch draft or cache,
+ // because a newer save already claimed the latest ticket.
+ await act(async () => {
+ rejectFirst(new Error('late failure'));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ });
+ await act(async () => {
+ await secondCommit;
+ });
+
+ expect(result.current.draft).toBe('重命名二');
+ expect(toastError).not.toHaveBeenCalled();
+ });
+
+ it('queues the second rename behind the in-flight one (server write order)', async () => {
+ let releaseFirst!: (v: unknown) => void;
+ mockUpdateDocument
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ releaseFirst = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(undefined);
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ // First rename — held in flight by the server mock.
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('重命名一'));
+ void result.current.commitEdit();
+
+ // Second rename submitted while the first is pending.
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('重命名二'));
+ const secondCommit = result.current.commitEdit();
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // Still queued — only the first write has reached the service.
+ expect(mockUpdateDocument).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ releaseFirst(undefined);
+ await secondCommit;
+ });
+
+ // The second write fires only after the first settles, in submit order.
+ expect(mockUpdateDocument).toHaveBeenCalledTimes(2);
+ expect(mockUpdateDocument).toHaveBeenLastCalledWith({ id: 'document-1', title: '重命名二' });
+ expect(result.current.draft).toBe('重命名二');
+ });
+
+ it('revalidates the agent-document list after a successful rename', async () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('开营筹备清单 V2'));
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+
+ expect(mockInvalidate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', documentId: 'document-1' }),
+ );
+ });
+
+ it('does not persist a cancelled title when Escape triggers the blur commit', async () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('被取消的名字'));
+
+ // Escape path: cancelEdit runs first, then the input blur fires
+ // `commitEdit` synchronously with the still-edited draft.
+ act(() => result.current.cancelEdit());
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+ expect(result.current.draft).toBe('开营筹备清单');
+ expect(result.current.editing).toBe(false);
+ });
+
+ it('re-arms the cancel flag so the next real commit still writes', async () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ // Cancel one edit...
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('被取消的名字'));
+ act(() => result.current.cancelEdit());
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+
+ // ...then commit a fresh rename normally.
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('开营筹备清单 V2'));
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+
+ expect(mockUpdateDocument).toHaveBeenCalledWith({
+ id: 'document-1',
+ title: '开营筹备清单 V2',
+ });
+ });
+
+ it('clears a dangling cancel when a new edit session starts', async () => {
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ // Cancel without the follow-up blur commit (e.g. input unmounted first).
+ act(() => result.current.startEdit());
+ act(() => result.current.cancelEdit());
+
+ act(() => result.current.startEdit());
+ act(() => result.current.setDraft('开营筹备清单 V2'));
+ await act(async () => {
+ await result.current.commitEdit();
+ });
+
+ expect(mockUpdateDocument).toHaveBeenCalledWith({
+ id: 'document-1',
+ title: '开营筹备清单 V2',
+ });
+ });
+
+ it('locks meta for a managed skill index (rename must not rewrite SKILL.md)', () => {
+ mockDocumentMeta.current = {
+ content: '---\nname: my-skill\n---\nbody',
+ fileType: 'skills/index',
+ filename: 'SKILL.md',
+ title: 'SKILL.md',
+ };
+
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ expect(result.current.metaLocked).toBe(true);
+ act(() => result.current.startEdit());
+ expect(result.current.editing).toBe(false);
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+ });
+
+ it('exposes the editor (not loading) for a loaded empty-title document', () => {
+ mockDocumentMeta.current = { filename: '', title: '' };
+
+ const { result } = renderHook(() => usePortalDocumentTitle());
+
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.savedTitle).toBe('');
+ act(() => result.current.startEdit());
+ expect(result.current.editing).toBe(true);
+ });
+});
+
+describe('usePortalDocumentHeaderActions', () => {
+ beforeEach(() => {
+ mockChatState.current.portalStack[0].agentDocumentId = 'agent-document-1';
+ mockAgentState.current.activeAgentId = 'agent-1';
+ clipboardWrite.mockClear();
+ toastSuccess.mockClear();
+ // jsdom exposes `navigator.clipboard` as getter-only; swap it per test.
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: clipboardWrite },
+ });
+ });
+
+ it('copies the agent-document URL when the binding proves ownership', async () => {
+ const { result } = renderHook(() => usePortalDocumentHeaderActions());
+
+ await act(async () => {
+ await result.current.copyLink();
+ });
+
+ expect(clipboardWrite).toHaveBeenCalledWith(
+ 'https://app.lobehub.com/agent/agent-1/docs/document-1',
+ );
+ expect(toastSuccess).toHaveBeenCalled();
+ });
+
+ it('refuses to copy a link for a plain document with no agent binding', async () => {
+ mockChatState.current.portalStack[0].agentDocumentId = undefined;
+
+ const { result } = renderHook(() => usePortalDocumentHeaderActions());
+
+ await act(async () => {
+ await result.current.copyLink();
+ });
+
+ // No URL was composed (no-op), and no success toast fired.
+ expect(clipboardWrite).not.toHaveBeenCalled();
+ expect(toastSuccess).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the resolved binding for menu gating', () => {
+ const { result } = renderHook(() => usePortalDocumentHeaderActions());
+
+ expect(result.current.agentDocumentId).toBe('agent-document-1');
+ expect(result.current.agentId).toBe('agent-1');
+ });
+});
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.ts b/src/features/Portal/Document/usePortalDocumentHeader.ts
new file mode 100644
index 00000000000..f26468d83cd
--- /dev/null
+++ b/src/features/Portal/Document/usePortalDocumentHeader.ts
@@ -0,0 +1,200 @@
+'use client';
+
+import { buildAgentDocumentUrl } from '@lobechat/builtin-tool-agent-documents';
+import { toast } from '@lobehub/ui/base-ui';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { useSingleton } from '@/hooks/useSingleton';
+import { useClientDataSWR } from '@/libs/swr';
+import { portalKeys } from '@/libs/swr/keys';
+import { documentService } from '@/services/document';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
+import { useAgentStore } from '@/store/agent';
+import { getDocumentRenderMode } from '@/utils/documentRenderMode';
+import { isSkillMarkdownDocument } from '@/utils/skillMarkdown';
+
+import { useResolvedAgentDocumentId, useResolvedDocumentId } from './documentViewContext';
+
+export const TITLE_MAX_LENGTH = 100;
+
+/**
+ * Title state + actions for the portal document header: the saved title
+ * (title › filename), the loading flag, and an edit/commit cycle that
+ * persists through the document service.
+ *
+ * `syncIdleDraft` is called from a `useEffect` keyed on the editing flag —
+ * the hook stays headless; the component decides when to resync.
+ */
+export const usePortalDocumentTitle = () => {
+ const { t } = useTranslation(['chat', 'common']);
+ const documentId = useResolvedDocumentId();
+ const agentId = useAgentStore((s) => s.activeAgentId);
+
+ const {
+ data: document,
+ isLoading,
+ mutate: mutateDocument,
+ } = useClientDataSWR(documentId ? portalKeys.documentHeader(documentId) : null, () =>
+ documentService.getDocumentById(documentId!),
+ );
+
+ const savedTitle = useMemo(
+ () => document?.title || document?.filename || '',
+ [document?.title, document?.filename],
+ );
+ // Anything the portal renders without the rich editor (highlight view,
+ // file preview) must not be renameable here — matching the full-page
+ // editor's `metaReadOnly` gate (#19760).
+ const isReadonly = !!document && getDocumentRenderMode(document).mode !== 'editor';
+ // A managed skill's `SKILL.md` index carries its identity in the filename —
+ // a portal rename would push the new title into both `title` and `filename`
+ // and desync the bundle. The full-page editor locks meta for the same reason
+ // (see AgentDocumentPage's `metaReadOnly`); the rename API rejects it anyway.
+ const isSkillIndex = !!document && isSkillMarkdownDocument(document);
+ const metaLocked = isReadonly || isSkillIndex;
+
+ const [draft, setDraft] = useState(savedTitle);
+ const [editing, setEditing] = useState(false);
+ // Serializes title writes end-to-end. Two layers:
+ // 1. `saveChain` queues the SERVER calls — updateDocument mutations run
+ // in submit order, so a slow first request can never land after (and
+ // overwrite) a newer rename.
+ // 2. `saveTicketRef` gates the CLIENT-side settlement — only the newest
+ // commit may touch the draft/SWR cache, so a rejected older request
+ // cannot roll back a newer intent.
+ const saveChain = useSingleton(() => ({ current: Promise.resolve() as Promise<unknown> }));
+ const saveTicketRef = useRef(0);
+
+ // Follow the SWR source while idle; never clobber a draft mid-typing.
+ const syncIdleDraft = useCallback(
+ (isEditing: boolean) => {
+ if (!isEditing) setDraft(savedTitle);
+ },
+ [savedTitle],
+ );
+
+ // Marks the in-progress edit as cancelled. Escape calls this BEFORE blurring
+ // the input: the blur that follows still fires `commitEdit`, but the flag
+ // makes that commit a no-op restore instead of persisting the edited draft
+ // the user just threw away.
+ const cancelEditRef = useRef(false);
+
+ const startEdit = useCallback(() => {
+ if (metaLocked) return;
+ // A fresh edit session never inherits a cancel whose blur commit never fired.
+ cancelEditRef.current = false;
+ setDraft(savedTitle);
+ setEditing(true);
+ }, [metaLocked, savedTitle]);
+
+ const cancelEdit = useCallback(() => {
+ cancelEditRef.current = true;
+ setDraft(savedTitle);
+ setEditing(false);
+ }, [savedTitle]);
+
+ const commitEdit = useCallback(async () => {
+ // A cancelled edit restores, it never writes — even though the blur event
+ // hands us the still-edited draft.
+ if (cancelEditRef.current) {
+ cancelEditRef.current = false;
+ return;
+ }
+ const nextTitle = draft.trim();
+ // Empty or unchanged drafts fall back to the saved title — no write.
+ if (!nextTitle || nextTitle === savedTitle || !documentId) {
+ setDraft(savedTitle);
+ setEditing(false);
+ return;
+ }
+
+ // Claim the newest save; only this ticket may settle the client state.
+ const ticket = ++saveTicketRef.current;
+ setEditing(false);
+ setDraft(nextTitle);
+
+ // Optimistic update, then reconcile with the server response.
+ mutateDocument((prev) => (prev ? { ...prev, title: nextTitle } : prev), { revalidate: false });
+
+ // Queue the server write behind any in-flight rename so the server sees
+ // the titles in the order the user submitted them — a slow first request
+ // can no longer land last and overwrite the newer title.
+ const write = saveChain.current
+ .catch(() => undefined)
+ .then(() =>
+ documentService.updateDocument({ id: documentId, title: nextTitle }).then((result) => {
+ if (ticket !== saveTicketRef.current) return result;
+ // Revalidate the caches other surfaces read titles from
+ // (working-sidebar tree, standalone document page read
+ // `agent:documentsList`), mirroring the full-page editor's
+ // post-rename list refresh.
+ void invalidateDocumentMutation({ agentId: agentId ?? undefined, documentId });
+ return result;
+ }),
+ );
+ saveChain.current = write;
+ try {
+ await write;
+ } catch {
+ if (ticket !== saveTicketRef.current) return;
+ toast.error(t('operationFailed', { ns: 'common' }));
+ setDraft(savedTitle);
+ mutateDocument((prev) => (prev ? { ...prev, title: savedTitle } : prev), {
+ revalidate: false,
+ });
+ }
+ }, [agentId, draft, documentId, mutateDocument, savedTitle, t]);
+
+ return {
+ cancelEdit,
+ commitEdit,
+ draft,
+ editing,
+ isLoading,
+ metaLocked,
+ savedTitle,
+ setDraft,
+ startEdit,
+ syncIdleDraft,
+ titleFallback: t('agentDocument.portal.titlePlaceholder', { ns: 'chat' }),
+ };
+};
+
+/**
+ * Header menu entries: rename (hidden when meta is locked) and copy link
+ * (only when the portal viewer carries the agent-documents binding that
+ * proves the active agent owns the document).
+ */
+export const usePortalDocumentHeaderActions = () => {
+ const { t } = useTranslation(['chat', 'file', 'common']);
+ const documentId = useResolvedDocumentId();
+ // The doc-anchored chat topic binds (agentId, documentId); the standalone
+ // route for "copy link" needs the owning agent id, which equals the store's
+ // activeAgentId inside this portal (see Body's panelEligible gate). The
+ // resolved agent-documents binding is the ownership proof: a plain notebook
+ // document opened beside an active agent must not produce a copy-link for an
+ // agent route that doesn't own it.
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ const agentDocumentId = useResolvedAgentDocumentId();
+ const appOrigin = useAppOrigin();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+
+ const { startEdit } = usePortalDocumentTitle();
+
+ const copyLink = useCallback(async () => {
+ // The binding is the runtime guard too: even a stale callback handed to a
+ // menu must never compose an agent-document URL for an unowned document.
+ if (!documentId || !agentId || !agentDocumentId) return;
+ const url = buildAgentDocumentUrl(appOrigin, agentId, documentId, {
+ workspaceSlug: activeWorkspaceSlug,
+ });
+ if (!url) return;
+ await navigator.clipboard.writeText(url);
+ toast.success(t('agentDocument.linkCopied', { ns: 'chat' }));
+ }, [activeWorkspaceSlug, agentDocumentId, agentId, appOrigin, documentId, t]);
+
+ return { agentDocumentId, agentId, copyLink, documentId, startEdit, t };
+};