Open History to see the last commit
1import type {
2 DevicePlatform,
3 DeviceServiceState,
4 DeviceSummary,
5 ScopedThreadRef,
6} from "@t3tools/contracts";
7import {
8 ChevronLeft,
9 Home,
10 PictureInPicture2,
11 Power,
12 RotateCcw,
13 SlidersHorizontal,
14 Smartphone,
15 Square,
16 X,
17} from "lucide-react";
18import { useEffect, useMemo, useState } from "react";
19
20import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
21import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";
22import { Button } from "~/components/ui/button";
23import { DiscoveryList, DiscoveryListRow } from "~/components/ui/discovery-list";
24import { Dialog } from "~/components/ui/dialog";
25import { WizardPopup } from "~/components/ui/wizard";
26import { Spinner } from "~/components/ui/spinner";
27import { Toggle } from "~/components/ui/toggle";
28import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
29import { cn } from "~/lib/utils";
30import { deviceEnvironment, useDeviceHubAccess, useDeviceState } from "~/state/device";
31import { formatEnvironmentQueryError } from "~/state/query";
32import { useAtomCommand } from "~/state/use-atom-command";
33import { DeviceStreamView, type DeviceStreamHandle } from "./DeviceStreamView";
34import { DeviceLoadingView } from "./DeviceLoadingView";
35import { DeviceSetup } from "./DeviceSetup";
36import { DeviceToolsPanel } from "./DeviceToolsPanel";
37import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
38
39const platformLabel = (platform: DevicePlatform) =>
40 platform === "ios" ? "iOS Simulators" : "Android Emulators";
41
42const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
43 `${device.hostId}\u0000${device.id}`;
44
45/** Each surface owns one host/device; only the visible surface streams. */
46export function DevicePanel(props: {
47 readonly mode: PreviewPanelMode;
48 readonly threadRef: ScopedThreadRef;
49 readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
50 readonly visible: boolean;
51 readonly onDismissSetup: () => void;
52}) {
53 const { environmentId, threadId } = props.threadRef;
54 const { state, loaded } = useDeviceState(environmentId);
55 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
56 const open = useAtomCommand(deviceEnvironment.open);
57 const close = useAtomCommand(deviceEnvironment.close);
58 const [operationError, setOperationError] = useState<string | null>(null);
59 const [pendingDevice, setPendingDevice] = useState<DeviceSummary | null>(null);
60 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
61 const [handle, setHandle] = useState<DeviceStreamHandle | null>(null);
62 const [toolsOpen, setToolsOpen] = useState(false);
63 const [axOverlay, setAxOverlay] = useState(false);
64 const access = useDeviceHubAccess(environmentId);
65
66 const hostDisabled = state.hostStatus === "disabled";
67
68 // Opening setup never grants permission to install or start helpers.
69 useEffect(() => {
70 if (!props.visible || !loaded || hostDisabled) return;
71 void list({ environmentId, input: {} });
72 }, [environmentId, list, loaded, props.visible, hostDisabled]);
73
74 const sessions = useMemo(
75 () => state.sessions.filter((session) => session.threadId === threadId),
76 [state.sessions, threadId],
77 );
78 const activeSession = props.surface.target
79 ? sessions.find(
80 (session) =>
81 session.deviceId === props.surface.target?.deviceId &&
82 session.hostId === props.surface.target.hostId,
83 )
84 : undefined;
85 const activeDevice = activeSession
86 ? state.devices.find(
87 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
88 )
89 : undefined;
90
91 const grouped = useMemo(() => groupDevices(state), [state]);
92
93 const selectDevice = async (value: string) => {
94 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
95 if (!device) return;
96 setOperationError(null);
97 setPendingDevice(device);
98 try {
99 const result = await open({
100 environmentId,
101 input: {
102 threadId,
103 hostId: device.hostId,
104 deviceId: device.id,
105 platform: device.platform,
106 },
107 });
108 if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
109 else
110 useRightPanelStore.getState().openDevice(props.threadRef, {
111 hostId: result.value.hostId,
112 deviceId: result.value.deviceId,
113 platform: device.platform,
114 name: device.name,
115 });
116 } finally {
117 setPendingDevice(null);
118 }
119 };
120
121 // Floating the device closes the panel, like the browser's floating preview.
122 const floatActive = () => {
123 if (!activeDevice) return;
124 usePreviewMiniPlayerStore.getState().open(props.threadRef, {
125 kind: "device",
126 hostId: activeDevice.hostId,
127 deviceId: activeDevice.id,
128 platform: activeDevice.platform,
129 name: activeDevice.name,
130 });
131 useRightPanelStore.getState().close(props.threadRef);
132 };
133
134 const closeActive = (powerOff: boolean) => {
135 if (!powerOff) {
136 useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
137 return;
138 }
139 if (!activeSession) return;
140 setOperationError(null);
141 void close({
142 environmentId,
143 input: {
144 threadId,
145 hostId: activeSession.hostId,
146 deviceId: activeSession.deviceId,
147 shutdown: powerOff,
148 },
149 }).then((result) => {
150 if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
151 else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
152 });
153 };
154
155 const bootingDevices =
156 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
157 const hostReady = Object.values(state.hostStatuses).some((host) => host.status === "ready");
158 const hostBusy =
159 !hostReady &&
160 Object.values(state.hostStatuses).some(
161 (host) => host.status === "installing" || host.status === "starting",
162 );
163 const unavailablePlatforms = state.hosts.flatMap((host) =>
164 host.platforms
165 .filter((platform) => !platform.available)
166 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
167 );
168
169 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
170 return (
171 <Dialog
172 open={props.visible}
173 onOpenChange={(isOpen) => {
174 if (!isOpen) props.onDismissSetup();
175 }}
176 >
177 <WizardPopup>
178 <DeviceSetup environmentId={environmentId} state={state} />
179 </WizardPopup>
180 </Dialog>
181 );
182 }
183
184 return (
185 <PreviewPanelShell mode={props.mode}>
186 <div className="flex h-9 shrink-0 items-center gap-1.5 border-b px-2">
187 <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
188 {props.surface.target
189 ? `${state.hosts.find((host) => host.id === props.surface.target?.hostId)?.label ?? "Device host"} · ${activeDevice?.version ?? props.surface.target.platform}`
190 : (pendingDevice?.name ?? "Choose a device")}
191 </span>
192 {activeDevice ? (
193 <>
194 <DeviceButton
195 label="Home"
196 onClick={() => handle?.pressButton("home")}
197 disabled={!handle?.inputConnected}
198 >
199 <Home />
200 </DeviceButton>
201 {activeDevice.platform === "android" ? (
202 <>
203 <DeviceButton
204 label="Back"
205 onClick={() => handle?.pressButton("back")}
206 disabled={!handle?.inputConnected}
207 >
208 <ChevronLeft />
209 </DeviceButton>
210 <DeviceButton
211 label="Recents"
212 onClick={() => handle?.pressButton("recents")}
213 disabled={!handle?.inputConnected}
214 >
215 <Square />
216 </DeviceButton>
217 </>
218 ) : (
219 <DeviceButton
220 label="Rotate"
221 onClick={() => handle?.rotate()}
222 disabled={!handle?.inputConnected}
223 >
224 <RotateCcw />
225 </DeviceButton>
226 )}
227 <Toggle
228 aria-label="Tools"
229 variant="ghost"
230 size="xs"
231 pressed={toolsOpen}
232 onPressedChange={(pressed) => setToolsOpen(Boolean(pressed))}
233 >
234 <SlidersHorizontal />
235 </Toggle>
236 <DeviceButton label="Float device over chat" onClick={floatActive}>
237 <PictureInPicture2 />
238 </DeviceButton>
239 <DeviceButton label="Power off" onClick={() => closeActive(true)}>
240 <Power />
241 </DeviceButton>
242 <DeviceButton label="Close" onClick={() => closeActive(false)}>
243 <X />
244 </DeviceButton>
245 </>
246 ) : null}
247 </div>
248 {hostReady && state.hostStatusDetail ? (
249 <div
250 role="status"
251 className="whitespace-pre-line border-b px-3 py-2 text-xs text-muted-foreground"
252 >
253 {state.hostStatusDetail}
254 </div>
255 ) : null}
256 {bootingDevices.length > 0 ? (
257 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
258 Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a minute.
259 </div>
260 ) : null}
261 {operationError ? (
262 <div
263 role="alert"
264 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
265 >
266 <p className="min-w-0 flex-1 whitespace-pre-wrap break-words">{operationError}</p>
267 <Button
268 size="icon-xs"
269 variant="ghost"
270 aria-label="Dismiss device error"
271 onClick={() => setOperationError(null)}
272 >
273 <X className="size-3" />
274 </Button>
275 </div>
276 ) : null}
277 <div className="@container relative flex min-h-0 flex-1">
278 {activeDevice && activeSession ? (
279 <>
280 <div className="relative min-h-0 min-w-0 flex-1">
281 <DeviceStreamView
282 key={deviceKey(activeDevice)}
283 environmentId={environmentId}
284 platform={activeDevice.platform}
285 deviceName={activeDevice.name}
286 deviceDescription={`${state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"} · ${activeDevice.version}`}
287 deviceId={activeDevice.id}
288 hostId={activeDevice.hostId}
289 visible={props.visible}
290 axOverlay={axOverlay}
291 onHandle={setHandle}
292 />
293 </div>
294 {toolsOpen ? (
295 <DeviceToolsPanel
296 key={deviceKey(activeDevice)}
297 environmentId={environmentId}
298 device={activeDevice}
299 access={access}
300 axOverlay={axOverlay}
301 onAxOverlayChange={setAxOverlay}
302 onClose={() => setToolsOpen(false)}
303 className="absolute inset-y-0 right-0 z-10 w-full max-w-72 border-l shadow-lg @[560px]:static @[560px]:w-72 @[560px]:shrink-0 @[560px]:shadow-none"
304 />
305 ) : null}
306 </>
307 ) : pendingDevice || hostBusy || !loaded ? (
308 <DeviceLoadingView
309 name={pendingDevice?.name ?? "Devices"}
310 description={
311 pendingDevice
312 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
313 : ""
314 }
315 stage="opening"
316 message={
317 pendingDevice
318 ? pendingDevice.booted
319 ? "Opening device…"
320 : "Starting device…"
321 : state.hostStatus === "installing"
322 ? "Installing device support…"
323 : "Finding devices…"
324 }
325 />
326 ) : (
327 <div className="flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
328 <div
329 className={cn(
330 "mx-auto flex w-full max-w-xl flex-col gap-6",
331 grouped.length === 0 && "my-auto items-center text-center",
332 )}
333 >
334 {grouped.length === 0 ? (
335 <>
336 <Smartphone className="size-6 opacity-60" />
337 <p className="max-w-sm">
338 {state.hostStatus === "failed"
339 ? (state.hostStatusDetail ?? "The device hub failed to start.")
340 : "No simulators or emulators were found on this environment."}
341 </p>
342 </>
343 ) : null}
344 {hostReady && grouped.length > 0 ? (
345 <div className="w-full space-y-6 text-left">
346 {grouped.map((group) => (
347 <section key={group.platform} className="space-y-3">
348 <div className="flex items-center gap-2 text-sm text-muted-foreground">
349 <Smartphone className="size-4 shrink-0" />
350 <h3 className="font-medium">{platformLabel(group.platform)}</h3>
351 </div>
352 <DiscoveryList>
353 {group.devices.map((device) => (
354 <DiscoveryListRow
355 key={deviceKey(device)}
356 icon={
357 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
358 <Smartphone className="size-4" />
359 </span>
360 }
361 title={device.name}
362 description={`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
363 disabled={pendingDeviceKey !== null}
364 aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
365 onClick={() => void selectDevice(deviceKey(device))}
366 action={
367 pendingDeviceKey === deviceKey(device) ? (
368 <Spinner className="size-3" />
369 ) : (
370 <span className="text-xs text-muted-foreground">
371 {device.booted ? "Open" : "Start"}
372 </span>
373 )
374 }
375 />
376 ))}
377 </DiscoveryList>
378 </section>
379 ))}
380 </div>
381 ) : null}
382 {hostReady &&
383 !state.devices.some((device) => device.platform === "android") &&
384 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
385 <p className="max-w-sm text-xs">
386 No Android virtual devices found. Create one in Android Studio's Device Manager,
387 then refresh.
388 </p>
389 ) : null}
390 {loaded && !hostBusy ? (
391 <Button
392 className="self-start"
393 variant={grouped.length > 0 ? "ghost" : "outline"}
394 size="sm"
395 onClick={() => void list({ environmentId, input: {} })}
396 >
397 Refresh devices
398 </Button>
399 ) : null}
400 </div>
401 </div>
402 )}
403 </div>
404 </PreviewPanelShell>
405 );
406}
407
408function DeviceButton(props: {
409 readonly label: string;
410 readonly onClick: () => void;
411 readonly disabled?: boolean;
412 readonly children: React.ReactNode;
413}) {
414 return (
415 <Tooltip>
416 <TooltipTrigger
417 render={
418 <Button
419 size="icon-xs"
420 variant="ghost-muted"
421 aria-label={props.label}
422 onClick={props.onClick}
423 disabled={props.disabled ?? false}
424 />
425 }
426 >
427 {props.children}
428 </TooltipTrigger>
429 <TooltipPopup>{props.label}</TooltipPopup>
430 </Tooltip>
431 );
432}
433
434function groupDevices(state: DeviceServiceState) {
435 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
436 for (const platform of ["ios", "android"] as const) {
437 const devices = state.devices
438 .filter((device) => device.platform === platform)
439 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
440 if (devices.length > 0) groups.push({ platform, devices });
441 }
442 return groups;
443}