🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(conversation): print only the transcript of the main conversation (#21571)
Arvin Xu434561928902
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.test.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.test.tsxnew file mode 100644index 00000000000..ab471153b06--- /dev/null+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.test.tsx@@ -0,0 +1,62 @@+import { render } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { PrintModeContext } from '@/features/Conversation/components/PrintModeContext';+import { createStore, Provider } from '@/features/Conversation/store';++import MessageContent from './index';++const openEditorModal = vi.fn(() => ({ close: vi.fn(), update: vi.fn() }) as any);++vi.mock('@/features/EditorModal', () => ({+ openEditorModal: (...args: any[]) => openEditorModal(...(args as [])),+}));+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++/** @example Printing must not open a second editor against the real one's store flag. */+describe('MessageContent editing lifecycle', () => {+ afterEach(() => {+ vi.clearAllMocks();+ });++ const setup = (printing: boolean) => {+ const store = createStore({+ context: { agentId: 'agent', topicId: 'topic', threadId: null },+ messages: [+ { id: 'm1', content: 'hello', role: 'user', createdAt: 0, updatedAt: 0 } as any,+ ],+ });+ const toggleMessageEditing = vi.spyOn(store.getState(), 'toggleMessageEditing');+ const wrapper = ({ children }: PropsWithChildren) => (+ <Provider createStore={() => store}>+ {printing ? <PrintModeContext value>{children}</PrintModeContext> : children}+ </Provider>+ );+ return { ...render(<MessageContent editing id={'m1'} message={'hello'} />, { wrapper }), toggleMessageEditing };+ };++ /** @example The screen row opens its editor and closes it on unmount. */+ it('opens the editor for the real row', () => {+ const { unmount } = setup(false);++ expect(openEditorModal).toHaveBeenCalledTimes(1);++ unmount();+ expect(openEditorModal.mock.results[0]!.value.close).toHaveBeenCalledTimes(1);+ });++ /** @example The print copy stays inert: no editor, so no draft-losing close on afterprint. */+ it('does not touch the editor lifecycle in the print copy', () => {+ const { unmount, toggleMessageEditing } = setup(true);++ expect(openEditorModal).not.toHaveBeenCalled();++ unmount();+ expect(openEditorModal).not.toHaveBeenCalled();+ expect(toggleMessageEditing).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsxindex 03a9588c7ba..c9c7e437440 100644--- a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx@@ -3,6 +3,7 @@ import { type ReactNode } from 'react';import { memo, useCallback, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';+import { usePrintMode } from '@/features/Conversation/components/PrintModeContext';import { dataSelectors, useConversationStore } from '@/features/Conversation/store';import { openEditorModal } from '@/features/EditorModal';import { usePermission } from '@/hooks/usePermission';@@ -57,6 +58,7 @@ const MessageContent = memo<MessageContentProps>(variant,}) => {const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);+ const printMode = usePrintMode();const editorData = useConversationStore((s) => dataSelectors.getDisplayMessageById(id)(s)?.editorData,@@ -97,10 +99,12 @@ const MessageContent = memo<MessageContentProps>(});useEffect(() => {- if (!editing) return;+ // The print copy renders this component too; opening a second editor for it+ // would close the real one (and drop its draft) when printing ends.+ if (!editing || printMode) return;const instance = openEditorRef.current!();return () => instance.close();- }, [editing]);+ }, [editing, printMode]);return (<Flexboxdiff --git a/src/features/Conversation/ChatList/components/PrintTranscript.tsx b/src/features/Conversation/ChatList/components/PrintTranscript.tsxnew file mode 100644index 00000000000..29c29f6b631--- /dev/null+++ b/src/features/Conversation/ChatList/components/PrintTranscript.tsx@@ -0,0 +1,47 @@+'use client';++import type { ReactNode } from 'react';+import { createPortal } from 'react-dom';++import WideScreenContainer from '../../../WideScreenContainer';+import { PrintModeContext } from '../../components/PrintModeContext';+import { CONVERSATION_PRINT_ROOT_CLASS } from '../constants';+import { useIsPrinting } from '../hooks/useIsPrinting';++interface PrintTranscriptProps {+ dataSource: string[];+ itemContent: (index: number, data: string) => ReactNode;+}++/**+ * Print-only copy of the loaded transcript.+ *+ * The virtual list mounts just the rows near the viewport inside a fixed-height+ * scroller, so printing the page captured one screen of messages framed by the+ * app chrome. While the browser prints, every loaded row renders here in normal+ * flow on `document.body`, and the global print styles hide the rest of the+ * app. It exists only between `beforeprint` and `afterprint`, so screens never+ * pay for it.+ */+const PrintTranscript = ({ dataSource, itemContent }: PrintTranscriptProps) => {+ const printing = useIsPrinting();++ if (!printing) return null;++ // Paper is white: re-scope the theme variables to light even in dark mode.+ return createPortal(+ <div className={CONVERSATION_PRINT_ROOT_CLASS} data-theme={'light'}>+ {/* Rows are the live renderer, so mark them static: no editor lifecycle may start here. */}+ <PrintModeContext value>+ {dataSource.map((id, index) => (+ <WideScreenContainer fullWidth key={id}>+ {itemContent(index, id)}+ </WideScreenContainer>+ ))}+ </PrintModeContext>+ </div>,+ document.body,+ );+};++export default PrintTranscript;diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsxindex 30f7f81552c..ef78ce15bd4 100644--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx@@ -44,6 +44,7 @@ import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';import BackBottom from './BackBottom';import HistoryPageError from './HistoryPageError';import HistoryPageSkeleton from './HistoryPageSkeleton';+import PrintTranscript from './PrintTranscript';const DebugInspector = lazy(() => import('./AutoScroll/DebugInspector'));@@ -69,6 +70,8 @@ interface VirtualizedListProps {itemContent: (index: number, data: string) => ReactNode;messageDeepLink?: ResolvedMessageDeepLink;paging?: 'backward' | 'forward';+ /** Print the loaded transcript, without the app chrome, when the page prints. */+ printable?: boolean;}/**@@ -85,6 +88,7 @@ const VirtualizedList = memo<VirtualizedListProps>(itemContent,messageDeepLink,paging,+ printable,}) => {const isForward = paging === 'forward';const virtuaRef = useRef<VListHandle>(null);@@ -584,6 +588,7 @@ const VirtualizedList = memo<VirtualizedListProps>(onScrollToBottom={handleBackBottom}/></WideScreenContainer>+ {printable && <PrintTranscript dataSource={dataSource} itemContent={itemContent} />}</div>);},diff --git a/src/features/Conversation/ChatList/constants.ts b/src/features/Conversation/ChatList/constants.tsindex f3531752dea..21a2a1975ee 100644--- a/src/features/Conversation/ChatList/constants.ts+++ b/src/features/Conversation/ChatList/constants.ts@@ -1,2 +1,9 @@/** Class of the virtual list that renders a conversation's rows. */export const VLIST_CLASS_NAME = 'conversation-vlist';++/**+ * Class of the print-only transcript mounted on `document.body` while the+ * browser prints. Global print styles hide every other body child when it is+ * present, so the paper carries the messages without the app chrome.+ */+export const CONVERSATION_PRINT_ROOT_CLASS = 'conversation-print-root';diff --git a/src/features/Conversation/ChatList/hooks/useIsPrinting.test.ts b/src/features/Conversation/ChatList/hooks/useIsPrinting.test.tsnew file mode 100644index 00000000000..e27a6de0dea--- /dev/null+++ b/src/features/Conversation/ChatList/hooks/useIsPrinting.test.ts@@ -0,0 +1,42 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useIsPrinting } from './useIsPrinting';++describe('useIsPrinting', () => {+ it('is false until the page prints', () => {+ const { result } = renderHook(() => useIsPrinting());++ expect(result.current).toBe(false);+ });++ it('turns true synchronously inside beforeprint', () => {+ const { result } = renderHook(() => useIsPrinting());++ // No act(): the browser lays out the printed pages right after the event,+ // so the update must already be committed when dispatchEvent returns.+ window.dispatchEvent(new Event('beforeprint'));++ expect(result.current).toBe(true);+ });++ it('turns false again after printing', () => {+ const { result } = renderHook(() => useIsPrinting());++ window.dispatchEvent(new Event('beforeprint'));+ act(() => {+ window.dispatchEvent(new Event('afterprint'));+ });++ expect(result.current).toBe(false);+ });++ it('stops listening once unmounted', () => {+ const { result, unmount } = renderHook(() => useIsPrinting());+ unmount();++ window.dispatchEvent(new Event('beforeprint'));++ expect(result.current).toBe(false);+ });+});diff --git a/src/features/Conversation/ChatList/hooks/useIsPrinting.ts b/src/features/Conversation/ChatList/hooks/useIsPrinting.tsnew file mode 100644index 00000000000..618dcd2c9db--- /dev/null+++ b/src/features/Conversation/ChatList/hooks/useIsPrinting.ts@@ -0,0 +1,28 @@+import { useEffect, useState } from 'react';+import { flushSync } from 'react-dom';++/**+ * Whether the browser is printing the page, from `beforeprint` to `afterprint`.+ *+ * The browser lays out the printed pages right after `beforeprint` returns, so+ * the update is flushed synchronously: anything rendered from this flag is in+ * the DOM by then, not one frame too late.+ */+export const useIsPrinting = () => {+ const [printing, setPrinting] = useState(false);++ useEffect(() => {+ const handleBeforePrint = () => flushSync(() => setPrinting(true));+ const handleAfterPrint = () => setPrinting(false);++ window.addEventListener('beforeprint', handleBeforePrint);+ window.addEventListener('afterprint', handleAfterPrint);++ return () => {+ window.removeEventListener('beforeprint', handleBeforePrint);+ window.removeEventListener('afterprint', handleAfterPrint);+ };+ }, []);++ return printing;+};diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 5c6926cff39..bb9f2f6afde 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -114,6 +114,12 @@ export interface ChatListProps {* to the newest-first read.*/onForwardPagingUnsupported?: () => void;+ /**+ * Print the loaded transcript, without the app chrome, when the page prints.+ * Opt in on the page's main conversation only: a side panel (thread portal,+ * copilot, floating chat) must not replace what its host page prints.+ */+ printable?: boolean;/*** Force showing welcome component even when messages exist*/@@ -141,6 +147,7 @@ const ChatList = memo<ChatListProps>(itemContent,messageDeepLink,onForwardPagingUnsupported,+ printable,showWelcome,}) => {// The chat store owns the transcript; this view keeps its sync mounted.@@ -383,6 +390,7 @@ const ChatList = memo<ChatListProps>(itemContent={itemContent ?? defaultItemContent}messageDeepLink={resolvedMessageDeepLink}paging={paging}+ printable={printable}/></BackgroundRunHintContext></MessageActionProvider>diff --git a/src/features/Conversation/components/PrintModeContext.ts b/src/features/Conversation/components/PrintModeContext.tsnew file mode 100644index 00000000000..2a0e4f82ff5--- /dev/null+++ b/src/features/Conversation/components/PrintModeContext.ts@@ -0,0 +1,15 @@+import { createContext, useContext } from 'react';++/**+ * Whether the current subtree is the static copy that only exists for browser+ * printing (`PrintTranscript`).+ *+ * The print copy reuses the live row renderer so paper looks like the screen,+ * and it is mounted only between `beforeprint` and `afterprint`. Interactive+ * lifecycles must stay shut inside it: a second message-editing modal opens+ * against the same store flag as the real editor, and closing it when the copy+ * unmounts also closes the user's editor and discards the unsaved draft.+ */+export const PrintModeContext = createContext(false);++export const usePrintMode = () => useContext(PrintModeContext);diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex 94247f89a94..5837bfad861 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -160,6 +160,7 @@ const Conversation = memo(() => {<TopicMigrationPlaceholder agentId={context.agentId} topicId={context.topicId} />) : (<ChatList+ printableheaderSlot={<div aria-hidden className={styles.floatingHeaderSpacer} />}messageDeepLink={messageDeepLink}welcome={<AgentHome />}diff --git a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx b/src/routes/(main)/group/features/Conversation/ConversationArea.tsxindex 07bebd195e5..83718ba77b2 100644--- a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx@@ -75,7 +75,7 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {{topicPending ? (<TopicMigrationPlaceholder groupId={context.groupId} topicId={context.topicId} />) : (- <ChatList messageDeepLink={messageDeepLink} welcome={<WelcomeChatItem />} />+ <ChatList printable messageDeepLink={messageDeepLink} welcome={<WelcomeChatItem />} />)}</Flexbox>{topicPending ? (diff --git a/src/styles/global.ts b/src/styles/global.tsindex 2b679cb64bc..89c68254c1f 100644--- a/src/styles/global.ts+++ b/src/styles/global.ts@@ -1,6 +1,7 @@import type { LobeTheme } from '@lobehub/ui';import { CLASSNAMES, css } from '@lobehub/ui';+import { CONVERSATION_PRINT_ROOT_CLASS } from '@/features/Conversation/ChatList/constants';import {MAC_PANEL_BG_VAR,MAC_WINDOW_FULLSCREEN_SELECTOR,@@ -98,6 +99,34 @@ const genGlobalStyle = ({ token }: { prefixCls: string; token: LobeTheme }) => c) {opacity: 1;}++ /* Printing a conversation: keep only its transcript, no sidebars, headers,+ composer or docks, and let the document grow past one viewport. */+ @media screen {+ .${CONVERSATION_PRINT_ROOT_CLASS} {+ display: none;+ }+ }++ @media print {+ html:has(> body > .${CONVERSATION_PRINT_ROOT_CLASS}),+ body:has(> .${CONVERSATION_PRINT_ROOT_CLASS}) {+ overflow: visible;++ height: auto;+ min-height: 0;+ max-height: none;++ /* Paper is white. next-themes writes a dark color-scheme inline on html,+ which paints the page canvas dark, and the dark theme paints body. */+ color-scheme: light !important;+ background: none !important;+ }++ body:has(> .${CONVERSATION_PRINT_ROOT_CLASS}) > :not(.${CONVERSATION_PRINT_ROOT_CLASS}) {+ display: none !important;+ }+ }`;export default genGlobalStyle;