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

previewAutomationRequestConsumer.test.ts

407 lines13.1 KB

1import {
2 EnvironmentId,
3 type PreviewAutomationRequest,
4 type PreviewAutomationResponse,
5 type PreviewAutomationStreamEvent,
6 PreviewTabId,
7 ThreadId,
8} from "@t3tools/contracts";
9import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
10import { describe, expect, it, vi } from "vite-plus/test";
11​
12import {
13 PreviewAutomationRecordingNotActiveError,
14 PreviewAutomationTargetUnavailableError,
15 PreviewAutomationViewportTimeoutError,
16} from "./previewAutomationErrors";
17import {
18 createPreviewAutomationRequestConsumerAtom,
19 serializePreviewAutomationError,
20} from "./previewAutomationRequestConsumer";
21​
22const environmentId = EnvironmentId.make("environment-1");
23const threadId = ThreadId.make("thread-1");
24const tabId = PreviewTabId.make("tab-1");
25const clientId = "client-1";
26const connectionId = "connection-1";
27​
28const request = (
29 requestId: string,
30 overrides: Partial<PreviewAutomationRequest> = {},
31): PreviewAutomationRequest => ({
32 requestId,
33 threadId,
34 operation: "status",
35 input: {},
36 timeoutMs: 15_000,
37 ...overrides,
38});
39​
40const requestEvent = (
41 requestId: string,
42 overrides: Partial<PreviewAutomationRequest> = {},
43 eventConnectionId = connectionId,
44): PreviewAutomationStreamEvent => ({
45 type: "request",
46 connectionId: eventConnectionId,
47 request: request(requestId, overrides),
48});
49​
50const consumerState = (handleRequest: (request: PreviewAutomationRequest) => Promise<unknown>) => ({
51 connectionAtom: Atom.make<string | null>(null),
52 requestHandlerAtom: Atom.make({ handle: handleRequest }),
53});
54​
55describe("previewAutomationRequestConsumer", () => {
56 it("acknowledges a replacement stream before consuming requests from it", async () => {
57 const requestsAtom = Atom.make(
58 AsyncResult.success<PreviewAutomationStreamEvent, Error>({
59 type: "connected",
60 connectionId,
61 }),
62 );
63 const handleRequest = vi.fn(async () => undefined);
64 const respond = vi.fn(async () => undefined);
65 const state = consumerState(handleRequest);
66 const consumerAtom = createPreviewAutomationRequestConsumerAtom({
67 requestsAtom,
68 clientId,
69 connectionAtom: state.connectionAtom,
70 environmentId,
71 requestHandlerAtom: state.requestHandlerAtom,
72 respond,
73 label: "test:preview-automation-connected",
74 });
75 const registry = AtomRegistry.make();
76​
77 registry.mount(consumerAtom);
78 registry.set(requestsAtom, AsyncResult.success(requestEvent("request-after-connect")));
79​
80 await vi.waitFor(() => expect(registry.get(state.connectionAtom)).toBe(connectionId));
81 await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
82 expect(handleRequest).toHaveBeenCalledTimes(1);
83 registry.dispose();
84 });
85​
86 it("drops late requests from an older stream generation", async () => {
87 const requestsAtom = Atom.make(
88 AsyncResult.success<PreviewAutomationStreamEvent, Error>({
89 type: "connected",
90 connectionId: "connection-2",
91 }),
92 );
93 const handleRequest = vi.fn(async () => undefined);
94 const respond = vi.fn(async () => undefined);
95 const state = consumerState(handleRequest);
96 const consumerAtom = createPreviewAutomationRequestConsumerAtom({
97 requestsAtom,
98 clientId,
99 connectionAtom: state.connectionAtom,
100 environmentId,
101 requestHandlerAtom: state.requestHandlerAtom,
102 respond,
103 label: "test:preview-automation-stale-generation",
104 });
105 const registry = AtomRegistry.make();
106​
107 registry.mount(consumerAtom);
108 registry.set(
109 requestsAtom,
110 AsyncResult.success(requestEvent("request-stale", {}, "connection-1")),
111 );
112​
113 await vi.waitFor(() => expect(registry.get(state.connectionAtom)).toBe("connection-2"));
114 expect(handleRequest).not.toHaveBeenCalled();
115 expect(respond).not.toHaveBeenCalled();
116 registry.dispose();
117 });
118​
119 it("consumes every request emitted before React can render", async () => {
120 const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
121 AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
122 );
123 const handleRequest = vi.fn(async (value: PreviewAutomationRequest) => ({
124 requestId: value.requestId,
125 }));
126 const responses: PreviewAutomationResponse[] = [];
127 const respond = vi.fn(async (response: PreviewAutomationResponse) => {
128 responses.push(response);
129 });
130 const state = consumerState(handleRequest);
131 const consumerAtom = createPreviewAutomationRequestConsumerAtom({
132 requestsAtom,
133 clientId,
134 connectionAtom: state.connectionAtom,
135 environmentId,
136 requestHandlerAtom: state.requestHandlerAtom,
137 respond,
138 label: "test:preview-automation-consumer",
139 });
140 const registry = AtomRegistry.make();
141 registry.mount(consumerAtom);
142​
143 registry.set(requestsAtom, AsyncResult.success(requestEvent("request-1")));
144 registry.set(requestsAtom, AsyncResult.success(requestEvent("request-2")));
145​
146 await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(2));
147 expect(handleRequest.mock.calls.map(([value]) => value.requestId)).toEqual([
148 "request-1",
149 "request-2",
150 ]);
151 expect(responses.map((response) => response.requestId)).toEqual(["request-1", "request-2"]);
152 registry.dispose();
153 });
154​
155 it("uses the latest request handler without rebuilding the stream consumer", async () => {
156 const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
157 AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
158 );
159 const firstHandler = vi.fn(async () => "first");
160 const secondHandler = vi.fn(async () => "second");
161 const respond = vi.fn(async (_response: PreviewAutomationResponse) => undefined);
162 const state = consumerState(firstHandler);
163 const consumerAtom = createPreviewAutomationRequestConsumerAtom({
164 requestsAtom,
165 clientId,
166 connectionAtom: state.connectionAtom,
167 environmentId,
168 requestHandlerAtom: state.requestHandlerAtom,
169 respond,
170 label: "test:preview-automation-latest-handler",
171 });
172 const registry = AtomRegistry.make();
173 registry.mount(consumerAtom);
174​
175 registry.set(requestsAtom, AsyncResult.success(requestEvent("request-first")));
176 await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
177 registry.set(state.requestHandlerAtom, { handle: secondHandler });
178 registry.set(requestsAtom, AsyncResult.success(requestEvent("request-second")));
179​
180 await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(2));
181 expect(firstHandler).toHaveBeenCalledTimes(1);
182 expect(secondHandler).toHaveBeenCalledTimes(1);
183 expect(respond.mock.calls.map(([response]) => response.result)).toEqual(["first", "second"]);
184 registry.dispose();
185 });
186​
187 it("consumes a request that arrived immediately before the consumer mounted", async () => {
188 const requestsAtom = Atom.make(
189 AsyncResult.success<PreviewAutomationStreamEvent, Error>(requestEvent("request-ready")),
190 );
191 const respond = vi.fn(async (_response: PreviewAutomationResponse) => undefined);
192 const state = consumerState(async () => undefined);
193 const consumerAtom = createPreviewAutomationRequestConsumerAtom({
194 requestsAtom,
195 clientId,
196 connectionAtom: state.connectionAtom,
197 environmentId,
198 requestHandlerAtom: state.requestHandlerAtom,
199 respond,
200 label: "test:preview-automation-initial-request",
201 });
202 const registry = AtomRegistry.make();
203​
204 registry.mount(consumerAtom);
205​
206 await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
207 expect(respond).toHaveBeenCalledWith({
208 clientId,
209 connectionId,
210 requestId: "request-ready",
211 ok: true,
212 });
213 registry.dispose();
214 });
215​
216 it("preserves tagged automation errors and their structured diagnostics", () => {
217 const error = new PreviewAutomationTargetUnavailableError({
218 requestId: "request-1",
219 operation: "click",
220 environmentId,
221 threadId,
222 tabId,
223 bridgeAvailable: false,
224 });
225​
226 expect(
227 serializePreviewAutomationError(error, {
228 requestId: "request-1",
229 operation: "click",
230 environmentId,
231 threadId,
232 tabId,
233 }),
234 ).toEqual({
235 _tag: "PreviewAutomationTabNotFoundError",
236 message:
237 "Preview automation target for click request request-1 is unavailable on environment environment-1 thread thread-1 (tab tab-1, bridge unavailable).",
238 detail: {
239 requestId: "request-1",
240 operation: "click",
241 environmentId: "environment-1",
242 threadId: "thread-1",
243 tabId: "tab-1",
244 bridgeAvailable: false,
245 },
246 });
247 });
248​
249 it("reports a missing recording even when no preview tab remains", () => {
250 const error = new PreviewAutomationRecordingNotActiveError({
251 requestId: "request-recording-stop",
252 environmentId,
253 threadId,
254 tabId: null,
255 });
256​
257 expect(
258 serializePreviewAutomationError(error, {
259 requestId: "request-recording-stop",
260 operation: "recordingStop",
261 environmentId,
262 threadId,
263 tabId: null,
264 }),
265 ).toMatchObject({
266 _tag: "PreviewAutomationExecutionError",
267 detail: { tabId: null },
268 });
269 });
270​
271 it("preserves viewport render timeouts as timeout responses", () => {
272 const error = new PreviewAutomationViewportTimeoutError({
273 requestId: "request-resize",
274 environmentId,
275 threadId,
276 tabId,
277 timeoutMs: 2_500,
278 });
279​
280 expect(
281 serializePreviewAutomationError(error, {
282 requestId: "request-resize",
283 operation: "resize",
284 environmentId,
285 threadId,
286 tabId,
287 }),
288 ).toMatchObject({
289 _tag: "PreviewAutomationTimeoutError",
290 detail: { tabId: "tab-1", timeoutMs: 2_500 },
291 });
292 });
293​
294 it("maps desktop non-editable targets to the public typed response", () => {
295 expect(
296 serializePreviewAutomationError(
297 {
298 _tag: "PreviewAutomationTargetNotEditableError",
299 tabId: "tab-1",
300 selectorKind: "selector",
301 selectorLength: 6,
302 },
303 {
304 requestId: "request-type",
305 operation: "type",
306 environmentId,
307 threadId,
308 tabId,
309 },
310 ),
311 ).toEqual({
312 _tag: "PreviewAutomationTargetNotEditableError",
313 message:
314 "Preview automation type request request-type requires an editable target in tab tab-1.",
315 detail: {
316 requestId: "request-type",
317 operation: "type",
318 environmentId: "environment-1",
319 threadId: "thread-1",
320 tabId: "tab-1",
321 selectorKind: "selector",
322 selectorLength: 6,
323 },
324 });
325 });
326​
327 it("correlates unexpected failures without exposing cause details", () => {
328 const cause = new Error("private bridge token: preview-secret");
329 const context = {
330 requestId: "request-2",
331 operation: "snapshot" as const,
332 environmentId,
333 threadId,
334 tabId,
335 };
336 const response = serializePreviewAutomationError(cause, context);
337​
338 expect(response).toEqual({
339 _tag: "PreviewAutomationExecutionError",
340 message:
341 "Preview automation snapshot request request-2 failed on environment environment-1 thread thread-1 (tab tab-1).",
342 detail: {
343 requestId: "request-2",
344 operation: "snapshot",
345 environmentId: "environment-1",
346 threadId: "thread-1",
347 tabId: "tab-1",
348 },
349 });
350 expect(JSON.stringify(response)).not.toContain("preview-secret");
351 });
352​
353 it("sanitizes unexpected handler failures at the response boundary", async () => {
354 const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
355 AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
356 );
357 const responses: PreviewAutomationResponse[] = [];
358 const state = consumerState(async () => {
359 throw new Error("desktop IPC secret: do-not-return");
360 });
361 const consumerAtom = createPreviewAutomationRequestConsumerAtom({
362 requestsAtom,
363 clientId,
364 connectionAtom: state.connectionAtom,
365 environmentId,
366 requestHandlerAtom: state.requestHandlerAtom,
367 respond: async (response) => {
368 responses.push(response);
369 },
370 label: "test:preview-automation-failure-boundary",
371 });
372 const registry = AtomRegistry.make();
373 registry.mount(consumerAtom);
374​
375 registry.set(
376 requestsAtom,
377 AsyncResult.success(
378 requestEvent("request-failed", {
379 operation: "click",
380 tabId,
381 }),
382 ),
383 );
384​
385 await vi.waitFor(() => expect(responses).toHaveLength(1));
386 expect(responses[0]).toEqual({
387 clientId,
388 connectionId,
389 requestId: "request-failed",
390 ok: false,
391 error: {
392 _tag: "PreviewAutomationExecutionError",
393 message:
394 "Preview automation click request request-failed failed on environment environment-1 thread thread-1 (tab tab-1).",
395 detail: {
396 requestId: "request-failed",
397 operation: "click",
398 environmentId: "environment-1",
399 threadId: "thread-1",
400 tabId: "tab-1",
401 },
402 },
403 });
404 expect(JSON.stringify(responses[0])).not.toContain("do-not-return");
405 registry.dispose();
406 });
407});