Open History to see the last commit
1import { DeviceHostUpdates } from "./DeviceHostUpdates";
2import type {
3 DevicePlatform,
4 DeviceServiceState,
5 DeviceSummary,
6 ScopedThreadRef,
7} from "@t3tools/contracts";
8import { ArrowUpRight, CircleAlert, Play, Smartphone, Square, X } from "lucide-react";
9import { useAtomMount } from "@effect/atom-react";
10import { T, useGT, Var } from "gt-react";
11import { type ReactNode, useState } from "react";
12
13import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
14import {
15 selectThreadRightPanelState,
16 useRightPanelStore,
17 type RightPanelSurface,
18} from "~/rightPanelStore";
19import { Button } from "~/components/ui/button";
20import { DiscoveryList } from "~/components/ui/discovery-list";
21import { Dialog } from "~/components/ui/dialog";
22import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
23import { WizardPopup } from "~/components/ui/wizard";
24import { Spinner } from "~/components/ui/spinner";
25import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
26import { cn } from "~/lib/utils";
27import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
28import {
29 deviceEnvironment,
30 deviceHostProbeAtom,
31 NO_DEVICE_PROBE_ATOM,
32 useDeviceState,
33} from "~/state/device";
34import { formatEnvironmentQueryError } from "~/state/query";
35import { useAtomCommand } from "~/state/use-atom-command";
36import { DeviceLoadingView } from "./DeviceLoadingView";
37import {
38 DeviceSetup,
39 deviceHubReadiness,
40 incompleteListings,
41 isAndroidDiscoveryUncertain,
42} from "./DeviceSetup";
43import { DeviceWorkspace } from "./DeviceWorkspace";
44import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
45
46const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
47 `${device.hostId}\u0000${device.id}`;
48
49export function DevicePanel(props: {
50 readonly mode: PreviewPanelMode;
51 readonly threadRef: ScopedThreadRef;
52 readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
53 readonly visible: boolean;
54 readonly onDismissSetup: () => void;
55}) {
56 const { environmentId, threadId } = props.threadRef;
57 const gt = useGT();
58 const { state, loaded, error: stateError, refresh: refreshState } = useDeviceState(environmentId);
59 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
60 const open = useAtomCommand(deviceEnvironment.open);
61 const close = useAtomCommand(deviceEnvironment.close);
62 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
63 // The panel stays mounted across thread switches, so an in-flight open or
64 // power-off is tagged with the thread it belongs to and only shown there.
65 const scope = `${environmentId}\u0000${threadId}`;
66 const [operation, setOperation] = useState<{
67 readonly scope: string;
68 readonly pending: DeviceSummary | null;
69 readonly error: string | null;
70 } | null>(null);
71 const pendingDevice = operation?.scope === scope ? operation.pending : null;
72 const operationError = operation?.scope === scope ? operation.error : null;
73 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
74 // Power-offs act on the environment, not the thread, so they outlive thread switches.
75 const [stopping, setStopping] = useState<ReadonlySet<string>>(() => new Set());
76 const [stopErrors, setStopErrors] = useState<Readonly<Record<string, string>>>({});
77 const stopError = stopErrors[environmentId];
78 const setStopError = (message: string | undefined) =>
79 setStopErrors((current) => {
80 const next = { ...current };
81 if (message === undefined) delete next[environmentId];
82 else next[environmentId] = message;
83 return next;
84 });
85 const stoppingKey = (device: DeviceSummary) => `${environmentId}\u0000${deviceKey(device)}`;
86 const isStopping = (device: DeviceSummary) => stopping.has(stoppingKey(device));
87
88 const hostDisabled = state.hostStatus === "disabled";
89
90 useAtomMount(
91 props.visible && loaded && !hostDisabled
92 ? deviceHostProbeAtom(environmentId)
93 : NO_DEVICE_PROBE_ATOM,
94 );
95
96 const sessions = state.sessions.filter((session) => session.threadId === threadId);
97 const activeSession = props.surface.target
98 ? sessions.find(
99 (session) =>
100 session.deviceId === props.surface.target?.deviceId &&
101 session.hostId === props.surface.target.hostId,
102 )
103 : undefined;
104 const activeDevice = activeSession
105 ? state.devices.find(
106 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
107 )
108 : undefined;
109 const activeHost = activeDevice
110 ? state.hosts.find((host) => host.id === activeDevice.hostId)
111 : undefined;
112
113 const grouped = groupDevices(state);
114 const stoppable = state.devices.filter((device) => device.booted && !device.physical);
115
116 const startOperation = (pending: DeviceSummary | null) => {
117 const started = { scope, pending, error: null };
118 setOperation(started);
119 // Returning to the same thread can start a newer operation before this one settles.
120 return (error: string | null) =>
121 setOperation((current) =>
122 current === started ? { ...started, pending: null, error } : current,
123 );
124 };
125
126 const selectDevice = async (value: string) => {
127 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
128 if (!device) return;
129 const settleOperation = startOperation(device);
130 const result = await open({
131 environmentId,
132 input: {
133 threadId,
134 hostId: device.hostId,
135 deviceId: device.id,
136 platform: device.platform,
137 },
138 });
139 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
140 else {
141 // The server opened the device for the starting thread, so its tab opens there.
142 useRightPanelStore.getState().openDevice(props.threadRef, {
143 hostId: result.value.hostId,
144 deviceId: result.value.deviceId,
145 platform: device.platform,
146 name: device.name,
147 });
148 settleOperation(null);
149 }
150 };
151
152 const stopDevices = async (devices: readonly DeviceSummary[]) => {
153 setStopError(undefined);
154 setStopping((current) => new Set([...current, ...devices.map(stoppingKey)]));
155 const results = await Promise.all(
156 devices.map((device) =>
157 shutdown({
158 environmentId,
159 input: { hostId: device.hostId, deviceId: device.id, platform: device.platform },
160 }).finally(() =>
161 setStopping((current) => {
162 const next = new Set(current);
163 next.delete(stoppingKey(device));
164 return next;
165 }),
166 ),
167 ),
168 );
169 const failure = results.find((result) => result._tag === "Failure");
170 if (failure?._tag === "Failure") setStopError(formatEnvironmentQueryError(failure.cause));
171 };
172
173 const floatActive = () => {
174 if (!activeDevice) return;
175 usePreviewMiniPlayerStore.getState().open(props.threadRef, {
176 kind: "device",
177 hostId: activeDevice.hostId,
178 deviceId: activeDevice.id,
179 platform: activeDevice.platform,
180 name: activeDevice.name,
181 });
182 useRightPanelStore.getState().close(props.threadRef);
183 };
184
185 const closeSurface = () => {
186 const store = useRightPanelStore.getState();
187 const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);
188 store.closeSurface(props.threadRef, props.surface.id);
189 focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);
190 };
191
192 const closeActive = (powerOff: boolean) => {
193 if (!powerOff) {
194 closeSurface();
195 return;
196 }
197 if (!activeSession) return;
198 const settleOperation = startOperation(null);
199 void close({
200 environmentId,
201 input: {
202 threadId,
203 hostId: activeSession.hostId,
204 deviceId: activeSession.deviceId,
205 shutdown: powerOff,
206 },
207 }).then((result) => {
208 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
209 else closeSurface();
210 });
211 };
212
213 const bootingDevices =
214 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
215 const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
216 const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded);
217 // Without a first snapshot a failed subscription never settles on its own.
218 const loadError = loaded ? null : stateError;
219 const diagnostics = state.hosts.flatMap((host) => {
220 const status = state.hostStatuses[host.id];
221 const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined);
222 return detail && (status?.status ?? state.hostStatus) === "ready"
223 ? [
224 {
225 hostId: host.id,
226 label: host.label,
227 detail,
228 incompletePlatforms: incompleteListings(status),
229 },
230 ]
231 : [];
232 });
233 const unavailablePlatforms = state.hosts.flatMap((host) =>
234 host.platforms
235 .filter((platform) => !platform.available)
236 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
237 );
238
239 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
240 return (
241 <Dialog
242 open={props.visible}
243 onOpenChange={(isOpen) => {
244 if (!isOpen) props.onDismissSetup();
245 }}
246 >
247 <WizardPopup>
248 <DeviceSetup environmentId={environmentId} state={state} />
249 </WizardPopup>
250 </Dialog>
251 );
252 }
253
254 return (
255 <PreviewPanelShell mode={props.mode}>
256 <div className="relative flex min-h-0 flex-1 flex-col">
257 <div
258 className={cn(
259 "shrink-0 bg-background",
260 loading && "absolute inset-x-0 top-0 z-10 max-h-[40%] overflow-y-auto",
261 )}
262 >
263 <div hidden={!!activeDevice}>
264 {diagnostics.map((diagnostic) => (
265 <DeviceDiscoveryWarning
266 key={`${environmentId}\u0000${diagnostic.hostId}`}
267 label={diagnostic.label}
268 detail={diagnostic.detail}
269 incompletePlatforms={diagnostic.incompletePlatforms}
270 onRetry={() => list({ environmentId, input: {} })}
271 />
272 ))}
273 </div>
274 <DeviceHostUpdates state={state} environmentId={environmentId} />
275 {bootingDevices.length > 0 ? (
276 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
277 <T>
278 Starting <Var>{bootingDevices.map((device) => device.name).join(", ")}</Var>… This
279 can take a minute.
280 </T>
281 </div>
282 ) : null}
283 {operationError ? (
284 <DeviceNotice onDismiss={() => setOperation(null)}>{operationError}</DeviceNotice>
285 ) : null}
286 {stopError !== undefined ? (
287 <DeviceNotice onDismiss={() => setStopError(undefined)}>{stopError}</DeviceNotice>
288 ) : null}
289 </div>
290 <div className="@container relative flex min-h-0 flex-1">
291 {activeDevice && activeSession ? (
292 <DeviceWorkspace
293 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
294 environmentId={environmentId}
295 device={activeDevice}
296 hostLabel={activeHost?.label ?? gt("Device host")}
297 hostKind={activeHost?.kind}
298 hostDiagnostics={
299 diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
300 }
301 visible={props.visible}
302 onFloat={floatActive}
303 onClose={() => closeActive(false)}
304 onPowerOff={() => closeActive(true)}
305 />
306 ) : loading ? (
307 <DeviceLoadingView
308 name={pendingDevice?.name ?? gt("Devices")}
309 description={
310 pendingDevice
311 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? gt("Device host")} · ${pendingDevice.version}`
312 : ""
313 }
314 stage="opening"
315 message={
316 loadError ??
317 (pendingDevice
318 ? pendingDevice.booted
319 ? gt("Opening device…")
320 : gt("Starting device…")
321 : state.hostStatus === "installing"
322 ? (state.hostStatusDetail ?? gt("Installing device support…"))
323 : gt("Finding devices…"))
324 }
325 error={loadError !== null}
326 >
327 {loadError !== null ? (
328 <Button size="sm" variant="outline" onClick={refreshState}>
329 <T>Retry</T>
330 </Button>
331 ) : null}
332 </DeviceLoadingView>
333 ) : (
334 <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
335 <div
336 className={cn(
337 "mx-auto flex w-full max-w-xl flex-col gap-6",
338 grouped.length === 0 && "my-auto items-center text-center",
339 )}
340 >
341 {grouped.length === 0 ? (
342 <>
343 <Smartphone className="size-6 opacity-60" />
344 <p
345 className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
346 tabIndex={state.hostStatus === "failed" ? 0 : undefined}
347 >
348 {state.hostStatus === "failed"
349 ? (state.hostStatusDetail ?? gt("The device hub failed to start."))
350 : gt("No simulators or emulators were found on this environment.")}
351 </p>
352 </>
353 ) : null}
354 {hostReady && grouped.length > 0 ? (
355 <div className="w-full space-y-6 text-left">
356 {grouped.map((group) => (
357 <section key={group.platform} className="space-y-3">
358 <div className="flex items-center gap-2 text-sm text-muted-foreground">
359 <Smartphone className="size-4 shrink-0" />
360 <h3 className="font-medium">
361 {group.platform === "ios"
362 ? gt("iOS Simulators")
363 : gt("Android Emulators")}
364 </h3>
365 </div>
366 <DiscoveryList>
367 {group.devices.map((device) => (
368 <div
369 key={deviceKey(device)}
370 className="flex items-center gap-3 px-3 py-3"
371 >
372 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
373 <Smartphone className="size-4" />
374 </span>
375 <div className="flex min-w-0 flex-1 flex-col">
376 <span className="truncate text-sm font-medium text-foreground">
377 {device.name}
378 </span>
379 <span className="truncate text-xs text-muted-foreground">
380 {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? gt("Running", { $context: "device state" }) : gt("Stopped", { $context: "device state" })}`}
381 </span>
382 </div>
383 {device.booted && !device.physical ? (
384 <Tooltip>
385 <TooltipTrigger
386 render={
387 <Button
388 variant="outline"
389 size="icon-sm"
390 disabled={
391 isStopping(device) ||
392 pendingDeviceKey === deviceKey(device)
393 }
394 aria-label={gt("Stop {name}", { name: device.name })}
395 onClick={() => void stopDevices([device])}
396 />
397 }
398 >
399 {isStopping(device) ? <Spinner size="xs" /> : <Square />}
400 </TooltipTrigger>
401 <TooltipPopup>
402 {gt("Stop", { $context: "verb, powers off a running device" })}
403 </TooltipPopup>
404 </Tooltip>
405 ) : null}
406 <Button
407 variant="outline"
408 size="sm"
409 disabled={pendingDeviceKey !== null || isStopping(device)}
410 aria-label={
411 device.booted
412 ? gt("Open {name}", { name: device.name })
413 : gt("Start {name}", { name: device.name })
414 }
415 onClick={() => void selectDevice(deviceKey(device))}
416 >
417 {pendingDeviceKey === deviceKey(device) ? (
418 <Spinner size="xs" />
419 ) : device.booted ? (
420 <ArrowUpRight />
421 ) : (
422 <Play />
423 )}
424 {device.booted
425 ? gt("Open", { $context: "verb, opens a running device" })
426 : gt("Start", { $context: "verb, boots a device" })}
427 </Button>
428 </div>
429 ))}
430 </DiscoveryList>
431 </section>
432 ))}
433 </div>
434 ) : null}
435 {hostReady &&
436 !isAndroidDiscoveryUncertain(state) &&
437 !state.devices.some((device) => device.platform === "android") &&
438 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
439 <p className="max-w-sm text-xs">
440 <T>
441 No Android virtual devices found. Create one in Android Studio's Device
442 Manager, then refresh.
443 </T>
444 </p>
445 ) : null}
446 {loaded && !hostBusy ? (
447 <div
448 className={cn(
449 "flex flex-wrap gap-2",
450 grouped.length > 0 ? "self-start" : "self-center",
451 )}
452 >
453 <Button
454 variant="outline"
455 size="sm"
456 onClick={() => void list({ environmentId, input: {} })}
457 >
458 <T>Refresh devices</T>
459 </Button>
460 {stoppable.length > 0 ? (
461 <Button
462 variant="outline"
463 size="sm"
464 disabled={stoppable.every(isStopping)}
465 onClick={() =>
466 void stopDevices(stoppable.filter((device) => !isStopping(device)))
467 }
468 >
469 <T>Stop all devices</T>
470 </Button>
471 ) : null}
472 </div>
473 ) : null}
474 </div>
475 </div>
476 )}
477 </div>
478 </div>
479 </PreviewPanelShell>
480 );
481}
482
483function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) {
484 const gt = useGT();
485 return (
486 <div
487 role="alert"
488 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
489 >
490 <CircleAlert className="mt-1 size-3.5 shrink-0" />
491 <div
492 className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
493 tabIndex={0}
494 >
495 {props.children}
496 </div>
497 <Button
498 size="icon-xs"
499 variant="ghost"
500 aria-label={gt("Dismiss device error")}
501 onClick={props.onDismiss}
502 >
503 <X />
504 </Button>
505 </div>
506 );
507}
508
509function DeviceDiscoveryWarning(props: {
510 readonly label: string;
511 readonly detail: string;
512 readonly incompletePlatforms: readonly DevicePlatform[];
513 readonly onRetry: () => Promise<unknown>;
514}) {
515 const gt = useGT();
516 const [open, setOpen] = useState(false);
517 const [retrying, setRetrying] = useState(false);
518 const [dismissedCause, setDismissedCause] = useState<string | null>(null);
519 const cause = `${props.incompletePlatforms.join()}\u0000${props.detail}`;
520 // A dismissal hides one occurrence; a cause that returns later shows again.
521 if (dismissedCause !== null && dismissedCause !== cause) setDismissedCause(null);
522 if (dismissedCause === cause) return null;
523 const platforms = props.incompletePlatforms.map((platform) =>
524 platform === "ios" ? "iOS" : "Android",
525 );
526 return (
527 <div
528 role="status"
529 className="flex flex-wrap items-center gap-x-2 gap-y-0.5 border-b px-3 py-1 text-xs text-muted-foreground"
530 >
531 <span className="flex min-w-0 flex-1 basis-56 items-start gap-2">
532 <CircleAlert className="mt-px size-3.5 shrink-0 text-warning-foreground" />
533 <span className="min-w-0">
534 {platforms.length > 1
535 ? gt("{first} and {second} lists on {host} may be incomplete.", {
536 first: platforms[0],
537 second: platforms[1],
538 host: props.label,
539 })
540 : platforms.length === 1
541 ? gt("{platform} list on {host} may be incomplete.", {
542 platform: platforms[0],
543 host: props.label,
544 })
545 : gt("Device discovery on {host} reported a warning.", { host: props.label })}
546 </span>
547 </span>
548 <span className="ml-auto flex shrink-0 items-center gap-0.5">
549 {platforms.length > 0 ? (
550 <Button
551 size="micro"
552 variant="ghost"
553 disabled={retrying}
554 aria-label={gt("Retry device discovery on {host}", { host: props.label })}
555 onClick={() => {
556 setRetrying(true);
557 void props.onRetry().finally(() => setRetrying(false));
558 }}
559 >
560 {retrying ? gt("Retrying…") : gt("Retry")}
561 </Button>
562 ) : null}
563 <Popover open={open} onOpenChange={setOpen}>
564 <PopoverTrigger
565 aria-label={gt("Details for {host}", { host: props.label })}
566 render={<Button size="micro" variant="ghost" />}
567 >
568 <T>Details</T>
569 </PopoverTrigger>
570 <PopoverPopup side="bottom" align="end" width="lg" padding="compact">
571 <p className="whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground">
572 {props.detail}
573 </p>
574 </PopoverPopup>
575 </Popover>
576 <Button
577 size="icon-micro"
578 variant="ghost"
579 aria-label={gt("Dismiss device warning for {host}", { host: props.label })}
580 onClick={() => {
581 setOpen(false);
582 setDismissedCause(cause);
583 }}
584 >
585 <X />
586 </Button>
587 </span>
588 </div>
589 );
590}
591
592function groupDevices(state: DeviceServiceState) {
593 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
594 for (const platform of ["ios", "android"] as const) {
595 const devices = state.devices
596 .filter((device) => device.platform === platform)
597 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
598 if (devices.length > 0) groups.push({ platform, devices });
599 }
600 return groups;
601}