Watch
0
0
Fork
You've already forked hyperhive
0

swarm-ui: restructure the agent card into status, terminal, subagents and settings, with badge controls for internet, permissions and allowed domains

This commit is contained in:
iris 2026-11-03 23:47:44 +01:00 • committed by mara
commit 5e23734667

View file

@ -1,24 +1,27 @@
// <AgentPermissions> — one agent's permissions in an opened agent card: what the
// swarm grants it, and an editor for that.
// <AgentPermissions> and <AgentInternet> — one agent's grant in an opened agent
// card: the permissions it holds, and how far its traffic may leave the host.
// Each is a badge that opens a control under it, which saves as soon as it
// changes.
//
// Reads `GET /api/agents/{name}/permissions`, which answers the stored list as
// `{ permissions? }` (`{}` when the swarm sets none, so the agent runs on the
// default set). The editor offers the catalogue from `GET /api/permissions` as
// checkboxes and PUTs the ticked ones, a PUT replacing the stored value whole.
// A selection equal to the default set DELETEs instead, as the create form
// sends nothing for it: the agent then follows the default if that changes.
// The route's refusal shows as it arrives, next to the boxes.
// Both read `GET /api/agents/{name}/permissions`, which answers the stored
// grant as `{ permissions?, unrestricted_internet?, internet_log? }` (`{}` when
// the swarm sets none, so the agent runs on the default set). The permissions
// control offers the catalogue from `GET /api/permissions` as checkboxes and
// PUTs the ticked ones, a PUT replacing the stored value whole. A selection
// equal to the default set DELETEs instead, as the create form sends nothing
// for it: the agent then follows the default if that changes. The internet
// control PUTs the mode with the stored list beside it. The route's refusal
// shows as it arrives, in the control.
//
// Its state belongs to one agent: callers key it by agent name, so switching
// agents remounts it instead of showing the previous agent's grant.
// Their state belongs to one agent: callers key them by agent name, so
// switching agents remounts them instead of showing the previous agent's grant.
import { useEffect, 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 } from "@hive/shared/badge.js";
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
import { Button } from "../../ui/button/Button.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { MultiselectFilterOptions } from "../../ui/multiselect-filter/MultiselectFilter.js";
import { Panel } from "../../ui/panel/Panel.js";
import {
requestPermissions,
togglePermission,
@ -46,28 +49,26 @@ interface Catalogue {
default: string[];
}
// The buttons for the modes an agent is not in: mode, label, tooltip.
// The modes of the internet control: mode, label, what it means.
const INTERNET_MODES: [InternetMode, string, string][] = [
[
"unrestricted",
"allow unrestricted",
"let its traffic leave the host unfiltered",
],
["restricted", "restricted", "allow only the listed names"],
["log", "log", "allow what restricted would deny, and log it as would_deny"],
["restricted", "restrict", "allow only the listed names"],
["unrestricted", "unrestricted", "let its traffic leave the host unfiltered"],
];
function permissionsUrl(agent: string): string {
return `/api/agents/${encodeURIComponent(agent)}/permissions`;
}
export function AgentPermissions({ agent }: { agent: string }) {
// The stored grant of one agent, and what changes it.
function useGrant(agent: string) {
const [grant, setGrant] = useState<Grant | null>(null);
const [error, setError] = useState<ProblemDetails | null>(null);
// Bumped after a save or a clear, so the grant is fetched again.
const [reload, setReload] = useState(0);
const [editing, setEditing] = useState(false);
const [flagBusy, setFlagBusy] = useState(false);
const [busy, setBusy] = useState(false);
// The refusal of the last save, kept apart from a failed read.
const [saveError, setSaveError] = useState<ProblemDetails | null>(null);
useEffect(() => {
let cancelled = false;
@ -89,165 +90,94 @@ export function AgentPermissions({ agent }: { agent: string }) {
};
}, [agent, reload]);
// Sets the internet mode, sending the stored list with it.
async function setInternet(g: Grant, mode: InternetMode) {
if (flagBusy) return;
setFlagBusy(true);
// Sends one change and reads the grant again; true when the route took it.
async function send(init: RequestInit): Promise<boolean> {
setBusy(true);
setSaveError(null);
try {
const r = await fetch(permissionsUrl(agent), {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(internetBody(g.permissions, mode)),
});
const r = await fetch(permissionsUrl(agent), init);
if (!r.ok) {
setError(await readApiError(r));
return;
setSaveError(await readApiError(r));
return false;
}
setReload((n) => n + 1);
return true;
} catch (e: unknown) {
setError({ detail: String(e) });
setSaveError({ detail: String(e) });
return false;
} finally {
setFlagBusy(false);
setBusy(false);
}
}
// A grant already loaded stays under a failed refetch, so a save that
// worked is not hidden by a read that did not.
const errorPanel = error ? (
const readFailure = error ? (
<>
<ApiErrorPanel context="reading the permissions failed" problem={error} />
<Button onClick={() => setReload((n) => n + 1)}>retry</Button>
</>
) : null;
if (grant === null) {
return (
errorPanel ?? (
<span class="ui-agent-limits-muted" role="status">
loading the permissions…
</span>
)
);
}
return (
<div class="ui-agent-limits">
{errorPanel}
<Badge label="permissions" value={grantSummary(grant.permissions)} />
{grant.permissions && grant.permissions.length > 0 ? (
<ul class="ui-agent-limits-list">
{grant.permissions.map((p) => (
<li key={p}>
<Badge value={p} />
</li>
))}
</ul>
) : null}
<Badge
label="internet"
value={internetSummary(grant.unrestricted_internet, grant.internet_log)}
/>
{INTERNET_MODES.filter(
([mode]) =>
mode !==
internetMode(grant.unrestricted_internet, grant.internet_log),
).map(([mode, label, title]) => (
<Badge
key={mode}
variant="quiet"
value={label}
title={`${title} for ${agent}`}
onClick={() => void setInternet(grant, mode)}
/>
))}
<Badge
variant="quiet"
value="edit"
title={`set the permissions the swarm grants ${agent}`}
onClick={() => setEditing(true)}
/>
<Dialog
open={editing}
onClose={() => setEditing(false)}
label="edit permissions"
plain
>
{/* Remounted per open, so a cancelled edit leaves nothing behind. */}
{editing ? (
<PermissionsForm
agent={agent}
grant={grant}
onClose={() => setEditing(false)}
onSaved={() => {
setEditing(false);
setReload((n) => n + 1);
}}
/>
) : null}
</Dialog>
</div>
);
const loading =
grant === null
? (readFailure ?? (
<span class="ui-agent-limits-muted" role="status">
loading the permissions…
</span>
))
: null;
return { grant, busy, saveError, readFailure, loading, send };
}
function PermissionsForm({
agent,
grant,
onClose,
onSaved,
}: {
agent: string;
grant: Grant;
onClose: () => void;
onSaved: () => void;
}) {
export function AgentPermissions({ agent }: { agent: string }) {
const { grant, busy, saveError, readFailure, loading, send } =
useGrant(agent);
const [catalogue, setCatalogue] = useState<Catalogue | null>(null);
const [selected, setSelected] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState<ProblemDetails | null>(null);
const [catalogueError, setCatalogueError] = useState<ProblemDetails | null>(
null,
);
// The boxes as ticked; they follow the stored grant once it is read again.
const [selected, setSelected] = useState<string[] | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
const r = await fetch("/api/permissions");
if (!r.ok) {
if (!cancelled) setProblem(await readApiError(r));
if (!cancelled) setCatalogueError(await readApiError(r));
return;
}
const data = (await r.json()) as Catalogue;
if (cancelled) return;
setCatalogue(data);
setSelected(editorSelection(grant.permissions, data.all, data.default));
if (!cancelled) setCatalogue(data);
})().catch((e: unknown) => {
if (!cancelled) setProblem({ detail: String(e) });
if (!cancelled) setCatalogueError({ detail: String(e) });
});
return () => {
cancelled = true;
};
}, [grant]);
}, []);
async function send(init: RequestInit) {
setBusy(true);
setProblem(null);
try {
const r = await fetch(permissionsUrl(agent), init);
if (!r.ok) {
// The boxes stay as ticked, so the operator can fix it and save again.
setProblem(await readApiError(r));
return;
}
onSaved();
} catch (e: unknown) {
setProblem({ detail: String(e) });
} finally {
setBusy(false);
}
}
// The stored grant changing (a save went through) resets the boxes to it.
const stored = grant?.permissions;
useEffect(() => {
setSelected(null);
}, [stored]);
function save(e: Event) {
e.preventDefault();
if (grant === null) return loading;
const ticked =
selected ??
(catalogue
? editorSelection(stored, catalogue.all, catalogue.default)
: []);
async function toggle(value: string) {
if (!catalogue) return;
const next = togglePermission(ticked, value);
setSelected(next);
// The default set sends no list, so the agent follows the default.
const list = requestPermissions(selected, catalogue.default);
void send(
const list = requestPermissions(next, catalogue.default);
const ok = await send(
list === undefined
? { method: "DELETE" }
: {
@ -256,53 +186,110 @@ function PermissionsForm({
body: JSON.stringify({ permissions: list }),
},
);
// A refused change puts the boxes back as stored.
if (!ok) setSelected(null);
}
return (
<Panel title={`permissions — ${agent}`} icon="🔑" onClose={onClose}>
<p>
What the swarm lets {agent} do. A tick grants that permission; leaving
the default set ticked keeps {agent} on the default if it changes. The
hive reads a change within about 30 seconds, and the agent takes it at
its next turn. Changing <code>manage_root_agent</code> restarts it after
its current turn.
</p>
<form class="ui-agent-limits-form" onSubmit={save}>
<div role="group" aria-label="permissions">
{catalogue ? (
<div class="ui-agent-limits">
{readFailure}
<BadgePopover
label="permissions"
value={grantSummary(grant.permissions)}
title={`see and change what the swarm lets ${agent} do`}
popoverLabel={`${agent} permissions`}
>
<p class="ui-badge-popover-help">
What the swarm lets {agent} do. A tick grants it; ticking the default
set keeps {agent} on the default if that changes. The hive reads a
change within about 30 seconds and the agent takes it at its next
turn. Changing <code>manage_root_agent</code> restarts it after its
current turn.
</p>
{catalogue ? (
<div role="group" aria-label="permissions">
<MultiselectFilterOptions
options={catalogue.all}
filter={{ values: selected, negate: false }}
onToggle={(v) => setSelected((s) => togglePermission(s, v))}
filter={{ values: ticked, negate: false }}
onToggle={(v) => void toggle(v)}
/>
) : (
<span class="ui-agent-limits-muted" role="status">
{problem ? "could not load the permissions" : "loading…"}
</span>
)}
</div>
{problem ? (
</div>
) : (
<span class="ui-agent-limits-muted" role="status">
{catalogueError ? "could not load the permissions" : "loading…"}
</span>
)}
{saveError ? (
<ApiErrorPanel
context="the permissions were not saved"
problem={problem}
problem={saveError}
/>
) : null}
<div class="ui-agent-limits-actions">
<Button
variant="primary"
type="submit"
disabled={busy || catalogue === null}
>
{busy ? "saving…" : "save"}
</Button>
<Button
disabled={busy || grant.permissions === undefined}
onClick={() => void send({ method: "DELETE" })}
>
use the default
</Button>
</div>
</form>
</Panel>
<Button
disabled={busy || grant.permissions === undefined}
onClick={() => void send({ method: "DELETE" })}
>
use the default
</Button>
</BadgePopover>
</div>
);
}
export function AgentInternet({ agent }: { agent: string }) {
const { grant, busy, saveError, readFailure, loading, send } =
useGrant(agent);
if (grant === null) return loading;
const mode = internetMode(grant.unrestricted_internet, grant.internet_log);
return (
<div class="ui-agent-limits">
{readFailure}
<BadgePopover
label="internet"
value={internetSummary(grant.unrestricted_internet, grant.internet_log)}
tone={mode === "restricted" ? "neutral" : "warning"}
title={`how far ${agent}'s traffic may leave the host`}
popoverLabel={`${agent} internet access`}
>
<p class="ui-badge-popover-help">
How far {agent}'s traffic may leave the host. Restricted allows only
the names listed under allowed domains; the hive reads a change within
about 30 seconds.
</p>
<ul class="ui-badge-popover-list">
{INTERNET_MODES.map(([m, label, meaning]) => (
<li key={m}>
<Badge
variant={m === mode ? "default" : "quiet"}
tone={m === mode ? "accent" : "neutral"}
value={label}
title={`${meaning} for ${agent}`}
disabled={busy}
onClick={
m === mode
? undefined
: () =>
void send({
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(
internetBody(grant.permissions, m),
),
})
}
/>{" "}
<span class="ui-agent-limits-muted">{meaning}</span>
</li>
))}
</ul>
{saveError ? (
<ApiErrorPanel
context="the internet mode was not saved"
problem={saveError}
/>
) : null}
</BadgePopover>
</div>
);
}