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

EasDeviceHostsSettings.tsx

435 lines16.5 KB

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