"use client"; import * as React from "react"; import { ArrowUpIcon, Bot, ChevronDownIcon, ChevronRightIcon, ListChecksIcon, Loader2Icon, MoreHorizontalIcon, PaperclipIcon, PencilIcon, PinIcon, PinOffIcon, PlusIcon, Square, Trash2Icon, XIcon, ZapIcon, } from "lucide-react"; import { toast } from "sonner"; import { MentionTextarea } from "@/components/mention-textarea"; import { SideQuestionButton, SideQuestionWorkspace } from "@/components/side-question-workspace"; import { TodoPopover } from "@/components/todo-popover"; import { ApprovalExecutionFocus, useApprovalFocus, useApprovalHistory } from "@/components/approval-execution-focus"; import { Transcript } from "@/components/transcript"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Spinner } from "@/components/ui/spinner"; import { useSideQuestions } from "@/hooks/use-side-questions"; import { mergeActivities } from "@/lib/activity-merge"; import { api } from "@/lib/api"; import { shouldSubmitOnKey, useChatSendMode } from "@/lib/chat-send-mode"; import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.client"; import { isBtwCommand } from "@/lib/side-questions"; import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types"; import { cn } from "@/lib/utils"; // fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx). function fmtBytes(n: number): string { if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MB`; if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KB`; return `${n} B`; } // fmtTokens renders a compact token count (1234 → 1.2k, 2_000_000 → 2M). function fmtTokens(n: number): string { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`; if (n >= 1000) return `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k`; return String(n); } // fmtDuration renders an elapsed milliseconds span compactly (90s → 1m30s). function fmtDuration(ms: number): string { const s = Math.floor(ms / 1000); if (s < 60) return `${s}s`; const m = Math.floor(s / 60); if (m < 60) return `${m}m${String(s % 60).padStart(2, "0")}s`; const h = Math.floor(m / 60); return `${h}h${String(m % 60).padStart(2, "0")}m`; } // HISTORY_PAGE is how many steps one history page loads: the latest page on open, // then one more page each time the user scrolls to the top. Kept modest so a long // thread stays snappy (only ~a page of rows is in the DOM until you scroll up). const HISTORY_PAGE = 200; const CONVERSATION_LIST_PAGE = 100; // Which agent groups the user has collapsed in the left rail. Persisted so the // rail looks the same after a reload; unknown keys are harmless (a deleted agent // simply never renders a group again). const COLLAPSED_AGENTS_KEY = "artex.chat.collapsed-agents"; function conversationIsPinned(conversation: Conversation): boolean { return conversation.pinned ?? Boolean(conversation.pinned_at); } // AgentGroup is one collapsible section of the left rail: all unpinned // conversations of a single agent, newest activity first. interface AgentGroup { key: string; name: string; conversations: Conversation[]; runningCount: number; } // groupByAgent buckets conversations by agent, preserving the incoming order // both inside a group and across groups. The server already sorts by updated_at // DESC, so first-appearance order == most-recently-active group first. function groupByAgent(conversations: Conversation[], agentByKey: Map): AgentGroup[] { const groups = new Map(); for (const conversation of conversations) { let group = groups.get(conversation.agent_key); if (!group) { group = { key: conversation.agent_key, name: agentByKey.get(conversation.agent_key)?.name || conversation.agent_key, conversations: [], runningCount: 0, }; groups.set(conversation.agent_key, group); } group.conversations.push(conversation); if (conversation.running) group.runningCount++; } return [...groups.values()]; } // LiveBadge is the small pulsing "实时" chip reused from the task's main-agent // console — shown while a turn is streaming. function LiveBadge() { return ( 实时 ); } // Composer is the shared bottom input (textarea grows to a cap, Enter sends, // Shift+Enter newlines) — the same affordance across DraftChat and ChatView. function Composer({ value, onChange, onSend, disabled, placeholder, leftSlot, running, onStop, stopDisabled, attachments, onPickFiles, onRemoveAttachment, uploading, allowBtw, }: { value: string; onChange: (v: string) => void; onSend: () => void; disabled: boolean; placeholder: string; leftSlot?: React.ReactNode; running?: boolean; onStop?: () => void; stopDisabled?: boolean; // 方式1 文件上传:传了 onPickFiles 才显示回形针按钮 + 附件 chip 预览。 attachments?: ChatAttachment[]; onPickFiles?: (files: FileList | null) => void; onRemoveAttachment?: (path: string) => void; uploading?: boolean; allowBtw?: boolean; }) { const fileInputRef = React.useRef(null); const atts = attachments ?? []; // 发送键位由系统设置决定(localStorage),默认 Enter 发送。 const sendMode = useChatSendMode(); function onKeyDown(e: React.KeyboardEvent) { if (!shouldSubmitOnKey(e, sendMode)) return; e.preventDefault(); onSend(); } return (
{atts.length > 0 && (
{atts.map((a) => (
{a.name} {fmtBytes(a.size)} {onRemoveAttachment && ( )}
))}
)}
{leftSlot ?
{leftSlot}
: null} {onPickFiles && ( <> { onPickFiles(e.target.files); e.target.value = ""; // allow re-picking the same file }} /> )} {running && allowBtw && isBtwCommand(value) && ( )} {running ? ( // while a run is in flight the send button becomes a stop button — // aborts just this session (the trigger queue keeps going). ) : ( )}
); } // LLMProfileRow shows the active LLM config below the composer and lets the user // switch it via a Popover. `selected` is the profile id or null for default. function LLMProfileRow({ profiles, selected, onChange, disabled, rightSlot, }: { profiles: LLMProfile[]; selected: number | null; onChange: (id: number | null) => void; disabled?: boolean; rightSlot?: React.ReactNode; }) { const [open, setOpen] = React.useState(false); const activeDefault = profiles.find((p) => p.is_default); const current = selected != null ? profiles.find((p) => Number(p.id) === selected) : null; const label = current ? current.name : `默认${activeDefault ? `(${activeDefault.name})` : ""}`; return (
{label}

选择 LLM 配置

{/* default option */} {profiles.map((p) => ( ))}
{rightSlot}
); } // DraftChat is the default right-pane view: a fresh chat (agent picker in the // header, centered empty state, composer) with NO conversation created yet. The // conversation is created lazily on the first send (ChatGPT-style), then the // parent switches to the real ChatView. function DraftChat({ agents, profiles, onStarted, }: { agents: Agent[]; profiles: LLMProfile[]; onStarted: (c: Conversation, pending?: { input?: string; attachments?: ChatAttachment[] }) => void; }) { const [agentKey, setAgentKey] = React.useState(""); const [llmProfileId, setLlmProfileId] = React.useState(null); const [input, setInput] = React.useState(""); const [sending, setSending] = React.useState(false); const [uploading, setUploading] = React.useState(false); // default the agent to Auto once agents load. React.useEffect(() => { if (!agentKey && agents.some((a) => a.key === "auto")) setAgentKey("auto"); }, [agentKey, agents]); const agent = agents.find((a) => a.key === agentKey); async function send() { const msg = input.trim(); if (!msg || !agentKey || sending) return; setSending(true); try { const c = await api.createConversation(agentKey, "", llmProfileId); await api.sendConversationMessage(c.id, msg); onStarted(c); } catch (e) { toast.error("发送失败:" + (e as Error).message); setSending(false); } } // Attachments need a conversation to own the uploads dir (sessions/conv-/), // and a draft has none yet — so picking a file CREATES the conversation, uploads // into it, then hands off to ChatView carrying the typed text + attachments (the // user sends from there). Mirrors the task main-agent console's upload, adapted to // the ChatGPT-style lazy-create flow. async function pickFiles(files: FileList | null) { if (!files || files.length === 0 || !agentKey || uploading || sending) return; setUploading(true); try { const c = await api.createConversation(agentKey, "", llmProfileId); const r = await api.chatUpload("session", `conv-${c.id}`, Array.from(files)); onStarted(c, { input, attachments: r.attachments }); } catch (e) { toast.error("上传失败:" + (e as Error).message); setUploading(false); } } const agentPicker = ( ); return ( <> {/* empty / landing state fills the panel */}
开始和「{agent?.name ?? "Agent"}」对话
{agent?.description &&

{agent.description}

}
); } // ChatView is the right pane for one conversation — mirrors the task detail's // main-agent console: header with agent + live badge + token/duration meta, a // scroll-stick transcript (chat mode), and the composer. function ChatView({ conv, agents, profiles, initial, onTitleMaybeChanged, onConvUpdated, }: { conv: Conversation; agents: Agent[]; profiles: LLMProfile[]; // pending text + already-uploaded attachments handed off from a draft that // created this conversation via the paperclip (consumed once, on mount). initial?: { input?: string; attachments?: ChatAttachment[] }; onTitleMaybeChanged: () => void; onConvUpdated: () => void; }) { const approvalFocus = useApprovalFocus({ conversationId: conv.id }); const [messages, setMessages] = React.useState([]); const [running, setRunning] = React.useState(false); const [input, setInput] = React.useState(initial?.input ?? ""); const [sending, setSending] = React.useState(false); const [stopping, setStopping] = React.useState(false); // 方式1 文件上传:已上传的附件(落到 sessions/conv-/uploads/),随下条消息一起发。 const [attachments, setAttachments] = React.useState(initial?.attachments ?? []); const [uploading, setUploading] = React.useState(false); const cursorRef = React.useRef(0); // newest loaded id — incremental-tail anchor const earliestRef = React.useRef(0); // earliest loaded id — reverse-pagination anchor const hasMoreRef = React.useRef(false); // older history remains above the loaded window const loadingMoreRef = React.useRef(false); // guard: one scroll-up load at a time const [historyLoaded, setHistoryLoaded] = React.useState(false); const [hasMore, setHasMore] = React.useState(false); // drives the "load earlier" hint const agent = agents.find((a) => a.key === conv.agent_key); const currentProfileId = conv.llm_profile_id ?? null; const side = useSideQuestions(`/api/conversations/${conv.id}`); async function changeProfile(id: number | null) { try { await api.updateConversationProfile(conv.id, id); onConvUpdated(); } catch (e) { toast.error("切换 LLM 失败:" + (e as Error).message); } } // conversation-scoped detail fetcher for the reused Transcript renderer. const fetchDetail = React.useCallback((seq: number) => api.conversationMsgDetail(conv.id, seq), [conv.id]); // seq of the most-recent TodoWrite tool call (for the Todo popover); null if none. const latestTodoSeq = React.useMemo(() => { for (let i = messages.length - 1; i >= 0; i--) { const a = messages[i]; if (a.kind === "tool_use" && a.tool === "TodoWrite") return a.seq; } return null; }, [messages]); // reset + load whenever the selected conversation changes. Load only the LATEST // page on open — a long thread's final answer sits at the very end, so the newest // page shows it immediately (issue #3: opening/refresh used to load the oldest // page, so the completed result was missing until another message advanced the // cursor). Older history streams in on scroll-up (loadEarlier below). React.useEffect(() => { cursorRef.current = 0; earliestRef.current = 0; hasMoreRef.current = false; setHasMore(false); setMessages([]); setHistoryLoaded(false); setRunning(false); let live = true; api .conversationHistory(conv.id, 0, HISTORY_PAGE) .then((r) => { if (!live) return; setMessages((current) => mergeActivities(r.items, current)); cursorRef.current = Math.max(cursorRef.current, r.cursor); earliestRef.current = r.items.length ? r.items[0].seq : 0; hasMoreRef.current = r.hasMore; setHasMore(r.hasMore); setRunning((current) => current || r.running); setHistoryLoaded(true); }) .catch(() => { // A source link can retry history through its locator; ordinary chats // retain the existing usable empty state on a transient failure. if (live) setHistoryLoaded(true); }); return () => { live = false; }; }, [conv.id]); // A trigger or another tab may start a turn while this conversation is open. // A false list snapshot must not stop the tail before its final messages load. React.useEffect(() => { if (conv.running) setRunning(true); }, [conv.running]); // poll while a turn is running: pull new steps after the cursor. React.useEffect(() => { if (!running) return; let live = true; let timer: ReturnType; const tick = async () => { let keepPolling = true; try { const r = await api.conversationMessages(conv.id, cursorRef.current); if (!live) return; if (r.items.length) { setMessages((prev) => mergeActivities(prev, r.items)); } cursorRef.current = Math.max(cursorRef.current, r.cursor); keepPolling = r.running; setRunning(r.running); if (!r.running) onTitleMaybeChanged(); // first-turn auto-title landed } catch { /* transient — keep polling */ } finally { // Slow responses must not overlap another poll with the same cursor. if (live && keepPolling) timer = setTimeout(() => void tick(), 1000); } }; void tick(); return () => { live = false; clearTimeout(timer); }; }, [running, conv.id, onTitleMaybeChanged]); const loadFocusPage = React.useCallback((before: number) => api.conversationHistory(conv.id, before, HISTORY_PAGE), [conv.id]); const mergeFocusPage = React.useCallback((page: { items: Activity[]; hasMore: boolean }) => { setMessages((prev) => mergeActivities(page.items, prev)); earliestRef.current = page.items[0]?.seq ?? earliestRef.current; hasMoreRef.current = page.hasMore; setHasMore(page.hasMore); }, []); const focusHistory = useApprovalHistory(approvalFocus.state?.source, historyLoaded, messages, loadFocusPage, mergeFocusPage); // ---- transcript auto-scroll (open → bottom; stick to bottom unless scrolled up) ---- const contentRef = React.useRef(null); const atBottomRef = React.useRef(true); const viewport = React.useCallback( () => (contentRef.current?.closest('[data-slot="scroll-area-viewport"]') as HTMLElement | null) ?? null, [], ); // Scroll-up loads one older page and prepends it, preserving the visual position // so the view doesn't jump (record height/offset before, restore the delta after). const loadEarlier = React.useCallback(async () => { if (loadingMoreRef.current || !hasMoreRef.current) return; const vp = viewport(); if (!vp) return; loadingMoreRef.current = true; const prevH = vp.scrollHeight; const prevTop = vp.scrollTop; try { const r = await api.conversationHistory(conv.id, earliestRef.current, HISTORY_PAGE); if (r.items.length) { setMessages((prev) => mergeActivities(r.items, prev)); earliestRef.current = r.items[0].seq; } hasMoreRef.current = r.hasMore; setHasMore(r.hasMore); requestAnimationFrame(() => { const v = viewport(); if (v) v.scrollTop = prevTop + (v.scrollHeight - prevH); }); } catch { /* transient — a later scroll retries */ } finally { loadingMoreRef.current = false; } }, [conv.id, viewport]); React.useEffect(() => { const vp = viewport(); if (!vp) return; const onScroll = () => { if (approvalFocus.state && !focusHistory.ready) return; atBottomRef.current = vp.scrollTop + vp.clientHeight >= vp.scrollHeight - 60; if (vp.scrollTop <= 80) void loadEarlier(); // near top → pull an older page }; vp.addEventListener("scroll", onScroll, { passive: true }); return () => vp.removeEventListener("scroll", onScroll); }, [viewport, loadEarlier, approvalFocus.state, focusHistory.ready]); // open/switch a conversation → jump to the latest (bottom) // biome-ignore lint/correctness/useExhaustiveDependencies: changing conversations intentionally retriggers the scroll reset. React.useLayoutEffect(() => { const vp = viewport(); if (vp) { vp.scrollTop = vp.scrollHeight; atBottomRef.current = true; } }, [conv.id, viewport]); // new activity → stick to bottom only if the user is already pinned there // biome-ignore lint/correctness/useExhaustiveDependencies: message and running changes intentionally retrigger bottom anchoring. React.useLayoutEffect(() => { if (approvalFocus.state || !atBottomRef.current) return; const vp = viewport(); if (vp) vp.scrollTop = vp.scrollHeight; }, [messages, running, viewport, approvalFocus.state]); // Per-conversation token total, live — same accounting as the main-agent // console: completed runs' `result` sum + the in-progress run's latest `usage`. const tokenTotal = React.useMemo(() => { let i = 0, o = 0, cr = 0; let li = 0, lo = 0, lcr = 0; let turns = 0; // agent 循环轮次 = 模型调用次数(每次一条 kind='usage') for (const a of messages) { if (a.kind === "result") { i += a.input_tokens ?? 0; o += a.output_tokens ?? 0; cr += a.cache_read_tokens ?? 0; li = lo = lcr = 0; } else if (a.kind === "usage") { turns += 1; li = a.input_tokens ?? 0; lo = a.output_tokens ?? 0; lcr = a.cache_read_tokens ?? 0; } } const I = i + li, O = o + lo, CR = cr + lcr; return { i: I, o: O, cr: CR, turns, any: I + O + CR > 0 }; }, [messages]); // pickFiles uploads into this conversation's session dir (sessions/conv-/ // uploads/) and queues the returned metadata to send with the next message. async function pickFiles(files: FileList | null) { if (!files || files.length === 0) return; setUploading(true); try { const r = await api.chatUpload("session", `conv-${conv.id}`, Array.from(files)); setAttachments((prev) => [...prev, ...r.attachments]); } catch (e) { toast.error("上传失败:" + (e as Error).message); } finally { setUploading(false); } } async function send() { const msg = input.trim(); const atts = attachments; if (side.handleCommand(msg, () => setInput(""))) return; if ((!msg && atts.length === 0) || sending || running) return; setSending(true); setInput(""); setAttachments([]); try { await api.sendConversationMessage(conv.id, msg, atts.length ? atts : undefined); // The live loop pulls the persisted human turn immediately. Sharing that // fetch avoids racing a separate post-send request against the poller. setRunning(true); } catch (e) { toast.error("发送失败:" + (e as Error).message); setInput(msg); // restore so the user doesn't lose their text setAttachments(atts); // and their attachments } finally { setSending(false); } } // stop aborts the in-flight run for this conversation. running flips to false on // the next 1s poll once the backend unwinds the agent; the trigger queue is not // affected — the agent's next queued fire still starts. async function stop() { if (stopping) return; setStopping(true); try { await api.stopConversation(conv.id); } catch (e) { toast.error("停止失败:" + (e as Error).message); } finally { setStopping(false); } } return ( {/* header: which agent + live + token meta */}
{agent?.name ?? conv.agent_key} {conv.agent_key} {agent && !agent.builtin && ( 自定义 )} {agent?.description && ( {agent.description} )} {running && }
{tokenTotal.turns > 0 && ( {tokenTotal.turns} 轮 )} {tokenTotal.any && ( input {fmtTokens(tokenTotal.i)} · cache {fmtTokens(tokenTotal.cr)} · output {fmtTokens(tokenTotal.o)} )}
{/* messages */}
{messages.length === 0 && !running ? (
开始和「{agent?.name ?? conv.agent_key}」对话
) : ( <> {hasMore && (
向上滚动加载更早的消息…
)} )}
setAttachments((p) => p.filter((x) => x.path !== path))} uploading={uploading} /> } />
); } // ConversationItem is one row in the left rail: title, agent subtitle, inline // rename, pin marker, and a compact action menu. Rows nested under an agent // group drop the agent subtitle (showAgent=false) — the header already says it. const ConversationItem = React.memo(function ConversationItem({ conv, agent, showAgent = true, active, renaming, renameText, onSelect, onStartRename, onRenameText, onCommitRename, onCancelRename, onTogglePinned, onDelete, selectionMode, selectedForDelete, onSelectedForDeleteChange, }: { conv: Conversation; agent?: Agent; showAgent?: boolean; active: boolean; renaming: boolean; renameText: string; onSelect: (id: number) => void; onStartRename: (conversation: Conversation) => void; onRenameText: (v: string) => void; onCommitRename: (id: number, title: string) => void; onCancelRename: () => void; onTogglePinned: (conversation: Conversation) => void; onDelete: (id: number) => void; selectionMode: boolean; selectedForDelete: boolean; onSelectedForDeleteChange: (id: number, checked: boolean) => void; }) { const [deleteOpen, setDeleteOpen] = React.useState(false); const renameInputRef = React.useRef(null); const cancelRenameRef = React.useRef(false); const pinned = conversationIsPinned(conv); React.useEffect(() => { if (!renaming) return; cancelRenameRef.current = false; renameInputRef.current?.focus(); renameInputRef.current?.select(); }, [renaming]); return (
{selectionMode && ( onSelectedForDeleteChange(conv.id, checked === true)} aria-label={`选择对话「${conv.title || "新对话"}」`} className="ml-1 shrink-0" /> )} {renaming ? ( onRenameText(e.target.value)} onBlur={() => { if (!cancelRenameRef.current) onCommitRename(conv.id, renameText); }} onKeyDown={(e) => { if (e.key === "Enter") onCommitRename(conv.id, renameText); if (e.key === "Escape") { e.preventDefault(); cancelRenameRef.current = true; onCancelRename(); } }} className="border-input bg-background min-w-0 flex-1 rounded-md border px-2 py-1 text-sm" /> ) : ( )} onStartRename(conv)}> 重命名 onTogglePinned(conv)}> {pinned ? : } {pinned ? "取消置顶" : "置顶"} setDeleteOpen(true)}> 删除 删除对话「{conv.title || "新对话"}」? 此操作不可撤销。 取消 onDelete(conv.id)}>删除
); }); // AgentGroupHeader is the sticky, clickable divider above one agent's rows: // collapse chevron, agent name, a running marker, and the row count. function AgentGroupHeader({ group, collapsed, hasActive, onToggle, }: { group: AgentGroup; collapsed: boolean; hasActive: boolean; onToggle: (key: string) => void; }) { return ( ); } export default function ChatPage() { const [agents, setAgents] = React.useState([]); const [profiles, setProfiles] = React.useState([]); const [convs, setConvs] = React.useState([]); const [agentFilter, setAgentFilter] = React.useState(null); const [selectedId, setSelectedId] = React.useState(null); const [sourceRequested, setSourceRequested] = React.useState(false); const [convsLoaded, setConvsLoaded] = React.useState(false); const selectConversation = React.useCallback((id: number | null) => { if (id !== selectedId) { const url = new URL(window.location.href); url.searchParams.delete("approval"); setSourceRequested(false); window.history.replaceState(null, "", url); } setSelectedId(id); }, [selectedId]); const [renamingId, setRenamingId] = React.useState(null); const [renameText, setRenameText] = React.useState(""); const [selectedConversationIds, setSelectedConversationIds] = React.useState>(() => new Set()); // selectionMode gates the multi-select UI: off by default (clean list, no // checkboxes); the header "多选" button turns it on, "完成" turns it off and // clears the selection. const [selectionMode, setSelectionMode] = React.useState(false); const [bulkDeleteOpen, setBulkDeleteOpen] = React.useState(false); const [bulkDeleting, setBulkDeleting] = React.useState(false); const [visibleConversationCount, setVisibleConversationCount] = React.useState(CONVERSATION_LIST_PAGE); // Collapsed agent groups. Hydrated from localStorage after mount (not a lazy // useState init) so the server and client render the same first pass. const [collapsedAgents, setCollapsedAgents] = React.useState>(() => new Set()); // Pending text + uploaded attachments handed off from a draft that created a // conversation via the paperclip, keyed by the new conversation id (consumed once // by ChatView on mount; ids never repeat, so leftover entries are harmless). const [pendingByConv, setPendingByConv] = React.useState< Record >({}); const conversationListSeq = React.useRef(0); const reloadConvs = React.useCallback(async () => { const seq = ++conversationListSeq.current; try { const items = await api.conversations(); if (seq === conversationListSeq.current) { setConvs(items); setConvsLoaded(true); } } catch { // Preserve the selected transcript and list on a transient poll failure. } }, []); React.useEffect(() => { api .agents() .then(setAgents) .catch(() => { /* Agent metadata is optional for rendering an existing conversation. */ }); api .llmProfiles() .then(setProfiles) .catch(() => { /* The conversation remains usable without profile labels. */ }); }, []); // One list poll supplies runtime state for all sidebar rows, including the // unselected ones. Await completion so slow requests do not overlap. React.useEffect(() => { let disposed = false; let timer: ReturnType; async function poll() { await reloadConvs(); if (!disposed) timer = setTimeout(() => void poll(), 2000); } void poll(); return () => { disposed = true; conversationListSeq.current++; clearTimeout(timer); }; }, [reloadConvs]); React.useEffect(() => { setSelectedConversationIds((current) => { if (current.size === 0) return current; const live = new Set(convs.map((conversation) => conversation.id)); const next = new Set([...current].filter((id) => live.has(id))); return next.size === current.size ? current : next; }); }, [convs]); React.useEffect(() => { const raw = getLocalStorageValue(COLLAPSED_AGENTS_KEY); if (!raw) return; try { const keys = JSON.parse(raw); if (Array.isArray(keys)) setCollapsedAgents(new Set(keys.filter((key): key is string => typeof key === "string"))); } catch { // Corrupted entry → start with everything expanded. } }, []); const toggleAgentCollapsed = React.useCallback((key: string) => { setCollapsedAgents((current) => { const next = new Set(current); if (!next.delete(key)) next.add(key); setLocalStorageValue(COLLAPSED_AGENTS_KEY, JSON.stringify([...next])); return next; }); }, []); // Restore the open conversation from the URL (?c=) on mount, so a refresh // returns to the same thread instead of the empty draft view. Runs after // hydration (not a lazy useState init) to avoid a server/client mismatch. React.useEffect(() => { const params = new URLSearchParams(window.location.search); setSourceRequested(params.has("approval")); const c = params.get("c"); const id = c ? Number(c) : NaN; if (Number.isFinite(id)) setSelectedId(id); }, []); // Mirror the current selection into the URL (replaceState → no history spam). A // selectedId with no matching conversation (e.g. a stale ?c=, or a just-created // one before reloadConvs lands) simply renders the draft view — harmless — so we // deliberately do NOT auto-clear it here (that raced new-conversation creation). React.useEffect(() => { const url = new URL(window.location.href); if (selectedId != null) url.searchParams.set("c", String(selectedId)); else url.searchParams.delete("c"); window.history.replaceState(null, "", url); }, [selectedId]); const selected = React.useMemo(() => convs.find((c) => c.id === selectedId) ?? null, [convs, selectedId]); const agentByKey = React.useMemo(() => new Map(agents.map((agent) => [agent.key, agent])), [agents]); const filteredConversations = React.useMemo( () => (agentFilter === null ? convs : convs.filter((conversation) => conversation.agent_key === agentFilter)), [convs, agentFilter], ); const visibleConversations = React.useMemo( () => filteredConversations.slice(0, visibleConversationCount), [filteredConversations, visibleConversationCount], ); // Pinned rows stay a flat block above the groups (server order = pinned_at DESC); // everything else is bucketed per agent, most-recently-active agent first. const pinnedConversations = React.useMemo( () => visibleConversations.filter(conversationIsPinned), [visibleConversations], ); const agentGroups = React.useMemo( () => groupByAgent( visibleConversations.filter((c) => !conversationIsPinned(c)), agentByKey, ), [visibleConversations, agentByKey], ); // conversation agents: custom agents + conversational built-ins (role=assistant, // e.g. Auto / 渗透测试). The orchestration built-ins (goals/planner/mainagent/worker) // are task-specific and stay hidden from the chat page. const chatAgents = React.useMemo(() => agents.filter((a) => !a.builtin || a.role === "assistant"), [agents]); const agentFilterOptions = React.useMemo(() => { const counts = new Map(); for (const conversation of convs) { counts.set(conversation.agent_key, (counts.get(conversation.agent_key) ?? 0) + 1); } // Include historical sources even if their Agent has since been disabled or deleted. const keys = new Set([...chatAgents.map((agent) => agent.key), ...counts.keys()]); if (agentFilter !== null) keys.add(agentFilter); return [...keys] .map((key) => ({ key, name: agentByKey.get(key)?.name || key, count: counts.get(key) ?? 0 })) .sort((a, b) => a.name.localeCompare(b.name, "zh-CN")); }, [convs, chatAgents, agentByKey, agentFilter]); const conversationCountLabel = agentFilter === null ? `共 ${convs.length} 个` : `${filteredConversations.length} / ${convs.length} 个`; function changeAgentFilter(key: string | null) { setAgentFilter(key); setVisibleConversationCount(CONVERSATION_LIST_PAGE); setSelectedConversationIds(new Set()); setBulkDeleteOpen(false); setRenamingId(null); } const selectedConversationCount = selectedConversationIds.size; const allConversationsSelected = filteredConversations.length > 0 && selectedConversationCount === filteredConversations.length; const someConversationsSelected = selectedConversationCount > 0 && !allConversationsSelected; let conversationHeaderChecked: boolean | "indeterminate" = false; if (allConversationsSelected) conversationHeaderChecked = true; else if (someConversationsSelected) conversationHeaderChecked = "indeterminate"; const toggleConversationSelected = React.useCallback((id: number, checked: boolean) => { setSelectedConversationIds((current) => { const next = new Set(current); if (checked) next.add(id); else next.delete(id); return next; }); }, []); function toggleAllConversations(checked: boolean) { setSelectedConversationIds( checked ? new Set(filteredConversations.map((conversation) => conversation.id)) : new Set(), ); } function exitSelectionMode() { setSelectionMode(false); setSelectedConversationIds(new Set()); } const del = React.useCallback( async (id: number) => { try { await api.deleteConversation(id); setSelectedId((current) => (current === id ? null : current)); setSelectedConversationIds((current) => { if (!current.has(id)) return current; const next = new Set(current); next.delete(id); return next; }); void reloadConvs(); } catch (e) { toast.error("删除失败:" + (e as Error).message); } }, [reloadConvs], ); async function deleteSelectedConversations() { const ids = [...selectedConversationIds]; if (ids.length === 0 || bulkDeleting) return; setBulkDeleting(true); const deleted = new Set(); const failed: { id: number; error: string }[] = []; try { for (let offset = 0; offset < ids.length; offset += 100) { const result = await api.deleteConversations(ids.slice(offset, offset + 100)); for (const item of result.items) { if (item.ok) deleted.add(item.id); else failed.push({ id: item.id, error: item.error ?? "对话不存在" }); } } if (deleted.has(selectedId ?? -1)) selectConversation(null); setSelectedConversationIds((current) => { const next = new Set(current); for (const id of deleted) next.delete(id); return next; }); if (deleted.size > 0) toast.success(`已删除 ${deleted.size} 个对话`); if (failed.length > 0) { const details = failed .slice(0, 3) .map((item) => `#${item.id}(${item.error})`) .join(";"); toast.error(`${failed.length} 个对话删除失败:${details}${failed.length > 3 ? " 等" : ""}`); } setBulkDeleteOpen(false); // Fully successful → return to the clean list; keep selection mode on if // some failed so the user can retry the remaining ones. if (failed.length === 0) setSelectionMode(false); void reloadConvs(); } catch (error) { toast.error(`批量删除失败:${(error as Error).message}`); void reloadConvs(); } finally { setBulkDeleting(false); } } const togglePinned = React.useCallback( async (conversation: Conversation) => { const pinned = conversationIsPinned(conversation); try { await api.pinConversation(conversation.id, !pinned); void reloadConvs(); } catch (e) { toast.error(`${pinned ? "取消置顶" : "置顶"}失败:${(e as Error).message}`); } }, [reloadConvs], ); const startRename = React.useCallback((c: Conversation) => { setRenamingId(c.id); setRenameText(c.title || ""); }, []); const commitRename = React.useCallback( async (id: number, value: string) => { const title = value.trim(); setRenamingId(null); if (!title) return; try { await api.renameConversation(id, title); void reloadConvs(); } catch (e) { toast.error("重命名失败:" + (e as Error).message); } }, [reloadConvs], ); const cancelRename = React.useCallback(() => setRenamingId(null), []); return (
{/* left: conversation list */}
{convs.length > 0 && (selectionMode ? (
toggleAllConversations(checked === true)} aria-label="选择当前筛选的全部对话" disabled={filteredConversations.length === 0 || bulkDeleting} /> {selectedConversationCount > 0 ? `已选 ${selectedConversationCount} 个` : conversationCountLabel} {selectedConversationCount > 0 && ( )}
) : (
{conversationCountLabel}
))}
{filteredConversations.length === 0 && (

{agentFilter === null ? "暂无对话" : "该 Agent 暂无对话"}

)} {pinnedConversations.map((c) => ( ))} {agentGroups.map((group) => { const collapsed = collapsedAgents.has(group.key); return ( c.id === selectedId)} onToggle={toggleAgentCollapsed} /> {!collapsed && group.conversations.map((c) => ( ))} ); })} {visibleConversationCount < filteredConversations.length && ( )}
{/* right: chat view */}
{selected ? ( ) : sourceRequested ? (
{convsLoaded ? "对话已被删除" : "正在加载对应对话…"}
) : ( { if (agentFilter !== null && agentFilter !== c.agent_key) changeAgentFilter(null); // Insert the new conversation immediately so `selected` resolves to // it on this render (switching to ChatView right away, before the // async reloadConvs lands); reloadConvs then reconciles titles etc. if (pending) setPendingByConv((p) => ({ ...p, [c.id]: pending })); setConvs((prev) => { if (prev.some((item) => item.id === c.id)) return prev; const firstUnpinned = prev.findIndex((item) => !conversationIsPinned(item)); const insertAt = firstUnpinned < 0 ? prev.length : firstUnpinned; return [...prev.slice(0, insertAt), c, ...prev.slice(insertAt)]; }); setSelectedId(c.id); void reloadConvs(); }} /> )}
删除选中的 {selectedConversationCount} 个对话? 对话消息和执行记录将一并删除,此操作不可撤销。 取消 { event.preventDefault(); void deleteSelectedConversations(); }} > {bulkDeleting && } {bulkDeleting ? "删除中" : "确认删除"}
); }