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