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, X } from "lucide-react";
9import { type ReactNode, useEffect, useState } from "react";
10
11import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
12import {
13 selectThreadRightPanelState,
14 useRightPanelStore,
15 type RightPanelSurface,
16} from "~/rightPanelStore";
17import { Button } from "~/components/ui/button";
18import { DiscoveryList } from "~/components/ui/discovery-list";
19import { Dialog } from "~/components/ui/dialog";
20import { WizardPopup } from "~/components/ui/wizard";
21import { Spinner } from "~/components/ui/spinner";
22import { cn } from "~/lib/utils";
23import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
24import { deviceEnvironment, useDeviceState } from "~/state/device";
25import { formatEnvironmentQueryError } from "~/state/query";
26import { useAtomCommand } from "~/state/use-atom-command";
27import { DeviceLoadingView } from "./DeviceLoadingView";
28import { DeviceSetup, deviceHubReadiness, isAndroidDiscoveryUncertain } from "./DeviceSetup";
29import { DeviceWorkspace } from "./DeviceWorkspace";
30import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
31
32const platformLabel = (platform: DevicePlatform) =>
33 platform === "ios" ? "iOS Simulators" : "Android Emulators";
34
35const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
36 `${device.hostId}\u0000${device.id}`;
37
38export function DevicePanel(props: {
39 readonly mode: PreviewPanelMode;
40 readonly threadRef: ScopedThreadRef;
41 readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
42 readonly visible: boolean;
43 readonly onDismissSetup: () => void;
44}) {
45 const { environmentId, threadId } = props.threadRef;
46 const { state, loaded } = useDeviceState(environmentId);
47 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
48 const open = useAtomCommand(deviceEnvironment.open);
49 const close = useAtomCommand(deviceEnvironment.close);
50 // The panel stays mounted across thread switches, so an in-flight open or
51 // power-off is tagged with the thread it belongs to and only shown there.
52 const scope = `${environmentId}\u0000${threadId}`;
53 const [operation, setOperation] = useState<{
54 readonly scope: string;
55 readonly pending: DeviceSummary | null;
56 readonly error: string | null;
57 } | null>(null);
58 const pendingDevice = operation?.scope === scope ? operation.pending : null;
59 const operationError = operation?.scope === scope ? operation.error : null;
60 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
61
62 const hostDisabled = state.hostStatus === "disabled";
63
64 // Opening setup never grants permission to install or start helpers.
65 useEffect(() => {
66 if (!props.visible || !loaded || hostDisabled) return;
67 void list({ environmentId, input: {} });
68 }, [environmentId, list, loaded, props.visible, hostDisabled]);
69
70 const sessions = state.sessions.filter((session) => session.threadId === threadId);
71 const activeSession = props.surface.target
72 ? sessions.find(
73 (session) =>
74 session.deviceId === props.surface.target?.deviceId &&
75 session.hostId === props.surface.target.hostId,
76 )
77 : undefined;
78 const activeDevice = activeSession
79 ? state.devices.find(
80 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
81 )
82 : undefined;
83
84 const grouped = groupDevices(state);
85
86 const startOperation = (pending: DeviceSummary | null) => {
87 const started = { scope, pending, error: null };
88 setOperation(started);
89 // Returning to the same thread can start a newer operation before this one settles.
90 return (error: string | null) =>
91 setOperation((current) =>
92 current === started ? { ...started, pending: null, error } : current,
93 );
94 };
95
96 const selectDevice = async (value: string) => {
97 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
98 if (!device) return;
99 const settleOperation = startOperation(device);
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") settleOperation(formatEnvironmentQueryError(result.cause));
110 else {
111 // The server opened the device for the starting thread, so its tab opens there.
112 useRightPanelStore.getState().openDevice(props.threadRef, {
113 hostId: result.value.hostId,
114 deviceId: result.value.deviceId,
115 platform: device.platform,
116 name: device.name,
117 });
118 settleOperation(null);
119 }
120 };
121
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 closeSurface = () => {
135 const store = useRightPanelStore.getState();
136 const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);
137 store.closeSurface(props.threadRef, props.surface.id);
138 focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);
139 };
140
141 const closeActive = (powerOff: boolean) => {
142 if (!powerOff) {
143 closeSurface();
144 return;
145 }
146 if (!activeSession) return;
147 const settleOperation = startOperation(null);
148 void close({
149 environmentId,
150 input: {
151 threadId,
152 hostId: activeSession.hostId,
153 deviceId: activeSession.deviceId,
154 shutdown: powerOff,
155 },
156 }).then((result) => {
157 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
158 else closeSurface();
159 });
160 };
161
162 const bootingDevices =
163 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
164 const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
165 const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded);
166 const diagnostics = state.hosts.flatMap((host) => {
167 const status = state.hostStatuses[host.id];
168 const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined);
169 return detail && (status?.status ?? state.hostStatus) === "ready"
170 ? [{ hostId: host.id, label: host.label, detail }]
171 : [];
172 });
173 const unavailablePlatforms = state.hosts.flatMap((host) =>
174 host.platforms
175 .filter((platform) => !platform.available)
176 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
177 );
178
179 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
180 return (
181 <Dialog
182 open={props.visible}
183 onOpenChange={(isOpen) => {
184 if (!isOpen) props.onDismissSetup();
185 }}
186 >
187 <WizardPopup>
188 <DeviceSetup environmentId={environmentId} state={state} />
189 </WizardPopup>
190 </Dialog>
191 );
192 }
193
194 return (
195 <PreviewPanelShell mode={props.mode}>
196 <div className="relative flex min-h-0 flex-1 flex-col">
197 <div
198 className={cn(
199 "shrink-0 bg-background",
200 loading && "absolute inset-x-0 top-0 z-10 max-h-[40%] overflow-y-auto",
201 )}
202 >
203 <div hidden={!!activeDevice}>
204 {diagnostics.map((diagnostic) => (
205 <DeviceDiscoveryWarning
206 key={`${environmentId}\u0000${diagnostic.hostId}\u0000${diagnostic.detail}`}
207 label={diagnostic.label}
208 detail={diagnostic.detail}
209 />
210 ))}
211 </div>
212 <DeviceHostUpdates state={state} environmentId={environmentId} />
213 {bootingDevices.length > 0 ? (
214 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
215 Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a
216 minute.
217 </div>
218 ) : null}
219 {operationError ? (
220 <DeviceNotice tone="error" onDismiss={() => setOperation(null)}>
221 {operationError}
222 </DeviceNotice>
223 ) : null}
224 </div>
225 <div className="@container relative flex min-h-0 flex-1">
226 {activeDevice && activeSession ? (
227 <DeviceWorkspace
228 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
229 environmentId={environmentId}
230 device={activeDevice}
231 hostLabel={
232 state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"
233 }
234 hostDiagnostics={
235 diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
236 }
237 visible={props.visible}
238 onFloat={floatActive}
239 onClose={() => closeActive(false)}
240 onPowerOff={() => closeActive(true)}
241 />
242 ) : loading ? (
243 <DeviceLoadingView
244 name={pendingDevice?.name ?? "Devices"}
245 description={
246 pendingDevice
247 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
248 : ""
249 }
250 stage="opening"
251 message={
252 pendingDevice
253 ? pendingDevice.booted
254 ? "Opening device…"
255 : "Starting device…"
256 : state.hostStatus === "installing"
257 ? (state.hostStatusDetail ?? "Installing device support…")
258 : "Finding devices…"
259 }
260 />
261 ) : (
262 <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
263 <div
264 className={cn(
265 "mx-auto flex w-full max-w-xl flex-col gap-6",
266 grouped.length === 0 && "my-auto items-center text-center",
267 )}
268 >
269 {grouped.length === 0 ? (
270 <>
271 <Smartphone className="size-6 opacity-60" />
272 <p
273 className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
274 tabIndex={state.hostStatus === "failed" ? 0 : undefined}
275 >
276 {state.hostStatus === "failed"
277 ? (state.hostStatusDetail ?? "The device hub failed to start.")
278 : "No simulators or emulators were found on this environment."}
279 </p>
280 </>
281 ) : null}
282 {hostReady && grouped.length > 0 ? (
283 <div className="w-full space-y-6 text-left">
284 {grouped.map((group) => (
285 <section key={group.platform} className="space-y-3">
286 <div className="flex items-center gap-2 text-sm text-muted-foreground">
287 <Smartphone className="size-4 shrink-0" />
288 <h3 className="font-medium">{platformLabel(group.platform)}</h3>
289 </div>
290 <DiscoveryList>
291 {group.devices.map((device) => (
292 <div
293 key={deviceKey(device)}
294 className="flex items-center gap-3 px-3 py-3"
295 >
296 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
297 <Smartphone className="size-4" />
298 </span>
299 <div className="flex min-w-0 flex-1 flex-col">
300 <span className="truncate text-sm font-medium text-foreground">
301 {device.name}
302 </span>
303 <span className="truncate text-xs text-muted-foreground">
304 {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
305 </span>
306 </div>
307 <Button
308 variant="outline"
309 size="sm"
310 disabled={pendingDeviceKey !== null}
311 aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
312 onClick={() => void selectDevice(deviceKey(device))}
313 >
314 {pendingDeviceKey === deviceKey(device) ? (
315 <Spinner size="xs" />
316 ) : device.booted ? (
317 <ArrowUpRight />
318 ) : (
319 <Play />
320 )}
321 {device.booted ? "Open" : "Start"}
322 </Button>
323 </div>
324 ))}
325 </DiscoveryList>
326 </section>
327 ))}
328 </div>
329 ) : null}
330 {hostReady &&
331 !isAndroidDiscoveryUncertain(state) &&
332 !state.devices.some((device) => device.platform === "android") &&
333 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
334 <p className="max-w-sm text-xs">
335 No Android virtual devices found. Create one in Android Studio's Device Manager,
336 then refresh.
337 </p>
338 ) : null}
339 {loaded && !hostBusy ? (
340 <Button
341 className={grouped.length > 0 ? "self-start" : "self-center"}
342 variant="outline"
343 size="sm"
344 onClick={() => void list({ environmentId, input: {} })}
345 >
346 Refresh devices
347 </Button>
348 ) : null}
349 </div>
350 </div>
351 )}
352 </div>
353 </div>
354 </PreviewPanelShell>
355 );
356}
357
358function DeviceNotice(props: {
359 readonly tone: "warning" | "error";
360 readonly onDismiss: () => void;
361 readonly children: ReactNode;
362}) {
363 return (
364 <div
365 role="alert"
366 className={cn(
367 "flex items-start gap-2 border-b px-3 py-2 text-xs",
368 props.tone === "warning"
369 ? "bg-warning-surface text-warning-foreground"
370 : "bg-destructive/5 text-destructive",
371 )}
372 >
373 <CircleAlert className="mt-1 size-3.5 shrink-0" />
374 <div
375 className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
376 tabIndex={0}
377 >
378 {props.children}
379 </div>
380 <Button
381 size="icon-xs"
382 variant="ghost"
383 aria-label={props.tone === "warning" ? "Dismiss device warning" : "Dismiss device error"}
384 onClick={props.onDismiss}
385 >
386 <X />
387 </Button>
388 </div>
389 );
390}
391
392function DeviceDiscoveryWarning(props: { readonly label: string; readonly detail: string }) {
393 const [dismissed, setDismissed] = useState(false);
394 if (dismissed) return null;
395 return (
396 <DeviceNotice tone="warning" onDismiss={() => setDismissed(true)}>
397 <p className="font-medium">Device discovery warning · {props.label}</p>
398 {props.detail}
399 </DeviceNotice>
400 );
401}
402
403function groupDevices(state: DeviceServiceState) {
404 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
405 for (const platform of ["ios", "android"] as const) {
406 const devices = state.devices
407 .filter((device) => device.platform === platform)
408 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
409 if (devices.length > 0) groups.push({ platform, devices });
410 }
411 return groups;
412}