Open History to see the last commit
1import {
2 EnvironmentId,
3 ThreadId,
4 type DeviceServiceState,
5 type ScopedThreadRef,
6} from "@t3tools/contracts";
7import type { ReactNode } from "react";
8import { page } from "vite-plus/test/browser";
9import { describe, expect, it, vi } from "vite-plus/test";
10
11import type { RightPanelSurface } from "~/rightPanelStore";
12
13import { act, render } from "../../../test/render";
14
15import { DevicePanel } from "./DevicePanel";
16import "~/index.css";
17
18type CommandResult =
19 | { _tag: "Success"; value: { hostId: string; deviceId: string } }
20 | { _tag: "Failure"; cause: unknown };
21const mocks = vi.hoisted(() => ({
22 open: vi.fn<(request: unknown) => Promise<CommandResult>>(),
23 close: vi.fn<(request: unknown) => Promise<CommandResult>>(),
24 list: vi.fn<(request: unknown) => Promise<CommandResult>>(),
25 shutdown: vi.fn<(request: unknown) => Promise<CommandResult>>(),
26 openDevice: vi.fn(),
27 closeSurface: vi.fn(),
28}));
29const phone = {
30 hostId: "local",
31 id: "phone",
32 name: "Phone",
33 platform: "ios",
34 version: "iOS 19",
35 booted: false,
36 physical: false,
37} as const;
38const deviceState: DeviceServiceState = {
39 hosts: [
40 {
41 id: "local",
42 kind: "local",
43 label: "This Mac",
44 platforms: [{ platform: "ios", available: true }],
45 hubInstalled: true,
46 agentDeviceInstalled: true,
47 },
48 ],
49 hostStatus: "ready",
50 hostStatuses: { local: { status: "ready" } },
51 devices: [phone],
52 sessions: [
53 {
54 threadId: ThreadId.make("thread-1"),
55 hostId: "local",
56 deviceId: "phone",
57 platform: "ios",
58 openedAt: "2026-01-01T00:00:00.000Z",
59 },
60 ],
61 onboardingCompleted: true,
62 agentAccessEnabled: true,
63 hubBasePath: "/api/device-hub",
64 revision: 1,
65};
66let currentState = deviceState;
67// One probe per environment, however many views mount it; each probe sends one list.
68vi.mock("~/state/device", async () => {
69 const Effect = await import("effect/Effect");
70 const { AsyncResult, Atom } = await import("effect/reactivity");
71 return {
72 deviceEnvironment: { list: "list", open: "open", close: "close", shutdown: "shutdown" },
73 deviceHostProbeAtom: Atom.family((environmentId: string) =>
74 Atom.make(() => Effect.promise(() => mocks.list({ environmentId, input: {} }))),
75 ),
76 NO_DEVICE_PROBE_ATOM: Atom.make(AsyncResult.initial<void, never>()),
77 useDeviceState: () => ({ state: currentState, loaded: true }),
78 };
79});
80vi.mock("~/state/use-atom-command", () => ({
81 useAtomCommand: (command: string) =>
82 command === "open"
83 ? mocks.open
84 : command === "close"
85 ? mocks.close
86 : command === "list"
87 ? mocks.list
88 : command === "shutdown"
89 ? mocks.shutdown
90 : () => Promise.resolve({ _tag: "Success", value: {} }),
91}));
92vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));
93vi.mock("~/rightPanelStore", () => ({
94 useRightPanelStore: {
95 getState: () => ({
96 byThreadKey: {},
97 openDevice: mocks.openDevice,
98 closeSurface: mocks.closeSurface,
99 }),
100 },
101 selectThreadRightPanelState: () => ({ isOpen: false, activeSurfaceId: null, surfaces: [] }),
102}));
103vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
104vi.mock("~/components/device/DeviceWorkspace", () => ({
105 DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
106 <button onClick={onPowerOff}>Power off</button>
107 ),
108}));
109vi.mock("~/components/preview/PreviewPanelShell", () => ({
110 PreviewPanelShell: ({ children }: { children: ReactNode }) => (
111 <div className="flex h-full min-h-0 flex-col">{children}</div>
112 ),
113}));
114
115const threadA = {
116 environmentId: EnvironmentId.make("environment-a"),
117 threadId: ThreadId.make("thread-1"),
118};
119// The panel stays mounted across both kinds of switch.
120const switches = [
121 ["another thread", { environmentId: threadA.environmentId, threadId: ThreadId.make("thread-2") }],
122 [
123 "the same thread id in another environment",
124 { ...threadA, environmentId: EnvironmentId.make("environment-b") },
125 ],
126] as const;
127const threadB = switches[0][1];
128const picker: Extract<RightPanelSurface, { kind: "device" }> = { id: "device", kind: "device" };
129const phoneTarget = { hostId: "local", deviceId: "phone", platform: "ios", name: "Phone" };
130const opened = { _tag: "Success", value: { hostId: "local", deviceId: "phone" } } as const;
131const failed = { _tag: "Failure", cause: new Error("boom") } as const;
132
133const deferred = () => {
134 let settle!: (result: CommandResult) => void;
135 const promise = new Promise<CommandResult>((resolve) => (settle = resolve));
136 return { promise, settle };
137};
138
139let container: HTMLDivElement;
140// Fixed key and a changing threadRef, as RightPanelSurfaceContent mounts it.
141const devicePanel = (threadRef: ScopedThreadRef, surface = picker) => (
142 <DevicePanel
143 key="device-panel"
144 mode="embedded"
145 threadRef={threadRef}
146 surface={surface}
147 visible
148 onDismissSetup={() => undefined}
149 />
150);
151const startButton = () => container.querySelector<HTMLButtonElement>('[aria-label="Start Phone"]');
152const click = (button: HTMLButtonElement | null) =>
153 act(async () => {
154 button!.click();
155 });
156const errors = () => container.querySelectorAll('[role="alert"]');
157
158function setup() {
159 vi.resetAllMocks();
160 mocks.list.mockResolvedValue({ _tag: "Success", value: { hostId: "local", deviceId: "" } });
161 currentState = deviceState;
162 container = document.createElement("div");
163 container.style.width = "480px";
164 container.style.height = "800px";
165}
166
167describe("DevicePanel thread switches", () => {
168 it("keeps the latest pick pending across switches away and back", async () => {
169 setup();
170 const first = deferred();
171 const second = deferred();
172 const latest = deferred();
173 mocks.open
174 .mockReturnValueOnce(first.promise)
175 .mockReturnValueOnce(second.promise)
176 .mockReturnValueOnce(latest.promise);
177 await using screen = await render(devicePanel(threadA), { container });
178 await click(startButton());
179 await screen.rerender(devicePanel(threadB));
180 await click(startButton());
181 await screen.rerender(devicePanel(threadA));
182 await click(startButton());
183
184 await act(async () => first.settle(failed));
185
186 expect(startButton()).toBeNull();
187 expect(errors()).toHaveLength(0);
188 expect(mocks.openDevice).not.toHaveBeenCalled();
189
190 await act(async () => second.settle(opened));
191
192 expect(startButton()).toBeNull();
193 expect(mocks.openDevice.mock.calls).toEqual([[threadB, phoneTarget]]);
194
195 await act(async () => latest.settle(opened));
196
197 expect(startButton()?.disabled).toBe(false);
198 expect(errors()).toHaveLength(0);
199 expect(mocks.openDevice.mock.calls).toEqual([
200 [threadB, phoneTarget],
201 [threadA, phoneTarget],
202 ]);
203 });
204});
205
206describe("DevicePanel device headings", () => {
207 it.each([
208 { inventory: "without an emulator", withEmulator: false },
209 { inventory: "alongside an emulator", withEmulator: true },
210 ])("shows Android Devices above a phone $inventory", async ({ withEmulator }) => {
211 setup();
212 const emulator = { ...phone, platform: "android", version: "Android 15" } as const;
213 const usbPhone = {
214 ...emulator,
215 id: "usb",
216 name: "USB Phone",
217 booted: true,
218 physical: true,
219 } as const;
220 currentState = { ...deviceState, devices: withEmulator ? [emulator, usbPhone] : [usbPhone] };
221 await using screen = await render(devicePanel(threadA), { container });
222
223 const section = screen.getByText(usbPhone.name, { exact: true }).element().closest("section");
224 expect(section).toBeInstanceOf(HTMLElement);
225 await expect
226 .element(
227 page
228 .elementLocator(section!)
229 .getByRole("heading", { name: "Android Devices", exact: true }),
230 )
231 .toBeVisible();
232 });
233});
234
235describe("DevicePanel host probe", () => {
236 it("probes the hosts once while setup shows inside the panel", async () => {
237 setup();
238 currentState = { ...deviceState, onboardingCompleted: false };
239 // An environment no other test probed, so its probe starts fresh.
240 const threadRef = { ...threadA, environmentId: EnvironmentId.make("environment-setup") };
241 await using _screen = await render(devicePanel(threadRef), { container });
242
243 await vi.waitFor(() => expect(mocks.list).toHaveBeenCalled());
244 expect(mocks.list.mock.calls).toEqual([
245 [{ environmentId: threadRef.environmentId, input: {} }],
246 ]);
247 });
248});
249
250describe("DevicePanel discovery warning", () => {
251 it("a dismissal hides only the cause it was made for", async () => {
252 setup();
253 const withCause = (detail: string): DeviceServiceState => ({
254 ...deviceState,
255 hostStatuses: { local: { status: "ready", detail, incompletePlatforms: ["ios"] } },
256 });
257 const warning = "iOS list on This Mac may be incomplete.";
258 currentState = withCause("first cause");
259 await using screen = await render(devicePanel(threadA), { container });
260
261 await screen.getByRole("button", { name: "Dismiss device warning for This Mac" }).click();
262 await screen.rerender(devicePanel(threadA));
263 await expect.element(screen.getByText(warning)).not.toBeInTheDocument();
264
265 currentState = withCause("second cause");
266 await screen.rerender(devicePanel(threadA));
267 await expect.element(screen.getByText(warning)).toBeVisible();
268 });
269});
270
271describe("DevicePanel stopping devices", () => {
272 const tablet = { ...phone, id: "tablet", name: "Tablet", booted: true } as const;
273 const usbPhone = {
274 ...phone,
275 id: "usb",
276 name: "USB Phone",
277 booted: true,
278 physical: true,
279 } as const;
280 const shutdownOf = (device: { readonly id: string }) => [
281 {
282 environmentId: threadA.environmentId,
283 input: { hostId: "local", deviceId: device.id, platform: "ios" },
284 },
285 ];
286
287 it("stops one running device, and stop all stops every running simulator", async () => {
288 setup();
289 const runningPhone = { ...phone, booted: true };
290 currentState = { ...deviceState, devices: [runningPhone, tablet, usbPhone] };
291 mocks.shutdown.mockResolvedValue(opened);
292 await using screen = await render(devicePanel(threadA), { container });
293
294 await expect
295 .element(screen.getByRole("button", { name: "Stop USB Phone" }))
296 .not.toBeInTheDocument();
297 await screen.getByRole("button", { name: "Stop Tablet" }).click();
298 await vi.waitFor(() => expect(mocks.shutdown.mock.calls).toEqual([shutdownOf(tablet)]));
299
300 mocks.shutdown.mockClear();
301 await screen.getByRole("button", { name: "Stop all devices" }).click();
302 await vi.waitFor(() =>
303 expect(mocks.shutdown.mock.calls).toEqual([shutdownOf(runningPhone), shutdownOf(tablet)]),
304 );
305 });
306
307 it("hides stop all when nothing is running and reports a failed stop", async () => {
308 setup();
309 await using screen = await render(devicePanel(threadA), { container });
310 await expect
311 .element(screen.getByRole("button", { name: "Stop all devices" }))
312 .not.toBeInTheDocument();
313
314 currentState = { ...deviceState, devices: [tablet] };
315 mocks.shutdown.mockResolvedValue(failed);
316 await screen.rerender(devicePanel(threadA));
317 await screen.getByRole("button", { name: "Stop Tablet" }).click();
318 await expect.element(screen.getByRole("alert")).toHaveTextContent("Device failed");
319 await expect.element(screen.getByRole("button", { name: "Stop Tablet" })).toBeEnabled();
320 });
321});