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