@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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