Open History to see the last commit
1import {
2 EnvironmentId,
3 ThreadId,
4 type DeviceServiceState,
5 type ScopedThreadRef,
6} from "@t3tools/contracts";
7import { act, type ReactNode } from "react";
8import { createRoot, type Root } from "react-dom/client";
9import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10
11import type { RightPanelSurface } from "~/rightPanelStore";
12
13import { DevicePanel } from "./DevicePanel";
14import "~/index.css";
15
16type CommandResult =
17 | { _tag: "Success"; value: { hostId: string; deviceId: string } }
18 | { _tag: "Failure"; cause: unknown };
19const mocks = vi.hoisted(() => ({
20 open: vi.fn<(request: unknown) => Promise<CommandResult>>(),
21 close: vi.fn<(request: unknown) => Promise<CommandResult>>(),
22 openDevice: vi.fn(),
23 closeSurface: vi.fn(),
24}));
25const phone = {
26 hostId: "local",
27 id: "phone",
28 name: "Phone",
29 platform: "ios",
30 version: "iOS 19",
31 booted: false,
32 physical: false,
33} as const;
34const deviceState: DeviceServiceState = {
35 hosts: [
36 {
37 id: "local",
38 kind: "local",
39 label: "This Mac",
40 platforms: [{ platform: "ios", available: true }],
41 hubInstalled: true,
42 agentDeviceInstalled: true,
43 },
44 ],
45 hostStatus: "ready",
46 hostStatuses: { local: { status: "ready" } },
47 devices: [phone],
48 sessions: [
49 {
50 threadId: ThreadId.make("thread-1"),
51 hostId: "local",
52 deviceId: "phone",
53 platform: "ios",
54 openedAt: "2026-01-01T00:00:00.000Z",
55 },
56 ],
57 onboardingCompleted: true,
58 agentAccessEnabled: true,
59 hubBasePath: "/api/device-hub",
60 revision: 1,
61};
62let currentState = deviceState;
63vi.mock("~/state/device", () => ({
64 deviceEnvironment: { list: "list", open: "open", close: "close" },
65 useDeviceState: () => ({ state: currentState, loaded: true }),
66}));
67vi.mock("~/state/use-atom-command", () => ({
68 useAtomCommand: (command: string) =>
69 command === "open"
70 ? mocks.open
71 : command === "close"
72 ? mocks.close
73 : () => Promise.resolve({ _tag: "Success", value: {} }),
74}));
75vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));
76vi.mock("~/rightPanelStore", () => ({
77 useRightPanelStore: {
78 getState: () => ({ openDevice: mocks.openDevice, closeSurface: mocks.closeSurface }),
79 },
80}));
81vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
82vi.mock("~/components/device/DeviceWorkspace", () => ({
83 DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
84 <button onClick={onPowerOff}>Power off</button>
85 ),
86}));
87vi.mock("~/components/preview/PreviewPanelShell", () => ({
88 PreviewPanelShell: ({ children }: { children: ReactNode }) => (
89 <div className="flex h-full min-h-0 flex-col">{children}</div>
90 ),
91}));
92
93const threadA = {
94 environmentId: EnvironmentId.make("environment-a"),
95 threadId: ThreadId.make("thread-1"),
96};
97// The panel stays mounted across both kinds of switch.
98const switches = [
99 ["another thread", { environmentId: threadA.environmentId, threadId: ThreadId.make("thread-2") }],
100 [
101 "the same thread id in another environment",
102 { ...threadA, environmentId: EnvironmentId.make("environment-b") },
103 ],
104] as const;
105const threadB = switches[0][1];
106const otherEnvironment = switches[1][1];
107const picker: Extract<RightPanelSurface, { kind: "device" }> = { id: "device", kind: "device" };
108const streaming: Extract<RightPanelSurface, { kind: "device" }> = {
109 id: "device:phone",
110 kind: "device",
111 target: { hostId: "local", deviceId: "phone", platform: "ios", name: "Phone" },
112};
113const phoneTarget = { hostId: "local", deviceId: "phone", platform: "ios", name: "Phone" };
114const opened = { _tag: "Success", value: { hostId: "local", deviceId: "phone" } } as const;
115const failed = { _tag: "Failure", cause: new Error("boom") } as const;
116
117const deferred = () => {
118 let settle!: (result: CommandResult) => void;
119 const promise = new Promise<CommandResult>((resolve) => (settle = resolve));
120 return { promise, settle };
121};
122
123let root: Root;
124let container: HTMLDivElement;
125// Fixed key and a changing threadRef, as RightPanelSurfaceContent mounts it.
126const show = (threadRef: ScopedThreadRef, surface = picker) =>
127 act(async () =>
128 root.render(
129 <DevicePanel
130 key="device-panel"
131 mode="embedded"
132 threadRef={threadRef}
133 surface={surface}
134 visible
135 onDismissSetup={() => undefined}
136 />,
137 ),
138 );
139const startButton = () => container.querySelector<HTMLButtonElement>('[aria-label="Start Phone"]');
140const click = (button: HTMLButtonElement | null) =>
141 act(async () => {
142 button!.click();
143 });
144const errors = () => container.querySelectorAll('[role="alert"]');
145
146beforeEach(() => {
147 vi.resetAllMocks();
148 currentState = deviceState;
149 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
150 container = document.createElement("div");
151 container.style.width = "480px";
152 container.style.height = "800px";
153 document.body.append(container);
154 root = createRoot(container);
155});
156afterEach(async () => {
157 await act(() => root.unmount());
158 container.remove();
159 vi.unstubAllGlobals();
160});
161
162describe("DevicePanel notices", () => {
163 it("keeps discovery warnings dismissed until the diagnostic or environment changes", async () => {
164 currentState = {
165 ...deviceState,
166 hostStatusDetail: "Could not read simulator usage timestamps.",
167 };
168 await show(threadA);
169 expect(errors()).toHaveLength(1);
170 expect(startButton()?.disabled).toBe(false);
171 await click(container.querySelector('[aria-label="Dismiss device warning"]'));
172 expect(errors()).toHaveLength(0);
173 await show(threadA);
174 expect(errors()).toHaveLength(0);
175
176 currentState = { ...currentState, hostStatusDetail: "A different discovery warning." };
177 await show(threadA);
178 expect(errors()).toHaveLength(1);
179 await click(container.querySelector('[aria-label="Dismiss device warning"]'));
180 await show(otherEnvironment);
181 expect(errors()).toHaveLength(1);
182 });
183
184 it("keeps the loading content centered when discovery and boot notices arrive or are dismissed", async () => {
185 const pick = deferred();
186 mocks.open.mockReturnValue(pick.promise);
187 await show(threadA);
188 await click(startButton());
189 const loadingBounds = () =>
190 container
191 .querySelector('[aria-label="Step 1 of 2: open device"]')!
192 .parentElement!.getBoundingClientRect();
193 const before = loadingBounds();
194 const panel = container.getBoundingClientRect();
195 expect(before.height).toBeGreaterThan(0);
196 expect(before.top + before.height / 2).toBeCloseTo(panel.top + panel.height / 2, 0);
197
198 currentState = {
199 ...deviceState,
200 hostStatusDetail: "Could not read CoreSimulator plist.\n".repeat(8),
201 bootingDevices: [{ ...phone, threadId: threadA.threadId }],
202 };
203 await show(threadA);
204 expect(loadingBounds().top).toBe(before.top);
205 expect(loadingBounds().left).toBe(before.left);
206 await click(container.querySelector('[aria-label="Dismiss device warning"]'));
207 expect(loadingBounds().top).toBe(before.top);
208 expect(loadingBounds().left).toBe(before.left);
209 await act(async () => pick.settle(failed));
210 });
211});
212
213describe("DevicePanel thread switches", () => {
214 it.each(switches)("does not carry a pending or failed pick to %s", async (_, target) => {
215 const pick = deferred();
216 mocks.open.mockReturnValue(pick.promise);
217 await show(threadA);
218 await click(startButton());
219 expect(startButton()).toBeNull();
220
221 await show(target);
222 expect(startButton()?.disabled).toBe(false);
223
224 await act(async () => pick.settle(failed));
225 expect(errors()).toHaveLength(0);
226 expect(mocks.openDevice).not.toHaveBeenCalled();
227
228 await show(threadA);
229 expect(startButton()?.disabled).toBe(false);
230 expect(errors()).toHaveLength(1);
231
232 await show(target);
233 expect(startButton()?.disabled).toBe(false);
234 expect(errors()).toHaveLength(0);
235 });
236
237 it.each([
238 [
239 "pick",
240 picker,
241 () => mocks.open,
242 () => click(startButton()),
243 () => expect(mocks.openDevice).toHaveBeenCalledExactlyOnceWith(threadA, phoneTarget),
244 ],
245 [
246 "power-off",
247 streaming,
248 () => mocks.close,
249 () => click(container.querySelector("button")),
250 () => expect(mocks.closeSurface).toHaveBeenCalledExactlyOnceWith(threadA, streaming.id),
251 ],
252 ] as const)(
253 "applies a late %s to its starting thread after switching environments with the same thread id",
254 async (_, surface, command, start, expectApplied) => {
255 const late = deferred();
256 command().mockReturnValue(late.promise);
257 await show(threadA, surface);
258 await start();
259
260 await show(otherEnvironment, surface);
261 await act(async () => late.settle(opened));
262
263 expectApplied();
264 },
265 );
266
267 it("keeps a late power-off error in the environment that started it", async () => {
268 const powerOff = deferred();
269 mocks.close.mockReturnValue(powerOff.promise);
270 await show(threadA, streaming);
271 await click(container.querySelector("button"));
272
273 await show(otherEnvironment, streaming);
274 await act(async () => powerOff.settle(failed));
275
276 expect(errors()).toHaveLength(0);
277 expect(mocks.closeSurface).not.toHaveBeenCalled();
278 await show(threadA, streaming);
279 expect(errors()).toHaveLength(1);
280 });
281
282 it("keeps the latest pick pending across switches away and back", async () => {
283 const first = deferred();
284 const second = deferred();
285 const latest = deferred();
286 mocks.open
287 .mockReturnValueOnce(first.promise)
288 .mockReturnValueOnce(second.promise)
289 .mockReturnValueOnce(latest.promise);
290 await show(threadA);
291 await click(startButton());
292 await show(threadB);
293 await click(startButton());
294 await show(threadA);
295 await click(startButton());
296
297 await act(async () => first.settle(failed));
298
299 expect(startButton()).toBeNull();
300 expect(errors()).toHaveLength(0);
301 expect(mocks.openDevice).not.toHaveBeenCalled();
302
303 await act(async () => second.settle(opened));
304
305 expect(startButton()).toBeNull();
306 expect(mocks.openDevice.mock.calls).toEqual([[threadB, phoneTarget]]);
307
308 await act(async () => latest.settle(opened));
309
310 expect(startButton()?.disabled).toBe(false);
311 expect(errors()).toHaveLength(0);
312 expect(mocks.openDevice.mock.calls).toEqual([
313 [threadB, phoneTarget],
314 [threadA, phoneTarget],
315 ]);
316 });
317});