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

DeviceSetup.tsx

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