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