diff --git a/docs/4-implementation/web-ui/swarm-ui.md b/docs/4-implementation/web-ui/swarm-ui.md index f08fc3037..4f12df2a7 100644 --- a/docs/4-implementation/web-ui/swarm-ui.md +++ b/docs/4-implementation/web-ui/swarm-ui.md @@ -1075,8 +1075,18 @@ Each agent on `/agents` opens four dialogs that write a credential for it into the swarm secret store through swarm-controller. All four are blind set actions: no route hands a token back. swarm-controller refuses to link a name that already holds an account; delete that account first to replace it. -The fourth, the API-key environment, is the exception: a save overwrites what the -store holds. +The fourth, the advanced settings (the API-key environment), is the exception: +a save overwrites what the store holds. It has two sections. The configuration +reads back and its box starts with the stored text. The secrets never read back, +so their box starts empty and replaces the stored secrets only when filled and +saved. + +The **claude login** row of an opened agent also sets the API key: **set API key** +(or **replace API key**) sends the key as `ANTHROPIC_API_KEY=` to the +agent's secrets, **remove API key** deletes them, and **advanced** opens +the form above. The row shows whether the store holds a key and never the key. A +change reaches the agent at its next restart, and an agent with a key tries it +instead of waiting for a claude login. An opened agent card lists its linked accounts at the end of its **settings** section, one row per account: kind, name and host. Opening an agent makes one request, diff --git a/frontend/packages/swarm-ui/src/agent/detail/AgentApiKey.tsx b/frontend/packages/swarm-ui/src/agent/detail/AgentApiKey.tsx new file mode 100644 index 000000000..e9cd279eb --- /dev/null +++ b/frontend/packages/swarm-ui/src/agent/detail/AgentApiKey.tsx @@ -0,0 +1,162 @@ +// — 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(null); + const [error, setError] = useState(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(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 ( +
+ {error ? ( + + ) : null} + {stored === null ? null : ( + <> + {" "} + + )} + setSetting(true)} + />{" "} + {stored ? ( + <> + { + setRemoveError(null); + setConfirming(true); + }} + />{" "} + + ) : null} + setAdvanced(true)} + /> + setSetting(false)} + label="set the API key" + plain + > + {setting ? ( + void load()} + onClose={() => setSetting(false)} + /> + ) : null} + + { + setAdvanced(false); + void load(); + }} + label="backend settings (advanced)" + plain + > + {advanced ? ( + { + setAdvanced(false); + void load(); + }} + /> + ) : null} + + setConfirming(false)} + onConfirm={() => void confirmRemove()} + > +

+ Remove the stored API key for {agent}? The key cannot + be read back, so it cannot be restored. The agent stops loading it at + its next restart. +

