Open History to see the last commit
1import { DeviceHostUpdates } from "./DeviceHostUpdates";
2import type { DevicePlatform, DeviceServiceState, EnvironmentId } from "@t3tools/contracts";
3import { Check, CircleAlert } from "lucide-react";
4import { AuthSettingsWriteScope } from "@t3tools/contracts";
5import { useAtomMount } from "@effect/atom-react";
6import { msg, T, useGT, useMessages, Var } from "gt-react";
7import { useState } from "react";
8
9import { Button } from "~/components/ui/button";
10import { DialogClose } from "~/components/ui/dialog";
11import { WizardHeader, WizardPanel, WizardSteps, WizardFooter } from "~/components/ui/wizard";
12import { Spinner } from "~/components/ui/spinner";
13import { Switch } from "~/components/ui/switch";
14import { deviceEnvironment, deviceHostProbeAtom, NO_DEVICE_PROBE_ATOM } from "~/state/device";
15import { useAtomCommand } from "~/state/use-atom-command";
16import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
17import { cn } from "~/lib/utils";
18import { m, type MessageResolver } from "~/i18n/messages";
19
20const platformName = (platform: DevicePlatform) => (platform === "ios" ? "iOS" : "Android");
21
22const deviceHubDescription = msg(
23 "Enable this environment to open simulators and emulators, whether they run here or on a remote device host.",
24);
25const agentDeviceDescription = msg(
26 "Allow new agent sessions in this environment to start and control local and remote devices, with required tools set up automatically.",
27);
28
29/** Platforms whose latest listing on a ready host may be missing devices. */
30export const incompleteListings = (
31 status: DeviceServiceState["hostStatuses"][string] | undefined,
32) =>
33 (["ios", "android"] as const).filter(
34 (platform) =>
35 status?.status === "ready" &&
36 (status.incompletePlatforms?.includes(platform) ||
37 (platform === "android" && status.androidDiscoveryIncomplete === true)),
38 );
39
40export const isAndroidDiscoveryUncertain = (state: DeviceServiceState) =>
41 Object.values(state.hostStatuses).some((status) =>
42 incompleteListings(status).includes("android"),
43 );
44
45/**
46 * `hostStatus` only tracks this machine. A machine without simulator tooling never
47 * starts its own hub, so setup and the panel must also count remote device hosts.
48 */
49export function deviceHubReadiness(state: DeviceServiceState) {
50 const statuses = Object.values(state.hostStatuses).map((host) => host.status);
51 const ready = state.hostStatus === "ready" || statuses.includes("ready");
52 const busy =
53 !ready &&
54 [state.hostStatus, ...statuses].some(
55 (status) => status === "installing" || status === "starting",
56 );
57 return { ready, busy };
58}
59
60/** A ready host keeps its devices usable but may still carry a discovery warning. */
61function deviceHostDiagnostics(
62 hosts: ReadonlyArray<Pick<DeviceServiceState["hosts"][number], "id" | "label">>,
63 hostStatuses: DeviceServiceState["hostStatuses"],
64) {
65 return hosts.flatMap((host) => {
66 const status = hostStatuses[host.id];
67 return status?.status === "ready" && status.detail
68 ? [{ hostId: host.id, label: host.label, detail: status.detail }]
69 : [];
70 });
71}
72
73function DeviceHostDiagnostics(props: {
74 readonly hosts: ReadonlyArray<Pick<DeviceServiceState["hosts"][number], "id" | "label">>;
75 readonly hostStatuses: DeviceServiceState["hostStatuses"];
76 readonly className?: string;
77}) {
78 const diagnostics = deviceHostDiagnostics(props.hosts, props.hostStatuses);
79 if (diagnostics.length === 0) return null;
80 return (
81 <div role="status" className={cn("space-y-1 text-xs text-muted-foreground", props.className)}>
82 {diagnostics.map(({ hostId, label, detail }) => (
83 <p key={hostId} className="whitespace-pre-line break-words">
84 <T>
85 <Var>{label}</Var>: <Var>{detail}</Var>
86 </T>
87 </p>
88 ))}
89 </div>
90 );
91}
92
93/** Components pass `useMessages()` so the message follows a language switch. */
94export function platformSetupStatus(
95 state: DeviceServiceState,
96 platform: DevicePlatform,
97 resolve: MessageResolver = m,
98) {
99 const hasDevices = state.devices.some((device) => device.platform === platform);
100 if (platform === "android" && !hasDevices && isAndroidDiscoveryUncertain(state)) {
101 return {
102 ready: false,
103 message: resolve(
104 msg("The Android device list may be incomplete. Check the device host and try again."),
105 ),
106 };
107 }
108 const availabilities = state.hosts.flatMap((host) =>
109 host.platforms
110 .filter((candidate) => candidate.platform === platform)
111 .map((candidate) => ({ ...candidate, host })),
112 );
113 const supportingHosts = availabilities
114 .filter((candidate) => candidate.available)
115 .map((candidate) => candidate.host);
116 if (supportingHosts.length === 0) {
117 return {
118 ready: false,
119 message:
120 availabilities[0]?.reason ??
121 resolve(msg`${{ platform: platformName(platform) }} support was not detected.`),
122 };
123 }
124 const readyHosts = supportingHosts.filter(
125 (host) =>
126 state.hostStatuses[host.id]?.status === "ready" ||
127 (host.kind === "local" && state.hostStatus === "ready"),
128 );
129 if (readyHosts.length > 0 && !hasDevices) {
130 if (
131 readyHosts.some((host) =>
132 state.hostStatuses[host.id]?.incompletePlatforms?.includes(platform),
133 )
134 ) {
135 return {
136 ready: false,
137 message: resolve(
138 msg`No ${{ platform: platformName(platform) }} devices were listed because device discovery reported a problem.`,
139 ),
140 };
141 }
142 return {
143 ready: false,
144 message:
145 platform === "ios"
146 ? resolve(
147 msg(
148 "Xcode is installed, but no iOS Simulator is available. Install a runtime in Xcode Settings → Components.",
149 ),
150 )
151 : resolve(
152 msg(
153 "The Android SDK is installed, but no Android device was found. Connect a phone with USB debugging on, or create a virtual device in Android Studio → Device Manager.",
154 ),
155 ),
156 };
157 }
158 const remoteHost = supportingHosts.every((host) => host.kind !== "local")
159 ? supportingHosts[0]
160 : undefined;
161 const host = remoteHost?.label;
162 return {
163 ready: true,
164 message:
165 remoteHost?.kind === "eas"
166 ? platform === "ios"
167 ? resolve(msg`${{ host }} starts iOS Simulators in the cloud with Expo Simulators.`)
168 : resolve(msg`${{ host }} starts Android emulators in the cloud with Expo Simulators.`)
169 : platform === "ios"
170 ? host
171 ? resolve(msg`Xcode and iOS Simulator are available on ${{ host }}.`)
172 : resolve(msg("Xcode and iOS Simulator are available."))
173 : host
174 ? resolve(msg`The Android SDK and Emulator are available on ${{ host }}.`)
175 : resolve(msg("The Android SDK is available.")),
176 };
177}
178
179export function DeviceSetup(props: {
180 readonly environmentId: EnvironmentId;
181 readonly state: DeviceServiceState;
182 readonly onComplete?: () => void;
183}) {
184 const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
185 const gt = useGT();
186 const m = useMessages();
187 const configure = useAtomCommand(deviceEnvironment.configure);
188 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
189 const [pending, setPending] = useState<"hub" | "check" | "agent" | "complete" | null>(null);
190 const [step, setStep] = useState(0);
191 const enabled = props.state.hostStatus !== "disabled";
192 const { ready, busy } = deviceHubReadiness(props.state);
193 const localPlatformsUnavailable = props.state.hosts.some(
194 (host) => host.kind === "local" && !host.platforms.some((platform) => platform.available),
195 );
196
197 useAtomMount(enabled ? deviceHostProbeAtom(props.environmentId) : NO_DEVICE_PROBE_ATOM);
198
199 const update = async (
200 kind: NonNullable<typeof pending>,
201 input: { enabled?: boolean; agentAccessEnabled?: boolean; onboardingCompleted?: boolean },
202 ) => {
203 if (!readEnvironmentScope(props.environmentId, AuthSettingsWriteScope)) return;
204 setPending(kind);
205 const result = await configure({ environmentId: props.environmentId, input });
206 setPending(null);
207 if (kind === "complete" && result._tag === "Success") props.onComplete?.();
208 };
209
210 return (
211 <>
212 <WizardHeader
213 title={gt`Set up devices`}
214 description={gt`Review what runs on this environment before using simulators and emulators.`}
215 >
216 <WizardSteps
217 steps={[gt`Device hub`, gt`Simulators`, gt`Agent access`]}
218 currentStep={step}
219 onStepChange={setStep}
220 isStepDisabled={(requested) => busy || pending !== null || requested > step}
221 />
222 </WizardHeader>
223
224 <WizardPanel>
225 <DeviceHostUpdates state={props.state} environmentId={props.environmentId} />
226 {step === 0 ? (
227 <section className="space-y-3 text-sm">
228 <h3 className="font-medium">
229 <T>Enable the device hub</T>
230 </h3>
231 <div className="flex items-start justify-between gap-4">
232 <p className="text-muted-foreground">{m(deviceHubDescription)}</p>
233 <Switch
234 checked={enabled}
235 disabled={!canConfigure || busy || pending !== null}
236 aria-label={gt`Enable device hub`}
237 onCheckedChange={(checked) =>
238 void update("hub", {
239 enabled: Boolean(checked),
240 ...(checked ? {} : { agentAccessEnabled: false }),
241 })
242 }
243 />
244 </div>
245 <DeviceHubSetupStatus
246 state={props.state}
247 pending={pending === "hub" || (busy && pending !== "agent")}
248 />
249 </section>
250 ) : null}
251
252 {step === 1 || (step === 0 && enabled && localPlatformsUnavailable) ? (
253 <section className={cn("space-y-3 text-sm", step === 0 && "mt-4")}>
254 <h3 className="font-medium">
255 <T>Check simulator support</T>
256 </h3>
257 <DevicePlatformSetup
258 state={props.state}
259 checking={pending === "check"}
260 disabled={!enabled || busy || pending !== null}
261 onCheck={() => {
262 setPending("check");
263 void list({ environmentId: props.environmentId, input: {} }).finally(() =>
264 setPending(null),
265 );
266 }}
267 />
268 </section>
269 ) : null}
270
271 {step === 2 ? (
272 <section className="space-y-3 text-sm">
273 <h3 className="font-medium">
274 <T>Allow agent control</T>
275 </h3>
276 <div className="flex items-start justify-between gap-4">
277 <p className="text-muted-foreground">{m(agentDeviceDescription)}</p>
278 <Switch
279 checked={props.state.agentAccessEnabled}
280 disabled={!canConfigure || !enabled || busy || pending !== null}
281 aria-label={gt`Allow agents to control devices`}
282 onCheckedChange={(checked) =>
283 void update("agent", { agentAccessEnabled: Boolean(checked) })
284 }
285 />
286 </div>
287 <AgentDeviceSetupStatus state={props.state} pending={pending === "agent"} />
288 <p className="text-xs text-muted-foreground">
289 <T>Leave this off to keep manual device controls without giving agents access.</T>
290 </p>
291 </section>
292 ) : null}
293 {props.state.hostStatus === "failed" && props.state.hostStatusDetail ? (
294 <p role="alert" className="mt-3 text-xs text-destructive">
295 {props.state.hostStatusDetail}
296 </p>
297 ) : null}
298 </WizardPanel>
299
300 <WizardFooter>
301 {step === 0 ? (
302 <DialogClose render={<Button variant="outline" />}>
303 <T>Cancel</T>
304 </DialogClose>
305 ) : (
306 <Button
307 variant="outline"
308 disabled={busy || pending !== null}
309 onClick={() => setStep(step - 1)}
310 >
311 <T>Back</T>
312 </Button>
313 )}
314 {step < 2 ? (
315 <Button disabled={!ready || pending !== null} onClick={() => setStep(step + 1)}>
316 <T>Continue</T>
317 </Button>
318 ) : (
319 <Button
320 disabled={!canConfigure || !ready || pending !== null}
321 onClick={() => void update("complete", { onboardingCompleted: true })}
322 >
323 {pending === "complete" ? gt`Saving…` : gt`Done`}
324 </Button>
325 )}
326 </WizardFooter>
327 </>
328 );
329}
330
331export function DeviceHubSetupStatus({
332 state,
333 pending,
334 compact = false,
335}: {
336 readonly state: DeviceServiceState;
337 readonly pending: boolean;
338 readonly compact?: boolean;
339}) {
340 const gt = useGT();
341 if (!pending && !deviceHubReadiness(state).ready) return null;
342 return (
343 <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground">
344 {pending ? <Spinner size="xs" /> : <Check className="size-3 text-success" />}
345 {pending
346 ? state.hostStatus === "installing"
347 ? compact
348 ? gt`Installing…`
349 : gt`Installing device hub…`
350 : state.hostStatus === "starting"
351 ? compact
352 ? gt`Starting…`
353 : gt`Starting device hub…`
354 : compact
355 ? gt`Updating…`
356 : gt`Updating device hub…`
357 : gt`Device hub is ready.`}
358 </p>
359 );
360}
361
362function DevicePlatformSetup(props: {
363 readonly state: DeviceServiceState;
364 readonly checking: boolean;
365 readonly disabled: boolean;
366 readonly onCheck: () => void;
367}) {
368 const gt = useGT();
369 const m = useMessages();
370 return (
371 <div className="space-y-3">
372 <PlatformStatus platform="iOS" status={platformSetupStatus(props.state, "ios", m)} />
373 <PlatformStatus platform="Android" status={platformSetupStatus(props.state, "android", m)} />
374 <DeviceHostDiagnostics hosts={props.state.hosts} hostStatuses={props.state.hostStatuses} />
375 <p className="text-xs text-muted-foreground">
376 <T>You can use either platform. Fixing a missing platform does not block the other one.</T>
377 </p>
378 <Button size="compact" variant="outline" disabled={props.disabled} onClick={props.onCheck}>
379 {props.checking ? <Spinner size="xs" /> : null}
380 {props.checking ? gt`Checking…` : gt`Check again`}
381 </Button>
382 </div>
383 );
384}
385
386export function AgentDeviceSetupStatus(props: {
387 readonly state: DeviceServiceState;
388 readonly pending: boolean;
389 readonly compact?: boolean;
390}) {
391 const gt = useGT();
392 if (props.pending) {
393 const label =
394 props.state.hostStatus === "installing"
395 ? props.compact
396 ? gt`Installing…`
397 : gt`Installing agent tools…`
398 : props.state.hostStatus === "starting"
399 ? props.compact
400 ? gt`Starting…`
401 : gt`Starting agent tools…`
402 : props.compact
403 ? gt`Updating…`
404 : gt`Updating agent access…`;
405 return (
406 <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground">
407 <Spinner size="xs" />
408 {label}
409 </p>
410 );
411 }
412 if (
413 props.state.agentAccessEnabled &&
414 deviceHubReadiness(props.state).ready &&
415 props.state.hosts.some((host) => host.agentDeviceInstalled)
416 ) {
417 return (
418 <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground">
419 <Check className="size-3 text-success" />
420 <T>Agent tools are ready.</T>
421 </p>
422 );
423 }
424 return null;
425}
426
427function PlatformStatus(props: {
428 readonly platform: string;
429 readonly status: { readonly ready: boolean; readonly message: string };
430 readonly compact?: boolean;
431}) {
432 const gt = useGT();
433 return (
434 <div
435 className={cn("flex gap-2", !props.compact && "rounded-md border border-border/60 px-3 py-2")}
436 >
437 {props.status.ready ? (
438 <Check className="mt-0.5 size-4 shrink-0 text-success" />
439 ) : (
440 <CircleAlert className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
441 )}
442 <div className={cn(props.compact && props.status.ready && "flex items-center gap-2")}>
443 <p className="font-medium">{props.platform}</p>
444 <p className="text-xs text-muted-foreground">
445 {props.compact && props.status.ready
446 ? gt({ context: "platform status" })`Ready`
447 : props.status.message}
448 </p>
449 </div>
450 </div>
451 );
452}