import { useEffect, useRef, useState } from 'react' import { useSearchParams } from 'react-router' import { MessagesSquare, UserSearch, GitCompareArrows, Map, Send, X, Check, Loader2, CircuitBoard, } from 'lucide-react' import type { ChatMessage, ResearchConversation } from '../types' import { useStore, uid, nowStr } from '../lib/store' import { researchAnswer } from '../lib/ai' import { Markdown } from '../components/Markdown' import { useStreaming, runSkillTrace } from '../hooks/useStreaming' import { PrimaryButton } from '../components/ui-ext/AiButton' type Entry = 'customer' | 'competitor' | 'market' | null const ENTRIES = [ { key: 'customer' as Entry, icon: UserSearch, title: '查目标客户', desc: '这家公司做什么,采购过什么?', placeholder: '输入完整企业名称,如:某某水务集团有限公司' }, { key: 'competitor' as Entry, icon: GitCompareArrows, title: '查竞争对手', desc: '这家公司的业务和客户情况怎样?', placeholder: '输入竞争对手的完整名称,可补充关注业务' }, { key: 'market' as Entry, icon: Map, title: '查区域市场', desc: '某地区智慧水务需求如何?', placeholder: '如:调研华东地区近一年的智慧水务市场' }, ] interface LocalMsg extends ChatMessage { streaming?: boolean pendingTrace?: boolean } export function ResearchPage() { const { research, saveConversation } = useStore() const [convId, setConvId] = useState(null) const [messages, setMessages] = useState([]) const [title, setTitle] = useState('') const [entry, setEntry] = useState(null) const [input, setInput] = useState('') const [busy, setBusy] = useState(false) const scrollRef = useRef(null) const traceCancelRef = useRef<(() => void) | null>(null) // 新对话的 convId 在流式输出完成后才入库;入库前先记入待持久化集合,避免被“对话已删除”守卫误清 const pendingConvRef = useRef>(new Set()) const { stream, stop } = useStreaming() const [searchParams, setSearchParams] = useSearchParams() useEffect(() => { scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' }) }, [messages]) useEffect(() => () => { stop(); traceCancelRef.current?.() }, [stop]) const messagesRef = useRef([]) useEffect(() => { messagesRef.current = messages }, [messages]) const persist = (msgs: LocalMsg[], t: string, id: string | null): string => { const cid = id ?? uid('conv') const existing = research.find(c => c.id === cid) const conv: ResearchConversation = { id: cid, title: t || existing?.title || '未命名调研', createdAt: existing?.createdAt ?? nowStr(), messages: msgs.map(({ streaming: _s, pendingTrace: _p, ...m }) => m), } saveConversation(conv) return cid } const ask = (raw: string) => { const q = raw.trim() if (!q || busy) return setBusy(true) setInput('') const userMsg: LocalMsg = { role: 'user', content: q, time: nowStr() } const result = researchAnswer(q, entry) const assistantMsg: LocalMsg = { role: 'assistant', content: '', time: nowStr(), skillTrace: [], pendingTrace: true, } setMessages([...messages, userMsg, assistantMsg]) const newTitle = title || result.title if (!title) setTitle(newTitle) const cid = convId ?? uid('conv') if (!convId) setConvId(cid) pendingConvRef.current.add(cid) // 展示实际发生的 Skill 调用进展,再输出结果 traceCancelRef.current?.() traceCancelRef.current = runSkillTrace(result.skillTrace, doneSteps => { setMessages(m => { const arr = [...m] arr[arr.length - 1] = { ...arr[arr.length - 1], skillTrace: doneSteps, pendingTrace: true } return arr }) }, () => { stream(result.markdown, (partial, done) => { setMessages(m => { const arr = [...m] arr[arr.length - 1] = { ...arr[arr.length - 1], content: partial, streaming: !done, pendingTrace: false } return arr }) if (done) { setBusy(false) pendingConvRef.current.delete(cid) persist(messagesRef.current, newTitle, cid) } }) }) setEntry(null) } const openConversation = (c: ResearchConversation) => { stop(); traceCancelRef.current?.() setConvId(c.id) setTitle(c.title) setMessages(c.messages.map(m => ({ ...m }))) setBusy(false) } const newConversation = () => { stop(); traceCancelRef.current?.() setConvId(null); setTitle(''); setMessages([]); setBusy(false); setEntry(null) } // 左侧导航栏通过 URL 参数控制:?conv= 打开历史对话,?new=1 新建对话 useEffect(() => { const conv = searchParams.get('conv') const isNew = searchParams.get('new') if (!conv && !isNew) return if (conv) { const c = research.find(x => x.id === conv) if (c) openConversation(c) } else { newConversation() } setSearchParams({}, { replace: true }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchParams]) // 当前对话在左侧导航被删除时,重置为新对话(待持久化的新对话除外) useEffect(() => { if (convId && !pendingConvRef.current.has(convId) && !research.some(c => c.id === convId)) newConversation() // eslint-disable-next-line react-hooks/exhaustive-deps }, [research, convId]) return (
{/* 对话区 */}
{messages.length === 0 ? (

对话调研

{ENTRIES.map(e => ( ))}
) : (
{messages.map((m, i) => (
{m.role === 'user' ? (
{m.content}
) : (
{m.skillTrace && (
{m.pendingTrace ? : } Skill 调用进展
    {m.skillTrace.map((s, j) => (
  • {s}
  • ))}
)} {m.content ? : null} {m.time && !m.streaming &&
{m.time}
}
)}
))}
)}
{/* 输入区 */}
{entry && (
已选入口:{ENTRIES.find(e => e.key === entry)?.title}
)}