import { useEffect, useRef, useState, type ReactNode } from 'react' import { Brain, ChevronRight, CircleCheck, CircleDot, Database, FileCode, GitBranch, Hand, Sparkles, Table2, Terminal, Wrench, XCircle, } from 'lucide-react' import clsx from 'clsx' import { Spinner } from '../components/ui' import { parseQueryResult, type ResultTable as Table, type Step, type StepKind, } from './decode' /** * 助手流:一轮轮「你问什么 → 它做了什么 → 结果」。 * * 纯展示,不碰 store。画布右栏(360px)和问数据页(宽屏)用的是同一个组件, * 差别只在 dense 这个开关上——而不是做成"一个组件三种停靠模式":那要求同一个 * 组件实例出现在三个不同的 DOM 父节点里,React 里除非用 portal 否则不成立, * 硬做就会变成跨路由 unmount/remount,输入框草稿和展开状态全丢。 * * 步骤来自 decode.ts,这里只负责怎么画。两边读同一个解码结果,所以同一次运行 * 在画布和问数据页讲的是同一个故事。 */ export interface StreamTurn { id: string /** 用户说了什么。画布上的 Copilot 指令也走这个字段 */ question?: string phase: 'running' | 'waiting' | 'done' | 'error' /** 一句话进度,顶在最前面 */ status?: string steps: Step[] /** 还在流的思考(尚未成为 Step)。只有 Anthropic 系模型会有 */ thinking?: string output?: Record | null error?: string runId?: string /** formal / exploratory。出具横幅要据此标注"不进正式归档" */ runClass?: string /** 这一轮建出来的图,可展开看、可放到画布 */ graph?: any graphNote?: string } const ICONS: Record = { node: CircleDot, think: Brain, llm: Sparkles, query: Database, schema: Table2, tool: Wrench, code: Terminal, branch: GitBranch, human: Hand, issuance: FileCode, note: CircleDot, error: XCircle, lifecycle: CircleCheck, } export function AssistantStream({ turns, dense = false, empty, approvalsFor, onOpenGraph, footer, }: { turns: StreamTurn[] /** 窄栏模式:更紧的排版、表格少列 */ dense?: boolean /** 没有任何一轮时显示什么 */ empty?: ReactNode /** 这一轮要不要插审批卡——插槽而不是内建,因为不同页面接流的方式不同 */ approvalsFor?: (turn: StreamTurn) => ReactNode onOpenGraph?: (graph: any) => void footer?: ReactNode }) { const bottomRef = useRef(null) const lastPhase = turns[turns.length - 1]?.phase const lastCount = turns[turns.length - 1]?.steps.length useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' }) }, [turns.length, lastPhase, lastCount]) if (!turns.length && empty) { return
{empty}{footer}
} return (
{turns.map((turn) => ( ))}
{footer}
) } function TurnCard({ turn, dense, approvals, onOpenGraph }: { turn: StreamTurn; dense: boolean; approvals?: ReactNode onOpenGraph?: (graph: any) => void }) { const running = turn.phase === 'running' return (
{turn.question && ( // 宽屏走聊天气泡(右对齐、实心),窄栏里气泡会挤成一条竖带, // 改用左侧强调条——同样能一眼看出"这句是你说的",但不吃宽度
{turn.question}
)}
{running && } {turn.phase === 'waiting' && } {turn.phase === 'error' && } {turn.phase === 'error' ? turn.error : turn.status} {turn.runId && ( #{turn.runId.slice(0, 6)} )}
{/* 还在流的思考。这是等待期间唯一能看的东西——但只有 Anthropic 系 模型会产出,所以它是增强,主干是下面的步骤 */} {running && turn.thinking && } {!!turn.steps.length && (
)} {approvals} {turn.output && ( )} {turn.graph && ( )}
) } /** 思考的尾窗:只露最后几行并跟着滚,不然一大坨会把步骤挤到屏幕外。 */ function ThinkingTail({ text }: { text: string }) { const ref = useRef(null) useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight }, [text]) return (
{text}
) } function StepList({ steps, dense, depth = 0 }: { steps: Step[]; dense: boolean; depth?: number }) { return (
0 && 'ml-3 border-l pl-2.5')}> {steps.map((step) => )}
) } function StepRow({ step, dense, depth }: { step: Step; dense: boolean; depth: number }) { const [open, setOpen] = useState(false) const Icon = ICONS[step.kind] ?? CircleDot const result = step.result const expandable = !!(step.detail || result) const table = result ? parseQueryResult(result) : null // 失败要压过 kind:一条 lifecycle 跑挂了还画成打勾的"完成"图标, // 是把失败说成了成功 const failed = step.status === 'failed' || step.level === 'error' // "等你确认"不是"正在忙"。转圈说的是"你等着",而这里正相反 const waiting = step.status === 'waiting' const Glyph = failed ? XCircle : waiting ? Hand : Icon const color = failed ? 'var(--err)' : waiting ? 'var(--warn)' : step.level === 'warn' ? 'var(--warn)' : step.kind === 'think' ? 'var(--text-faint)' : step.status === 'running' ? 'var(--accent)' // 顶层节点是主干,子步骤是它的过程——靠明度分层,不然一屏全是同一个灰 : depth === 0 && (step.kind === 'node' || step.kind === 'lifecycle') ? 'var(--text)' : 'var(--text-dim)' return (
{open && (
{step.detail && (
              {step.detail}
            
)} {table ? : result && (
                {result.slice(0, 2000)}
              
)}
)} {!!step.children?.length && ( )}
) } /** 查询结果画成表格。一屏 JSON 谁也看不出名堂,表格能一眼看到形状。 */ function ResultTable({ table, dense }: { table: Table; dense: boolean }) { const maxCols = dense ? 4 : 8 const maxRows = 12 const cols = table.columns.slice(0, maxCols) const hiddenCols = table.columns.length - cols.length const rows = table.rows.slice(0, maxRows) return (
{cols.map((c) => ( ))} {hiddenCols > 0 && } {rows.map((row, i) => ( {row.slice(0, maxCols).map((cell, j) => ( ))} {hiddenCols > 0 && } ))}
{c}+{hiddenCols}
{cell == null ? null : String(cell)} …
{[ rows.length < table.rows.length ? `显示前 ${rows.length} / ${table.rows.length} 行` : `${table.rows.length} 行`, hiddenCols > 0 ? `显示前 ${cols.length} / ${table.columns.length} 列` : null, // 两种"不全"性质不同:一个是 guard 主动限的,一个是存预览时切的。 // 混成一句"已截断",用户没法判断该去调查询还是去看完整工件。 table.truncated ? '查询撞了行数上限,库里还有更多' : null, table.clipped ? '这里只是预览,实际取回的行数更多' : null, ].filter(Boolean).join(' · ')}
) } function Output({ output, dense, runClass }: { output: Record; dense: boolean; runClass?: string }) { // _issuance 这类下划线开头的是内部字段,不是给人看的成果。 // 空值也要滤掉:output 里留一个 {"result": ""} 很常见(图跑通了但出口 // 没接上),它会渲染出一条什么都没有的分隔线——用户只会以为界面坏了 const entries = Object.entries(output) .filter(([k, v]) => !k.startsWith('_') && !isBlank(v)) const issuance = (output as any)._issuance if (!entries.length && !issuance) return null return (
{issuance && } {entries.map(([key, value]) => (
{entries.length > 1 && (
{key}
)}
))}
) } const TEXT_CAP = 3000 function isBlank(v: unknown): boolean { if (v == null) return true if (typeof v === 'string') return !v.trim() if (Array.isArray(v)) return !v.length if (typeof v === 'object') return !Object.keys(v as object).length return false } /** * 一个成果值该怎么显示。 * * 取数流程的最终产物十有八九就是结果集本身,而它在 output 里是一个 * JSON 字符串(还常常是被再编码一层的)。直接当文本贴出来就是满屏 * `\"attribute01\", \"attribute02\"`——技术上没错,但没人能从里面看出 * "查到了什么"。能认出结果集就画成表格,认不出才退回文本。 */ function OutputValue({ value, dense }: { value: unknown; dense: boolean }) { const [full, setFull] = useState(false) const table = typeof value === 'string' ? parseQueryResult(value) : (value && typeof value === 'object' && Array.isArray((value as any).columns) && Array.isArray((value as any).rows) ? { columns: (value as any).columns, rows: (value as any).rows, truncated: !!(value as any).truncated } : null) if (table) return const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) // 不设上限的话,一次没走查询工具、直接把几千行塞进 output 的运行会 // 把整条流卡住——列表本来就没做虚拟化 const long = text.length > TEXT_CAP return (
{long && !full ? text.slice(0, TEXT_CAP) : text} {long && ( )}
) } const TIER_META: Record = { formal: { label: '正式出具', color: 'var(--ok)', hint: '指标齐全,叙述中所有数字均可回指口径卡' }, degraded: { label: '降档出具', color: 'var(--warn)', hint: '存在缺口,结论请对照下方声明使用' }, withheld: { label: '不予出具', color: 'var(--err)', hint: '必需指标缺失或数字无法溯源,本期结论不作数' }, } /** * 出具档位。全站唯一一份——画布助手栏、问数据页、运行详情都用它。 * * 数据取自 output._issuance 而不是 issuance 事件:事件里只有 tier / * missing_* / unmatched(计数),而 output 里那份还带着 matched_numbers、 * metrics_checked、calibers、unmatched_numbers[].token。拿事件当数据源, * 横幅会静默退化成"核对 0 个指标",比不显示更糟。 */ export function IssuanceBanner({ issuance, runClass }: { issuance: any; runClass?: string }) { const tier = String(issuance?.tier ?? '') if (!tier) return null const meta = TIER_META[tier] ?? { label: tier, color: 'var(--warn)', hint: '' } const unmatched: any[] = issuance?.unmatched_numbers ?? [] return (
⚖ {meta.label} {runClass === 'exploratory' && ( 探索性 · 不进正式归档 )} 回指 {issuance.matched_numbers ?? 0} 个数字 / 核对 {issuance.metrics_checked ?? 0} 个指标
{meta.hint &&
{meta.hint}
} {(issuance.calibers ?? []).map((c: any) => (
口径:{c.caliber} @ {c.version}
))} {!!issuance.missing_required?.length && (
缺必需指标:{issuance.missing_required.join('、')}
)} {!!issuance.missing_expected?.length && (
缺数据声明:{issuance.missing_expected.join('、')} 本期缺失
)} {!!unmatched.length && (
无法回指的数字:{unmatched.map((u: any) => u.token ?? u).join('、')}
)}
) } function GraphPeek({ graph, note, dense, onOpen }: { graph: any; note?: string; dense: boolean; onOpen?: (g: any) => void }) { const [open, setOpen] = useState(false) const nodes = graph?.nodes ?? [] return (
{onOpen && ( )}
{open && (
{note && (
{note}
)} {nodes.map((n: any, i: number) => (
{i + 1} {n.type} {n.data?.label || n.id}
))}
)}
) } /** 供各页面复用的空态骨架。 */ export function StreamEmpty({ icon, title, hint, children }: { icon: ReactNode; title: string; hint?: string; children?: ReactNode }) { return (
{icon}
{title}
{hint &&
{hint}
} {children &&
{children}
}
) }