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

DeviceSetup.tsx

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