Button gains a danger variant and an autofocus prop; ConfirmDialog gains danger (red confirm, focus on cancel). Destroy, delete linked account, delete claude login, remove schedule and delete flow use it. New useConfirm hook asks from inside a handler (await confirm({...})) without a dialog's state at the call site. It now guards: removing a swarm-wide egress domain, removing a domain for every agent from an agent's popover, removing a stored API-key environment, firing a schedule now, moving an agent's internet to a looser mode, the /clear message, and reload over unsaved instructions (replacing window.confirm). The review try-out's button is now called push a branch for a PR, since it pushes a branch and does not open one, and asks first. loosensInternet is a tested helper.
402 lines
14 KiB
TypeScript
402 lines
14 KiB
TypeScript
// <AgentPermissions>, <AgentInternet> and <AgentRepos> — one agent's grant in an
|
|
// opened agent card: the permissions it holds, how far its traffic may leave
|
|
// the host, and how many repositories its forge account may create. Each is a badge that opens a control under it, which saves as soon as it
|
|
// changes.
|
|
//
|
|
// Both read `GET /api/agents/{name}/permissions`, which answers the stored
|
|
// grant as `{ permissions?, unrestricted_internet?, internet_log?, max_repos?, ssh? }` (`{}` 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, and the repositories
|
|
// control the limit the same way. The route's refusal
|
|
// shows as it arrives, in the control.
|
|
//
|
|
// 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 { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
|
|
import { BadgeSkeleton } from "../../ui/skeleton/BadgeSkeleton.js";
|
|
import { Hint } from "../../ui/hint/Hint.js";
|
|
import { TextField } from "../../ui/text-field/TextField.js";
|
|
import { MultiselectFilterOptions } from "../../ui/multiselect-filter/MultiselectFilter.js";
|
|
import {
|
|
requestPermissions,
|
|
togglePermission,
|
|
} from "../../pages/CreateAgentPermissions.js";
|
|
import {
|
|
editorSelection,
|
|
grantSummary,
|
|
internetBody,
|
|
internetMode,
|
|
internetSummary,
|
|
MAX_REPOS,
|
|
maxReposBody,
|
|
parseMaxRepos,
|
|
reposSummary,
|
|
loosensInternet,
|
|
type InternetMode,
|
|
} from "./permissions.js";
|
|
import "./AgentLimits.css";
|
|
|
|
// The stored grant as the route carries it; the field is absent when unset.
|
|
interface Grant {
|
|
permissions?: string[];
|
|
unrestricted_internet?: boolean;
|
|
internet_log?: boolean;
|
|
max_repos?: number;
|
|
ssh?: boolean;
|
|
}
|
|
|
|
// Mirrors swarm-controller's `Catalogue` (`GET /api/permissions`).
|
|
interface Catalogue {
|
|
all: string[];
|
|
default: string[];
|
|
}
|
|
|
|
// The modes of the internet control: mode, label, what it means.
|
|
const INTERNET_MODES: [InternetMode, string, string][] = [
|
|
["restricted", "restricted", "allow only the listed names"],
|
|
["log", "log", "allow what restricted would deny, and log it as would_deny"],
|
|
["unrestricted", "unrestricted", "let its traffic leave the host unfiltered"],
|
|
];
|
|
|
|
function permissionsUrl(agent: string): string {
|
|
return `/api/agents/${encodeURIComponent(agent)}/permissions`;
|
|
}
|
|
|
|
// The stored grant of one agent, and what changes it. One instance serves
|
|
// every control of the grant, so a save from one is seen by the others.
|
|
export function useGrant(agent: string) {
|
|
const [grant, setGrant] = useState<Grant | null>(null);
|
|
const [error, setError] = useState<ProblemDetails | null>(null);
|
|
// Bumped by a retry, so the grant is fetched again.
|
|
const [reload, setReload] = useState(0);
|
|
const [busy, setBusy] = useState(false);
|
|
// The refusal of the last save, kept apart from a failed read.
|
|
const [saveError, setSaveError] = useState<ProblemDetails | null>(null);
|
|
|
|
// Reads the grant; false when the read failed.
|
|
async function load(isCancelled: () => boolean): Promise<boolean> {
|
|
try {
|
|
const r = await fetch(permissionsUrl(agent));
|
|
if (!r.ok) {
|
|
if (!isCancelled()) setError(await readApiError(r));
|
|
return false;
|
|
}
|
|
const body = (await r.json()) as Grant;
|
|
if (isCancelled()) return false;
|
|
setGrant(body);
|
|
setError(null);
|
|
return true;
|
|
} catch (e: unknown) {
|
|
if (!isCancelled()) setError({ detail: String(e) });
|
|
return false;
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
void load(() => cancelled);
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [agent, reload]);
|
|
|
|
// Sends one change and reads the grant again before it lets go of `busy`,
|
|
// so the next change builds on what was stored; true when the route took it.
|
|
async function send(init: RequestInit): Promise<boolean> {
|
|
if (busy) return false;
|
|
setBusy(true);
|
|
setSaveError(null);
|
|
try {
|
|
const r = await fetch(permissionsUrl(agent), init);
|
|
if (!r.ok) {
|
|
setSaveError(await readApiError(r));
|
|
return false;
|
|
}
|
|
await load(() => false);
|
|
return true;
|
|
} catch (e: unknown) {
|
|
setSaveError({ detail: String(e) });
|
|
return false;
|
|
} finally {
|
|
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 readFailure = error ? (
|
|
<>
|
|
<ApiErrorPanel context="reading the permissions failed" problem={error} />
|
|
<Button onClick={() => setReload((n) => n + 1)}>retry</Button>
|
|
</>
|
|
) : null;
|
|
const loading =
|
|
grant === null
|
|
? (readFailure ?? <BadgeSkeleton what="the permissions" />)
|
|
: null;
|
|
return { grant, busy, saveError, readFailure, loading, send };
|
|
}
|
|
|
|
export type GrantState = ReturnType<typeof useGrant>;
|
|
|
|
export function AgentPermissions({
|
|
agent,
|
|
g,
|
|
}: {
|
|
agent: string;
|
|
g: GrantState;
|
|
}) {
|
|
const { grant, busy, saveError, loading, send } = g;
|
|
const [catalogue, setCatalogue] = useState<Catalogue | null>(null);
|
|
const [catalogueError, setCatalogueError] = useState<ProblemDetails | null>(
|
|
null,
|
|
);
|
|
// The boxes as ticked while a change is being saved; null shows the stored grant.
|
|
const [selected, setSelected] = useState<string[] | null>(null);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
(async () => {
|
|
const r = await fetch("/api/permissions");
|
|
if (!r.ok) {
|
|
if (!cancelled) setCatalogueError(await readApiError(r));
|
|
return;
|
|
}
|
|
const data = (await r.json()) as Catalogue;
|
|
if (!cancelled) setCatalogue(data);
|
|
})().catch((e: unknown) => {
|
|
if (!cancelled) setCatalogueError({ detail: String(e) });
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, []);
|
|
|
|
if (grant === null) return loading;
|
|
|
|
const stored = grant.permissions;
|
|
const ticked =
|
|
selected ??
|
|
(catalogue
|
|
? editorSelection(stored, catalogue.all, catalogue.default)
|
|
: []);
|
|
|
|
async function toggle(value: string) {
|
|
if (!catalogue || busy) return;
|
|
const next = togglePermission(ticked, value);
|
|
setSelected(next);
|
|
// The default set sends no list, so the agent follows the default.
|
|
const list = requestPermissions(next, catalogue.default);
|
|
await send(
|
|
list === undefined
|
|
? { method: "DELETE" }
|
|
: {
|
|
method: "PUT",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ permissions: list }),
|
|
},
|
|
);
|
|
// The grant was read again by now, or the change refused: show what is stored.
|
|
setSelected(null);
|
|
}
|
|
|
|
return (
|
|
<div class="ui-agent-limits">
|
|
<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: ticked, negate: false }}
|
|
onToggle={(v) => void toggle(v)}
|
|
disabled={busy}
|
|
scrollable={false}
|
|
/>
|
|
</div>
|
|
) : (
|
|
<Hint as="span" role="status">
|
|
{catalogueError ? "could not load the permissions" : "loading…"}
|
|
</Hint>
|
|
)}
|
|
{saveError ? (
|
|
<ApiErrorPanel
|
|
context="the permissions were not saved"
|
|
problem={saveError}
|
|
/>
|
|
) : null}
|
|
<Button
|
|
disabled={busy || grant.permissions === undefined}
|
|
onClick={() => void send({ method: "DELETE" })}
|
|
>
|
|
use the default
|
|
</Button>
|
|
</BadgePopover>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function AgentInternet({ agent, g }: { agent: string; g: GrantState }) {
|
|
const { grant, busy, saveError, loading, send } = g;
|
|
const [confirm, confirmDialog] = useConfirm();
|
|
if (grant === null) return loading;
|
|
|
|
const mode = internetMode(grant.unrestricted_internet, grant.internet_log);
|
|
|
|
// Letting more traffic out is asked first, and says what it lets out; going
|
|
// back to a tighter mode is not.
|
|
async function choose(next: InternetMode) {
|
|
if (grant === null) return;
|
|
if (loosensInternet(mode, next)) {
|
|
const meaning = INTERNET_MODES.find(([m]) => m === next)?.[2] ?? "";
|
|
const yes = await confirm({
|
|
label: `set ${agent} internet to ${next}`,
|
|
confirmLabel: `set ${next}`,
|
|
danger: next === "unrestricted",
|
|
body: (
|
|
<p>
|
|
Set <strong>{agent}</strong>'s internet to <strong>{next}</strong>?
|
|
This will {meaning}.
|
|
</p>
|
|
),
|
|
});
|
|
if (!yes) return;
|
|
}
|
|
void send({
|
|
method: "PUT",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(internetBody(grant.permissions, next)),
|
|
});
|
|
}
|
|
|
|
return (
|
|
<div class="ui-agent-limits">
|
|
<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"}
|
|
pressed={m === mode}
|
|
value={label}
|
|
title={`${meaning} for ${agent}`}
|
|
disabled={busy}
|
|
onClick={m === mode ? undefined : () => void choose(m)}
|
|
/>{" "}
|
|
<Hint as="span">{meaning}</Hint>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
{saveError ? (
|
|
<ApiErrorPanel
|
|
context="the internet mode was not saved"
|
|
problem={saveError}
|
|
/>
|
|
) : null}
|
|
</BadgePopover>
|
|
{confirmDialog}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function AgentRepos({ agent, g }: { agent: string; g: GrantState }) {
|
|
const { grant, busy, saveError, loading, send } = g;
|
|
// The box as typed; null shows the stored limit.
|
|
const [typed, setTyped] = useState<string | null>(null);
|
|
if (grant === null) return loading;
|
|
|
|
const stored = grant.max_repos ?? 0;
|
|
const text = typed ?? String(stored);
|
|
const parsed = parseMaxRepos(text);
|
|
|
|
async function save(e: Event) {
|
|
e.preventDefault();
|
|
if (parsed === null) return;
|
|
const ok = await send({
|
|
method: "PUT",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(maxReposBody(grant?.permissions, parsed)),
|
|
});
|
|
// The grant was read again, or the change refused: show what is stored.
|
|
if (ok) setTyped(null);
|
|
}
|
|
|
|
return (
|
|
<div class="ui-agent-limits">
|
|
<BadgePopover
|
|
label="repositories"
|
|
value={reposSummary(grant.max_repos)}
|
|
tone={stored === 0 ? "neutral" : "warning"}
|
|
title={`how many repositories ${agent}'s forge account may create`}
|
|
popoverLabel={`${agent} repository limit`}
|
|
>
|
|
<p class="ui-badge-popover-help">
|
|
How many repositories {agent}'s forge account may create, 0 to{" "}
|
|
{MAX_REPOS}. 0 means none. The swarm applies a change to the account
|
|
within seconds.
|
|
</p>
|
|
<p class="ui-badge-popover-help" role="note">
|
|
<strong>Warning:</strong> an agent that may create repositories can
|
|
add a CI workflow to them, and CI workflows run unsandboxed on the CI
|
|
runner. That is arbitrary code on the runner host. Only allow this for
|
|
agents you would trust with that.
|
|
</p>
|
|
<form onSubmit={(e) => void save(e)}>
|
|
<TextField
|
|
id={`max-repos-${agent}`}
|
|
label="repositories"
|
|
type="number"
|
|
value={text}
|
|
onInput={setTyped}
|
|
/>
|
|
<Button
|
|
variant="primary"
|
|
type="submit"
|
|
disabled={busy || parsed === null || parsed === stored}
|
|
>
|
|
{busy ? "saving…" : "save"}
|
|
</Button>
|
|
</form>
|
|
{saveError ? (
|
|
<ApiErrorPanel
|
|
context="the repository limit was not saved"
|
|
problem={saveError}
|
|
/>
|
|
) : null}
|
|
</BadgePopover>
|
|
</div>
|
|
);
|
|
}
|