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

PreviewAutomationHosts.test.tsx

363 lines12.3 KB

1import {
2 DEFAULT_CLIENT_SETTINGS,
3 EnvironmentId,
4 ThreadId,
5 type ClientSettings,
6 type PreviewAutomationResponse,
7 type PreviewAutomationStreamEvent,
8 type PreviewOpenInput,
9 type PreviewSessionSnapshot,
10} from "@t3tools/contracts";
11import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
12import * as Cause from "effect/Cause";
13import { AsyncResult, Atom } from "effect/unstable/reactivity";
14import { act } from "react";
15import { create, type ReactTestRenderer } from "react-test-renderer";
16import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
17​
18import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
19import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
20import { __resetClientSettingsPersistenceForTests } from "~/hooks/useSettings";
21import {
22 applyPreviewServerSnapshot,
23 readThreadPreviewState,
24 resetPreviewStateForTests,
25 applyPreviewDesktopState,
26} from "~/previewStateStore";
27import { appAtomRegistry, AppAtomRegistryProvider } from "~/rpc/atomRegistry";
28​
29import { PreviewAutomationHosts } from "./PreviewAutomationHosts";
30​
31const mocks = vi.hoisted(() => ({
32 getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
33 setClientSettings: vi.fn(),
34 open: vi.fn(async (_target: { environmentId: EnvironmentId; input: PreviewOpenInput }) =>
35 AsyncResult.success(snapshot),
36 ),
37 list: vi.fn(async () => AsyncResult.success(emptyList)),
38 resize: vi.fn(),
39 respond:
40 vi.fn<
41 (target: { environmentId: EnvironmentId; input: PreviewAutomationResponse }) => Promise<void>
42 >(),
43 focus: vi.fn<() => Promise<AtomCommandResult<void, Error>>>(),
44}));
45​
46vi.mock("~/localApi", () => ({
47 ensureLocalApi: () => ({ persistence: mocks }),
48}));
49vi.mock("~/env", () => ({ isElectron: true }));
50vi.mock("~/state/environments", () => ({
51 useEnvironments: () => ({ environments: [{ environmentId }] }),
52}));
53vi.mock("~/state/preview", () => ({
54 previewEnvironment: {
55 automationRequests: () => requestsAtom,
56 list: () => listAtom,
57 open: mocks.open,
58 resize: mocks.resize,
59 respondToAutomation: mocks.respond,
60 focusAutomationHost: mocks.focus,
61 },
62}));
63vi.mock("~/state/use-atom-command", () => ({
64 useAtomCommand: (command: unknown) => command,
65}));
66vi.mock("~/state/use-atom-query-runner", () => ({
67 useAtomQueryRunner: () => mocks.list,
68}));
69vi.mock("./previewBridge", () => ({ previewBridge: { automation: {} } }));
70​
71const environmentId = EnvironmentId.make("automation-environment");
72const threadId = ThreadId.make("automation-thread");
73const threadRef = { environmentId, threadId };
74const viewport = { _tag: "freeform", width: 1440, height: 900 } as const;
75const savedSettings: ClientSettings = {
76 ...DEFAULT_CLIENT_SETTINGS,
77 browserDefaultViewport: viewport,
78 browserDefaultProfileId: "work",
79 browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
80};
81const snapshot: PreviewSessionSnapshot = {
82 threadId,
83 tabId: "automation-tab",
84 navStatus: { _tag: "Idle" },
85 canGoBack: false,
86 canGoForward: false,
87 viewport,
88 profileId: "work",
89 updatedAt: "2026-09-05T00:00:00.000Z",
90};
91const emptyList = { sessions: [], serverEpoch: "test-server", revision: 0 };
92const listAtom = Atom.make(AsyncResult.success(emptyList));
93const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
94 AsyncResult.initial(false),
95);
96const requestEvent: PreviewAutomationStreamEvent = {
97 type: "request",
98 connectionId: "automation-connection",
99 request: {
100 requestId: "open-request",
101 threadId,
102 operation: "open",
103 input: { open: false, reuseExistingTab: false },
104 timeoutMs: 15_000,
105 },
106};
107​
108function deferred<A>() {
109 let resolve!: (value: A) => void;
110 const promise = new Promise<A>((complete) => {
111 resolve = complete;
112 });
113 return { promise, resolve };
115​
116let renderer: ReactTestRenderer | null = null;
117​
118beforeEach(async () => {
119 vi.clearAllMocks();
120 mocks.getClientSettings.mockReset().mockResolvedValue(savedSettings);
121 mocks.respond.mockReset();
122 mocks.focus.mockReset().mockResolvedValue(AsyncResult.success(undefined));
123 __resetClientSettingsPersistenceForTests();
124 resetPreviewStateForTests();
125 useBrowserSurfaceStore.setState({ byTabId: {} });
126 appAtomRegistry.set(requestsAtom, AsyncResult.initial(false));
127 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
128 vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
129 vi.stubGlobal(
130 "document",
131 Object.assign(new EventTarget(), {
132 hasFocus: () => false,
133 visibilityState: "visible",
134 querySelectorAll: () => [],
135 }),
136 );
137 await act(() => {
138 renderer = create(
139 <AppAtomRegistryProvider>
140 <PreviewAutomationHosts />
141 </AppAtomRegistryProvider>,
142 );
143 });
144});
145​
146afterEach(async () => {
147 await act(() => renderer?.unmount());
148 renderer = null;
149 resetPreviewStateForTests();
150 __resetClientSettingsPersistenceForTests();
151 vi.unstubAllGlobals();
152 vi.restoreAllMocks();
153});
154​
155describe("PreviewAutomationHosts open", () => {
156 it("waits for saved settings before opening a tab with the configured profile and viewport", async () => {
157 const readStarted = deferred<void>();
158 const read = deferred<ClientSettings>();
159 const response = deferred<PreviewAutomationResponse>();
160 mocks.getClientSettings.mockImplementationOnce(() => {
161 readStarted.resolve();
162 return read.promise;
163 });
164 mocks.respond.mockImplementationOnce(async ({ input }) => response.resolve(input));
165​
166 await act(async () => {
167 appAtomRegistry.set(requestsAtom, AsyncResult.success(requestEvent));
168 await readStarted.promise;
169 });
170 expect(mocks.open).not.toHaveBeenCalled();
171​
172 await act(async () => {
173 read.resolve(savedSettings);
174 await response.promise;
175 });
176​
177 expect(mocks.open).toHaveBeenCalledExactlyOnceWith({
178 environmentId,
179 input: { threadId, viewport, profileId: "work" },
180 });
181 expect(mocks.getClientSettings).toHaveBeenCalledOnce();
182 await expect(response.promise).resolves.toMatchObject({
183 requestId: "open-request",
184 ok: true,
185 result: { available: false, tabId: snapshot.tabId },
186 });
187 expect(readThreadPreviewState(threadRef).snapshot).toEqual(snapshot);
188 expect(mocks.setClientSettings).not.toHaveBeenCalled();
189 });
190​
191 it("reports a settings read failure without opening a tab", async () => {
192 vi.spyOn(console, "error").mockImplementation(() => undefined);
193 mocks.getClientSettings.mockRejectedValueOnce(new Error("Settings read failed"));
194 const response = deferred<PreviewAutomationResponse>();
195 mocks.respond.mockImplementationOnce(async ({ input }) => response.resolve(input));
196​
197 await act(async () => {
198 appAtomRegistry.set(requestsAtom, AsyncResult.success(requestEvent));
199 await response.promise;
200 });
201​
202 await expect(response.promise).resolves.toMatchObject({
203 requestId: "open-request",
204 ok: false,
205 error: { _tag: "PreviewAutomationExecutionError" },
206 });
207 expect(mocks.getClientSettings).toHaveBeenCalledOnce();
208 expect(mocks.open).not.toHaveBeenCalled();
209 expect(readThreadPreviewState(threadRef).snapshot).toBeNull();
210 expect(mocks.setClientSettings).not.toHaveBeenCalled();
211 });
212});
213​
214describe("PreviewAutomationHosts ownership", () => {
215 it("reports only local live tabs and removes ownership when their web contents close", async () => {
216 await act(() => {
217 appAtomRegistry.set(
218 requestsAtom,
219 AsyncResult.success({ type: "connected", connectionId: "automation-connection" }),
220 );
221 applyPreviewServerSnapshot(threadRef, snapshot);
222 });
223 expect(mocks.focus).toHaveBeenLastCalledWith(
224 expect.objectContaining({ input: expect.objectContaining({ liveTabs: [] }) }),
225 );
226 const overlay = {
227 hasWebContents: true,
228 canGoBack: false,
229 canGoForward: false,
230 loading: false,
231 zoomFactor: 1,
232 pictureInPicture: false,
233 colorScheme: "system" as const,
234 audioMuted: false,
235 audible: false,
236 controller: "none" as const,
237 favicon: null,
238 };
239 await act(() => applyPreviewDesktopState(threadRef, snapshot.tabId, overlay));
240 expect(mocks.focus).toHaveBeenLastCalledWith(
241 expect.objectContaining({
242 input: expect.objectContaining({
243 liveTabs: [{ threadId, tabId: snapshot.tabId, visible: false }],
244 }),
245 }),
246 );
247 const reportCount = mocks.focus.mock.calls.length;
248 await act(() =>
249 applyPreviewDesktopState(threadRef, snapshot.tabId, { ...overlay, loading: true }),
250 );
251 expect(mocks.focus).toHaveBeenCalledTimes(reportCount);
252 const runtimeTabId = previewRuntimeTabId(threadRef, null, snapshot.tabId);
253 const owner = Symbol();
254 await act(() => {
255 useBrowserSurfaceStore.getState().claim(runtimeTabId, owner, false);
256 useBrowserSurfaceStore
257 .getState()
258 .present(runtimeTabId, owner, { x: 0, y: 0, width: 800, height: 600 }, true, 0, 1);
259 });
260 expect(mocks.focus).toHaveBeenLastCalledWith(
261 expect.objectContaining({
262 input: expect.objectContaining({
263 liveTabs: [{ threadId, tabId: snapshot.tabId, visible: true }],
264 }),
265 }),
266 );
267 for (const visibilityState of ["hidden", "visible"]) {
268 await act(() => {
269 Object.assign(document, { visibilityState });
270 document.dispatchEvent(new Event("visibilitychange"));
271 });
272 expect(mocks.focus).toHaveBeenLastCalledWith(
273 expect.objectContaining({
274 input: expect.objectContaining({
275 focused: false,
276 liveTabs: [{ threadId, tabId: snapshot.tabId, visible: visibilityState === "visible" }],
277 }),
278 }),
279 );
280 }
281 await act(() => {
282 appAtomRegistry.set(
283 requestsAtom,
284 AsyncResult.success({ type: "connected", connectionId: "reconnected" }),
285 );
286 });
287 expect(mocks.focus).toHaveBeenLastCalledWith(
288 expect.objectContaining({
289 input: expect.objectContaining({
290 connectionId: "reconnected",
291 liveTabs: [{ threadId, tabId: snapshot.tabId, visible: true }],
292 }),
293 }),
294 );
295 await act(() =>
296 applyPreviewDesktopState(threadRef, snapshot.tabId, { ...overlay, hasWebContents: false }),
297 );
298 expect(mocks.focus).toHaveBeenLastCalledWith(
299 expect.objectContaining({ input: expect.objectContaining({ liveTabs: [] }) }),
300 );
301 });
302​
303 it.each([false, true])(
304 "retries failed reports without clearing newer connection reports (reconnect: %s)",
305 async (reconnect) => {
306 const report = deferred<Awaited<ReturnType<typeof mocks.focus>>>();
307 mocks.focus.mockReturnValueOnce(report.promise);
308 await act(() => {
309 appAtomRegistry.set(
310 requestsAtom,
311 AsyncResult.success({ type: "connected", connectionId: "first" }),
312 );
313 });
314 if (reconnect) {
315 await act(() => {
316 appAtomRegistry.set(
317 requestsAtom,
318 AsyncResult.success({ type: "connected", connectionId: "second" }),
319 );
320 });
321 }
322 await act(async () => {
323 report.resolve(AsyncResult.failure(Cause.fail(new Error("Focus report failed"))));
324 await report.promise;
325 });
326 expect(mocks.focus).toHaveBeenCalledTimes(reconnect ? 2 : 1);
327 await act(() => {
328 document.dispatchEvent(new Event("visibilitychange"));
329 });
330 expect(mocks.focus).toHaveBeenCalledTimes(2);
331 expect(mocks.focus).toHaveBeenLastCalledWith(
332 expect.objectContaining({
333 input: expect.objectContaining({ connectionId: reconnect ? "second" : "first" }),
334 }),
335 );
336 },
337 );
338​
339 it("does not claim an available runtime from a server snapshot alone", async () => {
340 const response = deferred<PreviewAutomationResponse>();
341 mocks.respond.mockImplementationOnce(async ({ input }) => response.resolve(input));
342 await act(async () => {
343 applyPreviewServerSnapshot(threadRef, snapshot);
344 appAtomRegistry.set(
345 requestsAtom,
346 AsyncResult.success({
347 ...requestEvent,
348 request: {
349 ...requestEvent.request,
350 operation: "status",
351 tabId: snapshot.tabId,
352 input: {},
353 },
354 }),
355 );
356 await response.promise;
357 });
358 await expect(response.promise).resolves.toMatchObject({
359 ok: true,
360 result: { available: false, tabId: snapshot.tabId },
361 });
362 });
363});