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