agenthub/frontend/app/office/page.tsx

243 lines
9.2 KiB
TypeScript

"use client";
// 办公室:左边是像素办公室实时画面,右边是这个 Agent 的控制台 ——
// 状态、正在做的事、最近产出,以及一个直接下指令的输入框。
import { Building2, Send } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useLive } from "@/components/LiveProvider";
import { OfficeScene } from "@/components/OfficeScene";
import {
Badge,
Chip,
Dot,
Empty,
ErrorNote,
KV,
Pager,
Panel,
PixelButton,
Spinner,
Textarea,
usePaged,
} from "@/components/ui";
import { api } from "@/lib/api";
import { agentTypeLabel, connectionMode, relTime, tone } from "@/lib/format";
import { useAsync } from "@/lib/useAsync";
export default function OfficePage() {
const { revision, status } = useLive();
const agents = useAsync(() => api.agents(), [revision]);
const tasks = useAsync(() => api.tasks({ limit: 80 }), [revision]);
const [selected, setSelected] = useState("");
const [prompt, setPrompt] = useState("");
const [busy, setBusy] = useState(false);
const [failed, setFailed] = useState("");
// `?? []` 每次渲染都会造一个新数组,直接塞进 useEffect 依赖会让它每帧都跑一遍
// —— 这正是 lint 那条 exhaustive-deps 警告的意思,用 useMemo 固定住引用。
const roster = useMemo(() => agents.data ?? [], [agents.data]);
const jobs = useMemo(() => tasks.data ?? [], [tasks.data]);
const current = roster.find((agent) => agent.id === selected) ?? roster.find((agent) => agent.name === selected);
useEffect(() => {
if (!selected && roster.length) setSelected(roster[0].id);
}, [roster, selected]);
const mine = current
? jobs.filter((job) => job.agent_id === current.id || job.agent_name === current.name)
: [];
const inflight = mine.filter((job) => job.status === "running" || job.status === "queued");
const produced = mine.filter((job) => job.status === "completed");
const crewPage = usePaged(roster, 12);
const inflightPage = usePaged(inflight, 5);
const producedPage = usePaged(produced, 5);
const dispatch = async () => {
if (!current || !prompt.trim()) return;
setBusy(true);
setFailed("");
try {
await api.createTask({ prompt: prompt.trim(), agent_id: current.name });
setPrompt("");
tasks.reload();
} catch (exc) {
setFailed(exc instanceof Error ? exc.message : String(exc));
} finally {
setBusy(false);
}
};
return (
<div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_370px]">
<Panel
title="办公室"
icon={<Building2 size={13} />}
>
{agents.error && <ErrorNote error={agents.error} />}
{agents.loading && !agents.data && <Spinner />}
{agents.data && roster.length === 0 ? (
<Empty title="办公室还空着" />
) : (
<div className="overflow-x-auto">
<OfficeScene
agents={roster}
tasks={jobs}
live={status === "open"}
selected={selected}
onSelect={(agent) => setSelected(agent.id)}
/>
</div>
)}
<div className="mt-2 flex flex-wrap items-center gap-2">
{crewPage.rows.map((agent) => (
<Chip
key={agent.id}
on={current?.id === agent.id || current?.name === agent.name}
onClick={() => setSelected(agent.id)}
>
<Dot tone={tone(agent.status)} pulse={agent.live} />
{agent.emoji ? agent.emoji + " " : ""}
{agent.display_name || agent.name}
</Chip>
))}
</div>
<Pager
page={crewPage.page}
pageCount={crewPage.pageCount}
total={crewPage.total}
pageSize={crewPage.pageSize}
onPage={crewPage.setPage}
onPageSize={crewPage.setPageSize}
sizes={[12, 24, 48]}
/>
</Panel>
<Panel
title={current ? (current.emoji ? current.emoji + " " : "") + (current.display_name || current.name) : "控制台"}
icon={<Send size={13} />}
actions={
current && (
<Link href={"/agents/" + encodeURIComponent(current.id)} className="pixel-link text-[12px]">
完整档案 →
</Link>
)
}
>
{!current ? (
<Empty title="未选择 Agent" />
) : (
<div className="grid min-w-0 gap-3">
<div className="flex flex-wrap items-center gap-1">
<Badge tone={tone(current.status)}>
<Dot tone={tone(current.status)} pulse={current.live} />
{current.status}
</Badge>
<Badge tone={current.agent_type === "custom" ? "gray" : "accent"}>
{agentTypeLabel(current.agent_type)}
</Badge>
<Badge>{current.driver}</Badge>
<Badge>{current.deployment_kind}</Badge>
<Badge tone="green">{connectionMode(current.connection_mode)}</Badge>
<Badge>
负载 {current.active_tasks}/{current.max_concurrency}
</Badge>
</div>
<KV
rows={[
["name", current.name],
["model", current.model || "-"],
["心跳", current.heartbeat_age_s === null ? "-" : Math.round(current.heartbeat_age_s) + "s 前"],
["部署", current.deployment_ref || "-"],
...(current.last_error ? ([["错误", current.last_error]] as [string, string][]) : []),
]}
/>
<div className="min-w-0">
<p className="pixel-title pb-1">正在做</p>
{inflight.length === 0 ? (
<p className="pixel-muted">空闲</p>
) : (
<>
<ul className="grid gap-1 pr-1">
{inflightPage.rows.map((job) => (
<li key={job.id} className="min-w-0">
<Link href={"/tasks/" + job.id} className="flex items-start gap-2">
<Dot tone={tone(job.status)} pulse />
<span className="min-w-0 flex-1 truncate">{job.title || job.prompt}</span>
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">{relTime(job.started_at ?? job.created_at)}</span>
</Link>
</li>
))}
</ul>
<Pager
page={inflightPage.page}
pageCount={inflightPage.pageCount}
total={inflightPage.total}
pageSize={inflightPage.pageSize}
onPage={inflightPage.setPage}
onPageSize={inflightPage.setPageSize}
sizes={[5, 10, 20]}
/>
</>
)}
</div>
<div className="min-w-0">
<p className="pixel-title pb-1">最近产出</p>
{produced.length === 0 ? (
<p className="pixel-muted">还没有产出</p>
) : (
<>
<ul className="grid gap-2 pr-1">
{producedPage.rows.map((job) => (
<li key={job.id} className="min-w-0 border-2 border-[var(--pixel-border)] bg-[var(--pixel-panel-fill)] px-2 py-1">
<Link href={"/tasks/" + job.id} className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate">{job.title || job.prompt}</span>
<span className="pixel-muted pixel-mono shrink-0 text-[12px]">{relTime(job.finished_at)}</span>
</Link>
<p className="pixel-muted line-clamp-2 min-w-0 pt-1 text-[12px] leading-snug break-words">
{job.result || "(空结果)"}
</p>
</li>
))}
</ul>
<Pager
page={producedPage.page}
pageCount={producedPage.pageCount}
total={producedPage.total}
pageSize={producedPage.pageSize}
onPage={producedPage.setPage}
onPageSize={producedPage.setPageSize}
sizes={[5, 10, 20]}
/>
</>
)}
</div>
<div>
<p className="pixel-title pb-1">给它下指令</p>
<Textarea
value={prompt}
onChange={(event) => setPrompt(event.target.value)}
placeholder={"例:帮我看看 deploy/nanobot-duo 的 compose 文件有没有问题"}
onKeyDown={(event) => {
if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) void dispatch();
}}
/>
{failed && <ErrorNote error={failed} />}
<div className="flex items-center gap-2 pt-2">
<PixelButton variant="primary" onClick={() => void dispatch()} disabled={busy || !prompt.trim()}>
{busy ? "派发中" : "派活"}
</PixelButton>
</div>
</div>
</div>
)}
</Panel>
</div>
);
}