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

DesktopBrowserHost.test.ts

1,040 lines40.3 KB

1// @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron debugger.
2import { describe, expect, it, vi } from "@effect/vitest";
3import { DesktopBrowserEvent } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Queue from "effect/Queue";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as TestClock from "effect/testing/TestClock";
10import * as NodeEvents from "node:events";
11​
12import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
13​
14const decodeEvent = Schema.decodeUnknownSync(Schema.fromJsonString(DesktopBrowserEvent));
15const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
16const decodeCdpReply = Schema.decodeUnknownSync(
17 Schema.fromJsonString(Schema.Struct({ id: Schema.Number })),
18);
19const key = { threadId: "thread-1", tabId: "tab-1" };
20/** Sends a page command whose id the fake debugger records as it receives it. */
21const command = (
22 host: DesktopBrowserHost.DesktopBrowserHost["Service"],
23 id: number,
24 method: string,
25) =>
26 host.handleCommandLine(
27 encodeJson({
28 type: "cdp",
29 ...key,
30 message: encodeJson({ id, method, params: { id }, sessionId: "t3-preview-page" }),
31 }),
32 );
33​
34const makeDebuggee = (
35 options: {
36 readonly deferFocus?: boolean;
37 readonly refuse?: (method: string, sessionId: string | undefined) => boolean;
38 } = {},
39) => {
40 const emitter = new NodeEvents.EventEmitter();
41 const pending: Array<() => void> = [];
42 const focusChanges: Array<() => void> = [];
43 const sent: Array<unknown> = [];
44 const sendWaiters: Array<() => void> = [];
45 const focusEmulation: Array<boolean> = [];
46 const debuggee = Object.assign(emitter, {
47 sendCommand: (
48 method: string,
49 params?: { id?: number; enabled?: boolean },
50 sessionId?: string,
51 ) =>
52 new Promise((resolve, reject) => {
53 if (options.refuse?.(method, sessionId)) {
54 reject(new Error("Refused"));
55 return;
56 }
57 if (method === "Target.getTargetInfo") {
58 resolve({ targetInfo: { targetId: "GUEST" } });
59 return;
60 }
61 if (method === "Emulation.setFocusEmulationEnabled") {
62 focusEmulation.push(params?.enabled === true);
63 if (options.deferFocus) focusChanges.push(() => resolve({}));
64 else resolve({});
65 return;
66 }
67 sent.push(params?.id);
68 pending.push(() => resolve({ method }));
69 sendWaiters.shift()?.();
70 }),
71 });
72 const webContents = Object.assign(new NodeEvents.EventEmitter(), {
73 getURL: () => "http://localhost/",
74 getTitle: () => "Page",
75 getUserAgent: () => "Electron",
76 });
77 return {
78 tab: {
79 webContents: webContents as unknown as Electron.WebContents,
80 debugger: debuggee as unknown as Electron.Debugger,
81 },
82 emit: (method: string, params: unknown) => emitter.emit("message", {}, method, params, ""),
83 navigate: () => webContents.emit("did-navigate"),
84 /** Ids of the commands the debugger received, in order. */
85 sent,
86 focusEmulation,
87 nextSend: () => new Promise<void>((resolve) => sendWaiters.push(resolve)),
88 release: () => pending.splice(0).forEach((resolve) => resolve()),
89 releaseFirst: () => pending.shift()?.(),
90 settleFocus: () => focusChanges.splice(0).forEach((resolve) => resolve()),
91 };
92};
93​
94/** Commands wait behind a focus emulation change; it settles within a macrotask. */
95// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
96const settle = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
97​
98const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], count: number) =>
99 host.events.pipe(
100 Stream.take(count),
101 Stream.runCollect,
102 Effect.map((lines) => lines.map((line) => decodeEvent(new TextDecoder().decode(line)))),
103 );
104​
105/**
106 * Ids of the replies the host sends, in order. A screenshot's reply leaves after its turn
107 * has passed on, so by then the next waiting screenshot, if any, has been sent. Subscribe
108 * before sending commands: a new subscriber releases the tab's relay.
109 */
110const watchReplies = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =>
111 Effect.gen(function* () {
112 const replies = yield* Queue.unbounded<number>();
113 yield* host.events.pipe(
114 Stream.map((line) => decodeEvent(new TextDecoder().decode(line))),
115 Stream.runForEach((event) =>
116 event.type === "cdp" ? Queue.offer(replies, decodeCdpReply(event.message).id) : Effect.void,
117 ),
118 Effect.forkScoped,
119 );
120 yield* Effect.yieldNow;
121 return replies;
122 });
123​
124/** Whether the client should paint the guest, each time that changes. */
125const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =>
126 Effect.gen(function* () {
127 const painting: Array<boolean> = [];
128 yield* host.painting.pipe(
129 Stream.runForEach(({ active }) => Effect.sync(() => painting.push(active))),
130 Effect.forkScoped,
131 );
132 yield* Effect.yieldNow;
133 return painting;
134 });
135​
136describe("DesktopBrowserHost", () => {
137 it.effect("announces tabs already attached to a backend that starts later", () =>
138 Effect.gen(function* () {
139 const host = yield* DesktopBrowserHost.make;
140 host.attach(key, makeDebuggee().tab);
141​
142 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
143 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
144 }),
145 );
146​
147 it.effect("drops replies from a relay the server released", () =>
148 Effect.gen(function* () {
149 const host = yield* DesktopBrowserHost.make;
150 const debuggee = makeDebuggee();
151 host.attach(key, debuggee.tab);
152 const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
153​
154 yield* Effect.yieldNow;
155 const command = (id: number, method: string) =>
156 host.handleCommandLine(
157 encodeJson({
158 type: "cdp",
159 ...key,
160 message: encodeJson({ id, method, sessionId: "t3-preview-page" }),
161 }),
162 );
163 yield* command(1, "Page.captureScreenshot");
164 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
165 yield* command(2, "DOM.enable");
166 yield* settle;
167 debuggee.release();
168 const [, reply] = yield* Fiber.join(reader);
169​
170 expect(reply).toMatchObject({ type: "cdp" });
171 expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2);
172 }).pipe(Effect.scoped),
173 );
174​
175 it.effect("sends a page one screenshot at a time", () =>
176 Effect.gen(function* () {
177 const host = yield* DesktopBrowserHost.make;
178 const debuggee = makeDebuggee();
179 host.attach(key, debuggee.tab);
180 const replies = yield* watchReplies(host);
181​
182 yield* command(host, 1, "Page.captureScreenshot");
183 yield* command(host, 2, "Page.captureScreenshot");
184 yield* command(host, 3, "DOM.enable");
185 yield* settle;
186 expect(debuggee.sent).toEqual([1, 3]);
187​
188 debuggee.releaseFirst();
189 expect(yield* Queue.take(replies)).toBe(1);
190 expect(debuggee.sent).toEqual([1, 3, 2]);
191 }).pipe(Effect.scoped),
192 );
193​
194 it.effect("stops waiting on a screenshot the page navigated away from", () =>
195 Effect.gen(function* () {
196 const host = yield* DesktopBrowserHost.make;
197 const debuggee = makeDebuggee();
198 host.attach(key, debuggee.tab);
199 const replies = yield* watchReplies(host);
200​
201 yield* command(host, 1, "Page.captureScreenshot");
202 yield* command(host, 2, "Page.captureScreenshot");
203 yield* command(host, 3, "Page.captureScreenshot");
204 yield* settle;
205 debuggee.navigate();
206 expect(debuggee.sent).toEqual([1, 2]);
207​
208 // The superseded screenshot answering late must not start a third beside the second.
209 debuggee.releaseFirst();
210 expect(yield* Queue.take(replies)).toBe(1);
211 expect(debuggee.sent).toEqual([1, 2]);
212​
213 debuggee.releaseFirst();
214 expect(yield* Queue.take(replies)).toBe(2);
215 expect(debuggee.sent).toEqual([1, 2, 3]);
216 }).pipe(Effect.scoped),
217 );
218​
219 it.effect("drops screenshots a released relay left waiting", () =>
220 Effect.gen(function* () {
221 const host = yield* DesktopBrowserHost.make;
222 const debuggee = makeDebuggee();
223 host.attach(key, debuggee.tab);
224​
225 yield* command(host, 1, "Page.captureScreenshot");
226 yield* command(host, 2, "Page.captureScreenshot");
227 yield* settle;
228 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
229 yield* command(host, 3, "Page.captureScreenshot");
230 expect(debuggee.sent).toEqual([1]);
231​
232 const sent = debuggee.nextSend();
233 debuggee.release();
234 yield* Effect.promise(() => sent);
235 expect(debuggee.sent).toEqual([1, 3]);
236 }),
237 );
238​
239 it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () =>
240 Effect.gen(function* () {
241 const host = yield* DesktopBrowserHost.make;
242 const debuggee = makeDebuggee();
243 host.attach(key, debuggee.tab);
244​
245 yield* command(host, 1, "DOM.enable");
246 yield* settle;
247 expect(debuggee.focusEmulation).toEqual([true]);
248 expect(debuggee.sent).toEqual([1]);
249 debuggee.release();
250 yield* settle;
251​
252 yield* TestClock.adjust("4 seconds");
253 yield* command(host, 2, "Input.dispatchMouseEvent");
254 yield* settle;
255 debuggee.release();
256 yield* settle;
257 yield* TestClock.adjust("4 seconds");
258 expect(debuggee.focusEmulation).toEqual([true]);
259​
260 yield* TestClock.adjust("10 seconds");
261 expect(debuggee.focusEmulation).toEqual([true, false]);
262​
263 yield* command(host, 3, "Page.captureScreenshot");
264 yield* settle;
265 expect(debuggee.focusEmulation).toEqual([true, false, true]);
266 expect(debuggee.sent).toEqual([1, 2, 3]);
267 }),
268 );
269​
270 it.effect("keeps a guest focused while a command it is running is still pending", () =>
271 Effect.gen(function* () {
272 const host = yield* DesktopBrowserHost.make;
273 const debuggee = makeDebuggee();
274 host.attach(key, debuggee.tab);
275 const replies = yield* watchReplies(host);
276​
277 // An evaluation awaiting the page's next frame, which a throttled guest never paints.
278 yield* command(host, 1, "Runtime.evaluate");
279 yield* settle;
280 expect(debuggee.sent).toEqual([1]);
281 yield* TestClock.adjust("1 minute");
282 expect(debuggee.focusEmulation).toEqual([true]);
283​
284 debuggee.release();
285 expect(yield* Queue.take(replies)).toBe(1);
286 yield* TestClock.adjust("1 minute");
287 expect(debuggee.focusEmulation).toEqual([true, false]);
288 }).pipe(Effect.scoped),
289 );
290​
291 it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () =>
292 Effect.gen(function* () {
293 const host = yield* DesktopBrowserHost.make;
294 const debuggee = makeDebuggee();
295 host.attach(key, debuggee.tab);
296​
297 yield* command(host, 1, "Runtime.evaluate");
298 yield* settle;
299 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
300 yield* TestClock.adjust("1 minute");
301 expect(debuggee.focusEmulation).toEqual([true, false]);
302​
303 // A command the old document never answers.
304 yield* command(host, 2, "Page.captureScreenshot");
305 yield* settle;
306 expect(debuggee.sent).toEqual([1, 2]);
307 debuggee.navigate();
308 yield* TestClock.adjust("1 minute");
309 expect(debuggee.focusEmulation).toEqual([true, false, true, false]);
310 }),
311 );
312​
313 it.effect("keeps a guest focused for the screenshot a navigation lets start", () =>
314 Effect.gen(function* () {
315 const host = yield* DesktopBrowserHost.make;
316 const debuggee = makeDebuggee();
317 host.attach(key, debuggee.tab);
318​
319 yield* command(host, 1, "Page.captureScreenshot");
320 yield* command(host, 2, "Page.captureScreenshot");
321 yield* settle;
322 debuggee.navigate();
323 expect(debuggee.sent).toEqual([1, 2]);
324 yield* TestClock.adjust("1 minute");
325 expect(debuggee.focusEmulation).toEqual([true]);
326 }),
327 );
328​
329 it.effect("never sends a screenshot a navigation superseded while focus was changing", () =>
330 Effect.gen(function* () {
331 const host = yield* DesktopBrowserHost.make;
332 const debuggee = makeDebuggee({ deferFocus: true });
333 host.attach(key, debuggee.tab);
334​
335 yield* command(host, 1, "Page.captureScreenshot");
336 yield* command(host, 2, "Page.captureScreenshot");
337 yield* settle;
338 debuggee.navigate();
339 debuggee.settleFocus();
340 yield* settle;
341 // Two captures in flight would undo the one-at-a-time guard.
342 expect(debuggee.sent).toEqual([2]);
343 }),
344 );
345​
346 it.effect("keeps a guest focused when its turn starts after the agent's first command", () =>
347 Effect.gen(function* () {
348 const host = yield* DesktopBrowserHost.make;
349 const debuggee = makeDebuggee();
350 host.attach(key, debuggee.tab);
351 const turn = (active: boolean) =>
352 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
353​
354 yield* command(host, 1, "Input.dispatchKeyEvent");
355 yield* settle;
356 yield* turn(true);
357 debuggee.release();
358 yield* settle;
359 yield* TestClock.adjust("1 minute");
360 expect(debuggee.focusEmulation).toEqual([true]);
361​
362 yield* turn(false);
363 yield* TestClock.adjust("1 minute");
364 expect(debuggee.focusEmulation).toEqual([true, false]);
365 }),
366 );
367​
368 it.effect("lets a guest throttle through a turn that only sent it housekeeping", () =>
369 Effect.gen(function* () {
370 const host = yield* DesktopBrowserHost.make;
371 const debuggee = makeDebuggee();
372 host.attach(key, debuggee.tab);
373 yield* host.handleCommandLine(
374 encodeJson({ type: "turn", threadId: key.threadId, active: true }),
375 );
376​
377 // Playwright re-enabling a domain after a reload is not the agent using the tab.
378 yield* command(host, 1, "Runtime.enable");
379 yield* settle;
380 debuggee.release();
381 yield* settle;
382 yield* TestClock.adjust("1 minute");
383 expect(debuggee.focusEmulation).toEqual([true, false]);
384​
385 yield* command(host, 2, "Runtime.evaluate");
386 yield* settle;
387 debuggee.release();
388 yield* settle;
389 yield* TestClock.adjust("1 minute");
390 expect(debuggee.focusEmulation).toEqual([true, false, true]);
391 }),
392 );
393​
394 it.effect("keeps a guest the agent used focused through its turn's pauses", () =>
395 Effect.gen(function* () {
396 const host = yield* DesktopBrowserHost.make;
397 const debuggee = makeDebuggee();
398 host.attach(key, debuggee.tab);
399 const turn = (active: boolean) =>
400 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
401​
402 yield* turn(true);
403 yield* TestClock.adjust("1 minute");
404 expect(debuggee.focusEmulation).toEqual([]);
405​
406 yield* command(host, 1, "Input.dispatchKeyEvent");
407 yield* settle;
408 debuggee.release();
409 yield* settle;
410 // The model thinks between steps; a focus-sensitive menu must not blur meanwhile.
411 yield* TestClock.adjust("1 minute");
412 expect(debuggee.focusEmulation).toEqual([true]);
413​
414 yield* turn(false);
415 yield* TestClock.adjust("1 minute");
416 expect(debuggee.focusEmulation).toEqual([true, false]);
417 }),
418 );
419​
420 it.effect(
421 "ends a command's hold with the turn that sent it, even if Chromium never answers",
422 () =>
423 Effect.gen(function* () {
424 const host = yield* DesktopBrowserHost.make;
425 const debuggee = makeDebuggee();
426 host.attach(key, debuggee.tab);
427 yield* host.handleCommandLine(
428 encodeJson({ type: "turn", threadId: key.threadId, active: true }),
429 );
430​
431 // A screenshot of a hidden guest the server already gave up on.
432 yield* command(host, 1, "Page.captureScreenshot");
433 yield* settle;
434 expect(debuggee.sent).toEqual([1]);
435 yield* host.handleCommandLine(
436 encodeJson({ type: "turn", threadId: key.threadId, active: false }),
437 );
438 yield* TestClock.adjust("1 minute");
439 expect(debuggee.focusEmulation).toEqual([true, false]);
440 }),
441 );
442​
443 it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () =>
444 Effect.gen(function* () {
445 const host = yield* DesktopBrowserHost.make;
446 const debuggee = makeDebuggee();
447 host.attach(key, debuggee.tab);
448 const replies = yield* watchReplies(host);
449 const raw = (message: Record<string, unknown>) =>
450 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
451 const turn = (active: boolean) =>
452 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
453​
454 // The server's own CDP session, evaluating a promise that never settles.
455 yield* turn(true);
456 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
457 expect(yield* Queue.take(replies)).toBe(1);
458 yield* raw({ id: 2, method: "Runtime.evaluate", sessionId: "t3-preview-page-1" });
459 yield* settle;
460 yield* turn(false);
461 yield* TestClock.adjust("1 minute");
462 expect(debuggee.focusEmulation).toEqual([true, false]);
463​
464 // A viewer streaming the guest keeps it focused through a turn's end.
465 yield* turn(true);
466 yield* raw({ id: 3, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
467 expect(yield* Queue.take(replies)).toBe(3);
468 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
469 yield* settle;
470 yield* turn(false);
471 yield* TestClock.adjust("1 minute");
472 expect(debuggee.focusEmulation).toEqual([true, false, true]);
473 }).pipe(Effect.scoped),
474 );
475​
476 it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () =>
477 Effect.gen(function* () {
478 const host = yield* DesktopBrowserHost.make;
479 const debuggee = makeDebuggee();
480 host.attach(key, debuggee.tab);
481 const replies = yield* watchReplies(host);
482 const painting = yield* watchPainting(host);
483 const raw = (message: Record<string, unknown>) =>
484 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
485​
486 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
487 expect(yield* Queue.take(replies)).toBe(1);
488 yield* raw({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
489 yield* settle;
490 yield* raw({
491 id: 3,
492 method: "Target.detachFromTarget",
493 params: { sessionId: "t3-preview-page-1" },
494 });
495 expect(yield* Queue.take(replies)).toBe(3);
496 expect(painting).toEqual([true, false]);
497​
498 // The agent's screenshot waits its turn; painting lets the abandoned one finish first.
499 yield* command(host, 4, "Page.captureScreenshot");
500 yield* settle;
501 expect(painting).toEqual([true, false, true]);
502 debuggee.release();
503 expect(yield* Queue.take(replies)).toBe(2);
504 yield* settle;
505 expect(debuggee.sent).toEqual([undefined, 4]);
506 debuggee.release();
507 expect(yield* Queue.take(replies)).toBe(4);
508 yield* settle;
509 expect(painting).toEqual([true, false, true, false]);
510 }).pipe(Effect.scoped),
511 );
512​
513 it.effect("stops painting for a queued screenshot once its session detaches", () =>
514 Effect.gen(function* () {
515 const host = yield* DesktopBrowserHost.make;
516 const debuggee = makeDebuggee();
517 host.attach(key, debuggee.tab);
518 const replies = yield* watchReplies(host);
519 const painting = yield* watchPainting(host);
520 const raw = (message: Record<string, unknown>) =>
521 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
522 const turn = (active: boolean) =>
523 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
524​
525 // The agent's screenshot is abandoned at turn end; a viewer's waits behind it, then leaves.
526 yield* turn(true);
527 yield* command(host, 1, "Page.captureScreenshot");
528 yield* settle;
529 yield* turn(false);
530 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
531 expect(yield* Queue.take(replies)).toBe(2);
532 yield* raw({ id: 3, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
533 yield* settle;
534 expect(painting).toEqual([true, false, true]);
535 yield* raw({
536 id: 4,
537 method: "Target.detachFromTarget",
538 params: { sessionId: "t3-preview-page-1" },
539 });
540 expect(yield* Queue.take(replies)).toBe(4);
541 expect(painting).toEqual([true, false, true, false]);
542 yield* TestClock.adjust("1 minute");
543 expect(debuggee.focusEmulation).toEqual([true, false]);
544 }).pipe(Effect.scoped),
545 );
546​
547 it.effect("never sends a screenshot whose session detached while focus was changing", () =>
548 Effect.gen(function* () {
549 const host = yield* DesktopBrowserHost.make;
550 const debuggee = makeDebuggee({ deferFocus: true });
551 host.attach(key, debuggee.tab);
552 const replies = yield* watchReplies(host);
553 const raw = (message: Record<string, unknown>) =>
554 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
555​
556 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
557 expect(yield* Queue.take(replies)).toBe(1);
558 yield* raw({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
559 yield* raw({
560 id: 3,
561 method: "Target.detachFromTarget",
562 params: { sessionId: "t3-preview-page-1" },
563 });
564 expect(yield* Queue.take(replies)).toBe(3);
565 debuggee.settleFocus();
566 yield* settle;
567 expect(debuggee.sent).toEqual([]);
568 }).pipe(Effect.scoped),
569 );
570​
571 it.effect("stops painting for a screenshot still queued when the agent's turn ends", () =>
572 Effect.gen(function* () {
573 const host = yield* DesktopBrowserHost.make;
574 const debuggee = makeDebuggee();
575 host.attach(key, debuggee.tab);
576 const painting = yield* watchPainting(host);
577 const turn = (active: boolean) =>
578 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
579​
580 yield* turn(true);
581 yield* command(host, 1, "Page.captureScreenshot");
582 yield* command(host, 2, "Page.captureScreenshot");
583 yield* settle;
584 yield* turn(false);
585 yield* settle;
586 expect(painting).toEqual([true, false]);
587​
588 // The first answers late; the second still goes in turn, but holds nothing.
589 debuggee.releaseFirst();
590 yield* settle;
591 expect(debuggee.sent).toEqual([1, 2]);
592 expect(painting).toEqual([true, false]);
593 yield* TestClock.adjust("1 minute");
594 expect(debuggee.focusEmulation).toEqual([true, false]);
595 }).pipe(Effect.scoped),
596 );
597​
598 it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () =>
599 Effect.gen(function* () {
600 const host = yield* DesktopBrowserHost.make;
601 const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" });
602 host.attach(key, debuggee.tab);
603 const replies = yield* watchReplies(host);
604 const painting = yield* watchPainting(host);
605 const raw = (message: Record<string, unknown>) =>
606 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
607​
608 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
609 expect(yield* Queue.take(replies)).toBe(1);
610 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
611 expect(yield* Queue.take(replies)).toBe(2);
612 yield* settle;
613 expect(painting).toEqual([true, false]);
614 yield* TestClock.adjust("1 minute");
615 expect(debuggee.focusEmulation).toEqual([true, false]);
616 }).pipe(Effect.scoped),
617 );
618​
619 it.effect("lets a guest throttle after a person's input through a viewer that then closed", () =>
620 Effect.gen(function* () {
621 const host = yield* DesktopBrowserHost.make;
622 const debuggee = makeDebuggee();
623 host.attach(key, debuggee.tab);
624 const replies = yield* watchReplies(host);
625 const raw = (message: Record<string, unknown>) =>
626 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
627​
628 yield* host.handleCommandLine(
629 encodeJson({ type: "turn", threadId: key.threadId, active: true }),
630 );
631 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
632 expect(yield* Queue.take(replies)).toBe(1);
633 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
634 yield* raw({ id: 3, method: "Input.dispatchMouseEvent", sessionId: "t3-preview-page-1" });
635 yield* settle;
636 debuggee.release();
637 yield* raw({
638 id: 4,
639 method: "Target.detachFromTarget",
640 params: { sessionId: "t3-preview-page-1" },
641 });
642 yield* settle;
643 yield* TestClock.adjust("1 minute");
644 expect(debuggee.focusEmulation).toEqual([true, false]);
645 }).pipe(Effect.scoped),
646 );
647​
648 it.effect("keeps a page's screencast when a child session's screencast is refused", () =>
649 Effect.gen(function* () {
650 const host = yield* DesktopBrowserHost.make;
651 const debuggee = makeDebuggee({
652 refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined,
653 });
654 host.attach(key, debuggee.tab);
655 const replies = yield* watchReplies(host);
656 const raw = (message: Record<string, unknown>) =>
657 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
658​
659 yield* command(host, 1, "Page.startScreencast");
660 yield* settle;
661 debuggee.release();
662 expect(yield* Queue.take(replies)).toBe(1);
663 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "child-frame" });
664 expect(yield* Queue.take(replies)).toBe(2);
665 yield* TestClock.adjust("1 minute");
666 expect(debuggee.focusEmulation).toEqual([true]);
667 }).pipe(Effect.scoped),
668 );
669​
670 it.effect("ignores a screencast that arrives on a session after it detached", () =>
671 Effect.gen(function* () {
672 const host = yield* DesktopBrowserHost.make;
673 const debuggee = makeDebuggee();
674 host.attach(key, debuggee.tab);
675 const replies = yield* watchReplies(host);
676 const raw = (message: Record<string, unknown>) =>
677 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
678​
679 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
680 expect(yield* Queue.take(replies)).toBe(1);
681 yield* raw({
682 id: 2,
683 method: "Target.detachFromTarget",
684 params: { sessionId: "t3-preview-page-1" },
685 });
686 expect(yield* Queue.take(replies)).toBe(2);
687 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
688 yield* settle;
689 debuggee.release();
690 yield* settle;
691 yield* TestClock.adjust("1 minute");
692 expect(debuggee.focusEmulation).toEqual([true, false]);
693 }).pipe(Effect.scoped),
694 );
695​
696 it.effect("lets a guest throttle once the session waiting on its command detaches", () =>
697 Effect.gen(function* () {
698 const host = yield* DesktopBrowserHost.make;
699 const debuggee = makeDebuggee();
700 host.attach(key, debuggee.tab);
701 const replies = yield* watchReplies(host);
702 const raw = (message: Record<string, unknown>) =>
703 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
704​
705 // A viewer's own CDP session, closed while its still of a hidden guest is pending.
706 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
707 expect(yield* Queue.take(replies)).toBe(1);
708 yield* raw({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
709 yield* settle;
710 yield* TestClock.adjust("1 minute");
711 expect(debuggee.focusEmulation).toEqual([true]);
712​
713 yield* raw({
714 id: 3,
715 method: "Target.detachFromTarget",
716 params: { sessionId: "t3-preview-page-1" },
717 });
718 yield* TestClock.adjust("1 minute");
719 expect(debuggee.focusEmulation).toEqual([true, false]);
720 }).pipe(Effect.scoped),
721 );
722​
723 it.effect("never sends a screenshot queued by a session that has since detached", () =>
724 Effect.gen(function* () {
725 const host = yield* DesktopBrowserHost.make;
726 const debuggee = makeDebuggee();
727 host.attach(key, debuggee.tab);
728 const replies = yield* watchReplies(host);
729 const raw = (message: Record<string, unknown>) =>
730 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
731​
732 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
733 expect(yield* Queue.take(replies)).toBe(1);
734 yield* command(host, 2, "Page.captureScreenshot");
735 yield* raw({ id: 3, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
736 yield* raw({
737 id: 4,
738 method: "Target.detachFromTarget",
739 params: { sessionId: "t3-preview-page-1" },
740 });
741 yield* settle;
742 debuggee.release();
743 expect(yield* Queue.take(replies)).toBe(4);
744 // The dropped screenshot's error reply leaves as the first frees its turn.
745 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([3, 2]);
746 yield* settle;
747 expect(debuggee.sent).toEqual([2]);
748​
749 yield* TestClock.adjust("1 minute");
750 expect(debuggee.focusEmulation).toEqual([true, false]);
751 }).pipe(Effect.scoped),
752 );
753​
754 it.effect("keeps a streamed guest focused until its screencast ends", () =>
755 Effect.gen(function* () {
756 const host = yield* DesktopBrowserHost.make;
757 const debuggee = makeDebuggee();
758 host.attach(key, debuggee.tab);
759​
760 yield* command(host, 1, "Page.startScreencast");
761 yield* TestClock.adjust("1 minute");
762 expect(debuggee.focusEmulation).toEqual([true]);
763​
764 yield* command(host, 2, "Page.stopScreencast");
765 yield* settle;
766 debuggee.release();
767 yield* settle;
768 yield* TestClock.adjust("1 minute");
769 expect(debuggee.focusEmulation).toEqual([true, false]);
770​
771 // A viewer whose connection went away without stopping its screencast.
772 yield* command(host, 3, "Page.startScreencast");
773 yield* settle;
774 debuggee.release();
775 yield* settle;
776 yield* TestClock.adjust("1 minute");
777 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
778 yield* TestClock.adjust("1 minute");
779 expect(debuggee.focusEmulation).toEqual([true, false, true, false]);
780 }),
781 );
782​
783 it.effect("keeps a guest focused while any of its screencasts runs", () =>
784 Effect.gen(function* () {
785 const host = yield* DesktopBrowserHost.make;
786 const debuggee = makeDebuggee();
787 host.attach(key, debuggee.tab);
788 const replies = yield* watchReplies(host);
789 const raw = (message: Record<string, unknown>) =>
790 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
791​
792 // Two viewers, or a viewer and a recording, each on its own session.
793 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
794 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
795 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]);
796 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
797 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
798 yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" });
799 yield* settle;
800 debuggee.release();
801 yield* settle;
802 yield* TestClock.adjust("1 minute");
803 expect(debuggee.focusEmulation).toEqual([true]);
804​
805 yield* raw({
806 id: 6,
807 method: "Target.detachFromTarget",
808 params: { sessionId: "t3-preview-page-2" },
809 });
810 yield* TestClock.adjust("1 minute");
811 expect(debuggee.focusEmulation).toEqual([true, false]);
812 }).pipe(Effect.scoped),
813 );
814​
815 it.effect("paints a hidden guest only while the screenshot it is taking is pending", () =>
816 Effect.gen(function* () {
817 const host = yield* DesktopBrowserHost.make;
818 const debuggee = makeDebuggee();
819 host.attach(key, debuggee.tab);
820 const painting = yield* watchPainting(host);
821​
822 yield* command(host, 1, "DOM.enable");
823 yield* settle;
824 expect(painting).toEqual([]);
825​
826 yield* command(host, 2, "Page.captureScreenshot");
827 yield* command(host, 3, "Page.captureScreenshot");
828 yield* settle;
829 expect(painting).toEqual([true]);
830​
831 // The first answers once the guest paints; the queued one then takes its turn.
832 debuggee.release();
833 yield* settle;
834 expect(debuggee.sent).toEqual([1, 2, 3]);
835 debuggee.release();
836 yield* settle;
837 expect(painting).toEqual([true, false]);
838 }).pipe(Effect.scoped),
839 );
840​
841 it.effect("stops painting for a screenshot Chromium never answers", () =>
842 Effect.gen(function* () {
843 const host = yield* DesktopBrowserHost.make;
844 const debuggee = makeDebuggee();
845 host.attach(key, debuggee.tab);
846 const painting = yield* watchPainting(host);
847 const turn = (active: boolean) =>
848 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
849​
850 // The server gave up on it, and the agent's turn ends.
851 yield* turn(true);
852 yield* command(host, 1, "Page.captureScreenshot");
853 yield* settle;
854 yield* turn(false);
855 yield* settle;
856 expect(painting).toEqual([true, false]);
857​
858 // The page loads a new document, which also frees the screenshot turn.
859 debuggee.navigate();
860 yield* command(host, 2, "Page.captureScreenshot");
861 yield* settle;
862 debuggee.navigate();
863 yield* settle;
864 expect(painting).toEqual([true, false, true, false]);
865​
866 // The server releases the relay.
867 yield* command(host, 3, "Page.captureScreenshot");
868 yield* settle;
869 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
870 yield* settle;
871 expect(painting).toEqual([true, false, true, false, true, false]);
872​
873 // The guest detaches; a replacement starts with no screenshot pending.
874 const replacement = makeDebuggee();
875 host.attach(key, replacement.tab);
876 yield* command(host, 4, "Page.captureScreenshot");
877 yield* settle;
878 host.detach(key);
879 yield* settle;
880 expect(painting).toEqual([true, false, true, false, true, false, true, false]);
881 }).pipe(Effect.scoped),
882 );
883​
884 it.effect("paints a streamed guest until its last screencast ends", () =>
885 Effect.gen(function* () {
886 const host = yield* DesktopBrowserHost.make;
887 const debuggee = makeDebuggee();
888 host.attach(key, debuggee.tab);
889 const replies = yield* watchReplies(host);
890 const painting = yield* watchPainting(host);
891 const raw = (message: Record<string, unknown>) =>
892 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
893​
894 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
895 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
896 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]);
897 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
898 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
899 yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" });
900 yield* settle;
901 debuggee.release();
902 yield* settle;
903 expect(painting).toEqual([true]);
904​
905 yield* raw({
906 id: 6,
907 method: "Target.detachFromTarget",
908 params: { sessionId: "t3-preview-page-2" },
909 });
910 yield* settle;
911 expect(painting).toEqual([true, false]);
912 }).pipe(Effect.scoped),
913 );
914​
915 it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
916 Effect.gen(function* () {
917 const host = yield* DesktopBrowserHost.make;
918 const debuggee = makeDebuggee();
919 host.attach(key, debuggee.tab);
920 const paths: Array<string> = [];
921 const item = {
922 setSavePath: (path: string) => void paths.push(path),
923 } as unknown as Electron.DownloadItem;
924​
925 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);
926 yield* host.handleCommandLine(
927 encodeJson({
928 type: "cdp",
929 ...key,
930 message: encodeJson({
931 id: 1,
932 method: "Browser.setDownloadBehavior",
933 params: { behavior: "allowAndName", downloadPath: "/srv/downloads" },
934 }),
935 }),
936 );
937 debuggee.emit("Browser.downloadWillBegin", { guid: "guid-1", suggestedFilename: "r.csv" });
938 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true);
939 expect(paths).toEqual(["/srv/downloads/guid-1"]);
940 }),
941 );
942​
943 it.effect("tells a download the person clicked from one the agent's input started", () =>
944 Effect.gen(function* () {
945 const host = yield* DesktopBrowserHost.make;
946 const debuggee = makeDebuggee();
947 host.attach(key, debuggee.tab);
948​
949 yield* host.handleCommandLine(
950 encodeJson({
951 type: "cdp",
952 ...key,
953 message: encodeJson({ id: 1, method: "DOM.getDocument", params: {} }),
954 }),
955 );
956 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(true);
957 yield* host.handleCommandLine(
958 encodeJson({
959 type: "cdp",
960 ...key,
961 message: encodeJson({
962 id: 2,
963 method: "Input.dispatchMouseEvent",
964 params: { type: "mousePressed", x: 1, y: 1 },
965 }),
966 }),
967 );
968 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false);
969 }),
970 );
971​
972 it.effect("detaches only the tab whose CDP event is too large to relay", () =>
973 Effect.gen(function* () {
974 const host = yield* DesktopBrowserHost.make;
975 const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()];
976 const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand");
977 const keys = [key, { threadId: "thread-2", tabId: "tab-2" }];
978 const events = yield* Queue.unbounded<DesktopBrowserEvent>();
979 yield* host.events.pipe(
980 Stream.runForEach((line) =>
981 Queue.offer(events, decodeEvent(new TextDecoder().decode(line))),
982 ),
983 Effect.forkScoped,
984 );
985 for (const [index, tabKey] of keys.entries()) {
986 host.attach(tabKey, tabs[index]!.tab);
987 expect(yield* Queue.take(events)).toEqual({ type: "attached", ...tabKey });
988 yield* host.handleCommandLine(
989 encodeJson({
990 type: "cdp",
991 ...tabKey,
992 message: encodeJson({ id: 1, method: "Target.setAutoAttach" }),
993 }),
994 );
995 // The command's reply and the page announcement.
996 yield* Queue.takeN(events, 2);
997 }
998​
999 yield* host.handleCommandLine(
1000 encodeJson({
1001 type: "cdp",
1002 ...key,
1003 message: encodeJson({
1004 id: 2,
1005 method: "Target.setAutoAttach",
1006 params: { autoAttach: true, waitForDebuggerOnStart: true, flatten: true },
1007 sessionId: "t3-preview-page",
1008 }),
1009 }),
1010 );
1011 yield* command(host, 3, "Page.startScreencast");
1012 tabs[0]!.emit("Runtime.consoleAPICalled", {
1013 args: Array(2048).fill("x".repeat(40 * 1024)),
1014 });
1015 tabs[1]!.emit("Page.loadEventFired", { timestamp: 1 });
1016 const [detached, next] = yield* Queue.takeN(events, 2);
1017​
1018 const { type, threadId, tabId } = detached!;
1019 expect({ type, threadId, tabId }).toEqual({ type: "detached", ...key });
1020 expect(send).toHaveBeenCalledWith("Target.setAutoAttach", {
1021 autoAttach: false,
1022 waitForDebuggerOnStart: false,
1023 flatten: true,
1024 });
1025 tabs[0]!.settleFocus();
1026 yield* settle;
1027 expect(send).not.toHaveBeenCalledWith("Target.setAutoAttach", {
1028 autoAttach: true,
1029 waitForDebuggerOnStart: true,
1030 flatten: true,
1031 });
1032 expect(send).toHaveBeenCalledWith("Page.stopScreencast");
1033 expect(tabs[0]!.focusEmulation).toEqual([true, false]);
1034 expect(next).toMatchObject({ type: "cdp", ...keys[1] });
1035 expect(JSON.parse((next as { message: string }).message)).toMatchObject({
1036 method: "Page.loadEventFired",
1037 });
1038 }).pipe(Effect.scoped),
1039 );
1040});