Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/frontend/packages/swarm-ui/src/pages/AgentsPage.tsx
iris 2874badd4c swarm-ui: use ConfirmDialog for the stop confirmation too
mara: "use the new component where we already have confirm dialogs."
The stop/offline direction of the wanted toggle used a native
window.confirm -- the reasoning at the time was that a hand-rolled
Dialog felt heavy for a reversible action, with the real Dialog confirm
reserved for the irreversible destroy direction. Now that
ConfirmDialog is a one-line-per-caller shared component, that argument
no longer buys consistency anything, so both directions confirm the
same way.
2026-09-07 19:07:21 +02:00

463 lines
18 KiB
TypeScript

// <AgentsPage> — the swarm's agent roster, merged with each agent's open
// config-PR status, swarm-wide health status, and declared wanted state
// in the same table. Three separate asks (a roster listing, a per-agent
// config-PR indicator, and per-agent status/liveness) that turned out to
// be one page: a roster with no per-row detail is thin, and neither a
// config-PR panel nor a status panel has anything to render against
// without a roster to embed in.
//
// One fetch, on a refresh-interval cadence like HivesPage: `GET
// /api/agents/status` — one row per roster agent (identity store is the
// roster, so a never-reported agent still gets a row), each already
// carrying its freshness/snapshot/config PR/wanted state. That merge
// used to be three separate fetches (`/api/agents`, `/api/config-prs`,
// `/api/agents/status`) joined client-side by name; per operator review
// feedback ("the view should be filled by a single backend call") the
// join moved server-side instead — see `swarm-controller/src/main.rs`'s
// `get_agents_status` handler for where `config_pr`/`wanted` get merged
// in and why that's the handler's job rather than
// `agent_status::AgentStatusReader`'s. No more per-page joining left to
// do here: the wire row *is* the table row.
//
// Owns the "+ agent" trigger too — the roster this populates is the
// natural home for the action that populates it; a separate top-level
// nav entry would be one click of indirection for no benefit. The form
// itself (`CreateAgentForm`) mounts inside a `Dialog` here rather than
// its own route.
//
// The "wanted" column is the start/stop control (`toggleWanted`) plus a
// separate destroy control (`destroyAgent`) — both confirm via the
// shared `ui/confirm-dialog`.
import { useState } from "preact/hooks";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Badge, type BadgeTone } from "@hive/shared/badge.js";
import { Button } from "../ui/button/Button.js";
import { ConfirmDialog } from "../ui/confirm-dialog/ConfirmDialog.js";
import { Dialog } from "../ui/dialog/Dialog.js";
import { Panel } from "../ui/panel/Panel.js";
import { RelativeTime } from "../ui/relative-time/RelativeTime.js";
import {
RefreshIntervalPicker,
useRefreshInterval,
type RefreshIntervalMs,
} from "../ui/refresh-interval/RefreshInterval.js";
import { Table, type TableColumn } from "../ui/table/Table.js";
import { CreateAgentForm } from "./CreateAgentForm.js";
interface ConfigPrStatus {
pr_number: number;
html_url: string | null;
}
type Freshness = "fresh" | "stale" | "never_reported" | "unknown";
interface AgentStatusSnapshot {
status_text: string | null;
status_set_at: number | null;
running: boolean;
}
// `"up"` / `"offline"` / `"destroyed"`, wire-spelled by
// `swarm_queue_client::wanted::AgentState::as_str` — kept as a bare
// `string | null` rather than a union, same reason
// `config_pr`'s shape isn't re-derived here: this page renders whatever
// the wire sends, it doesn't validate the enum client-side.
type Wanted = string | null;
// Mirrors `agent_status::AgentStatusRow` field-for-field — this *is* the
// table row now, not a shape assembled from it, so there's no separate
// join-result type to keep in sync with the wire contract by hand.
interface AgentRow {
name: string;
hive: string | null;
freshness: Freshness;
last_seen_unix: number | null;
// `age_seconds` deliberately unused here, same reason as HivesPage:
// `RelativeTime` recomputes age client-side from `last_seen_unix`
// rather than rendering a once-computed-at-fetch value.
snapshot: AgentStatusSnapshot | null;
config_pr: ConfigPrStatus | null;
wanted: Wanted;
}
// Same tone pairing as HivesPage — one freshness enum shared by both
// endpoints, so the same tone rule applies to both pages — but `unknown`'s
// label diverges deliberately: an agent outside the swarm-identity roster
// has a concrete next step (register it), while an unrecognized *hive* on
// HivesPage doesn't carry the same actionable meaning.
const FRESHNESS: Record<Freshness, { tone: BadgeTone; label: string }> = {
fresh: { tone: "positive", label: "fresh" },
stale: { tone: "warning", label: "stale" },
never_reported: { tone: "neutral", label: "never reported" },
// `unknown` means the agent reported into the KV bucket but isn't in
// the swarm-identity roster — a real, distinct case ("hive-reported,
// not yet in swarm level"), not just a fallback default, so it gets a
// label that says what to do about it rather than reusing the enum
// name as the label.
unknown: { tone: "negative", label: "not in swarm identity" },
};
// Same 30s default + same reasoning as HivesPage: no inputs on this page
// for a refresh to clobber, so the out-of-the-box behaviour should just
// solve staleness rather than require an opt-in every visit.
const DEFAULT_INTERVAL_MS: RefreshIntervalMs = 30_000;
export function AgentsPage() {
const [rows, setRows] = useState<AgentRow[] | null>(null);
const [error, setError] = useState<ProblemDetails | null>(null);
const [intervalMs, setIntervalMs] =
useState<RefreshIntervalMs>(DEFAULT_INTERVAL_MS);
const [createOpen, setCreateOpen] = useState(false);
// Per-agent, not one page-wide flag: one row's declare-in-flight
// shouldn't disable every other row's button.
const [pendingAgents, setPendingAgents] = useState<ReadonlySet<string>>(
new Set(),
);
const [actionErrors, setActionErrors] = useState<
ReadonlyMap<string, ProblemDetails>
>(new Map());
// The row pending destroy confirmation, `null` when the dialog is
// closed — not a boolean, so the dialog can name the agent without a
// second piece of state to keep in sync with it. `stopTarget` mirrors
// it for the "declare offline" direction of the same toggle — two
// separate pieces of state (not one "pending confirm" union) since
// both `ConfirmDialog`s can't be open at once anyway and keeping them
// apart means each one's JSX below reads standalone.
const [destroyTarget, setDestroyTarget] = useState<AgentRow | null>(null);
const [stopTarget, setStopTarget] = useState<AgentRow | null>(null);
async function refresh() {
const res = await fetch("/api/agents/status");
if (!res.ok) {
setError(await readApiError(res));
return;
}
setRows((await res.json()) as AgentRow[]);
// A refresh that succeeds clears a previous failure — otherwise a
// transient error would sit on screen forever after the data itself
// has recovered.
setError(null);
}
useRefreshInterval(intervalMs, () => {
refresh().catch((e: unknown) => setError({ detail: String(e) }));
});
// Shared by `confirmStop` and `destroyAgent` — both are "PUT a new
// `wanted` declaration, track per-agent pending/error state, patch the
// response back into `rows`" with nothing else distinguishing them.
// Which `ConfirmDialog` fires it and the target state stay in each
// caller, since those are the parts that actually differ.
async function declareState(row: AgentRow, target: string) {
if (!row.hive) return;
setPendingAgents((prev) => new Set(prev).add(row.name));
setActionErrors((prev) => {
const next = new Map(prev);
next.delete(row.name);
return next;
});
try {
const res = await fetch(
`/api/hives/${encodeURIComponent(row.hive)}/agents/${encodeURIComponent(row.name)}/state`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ state: target }),
},
);
if (!res.ok) {
const problem = await readApiError(res);
setActionErrors((prev) => new Map(prev).set(row.name, problem));
return;
}
// The PUT response is the hive's whole declaration set (every
// agent's `wanted` state) — same shape `GET /api/hives/{hive}/wanted`
// returns — so patch just that field into the rows already on
// screen rather than firing a second, full `/api/agents/status`
// round-trip merely to learn one hive's `wanted` column changed.
// Everything else on the grid (freshness, snapshot, config PR)
// still catches up on the next interval-driven `refresh()`.
const declared = (await res.json()) as { agent: string; state: string }[];
setRows((prev) => {
if (!prev) return prev;
const byAgent = new Map(declared.map((d) => [d.agent, d.state]));
return prev.map((r) =>
r.hive === row.hive && byAgent.has(r.name)
? { ...r, wanted: byAgent.get(r.name) ?? r.wanted }
: r,
);
});
} catch (e: unknown) {
setActionErrors((prev) =>
new Map(prev).set(row.name, { detail: String(e) }),
);
} finally {
setPendingAgents((prev) => {
const next = new Set(prev);
next.delete(row.name);
return next;
});
}
}
// Declares the opposite of `row`'s current state. A row with no
// declaration yet (`wanted === null`) has nothing to flip, so the
// target is read off the agent's own last-reported `running` instead
// — the button's first click always means "make the declaration match
// reality, then flip it", which is the only reading that makes sense
// without a declaration to toggle. The "up" direction needs no
// confirmation and declares straight away; "offline" opens the
// `stopTarget` `ConfirmDialog` instead of declaring directly — see
// `confirmStop`.
async function toggleWanted(row: AgentRow) {
if (!row.hive) return;
const impliedCurrent =
row.wanted ?? (row.snapshot?.running ? "up" : "offline");
const target = impliedCurrent === "up" ? "offline" : "up";
if (target === "offline") {
setStopTarget(row);
return;
}
await declareState(row, target);
}
// Fires from the `stopTarget` confirm `Dialog`. Used to be a native
// `window.confirm` (stop is reversible, a later start un-does it, so a
// lighter-weight prompt than destroy's felt proportionate) — mara,
// reviewing the destroy confirm: use the shared component everywhere
// we already confirm before acting, not just for destroy. Once
// `ConfirmDialog` existed as a one-line-per-caller component, the
// "native is lighter" argument no longer bought consistency anything.
async function confirmStop(row: AgentRow) {
setStopTarget(null);
await declareState(row, "offline");
}
// Fires from the `destroyTarget` confirm `Dialog`, never directly off
// a row click — see `destroyTarget`/the "destroy" badge in the
// `wanted` column. Unlike `toggleWanted`, there's no "current state"
// to read: destroy is a one-way declaration, not a flip.
async function destroyAgent(row: AgentRow) {
setDestroyTarget(null);
await declareState(row, "destroyed");
}
const columns: TableColumn<AgentRow>[] = [
{
key: "name",
header: "name",
render: (a) => a.name,
sortBy: (a) => a.name,
filterValue: (a) => a.name,
},
{
key: "hive",
header: "hive",
render: (a) => a.hive ?? "—",
sortBy: (a) => a.hive ?? "",
filterValue: (a) => a.hive ?? "",
},
{
key: "status",
header: "status",
// Technical freshness only — the agent's own free-text status
// string used to be concatenated into this same badge, which
// stuffed a full sentence into a pill meant for a short discrete
// label and blew the row out (mara: "looks messy"). That string
// now lives in its own "message" column below.
sortBy: (a) => FRESHNESS[a.freshness].label,
filterValue: (a) => FRESHNESS[a.freshness].label,
render: (a) => {
const { tone, label } = FRESHNESS[a.freshness];
return (
<Badge
tone={tone}
title={
a.freshness === "unknown"
? "reported by its hive but not registered in swarm-level identity — needs migration"
: undefined
}
value={
<>
{label}
{a.last_seen_unix !== null ? (
<>
{" "}
(<RelativeTime epochMs={a.last_seen_unix * 1000} />)
</>
) : null}
</>
}
/>
);
},
},
{
key: "message",
header: "message",
cellClass: "ui-table-prose",
// Plain text, not a Badge — the agent's own free-form status
// sentence, as distinct from the technical freshness state in the
// "status" column. A `running: false` snapshot always carries
// `status_text: null` (the wire contract's own rule), so a stopped
// agent just shows an em dash here rather than a stale message.
render: (a) => a.snapshot?.status_text ?? "—",
filterValue: (a) => a.snapshot?.status_text ?? "",
},
{
key: "wanted",
header: "wanted",
// The start/stop control: clicking the current-declared-state
// badge toggles it — `Badge`'s own "chip plus, optionally, the
// control" shape (see its header comment, which names pause/resume
// as the exact motivating case), not a separate status chip next
// to a separate button. Destroy is a second, `quiet`-variant badge
// next to it rather than a third toggle state: folding it into the
// same click target would make one wrong click irreversible, and
// `wanted === "destroyed"` already reads fine as this badge's own
// display value without a dedicated affordance to view it.
sortBy: (a) => a.wanted ?? "",
filterValue: (a) => a.wanted ?? "no declaration",
render: (a) => {
const pending = pendingAgents.has(a.name);
const impliedCurrent =
a.wanted ?? (a.snapshot?.running ? "up" : "offline");
const actionLabel = impliedCurrent === "up" ? "stop" : "start";
const tone: BadgeTone = a.wanted === "up" ? "positive" : "neutral";
const err = actionErrors.get(a.name);
// Already destroyed, or nothing to destroy against — same guard
// shape as the wanted toggle's own `!a.hive` check.
const destroyable = a.hive && a.wanted !== "destroyed";
return (
<>
<Badge
tone={tone}
value={pending ? "…" : (a.wanted ?? "no declaration")}
onClick={a.hive ? () => void toggleWanted(a) : undefined}
disabled={pending || !a.hive}
title={
a.hive
? `click to ${actionLabel} ${a.name}`
: "no hive on record for this agent — nothing to declare against"
}
/>
{destroyable ? (
<Badge
variant="quiet"
tone="negative"
value="destroy"
onClick={() => setDestroyTarget(a)}
disabled={pending}
title={`destroy ${a.name} — tears the container down, irreversible`}
/>
) : null}
{err ? (
<Badge
tone="negative"
value="failed"
title={err.detail ?? "the declaration failed"}
/>
) : null}
</>
);
},
},
{
key: "config-pr",
header: "config PR",
sortBy: (a) => a.config_pr?.pr_number ?? 0,
filterValue: (a) => (a.config_pr ? `#${a.config_pr.pr_number}` : ""),
render: (a) =>
a.config_pr ? (
<Badge
tone="warning"
value={
a.config_pr.html_url ? (
<a href={a.config_pr.html_url} target="_blank" rel="noreferrer">
#{a.config_pr.pr_number}
</a>
) : (
`#${a.config_pr.pr_number}`
)
}
/>
) : (
"—"
),
},
];
return (
<Panel
title="agents"
icon="👥"
actions={
<>
<Button variant="primary" onClick={() => setCreateOpen(true)}>
+ agent
</Button>
<RefreshIntervalPicker
id="agents-refresh"
value={intervalMs}
onChange={setIntervalMs}
/>
</>
}
>
{error ? (
<ApiErrorPanel
context="failed to load the agent roster"
problem={error}
/>
) : null}
{!error && rows === null ? <p>loading…</p> : null}
{rows ? (
<Table
columns={columns}
rows={rows}
rowKey={(a) => a.name}
emptyMessage="no agents yet — the swarm-wide identity store has no agents registered on any hive"
/>
) : null}
<Dialog
open={createOpen}
onClose={() => setCreateOpen(false)}
label="create agent"
>
<CreateAgentForm />
</Dialog>
<ConfirmDialog
open={stopTarget !== null}
label="stop agent"
onCancel={() => setStopTarget(null)}
onConfirm={() => stopTarget && void confirmStop(stopTarget)}
confirmLabel="stop"
>
{stopTarget ? (
<p>
Declare <strong>{stopTarget.name}</strong> offline? The hive brings
its container down on its next reconcile sweep.
</p>
) : null}
</ConfirmDialog>
<ConfirmDialog
open={destroyTarget !== null}
label="destroy agent"
onCancel={() => setDestroyTarget(null)}
onConfirm={() => destroyTarget && void destroyAgent(destroyTarget)}
confirmLabel="destroy"
>
{destroyTarget ? (
<p>
Destroy <strong>{destroyTarget.name}</strong>? The hive tears its
container down on its next reconcile sweep. This is not reversible
from here — bringing it back means redeploying via "+ agent", which
reuses the agent's existing identity, config repo, and forge
collaborator access rather than starting over.
</p>
) : null}
</ConfirmDialog>
</Panel>
);
}