import { Component, Fragment, memo, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
import type { AssistantBlock, UserMessageNode } from '@deepseek-ai/dsh-client-ui-conversation/client';
import { JsonBlock, MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives';
import { ComposerFillContext, McpAppFrame } from './McpAppFrame.js';
import { formatMessageClock } from './message-chrome.js';
import { markdownLabels, truncatedJsonLabel } from './primitive-labels.js';
import type { BlockRenderProps, ReaderBlockOwner } from './types.js';
import { useStreamingText } from './streaming.js';
import { MotionMarkdown, MotionPlainText } from './word-motion.js';
import { activeTextTransform, displayStreaming, originalAnswerText, readerBlockOwner, useDisplayText } from './text-transform.js';
import type { TextTransformRegistry } from './text-transform.js';
import css from './Reader.module.css';
const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
export class BlockBoundary extends Component<{ children: ReactNode }, { failed: boolean; detail: string }> {
state = { failed: false, detail: '' };
// Temporary diagnostic: surface the reason inline so a recurrence is reportable
// without a console. Remove once the reported block crash is identified.
static getDerivedStateFromError(error: unknown) {
const err = error as { message?: unknown } | undefined;
return { failed: true, detail: String(err?.message ?? error).slice(0, 160) };
}
render() {
return this.state.failed
?
此内容暂时无法在阅读页显示;原对话中的记录未受影响。({this.state.detail})
: this.props.children;
}
}
export const ImageBlock = memo(function ImageBlock({ attachment, loadImage }: {
attachment: ImageAttachmentRef; loadImage: BlockRenderProps['loadImage'];
}) {
const [attempt, setAttempt] = useState(0);
const [url, setUrl] = useState(null);
const [error, setError] = useState(false);
const [decoded, setDecoded] = useState(false);
const dialog = useRef(null);
const opener = useRef(null);
useEffect(() => {
let active = true;
let owned: string | null = null;
const timeout = setTimeout(() => { if (active) { setError(true); active = false; } }, 20000);
setError(false); setDecoded(false); setUrl(null);
void loadImage(attachment).then(result => {
if (!active) return;
clearTimeout(timeout);
if (!IMAGE_TYPES.has(result.mediaType)) throw new Error('Unsupported image media type');
const bytes = Uint8Array.from(result.data);
owned = URL.createObjectURL(new Blob([bytes.buffer], { type: result.mediaType }));
setUrl(owned);
}).catch(() => { clearTimeout(timeout); if (active) setError(true); });
return () => { active = false; clearTimeout(timeout); if (owned) URL.revokeObjectURL(owned); };
}, [attachment.attachmentId, attempt, loadImage]);
const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4;
const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3;
return
{!error && url &&
}
{(!decoded || error) &&
{error ? '图片未能加载' : '正在加载图片'}
{error && }
}
{attachment.name && {attachment.name}}
;
});
export function contentBlocks(content: UserMessageNode['content']): AssistantBlock[] {
return content.map(block => {
if (block.type === 'text') return { kind: 'text', text: block.text };
if (block.type === 'image') return { kind: 'image', attachment: block.attachment };
return { kind: 'other', block };
});
}
type TextPresentation = { startedAt?: number; interrupted?: boolean; liveText?: boolean };
type MarkdownStreamProps = {
text: string;
streaming: boolean;
holdFormatting: boolean;
kind?: 'body' | 'reasoning';
fileMentions?: BlockRenderProps['fileMentions'];
transformed?: boolean;
} & TextPresentation;
function MarkdownStream({ text, streaming, holdFormatting, startedAt, interrupted = false, liveText = false, kind = 'body', fileMentions, transformed = false }: MarkdownStreamProps) {
const root = useRef(null);
const presentation = useStreamingText(text, streaming, { startedAt, interrupted: interrupted || !liveText, selected: holdFormatting });
// Native Markdown changes block keys for its full final parse. Keep the last
// committed mode while this answer is selected, then finish formatting on
// deselection. Business status and the source text still update normally.
const committedMode = useRef(streaming);
const effectiveMode = holdFormatting ? committedMode.current : presentation.formatStreaming;
useLayoutEffect(() => { committedMode.current = effectiveMode; }, [effectiveMode]);
return
;
}
function TransformedMarkdown({ registry, blockKey, source, text, streaming, ...props }: MarkdownStreamProps & { registry: TextTransformRegistry; blockKey: string; source: ReaderBlockOwner['source'] }) {
const shown = useDisplayText(registry, { text, streaming, blockKey, kind: 'body', source });
return ;
}
function ReadingMarkdown({ blockKey, source, ...props }: MarkdownStreamProps & { blockKey: string; source: ReaderBlockOwner['source'] }) {
const registry = activeTextTransform();
if (registry?.has('body')) return ;
return ;
}
type ReasoningStreamProps = { blockKey: string; text: string; streaming: boolean; holdFormatting: boolean; transformed?: boolean } & TextPresentation;
function ReasoningStream({ blockKey, text, streaming, holdFormatting, startedAt, interrupted = false, liveText = false, transformed = false }: ReasoningStreamProps) {
const presentation = useStreamingText(text, streaming, { startedAt, interrupted: interrupted || !liveText, selected: holdFormatting });
return
;
}
function TransformedReasoning({ registry, blockKey, source, text, streaming, ...props }: ReasoningStreamProps & { registry: TextTransformRegistry; blockKey: string; source: ReaderBlockOwner['source'] }) {
const shown = useDisplayText(registry, { text, streaming, blockKey, kind: 'reasoning', source });
return ;
}
function ReadingReasoning({ blockKey, source, ...props }: ReasoningStreamProps & { blockKey: string; source: ReaderBlockOwner['source'] }) {
const registry = activeTextTransform();
if (registry?.has('reasoning')) return ;
return ;
}
function fallback(block: AssistantBlock, streaming: boolean, source: ReaderBlockOwner['source'], loadImage: BlockRenderProps['loadImage'], fillComposer: BlockRenderProps['fillComposer'], holdFormatting: boolean, presentation: TextPresentation, blockKey: string, fileMentions?: BlockRenderProps['fileMentions']): ReactNode {
switch (block.kind) {
case 'text': return source === 'user' ? : ;
case 'image': return ;
case 'reasoning': return ;
case 'tool-call': return ;
case 'other': {
const raw = block.block;
if (raw && typeof raw === 'object') {
const item = raw as Record;
if ((item.type === 'mcp-app' || item.type === 'mcpapp' || item.type === 'ui') && typeof item.html === 'string') {
return ;
}
}
return ;
}
}
}
export const Blocks = memo(function Blocks({ blocks, streaming = false, source = 'assistant', holdFormatting = false, startedAt, interrupted, liveText, renderSlotChain, loadImage, fillComposer, fileMentions }: BlockRenderProps & TextPresentation & {
blocks: readonly AssistantBlock[]; streaming?: boolean; source?: ReaderBlockOwner['source']; holdFormatting?: boolean;
}) {
const reactId = useId();
return
{blocks.map((block, index) =>
{renderSlotChain('dsh-better-display.block', readerBlockOwner(block, streaming, source, { startedAt, interrupted, liveText }, holdFormatting), { fallback: fallback(block, streaming, source, loadImage, fillComposer, holdFormatting, { startedAt, interrupted, liveText }, `${reactId}:${index}:${block.kind}`, fileMentions) })}
)}
;
});
import { TurnMetrics } from './TurnMetrics.js';
function CopyGlyph() {
return ;
}
function useCopyReceipt() {
const [receipt, setReceipt] = useState('');
const timer = useRef | null>(null);
useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
const copy = async (text: string) => {
const accepted = await writeClipboard(text);
setReceipt(accepted ? '已复制' : '未能复制,请手动选择文字');
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => setReceipt(''), 2000);
};
return { receipt, copy };
}
function MessageClock({ time }: { time: number }) {
return ;
}
export function CopyAnswer({ blocks, onFork, metrics, extraActions }: { blocks: readonly AssistantBlock[]; onFork?: () => void; metrics?: BlockRenderProps['metrics']; extraActions?: ReactNode }) {
const { receipt, copy } = useCopyReceipt();
// Session text. A display transformer does not write these blocks.
const text = originalAnswerText(blocks);
const endedAt = metrics?.endedAt;
const hasMetrics = metrics !== undefined && (metrics.usage !== undefined || metrics.runMs !== undefined || endedAt !== undefined);
if (!text.trim() && !onFork && !hasMetrics) return null;
return
{text.trim() !== '' && (
)}
{extraActions}
{onFork && (
)}
{metrics &&
}
{endedAt !== undefined &&
}
{receipt}
;
}
export function UserMessageActions({ text, time }: { text: string; time?: number }) {
const { receipt, copy } = useCopyReceipt();
const hasText = text.trim() !== '';
if (!hasText && time === undefined) return null;
return
{time !== undefined && }
{hasText && (
)}
{receipt}
;
}