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

DeviceSetup.tsx

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