/** * ============================================================ * src/ui/MessageList.tsx —— 消息历史展示 * ------------------------------------------------------------ * 渲染历史消息(system 不显示)。 * 使用 Ink 5.x 的 commit 历史到终端 scrollback: * 鼠标滚轮可以自然翻阅,性能也更好(已 commit 的行不会再 rerender)。 * * 流式中的 assistant 文本不再在这里"假消息"显示—— * streaming 阶段不渲染 live answer,turn 结束后再以正式的 * assistant Message 进入 history 并被 commit。 * * banner 也走 Static 流(items[0])。 * Ink 5 的 Static 约定要求 Static 是兄弟节点中第一个,否则它上方的 live * 兄弟会跟 Static commit 一起被重打到 stdout(用户实测看到 banner 被 * 反复打印 N 次)。把 banner 作为 Static 的第一个 item,banner 自然 * commit 进 scrollback,启动时打印一次,不再反复出现。 * * 分开用户请求、执行活动、子任务交接和最终答复;工具原文按需查看。 * ============================================================ */ import React from 'react'; import { Box, Static, Text } from 'ink'; import { conciseToolDescription } from './toolProgress.js'; import { activityLines, activityText, agentNotice, backgroundNoticeCard, backgroundTaskNotice, backgroundWakeStub, noticeCard, receiptCard, systemNotice, type ActivityCard } from './activityPresentation.js'; import { advisorOpinionText } from '../advisor/presentation.js'; import { contentToDisplayText, contentToPlainText } from '../multimodal.js'; import type { Message } from '../types.js'; import { createPublicTextStream } from './publicText.js'; import { transcriptRows } from './commandTranscript.js'; import { workflowOutcomeLabel } from '../runtime/workflowPresentation.js'; import { figures } from './figures.js'; import { terminalText } from './terminalText.js'; import { type MdLineKind, renderMarkdownLines } from './markdown.js'; import { theme } from './theme.js'; import { toolBatchSummary, toolHistoryVisibility } from './toolProgress.js'; import { repeatedAgentActivities } from './agentActivityDedup.js'; import { priorTaskNoticeCards } from './activityPresentation.js'; import { isPriorTaskNotice } from '../runtime/systemEvents.js'; /** * Turn 元信息:每个非中断 user message 是一个 turn 的起点。 * 由 summarizeTurn() 一次性扫 history 算出,挂在 StaticItem 上喂给 MessageRow。 */ export interface TurnMeta { turnN: number; /** turn 内最后一条 assistant/tool timestamp - user timestamp(缺失 fallback 0) */ durationMs: number; /** turn 内所有 assistant 的 tool_calls.length 累加 */ toolsCount: number; /** user message 的 timestamp(缺失 fallback Date.now()) */ timestamp: number; } /** 中断标记 user message 的固定内容(loop.ts 写入) */ const INTERRUPT_USER_CONTENT = '(用户按下了 ESC/Ctrl+C 中断了任务)'; /** Static items 的混合类型:banner 在 items[0],messages 在后面。 */ type StaticItem = | { kind: 'banner'; text: string; key: string } | { kind: 'prior-notices'; card: ActivityCard; key: string } | { kind: 'message'; msg: Message; turnMeta: TurnMeta | null; /** tool 消息的发起方人话描述(buildToolCallIndex 反查);其余消息 null */ toolMeta: ToolCallMeta | null; key: string; hiddenActivity?: boolean; }; interface Props { history: Message[]; /** compact / clearHistory 触发递增;作为 的 remount 触发器 */ compactGeneration: number; /** banner 文案;不传则不渲染 banner 行 */ bannerText?: string; } const MAX_TOOL_PREVIEW_LINES = 3; /** * 顾问意见的例外:它不是「工具输出」那类可略读的噪声,而是**第二个模型的独立评审**, * 用户此刻最想看的就是它说了什么。折叠到 3 行等于藏起来 —— 而 `/advisor ask` 手动路径 * 反而是 ephemeralLine 全文输出,同一份内容两种待遇。 * * 24 行的依据:顾问 persona 明确要求「只讲最关键的 1-3 点、不复述历史」,一份合规的 * 评审装得下;真跑长了仍然折叠 + /show,刷屏边界没有放开。 */ const MAX_ADVISOR_PREVIEW_LINES = 24; /** tool 结果的预览行数上限(纯函数,单独导出可测)。 */ export function toolPreviewCap(toolName?: string): number { return toolName === 'Advisor' ? MAX_ADVISOR_PREVIEW_LINES : MAX_TOOL_PREVIEW_LINES; } export interface AssistantDisplayLine { /** prose = 可含 ANSI 的正文行;code = 原文逐字节;fence = ``` 围栏 */ content: string; /** * 行前缀。code/fence **恒为 ''**(复制安全断言点:代码顶格零装饰, * 复制粘贴即原文);prose 首条非空行 '⏺ '、续行 ' '(视觉锚点, * 普通文字复制场景少,保留过程锚更重要)。 */ prefix: '⏺ ' | ' ' | ''; kind: MdLineKind; /** wrap='end':Ink 原样输出(不注入换行、不截断),超宽交终端软换行 */ wrap: 'end'; } /** * 把 assistant 最终正文拆成展示行:markdown 管线(src/ui/markdown.ts)产出 * prose/code/fence 三类行,⏺ 锚点落在**第一条非空 prose 行**——答案以代码块 * 开头时代码顶格在前、⏺ 顺延;全代码答案无 ⏺(代码纯净优先)。 * 纯文本无 markdown 特征时走快路径,与旧「按 \n 切 + wrap='end'」逐行一致。 */ export function buildAssistantDisplayLines(text: string): AssistantDisplayLine[] { if (text.length === 0) return []; let anchorPlaced = false; return renderMarkdownLines(text).map((line) => { if (line.kind !== 'prose') { return { content: line.text, prefix: '' as const, kind: line.kind, wrap: 'end' as const }; } if (!anchorPlaced && line.text.trim() !== '') { anchorPlaced = true; return { content: line.text, prefix: '⏺ ' as const, kind: line.kind, wrap: 'end' as const }; } return { content: line.text, prefix: ' ' as const, kind: line.kind, wrap: 'end' as const }; }); } /** 工具调用元信息:tool 消息头行的「人话描述」来源(从同 turn assistant 反查)。 */ export interface ToolCallMeta { toolName: string; friendly: string; } /** * 扫 history 里全部 assistant.tool_calls,建 tool_call_id → 人话描述 索引。 * tool 消息本身只有 content + tool_call_id(不动 history 字节的前提下, * 头行要显示「哪个工具在干什么」只能反查发起方)。 提交时序保证 * assistant(tool_calls) 恒先于对应 tool 消息入 history,索引命中无竞态。 */ export function buildToolCallIndex(history: Message[]): Map { const map = new Map(); for (const m of history) { if (m.role !== 'assistant' || !m.tool_calls) continue; for (const tc of m.tool_calls) { map.set(tc.id, { toolName: tc.function.name, friendly: conciseToolDescription(tc.function.name, tc.function.arguments), }); } } return map; } /** * 扫一遍 history,按 user message 切分 turn,返回每条 message 对应的 turnMeta。 * 返回数组长度 = history.length,与 history 一一对应: * - user message(非中断)→ 该 turn 的 TurnMeta(turnN 递增,>=1) * - 中断标记 user / assistant / tool / system → null * * 算法: * 1) 先识别"turn 起点":所有非中断 user message * 2) 每个 turn 起点 turnN 从 1 递增 * 3) turn 结束位置 = 下一个 turn 起点之前(或 history 末尾) * 4) durationMs = turn 内最后一条 assistant/tool 的 timestamp - user.timestamp * 5) toolsCount = turn 内所有 assistant.tool_calls?.length 累加 * * 导出供单测断言。 */ export function summarizeTurn(history: Message[]): Array { const result: Array = new Array(history.length).fill(null); // 找出所有 turn 起点的 index const turnStartIndices: number[] = []; for (let i = 0; i < history.length; i++) { const m = history[i]; if ( m.role === 'user' && !systemNotice(m) && contentToPlainText(m.content) !== INTERRUPT_USER_CONTENT ) { turnStartIndices.push(i); } } for (let t = 0; t < turnStartIndices.length; t++) { const startIdx = turnStartIndices[t]; const endIdx = t + 1 < turnStartIndices.length ? turnStartIndices[t + 1] - 1 : history.length - 1; const startMsg = history[startIdx]; const userTimestamp = (startMsg as { timestamp?: number }).timestamp ?? Date.now(); let lastResponseTs: number | null = null; let toolsCount = 0; for (let j = startIdx + 1; j <= endIdx; j++) { const m = history[j]; if (m.role === 'assistant') { toolsCount += m.tool_calls?.length ?? 0; if (typeof m.timestamp === 'number') lastResponseTs = m.timestamp; } else if (m.role === 'tool') { if (typeof m.timestamp === 'number') lastResponseTs = m.timestamp; } } const durationMs = lastResponseTs !== null ? Math.max(0, lastResponseTs - userTimestamp) : 0; result[startIdx] = { turnN: t + 1, durationMs, toolsCount, timestamp: userTimestamp, }; } return result; } /** 格式化 timestamp 为 HH:MM(本地时区) */ function formatTime(ts: number): string { return new Date(ts).toTimeString().slice(0, 5); } /** * React.memo 包装:props 浅比较够用,history 引用不变时 streaming 高频更新 * 不会重算 items。 */ /** * 文本终态回执 → 一行人类可读说明。 * * 只有非 completed 才返回内容:completed 仍走原来的「最终回答 / 工作进展」。 * 这里同时给出「继续」入口提示 —— 续写是显式动作,不自动重试。 */ function describeGeneration(receipt?: Message['generation']): string | undefined { if (!receipt || receipt.status === 'completed') return undefined; const reason = receipt.status === 'incomplete' ? receipt.stopReason === 'length' ? '输出长度达到上限' : '响应流未正常结束' : receipt.source === 'user_cancel' ? '用户中断' : receipt.source === 'queued_input' ? '收到新输入' : receipt.source === 'idle_timeout' ? '等待响应超时' : receipt.source === 'transport_error' ? '网络传输中断' : receipt.source === 'provider_error' ? `服务端错误${receipt.errorCode ? `(${receipt.errorCode})` : ''}` : '原因未知'; return `部分回答 · ${reason} · 发送「继续」可接着输出`; } export const MessageList = React.memo(function MessageList({ history, compactGeneration, bannerText, }: Props): JSX.Element { // Ink Static can append but cannot amend a printed row. Seal the last group // after each committed render; notices arriving together still share a card. const sealedGroups = React.useMemo(() => new Set(), [compactGeneration]); const rows = React.useMemo(() => transcriptRows(history), [history]); React.useLayoutEffect(() => { const tail = rows.at(-1); if (tail?.id && isPriorTaskNotice(tail)) sealedGroups.add(tail.id); }, [rows, sealedGroups]); const items: StaticItem[] = React.useMemo(() => { const turnMetas = summarizeTurn(rows); const toolIndex = buildToolCallIndex(history); const hiddenActivities = repeatedAgentActivities(rows, toolIndex); const project = (m: Message, idx: number): StaticItem[] => { if (isPriorTaskNotice(m)) { const previous = rows[idx - 1]; if (previous?.id && isPriorTaskNotice(previous) && !sealedGroups.has(previous.id)) return []; let end = idx + 1; while (end < rows.length && !sealedGroups.has(rows[end - 1]!.id!) && isPriorTaskNotice(rows[end]!)) end++; const cards = priorTaskNoticeCards(rows.slice(idx, end)); const warning = cards.filter(card => card.warning).length; return [{ kind: 'prior-notices', key: m.id ?? `prior-${idx}`, card: { title: `先前目标 · ${cards.length} 条后台通知`, warning: warning > 0, lines: [warning ? `${warning} 条需要核对或接手 · /show notices 查看` : '/show notices 查看,不计入当前任务'], } }]; } return [{ kind: 'message', msg: m, hiddenActivity: hiddenActivities.has(idx), turnMeta: turnMetas[idx], toolMeta: m.role === 'tool' ? (toolIndex.get(m.tool_call_id) ?? null) : null, key: m.id ?? `message-${idx}` }]; }; return [ ...(bannerText ? [ { kind: 'banner' as const, text: bannerText, key: `banner-${bannerText.slice(0, 10)}`, }, ] : []), ...rows.flatMap(project), ]; }, [bannerText, history, rows, sealedGroups]); return ( {(item) => { if (item.kind === 'banner') { return ; } if (item.kind === 'prior-notices') return ; return ( ); }} ); }); function BannerRow({ text }: { text: string }): JSX.Element { const [head, ...rest] = terminalText(text).split(' ·'); return {head} {rest.length > 0 && {' ·' + rest.join(' ·')}} ; } function ResultCard({card, shortId}: {card: ActivityCard; shortId?: string}): JSX.Element { return {card.title} {card.lines.map((line, i) => {line})} {shortId && {`详情 /show ${terminalText(shortId)}`}} ; } function MessageRow({ message, turnMeta, toolMeta, hiddenActivity, }: { message: Message; turnMeta: TurnMeta | null; toolMeta?: ToolCallMeta | null; hiddenActivity?: boolean; }): JSX.Element | null { switch (message.role) { case 'system': { // v2.x:ephemeral system message 是 UI 临时提示(slash 命令输出等), // 用暗灰单行风格显示;正经 system prompt(_ephemeral=undefined)依然 hide。 const ephemeral = (message as { _ephemeral?: true })._ephemeral === true; if (!ephemeral) return null; if (message.commandDisplay?.kind === 'result') return ( 命令结果 {terminalText(message.content).trimEnd()} ); // The final snapshot repeats the whole milestone list; the stage rows // are already in scrollback. Keep the outcome and its actual reason. const workflow = message.workflowPresentation; if (workflow) { const outcome = workflowOutcomeLabel(workflow.outcome); return !!line && line !== outcome), warning: !!workflow.outcome && workflow.outcome !== 'succeeded', }} />; } const milestone = message._uiProgress === true; const lines = message.draftPresentation ? renderMarkdownLines(terminalText(message.content)).map(line => line.text) : terminalText(message.content).split('\n'); const displayLines = milestone && !message.draftPresentation ? activityLines(message.content, 4) : lines; if (milestone && !displayLines.length && !message.generation) return null; return ( {message.draftPresentation && {message.draftPresentation.label}} {displayLines.map((line, i) => ( {line} ))} {/* 没有可见正文时,终态回执挂在 system 进度消息上;这里不显示的话, 重启会话后就只剩一句“已中断”,看不出是超时、断流还是用户取消。 */} {describeGeneration(message.generation) && ( {describeGeneration(message.generation)} )} ); } case 'user': { // The foreground answer already used these successful receipts. Keep // them searchable with /show notices without repeating them after it. if (message.taskNotice?.accounted) return null; if (message.inputOrigin === 'compact-summary' || message.inputOrigin === 'compact-fallback') return 上下文续接记录 · 系统生成,不是新的用户要求; const body = terminalText(contentToDisplayText(message.content)); if (agentNotice(message)) return ; if (backgroundTaskNotice(message)) return ; // 唤醒桩本身对用户没有信息量(通知卡紧随其后),只留一行交代这轮是自动起的。 if (backgroundWakeStub(message)) return 后台任务结束,已自动继续; if (body === INTERRUPT_USER_CONTENT) return 本轮已由用户中断; return ( {turnMeta ? `你 · 第 ${turnMeta.turnN} 轮 · ${formatTime(turnMeta.timestamp)}` : '你'} {body} ); } case 'assistant': { // assistant 可能只有 tool_calls 没有 content(content 为 null) const raw = message.content ?? ''; const tcCount = message.tool_calls?.length ?? 0; const progress = message.presentation === 'progress' || tcCount > 0; const stream = createPublicTextStream(); const body = stream.append(raw) + stream.finish(); // A progress-labelled delivery can contain the user's actual document. // Only condense the commentary attached to calls, never the deliverable. const answer = tcCount ? activityLines(body, 3).join('\n') : body; if (!answer.trim() && !tcCount && !describeGeneration(message.generation)) return null; return ( {/* 最终答案:markdown 管线格式化(标题/列表/行内代码/引用),⏺ 锚点落 第一条非空 prose 行 + 默认亮色正文(答案是主角)。代码块「零装饰」: fence 行 dim、code 行顶格无前缀无染色逐字节原文 —— 复制粘贴即原文。 纯 渲染(write-once),零刷屏风险,不碰 LiveArea 的 INV-1/INV-2。 */} {describeGeneration(message.generation) ? ( {describeGeneration(message.generation)} ) : ( answer.trim() && ( {progress ? '工作进展' : message.presentation === 'final' ? '最终回答' : '回复'} ) )} {buildAssistantDisplayLines(answer).map((line, i) => { if (line.kind === 'fence') { return ( {line.content} ); } if (line.kind === 'code') { return ( {line.content.length > 0 ? line.content : ' '} ); } return line.prefix === '⏺ ' ? ( {line.prefix} {line.content.length > 0 ? line.content : ' '} ) : ( {`${line.prefix}${line.content}`.length > 0 ? `${line.prefix}${line.content}` : ' '} ); })} {tcCount > 0 && ( {terminalText(`${figures.corner} 工具调用 · ${toolBatchSummary(message.tool_calls ?? [])}${tcCount > 2 ? ' · /show 查看' : ''}`)} )} ); } case 'tool': { if (hiddenActivity) return null; const card = receiptCard(message, toolMeta?.toolName, toolMeta?.friendly); const shortId = message.tool_call_id.slice(-8); if (card) return ; if (toolHistoryVisibility(toolMeta?.toolName, message.content, message.display_ok) === 'hidden') return null; const isAdvisor = toolMeta?.toolName === 'Advisor'; const report = isAdvisor ? advisorOpinionText(message.content) : message.content; const lines = activityLines(report, toolPreviewCap(toolMeta?.toolName)); return ; } } }