import { useEffect, useMemo, useRef, useState } from 'react'; import { Sparkles, ChevronDown, ChevronRight, Brain, Zap } from 'lucide-react'; interface SkillSelectStreamingViewProps { text: string; thinkingText?: string; } /** * 从流式 JSON 文本里增量提取已识别的技能名(仅取**已闭合**的字符串项)。 * * LLM 输出形如 `{"selected_skills": ["skill-a", "skill-b", "skill-c"], "reason": "..."}`。 * 不等整段 JSON 解析完,逐字符扫描: * - 定位 `"selected_skills":\s*[` * - 在该位置后到 `]`(或文本末尾)之间逐个匹配 `"..."` * - 只取已闭合的字符串(结尾必须是 `"`),保证不显示正在打字的半截名字 */ function extractStreamingSkillNames(text: string): string[] { if (!text) return []; const keyMatch = text.match(/["']?selected_skills["']?\s*:\s*\[/); if (!keyMatch) return []; const start = keyMatch.index! + keyMatch[0].length; const rest = text.slice(start); const endIdx = rest.indexOf(']'); const arrBody = endIdx >= 0 ? rest.slice(0, endIdx) : rest; const names: string[] = []; const re = /"((?:[^"\\]|\\.)*)"/g; let m: RegExpExecArray | null; while ((m = re.exec(arrBody)) !== null) { const name = m[1].trim(); if (name) names.push(name); } return names; } /** * 从流式 JSON 文本里提取 `reason` 字段当前已输出的内容。 * * 和 skill name 不同,reason 是流式叙述文本,**未闭合也要展示**(带闪烁光标), * 让用户看到 LLM 正在解释选择理由。 */ function extractStreamingReason(text: string): { value: string; closed: boolean } { if (!text) return { value: '', closed: false }; // 匹配 "reason": "..." 直到下一个未转义的 " 或文本末尾 const m = text.match(/["']?reason["']?\s*:\s*"((?:[^"\\]|\\.)*?)("|$)/); if (!m) return { value: '', closed: false }; const raw = m[1]; const closed = m[2] === '"'; // 反转义常见序列 const value = raw .replace(/\\n/g, '\n') .replace(/\\t/g, '\t') .replace(/\\"/g, '"') .replace(/\\\\/g, '\\'); return { value, closed }; } export function SkillSelectStreamingView({ text, thinkingText }: SkillSelectStreamingViewProps) { const thinkRef = useRef(null); const [thinkOpen, setThinkOpen] = useState(true); // 增量解析:候选技能 + 选择原因 const streamingSkills = useMemo(() => extractStreamingSkillNames(text), [text]); const reason = useMemo(() => extractStreamingReason(text), [text]); useEffect(() => { if (thinkOpen && thinkRef.current) thinkRef.current.scrollTop = thinkRef.current.scrollHeight; }, [thinkingText, thinkOpen]); // 步骤预览始终渲染(挂载即显示),让父组件控制挂载时机; // 这样首个空 chunk 到达时用户就能看到"等待模型输出"占位 + 跳动光标 const showStepPreview = true; return (
{/* 思考过程(amber,可折叠) */} {thinkingText && (
{thinkOpen && (
              {thinkingText}
              {!text && (
                
              )}
            
)}
)} {/* 步骤预览(violet,与 SkillStepsCard 的"筛选相关技能"步骤同构) */} {showStepPreview && (
筛选相关技能 {streamingSkills.length > 0 && ( · 候选 {streamingSkills.length} 个(将按顺序使用) )} {[0, 1, 2].map((i) => ( ))}
{/* 已识别的候选技能 badges */} {streamingSkills.length > 0 && (
{streamingSkills.map((name, idx) => ( {name} ))}
)} {/* reason 实时文本:未闭合也展示(带光标),闭合后光标消失 */} {reason.value && (
原因: {reason.value} {!reason.closed && ( )}
)} {/* 还没出现任何 skill / reason 时给一个占位提示 */} {!streamingSkills.length && !reason.value && (
等待模型输出
)}
)}
); }