"use client"; import * as React from "react"; import { ArrowUpIcon, BotIcon, HistoryIcon, Loader2Icon, PlusIcon, SquareIcon, Trash2Icon, XIcon } from "lucide-react"; import { toast } from "sonner"; import { MentionTextarea } from "@/components/mention-textarea"; import { Transcript } from "@/components/transcript"; import { Button } from "@/components/ui/button"; import { InputGroup, InputGroupAddon, InputGroupButton } from "@/components/ui/input-group"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { api } from "@/lib/api"; import type { Activity, Conversation } from "@/lib/types"; function mergeActivities(oldItems: Activity[], incoming: Activity[]) { const byID = new Map(oldItems.map((item) => [item.seq, item])); for (const item of incoming) byID.set(item.seq, item); return [...byID.values()].sort((a, b) => a.seq - b.seq); } export function FindingAutoChat({ findingId, findingTitle, agentKey = "auto", agentLabel = "Auto Agent", promptPlaceholder = "询问这个漏洞…", modal = false, initialConversationId, open, onOpenChange, }: { findingId: string; findingTitle: string; agentKey?: string; agentLabel?: string; promptPlaceholder?: string; modal?: boolean; initialConversationId?: number; open: boolean; onOpenChange: (open: boolean) => void; }) { const [conversation, setConversation] = React.useState(null); const [messages, setMessages] = React.useState([]); const [input, setInput] = React.useState(""); const [running, setRunning] = React.useState(false); const [loading, setLoading] = React.useState(false); const [sending, setSending] = React.useState(false); const [stopping, setStopping] = React.useState(false); const [manualEmpty, setManualEmpty] = React.useState(false); const [historyOpen, setHistoryOpen] = React.useState(false); const [history, setHistory] = React.useState([]); const cursor = React.useRef(0); const chatViewportRef = React.useRef(null); const safeTitle = findingTitle.replace(/[\[\]\r\n]/g, " ").trim().slice(0, 100); const storageKey = `artex.finding.${agentKey}-conversation.${findingId}`; const createConversation = React.useCallback(async () => { setManualEmpty(false); setMessages([]); setRunning(false); setLoading(true); try { const created = await api.createConversation(agentKey, `漏洞 #${findingId} · ${safeTitle}`); window.localStorage.setItem(storageKey, String(created.id)); setConversation(created); } catch (error) { toast.error(`创建 Auto 对话失败:${(error as Error).message}`); } finally { setLoading(false); } }, [agentKey, findingId, safeTitle, storageKey]); React.useEffect(() => { if (!open || conversation || manualEmpty) return; if (initialConversationId && initialConversationId > 0) { setConversation({ id: initialConversationId, agent_key: agentKey, title: `漏洞 #${findingId} · ${safeTitle}`, created_at: "", updated_at: "" }); return; } const storedID = agentKey === "auto" ? Number(window.localStorage.getItem(storageKey)) : 0; if (Number.isSafeInteger(storedID) && storedID > 0) { setConversation({ id: storedID, agent_key: agentKey, title: `漏洞 #${findingId} · ${safeTitle}`, created_at: "", updated_at: "", }); return; } void createConversation(); }, [conversation, createConversation, initialConversationId, manualEmpty, open, safeTitle, storageKey]); React.useEffect(() => { if (!historyOpen && !running) return; let live = true; let timer: ReturnType; const load = async () => { try { const items = await api.conversations(); if (!live) return; const prefix = `漏洞 #${findingId} ·`; setHistory(items.filter((item) => item.agent_key === agentKey && item.title.startsWith(prefix))); } catch { if (live && historyOpen) setHistory([]); } finally { if (live && (historyOpen || running)) timer = setTimeout(() => void load(), 2000); } }; void load(); return () => { live = false; clearTimeout(timer); }; }, [agentKey, findingId, historyOpen, running]); React.useEffect(() => { if (!open || !conversation) return; let live = true; cursor.current = 0; api .conversationHistory(conversation.id, 0, 200) .then((page) => { if (!live) return; setMessages((current) => mergeActivities(current, page.items)); cursor.current = page.cursor; setRunning(page.running); }) .catch((error: Error) => { if (error.message.includes("404")) { window.localStorage.removeItem(storageKey); setConversation(null); } }); return () => { live = false; }; }, [conversation, open, storageKey]); React.useEffect(() => { if (!open || !conversation || loading || !messages.length) return; const viewport = chatViewportRef.current; if (!viewport) return; const key = `artex.conversation-scroll.${conversation.id}`; const saved = window.sessionStorage.getItem(key); requestAnimationFrame(() => { if (saved != null) viewport.scrollTop = Number(saved) || 0; else viewport.scrollTop = viewport.scrollHeight; }); }, [conversation, loading, messages.length, open]); React.useEffect(() => { if (!open || !conversation || !running) return; let live = true; let timer: ReturnType; const poll = async () => { try { const page = await api.conversationMessages(conversation.id, cursor.current); if (!live) return; if (page.items.length) setMessages((current) => mergeActivities(current, page.items)); cursor.current = Math.max(cursor.current, page.cursor); setRunning(page.running); if (page.running) timer = setTimeout(() => void poll(), 1000); } catch { if (live) timer = setTimeout(() => void poll(), 1500); } }; void poll(); return () => { live = false; clearTimeout(timer); }; }, [conversation, open, running]); const send = async () => { const question = input.trim(); if (!conversation || !question || sending || running) return; setSending(true); setInput(""); const firstQuestion = !messages.some((item) => item.kind === "user"); const message = firstQuestion ? `@[漏洞#${findingId} ${safeTitle}] ${question}` : question; try { await api.sendConversationMessage(conversation.id, message); setRunning(true); } catch (error) { setInput(question); toast.error(`发送失败:${(error as Error).message}`); } finally { setSending(false); } }; const selectHistory = (item: Conversation) => { setManualEmpty(false); setMessages([]); setRunning(false); setConversation(item); window.localStorage.setItem(storageKey, String(item.id)); setHistoryOpen(false); }; const deleteConversation = async () => { if (!conversation) return; try { await api.deleteConversation(conversation.id); window.localStorage.removeItem(storageKey); setConversation(null); setMessages([]); setRunning(false); setManualEmpty(true); setHistory((items) => items.filter((item) => item.id !== conversation.id)); toast.success("已删除当前漏洞对话"); } catch (error) { toast.error(`删除对话失败:${(error as Error).message}`); } }; const stop = async () => { if (!conversation || stopping || !running) return; setStopping(true); try { await api.stopConversation(conversation.id); } catch (error) { toast.error(`停止失败:${(error as Error).message}`); } finally { setStopping(false); } }; if (!open) return null; return (

{agentLabel} {running && 运行中}

漏洞 #{findingId} · {safeTitle}

漏洞历史对话

{history.length ? history.map((item) => ( )) :

暂无历史对话

}
{ if (conversation) window.sessionStorage.setItem(`artex.conversation-scroll.${conversation.id}`, String(event.currentTarget.scrollTop)); }} className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto p-3" >
{loading ? (
正在创建 Auto 对话…
) : messages.length ? ( api.conversationMsgDetail(conversation?.id ?? 0, seq)} /> ) : (

{conversation ? "请输入你想了解的内容。" : "点击上方 + 新建漏洞对话。"}

)}
{ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void send(); } }} /> 将自动引用当前漏洞 {running ? ( void stop()} disabled={stopping} aria-label="停止 Auto Agent"> ) : ( void send()} disabled={!input.trim() || sending}> )}
); }