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