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 : group.devices.some((device) => device.physical)
364 ? gt("Android Devices")
365 : gt("Android Emulators")}
366 </h3>
367 </div>
368 <DiscoveryList>
369 {group.devices.map((device) => (
370 <div
371 key={deviceKey(device)}
372 className="flex items-center gap-3 px-3 py-3"
373 >
374 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
375 <Smartphone className="size-4" />
376 </span>
377 <div className="flex min-w-0 flex-1 flex-col">
378 <span className="truncate text-sm font-medium text-foreground">
379 {device.name}
380 </span>
381 <span className="truncate text-xs text-muted-foreground">
382 {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? gt("Running", { $context: "device state" }) : gt("Stopped", { $context: "device state" })}`}
383 </span>
384 </div>
385 {device.booted && !device.physical ? (
386 <Tooltip>
387 <TooltipTrigger
388 render={
389 <Button
390 variant="outline"
391 size="icon-sm"
392 disabled={
393 isStopping(device) ||
394 pendingDeviceKey === deviceKey(device)
395 }
396 aria-label={gt("Stop {name}", { name: device.name })}
397 onClick={() => void stopDevices([device])}
398 />
399 }
400 >
401 {isStopping(device) ? <Spinner size="xs" /> : <Square />}
402 </TooltipTrigger>
403 <TooltipPopup>
404 {gt("Stop", { $context: "verb, powers off a running device" })}
405 </TooltipPopup>
406 </Tooltip>
407 ) : null}
408 <Button
409 variant="outline"
410 size="sm"
411 disabled={pendingDeviceKey !== null || isStopping(device)}
412 aria-label={
413 device.booted
414 ? gt("Open {name}", { name: device.name })
415 : gt("Start {name}", { name: device.name })
416 }
417 onClick={() => void selectDevice(deviceKey(device))}
418 >
419 {pendingDeviceKey === deviceKey(device) ? (
420 <Spinner size="xs" />
421 ) : device.booted ? (
422 <ArrowUpRight />
423 ) : (
424 <Play />
425 )}
426 {device.booted
427 ? gt("Open", { $context: "verb, opens a running device" })
428 : gt("Start", { $context: "verb, boots a device" })}
429 </Button>
430 </div>
431 ))}
432 </DiscoveryList>
433 </section>
434 ))}
435 </div>
436 ) : null}
437 {hostReady &&
438 !isAndroidDiscoveryUncertain(state) &&
439 !state.devices.some((device) => device.platform === "android") &&
440 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
441 <p className="max-w-sm text-xs">
442 <T>
443 No Android virtual devices found. Create one in Android Studio's Device
444 Manager, then refresh.
445 </T>
446 </p>
447 ) : null}
448 {loaded && !hostBusy ? (
449 <div
450 className={cn(
451 "flex flex-wrap gap-2",
452 grouped.length > 0 ? "self-start" : "self-center",
453 )}
454 >
455 <Button
456 variant="outline"
457 size="sm"
458 onClick={() => void list({ environmentId, input: {} })}
459 >
460 <T>Refresh devices</T>
461 </Button>
462 {stoppable.length > 0 ? (
463 <Button
464 variant="outline"
465 size="sm"
466 disabled={stoppable.every(isStopping)}
467 onClick={() =>
468 void stopDevices(stoppable.filter((device) => !isStopping(device)))
469 }
470 >
471 <T>Stop all devices</T>
472 </Button>
473 ) : null}
474 </div>
475 ) : null}
476 </div>
477 </div>
478 )}
479 </div>
480 </div>
481 </PreviewPanelShell>
482 );
483}
484
485function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) {
486 const gt = useGT();
487 return (
488 <div
489 role="alert"
490 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
491 >
492 <CircleAlert className="mt-1 size-3.5 shrink-0" />
493 <div
494 className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
495 tabIndex={0}
496 >
497 {props.children}
498 </div>
499 <Button
500 size="icon-xs"
501 variant="ghost"
502 aria-label={gt("Dismiss device error")}
503 onClick={props.onDismiss}
504 >
505 <X />
506 </Button>
507 </div>
508 );
509}
510
511function DeviceDiscoveryWarning(props: {
512 readonly label: string;
513 readonly detail: string;
514 readonly incompletePlatforms: readonly DevicePlatform[];
515 readonly onRetry: () => Promise<unknown>;
516}) {
517 const gt = useGT();
518 const [open, setOpen] = useState(false);
519 const [retrying, setRetrying] = useState(false);
520 const [dismissedCause, setDismissedCause] = useState<string | null>(null);
521 const cause = `${props.incompletePlatforms.join()}\u0000${props.detail}`;
522 // A dismissal hides one occurrence; a cause that returns later shows again.
523 if (dismissedCause !== null && dismissedCause !== cause) setDismissedCause(null);
524 if (dismissedCause === cause) return null;
525 const platforms = props.incompletePlatforms.map((platform) =>
526 platform === "ios" ? "iOS" : "Android",
527 );
528 return (
529 <div
530 role="status"
531 className="flex flex-wrap items-center gap-x-2 gap-y-0.5 border-b px-3 py-1 text-xs text-muted-foreground"
532 >
533 <span className="flex min-w-0 flex-1 basis-56 items-start gap-2">
534 <CircleAlert className="mt-px size-3.5 shrink-0 text-warning-foreground" />
535 <span className="min-w-0">
536 {platforms.length > 1
537 ? gt("{first} and {second} lists on {host} may be incomplete.", {
538 first: platforms[0],
539 second: platforms[1],
540 host: props.label,
541 })
542 : platforms.length === 1
543 ? gt("{platform} list on {host} may be incomplete.", {
544 platform: platforms[0],
545 host: props.label,
546 })
547 : gt("Device discovery on {host} reported a warning.", { host: props.label })}
548 </span>
549 </span>
550 <span className="ml-auto flex shrink-0 items-center gap-0.5">
551 {platforms.length > 0 ? (
552 <Button
553 size="micro"
554 variant="ghost"
555 disabled={retrying}
556 aria-label={gt("Retry device discovery on {host}", { host: props.label })}
557 onClick={() => {
558 setRetrying(true);
559 void props.onRetry().finally(() => setRetrying(false));
560 }}
561 >
562 {retrying ? gt("Retrying…") : gt("Retry")}
563 </Button>
564 ) : null}
565 <Popover open={open} onOpenChange={setOpen}>
566 <PopoverTrigger
567 aria-label={gt("Details for {host}", { host: props.label })}
568 render={<Button size="micro" variant="ghost" />}
569 >
570 <T>Details</T>
571 </PopoverTrigger>
572 <PopoverPopup side="bottom" align="end" width="lg" padding="compact">
573 <p className="whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground">
574 {props.detail}
575 </p>
576 </PopoverPopup>
577 </Popover>
578 <Button
579 size="icon-micro"
580 variant="ghost"
581 aria-label={gt("Dismiss device warning for {host}", { host: props.label })}
582 onClick={() => {
583 setOpen(false);
584 setDismissedCause(cause);
585 }}
586 >
587 <X />
588 </Button>
589 </span>
590 </div>
591 );
592}
593
594function groupDevices(state: DeviceServiceState) {
595 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
596 for (const platform of ["ios", "android"] as const) {
597 const devices = state.devices
598 .filter((device) => device.platform === platform)
599 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
600 if (devices.length > 0) groups.push({ platform, devices });
601 }
602 return groups;
603}