import { useCallback, useEffect, useRef } from 'react' // 流式输出 hook:把完整文本按字符逐步吐出,模拟 AI 生成过程 export function useStreaming() { const timerRef = useRef(null) // 必须用 useCallback 固定引用:否则每次渲染都会生成新 stop, // 使依赖 [stop] 的卸载 effect 在每次渲染时触发清理,把进行中的 trace 定时器一并清掉 const stop = useCallback(() => { if (timerRef.current) window.clearInterval(timerRef.current) timerRef.current = null }, []) useEffect(() => () => { if (timerRef.current) window.clearInterval(timerRef.current) }, []) const stream = ( full: string, onTick: (partial: string, done: boolean) => void, speed = 12, ) => { if (timerRef.current) window.clearInterval(timerRef.current) let pos = 0 timerRef.current = window.setInterval(() => { pos = Math.min(full.length, pos + 3) onTick(full.slice(0, pos), pos >= full.length) if (pos >= full.length && timerRef.current) { window.clearInterval(timerRef.current) timerRef.current = null } }, speed) } return { stream, stop } } // 逐条展示 Skill 调用步骤,全部完成后回调 export function runSkillTrace( steps: string[], onStep: (done: string[]) => void, onComplete: () => void, interval = 700, ): () => void { let idx = 0 const done: string[] = [] const timer = window.setInterval(() => { if (idx < steps.length) { done.push(steps[idx++]) onStep([...done]) } else { window.clearInterval(timer) onComplete() } }, interval) return () => window.clearInterval(timer) }