"use client"; import * as React from "react"; import Link from "next/link"; import { useRouter, useSearchParams } from "next/navigation"; import { ArchiveIcon, ArrowLeftIcon, BrainIcon, CheckIcon, CircleAlertIcon, PauseIcon, PlayIcon } from "lucide-react"; import { toast } from "sonner"; import { StatusBadge } from "@/components/status-badge"; import { TaskLLMProfileChain } from "@/components/task-llm-profile-chain"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { Popover, PopoverContent, PopoverDescription, PopoverHeader, PopoverTitle, PopoverTrigger, } from "@/components/ui/popover"; import { Separator } from "@/components/ui/separator"; import { SidebarTrigger } from "@/components/ui/sidebar"; import { Spinner } from "@/components/ui/spinner"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { api } from "@/lib/api"; import type { LLMProfile, Task } from "@/lib/types"; import { AssetsTab } from "./_tabs/assets-tab"; import { BroadcastTab } from "./_tabs/broadcast-tab"; import { CoverageGraphTab } from "./_tabs/coverage-graph-tab"; import { FindingsTab } from "./_tabs/findings-tab"; import { GraphTab } from "./_tabs/graph-tab"; import { InterceptTab } from "./_tabs/intercept-tab"; import { OverviewTab } from "./_tabs/overview-tab"; import { ReportTab } from "./_tabs/report-tab"; import { RetestsTab } from "./_tabs/retests-tab"; import { SessionsTab } from "./_tabs/sessions-tab"; const TABS = [ { value: "sessions", label: "会话" }, { value: "overview", label: "总览" }, { value: "graph", label: "探索链路" }, { value: "broadcast", label: "播报板" }, { value: "findings", label: "发现" }, { value: "retests", label: "复测" }, { value: "assets", label: "测试资产" }, { value: "coverage", label: "资产覆盖图" }, { value: "intercept", label: "拦截审批" }, { value: "report", label: "报告" }, ]; function taskProfileIDs(task: Task): string[] { if (task.llm_profile_ids && task.llm_profile_ids.length > 0) { return task.llm_profile_ids.map(String); } return task.llm_profile_id ? [String(task.llm_profile_id)] : []; } function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: LLMProfile[]; onUpdated: () => void }) { const [open, setOpen] = React.useState(false); const [profileIDs, setProfileIDs] = React.useState(() => taskProfileIDs(task)); const [activeProfileID, setActiveProfileID] = React.useState( task.active_llm_profile_id ? String(task.active_llm_profile_id) : (taskProfileIDs(task)[0] ?? ""), ); const [saving, setSaving] = React.useState(false); const popoverContentRef = React.useRef(null); const chain = taskProfileIDs(task); const exhausted = task.llm_failover_state === "chain_exhausted"; // 任何状态都可以改链,终态也不例外:任务结束后主 Agent 对话仍走这条链, // 链上模型出问题时必须能换掉,否则已完成任务就没法继续交互。 const terminal = ["done", "failed", "timeout"].includes(task.status); // A null active profile on an exhausted, non-empty chain is a persisted end // cursor. Keep the status display honest; choosing the first profile is only // the editor's reset draft and does not mean it is currently active. let activeID = chain[0] ?? ""; if (exhausted) activeID = ""; if (task.active_llm_profile_id) activeID = String(task.active_llm_profile_id); const activeProfile = profiles.find((profile) => profile.id === activeID); const currentLabel = exhausted ? "配置链已耗尽" : (activeProfile?.name ?? (activeID ? `配置 #${activeID}` : "跟随默认配置")); const activeIndex = chain.indexOf(activeID); const backupCount = activeIndex >= 0 ? Math.max(0, chain.length - activeIndex - 1) : 0; const currentTitle = [currentLabel, activeProfile?.model, backupCount > 0 ? `${backupCount} 个备用` : ""] .filter(Boolean) .join(" · "); let editorDescription = "调整顺序或当前配置后,将从下一次 LLM 调用开始生效。"; if (terminal) editorDescription = "任务已结束,改动只影响后续的主 Agent 对话。"; let saveLabel = "保存"; if (exhausted) saveLabel = "保存并重置"; if (saving) saveLabel = "保存中"; const syncDraft = React.useCallback(() => { const next = taskProfileIDs(task); setProfileIDs(next); setActiveProfileID(task.active_llm_profile_id ? String(task.active_llm_profile_id) : (next[0] ?? "")); }, [task]); const handleOpenChange = (next: boolean) => { setOpen(next); if (next) syncDraft(); }; const handleProfileIDsChange = (next: string[]) => { setProfileIDs(next); setActiveProfileID((current) => (next.includes(current) ? current : (next[0] ?? ""))); }; const save = async () => { setSaving(true); try { const result = await api.updateTaskLLMProfiles( task.id, profileIDs.map(Number), activeProfileID ? Number(activeProfileID) : undefined, ); if (result.switch_event) { toast.info(result.switch_event.summary, { id: `task-${task.id}-llm-${result.switch_event.seq}` }); } else { toast.success( result.reopened_intents > 0 ? `LLM 配置已更新,并恢复 ${result.reopened_intents} 条额度阻塞意图` : "LLM 配置已更新", ); } setOpen(false); onUpdated(); } catch (error) { toast.error("更新失败:" + (error as Error).message); } finally { setSaving(false); } }; return ( 任务 LLM 配置链 {editorDescription} {exhausted && ( 配置链额度已耗尽 {task.llm_failover_reason ?? "所有已选配置均被判定为额度不足。保存配置链可重置故障状态。"} )}
); } function TaskDetailInner() { const router = useRouter(); const searchParams = useSearchParams(); const id = searchParams.get("id") ?? ""; const [task, setTask] = React.useState(null); const [paused, setPaused] = React.useState(false); const [loaded, setLoaded] = React.useState(false); const [tab, setTab] = React.useState("sessions"); const [interceptPendingCount, setInterceptPendingCount] = React.useState(0); const [profiles, setProfiles] = React.useState([]); const [archiving, setArchiving] = React.useState(false); React.useEffect(() => { api .llmProfiles() .then(setProfiles) .catch(() => setProfiles([])); }, []); React.useEffect(() => { let alive = true; const load = () => api .interceptTask(id) .then((rows) => { if (alive) setInterceptPendingCount(rows.filter((r) => r.status === "pending").length); }) .catch(() => { // Polling is best-effort; the next interval retries automatically. }); void load(); const t = setInterval(load, 5000); return () => { alive = false; clearInterval(t); }; }, [id]); const taskLoadInFlight = React.useRef(null); const load = React.useCallback(() => { if (taskLoadInFlight.current === id) return; taskLoadInFlight.current = id; Promise.all([api.task(id), api.stats(id).catch(() => null)]) .then(([task, s]) => { if (taskLoadInFlight.current !== id) return; const base = { ...task }; const at = s?.active_task; if (at) { base.in_flight = at.in_flight; base.goals_total = at.goals_total; base.goals_met = at.goals_met; base.engine_mode = s?.engine_mode ?? at.engine_mode; base.paused = at.paused; } setTask(base); setPaused(at?.paused ?? base.paused ?? false); }) .catch(() => { // Keep the last rendered task state during a transient poll failure. }) .finally(() => { if (taskLoadInFlight.current === id) { taskLoadInFlight.current = null; setLoaded(true); } }); }, [id]); React.useEffect(() => { load(); const timer = setInterval(load, 5000); return () => clearInterval(timer); }, [load]); async function togglePause() { if (task && ["done", "failed", "timeout"].includes(task.status)) return; const next = !paused; try { await api.controlTask(id, next ? "pause" : "resume"); setPaused(next); toast.success(next ? "已暂停探索" : "已恢复探索"); } catch (e) { toast.error("操作失败:" + (e as Error).message); } } async function archiveTask() { if (!task || archiving) return; setArchiving(true); try { await api.archiveTask(task.id); toast.success("任务已加入归档队列"); router.push("/function/tasks"); } catch (error) { toast.error(`归档失败:${(error as Error).message}`); setArchiving(false); } } if (!task) { return (

{loaded ? `任务 ${id} 已被删除、归档或不存在` : "加载中…"}

{loaded && ( )}
); } const completed = task.status === "done"; const terminal = ["done", "failed", "timeout"].includes(task.status); const archiveLifecycleEligible = terminal || paused || task.status === "paused"; const canArchive = archiveLifecycleEligible && !task.archive_blocked_by_task_id; let archiveDisabledReason = task.queued ? "排队中的任务必须先暂停" : "运行中的任务必须先暂停"; if (archiveLifecycleEligible && task.archive_blocked_by_task_id) { archiveDisabledReason = `任务被未归档任务 #${task.archive_blocked_by_task_id} 直接继承,请先归档依赖任务`; } const engineMode = paused ? "paused" : (task.engine_mode ?? "idle"); let controlVariant: "default" | "secondary" | "outline" = "outline"; let controlIcon = ; let controlLabel = "暂停"; if (terminal) { controlVariant = "secondary"; controlIcon = ; controlLabel = completed ? "已完成" : "已结束"; } else if (paused) { controlVariant = "default"; controlIcon = ; controlLabel = "恢复"; } const archiveTrigger = ( ); return ( {/* Top fixed area */}

{task.name || task.description}

{task.id} {canArchive ? ( {archiveTrigger} 归档任务 #{task.id}? 任务图谱、关联记录、独占资产与流量、工作文件和 LLM 历史将压缩到冷存储。归档完成后可在任务列表的“已归档”页还原。 取消 void archiveTask()}>确认归档 ) : ( {archiveTrigger} {archiveDisabledReason} )}

{task.goal}

{/* Tabs */}
{TABS.map((t) => ( {t.label} {t.value === "intercept" && interceptPendingCount > 0 && ( {interceptPendingCount > 99 ? "99+" : interceptPendingCount} )} ))}
{/* Tab content */}
); } // useSearchParams must sit under a Suspense boundary for static export. export default function TaskDetailPage() { return ( ); }