"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, open, onOpenChange, }: { findingId: string; findingTitle: string; 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 safeTitle = findingTitle.replace(/[\[\]\r\n]/g, " ").trim().slice(0, 100); const storageKey = `artex.finding.auto-conversation.${findingId}`; const createConversation = React.useCallback(async () => { setManualEmpty(false); setMessages([]); setRunning(false); setLoading(true); try { const created = await api.createConversation("auto", `漏洞 #${findingId} · ${safeTitle}`); window.localStorage.setItem(storageKey, String(created.id)); setConversation(created); } catch (error) { toast.error(`创建 Auto 对话失败:${(error as Error).message}`); } finally { setLoading(false); } }, [findingId, safeTitle, storageKey]); React.useEffect(() => { if (!open || conversation || manualEmpty) return; const storedID = Number(window.localStorage.getItem(storageKey)); if (Number.isSafeInteger(storedID) && storedID > 0) { setConversation({ id: storedID, agent_key: "auto", title: `漏洞 #${findingId} · ${safeTitle}`, created_at: "", updated_at: "", }); return; } void createConversation(); }, [conversation, createConversation, 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 === "auto" && 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); }; }, [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 || !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 (

Auto Agent {running && 运行中}

漏洞 #{findingId} · {safeTitle}

漏洞历史对话

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

暂无历史对话

}
{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}> )}
); }