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

DevicePanel.browser.test.tsx

182 lines5.7 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 openDevice: vi.fn(),
24 closeSurface: vi.fn(),
25}));
26const phone = {
27 hostId: "local",
28 id: "phone",
29 name: "Phone",
30 platform: "ios",
31 version: "iOS 19",
32 booted: false,
33 physical: false,
34} as const;
35const deviceState: DeviceServiceState = {
36 hosts: [
37 {
38 id: "local",
39 kind: "local",
40 label: "This Mac",
41 platforms: [{ platform: "ios", available: true }],
42 hubInstalled: true,
43 agentDeviceInstalled: true,
44 },
45 ],
46 hostStatus: "ready",
47 hostStatuses: { local: { status: "ready" } },
48 devices: [phone],
49 sessions: [
50 {
51 threadId: ThreadId.make("thread-1"),
52 hostId: "local",
53 deviceId: "phone",
54 platform: "ios",
55 openedAt: "2026-01-01T00:00:00.000Z",
56 },
57 ],
58 onboardingCompleted: true,
59 agentAccessEnabled: true,
60 hubBasePath: "/api/device-hub",
61 revision: 1,
62};
63let currentState = deviceState;
64vi.mock("~/state/device", () => ({
65 deviceEnvironment: { list: "list", open: "open", close: "close" },
66 useDeviceState: () => ({ state: currentState, loaded: true }),
67}));
68vi.mock("~/state/use-atom-command", () => ({
69 useAtomCommand: (command: string) =>
70 command === "open"
71 ? mocks.open
72 : command === "close"
73 ? mocks.close
74 : () => Promise.resolve({ _tag: "Success", value: {} }),
75}));
76vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));
77vi.mock("~/rightPanelStore", () => ({
78 useRightPanelStore: {
79 getState: () => ({ openDevice: mocks.openDevice, closeSurface: mocks.closeSurface }),
80 },
81}));
82vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
83vi.mock("~/components/device/DeviceWorkspace", () => ({
84 DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
85 <button onClick={onPowerOff}>Power off</button>
86 ),
87}));
88vi.mock("~/components/preview/PreviewPanelShell", () => ({
89 PreviewPanelShell: ({ children }: { children: ReactNode }) => (
90 <div className="flex h-full min-h-0 flex-col">{children}</div>
91 ),
92}));
93​
94const threadA = {
95 environmentId: EnvironmentId.make("environment-a"),
96 threadId: ThreadId.make("thread-1"),
97};
98// The panel stays mounted across both kinds of switch.
99const switches = [
100 ["another thread", { environmentId: threadA.environmentId, threadId: ThreadId.make("thread-2") }],
101 [
102 "the same thread id in another environment",
103 { ...threadA, environmentId: EnvironmentId.make("environment-b") },
104 ],
105] as const;
106const threadB = switches[0][1];
107const picker: Extract<RightPanelSurface, { kind: "device" }> = { id: "device", kind: "device" };
108const phoneTarget = { hostId: "local", deviceId: "phone", platform: "ios", name: "Phone" };
109const opened = { _tag: "Success", value: { hostId: "local", deviceId: "phone" } } as const;
110const failed = { _tag: "Failure", cause: new Error("boom") } as const;
111​
112const deferred = () => {
113 let settle!: (result: CommandResult) => void;
114 const promise = new Promise<CommandResult>((resolve) => (settle = resolve));
115 return { promise, settle };
116};
117​
118let container: HTMLDivElement;
119// Fixed key and a changing threadRef, as RightPanelSurfaceContent mounts it.
120const devicePanel = (threadRef: ScopedThreadRef, surface = picker) => (
121 <DevicePanel
122 key="device-panel"
123 mode="embedded"
124 threadRef={threadRef}
125 surface={surface}
126 visible
127 onDismissSetup={() => undefined}
128 />
129);
130const startButton = () => container.querySelector<HTMLButtonElement>('[aria-label="Start Phone"]');
131const click = (button: HTMLButtonElement | null) =>
132 act(async () => {
133 button!.click();
134 });
135const errors = () => container.querySelectorAll('[role="alert"]');
136​
137function setup() {
138 vi.resetAllMocks();
139 currentState = deviceState;
140 container = document.createElement("div");
141 container.style.width = "480px";
142 container.style.height = "800px";
144​
145describe("DevicePanel thread switches", () => {
146 it("keeps the latest pick pending across switches away and back", async () => {
147 setup();
148 const first = deferred();
149 const second = deferred();
150 const latest = deferred();
151 mocks.open
152 .mockReturnValueOnce(first.promise)
153 .mockReturnValueOnce(second.promise)
154 .mockReturnValueOnce(latest.promise);
155 await using screen = await render(devicePanel(threadA), { container });
156 await click(startButton());
157 await screen.rerender(devicePanel(threadB));
158 await click(startButton());
159 await screen.rerender(devicePanel(threadA));
160 await click(startButton());
161​
162 await act(async () => first.settle(failed));
163​
164 expect(startButton()).toBeNull();
165 expect(errors()).toHaveLength(0);
166 expect(mocks.openDevice).not.toHaveBeenCalled();
167​
168 await act(async () => second.settle(opened));
169​
170 expect(startButton()).toBeNull();
171 expect(mocks.openDevice.mock.calls).toEqual([[threadB, phoneTarget]]);
172​
173 await act(async () => latest.settle(opened));
174​
175 expect(startButton()?.disabled).toBe(false);
176 expect(errors()).toHaveLength(0);
177 expect(mocks.openDevice.mock.calls).toEqual([
178 [threadB, phoneTarget],
179 [threadA, phoneTarget],
180 ]);
181 });
182});