import type {} from '@deepseek-ai/dsh-session-turn-outline/types'; import type {} from '@deepseek-ai/dsh-agent/types'; import { Fragment, memo, useCallback, useEffect, useId, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import type { ReactNode, RefObject } from 'react'; import type { ChatConversationViewNode, ChatNode, ChatNodeKind, ChatNodeOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client'; import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'; import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'; import { BlockBoundary, Blocks, contentBlocks, UserMessageActions } from './Blocks.js'; import { AssistantNode } from './AssistantNode.js'; import { ToolActivity, ToolMedia } from './ToolActivity.js'; import { OfficialNode, OfficialTail } from './OfficialContent.js'; import { OFFICIAL_SEATS, readerGroupAction } from './official-slots.js'; import { preparingLabel, readerFlow } from './tool-activity.js'; import { Disclosure, ProcessFragment, RetiringTurns, StatusText, useMotionAllowed, usePinnedSelection, useReadingScroll } from './motion.js'; import { StreamMotionContext } from './streaming.js'; import { boundaryOf, forkAnchorSeq, groupNodes, hasProcessContent, processChoiceKey, processExpanded, terminalLabel } from './projection.js'; import { basename, createProducedFileMentions, dirname, getTurnDeliverables, showDeliverablesRow } from './deliverables.js'; import { deliverableOpenModeOf, type DeliverableOpenMode } from './open-file.js'; import { asReadonlyArray, pendingSubmissionImages, type PendingSubmissionEcho } from './pending-submission.js'; import { WaitingStatus } from './WaitingStatus.js'; import { handsBackToModel, waitingAnchor } from './waiting-clock.js'; import { ContextInjectionRow } from './native/ContextInjectionRow.js'; import { TimelineRail } from './TimelineRail.js'; import { landTurn, scrollerOf } from './conversation-scroll.js'; import { mergeTimelineItems, type TimelineItem } from './timeline.js'; import { planProcessSeams, presentLiveTurn, segmentLiveTurn } from './live-turn.js'; import type { LiveStep } from './live-turn.js'; import { frostedGlassOf } from './fold-intensity.js'; import { ChoreographedFlow, useFlowChat } from './ChoreographedFlow.js'; import { ClosedProcessSummary } from './ClosedProcessSummary.js'; import { ReaderLaneScope, StickyLane } from './StickyLane.js'; import type { ReaderGroup, TurnBoundary } from './projection.js'; import type { BlockRenderProps, ReaderProps } from './types.js'; import css from './Reader.module.css'; import { markdownLabels, truncatedJsonLabel } from './primitive-labels.js'; import { chatSeatProps } from './chat-seat.js'; import { visibleChatKeys, visibleChatSignature } from './rewind-cut.js'; import { ensureStyles } from './styles.js'; function isNode(node: ChatConversationViewNode, kind: K): node is ChatNode { return node.kind === kind; } function observedInputIds(order: readonly string[], getNode: (key: string) => ChatConversationViewNode | undefined): Set { const ids = new Set(); for (const key of order) { const node = getNode(key); if (!node || (node.kind !== 'user' && node.kind !== 'steering' && node.kind !== 'turn-trigger')) continue; const source = (node.data as { source?: { kind?: string; rpcId?: unknown } }).source; if (source?.kind === 'user' && typeof source.rpcId === 'string') ids.add(source.rpcId); } return ids; } function inboxText(item: { content?: readonly unknown[] }): string { return (item.content ?? []).filter((block): block is { type: 'text'; text: string } => { return typeof block === 'object' && block !== null && (block as { type?: unknown }).type === 'text' && typeof (block as { text?: unknown }).text === 'string'; }).map(block => block.text).join(''); } function inboxAttachmentCount(item: { content?: readonly unknown[] }): number { return (item.content ?? []).filter(block => typeof block === 'object' && block !== null && (block as { type?: unknown }).type !== 'text').length; } function cleanErrorMessage(raw: string | undefined): string { if (!raw) return '模型服务暂时无响应或连接中断,请稍后重试。'; let str = raw.trim(); if (str.includes('"error"') || str.startsWith('{')) { try { const idx = str.indexOf('{'); const parsed = JSON.parse(str.slice(idx)); const msg = parsed?.error?.message || parsed?.message || parsed?.error; if (typeof msg === 'string') str = msg; } catch { // keep } } return str; } type SeatProps = BlockRenderProps & Pick & { nodeKey: string; boundary: TurnBoundary; pinned?: boolean; processOpen?: boolean; }; const CompactionDivider = memo(function CompactionDivider({ data }: { data: { summary?: string | null; shadowedItemCount?: number | null; shadowedTokenCount?: number | null } | null; }) { const [open, setOpen] = useState(false); if (!data) return null; const hasSummary = typeof data.summary === 'string' && data.summary.trim().length > 0; const items = data.shadowedItemCount; const tokens = data.shadowedTokenCount; let label = '已压缩历史上下文'; if (items && tokens) { const kTokens = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens); label = `已压缩 ${items} 条上下文 · 释放约 ${kTokens} tokens`; } else if (items) { label = `已压缩 ${items} 条上下文`; } else if (tokens) { const kTokens = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens); label = `已压缩上下文 · 释放约 ${kTokens} tokens`; } return (
{hasSummary ? ( ) : ( {label} )}
{open && hasSummary && (
前期对话要点备忘
)}
); }); const ProcessNode = memo(function ProcessNode({ useChat, t, nodeKey, open, motion, onRead, returnFocusTo }: Pick & { nodeKey: string; open: boolean; motion: boolean; onRead: () => void; returnFocusTo: RefObject; }) { const node = useChat(snapshot => snapshot.nodes.get(nodeKey)); if (!node || node.visibility === 'hidden') return null; let content: ReactNode = null; if (isNode(node, 'context')) content = ; else if (isNode(node, 'system-prompt')) content =
系统提示词
{node.data.text}
; else if (isNode(node, 'model-retry')) content = ; else if (isNode(node, 'manual-compaction')) { if (node.data.command.outcome?.kind === 'error') { content =
上下文压缩未成功

{node.data.command.outcome.text}

; } else { content = node.data.compaction ? : null; } } else if (isNode(node, 'compaction')) content = ; else if (isNode(node, 'command')) content = ; return content && {content}; }); const MainNode = memo(function MainNode({ useChat, nodeKey, boundary, pinned, processOpen: _processOpen = false, ...render }: SeatProps) { const node = useChat(snapshot => snapshot.nodes.get(nodeKey)); const [disclosureReset] = useState(() => createSnapshotStore(0)); if (!node || node.visibility === 'hidden') return null; if (isNode(node, 'user') || isNode(node, 'steering')) { const blocks = contentBlocks(node.data.content); const imageBlocks = blocks.filter(b => b.kind === 'image'); const otherBlocks = blocks.filter(b => b.kind !== 'image'); const text = otherBlocks.filter((block): block is Extract => block.kind === 'text').map(block => block.text).join('\n\n'); const time = node.data.time; const fallback = <> {node.kind === 'steering' &&

补充消息

} {imageBlocks.length > 0 &&
} {otherBlocks.length > 0 &&
} ; const official = render.official; let rendered: ReactNode = fallback; if (official) { const turn = node.location.kind === 'turn' || node.location.kind === 'step' ? node.location.turn : undefined; const owner: ChatNodeOwnerProps & Pick = { cwd: render.cwd, openFile: render.openFile ?? (() => {}), forkAt: render.forkAt ?? (() => {}), inspectCall: callId => official.openView('trajectory', callId), loadImage: official.officialImageLoader, fileMentions: official.officialFileMentions, sessionId: render.sessionId, }; const options = { hookContext: { turnData: turn?.data, disclosureReset, useGroupAction: readerGroupAction }, fallback }; rendered = node.kind === 'user' ? official.renderSlot(OFFICIAL_SEATS.nodes, { ...owner, node }, { ...options, entryKey: 'user' }) : official.renderSlot(OFFICIAL_SEATS.nodes, { ...owner, node }, { ...options, entryKey: 'steering' }); } return
{rendered}
; } if (isNode(node, 'assistant-step')) return null; if (isNode(node, 'tool-call')) return ; if (isNode(node, 'turn-error')) return
本轮运行失败 {node.data.code && {node.data.code}}

{cleanErrorMessage(node.data.message)}

; if (isNode(node, 'turn-max-tokens')) return
已到达输出长度限制,回答尚未完整。
; if (isNode(node, 'model-retry')) return node.data.current.retryState === 'scheduled' ?
模型请求未成功,正在等待重试。详情保留在执行过程中。
: null; if (isNode(node, 'command') && render.official) return } />; if (isNode(node, 'command')) { if (node.data.outcome?.kind === 'error') return
命令执行未成功

{node.data.outcome.text ?? node.data.name ?? '查看原对话中的命令记录'}

; return node.data.outcome?.text ? : null; } if (isNode(node, 'manual-compaction') || isNode(node, 'compaction')) return null; if (node.kind === 'context' || node.kind === 'turn-tail' || node.kind === 'system-prompt' || node.kind === 'turn-process') return null; // No 'command-input' branch: that string is not a chat node kind in any released // host (it appears nowhere in the installed packages), so a slash command arrives // as 'command' above and is rendered there. Keeping the branch only made the file // look like it handled a case that cannot occur. return

此记录类型暂未接入阅读页:{node.kind}

{render.official && } } />; }); /** * Sub-agents this turn dispatched, read from the host's own Turn-process row. * * The host already derives this from the dispatch tree (`subagentCount` on * `TurnProcessChatData`), so counting calls here would only risk disagreeing with * it. The row is otherwise hidden by the reader, which is why this is the one place * its counters are read. */ function subagentCount(snapshot: { nodes: { get(key: string): ChatConversationViewNode | undefined } }, keys: readonly string[]): number { for (const key of keys) { const node = snapshot.nodes.get(key); if (!node || node.kind !== 'turn-process') continue; const value = (node.data as { subagentCount?: unknown }).subagentCount; if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value; } return 0; } function GroupStatus({ group, useChat, pending, motion }: Pick & { group: ReaderGroup; motion: boolean; pending: { kind?: string } | undefined }) { const text = useChat(snapshot => { const turn = group.turn === null ? undefined : snapshot.timeline.turns.get(group.turn); if (turn?.status === 'closed') { if (turn.end?.data.reason.kind !== 'completed') return '执行过程'; const elapsed = turn.start && turn.end ? Math.max(0, Math.round((turn.end.time - turn.start.time) / 1000)) : null; return elapsed === null ? '执行过程' : elapsed < 60 ? `用时 ${elapsed} 秒` : `用时 ${Math.floor(elapsed / 60)} 分 ${elapsed % 60} 秒`; } if (turn?.status !== 'open') return '执行过程'; if (pending !== undefined) return '等待你的操作'; const current = turn.steps.at(-1)?.data.get('assistant-step'); const last = current?.blocks.at(-1); if (current?.status === 'running' && last?.kind === 'tool-call') { const spawned = subagentCount(snapshot, group.keys); return spawned ? `${preparingLabel(last.name)}·${spawned} 个子代理` : preparingLabel(last.name); } for (let index = group.keys.length - 1; index >= 0; index--) { const node = snapshot.nodes.get(group.keys[index]); if (!node) continue; if (isNode(node, 'tool-call') && !('kind' in node.data.root)) return '正在使用工具'; if (isNode(node, 'assistant-step') && node.data.status === 'running') { const last = node.data.blocks.at(-1); return last?.kind === 'reasoning' ? '正在思考' : last?.kind === 'text' ? '正在输出' : '正在准备回复'; } } return '正在处理'; }); const busy = useChat(snapshot => group.turn !== null && snapshot.timeline.turns.get(group.turn)?.status === 'open' && pending === undefined); return ; } const DeliverableChip = memo(function DeliverableChip({ path, openFile, revealFile, openMode }: { path: string; openFile?: (path: string) => Promise | void; revealFile?: (path: string) => Promise | void; openMode: DeliverableOpenMode; }) { const [status, setStatus] = useState<'idle' | 'opened' | 'copied' | 'revealed'>('idle'); const timer = useRef>(); const flash = (next: 'opened' | 'copied' | 'revealed') => { setStatus(next); clearTimeout(timer.current); timer.current = setTimeout(() => setStatus('idle'), 1600); }; const onOpen = (event: React.MouseEvent) => { event.stopPropagation(); try { openFile?.(path); flash('opened'); } catch { // fallback } }; const onReveal = (event: React.MouseEvent) => { event.stopPropagation(); try { if (revealFile) { revealFile(path); } else { openFile?.(dirname(path)); } flash('revealed'); } catch { // fallback } }; const onCopy = (event: React.MouseEvent) => { event.stopPropagation(); try { void navigator.clipboard?.writeText(path); flash('copied'); } catch { // fallback } }; const name = basename(path); const folder = dirname(path); return (
); }); function DeliverablesRow({ deliverables, openFile, revealFile, openMode }: { deliverables: readonly string[]; openFile?: (path: string) => Promise | void; revealFile?: (path: string) => Promise | void; openMode: DeliverableOpenMode; }) { const [folderStatus, setFolderStatus] = useState<'idle' | 'opened'>('idle'); const onOpenWorkspace = () => { try { openFile?.('.'); setFolderStatus('opened'); setTimeout(() => setFolderStatus('idle'), 1600); } catch { // ignore } }; return (
产物
{deliverables.slice(0, 8).map(path => ( ))} {deliverables.length > 8 && ( + {deliverables.length - 8} 个文件 )} {deliverables.length > 1 && ( )}
); } const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel = false, ...props }: ReaderProps & { group: ReaderGroup; motion: boolean; autoFold: boolean; pinnedKeys: readonly string[]; selectedProcessKeys: readonly string[]; isAwaitingModel?: boolean }) { const snapshot = props.useChat(snapshot => snapshot); const nodes = snapshot.nodes; const turn = group.turn === null ? undefined : snapshot.timeline.turns.get(group.turn); const interaction = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction); const sessionRunning = props.useSession(snapshot => snapshot.running); const boundary = useMemo(() => boundaryOf(turn), [turn]); const choiceKey = processChoiceKey(group.key, boundary); const expansionChoice = props.useStore(state => state.expanded[choiceKey]); const flowId = useId(); const processButton = useRef(null); const setExpanded = useCallback((value: boolean) => props.actions.setExpanded(choiceKey, value), [props.actions, choiceKey]); const pinProcess = useCallback(() => setExpanded(true), [setExpanded]); const firstKind = props.useChat(snapshot => snapshot.nodes.get(group.keys[0])?.kind); const startsWithUser = firstKind === 'user'; const mainKeys = startsWithUser ? group.keys.slice(1) : group.keys; const flow = useMemo(() => readerFlow({ ...group, keys: mainKeys }, turn, key => nodes.get(key), snapshot.order), [nodes, group, mainKeys, turn, snapshot.order]); const steps = useMemo(() => segmentLiveTurn(flow, key => nodes.get(key)), [flow, nodes]); const liveItems = useMemo(() => presentLiveTurn(steps, boundary, autoFold), [steps, boundary, autoFold]); const openMode = deliverableOpenModeOf(useSyncExternalStore( props.openPrefs?.subscribe ?? ((fn: () => void) => { void fn; return () => {}; }), () => props.openPrefs?.getSnapshot()?.deliverableOpenMode, () => 'external', )); const hasProcess = flow.some(item => item.kind === 'tool' || hasProcessContent(nodes.get(item.nodeKey), boundary)); const showStatusLane = hasProcess && !isAwaitingModel; const showClosedSummary = boundary.status === 'closed' && hasProcess && autoFold; // Only a real, still-active text selection delays folding. Merely clicking, // focusing or scrolling the live card does not create a permanent override. const holdingSelection = selectedProcessKeys.some(key => flow.some(item => item.key === key) || liveItems.some(item => item.kind === 'fold' ? item.key === key || item.steps.some(step => step.key === key || ('nodeKey' in step && step.nodeKey === key)) : item.key === key || ('nodeKey' in item.step && item.step.nodeKey === key))); const expanded = !autoFold || holdingSelection || processExpanded(expansionChoice, boundary); // Seam between narration blocks. Skip a run a live-fold cell already // covers, and do not drop the previous body's bottom spacing. const seamPlan = useMemo( () => planProcessSeams(steps, liveItems, expanded), [steps, liveItems, expanded], ); const [foldOpenByKey, setFoldOpenByKey] = useState>({}); useLayoutEffect(() => { // Restoring automatic folding also releases live "prior steps" disclosures. if (autoFold) setFoldOpenByKey(current => Object.keys(current).length ? {} : current); }, [autoFold]); const deliverables = useMemo(() => getTurnDeliverables(turn, flow), [turn, flow]); const tailData = useMemo(() => { for (const key of group.keys) { const n = nodes.get(key); if (n && isNode(n, 'turn-tail')) return n.data; } return undefined; }, [group.keys, nodes]); const tailOwner = useMemo(() => turn && tailData ? { turn, seq: tailData.closing?.finalNode.seq ?? tailData.seq, openFile: props.openFile, } : undefined, [turn, tailData, props.openFile]); const fileMentions = useMemo(() => { const official = tailOwner ? props.officialFileMentions(tailOwner) : undefined; const reader = deliverables.length > 0 ? createProducedFileMentions(deliverables, props.openFile) : undefined; return official || reader ? { resolve: (value: string) => official?.resolve(value) ?? reader?.resolve(value) } : undefined; }, [tailOwner, props.officialFileMentions, deliverables, props.openFile]); const official = useMemo(() => ({ renderSlot: props.renderSlot, renderSlotChain: props.renderSlotChain, officialImageLoader: props.officialImageLoader, officialFileMentions: props.officialFileMentions, officialPreviewFile: props.officialPreviewFile, officialHost: props.officialHost, openView: props.openView, }), [props.renderSlot, props.renderSlotChain, props.officialImageLoader, props.officialFileMentions, props.officialPreviewFile, props.officialHost, props.openView]); const cwd = props.useSessions(state => state.byId[props.sessionId]?.cwd); const runMs = turn?.start && turn?.end ? Math.max(0, turn.end.time - turn.start.time) : undefined; const metrics = useMemo(() => ({ usage: tailData?.tokenUsage, runMs, tokensPerSecond: (tailData as { tokensPerSecond?: number } | undefined)?.tokensPerSecond, ttftMs: (tailData as { ttftMs?: number } | undefined)?.ttftMs, endedAt: tailData?.closing?.time ?? turn?.end?.time, }), [tailData, runMs, turn?.end?.time]); const forkSeq = forkAnchorSeq([tailData?.closing?.finalNode]); const presentation = useMemo(() => { // ChatNodeStore exposes live keyed readers. Materialize this turn instead of // retaining a live get() function and mistakenly calling it a frozen frame. const captured = new Map(group.keys.flatMap(key => { const node = nodes.get(key); return node ? [[key, node] as const] : []; })); return { items: holdingSelection ? presentLiveTurn(steps, boundary, false) : liveItems, snapshot: { ...snapshot, nodes: { ...nodes, get: (key: string) => captured.get(key), values: () => [...captured.values()] } } }; }, [snapshot, nodes, group, steps, boundary, liveItems, holdingSelection]); const shared = { useChat: useFlowChat, renderSlotChain: props.renderSlotChain, loadImage: props.loadImage, fillComposer: props.fillComposer, openFile: props.openFile, revealFile: props.revealFile, forkAt: props.forkAt, forkSeq, fileMentions, metrics, official, sessionId: props.sessionId, cwd, }; const terminal = terminalLabel(boundary.reason); const hasTurnError = flow.some(item => item.kind === 'node' && nodes.get(item.nodeKey)?.kind === 'turn-error'); // A stopped turn normally stays quiet, but a stopped turn that produced no // prose at all reads as if its answer vanished into the process fold. Say so. const hasAnswerProse = steps.some(step => step.kind === 'body' && step.blocks.some(block => block.kind === 'text' && block.text.trim() !== '')); const stoppedWithoutAnswer = (boundary.reason === 'interrupted' || boundary.reason === 'aborted') && !hasAnswerProse; const showTerminalNotice = terminal && !hasTurnError && (stoppedWithoutAnswer || (boundary.reason !== 'interrupted' && boundary.reason !== 'aborted')); const renderStep = (step: LiveStep, folded: boolean) => { const processOpen = folded || expanded; if (step.kind === 'reasoning' || step.kind === 'body') return ; if (step.kind === 'tool') return {step.entry.block && } ; if (step.kind === 'user') return ; return ; }; return
{startsWithUser && }
{(showStatusLane || showClosedSummary) &&
{showStatusLane && } /> } {showClosedSummary && step.kind !== 'user' && step.kind !== 'body')} />}
} { pinProcess(); setFoldOpenByKey(current => ({ ...current, [key]: value })); }} renderStep={renderStep} />
{/* 状态指示永远排在流程之后:AI 的响应永远出现在最新消息(含补充消息)的下方 */} {!hasProcess && boundary.status === 'open' && !isAwaitingModel &&
} {showDeliverablesRow(boundary.status, deliverables) && } {boundary.status === 'closed' && } {showTerminalNotice &&
{terminal}
}
; }); export function Reader(props: ReaderProps) { useInsertionEffect(() => { ensureStyles(); }, []); const root = useRef(null); const activatedAt = useRef(Date.now()); const order = props.useChat(snapshot => snapshot.order); const nodes = props.useChat(snapshot => snapshot.nodes); // A rewind upserts the command row in place, so order and nodes keep their identity. const rewindSignature = props.useChat(snapshot => visibleChatSignature(snapshot)); const renderKeys = useMemo(() => visibleChatKeys({ order, nodes }), [order, nodes, rewindSignature]); const timeline = props.useChat(snapshot => snapshot.timeline); const running = props.useSession(snapshot => snapshot.running); const pending = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction); const openError = props.useSession(snapshot => snapshot.openError); const loading = props.useSession(snapshot => snapshot.openState === 'loading'); const hasMore = props.useSession(snapshot => snapshot.hasMore); const loadingOlder = props.useSession(snapshot => snapshot.loadingOlder); const pendingSubmissions = props.useSession(snapshot => snapshot.pendingSubmissions); const pendingList = asReadonlyArray(pendingSubmissions); const inbox = props.useProjection?.('inbox'); type PendingInboxItem = { source?: { kind?: string; rpcId?: unknown }; content?: readonly unknown[] }; const inboxSteering = asReadonlyArray(inbox?.['next-step']).filter(item => item.source?.kind === 'user'); const observed = useMemo(() => observedInputIds(order, key => nodes.get(key)), [order, nodes]); const visibleSubmissions = useMemo(() => pendingList.filter(sub => sub.placement !== 'queued' && !observed.has(sub.requestId)), [pendingList, observed]); const pendingInputs = useMemo(() => { const local = new Map(visibleSubmissions.map(sub => [sub.requestId, sub])); const localIds = new Set(pendingList.filter(sub => sub.placement !== 'queued').map(sub => sub.requestId)); const rows: Array = []; for (const item of inboxSteering) { const rpcId = typeof item.source?.rpcId === 'string' ? item.source.rpcId : undefined; if (!rpcId) { rows.push(item); continue; } const submission = local.get(rpcId); if (submission) { local.delete(rpcId); rows.push(submission); } else if (!localIds.has(rpcId)) rows.push(item); } rows.push(...local.values()); return rows; }, [inboxSteering, pendingList, visibleSubmissions]); const waitAnchor = waitingAnchor(renderKeys, key => nodes.get(key), pendingList); const motionPreference = props.useStore(state => state.motion); const motion = useMotionAllowed(motionPreference); const prefsSnap = useSyncExternalStore( props.openPrefs?.subscribe ?? ((fn: () => void) => { void fn; return () => {}; }), () => props.openPrefs?.getSnapshot?.(), () => undefined, ); const storeAutoFold = props.useStore(state => state.autoFold); const autoFold = prefsSnap?.autoFold ?? (prefsSnap?.foldIntensity !== undefined ? prefsSnap.foldIntensity !== 0 : undefined) ?? storeAutoFold ?? true; const previousAutoFold = useRef(autoFold); useLayoutEffect(() => { const restored = autoFold && !previousAutoFold.current; previousAutoFold.current = autoFold; // Watch the effective preference so toolbar and Settings changes behave alike. // Reading while folding is off must not pin completed process content forever. if (restored) props.actions.resetExpanded(); }, [autoFold, props.actions]); const frostedGlass = frostedGlassOf(prefsSnap); const streamMotion = useMemo(() => ({ enabled: motion, activatedAt: activatedAt.current }), [motion]); const groups = useMemo(() => groupNodes(renderKeys, key => nodes.get(key)), [renderKeys, nodes, timeline]); const isAwaitingModel = useMemo(() => { // 状态机铁律:「深度求索中」与「正在处理/思考」永远互斥。 // 1. 仅空闲发送(!running)的本地回显窗口:用户按下回车第 0 毫秒立即反馈。 // 忙碌时的 queued/steering 回显不算等待——模型本来就在工作。 if (!running && pendingList.length > 0) return true; const lastKey = renderKeys.at(-1); const lastNode = lastKey ? nodes.get(lastKey) : undefined; if (!lastKey || !lastNode) return false; // 2. 模型已经产出内容:等待结束,计时器必须立刻消失。 // 「产出」= assistant-step 已带 block(正文/思维链/工具调用都算)。 if (lastNode.kind === 'assistant-step') { const data = lastNode.data as { status?: string; blocks?: unknown[] }; const blocks = data.blocks ?? []; // 空 block 且仍在跑 = 请求已发出、模型还没吐字,正是要计时的那一刻。 return blocks.length === 0 && data.status === 'running'; } // 3. 球在模型脚下:用户刚发言,或工具已返回、上下文已注入、命令已执行。 // 这些时刻模型随时可能卡住,正是要计时的地方;工具执行期间不计时, // 因为那时忙的是工具而不是模型。 // handsBackToModel 内部按 chat 层 kind 判定,并区分「工具已返回」与 // 「工具仍在跑」——后者不算等待。 const modelOwesResponse = handsBackToModel(lastNode); if (!modelOwesResponse) return false; // 轮次已结束就没什么可等的。 const lastGroup = groups.at(-1); const turn = lastGroup?.turn === null || lastGroup?.turn === undefined ? undefined : timeline.turns.get(lastGroup.turn); return turn?.status !== 'closed'; }, [running, pendingList, renderKeys, nodes, groups, timeline]); const scroll = useReadingScroll(root, motion); const pinnedKeys = usePinnedSelection(root); const selectedProcessKeys = usePinnedSelection(root, '[data-reader-process]'); const [historyError, setHistoryError] = useState(false); // 1. Navigation items from Chat snapshot const turnNavigationItems = props.useChat(snapshot => snapshot.navigation?.items ? snapshot.navigation.items() : undefined); // 2. Whole-log turn outline projection const turnOutline = props.useProjection?.('turnOutline'); // 3. Track turns with deliverables const turnsWithDeliverables = useMemo(() => { const set = new Set(); for (const [turnNum, loc] of timeline.turns) { const deliv = (loc.data as { get(key: string): unknown } | undefined)?.get('deliverables') as { produced?: unknown[] } | undefined; if (Array.isArray(deliv?.produced) && deliv.produced.length > 0) { set.add(turnNum); } } return set; }, [timeline]); // 4. Merged timeline items for the rail const timelineItems = useMemo( () => mergeTimelineItems(turnNavigationItems, turnOutline, turnsWithDeliverables), [turnNavigationItems, turnOutline, turnsWithDeliverables], ); // 5. Active & busy turn tracking const [activeTurn, setActiveTurn] = useState(null); const [busyTurn, setBusyTurn] = useState(null); // Scroll spy to update activeTurn useEffect(() => { const el = root.current; if (!el) return; const scroller = el.closest('[data-conversation-scroll]') ?? el; let ticking = false; const updateActive = () => { if (ticking) return; ticking = true; requestAnimationFrame(() => { ticking = false; const line = (scroller instanceof HTMLElement ? scroller.clientHeight : window.innerHeight) * 0.35; const turnRows = el.querySelectorAll('[data-reader-turn]:not([data-reader-turn="unresolved"])'); let current: number | null = null; for (const row of turnRows) { const rect = row.getBoundingClientRect(); if (rect.top <= line) { const num = Number(row.dataset.readerTurn); if (Number.isSafeInteger(num)) current = num; } else { break; } } if (current !== null) { setActiveTurn(current); } else if (turnRows.length > 0) { const first = Number(turnRows[0].dataset.readerTurn); if (Number.isSafeInteger(first)) setActiveTurn(first); } }); }; scroller.addEventListener('scroll', updateActive, { passive: true }); updateActive(); return () => scroller.removeEventListener('scroll', updateActive); }, [groups]); // Navigation handler (supports loaded jump & unloaded loadThrough). // Land on the conversation scroller only — scrollIntoView also moves // ancestor boxes and can lift the sticky composer after a top→bottom jump. const onNavigateTurn = useCallback(async (item: TimelineItem) => { const el = root.current; if (!el) return; const port = scrollerOf(el); const reveal = (turn: number) => { const targetRow = el.querySelector(`[data-reader-turn="${turn}"]`); if (!targetRow) return; const last = timelineItems.at(-1); if (last !== undefined && last.turn === turn) { scroll.jump(); } else { scroll.release(); landTurn(targetRow, port); } setActiveTurn(turn); }; if (item.anchor.kind === 'loaded') { reveal(item.turn); return; } setBusyTurn(item.turn); try { if (props.loadThrough) { await props.loadThrough(item.anchor.seq); } else { await props.loadOlder(); } setTimeout(() => { reveal(item.turn); }, 50); } finally { setBusyTurn(null); } }, [props.loadThrough, props.loadOlder, scroll.jump, scroll.release, timelineItems]); const lastKey = renderKeys.at(-1); const lastNode = lastKey ? nodes.get(lastKey) : undefined; const lastSubmissionId = pendingList.length ? pendingList[pendingList.length - 1].requestId : null; const lastOrderKeyRef = useRef(lastKey); const lastSubmissionRef = useRef(lastSubmissionId); useLayoutEffect(() => { const appendedUser = lastKey !== lastOrderKeyRef.current && (lastNode?.kind === 'user' || lastNode?.kind === 'steering'); const appendedSubmission = lastSubmissionId !== null && lastSubmissionId !== lastSubmissionRef.current; lastOrderKeyRef.current = lastKey; lastSubmissionRef.current = lastSubmissionId; if (appendedUser || appendedSubmission) { scroll.jump(); } }, [lastKey, lastNode?.kind, lastSubmissionId, scroll]); // ChatView publishes data-chat-flow="" on its column. Skins treat a // scrollport without that hook as inspect-only and hide [data-composer-seat]. // dsh-claude-style 0.19.x also hides the host seat whenever the first tab // is not 对话. Reader.module.css restores that seat only while this root // (data-dsh-better-display) is mounted. return
{hasMore && } {historyError &&
历史记录加载失败,可再次尝试;现有内容未改变。
} {openError &&
会话暂时无法读取:{openError.message}
} {loading && groups.length === 0 &&

正在读取会话…

} } /> {pendingInputs.map((item, index) => { const submission = 'requestId' in item ? item : undefined; const text = submission?.text ?? inboxText(item as PendingInboxItem); const images = submission ? pendingSubmissionImages(submission) : []; const attachmentCount = submission ? images.length : inboxAttachmentCount(item as PendingInboxItem); const requestId = submission?.requestId ?? `inbox-${index}`; return (
{images.length > 0 && (
{images.map((item, idx) => (
{item.name
))}
)} {text ? (
{text}
) : null}
); })} {isAwaitingModel && } {pending !== undefined &&
{pending.kind === 'question' ? '需要你回答一个问题' : '需要你的确认'} 请在下方原生操作区处理。此提示不会收进执行过程。
} {scroll.detached &&
}
; }