The best way to control Claude Code, Codex and more from any computer or phone

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