Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SimlockDeviceHostEditor.tsx

358 lines13.0 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useId, useState, type ReactNode } from "react";
3import {
4 isSecretReference,
5 type EnvironmentId,
6 type SettingsSecretValue,
7 type SimlockDeviceHostConfig,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Option from "effect/Option";
11import { AsyncResult, Atom } from "effect/reactivity";
12import { XIcon } from "lucide-react";
13​
14import { deviceSimlockIdentityCheck } from "../../state/device";
15import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
16​
17import { Button } from "../ui/button";
18import {
19 Dialog,
20 DialogDescription,
21 DialogFooter,
22 DialogHeader,
23 DialogPanel,
24 DialogPopup,
25 DialogTitle,
26} from "../ui/dialog";
27import { Input } from "../ui/input";
28import { Spinner } from "../ui/spinner";
29import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
30import {
31 planSimlockDeviceHostSave,
32 simlockDeviceHostProblem,
33 type SimlockHostEnvironment,
34 type SimlockTokenEntry,
35} from "./simlockDeviceHostsSettings.logic";
36​
37const failureMessage = (cause: Cause.Cause<unknown>) => {
38 const error = Cause.squash(cause);
39 return error instanceof Error ? error.message : String(error);
40};
41​
42/** The gateway each environment's own agent-device points at, if any. */
43const machineGatewaysAtom = environmentAtomList("web-simlock-machine-gateways", (environmentId) =>
44 deviceSimlockIdentityCheck({ environmentId, input: {} }),
45);
46​
47const NO_CHECK = Atom.make(AsyncResult.initial()).pipe(Atom.withLabel("simlock-identity:none"));
48​
49/** Shared fields once, then one agent token per environment: Simlock counts leases per token. */
50export function SimlockDeviceHostEditor(props: {
51 host: SimlockDeviceHostConfig;
52 isNew: boolean;
53 environments: ReadonlyArray<SimlockHostEnvironment>;
54 busy: boolean;
55 onSave: (
56 host: SimlockDeviceHostConfig,
57 tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>,
58 ) => void;
59 onClose: () => void;
60}) {
61 const [draft, setDraft] = useState(props.host);
62 const [urlEdited, setUrlEdited] = useState(false);
63 const machineGateways = useAtomValue(
64 machineGatewaysAtom(
65 environmentIdsKey(
66 props.isNew ? props.environments.map((environment) => environment.environmentId) : [],
67 ),
68 ),
69 );
70 // A new host starts at the gateway an environment's agent-device already uses.
71 const detectedUrl = machineGateways
72 .map((result) => Option.getOrUndefined(AsyncResult.value(result))?.gatewayUrl)
73 .find(Boolean);
74 const gatewayUrl = urlEdited || draft.gatewayUrl ? draft.gatewayUrl : (detectedUrl ?? "");
75 const savedValue = (environment: SimlockHostEnvironment) =>
76 environment.hosts.find((host) => host.id === props.host.id)?.agentToken ?? "";
77 const savedToken = (environment: SimlockHostEnvironment) => savedValue(environment) !== "";
78 const [tokens, setTokens] = useState<ReadonlyMap<EnvironmentId, SimlockTokenEntry>>(
79 () =>
80 new Map(
81 props.environments.map((environment) => [
82 environment.environmentId,
83 savedToken(environment) ? { kind: "saved" } : { kind: "cleared" },
84 ]),
85 ),
86 );
87 const next: SimlockDeviceHostConfig = {
88 ...draft,
89 label: draft.label.trim(),
90 gatewayUrl: gatewayUrl.trim(),
91 };
92 const checkUrl = simlockDeviceHostProblem(next) === null ? next.gatewayUrl : null;
93 // Environments whose token field holds a secret reference that cannot be saved yet.
94 const [invalidTokens, setInvalidTokens] = useState<ReadonlySet<EnvironmentId>>(new Set());
95 const plan = planSimlockDeviceHostSave(props.environments, next, tokens);
96 const problem =
97 "problem" in plan
98 ? plan.problem
99 : invalidTokens.size > 0
100 ? "Enter a valid secret reference."
101 : null;
102 const several = props.environments.length > 1;
103​
104 const limit = (
105 field: "maxLeases" | "maxLeaseMinutes",
106 label: string,
107 min: number,
108 max: number,
109 ) => (
110 <label className="block space-y-1.5">
111 <span>{label}</span>
112 <Input
113 type="number"
114 min={min}
115 max={max}
116 value={draft[field]}
117 disabled={props.busy}
118 onChange={(event) => {
119 const value = Number(event.target.value);
120 setDraft((current) => ({ ...current, [field]: value }));
121 }}
122 />
123 </label>
124 );
125​
126 return (
127 <Dialog
128 open
129 onOpenChange={(open) => {
130 if (!open && !props.busy) props.onClose();
131 }}
132 >
133 <DialogPopup showCloseButton={!props.busy}>
134 <form
135 className="flex min-h-0 flex-col"
136 onSubmit={(event) => {
137 event.preventDefault();
138 if (problem === null && !props.busy) props.onSave(next, tokens);
139 }}
140 >
141 <DialogHeader>
142 <DialogTitle>{props.isNew ? "Add Simlock host" : "Edit Simlock host"}</DialogTitle>
143 <DialogDescription>
144 {several
145 ? "Each selected environment's server leases devices from your Simlock gateway with its own agent token, and releases them when they close."
146 : "The environment's server leases devices from your Simlock gateway and releases them when they close."}
147 </DialogDescription>
148 </DialogHeader>
149 <DialogPanel>
150 <label className="block space-y-1.5 text-sm">
151 <span>Name</span>
152 <Input
153 autoFocus
154 required
155 value={draft.label}
156 disabled={props.busy}
157 onChange={(event) => {
158 const label = event.target.value;
159 setDraft((current) => ({ ...current, label }));
160 }}
161 />
162 </label>
163 <label className="block space-y-1.5 text-sm">
164 <span>Gateway URL</span>
165 <Input
166 required
167 type="url"
168 placeholder="https://gateway.example.ts.net:4700"
169 value={gatewayUrl}
170 disabled={props.busy}
171 onChange={(event) => {
172 const gatewayUrl = event.target.value;
173 setUrlEdited(true);
174 setDraft((current) => ({ ...current, gatewayUrl }));
175 }}
176 />
177 </label>
178 <div className="space-y-3">
179 {props.environments.map((environment) => (
180 <SimlockTokenField
181 key={environment.environmentId}
182 environmentId={environment.environmentId}
183 hostId={props.isNew ? null : props.host.id}
184 gatewayUrl={checkUrl}
185 label={several ? `Agent token · ${environment.label}` : "Agent token"}
186 token={tokens.get(environment.environmentId) ?? { kind: "cleared" }}
187 saved={savedValue(environment)}
188 busy={props.busy}
189 onChange={(token) =>
190 setTokens((current) => new Map(current).set(environment.environmentId, token))
191 }
192 onValidityChange={(valid) =>
193 setInvalidTokens((current) => {
194 const nextInvalid = new Set(current);
195 if (valid) nextInvalid.delete(environment.environmentId);
196 else nextInvalid.add(environment.environmentId);
197 return nextInvalid;
198 })
199 }
200 />
201 ))}
202 <p className="text-xs text-muted-foreground">
203 Leases, drives, and streams devices. Create one{several ? " per environment" : ""}{" "}
204 with <code>simlock --gateway token create --role agent</code>, or leave it blank to
205 add it later. A blank token uses the machine's{" "}
206 <code>AGENT_DEVICE_DAEMON_AUTH_TOKEN</code> when its{" "}
207 <code>AGENT_DEVICE_DAEMON_BASE_URL</code> is this gateway.
208 </p>
209 </div>
210 <div className="grid grid-cols-2 gap-3 text-sm">
211 {limit("maxLeases", "Devices at once", 1, 20)}
212 {limit("maxLeaseMinutes", "Lease minutes", 5, 240)}
213 </div>
214 <p className="text-xs text-muted-foreground">
215 A lease ends after the lease minutes even while in use.
216 {props.isNew ? null : " Saving restarts this host, which releases its devices."}
217 </p>
218 {problem === null || !gatewayUrl ? null : (
219 <p className="text-xs text-destructive" role="alert">
220 {problem}
221 </p>
222 )}
223 </DialogPanel>
224 <DialogFooter>
225 <Button type="button" variant="ghost" disabled={props.busy} onClick={props.onClose}>
226 Cancel
227 </Button>
228 <Button type="submit" disabled={props.busy || problem !== null}>
229 {props.busy ? <Spinner size="xs" /> : null} Save host
230 </Button>
231 </DialogFooter>
232 </form>
233 </DialogPopup>
234 </Dialog>
235 );
237​
238function SimlockTokenField(props: {
239 environmentId: EnvironmentId;
240 hostId: string | null;
241 gatewayUrl: string | null;
242 label: ReactNode;
243 token: SimlockTokenEntry;
244 /** This environment's saved token: redacted when a literal, shown when a secret reference. */
245 saved: SettingsSecretValue;
246 busy: boolean;
247 onChange: (token: SimlockTokenEntry) => void;
248 onValidityChange: (valid: boolean) => void;
249}) {
250 const id = useId();
251 const sources = useSecretSources(props.environmentId);
252 const [inputKey, setInputKey] = useState(0);
253 // Emptying the field or leaving a reference returns to a saved literal, never to a saved reference.
254 const savedLiteral = typeof props.saved === "string" && props.saved !== "";
255 const entered =
256 props.token.kind !== "new"
257 ? ""
258 : typeof props.token.value === "string"
259 ? props.token.value.trim()
260 : props.token.value;
261 // A cleared field asks about the machine's own token, which a blank one falls back to.
262 const check = useAtomValue(
263 props.gatewayUrl === null
264 ? NO_CHECK
265 : deviceSimlockIdentityCheck({
266 environmentId: props.environmentId,
267 input: {
268 gatewayUrl: props.gatewayUrl,
269 ...(entered
270 ? { agentToken: entered }
271 : props.token.kind === "saved" && props.hostId !== null
272 ? { hostId: props.hostId }
273 : {}),
274 },
275 }),
276 );
277 const identity = AsyncResult.isSuccess(check) ? check.value : null;
278 const status =
279 props.gatewayUrl === null ? null : check._tag === "Initial" || check.waiting ? (
280 <span className="text-muted-foreground">Checking…</span>
281 ) : identity ? (
282 <span className="text-muted-foreground">
283 {identity.tokenSource === "env"
284 ? `Using this machine's agent-device token (${identity.signedInAs}).`
285 : `Accepted as ${identity.signedInAs}.`}
286 </span>
287 ) : AsyncResult.isFailure(check) ? (
288 <span
289 className={props.token.kind === "cleared" ? "text-muted-foreground" : "text-destructive"}
290 >
291 {failureMessage(check.cause)}
292 </span>
293 ) : null;
294 return (
295 <div className="space-y-1.5 text-sm">
296 <label htmlFor={id} className="block">
297 {props.label}
298 </label>
299 <div className="flex items-center gap-2">
300 <SecretSourceInput
301 key={inputKey}
302 id={id}
303 aria-label="Agent token"
304 environmentId={props.environmentId}
305 className="min-w-0 flex-1"
306 configured={props.token.kind === "saved" && typeof props.saved === "string"}
307 value={
308 props.token.kind === "new"
309 ? props.token.value
310 : props.token.kind === "saved" && isSecretReference(props.saved)
311 ? props.saved
312 : ""
313 }
314 sources={sources}
315 onValidityChange={props.onValidityChange}
316 onSecretChange={(secret) =>
317 props.onChange(
318 secret
319 ? { kind: "new", value: secret }
320 : savedLiteral
321 ? { kind: "saved" }
322 : { kind: "cleared" },
323 )
324 }
325 disabled={props.busy}
326 onChange={(event) => {
327 const value = event.target.value;
328 // Emptying the field is not clearing the saved token; the Clear button is.
329 props.onChange(
330 value
331 ? { kind: "new", value }
332 : savedLiteral
333 ? { kind: "saved" }
334 : { kind: "cleared" },
335 );
336 }}
337 />
338 {props.token.kind !== "cleared" ? (
339 <Button
340 type="button"
341 size="icon-sm"
342 variant="ghost-destructive"
343 aria-label="Clear agent token"
344 disabled={props.busy}
345 onClick={() => {
346 props.onChange({ kind: "cleared" });
347 props.onValidityChange(true);
348 setInputKey((key) => key + 1);
349 }}
350 >
351 <XIcon className="size-3.5" />
352 </Button>
353 ) : null}
354 </div>
355 {status ? <p className="text-xs">{status}</p> : null}
356 </div>
357 );