Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 createCdpRelayConnection,
5 type CdpRelayConnection,
6 type CdpRelayTarget,
7} from "./CdpRelay.ts";
8
9const makeTarget = (
10 send: CdpRelayTarget["send"],
11 setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {},
12 ackScreencastFrame: CdpRelayTarget["ackScreencastFrame"] = () => {},
13): CdpRelayTarget => ({
14 send,
15 targetId: async () => "GUEST-TARGET",
16 url: () => "http://localhost:4719/",
17 title: () => "Fixture",
18 userAgent: () => "Electron",
19 setDownloadDirectory,
20 receivesScreencast: () => true,
21 ackScreencastFrame,
22});
23
24const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
25 createCdpRelayConnection(target, write, () => {});
26
27// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
28// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
29const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
30
31describe("CDP relay", () => {
32 it("announces only the tab's page, under its real target id", async () => {
33 const written: Array<Record<string, unknown>> = [];
34 const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
35 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
36 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
37 await settle();
38 const attach = written.findIndex((message) => message["id"] === 1);
39 expect(written.slice(attach, attach + 2)).toEqual([
40 { id: 1, result: {} },
41 {
42 method: "Target.attachedToTarget",
43 params: expect.objectContaining({
44 sessionId: "t3-preview-page",
45 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
46 }),
47 },
48 ]);
49 expect(written).toContainEqual({
50 id: 2,
51 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
52 });
53 });
54
55 it("forwards page commands to the tab and lets a slow one finish last", async () => {
56 const pending: Array<() => void> = [];
57 const send = vi.fn(
58 (method: string) =>
59 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
60 );
61 const written: Array<Record<string, unknown>> = [];
62 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
63 relay.receive(
64 JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
65 );
66 relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" }));
67 pending[1]!();
68 await settle();
69 expect(written).toEqual([
70 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
71 ]);
72 pending[0]!();
73 await settle();
74 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined, undefined);
75 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session", undefined);
76 expect(written.at(-1)).toEqual({
77 id: 5,
78 result: { method: "Page.captureScreenshot" },
79 sessionId: "t3-preview-page",
80 });
81 });
82
83 it("resumes paused child frames, so cross-site iframes run", async () => {
84 const send = vi.fn(async () => ({}));
85 const relay = makeRelay(makeTarget(send), () => {});
86 relay.receive(
87 JSON.stringify({
88 id: 1,
89 method: "Runtime.runIfWaitingForDebugger",
90 sessionId: "t3-preview-page",
91 }),
92 );
93 relay.receive(
94 JSON.stringify({
95 id: 2,
96 method: "Runtime.runIfWaitingForDebugger",
97 sessionId: "iframe-session",
98 }),
99 );
100 await settle();
101 expect(send.mock.calls).toEqual([
102 ["Runtime.runIfWaitingForDebugger", {}, "iframe-session", undefined],
103 ]);
104 });
105
106 // Playwright enables focus emulation on every page it connects to, and Chromium then
107 // counts the guest as captured: a preview the panel hides keeps its timers unthrottled.
108 it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => {
109 const send = vi.fn(async () => ({}));
110 const written: Array<Record<string, unknown>> = [];
111 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
112 relay.receive(
113 JSON.stringify({
114 id: 1,
115 method: "Emulation.setFocusEmulationEnabled",
116 params: { enabled: true },
117 sessionId: "t3-preview-page",
118 }),
119 );
120 await settle();
121 expect(written).toEqual([{ id: 1, result: {}, sessionId: "t3-preview-page" }]);
122 expect(send).not.toHaveBeenCalled();
123 });
124
125 it("routes tab events to the page session once the page is announced", async () => {
126 const written: Array<Record<string, unknown>> = [];
127 const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
128 relay.event("Page.loadEventFired", {}, undefined);
129 expect(written).toEqual([]);
130 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
131 await settle();
132 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
133 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
134 expect(written.slice(-2)).toEqual([
135 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
136 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
137 ]);
138 });
139
140 it("delivers page events after the frame-tree snapshot only once Playwright has its reply", async () => {
141 let answerFrameTree = () => {};
142 let relay: CdpRelayConnection | undefined;
143 const send = vi.fn<CdpRelayTarget["send"]>((method, _params, _sessionId, _owner, received) => {
144 if (method !== "Page.getFrameTree") return Promise.resolve({ method });
145 return new Promise((resolve) => {
146 answerFrameTree = () => {
147 received?.();
148 relay!.event("Page.frameNavigated", { frame: { id: "F" } }, "");
149 resolve({ frameTree: { frame: { id: "F" } } });
150 };
151 });
152 });
153 const written: Array<Record<string, unknown>> = [];
154 relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
155 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
156 await settle();
157 const page = (id: number, method: string) =>
158 relay!.receive(JSON.stringify({ id, method, sessionId: "t3-preview-page" }));
159 page(2, "Page.getFrameTree");
160 page(3, "Runtime.enable");
161 page(4, "Inspector.enable");
162 await settle();
163 // Crash detection stays live; other page commands wait for the snapshot reply.
164 expect(send.mock.calls.map(([method]) => method)).toEqual([
165 "Page.getFrameTree",
166 "Inspector.enable",
167 ]);
168 written.length = 0;
169 answerFrameTree();
170 await settle();
171 expect(written.slice(0, 2)).toEqual([
172 { id: 2, result: { frameTree: { frame: { id: "F" } } }, sessionId: "t3-preview-page" },
173 {
174 method: "Page.frameNavigated",
175 params: { frame: { id: "F" } },
176 sessionId: "t3-preview-page",
177 },
178 ]);
179 expect(send.mock.calls.map(([method]) => method)).toContain("Runtime.enable");
180 });
181});
182
183describe("CDP relay extra sessions", () => {
184 it("gives a second page session the page's commands and events", async () => {
185 const send = vi.fn<CdpRelayTarget["send"]>(async () => ({}));
186 const written: Array<Record<string, unknown>> = [];
187 const nativeAcks: Array<number> = [];
188 const relay = makeRelay(
189 makeTarget(send, undefined, (frameId) => nativeAcks.push(frameId)),
190 (raw) => written.push(JSON.parse(raw)),
191 );
192 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
193 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
194 await settle();
195 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
196 .sessionId;
197 relay.receive(
198 JSON.stringify({
199 id: 3,
200 method: "Target.attachToTarget",
201 params: { targetId: "GUEST-TARGET", flatten: true },
202 sessionId: browserSession,
203 }),
204 );
205 relay.receive(
206 JSON.stringify({
207 id: 4,
208 method: "Target.attachToTarget",
209 params: { targetId: "SOMETHING-ELSE" },
210 sessionId: browserSession,
211 }),
212 );
213 await settle();
214 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
215 .sessionId;
216 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
217 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
218 await settle();
219 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra);
220 written.length = 0;
221 const frame = (frameId: number) =>
222 relay.event("Page.screencastFrame", { data: "x", sessionId: frameId }, undefined);
223 const ack = (sessionId: string, frameId: number) =>
224 relay.receive(
225 JSON.stringify({
226 id: 6,
227 method: "Page.screencastFrameAck",
228 params: { sessionId: frameId },
229 sessionId,
230 }),
231 );
232 const delivered = () => {
233 const frames = written
234 .filter((m) => m["method"])
235 .map((m) => [m["sessionId"], (m["params"] as { sessionId?: number }).sessionId]);
236 written.length = 0;
237 return frames;
238 };
239 frame(1);
240 expect(delivered()).toEqual([
241 ["t3-preview-page", 1],
242 [extra, 1],
243 ]);
244 // A session that has not acknowledged its frame gets only the newest one, on its ack.
245 for (let i = 2; i < 100; i++) frame(i);
246 expect(delivered()).toEqual([]);
247 // Frames every session is busy for stay unacknowledged, so Chromium pauses at its in-flight limit.
248 expect(nativeAcks).toEqual([1]);
249 ack(extra, 1);
250 await settle();
251 expect(delivered()).toEqual([[extra, 99]]);
252 // Each consumer ack lets Chromium send one more frame.
253 expect(nativeAcks).toEqual([1, 2]);
254 ack(extra, 99);
255 await settle();
256 expect(delivered()).toEqual([]);
257 expect(nativeAcks).toEqual([1, 2, 3]);
258 frame(100);
259 expect(delivered()).toEqual([[extra, 100]]);
260 ack(extra, 99);
261 await settle();
262 frame(101);
263 expect(delivered()).toEqual([]);
264 expect(send.mock.calls.some(([method]) => method === "Page.screencastFrameAck")).toBe(false);
265 // A restart keeps the unacknowledged frame's slot until its own acknowledgement.
266 relay.receive(JSON.stringify({ id: 7, method: "Page.stopScreencast", sessionId: extra }));
267 relay.receive(JSON.stringify({ id: 8, method: "Page.startScreencast", sessionId: extra }));
268 await settle();
269 delivered();
270 frame(102);
271 expect(delivered()).toEqual([]);
272 ack(extra, 100);
273 await settle();
274 expect(delivered()).toEqual([[extra, 102]]);
275 // Other events still reach a session while its frame is unacknowledged.
276 relay.event("Page.loadEventFired", { timestamp: 1 }, undefined);
277 expect(delivered().map(([session]) => session)).toEqual(["t3-preview-page", extra]);
278 });
279});
280
281describe("CDP relay downloads", () => {
282 it("captures preview downloads without changing the default browser context", async () => {
283 const send = vi.fn(async () => ({}));
284 const directories: Array<string | null> = [];
285 const written: Array<Record<string, unknown>> = [];
286 const relay = makeRelay(
287 makeTarget(send, (directory) => directories.push(directory)),
288 (raw) => written.push(JSON.parse(raw)),
289 );
290 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
291 relay.receive(
292 JSON.stringify({
293 id: 2,
294 method: "Browser.setDownloadBehavior",
295 params: {
296 behavior: "allowAndName",
297 browserContextId: "t3-preview",
298 downloadPath: "/srv/artifacts",
299 eventsEnabled: true,
300 },
301 }),
302 );
303 await settle();
304 expect(directories).toEqual(["/srv/artifacts"]);
305 expect(send.mock.calls).toEqual([
306 ["Page.setDownloadBehavior", { behavior: "default" }, undefined],
307 ]);
308 written.length = 0;
309 relay.event("Page.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
310 relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");
311 expect(written).toEqual([
312 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
313 { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } },
314 ]);
315 });
316
317 it("keeps denial scoped to the preview and restores Electron's save handling when allowed", async () => {
318 const send = vi.fn(async () => ({}));
319 const directories: Array<string | null> = [];
320 const relay = makeRelay(
321 makeTarget(send, (directory) => directories.push(directory)),
322 () => {},
323 );
324 for (const [id, behavior] of ["deny", "allowAndName"].entries()) {
325 relay.receive(
326 JSON.stringify({
327 id,
328 method: "Browser.setDownloadBehavior",
329 params: { behavior, downloadPath: "/srv/artifacts" },
330 }),
331 );
332 await settle();
333 }
334 expect(directories).toEqual([null, "/srv/artifacts"]);
335 expect(send.mock.calls).toEqual([
336 ["Page.setDownloadBehavior", { behavior: "deny" }, undefined],
337 ["Page.setDownloadBehavior", { behavior: "default" }, undefined],
338 ]);
339 });
340
341 it("does not publish download events when the connection has disabled them", async () => {
342 const written: Array<Record<string, unknown>> = [];
343 const relay = makeRelay(makeTarget(vi.fn(async () => ({}))), (raw) =>
344 written.push(JSON.parse(raw)),
345 );
346 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
347 relay.receive(
348 JSON.stringify({
349 id: 2,
350 method: "Browser.setDownloadBehavior",
351 params: { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: false },
352 }),
353 );
354 await settle();
355 written.length = 0;
356 relay.event("Page.downloadWillBegin", { guid: "g1" }, "");
357 relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");
358 expect(written).toEqual([]);
359 });
360
361 it.each([false, true])(
362 "keeps the previous download configuration (events enabled: %s) when configuration fails",
363 async (enabled) => {
364 const send = vi
365 .fn(async () => ({}))
366 .mockResolvedValueOnce({})
367 .mockRejectedValueOnce(new Error("Page command rejected"));
368 const written: Array<Record<string, unknown>> = [];
369 let directory: string | null = null;
370 const relay = makeRelay(
371 makeTarget(send, (value) => {
372 directory = value;
373 }),
374 (raw) => written.push(JSON.parse(raw)),
375 );
376 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
377 for (const [id, eventsEnabled] of [enabled, !enabled].entries()) {
378 relay.receive(
379 JSON.stringify({
380 id: id + 2,
381 method: "Browser.setDownloadBehavior",
382 params: {
383 behavior: id === 1 && enabled ? "deny" : "allowAndName",
384 downloadPath: id === 0 ? "/srv/artifacts" : "/srv/new-artifacts",
385 eventsEnabled,
386 },
387 }),
388 );
389 await settle();
390 }
391 expect(written).toContainEqual({
392 id: 3,
393 error: { code: -32000, message: "Page command rejected" },
394 });
395 expect(directory).toBe("/srv/artifacts");
396 written.length = 0;
397 relay.event("Page.downloadWillBegin", { guid: "g1" }, "");
398 relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");
399 expect(written).toEqual(
400 enabled
401 ? [
402 { method: "Browser.downloadWillBegin", params: { guid: "g1" } },
403 { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } },
404 ]
405 : [],
406 );
407 },
408 );
409});
410
411describe("CDP relay payload budget", () => {
412 // 2,048 references to one 40 KiB string: about 80 MiB once serialized, little memory here.
413 const oversized = Array(2048).fill("x".repeat(40 * 1024));
414
415 it("fails only an oversized reply and still returns a large screenshot", async () => {
416 const screenshot = "A".repeat(16 * 1024 * 1024);
417 const send = vi.fn(async (method: string) =>
418 method === "DOM.getDocument" ? { nodes: oversized } : { data: screenshot },
419 );
420 const written: Array<Record<string, unknown>> = [];
421 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
422 relay.receive(
423 JSON.stringify({ id: 1, method: "DOM.getDocument", sessionId: "t3-preview-page" }),
424 );
425 relay.receive(
426 JSON.stringify({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
427 );
428 await settle();
429
430 const replies = written.map(({ id, error, result }) => ({
431 id,
432 error,
433 size: (result as { data?: string } | undefined)?.data?.length,
434 }));
435 expect(replies).toEqual([
436 { id: 1, error: { code: -32000, message: "CDP payload too large" }, size: undefined },
437 { id: 2, error: undefined, size: screenshot.length },
438 ]);
439 });
440
441 it.each([
442 { args: oversized },
443 { args: "\u0001".repeat(12 * 1024 * 1024) },
444 { args: Array(2_700_000).fill(-0.0000010000000000000002) },
445 ])("closes instead of dropping an oversized event (%#)", async ({ args }) => {
446 const written: Array<Record<string, unknown>> = [];
447 const close = vi.fn();
448 const relay = createCdpRelayConnection(
449 makeTarget(vi.fn()),
450 (raw) => written.push(JSON.parse(raw)),
451 close,
452 );
453 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
454 await settle();
455 written.length = 0;
456
457 relay.event("Runtime.consoleAPICalled", { args }, "");
458 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
459
460 relay.receive(JSON.stringify({ id: 2, method: "Target.setAutoAttach" }));
461 expect(close).toHaveBeenCalledOnce();
462 expect(written.map((message) => message["method"])).toEqual([]);
463 });
464});
465
466describe("CDP relay reconnects", () => {
467 it("reports the page's default execution context to every connection", async () => {
468 // Electron keeps one debugger attached, so Runtime stays enabled after a client drops,
469 // and the native Runtime.enable announces contexts again only after Runtime.disable.
470 let runtimeEnabled = false;
471 let current: CdpRelayConnection | undefined;
472 const context = {
473 context: { id: 1, origin: "null", name: "", auxData: { isDefault: true, frameId: "F" } },
474 };
475 const send = vi.fn(async (method: string) => {
476 if (method === "Runtime.disable") runtimeEnabled = false;
477 if (method === "Runtime.enable" && !runtimeEnabled) {
478 runtimeEnabled = true;
479 current!.event("Runtime.executionContextCreated", context, "");
480 }
481 return {};
482 });
483 const connect = async () => {
484 const written: Array<Record<string, unknown>> = [];
485 current = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
486 current.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
487 await settle();
488 current.receive(
489 JSON.stringify({ id: 2, method: "Runtime.enable", sessionId: "t3-preview-page" }),
490 );
491 await settle();
492 return written.filter((m) => m["method"] === "Runtime.executionContextCreated");
493 };
494 const expected = [
495 {
496 method: "Runtime.executionContextCreated",
497 params: context,
498 sessionId: "t3-preview-page",
499 },
500 ];
501 expect(await connect()).toEqual(expected);
502 expect(await connect()).toEqual(expected);
503 });
504});