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 { Smartphone, X } from "lucide-react";
9import { useEffect, useMemo, useState } from "react";
10
11import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
12import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";
13import { Button } from "~/components/ui/button";
14import { DiscoveryList, DiscoveryListRow } 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 } 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 const [operationError, setOperationError] = useState<string | null>(null);
46 const [pendingDevice, setPendingDevice] = useState<DeviceSummary | null>(null);
47 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
48
49 const hostDisabled = state.hostStatus === "disabled";
50
51 // Opening setup never grants permission to install or start helpers.
52 useEffect(() => {
53 if (!props.visible || !loaded || hostDisabled) return;
54 void list({ environmentId, input: {} });
55 }, [environmentId, list, loaded, props.visible, hostDisabled]);
56
57 const sessions = useMemo(
58 () => state.sessions.filter((session) => session.threadId === threadId),
59 [state.sessions, threadId],
60 );
61 const activeSession = props.surface.target
62 ? sessions.find(
63 (session) =>
64 session.deviceId === props.surface.target?.deviceId &&
65 session.hostId === props.surface.target.hostId,
66 )
67 : undefined;
68 const activeDevice = activeSession
69 ? state.devices.find(
70 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
71 )
72 : undefined;
73
74 const grouped = useMemo(() => groupDevices(state), [state]);
75
76 const selectDevice = async (value: string) => {
77 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
78 if (!device) return;
79 setOperationError(null);
80 setPendingDevice(device);
81 try {
82 const result = await open({
83 environmentId,
84 input: {
85 threadId,
86 hostId: device.hostId,
87 deviceId: device.id,
88 platform: device.platform,
89 },
90 });
91 if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
92 else
93 useRightPanelStore.getState().openDevice(props.threadRef, {
94 hostId: result.value.hostId,
95 deviceId: result.value.deviceId,
96 platform: device.platform,
97 name: device.name,
98 });
99 } finally {
100 setPendingDevice(null);
101 }
102 };
103
104 const floatActive = () => {
105 if (!activeDevice) return;
106 usePreviewMiniPlayerStore.getState().open(props.threadRef, {
107 kind: "device",
108 hostId: activeDevice.hostId,
109 deviceId: activeDevice.id,
110 platform: activeDevice.platform,
111 name: activeDevice.name,
112 });
113 useRightPanelStore.getState().close(props.threadRef);
114 };
115
116 const closeActive = (powerOff: boolean) => {
117 if (!powerOff) {
118 useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
119 return;
120 }
121 if (!activeSession) return;
122 setOperationError(null);
123 void close({
124 environmentId,
125 input: {
126 threadId,
127 hostId: activeSession.hostId,
128 deviceId: activeSession.deviceId,
129 shutdown: powerOff,
130 },
131 }).then((result) => {
132 if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
133 else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
134 });
135 };
136
137 const bootingDevices =
138 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
139 const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
140 const unavailablePlatforms = state.hosts.flatMap((host) =>
141 host.platforms
142 .filter((platform) => !platform.available)
143 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
144 );
145
146 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
147 return (
148 <Dialog
149 open={props.visible}
150 onOpenChange={(isOpen) => {
151 if (!isOpen) props.onDismissSetup();
152 }}
153 >
154 <WizardPopup>
155 <DeviceSetup environmentId={environmentId} state={state} />
156 </WizardPopup>
157 </Dialog>
158 );
159 }
160
161 return (
162 <PreviewPanelShell mode={props.mode}>
163 {hostReady && !activeDevice && state.hostStatusDetail ? (
164 <div
165 role="status"
166 className="whitespace-pre-line border-b px-3 py-2 text-xs text-muted-foreground"
167 >
168 {state.hostStatusDetail}
169 </div>
170 ) : null}
171 <DeviceHostUpdates state={state} environmentId={environmentId} />
172 {bootingDevices.length > 0 ? (
173 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
174 Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a minute.
175 </div>
176 ) : null}
177 {operationError ? (
178 <div
179 role="alert"
180 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
181 >
182 <p className="min-w-0 flex-1 whitespace-pre-wrap break-words">{operationError}</p>
183 <Button
184 size="icon-xs"
185 variant="ghost"
186 aria-label="Dismiss device error"
187 onClick={() => setOperationError(null)}
188 >
189 <X className="size-3" />
190 </Button>
191 </div>
192 ) : null}
193 <div className="@container relative flex min-h-0 flex-1">
194 {activeDevice && activeSession ? (
195 <DeviceWorkspace
196 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
197 environmentId={environmentId}
198 device={activeDevice}
199 hostLabel={
200 state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"
201 }
202 hostDiagnostics={state.hostStatusDetail}
203 visible={props.visible}
204 onFloat={floatActive}
205 onClose={() => closeActive(false)}
206 onPowerOff={() => closeActive(true)}
207 />
208 ) : pendingDevice || hostBusy || !loaded ? (
209 <DeviceLoadingView
210 name={pendingDevice?.name ?? "Devices"}
211 description={
212 pendingDevice
213 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
214 : ""
215 }
216 stage="opening"
217 message={
218 pendingDevice
219 ? pendingDevice.booted
220 ? "Opening device…"
221 : "Starting device…"
222 : state.hostStatus === "installing"
223 ? (state.hostStatusDetail ?? "Installing device support…")
224 : "Finding devices…"
225 }
226 />
227 ) : (
228 <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
229 <div
230 className={cn(
231 "mx-auto flex w-full max-w-xl flex-col gap-6",
232 grouped.length === 0 && "my-auto items-center text-center",
233 )}
234 >
235 {grouped.length === 0 ? (
236 <>
237 <Smartphone className="size-6 opacity-60" />
238 <p className="max-w-sm">
239 {state.hostStatus === "failed"
240 ? (state.hostStatusDetail ?? "The device hub failed to start.")
241 : "No simulators or emulators were found on this environment."}
242 </p>
243 </>
244 ) : null}
245 {hostReady && grouped.length > 0 ? (
246 <div className="w-full space-y-6 text-left">
247 {grouped.map((group) => (
248 <section key={group.platform} className="space-y-3">
249 <div className="flex items-center gap-2 text-sm text-muted-foreground">
250 <Smartphone className="size-4 shrink-0" />
251 <h3 className="font-medium">{platformLabel(group.platform)}</h3>
252 </div>
253 <DiscoveryList>
254 {group.devices.map((device) => (
255 <DiscoveryListRow
256 key={deviceKey(device)}
257 icon={
258 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
259 <Smartphone className="size-4" />
260 </span>
261 }
262 title={device.name}
263 description={`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
264 disabled={pendingDeviceKey !== null}
265 aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
266 onClick={() => void selectDevice(deviceKey(device))}
267 action={
268 pendingDeviceKey === deviceKey(device) ? (
269 <Spinner size="xs" />
270 ) : (
271 <span className="text-xs text-muted-foreground">
272 {device.booted ? "Open" : "Start"}
273 </span>
274 )
275 }
276 />
277 ))}
278 </DiscoveryList>
279 </section>
280 ))}
281 </div>
282 ) : null}
283 {hostReady &&
284 !state.devices.some((device) => device.platform === "android") &&
285 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
286 <p className="max-w-sm text-xs">
287 No Android virtual devices found. Create one in Android Studio's Device Manager,
288 then refresh.
289 </p>
290 ) : null}
291 {loaded && !hostBusy ? (
292 <Button
293 className={grouped.length > 0 ? "self-start" : "self-center"}
294 variant={grouped.length > 0 ? "ghost" : "outline"}
295 size="sm"
296 onClick={() => void list({ environmentId, input: {} })}
297 >
298 Refresh devices
299 </Button>
300 ) : null}
301 </div>
302 </div>
303 )}
304 </div>
305 </PreviewPanelShell>
306 );
307}
308
309function groupDevices(state: DeviceServiceState) {
310 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
311 for (const platform of ["ios", "android"] as const) {
312 const devices = state.devices
313 .filter((device) => device.platform === platform)
314 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
315 if (devices.length > 0) groups.push({ platform, devices });
316 }
317 return groups;
318}