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

DeviceSetup.tsx

387 lines14.3 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. */
47export function 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 platform === "ios"
121 ? `Xcode and iOS Simulator are available${location}.`
122 : `The Android SDK and Emulator are available${location}.`,
123 };
125​
126export function DeviceSetup(props: {
127 readonly environmentId: EnvironmentId;
128 readonly state: DeviceServiceState;
129 readonly onComplete?: () => void;
130}) {
131 const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
132 const configure = useAtomCommand(deviceEnvironment.configure);
133 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
134 const [pending, setPending] = useState<"hub" | "check" | "agent" | "complete" | null>(null);
135 const [step, setStep] = useState(0);
136 const enabled = props.state.hostStatus !== "disabled";
137 const { ready, busy } = deviceHubReadiness(props.state);
138 const localPlatformsUnavailable = props.state.hosts.some(
139 (host) => host.kind === "local" && !host.platforms.some((platform) => platform.available),
140 );
141​
142 // Remote hosts report platforms only after a probe, like the Device panel's refresh on open.
143 useEffect(() => {
144 if (enabled) void list({ environmentId: props.environmentId, input: {} });
145 }, [enabled, list, props.environmentId]);
146​
147 const update = async (
148 kind: NonNullable<typeof pending>,
149 input: { enabled?: boolean; agentAccessEnabled?: boolean; onboardingCompleted?: boolean },
150 ) => {
151 if (!readEnvironmentScope(props.environmentId, AuthSettingsWriteScope)) return;
152 setPending(kind);
153 const result = await configure({ environmentId: props.environmentId, input });
154 setPending(null);
155 if (kind === "complete" && result._tag === "Success") props.onComplete?.();
156 };
157​
158 return (
159 <>
160 <WizardHeader
161 title="Set up devices"
162 description="Review what runs on this environment before using simulators and emulators."
163 >
164 <WizardSteps
165 steps={["Device hub", "Simulators", "Agent access"]}
166 currentStep={step}
167 onStepChange={setStep}
168 isStepDisabled={(requested) => busy || pending !== null || requested > step}
169 />
170 </WizardHeader>
171​
172 <WizardPanel>
173 <DeviceHostUpdates state={props.state} environmentId={props.environmentId} />
174 {step === 0 ? (
175 <section className="space-y-3 text-sm">
176 <h3 className="font-medium">Enable the device hub</h3>
177 <div className="flex items-start justify-between gap-4">
178 <p className="text-muted-foreground">{deviceHubDescription}</p>
179 <Switch
180 checked={enabled}
181 disabled={!canConfigure || busy || pending !== null}
182 aria-label="Enable device hub"
183 onCheckedChange={(checked) =>
184 void update("hub", {
185 enabled: Boolean(checked),
186 ...(checked ? {} : { agentAccessEnabled: false }),
187 })
188 }
189 />
190 </div>
191 <DeviceHubSetupStatus
192 state={props.state}
193 pending={pending === "hub" || (busy && pending !== "agent")}
194 />
195 </section>
196 ) : null}
197​
198 {step === 1 || (step === 0 && enabled && localPlatformsUnavailable) ? (
199 <section className={cn("space-y-3 text-sm", step === 0 && "mt-4")}>
200 <h3 className="font-medium">Check simulator support</h3>
201 <DevicePlatformSetup
202 state={props.state}
203 checking={pending === "check"}
204 disabled={!enabled || busy || pending !== null}
205 onCheck={() => {
206 setPending("check");
207 void list({ environmentId: props.environmentId, input: {} }).finally(() =>
208 setPending(null),
209 );
210 }}
211 />
212 </section>
213 ) : null}
214​
215 {step === 2 ? (
216 <section className="space-y-3 text-sm">
217 <h3 className="font-medium">Allow agent control</h3>
218 <div className="flex items-start justify-between gap-4">
219 <p className="text-muted-foreground">{agentDeviceDescription}</p>
220 <Switch
221 checked={props.state.agentAccessEnabled}
222 disabled={!canConfigure || !enabled || busy || pending !== null}
223 aria-label="Allow agents to control devices"
224 onCheckedChange={(checked) =>
225 void update("agent", { agentAccessEnabled: Boolean(checked) })
226 }
227 />
228 </div>
229 <AgentDeviceSetupStatus state={props.state} pending={pending === "agent"} />
230 <p className="text-xs text-muted-foreground">
231 Leave this off to keep manual device controls without giving agents access.
232 </p>
233 </section>
234 ) : null}
235 {props.state.hostStatus === "failed" && props.state.hostStatusDetail ? (
236 <p role="alert" className="mt-3 text-xs text-destructive">
237 {props.state.hostStatusDetail}
238 </p>
239 ) : null}
240 </WizardPanel>
241​
242 <WizardFooter>
243 {step === 0 ? (
244 <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
245 ) : (
246 <Button
247 variant="outline"
248 disabled={busy || pending !== null}
249 onClick={() => setStep(step - 1)}
250 >
251 Back
252 </Button>
253 )}
254 {step < 2 ? (
255 <Button disabled={!ready || pending !== null} onClick={() => setStep(step + 1)}>
256 Continue
257 </Button>
258 ) : (
259 <Button
260 disabled={!canConfigure || !ready || pending !== null}
261 onClick={() => void update("complete", { onboardingCompleted: true })}
262 >
263 {pending === "complete" ? "Saving…" : "Done"}
264 </Button>
265 )}
266 </WizardFooter>
267 </>
268 );
270​
271export function DeviceHubSetupStatus({
272 state,
273 pending,
274 compact = false,
275}: {
276 readonly state: DeviceServiceState;
277 readonly pending: boolean;
278 readonly compact?: boolean;
279}) {
280 if (!pending && !deviceHubReadiness(state).ready) return null;
281 return (
282 <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground">
283 {pending ? <Spinner size="xs" /> : <Check className="size-3 text-success" />}
284 {pending
285 ? state.hostStatus === "installing"
286 ? compact
287 ? "Installing…"
288 : "Installing device hub…"
289 : state.hostStatus === "starting"
290 ? compact
291 ? "Starting…"
292 : "Starting device hub…"
293 : compact
294 ? "Updating…"
295 : "Updating device hub…"
296 : "Device hub is ready."}
297 </p>
298 );
300​
301function DevicePlatformSetup(props: {
302 readonly state: DeviceServiceState;
303 readonly checking: boolean;
304 readonly disabled: boolean;
305 readonly onCheck: () => void;
306}) {
307 return (
308 <div className="space-y-3">
309 <PlatformStatus platform="iOS" status={platformSetupStatus(props.state, "ios")} />
310 <PlatformStatus platform="Android" status={platformSetupStatus(props.state, "android")} />
311 <DeviceHostDiagnostics hosts={props.state.hosts} hostStatuses={props.state.hostStatuses} />
312 <p className="text-xs text-muted-foreground">
313 You can use either platform. Fixing a missing platform does not block the other one.
314 </p>
315 <Button size="compact" variant="outline" disabled={props.disabled} onClick={props.onCheck}>
316 {props.checking ? <Spinner size="xs" /> : null}
317 {props.checking ? "Checking…" : "Check again"}
318 </Button>
319 </div>
320 );
322​
323export function AgentDeviceSetupStatus(props: {
324 readonly state: DeviceServiceState;
325 readonly pending: boolean;
326 readonly compact?: boolean;
327}) {
328 if (props.pending) {
329 const label =
330 props.state.hostStatus === "installing"
331 ? props.compact
332 ? "Installing…"
333 : "Installing agent tools…"
334 : props.state.hostStatus === "starting"
335 ? props.compact
336 ? "Starting…"
337 : "Starting agent tools…"
338 : props.compact
339 ? "Updating…"
340 : "Updating agent access…";
341 return (
342 <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground">
343 <Spinner size="xs" />
344 {label}
345 </p>
346 );
347 }
348 if (
349 props.state.agentAccessEnabled &&
350 deviceHubReadiness(props.state).ready &&
351 props.state.hosts.some((host) => host.agentDeviceInstalled)
352 ) {
353 return (
354 <p role="status" className="flex items-center gap-2 text-xs text-muted-foreground">
355 <Check className="size-3 text-success" />
356 Agent tools are ready.
357 </p>
358 );
359 }
360 return null;
362​
363export function PlatformStatus(props: {
364 readonly platform: string;
365 readonly status: { readonly ready: boolean; readonly message: string };
366 readonly compact?: boolean;
367}) {
368 return (
369 <div
370 className={cn("flex gap-2", !props.compact && "rounded-md border border-border/60 px-3 py-2")}
371 >
372 <MorphIcon
373 className={cn(
374 "mt-0.5 size-4 shrink-0",
375 props.status.ready ? "text-success" : "text-muted-foreground",
376 )}
377 icon={props.status.ready ? CheckGlyph : CircleAlert}
378 />
379 <div className={cn(props.compact && props.status.ready && "flex items-center gap-2")}>
380 <p className="font-medium">{props.platform}</p>
381 <p className="text-xs text-muted-foreground">
382 {props.compact && props.status.ready ? "Ready" : props.status.message}
383 </p>
384 </div>
385 </div>
386 );