Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m as resolveMessage } from "~/i18n/messages";
3import { useAtomValue } from "@effect/atom-react";
4import { msg, T, useGT, useMessages, type Msg } from "gt-react";
5import { useId, useRef, useState } from "react";
6import * as Cause from "effect/Cause";
7import * as Option from "effect/Option";
8import {
9 isSecretReference,
10 type DeviceEasAccount,
11 type EasDeviceHostConfig,
12 type EnvironmentId,
13 type SettingsSecretValue,
14} from "@t3tools/contracts";
15import { XIcon } from "lucide-react";
16
17import { deviceEasAccountCheck, deviceEnvironment } from "../../state/device";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { Button } from "../ui/button";
20import {
21 Dialog,
22 DialogDescription,
23 DialogFooter,
24 DialogHeader,
25 DialogPanel,
26 DialogPopup,
27 DialogTitle,
28} from "../ui/dialog";
29import { Input } from "../ui/input";
30import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
31import { Spinner } from "../ui/spinner";
32import { parseEasDeviceHostDraft } from "./easDeviceHostsSettings.logic";
33import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
34
35const FROM_THREAD_PROJECT = "thread-project";
36
37const SIGNED_IN_MESSAGES: Record<
38 DeviceEasAccount["credentialSource"],
39 (values: { account: string }) => string | Msg
40> = {
41 settings: ({ account }: { account: string }) =>
42 msg`Signed in as ${{ account }} with the access token saved here.`,
43 env: ({ account }: { account: string }) =>
44 msg`Signed in as ${{ account }} with EXPO_TOKEN on the server.`,
45 "eas-login": ({ account }: { account: string }) =>
46 msg`Signed in as ${{ account }} with the server's eas login.`,
47};
48
49const failureMessage = (cause: Cause.Cause<unknown>) => {
50 const error = Cause.squash(cause);
51 return error instanceof Error
52 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
53 : String(error);
54};
55
56type AccountCheck =
57 | { status: "idle" }
58 | { status: "checking" }
59 | { status: "signed-in"; account: DeviceEasAccount }
60 | { status: "failed"; error: string };
61
62export function EasDeviceHostEditor(props: {
63 environmentId: EnvironmentId;
64 host: EasDeviceHostConfig;
65 isNew: boolean;
66 busy: boolean;
67 onSave: (host: EasDeviceHostConfig) => void;
68 onClose: () => void;
69}) {
70 const gt = useGT();
71 const m = useMessages();
72 const check = useAtomCommand(deviceEnvironment.easAccount, { reportFailure: false });
73 const [draft, setDraft] = useState(props.host);
74 const tokenId = useId();
75 const secretSources = useSecretSources(props.environmentId);
76 const [tokenValid, setTokenValid] = useState(true);
77 const [tokenInputKey, setTokenInputKey] = useState(0);
78 // A saved token arrives redacted; only a replacement or a clear changes it.
79 const [token, setToken] = useState<
80 { kind: "saved" } | { kind: "new"; value: SettingsSecretValue } | { kind: "cleared" }
81 >(props.host.accessToken ? { kind: "saved" } : { kind: "cleared" });
82 // Checking on open names the saved project and shows a rejected credential
83 // before anything is changed. A manual check or a token edit replaces it.
84 const openCheck = useAtomValue(
85 deviceEasAccountCheck({
86 environmentId: props.environmentId,
87 input: props.host.accessToken
88 ? props.isNew
89 ? {}
90 : { hostId: props.host.id }
91 : { accessToken: "" },
92 }),
93 );
94 const [checked, setAccount] = useState<AccountCheck | null>(null);
95 const account: AccountCheck =
96 checked ??
97 (openCheck._tag === "Initial" || openCheck.waiting
98 ? { status: "checking" }
99 : openCheck._tag === "Success"
100 ? { status: "signed-in", account: openCheck.value }
101 : { status: "failed", error: failureMessage(openCheck.cause) });
102 const next: EasDeviceHostConfig = {
103 ...draft,
104 label: draft.label.trim(),
105 accessToken:
106 token.kind === "saved" ? props.host.accessToken : token.kind === "new" ? token.value : "",
107 };
108 const valid = tokenValid && Option.isSome(parseEasDeviceHostDraft(next));
109 // Why Save is off, for the limits the fields' ranges do not show.
110 const problem = valid
111 ? null
112 : !tokenValid
113 ? gt`Enter a valid secret reference.`
114 : draft.maxSessionMinutes > 0 && draft.idleMinutes >= draft.maxSessionMinutes
115 ? gt`Idle minutes must be smaller than session minutes.`
116 : gt`Give the host a label and limits within the ranges shown.`;
117 const apps = account.status === "signed-in" ? account.account.apps : [];
118
119 // A check answers for the credential it was asked about: a later check or a
120 // token edit makes an earlier answer stale.
121 const latestCheck = useRef(0);
122 const resetAccount = () => {
123 latestCheck.current++;
124 setAccount({ status: "idle" });
125 };
126 const requestCheck = async () => {
127 const run = ++latestCheck.current;
128 const result = await check({
129 environmentId: props.environmentId,
130 input: {
131 ...(token.kind === "saved" && !props.isNew ? { hostId: props.host.id } : {}),
132 // A cleared token is sent as empty, so the check does not fall back to
133 // the saved one that Save is about to drop.
134 ...(token.kind === "new"
135 ? { accessToken: token.value }
136 : token.kind === "cleared"
137 ? { accessToken: "" }
138 : {}),
139 },
140 });
141 if (run !== latestCheck.current) return;
142 setAccount(
143 result._tag === "Success"
144 ? { status: "signed-in", account: result.value }
145 : { status: "failed", error: failureMessage(result.cause) },
146 );
147 };
148 const checkAccount = () => {
149 setAccount({ status: "checking" });
150 void requestCheck();
151 };
152
153 const limit = (
154 field: "maxSessionMinutes" | "idleMinutes" | "maxConcurrentSessions",
155 label: string,
156 max: number,
157 ) => (
158 <label className="block space-y-1.5">
159 <span>{label}</span>
160 <Input
161 type="number"
162 min={1}
163 max={max}
164 value={Number.isNaN(draft[field]) ? "" : draft[field]}
165 disabled={props.busy}
166 onChange={(event) => {
167 const value = event.target.valueAsNumber;
168 setDraft((current) => ({ ...current, [field]: value }));
169 }}
170 />
171 </label>
172 );
173
174 return (
175 <Dialog
176 open
177 onOpenChange={(open) => {
178 if (!open && !props.busy) props.onClose();
179 }}
180 >
181 <DialogPopup showCloseButton={!props.busy}>
182 <form
183 className="flex min-h-0 flex-col"
184 onSubmit={(event) => {
185 event.preventDefault();
186 if (valid && !props.busy) props.onSave(next);
187 }}
188 >
189 <DialogHeader>
190 <DialogTitle>{props.isNew ? gt`Add Expo host` : gt`Edit Expo host`}</DialogTitle>
191 <DialogDescription>
192 <T>
193 The environment's server signs in to Expo and starts the sessions. Without a token
194 here it uses EXPO_TOKEN, then its eas login.
195 </T>
196 </DialogDescription>
197 </DialogHeader>
198 <DialogPanel>
199 <label className="block space-y-1.5 text-sm">
200 <span>
201 <T>Name</T>
202 </span>
203 <Input
204 autoFocus
205 required
206 value={draft.label}
207 disabled={props.busy}
208 onChange={(event) => {
209 const label = event.target.value;
210 setDraft((current) => ({ ...current, label }));
211 }}
212 />
213 </label>
214 <div className="space-y-1.5 text-sm">
215 <label htmlFor={tokenId} className="block">
216 <T>Expo access token</T>
217 </label>
218 <div className="flex items-center gap-2">
219 <SecretSourceInput
220 key={tokenInputKey}
221 id={tokenId}
222 aria-label={gt`Expo access token`}
223 className="min-w-0 flex-1"
224 configured={token.kind === "saved" && typeof props.host.accessToken === "string"}
225 value={
226 token.kind === "new"
227 ? token.value
228 : token.kind === "saved" && isSecretReference(props.host.accessToken)
229 ? props.host.accessToken
230 : ""
231 }
232 sources={secretSources}
233 environmentId={props.environmentId}
234 onValidityChange={(valid) => {
235 setTokenValid(valid);
236 resetAccount();
237 }}
238 onSecretChange={(secret) => {
239 setToken(secret ? { kind: "new", value: secret } : { kind: "cleared" });
240 resetAccount();
241 }}
242 disabled={props.busy}
243 placeholder={gt`Optional`}
244 onChange={(event) => {
245 const value = event.target.value;
246 // Emptying the field is not clearing the saved token; the
247 // Clear button is, so a saved token comes back here.
248 setToken(
249 value
250 ? { kind: "new", value }
251 : props.host.accessToken
252 ? { kind: "saved" }
253 : { kind: "cleared" },
254 );
255 resetAccount();
256 }}
257 />
258 {token.kind !== "cleared" ? (
259 <Button
260 type="button"
261 size="icon-sm"
262 variant="ghost-destructive"
263 aria-label={gt`Clear access token`}
264 onClick={() => {
265 setToken({ kind: "cleared" });
266 setTokenValid(true);
267 setTokenInputKey((key) => key + 1);
268 resetAccount();
269 }}
270 >
271 <XIcon className="size-3.5" />
272 </Button>
273 ) : null}
274 </div>
275 </div>
276 <div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 px-3 py-2.5">
277 <p role="status" className="min-w-0 text-xs text-muted-foreground">
278 {account.status === "signed-in"
279 ? m(
280 SIGNED_IN_MESSAGES[account.account.credentialSource]({
281 account: account.account.signedInAs,
282 }),
283 )
284 : account.status === "failed"
285 ? account.error
286 : account.status === "checking"
287 ? gt`Checking the Expo account…`
288 : gt`Check the Expo account before choosing a project.`}
289 </p>
290 <Button
291 type="button"
292 size="sm"
293 variant="outline"
294 disabled={props.busy || !tokenValid || account.status === "checking"}
295 onClick={() => void checkAccount()}
296 >
297 {account.status === "checking" ? <Spinner size="xs" /> : null} <T>Check account</T>
298 </Button>
299 </div>
300 <div className="space-y-1.5 text-sm">
301 <span>
302 <T>Expo project</T>
303 </span>
304 <Select
305 value={draft.appId ?? FROM_THREAD_PROJECT}
306 disabled={props.busy}
307 onValueChange={(value) => {
308 if (typeof value !== "string") return;
309 setDraft((current) => {
310 const { appId: _, ...rest } = current;
311 return value === FROM_THREAD_PROJECT ? rest : { ...rest, appId: value };
312 });
313 }}
314 >
315 <SelectTrigger size="sm" aria-label={gt`Expo project`}>
316 <SelectValue>
317 {(value: string) =>
318 value === FROM_THREAD_PROJECT
319 ? gt`From the thread's project`
320 : (apps.find((app) => app.id === value)?.fullName ?? value)
321 }
322 </SelectValue>
323 </SelectTrigger>
324 <SelectPopup>
325 <SelectItem value={FROM_THREAD_PROJECT}>
326 <T>From the thread's project</T>
327 </SelectItem>
328 {draft.appId && !apps.some((app) => app.id === draft.appId) ? (
329 <SelectItem value={draft.appId}>{draft.appId}</SelectItem>
330 ) : null}
331 {apps.map((app) => (
332 <SelectItem key={app.id} value={app.id}>
333 {app.fullName}
334 </SelectItem>
335 ))}
336 </SelectPopup>
337 </Select>
338 <p className="text-xs text-muted-foreground">
339 <T>
340 Sessions bill the project's Expo account. "From the thread's project" reads
341 extra.eas.projectId from the project's app config.
342 </T>
343 </p>
344 </div>
345 <div className="grid grid-cols-3 gap-3 text-sm">
346 {limit("maxConcurrentSessions", gt`Sessions at once`, 20)}
347 {limit("maxSessionMinutes", gt`Session minutes`, 115)}
348 {limit("idleMinutes", gt`Idle minutes`, 60)}
349 </div>
350 <p className="text-xs text-muted-foreground">
351 <T>
352 Expo Simulators needs a paid Expo account. A session runs for up to 115 minutes and
353 stops early when it is idle for the idle minutes, so idle minutes must be less than
354 session minutes.
355 </T>
356 {props.isNew ? null : (
357 <>
358 {" "}
359 <T>Saving restarts this host and stops its running sessions.</T>
360 </>
361 )}
362 </p>
363 {problem === null ? null : (
364 <p className="text-xs text-destructive" role="alert">
365 {problem}
366 </p>
367 )}
368 </DialogPanel>
369 <DialogFooter>
370 <Button type="button" variant="ghost" disabled={props.busy} onClick={props.onClose}>
371 <T>Cancel</T>
372 </Button>
373 <Button type="submit" disabled={props.busy || !valid}>
374 {props.busy ? <Spinner size="xs" /> : null} <T>Save host</T>
375 </Button>
376 </DialogFooter>
377 </form>
378 </DialogPopup>
379 </Dialog>
380 );
381}