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 { 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: () => ({
80 byThreadKey: {},
81 openDevice: mocks.openDevice,
82 closeSurface: mocks.closeSurface,
83 }),
84 },
85 selectThreadRightPanelState: () => ({ isOpen: false, activeSurfaceId: null, surfaces: [] }),
86}));
87vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
88vi.mock("~/components/device/DeviceWorkspace", () => ({
89 DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
90 <button onClick={onPowerOff}>Power off</button>
91 ),
92}));
93vi.mock("~/components/preview/PreviewPanelShell", () => ({
94 PreviewPanelShell: ({ children }: { children: ReactNode }) => (
95 <div className="flex h-full min-h-0 flex-col">{children}</div>
96 ),
97}));
98
99const threadA = {
100 environmentId: EnvironmentId.make("environment-a"),
101 threadId: ThreadId.make("thread-1"),
102};
103// The panel stays mounted across both kinds of switch.
104const switches = [
105 ["another thread", { environmentId: threadA.environmentId, threadId: ThreadId.make("thread-2") }],
106 [
107 "the same thread id in another environment",
108 { ...threadA, environmentId: EnvironmentId.make("environment-b") },
109 ],
110] as const;
111const threadB = switches[0][1];
112const picker: Extract<RightPanelSurface, { kind: "device" }> = { id: "device", kind: "device" };
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 container: HTMLDivElement;
124// Fixed key and a changing threadRef, as RightPanelSurfaceContent mounts it.
125const devicePanel = (threadRef: ScopedThreadRef, surface = picker) => (
126 <DevicePanel
127 key="device-panel"
128 mode="embedded"
129 threadRef={threadRef}
130 surface={surface}
131 visible
132 onDismissSetup={() => undefined}
133 />
134);
135const startButton = () => container.querySelector<HTMLButtonElement>('[aria-label="Start Phone"]');
136const click = (button: HTMLButtonElement | null) =>
137 act(async () => {
138 button!.click();
139 });
140const errors = () => container.querySelectorAll('[role="alert"]');
141
142function setup() {
143 vi.resetAllMocks();
144 currentState = deviceState;
145 container = document.createElement("div");
146 container.style.width = "480px";
147 container.style.height = "800px";
148}
149
150describe("DevicePanel thread switches", () => {
151 it("keeps the latest pick pending across switches away and back", async () => {
152 setup();
153 const first = deferred();
154 const second = deferred();
155 const latest = deferred();
156 mocks.open
157 .mockReturnValueOnce(first.promise)
158 .mockReturnValueOnce(second.promise)
159 .mockReturnValueOnce(latest.promise);
160 await using screen = await render(devicePanel(threadA), { container });
161 await click(startButton());
162 await screen.rerender(devicePanel(threadB));
163 await click(startButton());
164 await screen.rerender(devicePanel(threadA));
165 await click(startButton());
166
167 await act(async () => first.settle(failed));
168
169 expect(startButton()).toBeNull();
170 expect(errors()).toHaveLength(0);
171 expect(mocks.openDevice).not.toHaveBeenCalled();
172
173 await act(async () => second.settle(opened));
174
175 expect(startButton()).toBeNull();
176 expect(mocks.openDevice.mock.calls).toEqual([[threadB, phoneTarget]]);
177
178 await act(async () => latest.settle(opened));
179
180 expect(startButton()?.disabled).toBe(false);
181 expect(errors()).toHaveLength(0);
182 expect(mocks.openDevice.mock.calls).toEqual([
183 [threadB, phoneTarget],
184 [threadA, phoneTarget],
185 ]);
186 });
187});