Watch
0
0
Fork
You've already forked hyperhive
0

swarm-ui: forms share one submit flow, result line and field column

useSubmit holds the idle, sending, done and error state and the request
flow that six forms each wrote out; FormResult shows the success line and
the problem panel; FormStack is the column the link, claude-login,
inference and limits forms each styled by hand. The create-agent, link
account, backend-env and agent-input forms use the submit flow; the link,
claude-login, inference and limits forms use FormStack.
This commit is contained in:
iris 2026-11-06 18:47:34 +01:00 • committed by mara
commit 811b23cd6b
23 changed files with 517 additions and 377 deletions

View file

@ -1,12 +1,4 @@
/* <ClaudeLoginDialog> — the code form's column, as
`LinkMatrixAccountForm.css` lays its form out. */
.claude-login-form {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75em;
margin-top: 1em;
}
/* <ClaudeLoginDialog> */
.claude-login-ok {
margin-block: 1em;
}

View file

@ -10,6 +10,7 @@ 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 { Button } from "../../ui/button/Button.js";
import { FormStack } from "../../ui/form-stack/FormStack.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { ExternalLink } from "../../ui/external-link/ExternalLink.js";
import { Hint } from "../../ui/hint/Hint.js";
@ -103,7 +104,7 @@ export function ClaudeLoginDialog({
<ExternalLink href={step.url}>the claude login page</ExternalLink>
, sign in with this agent's account, and paste the code it shows.
</p>
<form class="claude-login-form" onSubmit={submit}>
<FormStack onSubmit={submit}>
<TextField
id="claude-login-code"
label="code"
@ -118,7 +119,7 @@ export function ClaudeLoginDialog({
>
{step.step === "submitting" ? "logging in…" : "log in"}
</Button>
</form>
</FormStack>
</>
)}
{step.step === "stored" && (

View file

@ -20,10 +20,3 @@
.ui-agent-inference-source {
color: var(--muted);
}
.ui-agent-inference-form {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75em;
margin-top: 1em;
}

View file

@ -22,6 +22,7 @@ import { Panel } from "../../ui/panel/Panel.js";
import { SelectField } from "../../ui/select-field/SelectField.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 "../../ui/badge-row/BadgeRow.css";
import "./AgentInference.css";
import { MAX_SUBAGENTS, maxSubagentsValue } from "./max-subagents.js";
@ -365,7 +366,7 @@ function InferenceForm({
started with, and subagents already running past a lowered cap keep
running.
</p>
<form class="ui-agent-inference-form" onSubmit={save}>
<FormStack onSubmit={save}>
<InferenceFields draft={draft} onChange={setDraft} />
{problem ? (
<ApiErrorPanel context="saving failed" problem={problem} />
@ -385,7 +386,7 @@ function InferenceForm({
clear the swarm's setting
</Button>
</ActionRow>
</form>
</FormStack>
</Panel>
);
}

View file

@ -14,13 +14,6 @@
.ui-agent-limits-muted {
color: var(--muted);
}
.ui-agent-limits-form {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.5em;
margin-top: 1em;
}
.ui-agent-limits-hint {
margin: 0 0 0.5em;
}

View file

@ -18,6 +18,7 @@ import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Badge } from "@hive/shared/badge.js";
import { ActionRow } from "../../ui/action-row/ActionRow.js";
import { Button } from "../../ui/button/Button.js";
import { FormStack } from "../../ui/form-stack/FormStack.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { Hint } from "../../ui/hint/Hint.js";
import { Panel } from "../../ui/panel/Panel.js";
@ -231,7 +232,7 @@ function LimitsForm({
hive. The hive reads a change within about 30 seconds, and a running
agent takes it at its next spawn or rebuild.
</p>
<form class="ui-agent-limits-form" onSubmit={save}>
<FormStack onSubmit={save}>
<LimitsFields
cpu={cpu}
memory={memory}
@ -252,7 +253,7 @@ function LimitsForm({
clear the swarm's caps
</Button>
</ActionRow>
</form>
</FormStack>
</Panel>
);
}

View file

@ -27,6 +27,7 @@ import { Badge } from "@hive/shared/badge.js";
import { ActionRow } from "../../ui/action-row/ActionRow.js";
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
import { Button } from "../../ui/button/Button.js";
import { FormStack } from "../../ui/form-stack/FormStack.js";
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { Panel } from "../../ui/panel/Panel.js";
@ -214,7 +215,7 @@ export function AddForm({
: "A name that resolves to a private address stays blocked. The entry adds to the names each hive's own configuration allows."}{" "}
The hive reads a change within about 30 seconds.
</p>
<form class="ui-agent-limits-form" onSubmit={(e) => void save(e)}>
<FormStack onSubmit={(e) => void save(e)}>
<TextField
id={deny ? "denied-domain" : "allowed-domain"}
label="domain"
@ -242,7 +243,7 @@ export function AddForm({
{busy ? "adding…" : "add"}
</Button>
</ActionRow>
</form>
</FormStack>
</Panel>
);
}

View file

@ -13,5 +13,4 @@
}
.ui-agent-input-sent {
margin-block-start: 0.25rem;
color: var(--green);
}

View file

@ -5,42 +5,27 @@
// sender from the gateway, not from this request).
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 { TextField } from "../../ui/text-field/TextField.js";
import { Button } from "../../ui/button/Button.js";
import { Hint } from "../../ui/hint/Hint.js";
import { useSubmit } from "../../ui/submit/useSubmit.js";
import "./AgentInputForm.css";
type SubmitState =
| { status: "idle" }
| { status: "submitting" }
| { status: "sent" }
| { status: "error"; problem: ProblemDetails };
export function AgentInputForm({ agentName }: { agentName: string }) {
const [body, setBody] = useState("");
const [result, setResult] = useState<SubmitState>({ status: "idle" });
const { state, submitting, run } = useSubmit();
async function submit(e: Event) {
function submit(e: Event) {
e.preventDefault();
setResult({ status: "submitting" });
try {
const r = await fetch(
`/api/agents/${encodeURIComponent(agentName)}/input`,
{
void run(
() =>
fetch(`/api/agents/${encodeURIComponent(agentName)}/input`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ body }),
},
);
if (!r.ok) {
setResult({ status: "error", problem: await readApiError(r) });
return;
}
setResult({ status: "sent" });
setBody("");
} catch (err) {
setResult({ status: "error", problem: { detail: String(err) } });
}
}),
{ onDone: () => setBody("") },
);
}
return (
@ -53,17 +38,17 @@ export function AgentInputForm({ agentName }: { agentName: string }) {
required
onInput={setBody}
/>
<Button
variant="primary"
type="submit"
disabled={result.status === "submitting"}
>
{result.status === "submitting" ? "sending…" : "send"}
<Button variant="primary" type="submit" disabled={submitting}>
{submitting ? "sending…" : "send"}
</Button>
</form>
{result.status === "sent" && <p class="ui-agent-input-sent">sent</p>}
{result.status === "error" && (
<ApiErrorPanel context="failed to send" problem={result.problem} />
{state.status === "done" && (
<Hint tone="ok" class="ui-agent-input-sent">
sent
</Hint>
)}
{state.status === "error" && (
<ApiErrorPanel context="failed to send" problem={state.problem} />
)}
</div>
);

View file

@ -41,7 +41,10 @@ import {
ExpandableCardListSkeleton,
} from "../ui/expandable-card/ExpandableCard.js";
import { ExternalLink } from "../ui/external-link/ExternalLink.js";
import { FormStack } from "../ui/form-stack/FormStack.js";
import { Hint, type HintTone } from "../ui/hint/Hint.js";
import { FormResult } from "../ui/submit/FormResult.js";
import type { SubmitState } from "../ui/submit/submit.js";
import { Toolbar } from "../ui/toolbar/Toolbar.js";
import { ConfirmDialog } from "../ui/confirm-dialog/ConfirmDialog.js";
import { Popover } from "../ui/popover/Popover.js";
@ -52,6 +55,14 @@ import "./ComponentsPage.css";
const HINT_TONES: HintTone[] = ["muted", "warn", "error", "ok"];
const SUBMIT_SAMPLES: [string, SubmitState][] = [
["done", { status: "done", value: undefined }],
[
"error",
{ status: "error", problem: { detail: "the agent is not listening" } },
],
];
function Section({
title,
children,
@ -631,6 +642,31 @@ export function ComponentsPage() {
</Sample>
</Section>
<Section title="FormStack and FormResult">
<Sample label="FormStack: fields and buttons in one column">
<FormStack onSubmit={(e) => e.preventDefault()}>
<TextField
id="components-stack-name"
label="name"
value=""
onInput={() => {}}
/>
<Button variant="primary" type="submit">
save
</Button>
</FormStack>
</Sample>
{SUBMIT_SAMPLES.map(([label, state]) => (
<Sample key={label} label={`FormResult: ${label}`}>
<FormResult
state={state}
done={() => "stored the token"}
failed="failed to link the account"
/>
</Sample>
))}
</Section>
<Section title="ExpandableCard">
<Sample label="closed, open, and the loading twin">
<ExpandableCard

View file

@ -48,6 +48,7 @@ import {
import { CheckboxField } from "../ui/checkbox-field/CheckboxField.js";
import { FormField } from "../ui/form-field/FormField.js";
import { Hint } from "../ui/hint/Hint.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
import { MultiselectFilterOptions } from "../ui/multiselect-filter/MultiselectFilter.js";
import {
initialSelection,
@ -93,12 +94,6 @@ interface PermissionCatalogue {
default: string[];
}
type SubmitState =
| { status: "idle" }
| { status: "submitting" }
| { status: "done"; nodeId: number }
| { status: "error"; problem: ProblemDetails };
export function CreateAgentForm({
onClose,
initialName = "",
@ -121,7 +116,8 @@ export function CreateAgentForm({
// option's label can tell the two apart.
const [hives, setHives] = useState<HiveEntry[] | null>(null);
const [hivesError, setHivesError] = useState<ProblemDetails | null>(null);
const [result, setResult] = useState<SubmitState>({ status: "idle" });
// The done value is the queued job's node id.
const { state: result, run, reset } = useSubmit<number>();
// The optional settings sections, left empty unless the operator fills them.
const [cpu, setCpu] = useState("");
const [memory, setMemory] = useState("");
@ -218,48 +214,52 @@ export function CreateAgentForm({
const refusal =
result.status === "error" ? agentsMdRefusal(result.problem) : null;
async function submit() {
setResult({ status: "submitting" });
try {
// A section left empty is left out, so the request is the plain
// name-and-hive one unless the operator set something.
const limits = capsBody(cpu, memory);
const settings = draftBody(inference);
const r = await fetch("/api/agents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
name,
hive,
...(Object.keys(limits).length > 0 ? { limits } : {}),
...(Object.keys(settings).length > 0 ? { inference: settings } : {}),
permissions: catalogue
? requestPermissions(selected, catalogue.default)
: undefined,
...requestInternet(internet),
archetype: requestArchetype(picked),
...agentsMdBody(agentsMd),
function submit() {
// A section left empty is left out, so the request is the plain
// name-and-hive one unless the operator set something.
const limits = capsBody(cpu, memory);
const settings = draftBody(inference);
void run(
() =>
fetch("/api/agents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
name,
hive,
...(Object.keys(limits).length > 0 ? { limits } : {}),
...(Object.keys(settings).length > 0
? { inference: settings }
: {}),
permissions: catalogue
? requestPermissions(selected, catalogue.default)
: undefined,
...requestInternet(internet),
archetype: requestArchetype(picked),
...agentsMdBody(agentsMd),
}),
}),
});
if (!r.ok) {
const problem = await readApiError(r);
setResult({ status: "error", problem });
{
parse: async (r) => ((await r.json()) as CreateAgentResponse).node_id,
onDone: () => {
setName("");
setAgentsMd("");
pickArchetype("");
if (catalogue)
setSelected(
initialSelection(
catalogue.all,
catalogue.default,
extraPermissions,
),
);
},
// The text's own refusal shows beside its box, so go back to it.
if (agentsMdRefusal(problem) !== null) setStep("instructions");
return;
}
const data = (await r.json()) as CreateAgentResponse;
setResult({ status: "done", nodeId: data.node_id });
setName("");
setAgentsMd("");
pickArchetype("");
if (catalogue)
setSelected(
initialSelection(catalogue.all, catalogue.default, extraPermissions),
);
} catch (err) {
setResult({ status: "error", problem: { detail: String(err) } });
}
onError: (problem) => {
if (agentsMdRefusal(problem) !== null) setStep("instructions");
},
},
);
}
const problem = stepProblem(step, {
@ -275,12 +275,12 @@ export function CreateAgentForm({
function onSubmit(e: Event) {
e.preventDefault();
if (done || result.status === "submitting") return;
if (step === "summary") void submit();
if (step === "summary") submit();
else if (problem === null) setStep(nextStep(step));
}
function createAnother() {
setResult({ status: "idle" });
reset();
setStep("identity");
}
@ -329,7 +329,7 @@ export function CreateAgentForm({
{done && (
<Hint tone="ok" as="div" class="create-agent-result">
<p>
Queued as job node #{result.nodeId} —{" "}
Queued as job node #{result.value} —{" "}
<Link href="/jobs">watch it in jobs</Link>.
</p>
</Hint>

View file

@ -8,19 +8,12 @@
// stored value. A save replaces whatever is stored. Whether one is stored
// shows on the agent panel (`LinkedAccounts`).
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 { Panel } from "../ui/panel/Panel.js";
import { TextAreaField } from "../ui/text-area-field/TextAreaField.js";
import { Button } from "../ui/button/Button.js";
import { Hint } from "../ui/hint/Hint.js";
import "./LinkMatrixAccountForm.css";
type SubmitState =
| { status: "idle" }
| { status: "submitting" }
| { status: "done"; message: string }
| { status: "error"; problem: ProblemDetails };
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
// A swarm-controller without the route answers 404 with no problem body.
const NO_ROUTE =
@ -36,46 +29,37 @@ export function LinkBackendEnvForm({
onClose?: () => void;
}) {
const [env, setEnv] = useState("");
const [result, setResult] = useState<SubmitState>({ status: "idle" });
// The success line is what the request did, so it is the done value.
const { state, submitting: busy, run } = useSubmit<string>();
async function send(method: "PUT" | "DELETE", done: string) {
setResult({ status: "submitting" });
try {
const r = await fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/backend-env`,
method === "PUT"
? {
method,
headers: { "content-type": "application/json" },
body: JSON.stringify({ env }),
}
: { method },
);
if (!r.ok) {
const problem = await readApiError(r);
setResult({
status: "error",
problem:
r.status === 404 && !problem.detail
? { detail: NO_ROUTE }
: problem,
});
return;
}
setResult({ status: "done", message: done });
// The store holds the text; nothing here needs it.
setEnv("");
} catch (err) {
setResult({ status: "error", problem: { detail: String(err) } });
}
function send(method: "PUT" | "DELETE", done: string) {
void run(
() =>
fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/backend-env`,
method === "PUT"
? {
method,
headers: { "content-type": "application/json" },
body: JSON.stringify({ env }),
}
: { method },
),
{
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(""),
},
);
}
function save(e: Event) {
e.preventDefault();
void send("PUT", "stored the API-key environment for");
send("PUT", "stored the API-key environment for");
}
const busy = result.status === "submitting";
return (
<Panel
title={`set the API-key environment — ${agent}`}
@ -92,7 +76,7 @@ export function LinkBackendEnvForm({
agent whose <code>backendEnvironmentFile</code> has content stores that
file again.
</p>
<form class="link-matrix-account-form" onSubmit={save}>
<FormStack onSubmit={save}>
<TextAreaField
id="backend-env-text"
label="environment file text"
@ -108,24 +92,20 @@ export function LinkBackendEnvForm({
<Button
type="button"
disabled={busy}
onClick={() =>
void send("DELETE", "removed the API-key environment for")
}
onClick={() => send("DELETE", "removed the API-key environment for")}
>
remove
</Button>
</form>
{result.status === "done" && (
<Hint tone="ok" class="link-matrix-account-result-ok">
{result.message} <strong>{agent}</strong>
</Hint>
)}
{result.status === "error" && (
<ApiErrorPanel
context="failed to update the API-key environment"
problem={result.problem}
/>
)}
</FormStack>
<FormResult
state={state}
done={(message) => (
<>
{message} <strong>{agent}</strong>
</>
)}
failed="failed to update the API-key environment"
/>
</Panel>
);
}

View file

@ -9,12 +9,12 @@
// set: no route hands a token back. Linked labels and URLs show on
// the agent panel (`LinkedAccounts`).
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 { Panel } from "../ui/panel/Panel.js";
import { TextField } from "../ui/text-field/TextField.js";
import { Button } from "../ui/button/Button.js";
import { Hint } from "../ui/hint/Hint.js";
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
import {
checkLink,
LABEL_PATTERN,
@ -22,17 +22,10 @@ import {
linkUrl,
type ForgeLinkKind,
} from "../agent/detail/account-api.js";
import "./LinkMatrixAccountForm.css";
// Prefilled for gitlab; the field stays editable for a self-hosted instance.
const GITLAB_DEFAULT_URL = "https://gitlab.com";
type SubmitState =
| { status: "idle" }
| { status: "submitting" }
| { status: "done"; label: string; url: string }
| { status: "error"; problem: ProblemDetails };
export function LinkForgeAccountForm({
kind,
hive,
@ -47,35 +40,37 @@ export function LinkForgeAccountForm({
const [label, setLabel] = useState("");
const [url, setUrl] = useState(kind === "gitlab" ? GITLAB_DEFAULT_URL : "");
const [token, setToken] = useState("");
const [result, setResult] = useState<SubmitState>({ status: "idle" });
// The label is kept with the result, so the success message reads against
// what was sent even if the field is edited afterwards.
const { state, submitting, run, fail } = useSubmit<{
label: string;
url: string;
}>();
async function submit(e: Event) {
function submit(e: Event) {
e.preventDefault();
const invalid = checkLink(label, url, token);
if (invalid) {
setResult({ status: "error", problem: { detail: invalid } });
fail({ detail: invalid });
return;
}
setResult({ status: "submitting" });
try {
const r = await fetch(linkUrl(hive, agent, kind, label), {
method: "PUT",
headers: { "content-type": "application/json" },
body: linkBody(url, token),
});
if (!r.ok) {
setResult({ status: "error", problem: await readApiError(r) });
return;
}
const body = (await r.json().catch(() => ({}))) as { url?: string };
// The label is stored with the result, so the success message reads
// against what was sent even if the field is edited afterwards.
setResult({ status: "done", label, url: body.url ?? url.trim() });
// The store holds the token now; nothing here needs it.
setToken("");
} catch (err) {
setResult({ status: "error", problem: { detail: String(err) } });
}
const sent = label;
void run(
() =>
fetch(linkUrl(hive, agent, kind, sent), {
method: "PUT",
headers: { "content-type": "application/json" },
body: linkBody(url, token),
}),
{
parse: async (r) => {
const body = (await r.json().catch(() => ({}))) as { url?: string };
return { label: sent, url: body.url ?? url.trim() };
},
// The store holds the token now; nothing here needs it.
onDone: () => setToken(""),
},
);
}
return (
@ -107,7 +102,7 @@ export function LinkForgeAccountForm({
the external forge first; nothing is created there.
</p>
)}
<form class="link-matrix-account-form" onSubmit={submit}>
<FormStack onSubmit={submit}>
<TextField
id={`${kind}-account-label`}
label="label"
@ -139,26 +134,20 @@ export function LinkForgeAccountForm({
required
onInput={setToken}
/>
<Button
variant="primary"
type="submit"
disabled={result.status === "submitting"}
>
{result.status === "submitting" ? "linking…" : "link account"}
<Button variant="primary" type="submit" disabled={submitting}>
{submitting ? "linking…" : "link account"}
</Button>
</form>
{result.status === "done" && (
<Hint tone="ok" class="link-matrix-account-result-ok">
linked <strong>{result.label}</strong> ({result.url}) to{" "}
<strong>{agent}</strong>
</Hint>
)}
{result.status === "error" && (
<ApiErrorPanel
context="failed to link the account"
problem={result.problem}
/>
)}
</FormStack>
<FormResult
state={state}
done={(linked) => (
<>
linked <strong>{linked.label}</strong> ({linked.url}) to{" "}
<strong>{agent}</strong>
</>
)}
failed="failed to link the account"
/>
</Panel>
);
}

View file

@ -7,20 +7,13 @@
// One token per agent. A blind set: no route hands a token back.
// Whether one is stored shows on the agent panel (`LinkedAccounts`).
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 { Panel } from "../ui/panel/Panel.js";
import { TextField } from "../ui/text-field/TextField.js";
import { Button } from "../ui/button/Button.js";
import { ExternalLink } from "../ui/external-link/ExternalLink.js";
import { Hint } from "../ui/hint/Hint.js";
import "./LinkMatrixAccountForm.css";
type SubmitState =
| { status: "idle" }
| { status: "submitting" }
| { status: "done" }
| { status: "error"; problem: ProblemDetails };
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
export function LinkGithubAccountForm({
hive,
@ -32,30 +25,23 @@ export function LinkGithubAccountForm({
onClose?: () => void;
}) {
const [token, setToken] = useState("");
const [result, setResult] = useState<SubmitState>({ status: "idle" });
const { state, submitting, run } = useSubmit();
async function submit(e: Event) {
function submit(e: Event) {
e.preventDefault();
setResult({ status: "submitting" });
try {
const r = await fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/github-account`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token }),
},
);
if (!r.ok) {
setResult({ status: "error", problem: await readApiError(r) });
return;
}
setResult({ status: "done" });
void run(
() =>
fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/github-account`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token }),
},
),
// The store holds the token; nothing here needs it.
setToken("");
} catch (err) {
setResult({ status: "error", problem: { detail: String(err) } });
}
{ onDone: () => setToken("") },
);
}
return (
@ -74,7 +60,7 @@ export function LinkGithubAccountForm({
</ExternalLink>
; GitHub notifications also need the <code>notifications</code> scope.
</p>
<form class="link-matrix-account-form" onSubmit={submit}>
<FormStack onSubmit={submit}>
<TextField
id="github-account-token"
label="personal access token"
@ -83,25 +69,19 @@ export function LinkGithubAccountForm({
required
onInput={setToken}
/>
<Button
variant="primary"
type="submit"
disabled={result.status === "submitting"}
>
{result.status === "submitting" ? "linking…" : "link account"}
<Button variant="primary" type="submit" disabled={submitting}>
{submitting ? "linking…" : "link account"}
</Button>
</form>
{result.status === "done" && (
<Hint tone="ok" class="link-matrix-account-result-ok">
stored a github token for <strong>{agent}</strong>
</Hint>
)}
{result.status === "error" && (
<ApiErrorPanel
context="failed to link the account"
problem={result.problem}
/>
)}
</FormStack>
<FormResult
state={state}
done={() => (
<>
stored a github token for <strong>{agent}</strong>
</>
)}
failed="failed to link the account"
/>
</Panel>
);
}

View file

@ -1,17 +0,0 @@
/* <LinkMatrixAccountForm> — rendered inside a `Dialog` from `AgentsPage`,
one panel wide. Column layout + `.link-matrix-account-result-ok`
mirror `CreateAgentForm.css`'s `.create-agent-fields`/`.create-agent-result-ok`
— same shape, kept as its own file rather than sharing that
one since "form" here means a different component's layout, not a
generic kit primitive (see that file's own top comment on why
`ui/form-field` stays the only truly shared piece). */
.link-matrix-account-form {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75em;
margin-top: 1em;
}
.link-matrix-account-result-ok {
margin-block: 1em;
}

View file

@ -26,14 +26,13 @@
// `WantedMenu`-sized, which is why that one stays inline in
// `AgentsPage.tsx` and this one doesn't).
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 { Panel } from "../ui/panel/Panel.js";
import { TextField } from "../ui/text-field/TextField.js";
import { SelectField } from "../ui/select-field/SelectField.js";
import { Button } from "../ui/button/Button.js";
import { Hint } from "../ui/hint/Hint.js";
import "./LinkMatrixAccountForm.css";
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
type Mode = "token" | "password";
@ -45,15 +44,13 @@ type Mode = "token" | "password";
// gate, this just avoids a round-trip for an obviously-bad name.
const ACCOUNT_PATTERN = "[A-Za-z0-9_\\-]{1,63}";
type SubmitState =
| { status: "idle" }
| { status: "submitting" }
// `userId` is set in password mode (the server resolves it from the
// login response) and `undefined` in token mode — see
// `PutMatrixAccountResponse`'s own doc for why token mode doesn't
// spend a round trip resolving one.
| { status: "done"; account: string; userId?: string }
| { status: "error"; problem: ProblemDetails };
// `userId` is set in password mode (the server resolves it from the login
// response) and `undefined` in token mode — see `PutMatrixAccountResponse`'s
// own doc for why token mode doesn't spend a round trip resolving one.
interface Linked {
account: string;
userId?: string;
}
const MODE_OPTIONS = [
{ value: "token", label: "paste a token" },
@ -78,7 +75,7 @@ export function LinkMatrixAccountForm({
const [userId, setUserId] = useState("");
const [password, setPassword] = useState("");
const [homeserver, setHomeserver] = useState("");
const [result, setResult] = useState<SubmitState>({ status: "idle" });
const { state, submitting, run } = useSubmit<Linked>();
// A secret lives in state only while it is being typed and sent: it is
// dropped when the request ends, whether it worked or not, and when the
@ -88,51 +85,53 @@ export function LinkMatrixAccountForm({
setPassword("");
}
async function submit(e: Event) {
function submit(e: Event) {
e.preventDefault();
setResult({ status: "submitting" });
try {
const r = await fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/matrix-accounts/${encodeURIComponent(account)}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(
mode === "token"
? {
mode,
token,
// Omitted rather than sent empty — the contract marks
// it optional in token mode, and an empty string
// isn't "no homeserver", it's a homeserver named "".
homeserver: homeserver.trim() || undefined,
}
: {
mode,
user_id: userId,
password,
// Required in password mode — the field below enforces
// that before this branch is ever reachable.
homeserver: homeserver.trim(),
},
),
const sent = account;
void run(
async () => {
try {
return await fetch(
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/matrix-accounts/${encodeURIComponent(sent)}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(
mode === "token"
? {
mode,
token,
// Omitted rather than sent empty — the contract marks
// it optional in token mode, and an empty string
// isn't "no homeserver", it's a homeserver named "".
homeserver: homeserver.trim() || undefined,
}
: {
mode,
user_id: userId,
password,
// Required in password mode — the field below enforces
// that before this branch is ever reachable.
homeserver: homeserver.trim(),
},
),
},
);
} finally {
clearSecrets();
}
},
{
// The account name is kept with the result, so the success message
// reads against what was sent even if the field is edited afterwards.
parse: async (r) => {
const body = (await r.json().catch(() => ({}))) as {
user_id?: string;
};
return { account: sent, userId: body.user_id };
},
);
clearSecrets();
if (!r.ok) {
setResult({ status: "error", problem: await readApiError(r) });
return;
}
const body = (await r.json().catch(() => ({}))) as {
user_id?: string;
};
// The account name is stored with the result, so the success message
// reads against what was sent even if the field is edited afterwards.
setResult({ status: "done", account, userId: body.user_id });
} catch (err) {
clearSecrets();
setResult({ status: "error", problem: { detail: String(err) } });
}
},
);
}
return (
@ -146,7 +145,7 @@ export function LinkMatrixAccountForm({
daemon reads it from there within two minutes — nothing here restarts
anything directly.
</p>
<form class="link-matrix-account-form" onSubmit={submit}>
<FormStack onSubmit={submit}>
<TextField
id="matrix-account-name"
label="account"
@ -216,31 +215,25 @@ export function LinkMatrixAccountForm({
required={mode === "password"}
onInput={setHomeserver}
/>
<Button
variant="primary"
type="submit"
disabled={result.status === "submitting"}
>
{result.status === "submitting" ? "linking…" : "link account"}
<Button variant="primary" type="submit" disabled={submitting}>
{submitting ? "linking…" : "link account"}
</Button>
</form>
{result.status === "done" && (
<Hint tone="ok" class="link-matrix-account-result-ok">
linked <strong>{result.account}</strong> to <strong>{agent}</strong>
{result.userId ? (
<>
{" "}
— logged in as <strong>{result.userId}</strong>
</>
) : null}
</Hint>
)}
{result.status === "error" && (
<ApiErrorPanel
context="failed to link the account"
problem={result.problem}
/>
)}
</FormStack>
<FormResult
state={state}
done={(linked) => (
<>
linked <strong>{linked.account}</strong> to <strong>{agent}</strong>
{linked.userId ? (
<>
{" "}
— logged in as <strong>{linked.userId}</strong>
</>
) : null}
</>
)}
failed="failed to link the account"
/>
</Panel>
);
}

View file

@ -0,0 +1,12 @@
.ui-form-stack {
display: flex;
flex-direction: column;
gap: 0.75em;
margin-top: 1em;
}
.ui-form-stack-start {
align-items: flex-start;
}
.ui-form-stack-stretch {
align-items: stretch;
}

View file

@ -0,0 +1,26 @@
// <FormStack> — a `<form>` whose fields and buttons stack in one column, with
// the gap the forms in dialogs and panels share. The fields keep their own
// width (`align="start"`) or fill the form (`align="stretch"`).
import type { ComponentChildren } from "preact";
import "./FormStack.css";
export function FormStack({
onSubmit,
align = "start",
class: extraClass,
children,
}: {
onSubmit: (e: Event) => void;
align?: "start" | "stretch";
class?: string;
children: ComponentChildren;
}) {
const classes = ["ui-form-stack", `ui-form-stack-${align}`, extraClass]
.filter(Boolean)
.join(" ");
return (
<form class={classes} onSubmit={onSubmit}>
{children}
</form>
);
}

View file

@ -0,0 +1,3 @@
.ui-form-result {
margin-block: 1em;
}

View file

@ -0,0 +1,32 @@
// <FormResult> — what a form says after it sent its request: a success line
// when it is done, the problem panel when it failed, nothing otherwise. The
// success line is a `Hint` in the `ok` tone.
import type { ComponentChildren } from "preact";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { Hint } from "../hint/Hint.js";
import type { SubmitState } from "./submit.js";
import "./FormResult.css";
export function FormResult<T = void>({
state,
done,
failed,
}: {
state: SubmitState<T>;
/** The success line, given what the reply parsed to. */
done: (value: T) => ComponentChildren;
/** What failed, as the panel's heading says it: "failed to link the account". */
failed: string;
}) {
if (state.status === "done") {
return (
<Hint tone="ok" class="ui-form-result">
{done(state.value)}
</Hint>
);
}
if (state.status === "error") {
return <ApiErrorPanel context={failed} problem={state.problem} />;
}
return null;
}

Some files were not shown because too many files have changed in this diff Show more