+ {removeError ? ( + + ) : null} +
+
+ ); +} diff --git a/frontend/packages/swarm-ui/src/agent/detail/AgentDetail.tsx b/frontend/packages/swarm-ui/src/agent/detail/AgentDetail.tsx index 4894abb12..addae0d44 100644 --- a/frontend/packages/swarm-ui/src/agent/detail/AgentDetail.tsx +++ b/frontend/packages/swarm-ui/src/agent/detail/AgentDetail.tsx @@ -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 ( <>
inference
@@ -206,6 +207,9 @@ function SettingsRows({ agent }: { agent: string }) {
claude login
+ {hive ? ( + + ) : null}
); @@ -312,7 +316,7 @@ function SectionBody({ return ( <>
- +
diff --git a/frontend/packages/swarm-ui/src/agent/detail/LinkAccountMenu.tsx b/frontend/packages/swarm-ui/src/agent/detail/LinkAccountMenu.tsx index 636506726..5246b995b 100644 --- a/frontend/packages/swarm-ui/src/agent/detail/LinkAccountMenu.tsx +++ b/frontend/packages/swarm-ui/src/agent/detail/LinkAccountMenu.tsx @@ -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" } /> diff --git a/frontend/packages/swarm-ui/src/agent/detail/account-api.ts b/frontend/packages/swarm-ui/src/agent/detail/account-api.ts index 8a4f4e938..34be78507 100644 --- a/frontend/packages/swarm-ui/src/agent/detail/account-api.ts +++ b/frontend/packages/swarm-ui/src/agent/detail/account-api.ts @@ -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; +} diff --git a/frontend/packages/swarm-ui/src/agent/roster/AgentActions.tsx b/frontend/packages/swarm-ui/src/agent/roster/AgentActions.tsx index de865c112..4fcbd2fb3 100644 --- a/frontend/packages/swarm-ui/src/agent/roster/AgentActions.tsx +++ b/frontend/packages/swarm-ui/src/agent/roster/AgentActions.tsx @@ -277,7 +277,7 @@ export function useAgentActions( {backendTarget?.hive ? ( diff --git a/frontend/packages/swarm-ui/src/pages/LinkApiKeyForm.tsx b/frontend/packages/swarm-ui/src/pages/LinkApiKeyForm.tsx new file mode 100644 index 000000000..cdb66d6b9 --- /dev/null +++ b/frontend/packages/swarm-ui/src/pages/LinkApiKeyForm.tsx @@ -0,0 +1,94 @@ +// — sets an agent's API key. The key goes to the agent's +// backend secrets in the swarm secret store as `ANTHROPIC_API_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 ( + +

+ Bills {agent} through the API instead of a Claude + login. +

+ + + + Stored in the swarm secret store and never shown again; a save + replaces the stored key. The agent loads it at its next restart. + + + + ( + <> + stored the API key for {agent} + + )} + failed="failed to store the API key" + /> +
+ ); +} diff --git a/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.css b/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.css new file mode 100644 index 000000000..97b1774fc --- /dev/null +++ b/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.css @@ -0,0 +1,3 @@ +.backend-env-heading { + margin: 1.25em 0 0; +} diff --git a/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.tsx b/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.tsx index f0d0c985a..18a4757bc 100644 --- a/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.tsx +++ b/frontend/packages/swarm-ui/src/pages/LinkBackendEnvForm.tsx @@ -1,24 +1,32 @@ -// — 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`. +// — 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(); + const [config, setConfig] = useState(""); + const [loaded, setLoaded] = useState(false); + const [secrets, setSecrets] = useState(""); + const [secretsStored, setSecretsStored] = useState(null); + const configRun = useSubmit(); + const secretsRun = useSubmit(); const [confirm, confirmDialog] = useConfirm(); - async function removeEnv() { - const yes = await confirm({ - label: "remove the API-key environment", - confirmLabel: "remove", - danger: true, - body: ( -

- Remove the stored API-key environment for {agent}? - The stored text cannot be read back, so it cannot be restored; paste - it again to set it. -

- ), - }); - 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>, + 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: ( +

+ Remove the stored configuration for {agent}? An agent + whose backendEnvironmentFile has content stores that file + again. +

+ ), + }); + 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: ( +

+ Remove the stored secrets (the API key) for {agent}? + The stored text cannot be read back, so it cannot be restored. +

+ ), + }); + if (yes) { + send( + secretsRun, + backendSecretsUrl(hive, agent), + "DELETE", + "", + "removed the secrets of", + () => { + setSecrets(""); + void loadSecretsStored(); + }, + ); + } } return (

- Writes NAME=VALUE lines (for example{" "} - ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL) 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{" "} - backendEnvironmentFile. Remove deletes the stored text; an - agent whose backendEnvironmentFile has content stores that - file again. + Two env files, loaded at the agent'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 set API key.

- + configuration + { + e.preventDefault(); + send( + configRun, + backendEnvUrl(hive, agent), + "PUT", + config, + "stored the configuration of", + () => {}, + ); + }} + > - - + + + + ( <> {message} {agent} )} - failed="failed to update the API-key environment" + failed="failed to update the configuration" + /> + secrets + { + e.preventDefault(); + send( + secretsRun, + backendSecretsUrl(hive, agent), + "PUT", + secrets, + "stored the secrets of", + () => { + setSecrets(""); + void loadSecretsStored(); + }, + ); + }} + > + + + {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."} + + + + + + + ( + <> + {message} {agent} + + )} + failed="failed to update the secrets" /> {confirmDialog}
diff --git a/frontend/packages/swarm-ui/test/account-api.test.mjs b/frontend/packages/swarm-ui/test/account-api.test.mjs index a1622b3d2..256969667 100644 --- a/frontend/packages/swarm-ui/test/account-api.test.mjs +++ b/frontend/packages/swarm-ui/test/account-api.test.mjs @@ -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); + } +});