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

DeviceSetup.tsx

408 lines15.0 KB

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