Watch
0
0
Fork
You've already forked hyperhive
0

swarm ui: an agent's API key is set from its claude login row, and the advanced backend settings show the configuration and the secrets apart

The claude login row of an opened agent gains an API key line: a badge saying whether a key is stored, set or replace and remove, and advanced. Setting a key sends PUT on the backend-secrets route as ANTHROPIC_API_KEY=<key>; the key is never read back. The old API-key environment dialog becomes the advanced backend settings, with two sections: the configuration, which starts with the stored text and saves or removes it, and the secrets, whose box starts empty and replaces the stored secrets only when filled and saved. The link menu's entry is renamed to match, account-api.ts gets the route helpers and a key check with tests, and the swarm UI doc describes the row.
This commit is contained in:
iris 2026-11-20 20:23:08 +01:00 • committed by mara
commit da25f0a1c3
9 changed files with 545 additions and 65 deletions

View file

@ -0,0 +1,162 @@
// <AgentApiKey> — how one agent is billed, in the claude login row: whether an
// API key is stored (`GET …/backend-secrets`, which never returns the key), a
// button that sets or replaces it, one that removes it, and the advanced
// backend settings. With a key stored the agent tries the key instead of
// waiting for a claude login; a change reaches it at its next restart.
//
// Its state belongs to one agent: callers key it by agent name.
import { useCallback, 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 { ConfirmDialog } from "../../ui/confirm-dialog/ConfirmDialog.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { showToast } from "../../ui/toast/toasts.js";
import { LinkApiKeyForm } from "../../pages/LinkApiKeyForm.js";
import { LinkBackendEnvForm } from "../../pages/LinkBackendEnvForm.js";
import { backendSecretsUrl } from "./account-api.js";
export function AgentApiKey({ hive, agent }: { hive: string; agent: string }) {
const [stored, setStored] = useState<boolean | null>(null);
const [error, setError] = useState<ProblemDetails | null>(null);
const [setting, setSetting] = useState(false);
const [advanced, setAdvanced] = useState(false);
const [confirming, setConfirming] = useState(false);
const [removing, setRemoving] = useState(false);
const [removeError, setRemoveError] = useState<ProblemDetails | null>(null);
const load = useCallback(async () => {
try {
const r = await fetch(backendSecretsUrl(hive, agent));
if (!r.ok) {
setError(await readApiError(r));
return;
}
setStored(((await r.json()) as { stored: boolean }).stored);
setError(null);
} catch (err) {
setError({ detail: String(err) });
}
}, [hive, agent]);
useEffect(() => {
void load();
}, [load]);
async function confirmRemove() {
setRemoving(true);
setRemoveError(null);
try {
const r = await fetch(backendSecretsUrl(hive, agent), {
method: "DELETE",
});
// Nothing stored is the end state the removal wanted.
if (!r.ok && r.status !== 404) {
setRemoveError(await readApiError(r));
return;
}
setConfirming(false);
showToast(`removed the API key for ${agent}`);
await load();
} catch (err) {
setRemoveError({ detail: String(err) });
} finally {
setRemoving(false);
}
}
return (
<div class="agent-api-key">
{error ? (
<ApiErrorPanel context="reading the API key failed" problem={error} />
) : null}
{stored === null ? null : (
<>
<Badge
label="API key"
value={stored ? "stored" : "none"}
tone={stored ? "positive" : "neutral"}
/>{" "}
</>
)}
<Badge
variant="quiet"
value={stored ? "replace API key" : "set API key"}
title={`bill ${agent} through the API with a key instead of a claude login`}
onClick={() => setSetting(true)}
/>{" "}
{stored ? (
<>
<Badge
variant="quiet"
value="remove API key"
title={`remove the stored API key for ${agent}`}
onClick={() => {
setRemoveError(null);
setConfirming(true);
}}
/>{" "}
</>
) : null}
<Badge
variant="quiet"
value="advanced"
title={`edit ${agent}'s backend configuration and secrets as env files`}
onClick={() => setAdvanced(true)}
/>
<Dialog
open={setting}
onClose={() => setSetting(false)}
label="set the API key"
plain
>
{setting ? (
<LinkApiKeyForm
hive={hive}
agent={agent}
onSaved={() => void load()}
onClose={() => setSetting(false)}
/>
) : null}
</Dialog>
<Dialog
open={advanced}
onClose={() => {
setAdvanced(false);
void load();
}}
label="backend settings (advanced)"
plain
>
{advanced ? (
<LinkBackendEnvForm
hive={hive}
agent={agent}
onClose={() => {
setAdvanced(false);
void load();
}}
/>
) : null}
</Dialog>
<ConfirmDialog
open={confirming}
label={`remove the API key for ${agent}`}
confirmLabel={removing ? "removing…" : "remove API key"}
danger
confirmDisabled={removing}
onCancel={() => setConfirming(false)}
onConfirm={() => void confirmRemove()}
>
<p>
Remove the stored API key for <strong>{agent}</strong>? The key cannot
be read back, so it cannot be restored. The agent stops loading it at
its next restart.
</p>
{removeError ? (
<ApiErrorPanel context="remove failed" problem={removeError} />
) : null}
</ConfirmDialog>
</div>
);
}

View file

@ -17,6 +17,7 @@ import { ExternalLink } from "../../ui/external-link/ExternalLink.js";
import { Hint } from "../../ui/hint/Hint.js";
import { RelativeTime } from "../../ui/relative-time/RelativeTime.js";
import type { AgentActions } from "../roster/AgentActions.js";
import { AgentApiKey } from "./AgentApiKey.js";
import { AgentClaudeLogin } from "./AgentClaudeLogin.js";
import { AgentInference } from "./AgentInference.js";
import { StatusMessage } from "./StatusMessage.js";
@ -187,7 +188,7 @@ function OverviewRows({
);
}
function SettingsRows({ agent }: { agent: string }) {
function SettingsRows({ agent, hive }: { agent: string; hive: string | null }) {
return (
<>
<dt>inference</dt>
@ -206,6 +207,9 @@ function SettingsRows({ agent }: { agent: string }) {
<dt>claude login</dt>
<dd>
<AgentClaudeLogin key={agent} agent={agent} />
{hive ? (
<AgentApiKey key={`${hive}/${agent}`} hive={hive} agent={agent} />
) : null}
</dd>
</>
);
@ -312,7 +316,7 @@ function SectionBody({
return (
<>
<dl class="ui-agent-detail-fields">
<SettingsRows agent={row.name} />
<SettingsRows agent={row.name} hive={row.hive} />
<AccountsRows row={row} actions={actions} />
</dl>
<LinkAccountAction row={row} actions={actions} />

View file

@ -15,7 +15,7 @@ const OPTIONS: DropdownOption[] = [
{ value: "forge", label: "forge account" },
{ value: "gitlab", label: "gitlab account" },
{ value: "github", label: "github account" },
{ value: "backend", label: "API-key environment" },
{ value: "backend", label: "backend settings (advanced)" },
];
export function LinkAccountMenu({
@ -42,7 +42,7 @@ export function LinkAccountMenu({
disabled={!hasHive}
title={
hasHive
? `link a matrix, forge, gitlab or github account, or set the API-key environment, for ${agent}`
? `link a matrix, forge, gitlab or github account, or edit the advanced backend settings, for ${agent}`
: "no hive on record for this agent — nothing to link against"
}
/>

View file

@ -70,3 +70,28 @@ export function checkLink(
if (token === "") return "token is required";
return null;
}
/** GET, PUT and DELETE target for the agent's backend configuration. */
export function backendEnvUrl(hive: string, agent: string): string {
return `${agentBase(hive, agent)}/backend-env`;
}
/** GET (is any stored), PUT and DELETE target for the agent's backend secrets. */
export function backendSecretsUrl(hive: string, agent: string): string {
return `${agentBase(hive, agent)}/backend-secrets`;
}
/** The secrets text that holds `key` as the agent's Anthropic API key. */
export function apiKeySecrets(key: string): string {
return `ANTHROPIC_API_KEY=${key.trim()}`;
}
/** A message for a key the controller would refuse anyway, or null. */
export function checkApiKey(key: string): string | null {
const k = key.trim();
if (k === "") return "key is required";
if (/[\s"'\\]/.test(k)) {
return "a key has no spaces, quotes or backslashes";
}
return null;
}

View file

@ -277,7 +277,7 @@ export function useAgentActions(
<Dialog
open={backendTarget !== null}
onClose={closeBackend}
label="set the API-key environment"
label="backend settings (advanced)"
plain
>
{backendTarget?.hive ? (

View file

@ -0,0 +1,94 @@
// <LinkApiKeyForm> — sets an agent's API key. The key goes to the agent's
// backend secrets in the swarm secret store as `ANTHROPIC_API_KEY=<key>`
// (`PUT …/backend-secrets`); no route hands it back, so the box starts empty
// and a save replaces whatever is stored. The advanced form
// (`LinkBackendEnvForm`) is where the rest of the backend environment lives.
import { useState } from "preact/hooks";
import { Panel } from "../ui/panel/Panel.js";
import { TextField } from "../ui/text-field/TextField.js";
import { Button } from "../ui/button/Button.js";
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { Hint } from "../ui/hint/Hint.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
import {
apiKeySecrets,
backendSecretsUrl,
checkApiKey,
} from "../agent/detail/account-api.js";
export function LinkApiKeyForm({
hive,
agent,
onSaved,
onClose,
}: {
hive: string;
agent: string;
/** Called after a save, so the row can show the key as stored. */
onSaved?: () => void;
onClose?: () => void;
}) {
const [key, setKey] = useState("");
const { state, submitting, run, fail } = useSubmit();
function save(e: Event) {
e.preventDefault();
const problem = checkApiKey(key);
if (problem !== null) {
fail({ detail: problem });
return;
}
void run(
() =>
fetch(backendSecretsUrl(hive, agent), {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ env: apiKeySecrets(key) }),
}),
{
// The store holds the key; nothing here needs it.
onDone: () => {
setKey("");
onSaved?.();
},
},
);
}
return (
<Panel title={`set the API key — ${agent}`} icon="🔑" onClose={onClose}>
<p>
Bills <strong>{agent}</strong> through the API instead of a Claude
login.
</p>
<FormStack onSubmit={save}>
<TextField
id="api-key"
label="API key"
type="password"
value={key}
required
placeholder="sk-ant-…"
onInput={setKey}
/>
<Hint>
Stored in the swarm secret store and never shown again; a save
replaces the stored key. The agent loads it at its next restart.
</Hint>
<Button variant="primary" type="submit" disabled={submitting}>
{submitting ? "saving…" : "save"}
</Button>
</FormStack>
<FormResult
state={state}
done={() => (
<>
stored the API key for <strong>{agent}</strong>
</>
)}
failed="failed to store the API key"
/>
</Panel>
);
}

View file

@ -0,0 +1,3 @@
.backend-env-heading {
margin: 1.25em 0 0;
}

View file

@ -1,24 +1,32 @@
// <LinkBackendEnvForm> — writes an agent's backend environment (the text of
// a systemd `EnvironmentFile`) into the swarm secret store, or removes it.
// PUTs and DELETEs `/api/hives/{hive}/agents/{agent}/backend-env` — 204 on
// success, 400/404/500 as `problem+json`, shown via `ApiErrorPanel` like
// `LinkGithubAccountForm`.
// <LinkBackendEnvForm> — an agent's advanced backend settings: the two
// objects the agent loads, configuration first and secrets after it, so a
// secret wins over a variable of the same name. Both are the text of a
// systemd `EnvironmentFile`.
//
// A blind set: no route hands the text back, so the box never starts with the
// stored value. A save replaces whatever is stored. Whether one is stored
// shows on the agent panel (`LinkedAccounts`).
import { useState } from "preact/hooks";
// The configuration (`…/backend-env`) reads back as stored, so its box starts
// with the stored text. The secrets (`…/backend-secrets`) are write-only: their
// box starts empty, and the stored secrets change only when it is filled and
// saved (or removed). Whether any are stored shows beside the box.
import { useEffect, useState } from "preact/hooks";
import { Panel } from "../ui/panel/Panel.js";
import { TextAreaField } from "../ui/text-area-field/TextAreaField.js";
import { Button } from "../ui/button/Button.js";
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { Hint } from "../ui/hint/Hint.js";
import { ActionRow } from "../ui/action-row/ActionRow.js";
import { SectionHeading } from "../ui/section-heading/SectionHeading.js";
import { useConfirm } from "../ui/confirm-dialog/useConfirm.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
import {
backendEnvUrl,
backendSecretsUrl,
} from "../agent/detail/account-api.js";
import "./LinkBackendEnvForm.css";
// A swarm-controller without the route answers 404 with no problem body.
const NO_ROUTE =
"this swarm-controller has no backend-env route, or nothing is stored";
"this swarm-controller has no such route, or nothing is stored";
export function LinkBackendEnvForm({
hive,
@ -29,32 +37,57 @@ export function LinkBackendEnvForm({
agent: string;
onClose?: () => void;
}) {
const [env, setEnv] = useState("");
// The success line is what the request did, so it is the done value.
const { state, submitting: busy, run } = useSubmit<string>();
const [config, setConfig] = useState("");
const [loaded, setLoaded] = useState(false);
const [secrets, setSecrets] = useState("");
const [secretsStored, setSecretsStored] = useState<boolean | null>(null);
const configRun = useSubmit<string>();
const secretsRun = useSubmit<string>();
const [confirm, confirmDialog] = useConfirm();
async function removeEnv() {
const yes = await confirm({
label: "remove the API-key environment",
confirmLabel: "remove",
danger: true,
body: (
<p>
Remove the stored API-key environment for <strong>{agent}</strong>?
The stored text cannot be read back, so it cannot be restored; paste
it again to set it.
</p>
),
});
if (yes) send("DELETE", "removed the API-key environment for");
}
// The stored configuration, or nothing when none is stored (a 404).
useEffect(() => {
let live = true;
void (async () => {
try {
const r = await fetch(backendEnvUrl(hive, agent));
if (live && r.ok) setConfig(((await r.json()) as { env: string }).env);
} catch {
// The box stays empty; a save shows the real problem.
}
if (live) setLoaded(true);
})();
return () => {
live = false;
};
}, [hive, agent]);
function send(method: "PUT" | "DELETE", done: string) {
void run(
async function loadSecretsStored() {
try {
const r = await fetch(backendSecretsUrl(hive, agent));
if (r.ok)
setSecretsStored(((await r.json()) as { stored: boolean }).stored);
} catch {
setSecretsStored(null);
}
}
useEffect(() => {
void loadSecretsStored();
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per agent
}, [hive, agent]);
function send(
target: ReturnType<typeof useSubmit<string>>,
url: string,
method: "PUT" | "DELETE",
env: string,
done: string,
after: () => void,
) {
void target.run(
() =>
fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/backend-env`,
url,
method === "PUT"
? {
method,
@ -67,58 +100,180 @@ export function LinkBackendEnvForm({
parse: () => done,
refine: (r, problem) =>
r.status === 404 && !problem.detail ? { detail: NO_ROUTE } : problem,
// The store holds the text; nothing here needs it.
onDone: () => setEnv(""),
onDone: after,
},
);
}
function save(e: Event) {
e.preventDefault();
send("PUT", "stored the API-key environment for");
async function removeConfig() {
const yes = await confirm({
label: "remove the backend configuration",
confirmLabel: "remove",
danger: true,
body: (
<p>
Remove the stored configuration for <strong>{agent}</strong>? An agent
whose <code>backendEnvironmentFile</code> has content stores that file
again.
</p>
),
});
if (yes) {
send(
configRun,
backendEnvUrl(hive, agent),
"DELETE",
"",
"removed the configuration of",
() => setConfig(""),
);
}
}
async function removeSecrets() {
const yes = await confirm({
label: "remove the backend secrets",
confirmLabel: "remove",
danger: true,
body: (
<p>
Remove the stored secrets (the API key) for <strong>{agent}</strong>?
The stored text cannot be read back, so it cannot be restored.
</p>
),
});
if (yes) {
send(
secretsRun,
backendSecretsUrl(hive, agent),
"DELETE",
"",
"removed the secrets of",
() => {
setSecrets("");
void loadSecretsStored();
},
);
}
}
return (
<Panel
title={`set the API-key environment — ${agent}`}
title={`backend settings (advanced) — ${agent}`}
icon="🔗"
onClose={onClose}
>
<p>
Writes <code>NAME=VALUE</code> lines (for example{" "}
<code>ANTHROPIC_API_KEY</code> and <code>ANTHROPIC_BASE_URL</code>) to
the swarm secret store. Saving replaces whatever is stored, including
text the agent wrote itself. The agent fetches it within two minutes and
loads it at its next restart; it wins over the agent's{" "}
<code>backendEnvironmentFile</code>. Remove deletes the stored text; an
agent whose <code>backendEnvironmentFile</code> has content stores that
file again.
Two env files, loaded at the agent&apos;s next restart: the
configuration first, then the secrets, so a secret wins over a variable
of the same name. For just an API key, use <strong>set API key</strong>.
</p>
<FormStack onSubmit={save}>
<SectionHeading class="backend-env-heading">configuration</SectionHeading>
<FormStack
onSubmit={(e) => {
e.preventDefault();
send(
configRun,
backendEnvUrl(hive, agent),
"PUT",
config,
"stored the configuration of",
() => {},
);
}}
>
<TextAreaField
id="backend-env-text"
label="environment file text"
value={env}
id="backend-env-config"
label="NAME=VALUE lines, such as ANTHROPIC_BASE_URL"
value={config}
required
rows={6}
placeholder="ANTHROPIC_API_KEY=…"
onInput={setEnv}
rows={5}
placeholder={loaded ? "ANTHROPIC_BASE_URL=…" : "loading…"}
onInput={setConfig}
/>
<Button variant="primary" type="submit" disabled={busy}>
{busy ? "saving…" : "save"}
</Button>
<Button type="button" disabled={busy} onClick={() => void removeEnv()}>
remove
</Button>
<ActionRow>
<Button
variant="primary"
type="submit"
disabled={configRun.submitting || !loaded}
>
{configRun.submitting ? "saving…" : "save"}
</Button>
<Button
type="button"
disabled={configRun.submitting}
onClick={() => void removeConfig()}
>
remove
</Button>
</ActionRow>
</FormStack>
<FormResult
state={state}
state={configRun.state}
done={(message) => (
<>
{message} <strong>{agent}</strong>
</>
)}
failed="failed to update the API-key environment"
failed="failed to update the configuration"
/>
<SectionHeading class="backend-env-heading">secrets</SectionHeading>
<FormStack
onSubmit={(e) => {
e.preventDefault();
send(
secretsRun,
backendSecretsUrl(hive, agent),
"PUT",
secrets,
"stored the secrets of",
() => {
setSecrets("");
void loadSecretsStored();
},
);
}}
>
<TextAreaField
id="backend-env-secrets"
label="NAME=VALUE lines, such as ANTHROPIC_API_KEY"
value={secrets}
rows={3}
placeholder="ANTHROPIC_API_KEY=…"
onInput={setSecrets}
/>
<Hint>
{secretsStored === null
? "Write-only."
: secretsStored
? "Secrets are stored and never shown. Saving here replaces them; leave the box empty to keep them."
: "No secrets are stored."}
</Hint>
<ActionRow>
<Button
variant="primary"
type="submit"
disabled={secretsRun.submitting || secrets.trim() === ""}
>
{secretsRun.submitting ? "saving…" : "save"}
</Button>
<Button
type="button"
disabled={secretsRun.submitting || secretsStored === false}
onClick={() => void removeSecrets()}
>
remove
</Button>
</ActionRow>
</FormStack>
<FormResult
state={secretsRun.state}
done={(message) => (
<>
{message} <strong>{agent}</strong>
</>
)}
failed="failed to update the secrets"
/>
{confirmDialog}
</Panel>

View file

@ -4,6 +4,10 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
apiKeySecrets,
backendEnvUrl,
backendSecretsUrl,
checkApiKey,
checkLink,
deleteUrl,
linkBody,
@ -71,3 +75,26 @@ test("a message never contains the token", () => {
const msg = checkLink("Bad", "nope", "s3cr3t-value");
assert.ok(!String(msg).includes("s3cr3t-value"));
});
test("the backend routes sit under the agent and name the config and the secrets", () => {
assert.equal(
backendEnvUrl("pr1ma", "atlas"),
"/api/hives/pr1ma/agents/atlas/backend-env",
);
assert.equal(
backendSecretsUrl("pr1ma", "atlas"),
"/api/hives/pr1ma/agents/atlas/backend-secrets",
);
});
test("an API key becomes one trimmed ANTHROPIC_API_KEY line", () => {
assert.equal(apiKeySecrets(" sk-ant-x \n"), "ANTHROPIC_API_KEY=sk-ant-x");
});
test("a key the controller would refuse is caught first, and a plain one is not", () => {
assert.equal(checkApiKey("sk-ant-api03-AbC_d-9"), null);
assert.equal(checkApiKey(" "), "key is required");
for (const bad of ["a b", 'a"b', "a'b", "a\\b"]) {
assert.notEqual(checkApiKey(bad), null, bad);
}
});