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