/** * ============================================================ * src/ui/LiveArea.tsx —— 输入框上方的本轮过程区(有界多行流式 live 区) * ------------------------------------------------------------ * 结构(自上而下): * ┌ 状态行(恒 1 行):动画 spinner + 阶段标签 + 已耗时 (+ plugin 进度) * └ 内容区(0..N 行,有界):随阶段切换—— * thinking → 等待响应或思考状态,不显示内部 token * streaming → streamingText 尾部最近 N 行(默认亮色 = 答案是主角) * tool_executing →「当前正在」动作 + 可选独立进度行(gray dim) * compacting/idle→ 无内容行 * * ★ 暂态错误行(transientError):工作流步执行中 LLM 调用失败(会被该步重试)时, * 不把它当永久红字提交进 scrollback,而是作为**状态行下方的一条黄色暂态行**显示。 * 它随状态行每帧刷新而被覆盖(不 strand),重试成功后由 useChat 丢弃 → 自然消失。 * 彻底失败(步 ok:false / 顶层 halt)才由 useChat 改走永久红字(chat.error)。 * 这条行同样走 INV-1 宽度钳制(clampWidthStart),不破坏防刷屏不变量。 * * ★ 为什么这样能既"多行打字机 + 流式答案"又**不刷屏**(详见 liveViewport.ts 头部): * - INV-1:每行都用 wrapToDisplayLines / clampWidthStart 按 CJK/emoji=2 钳到 * ≤ cols - LIVE_RIGHT_MARGIN → 终端永不自动折行 → ink eraseLines 每帧精确。 * - INV-2:内容区取**尾部最近 N 行**(contentMaxLines 自适应终端高度),保证 * live 区总高度 < 终端行数 → 不触发 ink 的 outputHeight>=rows 全屏重写。 * 最终答案由 (MessageList)write-once 呈现,不进 live 区。 * * ★ 动画 spinner + 已耗时:非 idle 时挂一个 ~150ms tick 强制 re-render,保证 * "无 token 到达的纯等待期"spinner 仍在跳、秒数仍在走 → 消除"卡住"观感。 * 流式内容本身走 useChat 的 100ms 节流;ink 内部 32ms throttle 合并,频率安全。 * ============================================================ */ import React, { useEffect, useRef, useState } from 'react'; import { Box, Text } from 'ink'; import type { ProgressStage, ToolStatusState } from '../types.js'; import { LIVE_RIGHT_MARGIN, clampWidthStart, wrapToDisplayLines, } from './liveViewport.js'; import { theme } from './theme.js'; import { figures } from './figures.js'; import type { PluginProgressState } from './hooks/useChat.js'; import { liveToolDescription } from './toolProgress.js'; import { activityText } from './activityPresentation.js'; export interface LiveAreaProps { reservedRows?: number; progressNotice?: string | null; progressStage: ProgressStage; /** Has the provider actually emitted a reasoning event this stage? */ reasoningActive?: boolean; /** 最终答案流式预览(环形 buffer 尾部)。streaming 阶段多行显示。 */ streamingText: string; runningTools: ToolStatusState[]; backgroundAgents?: ToolStatusState[]; pluginProgress: PluginProgressState | null; /** * 暂态错误文案(黄色,状态行下方一行)。工作流步执行中 LLM 失败但会被该步重试时, * useChat 把错误存这里而非提交进 scrollback;重试成功 / 步结束后清空 → 自然消失。 * null/undefined = 无暂态错误。idle 阶段也允许显示(让"已恢复/重试中"提示在步间隙仍可见)。 * 设为可选:既有 buildLiveView 单测的 props 不带此字段也合法(缺省视为无)。 */ transientError?: string | null; terminalCols: number; terminalRows: number; } const STAGE_LABELS: Record, string> = { thinking: '思考中', streaming: '正在输出', tool_executing: '工作中', compacting: '压缩历史', }; /** 动画 spinner 帧(charWidth 上界按 2 计;终端实际多为 1,算宽无害)。 */ const SPINNER_FRAMES = ['✶', '✸', '✹', '✺', '✹', '✷']; /** spinner 推进 + 强制 re-render 间隔(ms)。~7Hz,远低于 ink 31Hz throttle,Windows 安全。 */ const SPINNER_INTERVAL_MS = 150; /** 内容区行数硬顶(大终端也不铺满,保持清爽)。 */ const CONTENT_HARD_CAP = 16; /** 预留输入视口、排队提示、状态栏和异常行;矮窗口允许完全收起正文预览。 */ const RESERVED_ROWS = 10; /** 内容区最多显示几行:自适应终端高度,留足 status/input 余量(满足 INV-2)。 */ export function contentMaxLines(terminalRows: number, reservedRows = RESERVED_ROWS): number { return Math.max(0, Math.min(CONTENT_HARD_CAP, terminalRows - reservedRows)); } /** 取数组尾部最近 n 个元素。 */ function lastN(arr: T[], n: number): T[] { if (n <= 0) return []; return arr.length <= n ? arr : arr.slice(arr.length - n); } function toolDesc(t: ToolStatusState): string { // 长时工具的步内实时进度(LoopEvent.tool_progress)追加在描述后—— // 比静态 args 信息量大得多(如生图 "[ai-image-plan] round 1/1 15/31 t2i → ai_p11.png")。 // 宽度钳制由调用方 clampWidthStart 统一负责(INV-1),这里只拼内容。 const progress = activityText(t.progress); return progress ? `${toolDescStatic(t)} · ${progress}` : toolDescStatic(t); } function toolDescStatic(t: ToolStatusState): string { return liveToolDescription(t.toolName, t.argsFriendly); } /** * 蜂群树:runningTools 里有 ≥2 个并行的 Agent 子任务时,把 tool_executing * 内容区渲染成树形(借鉴 Claude Code 的 AgentProgressLine 语汇): * * ⚡ 3 个子任务并行中(另有 1 个工具) * ├─ 子任务[explore] 检索路由实现 * │ ⎿ 第 2 轮 · Reading src/router.ts * └─ 子任务[explore] 调研配置系统 * ⎿ 正在撰写报告…(已输出 850 字) * * - <2 个 Agent → 返回 null,调用方走既有扁平路径(单 Agent 行为不变)。 * - 行预算:两行模式(描述行 + ⎿ 进度行)放不下 maxLines 时降级单行模式 * (进度拼在描述后),仍超则保留总览和靠前分支——INV-2 恒成立。 * - 每行经 clampWidthStart 钳宽(INV-1;树形字形 ├└│⎿ 已入 charWidth=2 上界)。 * - Agent 的 progress 行(agent.ts publish 的「label」第 N 轮 · …)剥掉与 * 描述行重复的「label」前缀,树里不重复念名字。 * 导出供单测断言(liveArea.test.ts 蜂群树 describe)。 */ export function buildSwarmLines( runningTools: ToolStatusState[], maxWidth: number, maxLines: number, ): string[] | null { const agents = runningTools.filter((t) => t.toolName === 'Agent'); if (agents.length < 2) return null; const others = runningTools.filter((t) => t.toolName !== 'Agent'); const queued = agents.filter((agent) => agent.progressDetail?.kind === 'subagent' && agent.progressDetail.phase === 'queued').length; const activeCount = agents.length - queued; const header = `${figures.swarm} ${activeCount} 运行${queued > 0 ? ` · ${queued} 排队` : ''}${ others.length > 0 ? `(另有 ${others.length} 个工具)` : '' }`; // 进度文案剥冗余 label 前缀(描述行已含「子任务[type] label」) const stripLabel = (p: string) => p.replace(/^「[^」]*」\s*/, ''); const twoLine = 1 + agents.length * 2 + others.length <= maxLines; const lines: string[] = [header]; agents.forEach((t, i) => { const isLast = i === agents.length - 1 && others.length === 0; const branch = isLast ? figures.corner : figures.branch; const progress = t.progress ? activityText(stripLabel(t.progress), '处理中…') : ''; if (twoLine) { lines.push(`${branch} ${toolDescStatic(t)}`); lines.push(`${isLast ? ' ' : `${figures.pipe} `}${figures.elbow} ${progress || '启动中…'}`); } else { lines.push(`${branch} ${toolDescStatic(t)}${progress ? ` · ${progress}` : ''}`); } }); for (const t of others) lines.push(` ${toolDesc(t)}`); return lines.slice(0, maxLines).map((l) => clampWidthStart(l, maxWidth)); } export interface LiveView { /** 状态行(恒 1 行,已钳到 ≤ maxWidth);idle+仅暂态错误时为空串(不渲染)。 */ statusLine: string; statusColor: typeof theme.user | typeof theme.plugin; /** 内容区显示行(已 wrap + 必要前缀,逐行 ≤ maxWidth;尾部最近 N 行)。 */ contentLines: string[]; /** true → 次要内容(gray dim:reasoning / tool);false → 主要内容(默认亮色:答案)。 */ contentDim: boolean; /** * 暂态错误行(黄色,状态行下方一行;已钳到 ≤ maxWidth)。null = 不显示。 * 与 contentLines 互不干扰:它是"过程级"提示(重试/超时/已恢复),不进 scrollback。 */ transientErrorLine: string | null; } /** * 纯函数:把一帧的 props(+ 动画 frame / 已耗时秒数)算成 LiveView。 * idle 且无暂态错误时返回 null(live 区隐藏);idle 但有暂态错误时仅渲染该黄色行 * (让"重试中/已恢复"提示在步间隙 stage 短暂回 idle 时也不闪没)。 * 导出供单测断言 INV-1(每行宽)/ INV-2(行数)/ 颜色层次。 */ export function buildLiveView( props: LiveAreaProps & { frame: string; elapsedSec: number }, ): LiveView | null { const { progressStage, streamingText, runningTools, transientError, terminalCols, terminalRows, frame, elapsedSec, } = props; const pluginProgress = props.pluginProgress?.completed ? null : props.pluginProgress; const maxWidth = Math.max(1, terminalCols - LIVE_RIGHT_MARGIN); const maxLines = contentMaxLines(terminalRows, props.reservedRows); // 暂态错误行:单行、钳宽(满足 INV-1)。空串视为无。 const transientErrorLine = (transientError || props.progressNotice) ? clampWidthStart(activityText(transientError || props.progressNotice, '状态已更新'), maxWidth) : null; // idle 且无暂态错误 → 整个 live 区隐藏(保持既有行为)。 // idle 但有暂态错误 → 只渲染那一行黄字,无状态行 / 无 spinner(避免 idle 还转圈)。 const background = props.backgroundAgents ?? []; if (progressStage === 'idle' && !background.length && (!pluginProgress || pluginProgress.completed)) { if (transientErrorLine === null) return null; return { statusLine: '', statusColor: theme.user, contentLines: [], contentDim: true, transientErrorLine, }; } const stage = progressStage === 'idle' ? 'tool_executing' : progressStage; // ---- 状态行 ---- let status = `${frame} ${stage === 'thinking' && !props.reasoningActive ? '等待模型响应' : STAGE_LABELS[stage]} (${elapsedSec}s)`; if (progressStage === 'idle' && background.length) status = `后台子任务 · ${background.length} 个执行中`; if (pluginProgress) { // current 缺省 = 纯文案进度(工作流步骤 title),不渲染数字 const num = pluginProgress.current !== undefined ? `${pluginProgress.current}/${pluginProgress.max ?? '?'}` : ''; const msg = activityText(pluginProgress.message); const body = [num, msg].filter(Boolean).join(' '); status += ` · ${activityText(pluginProgress.pluginId, '工作流')}${body ? ` · ${body}` : ''}`; } status = clampWidthStart(status, maxWidth); // ---- 内容区 ---- let contentLines: string[] = []; let contentDim = true; if (stage === 'streaming' && streamingText.length > 0) { // Compatibility for older event producers; new loops publish only approved answers. contentLines = lastN(wrapToDisplayLines(streamingText, maxWidth), maxLines); contentDim = false; // 答案 = 主角,默认亮色 } else if (stage === 'tool_executing' && runningTools.length > 0) { // ≥2 个并行 Agent 子任务 → 蜂群树;普通工具用“当前正在”主行,长时 // progress 独占下一行,避免主行变长后把最关键的 15/31 等进度截掉。 const swarm = buildSwarmLines(runningTools, maxWidth, maxLines); const flatLines = runningTools.flatMap((tool) => [ ` 当前正在:${toolDescStatic(tool)}`, ...(tool.progress ? [` ${figures.elbow} ${activityText(tool.progress, '处理中…')}`] : []), ]); contentLines = swarm ?? lastN(flatLines, maxLines).map((line) => clampWidthStart(line, maxWidth)); contentDim = true; } const action = activityText(pluginProgress?.action) || (runningTools.length === 1 ? toolDescStatic(runningTools[0]) : ''); if (runningTools.length === 1 && action === toolDescStatic(runningTools[0])) { contentLines = contentLines.filter(line => line !== clampWidthStart(` 当前正在:${action}`, maxWidth)); } const facts = [ ...(action ? [`当前动作:${action}`] : []), ...(activityText(pluginProgress?.nextAction) ? [`下一步:${activityText(pluginProgress?.nextAction)}`] : []), ...(activityText(pluginProgress?.summary) ? [`阶段结果:${activityText(pluginProgress?.summary)}`] : []), ...background.slice(0, 3).map(task => `子任务 · ${activityText(task.argsFriendly, '后台任务')}:${activityText(task.progress, '执行中')}`), ...(background.length > 3 ? [`另有 ${background.length - 3} 个后台子任务`] : []), ...Object.values(pluginProgress?.branches ?? {}).filter(branch => !branch.outcome).map(branch => `子流程 ${activityText(branch.name, '任务')}:${activityText(branch.message, '执行中')}`), ].map(line => clampWidthStart(line, maxWidth)); // A single available line belongs to the actual answer, not a stale plan. const factBudget = maxLines - (stage === 'streaming' && contentLines.length ? 1 : 0); const visibleFacts = facts.slice(0, factBudget); const space = maxLines - visibleFacts.length; contentLines = [...visibleFacts, ...(stage === 'streaming' ? lastN(contentLines, space) : contentLines.slice(0, space))]; return { statusLine: status, statusColor: stage === 'compacting' ? theme.plugin : theme.user, contentLines, contentDim, transientErrorLine, }; } export const LiveArea = React.memo(function LiveArea( props: LiveAreaProps, ): JSX.Element | null { const progressStage = props.progressStage === 'idle' && props.pluginProgress && !props.pluginProgress.completed ? 'tool_executing' : props.progressStage; // 计时起点:idle→非idle 那一刻记下,idle 清零。在 render 中惰性初始化 ref(幂等,安全)。 const startRef = useRef(null); if (progressStage === 'idle') { startRef.current = null; } else if (startRef.current === null) { startRef.current = Date.now(); } // 非 idle 时 ~150ms tick:强制 re-render,让 spinner/秒数在纯等待期也持续动。 const [, setTick] = useState(0); useEffect(() => { if (progressStage === 'idle') return; const timer = setInterval( () => setTick((t) => (t + 1) % 1_000_000), SPINNER_INTERVAL_MS, ); return () => clearInterval(timer); }, [progressStage]); // 不在 idle 直接 return:idle 但存在暂态错误时 buildLiveView 仍会返回一个 // 只含 transientErrorLine 的 view(让"已恢复/重试中"提示在步间隙也不闪没)。 const now = Date.now(); const elapsedSec = startRef.current ? Math.max(0, Math.floor((now - startRef.current) / 1000)) : 0; const frame = SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]; const view = buildLiveView({ ...props, frame, elapsedSec }); if (!view) return null; return ( {/* statusLine 为空串(idle+仅暂态错误)时不渲染状态行,避免空行占位 */} {view.statusLine.length > 0 && ( {view.statusLine} )} {view.contentLines.map((line, i) => ( {line.length > 0 ? line : ' '} ))} {/* 暂态错误行:黄色单行,状态行/内容区下方。重试中 = 黄;已恢复 = useChat 换成灰色文案(颜色统一黄,靠文案区分;保持 INV-1 已在 buildLiveView 钳宽)。 */} {view.transientErrorLine !== null && ( {view.transientErrorLine} )} ); });