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:
parent
0e10473e6f
commit
811b23cd6b
7 changed files with 517 additions and 377 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue