This commit is contained in:
pphua committed 2026-08-21 11:16:19 +08:00
1 parent 9793b522d9
commit b7e0b93023
46 files changed
+3632 -899

No files matched your search

@@ -1,27 +1,63 @@
"use client";
import * as React from "react";
import {
ActivityIcon,
AlertTriangleIcon,
BugIcon,
ClockIcon,
CoinsIcon,
PlusIcon,
RefreshCwIcon,
ShieldCheckIcon,
TargetIcon,
Trash2Icon,
} from "lucide-react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { StatusBadge } from "@/components/status-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Progress } from "@/components/ui/progress";
import { api } from "@/lib/api";
import type { Task, Stats, TaskNode, Finding } from "@/lib/types";
import type { Finding, ModelTokenStat, Stats, Task, TaskNode, TaskScopeRow } from "@/lib/types";
// 紧凑格式化 token 数(12345 → 12.3k,2000000 → 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);
}
// 缓存命中率 = 缓存读 / 输入(InputTokens 已含 cache_read 子集,故比值在 0–100%)。
function cacheHitRate(cacheRead: number, input: number): string {
if (input <= 0) return "—";
return Math.round((cacheRead / input) * 100) + "%";
}
// 测试范围一条的显示值:域名 / 网段 / 公司。
function scopeValue(row: TaskScopeRow): string {
if (row.domain) return row.domain;
if (row.net) return row.net;
if (row.company_id) return `company #${row.company_id}`;
return "—";
}
const SCOPE_KIND_LABELS: Record<TaskScopeRow["kind"], string> = {
company: "公司",
root_domain: "根域名",
subdomain: "子域名",
ip: "IP",
cidr: "网段",
};
const SCOPE_SOURCE_LABELS: Record<TaskScopeRow["source"], string> = {
auto: "自动",
agent: "Agent",
manual: "手动",
};
function StatCard({
label,
@@ -42,9 +78,7 @@ function StatCard({
</CardDescription>
<CardTitle className="text-2xl tabular-nums">{value}</CardTitle>
</CardHeader>
{sub && (
<CardContent className="text-xs text-muted-foreground">{sub}</CardContent>
)}
{sub && <CardContent className="text-xs text-muted-foreground">{sub}</CardContent>}
</Card>
);
}
@@ -63,6 +97,57 @@ export function OverviewTab({ taskId }: { taskId: string }) {
} | null>(null);
// 正在重跑的意图 id(含 "__all__" 表示批量),用于禁用按钮 + 转圈。
const [rerunning, setRerunning] = React.useState<Set<string>>(new Set());
// 测试范围列表 + 新增表单状态。
const [scope, setScope] = React.useState<TaskScopeRow[]>([]);
const [scopeKind, setScopeKind] = React.useState<TaskScopeRow["kind"]>("root_domain");
const [scopeValueInput, setScopeValueInput] = React.useState("");
const [scopeBusy, setScopeBusy] = React.useState(false);
const [scopeErr, setScopeErr] = React.useState("");
// 按模型的 token 用量(来自常开的 llm_usage 计量账本,逐次精确)。
const [modelTokens, setModelTokens] = React.useState<ModelTokenStat[]>([]);
const loadTokens = React.useCallback(async () => {
try {
const resp = await api.tokensByModel(taskId);
setModelTokens(resp.models);
} catch {
// 忽略:无 PG 时接口报错,卡片自然为空
}
}, [taskId]);
const loadScope = React.useCallback(async () => {
try {
const resp = await api.taskScope(taskId);
setScope(resp.scope);
} catch {
// 忽略:无 asset store 时接口 503,范围卡片自然为空
}
}, [taskId]);
const addScope = async () => {
const value = scopeValueInput.trim();
if (!value) return;
setScopeBusy(true);
setScopeErr("");
try {
await api.addTaskScope(taskId, scopeKind, value);
setScopeValueInput("");
await loadScope();
} catch (e) {
setScopeErr(e instanceof Error ? e.message : "添加失败");
} finally {
setScopeBusy(false);
}
};
const removeScope = async (row: TaskScopeRow) => {
setScope((prev) => prev.filter((s) => s.id !== row.id));
try {
await api.deleteTaskScope(taskId, row.id);
} catch {
await loadScope(); // 删除失败:重新拉取还原
}
};
const markRerun = (key: string, on: boolean) =>
setRerunning((prev) => {
@@ -77,9 +162,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
markRerun(id, true);
try {
await api.rerunIntent(taskId, id);
setIntents((prev) =>
prev.map((i) => (i.id === id ? { ...i, state: "open" } : i)),
);
setIntents((prev) => prev.map((i) => (i.id === id ? { ...i, state: "open" } : i)));
} catch {
// 失败忽略:下次轮询仍显示 blocked,用户可再点
} finally {
@@ -92,9 +175,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
markRerun("__all__", true);
try {
await api.rerunBlocked(taskId);
setIntents((prev) =>
prev.map((i) => (i.state === "blocked" ? { ...i, state: "open" } : i)),
);
setIntents((prev) => prev.map((i) => (i.state === "blocked" ? { ...i, state: "open" } : i)));
} catch {
// ignore
} finally {
@@ -107,13 +188,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const load = async () => {
try {
const [tasksResp, statsResp, intentsResp, findingsResp] =
await Promise.all([
api.tasks(),
api.stats(taskId),
api.intents(taskId),
api.findings(taskId),
]);
const [tasksResp, statsResp, intentsResp, findingsResp] = await Promise.all([
api.tasks(),
api.stats(taskId),
api.intents(taskId),
api.findings(taskId),
]);
if (cancelled) return;
setTask(tasksResp.tasks.find((t) => t.id === taskId) ?? null);
setStats(statsResp);
@@ -133,20 +213,35 @@ export function OverviewTab({ taskId }: { taskId: string }) {
};
load();
const timer = setInterval(load, 3000);
void loadScope();
void loadTokens();
const timer = setInterval(() => {
void load();
void loadTokens();
}, 3000);
return () => {
cancelled = true;
clearInterval(timer);
};
}, [taskId]);
}, [taskId, loadScope, loadTokens]);
const running = intents.filter((i) => i.state === "running");
const open = intents.filter((i) => i.state === "open");
const blocked = intents.filter((i) => i.state === "blocked");
const taskFindings = findings.filter((f) => f.task_id === taskId);
const goalsPct = task?.goals_total
? Math.round(((task.goals_met ?? 0) / task.goals_total) * 100)
: 0;
const goalsPct = task?.goals_total ? Math.round(((task.goals_met ?? 0) / task.goals_total) * 100) : 0;
// token 合计(跨全部模型),用于卡片头部总览。
const tokenTotals = modelTokens.reduce(
(acc, m) => {
acc.input += m.input_tokens;
acc.output += m.output_tokens;
acc.cacheRead += m.cache_read_tokens;
acc.cacheWrite += m.cache_write_tokens;
acc.calls += m.calls;
return acc;
},
{ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 },
);
return (
<div className="flex flex-col gap-4">
@@ -160,15 +255,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<div className="text-xs font-medium text-muted-foreground">描述</div>
<p className="text-sm whitespace-pre-wrap break-words">
{task?.description?.trim() || "—"}
</p>
<p className="text-sm whitespace-pre-wrap break-words">{task?.description?.trim() || "—"}</p>
</div>
<div className="flex flex-col gap-1.5">
<div className="text-xs font-medium text-muted-foreground">目标</div>
<p className="text-sm whitespace-pre-wrap break-words">
{task?.goal?.trim() || "—"}
</p>
<p className="text-sm whitespace-pre-wrap break-words">{task?.goal?.trim() || "—"}</p>
</div>
</CardContent>
</Card>
@@ -205,6 +296,157 @@ export function OverviewTab({ taskId }: { taskId: string }) {
</CardContent>
</Card>
)}
{/* LLM Token 用量:按模型分组,数据来自 llm_records(需开启 LLM 录制)。 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<CoinsIcon className="size-4 text-amber-500" /> LLM Token 用量
<span className="text-muted-foreground text-xs font-normal">
(按模型统计{tokenTotals.calls > 0 ? `,共 ${tokenTotals.calls} 次调用` : ""})
</span>
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{modelTokens.length > 0 ? (
<>
{/* 合计总览 */}
<div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 text-sm">
<span className="tabular-nums">
<span className="text-muted-foreground">输入 </span>
<span className="font-semibold">{fmtTokens(tokenTotals.input)}</span>
</span>
<span className="tabular-nums">
<span className="text-muted-foreground">输出 </span>
<span className="font-semibold">{fmtTokens(tokenTotals.output)}</span>
</span>
<span className="tabular-nums">
<span className="text-muted-foreground">缓存读 </span>
<span className="font-semibold">{fmtTokens(tokenTotals.cacheRead)}</span>
</span>
<span className="tabular-nums">
<span className="text-muted-foreground">缓存命中率 </span>
<span className="font-semibold text-emerald-500">
{cacheHitRate(tokenTotals.cacheRead, tokenTotals.input)}
</span>
</span>
</div>
{/* 按模型明细表 */}
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-muted-foreground border-b text-left text-xs">
<th className="py-1.5 pr-3 font-medium">模型</th>
<th className="py-1.5 pr-3 text-right font-medium">调用</th>
<th className="py-1.5 pr-3 text-right font-medium">输入</th>
<th className="py-1.5 pr-3 text-right font-medium">输出</th>
<th className="py-1.5 pr-3 text-right font-medium">缓存读</th>
<th className="py-1.5 text-right font-medium">命中率</th>
</tr>
</thead>
<tbody>
{modelTokens.map((m) => (
<tr key={m.model} className="border-b last:border-0">
<td className="max-w-[16rem] truncate py-1.5 pr-3 font-mono text-xs" title={m.model}>
{m.model}
</td>
<td className="py-1.5 pr-3 text-right tabular-nums">{m.calls}</td>
<td className="py-1.5 pr-3 text-right tabular-nums">{fmtTokens(m.input_tokens)}</td>
<td className="py-1.5 pr-3 text-right tabular-nums">{fmtTokens(m.output_tokens)}</td>
<td className="py-1.5 pr-3 text-right tabular-nums">{fmtTokens(m.cache_read_tokens)}</td>
<td className="py-1.5 text-right tabular-nums text-emerald-500">
{cacheHitRate(m.cache_read_tokens, m.input_tokens)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</>
) : (
<p className="text-muted-foreground text-sm">暂无 LLM 用量(任务尚未产生调用,或记录仍在写入)。</p>
)}
</CardContent>
</Card>
{/* 测试范围:覆盖度分母 + 授权边界,可手动增删。 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldCheckIcon className="size-4 text-emerald-500" /> 测试范围
<span className="text-muted-foreground text-xs font-normal">
(覆盖度分母 + 授权边界,共 {scope.length} 条)
</span>
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{/* 新增表单 */}
<div className="flex flex-wrap items-center gap-2">
<NativeSelect
size="sm"
value={scopeKind}
onChange={(e) => setScopeKind(e.target.value as TaskScopeRow["kind"])}
>
<NativeSelectOption value="root_domain">根域名</NativeSelectOption>
<NativeSelectOption value="subdomain">子域名</NativeSelectOption>
<NativeSelectOption value="ip">IP</NativeSelectOption>
<NativeSelectOption value="cidr">网段</NativeSelectOption>
<NativeSelectOption value="company">公司</NativeSelectOption>
</NativeSelect>
<Input
className="h-7 w-56 text-sm"
placeholder={
scopeKind === "company"
? "公司名或 id"
: scopeKind === "ip" || scopeKind === "cidr"
? "如 10.0.0.1 或 10.0.0.0/24"
: "如 example.com"
}
value={scopeValueInput}
onChange={(e) => setScopeValueInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void addScope();
}}
disabled={scopeBusy}
/>
<Button
size="sm"
variant="outline"
disabled={scopeBusy || !scopeValueInput.trim()}
onClick={() => void addScope()}
>
<PlusIcon className="size-3.5" /> 添加
</Button>
{scopeErr && <span className="text-xs text-red-500">{scopeErr}</span>}
</div>
{/* 范围列表 */}
{scope.length > 0 ? (
<div className="flex flex-col gap-1.5">
{scope.map((row) => (
<div key={row.id} className="flex items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm">
<span className="bg-muted text-muted-foreground shrink-0 rounded px-1.5 py-0.5 text-xs">
{SCOPE_KIND_LABELS[row.kind]}
</span>
<span className="min-w-0 flex-1 truncate font-mono text-xs">{scopeValue(row)}</span>
<span className="text-muted-foreground shrink-0 text-xs">{SCOPE_SOURCE_LABELS[row.source]}</span>
{row.task_id.toString() === taskId ? (
<Button
size="sm"
variant="ghost"
className="h-6 shrink-0 px-1.5"
onClick={() => void removeScope(row)}
>
<Trash2Icon className="size-3.5 text-red-500" />
</Button>
) : (
<span className="text-muted-foreground shrink-0 text-xs">继承</span>
)}
</div>
))}
</div>
) : (
<p className="text-muted-foreground text-sm">暂无测试范围,添加后可作为资产覆盖度的分母。</p>
)}
</CardContent>
</Card>
{/* Heartbeat */}
<Card>
<CardHeader>
@@ -224,17 +466,13 @@ export function OverviewTab({ taskId }: { taskId: string }) {
</div>
<div>
<div className="text-xs text-muted-foreground">运行中 Worker</div>
<div className="mt-1 text-lg font-semibold tabular-nums">
{running.length}
</div>
<div className="mt-1 text-lg font-semibold tabular-nums">{running.length}</div>
</div>
<div>
<div className="text-xs text-muted-foreground">最近活动</div>
<div className="mt-1 inline-flex items-center gap-1 text-sm">
<ClockIcon className="size-3.5" />
{task?.last_activity
? new Date(task.last_activity).toLocaleTimeString("zh-CN")
: "—"}
{task?.last_activity ? new Date(task.last_activity).toLocaleTimeString("zh-CN") : "—"}
</div>
</div>
<div>
@@ -270,9 +508,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<span className="min-w-0 flex-1 truncate">{i.payload}</span>
</div>
))}
{running.length === 0 && (
<p className="text-sm text-muted-foreground">暂无进行中意图</p>
)}
{running.length === 0 && <p className="text-sm text-muted-foreground">暂无进行中意图</p>}
</CardContent>
</Card>
@@ -284,27 +520,19 @@ export function OverviewTab({ taskId }: { taskId: string }) {
</CardHeader>
<CardContent className="grid grid-cols-2 gap-3 text-sm">
<div>
<div className="text-2xl font-semibold tabular-nums text-red-600">
{taskFindings.length}
</div>
<div className="text-2xl font-semibold tabular-nums text-red-600">{taskFindings.length}</div>
<div className="text-xs text-muted-foreground">确认漏洞</div>
</div>
<div>
<div className="text-2xl font-semibold tabular-nums text-blue-600">
{running.length}
</div>
<div className="text-2xl font-semibold tabular-nums text-blue-600">{running.length}</div>
<div className="text-xs text-muted-foreground">执行中</div>
</div>
<div>
<div className="text-2xl font-semibold tabular-nums">
{open.length}
</div>
<div className="text-2xl font-semibold tabular-nums">{open.length}</div>
<div className="text-xs text-muted-foreground">frontier 待领</div>
</div>
<div>
<div className="text-2xl font-semibold tabular-nums text-red-600">
{blocked.length}
</div>
<div className="text-2xl font-semibold tabular-nums text-red-600">{blocked.length}</div>
<div className="text-xs text-muted-foreground">被拦意图</div>
</div>
</CardContent>
@@ -323,9 +551,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<span className="min-w-0 flex-1 truncate">{f.summary}</span>
</div>
))}
{taskFindings.length === 0 && (
<p className="text-sm text-muted-foreground">暂无发现</p>
)}
{taskFindings.length === 0 && <p className="text-sm text-muted-foreground">暂无发现</p>}
</CardContent>
</Card>
</div>
@@ -337,19 +563,10 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<CardHeader className="flex-row items-center justify-between gap-2 space-y-0">
<CardTitle className="flex items-center gap-2 text-sm">
<AlertTriangleIcon className="size-4 text-red-500" /> 被拦/出错意图
<span className="text-xs font-normal text-muted-foreground">
(共 {blocked.length} 条,可重跑)
</span>
<span className="text-xs font-normal text-muted-foreground">(共 {blocked.length} 条,可重跑)</span>
</CardTitle>
<Button
size="sm"
variant="outline"
disabled={rerunning.has("__all__")}
onClick={() => void rerunAll()}
>
<RefreshCwIcon
className={`size-3.5 ${rerunning.has("__all__") ? "animate-spin" : ""}`}
/>
<Button size="sm" variant="outline" disabled={rerunning.has("__all__")} onClick={() => void rerunAll()}>
<RefreshCwIcon className={`size-3.5 ${rerunning.has("__all__") ? "animate-spin" : ""}`} />
全部重跑
</Button>
</CardHeader>
@@ -365,9 +582,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
disabled={rerunning.has(i.id)}
onClick={() => void rerunOne(i.id)}
>
<RefreshCwIcon
className={`size-3 ${rerunning.has(i.id) ? "animate-spin" : ""}`}
/>
<RefreshCwIcon className={`size-3 ${rerunning.has(i.id) ? "animate-spin" : ""}`} />
重跑
</Button>
</div>
@@ -383,24 +598,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
{/* Stat cards */}
<div className="grid grid-cols-2 gap-4 lg:grid-cols-3">
<StatCard
label="待领意图"
value={open.length}
icon={ShieldCheckIcon}
sub="frontier 开放"
/>
<StatCard
label="确认发现"
value={taskFindings.length}
icon={BugIcon}
sub="本任务"
/>
<StatCard
label="意图总数"
value={intents.length}
icon={AlertTriangleIcon}
sub="本任务全部意图"
/>
<StatCard label="待领意图" value={open.length} icon={ShieldCheckIcon} sub="frontier 开放" />
<StatCard label="确认发现" value={taskFindings.length} icon={BugIcon} sub="本任务" />
<StatCard label="意图总数" value={intents.length} icon={AlertTriangleIcon} sub="本任务全部意图" />
</div>
</div>
);
@@ -9,6 +9,7 @@ import { Markdown } from "@/components/markdown";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { api } from "@/lib/api";
import { copyText } from "@/lib/utils";
export function ReportTab({ taskId }: { taskId: string }) {
const [report, setReport] = React.useState<string>("");
@@ -34,12 +35,16 @@ export function ReportTab({ taskId }: { taskId: string }) {
};
}, [taskId]);
function copy() {
async function copy() {
if (!report) return;
navigator.clipboard?.writeText(report);
setCopied(true);
toast.success("已复制 Markdown");
setTimeout(() => setCopied(false), 1500);
const ok = await copyText(report);
if (ok) {
setCopied(true);
toast.success("已复制 Markdown");
setTimeout(() => setCopied(false), 1500);
} else {
toast.error("复制失败,请手动选择文本复制");
}
}
let content: React.ReactNode;
@@ -359,8 +359,6 @@ export function SessionsTab({ taskId }: { taskId: string }) {
const [olderIntents, setOlderIntents] = React.useState<TaskNode[]>([]);
const [intentsHasMore, setIntentsHasMore] = React.useState(false);
const [loadingOlderIntents, setLoadingOlderIntents] = React.useState(false);
// Local-only chat messages overlaid onto the main-agent transcript.
const [chatExtra, setChatExtra] = React.useState<Activity[]>([]);
const [input, setInput] = React.useState("");
const [sending, setSending] = React.useState(false);
const [stopping, setStopping] = React.useState(false);
@@ -613,7 +611,6 @@ export function SessionsTab({ taskId }: { taskId: string }) {
// ID) resumes from the DB, so a dropped realtime link self-heals; seq-merge dedups.
React.useEffect(() => {
setStore({});
setChatExtra([]);
setSseLive(false);
setActiveId(MAIN_ID); // a stale worker id from the previous task must not leak in
snapshotRef.current = 0;
@@ -892,13 +889,11 @@ export function SessionsTab({ taskId }: { taskId: string }) {
// worker session shows only its intent's activity, led by the intent objective.
const activity = React.useMemo(() => {
const items = activeState?.items ?? [];
if (isMain) {
// chatExtra is an optimistic local echo — drop any entry the persisted (SSE)
// copy already covers so messages don't show twice after the backend round-trips.
const seen = new Set(items.map((a) => `${a.kind} ${a.summary}`));
const pending = chatExtra.filter((a) => !seen.has(`${a.kind} ${a.summary}`));
return [...items, ...pending].sort((a, b) => a.seq - b.seq);
}
// The main-agent console renders purely from server data: the human turn is
// persisted+broadcast by the backend BEFORE it returns, so it arrives over the
// same SSE stream (worker="mainagent") as every agent step — no client-side
// optimistic echo, hence no fabricated seq that could collide with real DB ids.
if (isMain) return items;
if (isPlanner || isSystem) return items;
// Worker session: the intent leads the transcript as a right-aligned "user"-style
// message (the task handed to this worker), followed by its execution steps.
@@ -918,7 +913,6 @@ export function SessionsTab({ taskId }: { taskId: string }) {
isPlanner,
isSystem,
activeState,
chatExtra,
active.id,
active.title,
active.last_activity,
@@ -1010,6 +1004,26 @@ export function SessionsTab({ taskId }: { taskId: string }) {
const vp = viewport();
if (vp) vp.scrollTop = vp.scrollHeight;
}, [activity, viewport]);
// Lazy detail loads (AnswerBlock / ToolBlock / Markdown) grow the content AFTER the
// activity array settles, WITHOUT changing its reference — so the layout effects
// above never re-fire and a freshly opened session would leave its last message
// scrolled partly off-screen (the final answer expands from a one-line summary to
// full markdown below the fold). A ResizeObserver re-pins to the bottom on any
// height change while the user is still at the bottom, so opening the main agent
// lands on the last message fully shown. contentRef's div is always mounted, so the
// observer catches the transcript mounting + each detail expanding.
// biome-ignore lint/correctness/useExhaustiveDependencies: activeId intentionally rebinds the observer to the new session's content.
React.useEffect(() => {
const el = contentRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(() => {
if (!atBottomRef.current) return;
const vp = viewport();
if (vp) vp.scrollTop = vp.scrollHeight;
});
ro.observe(el);
return () => ro.disconnect();
}, [activeId, viewport]);
function stop() {
if (stopping) return;
@@ -1021,36 +1035,19 @@ export function SessionsTab({ taskId }: { taskId: string }) {
const text = input.trim();
const atts = attachments;
if ((!text && atts.length === 0) || sending) return;
const base = [...(store.main?.items ?? []), ...chatExtra];
const nextSeq = Math.max(0, ...base.map((a) => a.seq)) + 1;
const userMsg: Activity = {
seq: nextSeq,
worker: "mainagent",
ts: new Date().toISOString(),
kind: "user",
summary: text,
// 有附件时把 {text, attachments} 塞进 detail,乐观气泡直接渲染卡片,无需再拉取。
detail: atts.length > 0 ? JSON.stringify({ text, attachments: atts }) : undefined,
};
// optimistic echo of the human turn only; the agent's steps + final answer
// stream back live via SSE (worker="mainagent"), so we don't append the reply.
setChatExtra((prev) => [...prev, userMsg]);
// No optimistic echo: the backend persists+broadcasts the human turn before it
// returns, so it streams back over SSE (worker="mainagent") with its real DB
// seq — the transcript renders it from server data like every other step. Clear
// the composer eagerly for responsiveness; restore it if the send fails.
setInput("");
setAttachments([]);
setSending(true);
api
.chat(text, taskId, atts.length > 0 ? atts : undefined)
.catch(() => {
setChatExtra((prev) => [
...prev,
{
seq: nextSeq + 1,
worker: "mainagent",
ts: new Date().toISOString(),
kind: "text",
summary: "(发送失败,请稍后重试)",
},
]);
.catch((e) => {
setInput(text); // restore so the user doesn't lose their text / attachments
setAttachments(atts);
toast.error("发送失败:" + ((e as Error).message || "请稍后重试"));
})
.finally(() => setSending(false));
}
+341 -97
View File
@@ -172,7 +172,11 @@ function taskDuration(task: Task, nowSec: number): number {
return end > start ? end - start : 0;
}
function deleteSummary(result: DeleteTaskResult): string {
// deleteDetails takes only the countable part of the result so callers can pass an
// aggregate accumulated over a bulk delete.
type DeleteCounts = Omit<DeleteTaskResult, "deleted" | "cleanup_warning">;
function deleteDetails(result: DeleteCounts): string[] {
const details: string[] = [];
if (result.assets_deleted > 0) details.push(`删除资产 ${result.assets_deleted} 条`);
if (result.assets_detached > 0) details.push(`解除共享资产关联 ${result.assets_detached} 条`);
@@ -180,6 +184,11 @@ function deleteSummary(result: DeleteTaskResult): string {
if (result.files_deleted) details.push("删除任务文件");
if (result.findings_deleted > 0) details.push(`删除漏洞 ${result.findings_deleted} 条`);
if (result.llm_records_deleted > 0) details.push(`删除 LLM 请求/响应记录 ${result.llm_records_deleted} 条`);
return details;
}
function deleteSummary(result: DeleteTaskResult): string {
const details = deleteDetails(result);
return details.length > 0 ? `任务已删除(${details.join(",")})` : "任务已删除";
}
@@ -232,6 +241,48 @@ export default function TasksPage() {
[filtered, page, pageSize],
);
// 多选删除:选择跨翻页/筛选保留,只在任务真的消失(被删或后端不再返回)时收敛。
const [selectedIds, setSelectedIds] = React.useState<Set<string>>(() => new Set());
React.useEffect(() => {
setSelectedIds((prev) => {
if (prev.size === 0) return prev;
const live = new Set(tasks.map((t) => t.id));
const next = new Set([...prev].filter((id) => live.has(id)));
return next.size === prev.size ? prev : next;
});
}, [tasks]);
const toggleSelected = React.useCallback((id: string, checked: boolean) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (checked) next.add(id); else next.delete(id);
return next;
});
}, []);
const pageIds = React.useMemo(() => paginated.map((t) => t.id), [paginated]);
const pageSelectedCount = React.useMemo(
() => pageIds.filter((id) => selectedIds.has(id)).length,
[pageIds, selectedIds],
);
let headerChecked: boolean | "indeterminate" = false;
if (pageIds.length > 0 && pageSelectedCount === pageIds.length) {
headerChecked = true;
} else if (pageSelectedCount > 0) {
headerChecked = "indeterminate";
}
const toggleSelectedPage = React.useCallback((checked: boolean) => {
setSelectedIds((prev) => {
const next = new Set(prev);
for (const id of pageIds) {
if (checked) next.add(id); else next.delete(id);
}
return next;
});
}, [pageIds]);
// lastRef holds the previous poll's serialized payload: the list is re-fetched every
// POLL_MS but usually comes back unchanged, and setTasks on an identical payload would
// re-render the whole page for nothing. Bail out when it matches.
@@ -284,6 +335,63 @@ export default function TasksPage() {
}
}, [load]);
// deleteTasks 逐个删除所选任务:后端没有批量接口,且单次删除会连带清理资产/流量/文件,
// 串行执行以免一次性打爆后端;成功的从选中集移除,失败的保留以便重试。
const deleteTasks = React.useCallback(async (
ids: string[],
options: DeleteTaskOptions,
onProgress: (done: number) => void,
) => {
const total: DeleteCounts = {
assets_deleted: 0,
assets_detached: 0,
traffic_deleted: 0,
files_deleted: false,
findings_deleted: 0,
llm_records_deleted: 0,
};
const deleted: string[] = [];
const failed: { id: string; message: string }[] = [];
const warnings: string[] = [];
for (const id of ids) {
try {
const r = await api.deleteTask(id, options);
total.assets_deleted += r.assets_deleted;
total.assets_detached += r.assets_detached;
total.traffic_deleted += r.traffic_deleted;
total.files_deleted = total.files_deleted || r.files_deleted;
total.findings_deleted += r.findings_deleted;
total.llm_records_deleted += r.llm_records_deleted;
if (r.cleanup_warning) warnings.push(`#${id}:${r.cleanup_warning}`);
deleted.push(id);
} catch (e) {
failed.push({ id, message: (e as Error).message });
}
onProgress(deleted.length + failed.length);
}
if (deleted.length > 0) {
setSelectedIds((prev) => {
const next = new Set(prev);
for (const id of deleted) next.delete(id);
return next;
});
const details = deleteDetails(total);
const summary = `已删除 ${deleted.length} 个任务` + (details.length > 0 ? `(${details.join(",")})` : "");
if (warnings.length > 0) {
toast.warning(`${summary};部分外部数据清理未完成:${warnings.join(";")}`);
} else {
toast.success(summary);
}
}
if (failed.length > 0) {
const head = failed.slice(0, 3).map((f) => `#${f.id}(${f.message})`).join(";");
toast.error(`${failed.length} 个任务删除失败:${head}${failed.length > 3 ? " 等" : ""}`);
}
load();
}, [load]);
return (
<Card>
<CardContent className="flex flex-col gap-4 px-0 pt-6">
@@ -325,6 +433,15 @@ export default function TasksPage() {
<span className="text-muted-foreground text-xs tabular-nums">
{filtered.length}/{tasks.length} 条
</span>
{selectedIds.size > 0 && (
<>
<span className="text-xs tabular-nums">已选 {selectedIds.size} 个</span>
<Button size="sm" variant="ghost" onClick={() => setSelectedIds(new Set())}>
取消选择
</Button>
<BulkDeleteTasksDialog ids={[...selectedIds]} onDelete={deleteTasks} />
</>
)}
<ConcurrencySettingsDialog />
<CreateTaskSheet tasks={tasks} onCreated={load} />
</div>
@@ -341,6 +458,13 @@ export default function TasksPage() {
<Table className="**:data-[slot='table-cell']:px-4 **:data-[slot='table-head']:px-4">
<TableHeader className="[&_tr]:border-t">
<TableRow>
<TableHead className="w-10">
<Checkbox
checked={headerChecked}
onCheckedChange={(checked) => toggleSelectedPage(checked === true)}
aria-label="选择本页全部任务"
/>
</TableHead>
<TableHead className="font-mono">ID</TableHead>
<TableHead>描述</TableHead>
<TableHead>目标</TableHead>
@@ -361,6 +485,8 @@ export default function TasksPage() {
// 带来的整表重渲染,只让在跑的那几行走时长。
nowSec={task.status === "running" ? nowSec : 0}
onDelete={deleteTask}
selected={selectedIds.has(task.id)}
onSelectedChange={toggleSelected}
/>
))}
</TableBody>
@@ -461,13 +587,24 @@ const TaskRow = React.memo(function TaskRow({
task,
nowSec,
onDelete,
selected,
onSelectedChange,
}: {
task: Task;
nowSec: number;
onDelete: (id: string, options: DeleteTaskOptions) => Promise<void>;
selected: boolean;
onSelectedChange: (id: string, checked: boolean) => void;
}) {
return (
<TableRow className="group border-border/60">
<TableRow className="group border-border/60" data-state={selected ? "selected" : undefined}>
<TableCell>
<Checkbox
checked={selected}
onCheckedChange={(checked) => onSelectedChange(task.id, checked === true)}
aria-label={`选择任务 ${task.id}`}
/>
</TableCell>
<TableCell>
<code className="bg-muted rounded px-1.5 py-0.5 font-mono text-xs">{task.id}</code>
</TableCell>
@@ -554,6 +691,117 @@ const deleteOptionKeys: (keyof DeleteTaskOptions)[] = [
"delete_llm_records",
];
// DeleteOptionFields renders the「同时清理关联数据」checkbox block shared by the
// single-task and bulk delete dialogs. idPrefix keeps the label/input ids unique when
// several dialogs live in the same table.
function DeleteOptionFields({
idPrefix,
options,
onOptionsChange,
disabled,
}: {
idPrefix: string;
options: DeleteTaskOptions;
onOptionsChange: React.Dispatch<React.SetStateAction<DeleteTaskOptions>>;
disabled: boolean;
}) {
const selectedCount = deleteOptionKeys.filter((key) => options[key]).length;
let allChecked: boolean | "indeterminate" = false;
if (selectedCount === deleteOptionKeys.length) {
allChecked = true;
} else if (selectedCount > 0) {
allChecked = "indeterminate";
}
const updateOption = (key: keyof DeleteTaskOptions, checked: boolean) => {
onOptionsChange((current) => ({ ...current, [key]: checked }));
};
const updateAllOptions = (checked: boolean) => {
onOptionsChange({
delete_assets: checked,
delete_traffic: checked,
delete_files: checked,
delete_findings: checked,
delete_llm_records: checked,
});
};
return (
<FieldSet disabled={disabled}>
<FieldLegend variant="label">同时清理关联数据</FieldLegend>
<FieldGroup className="gap-3">
<Field orientation="horizontal">
<Checkbox
id={`delete-all-${idPrefix}`}
checked={allChecked}
onCheckedChange={(checked) => updateAllOptions(checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-all-${idPrefix}`}>全部删除</FieldLabel>
<FieldDescription>选中下方全部关联数据,包括资产、流量、文件、漏洞和 LLM 请求/响应记录。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-assets-${idPrefix}`}
checked={options.delete_assets}
onCheckedChange={(checked) => updateOption("delete_assets", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-assets-${idPrefix}`}>关联资产</FieldLabel>
<FieldDescription>删除仅属于该任务的资产;共享资产只解除当前任务关联。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-traffic-${idPrefix}`}
checked={options.delete_traffic}
onCheckedChange={(checked) => updateOption("delete_traffic", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-traffic-${idPrefix}`}>关联流量</FieldLabel>
<FieldDescription>按关联资产的精确主机名删除;仍被其他任务引用的共享主机流量会保留。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-files-${idPrefix}`}
checked={options.delete_files}
onCheckedChange={(checked) => updateOption("delete_files", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-files-${idPrefix}`}>任务文件</FieldLabel>
<FieldDescription>删除该任务工作目录中的上传文件、命令输出和其他产物。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-findings-${idPrefix}`}
checked={options.delete_findings}
onCheckedChange={(checked) => updateOption("delete_findings", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-findings-${idPrefix}`}>关联漏洞</FieldLabel>
<FieldDescription>永久删除该任务产生的独立漏洞记录与漏洞报告。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-llm-records-${idPrefix}`}
checked={options.delete_llm_records}
onCheckedChange={(checked) => updateOption("delete_llm_records", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-llm-records-${idPrefix}`}>LLM 请求/响应记录</FieldLabel>
<FieldDescription>永久删除该任务录制的 LLM 请求、响应、Token 与错误详情。</FieldDescription>
</FieldContent>
</Field>
</FieldGroup>
</FieldSet>
);
}
function DeleteTaskDialog({
task,
onDelete,
@@ -565,29 +813,6 @@ function DeleteTaskDialog({
const [deleting, setDeleting] = React.useState(false);
const [options, setOptions] = React.useState<DeleteTaskOptions>(emptyDeleteOptions);
const selectedCount = deleteOptionKeys.filter((key) => options[key]).length;
const allSelected = selectedCount === deleteOptionKeys.length;
let allChecked: boolean | "indeterminate" = false;
if (allSelected) {
allChecked = true;
} else if (selectedCount > 0) {
allChecked = "indeterminate";
}
const updateOption = (key: keyof DeleteTaskOptions, checked: boolean) => {
setOptions((current) => ({ ...current, [key]: checked }));
};
const updateAllOptions = (checked: boolean) => {
setOptions({
delete_assets: checked,
delete_traffic: checked,
delete_files: checked,
delete_findings: checked,
delete_llm_records: checked,
});
};
const handleOpenChange = (next: boolean) => {
if (deleting) return;
setOpen(next);
@@ -621,77 +846,12 @@ function DeleteTaskDialog({
的执行记录与探索链路将被永久删除。
</AlertDialogDescription>
</AlertDialogHeader>
<FieldSet disabled={deleting}>
<FieldLegend variant="label">同时清理关联数据</FieldLegend>
<FieldGroup className="gap-3">
<Field orientation="horizontal">
<Checkbox
id={`delete-all-${task.id}`}
checked={allChecked}
onCheckedChange={(checked) => updateAllOptions(checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-all-${task.id}`}>全部删除</FieldLabel>
<FieldDescription>选中下方全部关联数据,包括资产、流量、文件、漏洞和 LLM 请求/响应记录。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-assets-${task.id}`}
checked={options.delete_assets}
onCheckedChange={(checked) => updateOption("delete_assets", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-assets-${task.id}`}>关联资产</FieldLabel>
<FieldDescription>删除仅属于该任务的资产;共享资产只解除当前任务关联。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-traffic-${task.id}`}
checked={options.delete_traffic}
onCheckedChange={(checked) => updateOption("delete_traffic", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-traffic-${task.id}`}>关联流量</FieldLabel>
<FieldDescription>按关联资产的精确主机名删除;仍被其他任务引用的共享主机流量会保留。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-files-${task.id}`}
checked={options.delete_files}
onCheckedChange={(checked) => updateOption("delete_files", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-files-${task.id}`}>任务文件</FieldLabel>
<FieldDescription>删除该任务工作目录中的上传文件、命令输出和其他产物。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-findings-${task.id}`}
checked={options.delete_findings}
onCheckedChange={(checked) => updateOption("delete_findings", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-findings-${task.id}`}>关联漏洞</FieldLabel>
<FieldDescription>永久删除该任务产生的独立漏洞记录与漏洞报告。</FieldDescription>
</FieldContent>
</Field>
<Field orientation="horizontal">
<Checkbox
id={`delete-llm-records-${task.id}`}
checked={options.delete_llm_records}
onCheckedChange={(checked) => updateOption("delete_llm_records", checked === true)}
/>
<FieldContent>
<FieldLabel htmlFor={`delete-llm-records-${task.id}`}>LLM 请求/响应记录</FieldLabel>
<FieldDescription>永久删除该任务录制的 LLM 请求、响应、Token 与错误详情。</FieldDescription>
</FieldContent>
</Field>
</FieldGroup>
</FieldSet>
<DeleteOptionFields
idPrefix={task.id}
options={options}
onOptionsChange={setOptions}
disabled={deleting}
/>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>取消</AlertDialogCancel>
<AlertDialogAction
@@ -711,6 +871,90 @@ function DeleteTaskDialog({
);
}
// BulkDeleteTasksDialog deletes every checked task with one shared set of cleanup options.
// The backend has no batch endpoint, so deletion runs one task at a time (see deleteTasks)
// and the button shows live progress.
function BulkDeleteTasksDialog({
ids,
onDelete,
}: {
ids: string[];
onDelete: (
ids: string[],
options: DeleteTaskOptions,
onProgress: (done: number) => void,
) => Promise<void>;
}) {
const [open, setOpen] = React.useState(false);
const [deleting, setDeleting] = React.useState(false);
const [done, setDone] = React.useState(0);
const [options, setOptions] = React.useState<DeleteTaskOptions>(emptyDeleteOptions);
const handleOpenChange = (next: boolean) => {
if (deleting) return;
setOpen(next);
if (next) {
setOptions(emptyDeleteOptions());
setDone(0);
}
};
const handleDelete = async () => {
setDeleting(true);
setDone(0);
try {
await onDelete(ids, options, setDone);
setOpen(false);
} finally {
setDeleting(false);
}
};
return (
<AlertDialog open={open} onOpenChange={handleOpenChange}>
<AlertDialogTrigger asChild>
<Button size="sm" variant="outline">
<Trash2Icon className="text-destructive" /> 删除所选 {ids.length}
</Button>
</AlertDialogTrigger>
<AlertDialogContent className="max-h-[85vh] overflow-y-auto">
<AlertDialogHeader>
<AlertDialogTitle>确认删除所选 {ids.length} 个任务?</AlertDialogTitle>
<AlertDialogDescription>
这些任务的执行记录与探索链路将被永久删除,下方清理选项对所选任务统一生效。
</AlertDialogDescription>
</AlertDialogHeader>
<div className="text-muted-foreground flex flex-wrap gap-1 text-xs">
{ids.slice(0, 30).map((id) => (
<code key={id} className="bg-muted rounded px-1.5 py-0.5 font-mono">#{id}</code>
))}
{ids.length > 30 && <span className="self-center">…等 {ids.length} 个</span>}
</div>
<DeleteOptionFields
idPrefix="bulk"
options={options}
onOptionsChange={setOptions}
disabled={deleting}
/>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>取消</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={deleting}
onClick={(event) => {
event.preventDefault();
void handleDelete();
}}
>
{deleting && <Spinner data-icon="inline-start" />}
{deleting ? `删除中 ${done}/${ids.length}` : `删除 ${ids.length} 个任务`}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
// CreateTaskSheet is the 新建任务 drawer. Its form state lives HERE, not in TasksPage: with
// 描述/目标 held by the page component every keystroke re-rendered the whole task table
// behind the drawer (plus its sticky column and 20 AlertDialog trees), which showed up as
@@ -872,7 +1116,7 @@ function CreateTaskSheet({ tasks, onCreated }: { tasks: Task[]; onCreated: () =>
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button size="sm" className="ml-auto">
<Button size="sm">
<PlusIcon /> 新建任务
</Button>
</SheetTrigger>