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