Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DevicePanel.browser.test.tsx

291 lines10.1 KB

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