agenthub/frontend/app/page.tsx

625 lines
20 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
// 总览:hub 健康度 + 正在跑的活 + 吞吐健康度 + 最近产出。
// 布局约定:页面没有任何头部(派活在顶栏),只有一个面板网格;
// 行高在所有断点都固定(auto-rows),面板由 grid 拉伸到行高,所以永远一样高。
// 一个数字只出现在一处。
import { Activity, Bot, Boxes, Gauge, RefreshCw, Users, XCircle } from "lucide-react";
import Link from "next/link";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useLive } from "@/components/LiveProvider";
import {
Badge,
CopyButton,
Dot,
Empty,
ErrorNote,
KV,
Pager,
Panel,
PixelButton,
Spinner,
useConfirm,
usePaged,
useToast,
} from "@/components/ui";
import { api } from "@/lib/api";
import { duration, relTime, secondsAgo, shortId, tone, uptime } from "@/lib/format";
import { useAsync } from "@/lib/useAsync";
import type { Agent, Run, Task } from "@/lib/types";
/** 实时帧很密:把 socket revision 折叠成最多每 `ms` 一次刷新(trailing,最后一次不丢)。 */
function useLiveTick(ms = 3000) {
const { revision } = useLive();
const [tick, setTick] = useState(0);
const last = useRef(0);
useEffect(() => {
if (!revision) return;
const timer = setTimeout(
() => {
last.current = Date.now();
setTick((value) => value + 1);
},
Math.max(0, ms - (Date.now() - last.current)),
);
return () => clearTimeout(timer);
}, [revision, ms]);
return tick;
}
/** 页面时钟:让"已跑时长"和 24h 窗口随秒走动,而不是停在渲染那一刻。 */
function useNow(intervalMs = 1000) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(timer);
}, [intervalMs]);
return now;
}
const TASK_ORDER = ["running", "queued", "completed", "failed", "cancelled"];
const TASK_TINT: Record<string, string> = {
running: "var(--pixel-yellow)",
queued: "var(--pixel-yellow)",
completed: "var(--pixel-green)",
failed: "var(--pixel-red)",
cancelled: "var(--pixel-muted)",
};
/** 一行三个面板,行高在所有断点都固定 —— 面板自己不定高,由 grid 拉到一样高。
* 340 = 面板头 44 + 列表 4 行两行式(~202)+ Pager 55 + 边框余量,
* 所以每页刚好装满,不会出现半行被切,也不会出现矮一截的面板。 */
const GRID = "grid auto-rows-[340px] grid-cols-1 gap-3 lg:grid-cols-3";
const PANEL = "flex min-h-0 min-w-0 flex-col";
const PANEL_BODY = "flex min-h-0 flex-1 flex-col p-0";
const WIDE = " lg:col-span-2";
/** 把 { connector: 3, nanobot: 4 } 画成按数量降序的小 chip,一行放不下就整体换行。 */
const chips = (counts: Record<string, number> | undefined) => {
const rows = Object.entries(counts ?? {}).sort(
(a, b) => b[1] - a[1] || a[0].localeCompare(b[0]),
);
return rows.length ? (
rows.map(([key, value]) => (
<Badge key={key}>
{key} {value}
</Badge>
))
) : (
<span className="pixel-mono">-</span>
);
};
const byNewest = <T extends { created_at: string }>(rows: T[]) =>
[...rows].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
/** 在途任务已经跑了多久 / 排队等了多久。 */
const elapsed = (task: Task, now: number) => {
const from = task.status === "queued" ? task.created_at : (task.started_at ?? task.created_at);
const ms = now - new Date(from).getTime();
return Number.isFinite(ms) && ms >= 0 ? duration(ms / 1000) : "-";
};
/** 近 24h 逐小时完成/失败,按结束时间落桶。 */
const hourly = (rows: Task[], now: number) => {
const buckets = Array.from({ length: 24 }, () => ({ done: 0, failed: 0 }));
for (const task of rows) {
if (task.status !== "completed" && task.status !== "failed") continue;
const ended = new Date(task.finished_at ?? task.created_at).getTime();
const index = 23 - Math.floor((now - ended) / 3600_000);
if (index < 0 || index > 23) continue;
buckets[index][task.status === "completed" ? "done" : "failed"] += 1;
}
return buckets;
};
function List({ children }: { children: ReactNode }) {
return <ul className="grid grid-cols-1 gap-0.5 p-1.5">{children}</ul>;
}
/** 居中的空态/加载态:把面板剩下的空间填满,不让面板看起来缺一块。 */
function Centered({ children }: { children: ReactNode }) {
return <div className="flex min-h-0 flex-1 items-center justify-center">{children}</div>;
}
/** 跳到列表页的出口:所有面板的"全部"长一个样。 */
const AllLink = ({ href }: { href: string }) => (
<Link href={href} className="pixel-link shrink-0 text-[12px]">
全部 →
</Link>
);
/** 列表面板:内容超出就在面板内滚动,Pager 始终贴底对齐。 */
function ListPanel<T>({
title,
icon,
badge,
href,
wide = false,
rows,
loading,
empty,
pageSize,
sizes,
render,
}: {
title: string;
icon: ReactNode;
badge?: ReactNode;
href?: string;
wide?: boolean;
rows: T[];
loading: boolean;
empty: string;
pageSize: number;
sizes: number[];
render: (row: T) => ReactNode;
}) {
const paged = usePaged(rows, pageSize);
return (
<Panel
title={title}
icon={icon}
className={PANEL + (wide ? WIDE : "")}
bodyClass={PANEL_BODY}
actions={
<>
{badge}
{href && <AllLink href={href} />}
</>
}
>
{loading && rows.length === 0 ? (
<Centered>
<Spinner />
</Centered>
) : paged.total === 0 ? (
<Centered>
<Empty title={empty} />
</Centered>
) : (
<>
<div className="min-h-0 flex-1 overflow-y-auto">
<List>{paged.rows.map((row) => render(row))}</List>
</div>
<Pager
page={paged.page}
pageCount={paged.pageCount}
total={paged.total}
pageSize={paged.pageSize}
onPage={paged.setPage}
onPageSize={paged.setPageSize}
sizes={sizes}
/>
</>
)}
</Panel>
);
}
/** 状态分布 + 健康度 + 近 24h 节奏。分布用 hub 的全量计数,节奏用任务采样。 */
function ThroughputPanel({
counts,
rows,
now,
}: {
counts: Record<string, number>;
rows: Task[];
now: number;
}) {
const states = TASK_ORDER.filter((key) => counts[key]);
const total = states.reduce((sum, key) => sum + (counts[key] ?? 0), 0);
const settled = (counts.completed ?? 0) + (counts.failed ?? 0);
const rate = settled ? Math.round(((counts.completed ?? 0) / settled) * 100) : null;
const done = rows.filter((task) => task.status === "completed" && task.duration_s !== null);
const avg = done.length
? done.reduce((sum, task) => sum + (task.duration_s ?? 0), 0) / done.length
: null;
const last24 = rows.filter((task) => new Date(task.created_at).getTime() >= now - 86400_000);
const hours = hourly(rows, now);
const peak = Math.max(1, ...hours.map((bucket) => bucket.done + bucket.failed));
return (
<Panel
title="任务吞吐"
icon={<Gauge size={14} />}
className={PANEL + WIDE}
bodyClass="grid min-h-0 flex-1 gap-4 overflow-y-auto p-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)]"
>
<div className="grid content-start gap-3">
<div className="flex h-3 overflow-hidden rounded border-2 border-[var(--pixel-border)]">
{states.map((key) => (
<span
key={key}
style={{
width: ((counts[key] ?? 0) / Math.max(1, total)) * 100 + "%",
background: TASK_TINT[key],
}}
/>
))}
</div>
<div className="grid gap-1">
{states.map((key) => (
<span key={key} className="flex items-center gap-2 text-[12px]">
<Dot tone={tone(key)} />
<span className="w-[74px] shrink-0">{key}</span>
<span className="h-2 flex-1 border border-[var(--pixel-border-soft)]">
<span
className="block h-full"
style={{
width: ((counts[key] ?? 0) / Math.max(1, total)) * 100 + "%",
background: TASK_TINT[key],
}}
/>
</span>
<span className="pixel-mono w-9 shrink-0 text-right">{counts[key]}</span>
<span className="pixel-muted pixel-mono w-9 shrink-0 text-right">
{Math.round(((counts[key] ?? 0) / Math.max(1, total)) * 100)}%
</span>
</span>
))}
</div>
<KV
rows={[
["成功率", rate === null ? "-" : rate + "%"],
["平均耗时", duration(avg)],
[
"近 24h",
last24.length
? "完成 " +
last24.filter((task) => task.status === "completed").length +
" · 失败 " +
last24.filter((task) => task.status === "failed").length
: "无任务",
],
]}
/>
</div>
<div className="flex min-h-0 flex-col gap-1">
<span className="pixel-title">近 24h 逐小时</span>
<div className="flex min-h-14 flex-1 items-end gap-px border-b-2 border-[var(--pixel-border-soft)]">
{hours.map((bucket, index) => (
<span
key={index}
className="flex h-full flex-1 flex-col justify-end overflow-hidden"
title={-(23 - index) + "h:完成 " + bucket.done + " · 失败 " + bucket.failed}
>
{bucket.failed > 0 && (
<span
style={{ height: (bucket.failed / peak) * 100 + "%", background: "var(--pixel-red)" }}
/>
)}
{bucket.done > 0 && (
<span
style={{
height: (bucket.done / peak) * 100 + "%",
background: "var(--pixel-green)",
}}
/>
)}
</span>
))}
</div>
<span className="pixel-muted pixel-mono flex justify-between text-[11px]">
<span>-24h</span>
<span>现在</span>
</span>
</div>
</Panel>
);
}
export default function DashboardPage() {
const tick = useLiveTick();
const confirm = useConfirm();
const toast = useToast();
const now = useNow();
const meta = useAsync(() => api.meta(), []);
const teams = useAsync(() => api.teams(), []);
const stats = useAsync(() => api.stats(), [tick]);
const agents = useAsync(() => api.agents(), [tick]);
const tasks = useAsync(() => api.tasks({ limit: 300 }), [tick]);
const runs = useAsync(() => api.runs(), [tick]);
const hub = stats.data?.hub;
const bus = hub?.bus ?? {};
const dropped = Number(bus.dropped ?? 0);
const counts = stats.data?.tasks.by_status ?? {};
const sample = tasks.data ?? [];
const inflight = sample.filter((task) => task.status === "running" || task.status === "queued");
const failed = byNewest(sample.filter((task) => task.status === "failed"));
const failed24 = failed.filter(
(task) => new Date(task.created_at).getTime() >= now - 86400_000,
).length;
const agentIndex = new Map<string, Agent>();
(agents.data ?? []).forEach((agent) => {
agentIndex.set(agent.id, agent);
agentIndex.set(agent.name, agent);
});
const agentOf = (task: Task) => agentIndex.get(task.agent_id) ?? agentIndex.get(task.agent_name);
const online = stats.data?.agents.online_live ?? 0;
const total = stats.data?.agents.total ?? 0;
const roster = [...(agents.data ?? [])].sort(
(a, b) =>
Number(b.live) - Number(a.live) ||
(a.heartbeat_age_s ?? 1e12) - (b.heartbeat_age_s ?? 1e12) ||
a.name.localeCompare(b.name),
);
const runList = byNewest(runs.data ?? []);
// Agent 侧唯一要抄的东西:hub 地址(凭证在「接入」页签发)
const hubUrl = meta.data ? (
<span className="flex items-center gap-1">
<span className="pixel-mono">{meta.data.url}</span>
<CopyButton text={meta.data.url} label="复制" />
</span>
) : (
"-"
);
const busValue = (
<>
发布 {Number(bus.published ?? 0)} ·{" "}
<span className={dropped > 0 ? "text-[var(--pixel-red)]" : ""}>丢弃 {dropped}</span> · 订阅{" "}
{Number(bus.subscribers ?? 0)}
</>
);
const reloadAll = () => {
meta.reload();
teams.reload();
stats.reload();
agents.reload();
tasks.reload();
runs.reload();
};
const cancel = async (task: Task) => {
const ok = await confirm({ title: "取消任务?", confirmLabel: "取消任务", danger: true });
if (!ok) return;
try {
await api.cancelTask(task.id);
toast("ok", "已发出取消信号");
tasks.reload();
} catch (exc) {
toast("error", exc instanceof Error ? exc.message : String(exc));
}
};
const taskRow = (task: Task) => {
const agent = agentOf(task);
return (
<li
key={task.id}
className="flex flex-col gap-0.5 hover:bg-[var(--pixel-row-hover)]"
>
<span className="flex items-center gap-2">
<Dot tone={tone(task.status)} pulse={task.status === "running"} />
<Link
className="pixel-link min-w-0 flex-1 truncate"
href={"/tasks/" + task.id}
title={task.title || task.prompt}
>
{task.title || task.prompt || shortId(task.id)}
</Link>
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">{elapsed(task, now)}</span>
</span>
<span className="flex items-center gap-2 pl-5">
{agent ? (
<Link
className="pixel-link pixel-mono min-w-0 truncate text-[12px]"
href={"/agents/" + agent.name}
>
{agent.emoji} {agent.display_name || agent.name}
</Link>
) : (
<span className="pixel-muted shrink-0 text-[12px]">未分配</span>
)}
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">
{task.source || "console"}
</span>
<PixelButton
size="sm"
variant="danger"
onClick={() => cancel(task)}
className="ml-auto shrink-0"
>
<XCircle size={12} />
取消
</PixelButton>
</span>
</li>
);
};
const failedRow = (task: Task) => {
const agent = agentOf(task);
return (
<li
key={task.id}
className="flex flex-col gap-0.5 hover:bg-[var(--pixel-row-hover)]"
>
<span className="flex items-center gap-2">
<Dot tone="red" />
<Link className="pixel-link min-w-0 flex-1 truncate" href={"/tasks/" + task.id}>
{task.title || shortId(task.id)}
</Link>
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">
{relTime(task.created_at)}
</span>
</span>
<span className="pixel-muted pixel-mono truncate pl-5 text-[12px]">
{(agent ? (agent.display_name || agent.name) + " · " : "") +
(task.error.split("\n")[0] || "-")}
</span>
</li>
);
};
const agentRow = (agent: Agent) => (
<li key={agent.id} className="flex items-center gap-2 hover:bg-[var(--pixel-row-hover)]">
<Dot tone={tone(agent.status)} pulse={agent.live} />
<span className="min-w-0 flex-1">
<Link
className="pixel-link block truncate text-[14px]"
href={"/agents/" + agent.name}
>
{agent.emoji} {agent.display_name || agent.name}
</Link>
<span className="pixel-muted pixel-mono block truncate text-[12px]">
{agent.driver} · {agent.deployment_kind} · {secondsAgo(agent.heartbeat_age_s)}
</span>
</span>
<span className="pixel-mono shrink-0 text-right text-[12px]">
{agent.active_tasks}/{agent.max_concurrency}
</span>
</li>
);
const teamRow = (team: { id: string; name: string; playbook: string; member_count: number }) => (
<li key={team.id} className="flex items-center gap-2 hover:bg-[var(--pixel-row-hover)]">
<Link className="pixel-link min-w-0 flex-1 truncate" href={"/teams/" + team.name}>
{team.name}
</Link>
<Badge>{team.playbook || "-"}</Badge>
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">{team.member_count} 人</span>
</li>
);
const runRow = (run: Run) => (
<li
key={run.id}
className="flex flex-col gap-0.5 hover:bg-[var(--pixel-row-hover)]"
>
<span className="flex items-center gap-2">
<Dot tone={tone(run.status)} pulse={run.status === "running"} />
<Link className="pixel-link min-w-0 flex-1 truncate" href={"/runs/" + run.id} title={run.objective}>
{run.objective || shortId(run.id)}
</Link>
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">{relTime(run.created_at)}</span>
</span>
<span className="pixel-muted pixel-mono truncate pl-5 text-[12px]">
{run.status} · {duration(run.duration_s)}
</span>
</li>
);
return (
<div className="grid gap-3">
<ErrorNote error={stats.error ?? tasks.error ?? agents.error ?? runs.error} />
<div className={GRID}>
<Panel
title="Hub 状态"
icon={<Gauge size={14} />}
className={PANEL}
bodyClass="min-h-0 flex-1 overflow-y-auto p-3"
actions={
<PixelButton size="sm" icon aria-label="重载" title="重载" onClick={reloadAll}>
<RefreshCw size={12} />
</PixelButton>
}
>
<KV
rows={[
["版本", "v" + (meta.data?.version ?? "-")],
["接入地址", hubUrl],
["运行时长", hub ? uptime(hub.uptime_s) : "-"],
["Gateway", (hub?.connector_connections ?? 0) + " 连接"],
["消息总线", busValue],
]}
/>
<div className="pixel-muted mt-2 grid gap-1.5 border-t-[2px] border-[var(--pixel-border-soft)] pt-2 text-[12px]">
<span className="flex flex-wrap items-center gap-1">
接入方式 {chips(stats.data?.agents.by_driver)}
</span>
<span className="flex flex-wrap items-center gap-1">
部署形态 {chips(stats.data?.agents.by_deployment)}
</span>
</div>
</Panel>
<ListPanel
title="当前在途"
icon={<Activity size={14} />}
badge={
<Badge tone={inflight.length ? "yellow" : "gray"}>
{inflight.length} 在跑 · {sample.filter((task) => task.status === "queued").length} 排队
</Badge>
}
href="/tasks"
rows={inflight}
loading={tasks.loading}
empty="没有任务在跑"
pageSize={4}
sizes={[4, 10, 20]}
render={taskRow}
/>
<ListPanel
title="Agent 概览"
icon={<Bot size={14} />}
badge={
<Badge tone={online ? "green" : "red"}>
{online} / {total} 在线
</Badge>
}
href="/agents"
rows={roster}
loading={agents.loading}
empty="还没有 Agent"
pageSize={4}
sizes={[4, 10, 20]}
render={agentRow}
/>
<ThroughputPanel counts={counts} rows={sample} now={now} />
<ListPanel
title="最近异常"
icon={<XCircle size={14} />}
badge={failed24 ? <Badge tone="red">近 24h 失败 {failed24}</Badge> : undefined}
href="/tasks"
rows={failed}
loading={tasks.loading}
empty="暂无失败任务"
pageSize={4}
sizes={[4, 10, 20]}
render={failedRow}
/>
<ListPanel
title="最近 Runs"
icon={<Boxes size={14} />}
wide
rows={runList}
loading={runs.loading}
empty="还没有协作 Run"
pageSize={4}
sizes={[4, 10, 20]}
render={runRow}
/>
<ListPanel
title="团队"
icon={<Users size={14} />}
href="/teams"
rows={teams.data ?? []}
loading={teams.loading}
empty="还没有团队"
pageSize={7}
sizes={[7, 20, 50]}
render={teamRow}
/>
</div>
</div>
);
}