"use client"; import * as React from "react"; import Link from "next/link"; import { toast } from "sonner"; import { PlusIcon, Trash2Icon, ArrowRightIcon, StarIcon, SearchIcon, XIcon, } from "lucide-react"; import { StatusBadge } from "@/components/status-badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { TablePagination } from "@/components/table-pagination"; import { api } from "@/lib/api"; import type { Task, TaskStatus, LLMProfile } from "@/lib/types"; // ACTIVE_PROFILE is the sentinel Select value for "use the global active profile". const ACTIVE_PROFILE = "__active__"; // 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 a run duration in seconds as a compact human string. function fmtDuration(sec: number): string { if (sec <= 0) return "—"; const d = Math.floor(sec / 86400); const h = Math.floor((sec % 86400) / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; if (d > 0) return `${d}d ${h}h`; if (h > 0) return `${h}h ${m}m`; if (m > 0) return `${m}m ${s}s`; return `${s}s`; } // taskDuration is the task's run duration in seconds: created → now while running, // created → completion for a finished task, else created → last activity. 0 when it // never ran (no activity yet). function taskDuration(task: Task, nowSec: number): number { const start = task.created_unix ?? 0; if (!start) return 0; const end = task.status === "running" ? nowSec : task.completed_unix && task.completed_unix > 0 ? task.completed_unix : task.last_activity_unix ?? 0; return end > start ? end - start : 0; } // fmtDateTime renders a unix-seconds timestamp as a compact local date-time // (MM-DD HH:mm), or "—" when unset. function fmtDateTime(unix?: number): string { if (!unix || unix <= 0) return "—"; const d = new Date(unix * 1000); const p = (n: number) => String(n).padStart(2, "0"); return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; } const STATUS_OPTIONS: { value: TaskStatus; label: string }[] = [ { value: "created", label: "已创建" }, { value: "running", label: "运行中" }, { value: "paused", label: "已暂停" }, { value: "done", label: "已完成" }, { value: "failed", label: "失败" }, { value: "timeout", label: "已超时" }, ]; export default function TasksPage() { const [tasks, setTasks] = React.useState([]); const [description, setDescription] = React.useState(""); const [goal, setGoal] = React.useState(""); const [profiles, setProfiles] = React.useState([]); const [llmProfile, setLlmProfile] = React.useState(ACTIVE_PROFILE); // sentinel = active const [timeoutMin, setTimeoutMin] = React.useState(""); // 任务级超时(分钟);空/0 = 不限时 const [heartbeatMin, setHeartbeatMin] = React.useState("10"); // planner 心跳(分钟);默认10,下限10(与后端一致) const [seedFirstIntent, setSeedFirstIntent] = React.useState(true); // 创建时下发种子意图,worker 免等首轮 planner 直接开跑 const [open, setOpen] = React.useState(false); const [query, setQuery] = React.useState(""); const [statusFilter, setStatusFilter] = React.useState("all"); const [page, setPage] = React.useState(1); const [pageSize, setPageSize] = React.useState(20); const [nowSec, setNowSec] = React.useState(() => Math.floor(Date.now() / 1000)); const filtered = React.useMemo(() => { const q = query.trim().toLowerCase(); return tasks.filter((t) => { if (statusFilter !== "all" && t.status !== statusFilter) return false; if (!q) return true; return ( t.description.toLowerCase().includes(q) || t.goal.toLowerCase().includes(q) || t.id.toLowerCase().includes(q) ); }); }, [tasks, query, statusFilter]); // reset to page 1 whenever filters change React.useEffect(() => { setPage(1); }, [query, statusFilter]); const paginated = React.useMemo( () => filtered.slice((page - 1) * pageSize, page * pageSize), [filtered, page, pageSize], ); const load = React.useCallback(() => { api.tasks() .then((r) => { setTasks(r.tasks.map((t) => (t.id === r.active ? { ...t, active: true } : t))); }) .catch(() => {}); }, []); React.useEffect(() => { load(); const i = setInterval(load, 3000); return () => clearInterval(i); }, [load]); // load LLM profiles once for the create-task profile picker. React.useEffect(() => { api.llmProfiles().then(setProfiles).catch(() => setProfiles([])); }, []); // tick every second so running tasks' 运行时长 counts up live. React.useEffect(() => { const i = setInterval(() => setNowSec(Math.floor(Date.now() / 1000)), 1000); return () => clearInterval(i); }, []); async function createTask() { if (!description.trim() || !goal.trim()) { toast.error("请填写描述与目标"); return; } try { const pid = llmProfile === ACTIVE_PROFILE ? undefined : Number(llmProfile); const timeoutSec = Math.max(0, Math.floor(Number(timeoutMin) || 0)) * 60; const heartbeatSec = Math.max(10, Math.floor(Number(heartbeatMin) || 10)) * 60; // 下限 10min,与后端归一一致 await api.createTask(description.trim(), goal.trim(), pid, timeoutSec, seedFirstIntent, heartbeatSec); toast.success("任务已创建"); setDescription(""); setGoal(""); setLlmProfile(ACTIVE_PROFILE); setTimeoutMin(""); setHeartbeatMin("10"); setSeedFirstIntent(true); setOpen(false); load(); } catch (e) { toast.error("创建失败:" + (e as Error).message); } } async function deleteTask(id: string) { try { await api.deleteTask(id); toast.success("任务已删除(全局资产图保留)"); load(); } catch (e) { toast.error("删除失败:" + (e as Error).message); } } return (
setQuery(e.target.value)} className="pl-8" /> {query && ( )}
{filtered.length}/{tasks.length} 条 新建任务 填写测试对象与目标。