The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,445 lines 55.6 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron debugger.
2 import { describe, expect, it, vi } from "@effect/vitest";
3 import { DesktopBrowserEvent } from "@t3tools/contracts";
4 import * as Effect from "effect/Effect";
5 import * as Fiber from "effect/Fiber";
6 import * as Queue from "effect/Queue";
7 import * as Schema from "effect/Schema";
8 import * as Stream from "effect/Stream";
9 import * as TestClock from "effect/testing/TestClock";
10 import * as NodeEvents from "node:events";
11
12 import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
13
14 const decodeEvent = Schema.decodeUnknownSync(Schema.fromJsonString(DesktopBrowserEvent));
15 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
16 const decodeCdpReply = Schema.decodeUnknownSync(
17 Schema.fromJsonString(Schema.Struct({ id: Schema.Number })),
18 );
19 const decodeCdpMessage = Schema.decodeUnknownSync(
20 Schema.fromJsonString(
21 Schema.Struct({
22 id: Schema.optional(Schema.Number),
23 method: Schema.optional(Schema.String),
24 sessionId: Schema.optional(Schema.String),
25 }),
26 ),
27 );
28 const key = { threadId: "thread-1", tabId: "tab-1" };
29
30 /** A host whose client already draws `key` at full detail, so its screenshots go out at once. */
31 const makeDrawnHost = Effect.tap(DesktopBrowserHost.make, (host) =>
32 Effect.sync(() => host.setCaptureDrawn(key, true)),
33 );
34 /** Sends a page command whose id the fake debugger records as it receives it. */
35 const command = (
36 host: DesktopBrowserHost.DesktopBrowserHost["Service"],
37 id: number,
38 method: string,
39 ) =>
40 host.handleCommandLine(
41 encodeJson({
42 type: "cdp",
43 ...key,
44 message: encodeJson({ id, method, params: { id }, sessionId: "t3-preview-page" }),
45 }),
46 );
47
48 const makeDebuggee = (
49 options: {
50 readonly deferFocus?: boolean;
51 /** The guest is still loading its first page. */
52 readonly loading?: boolean;
53 readonly refuse?: (method: string, sessionId: string | undefined) => boolean;
54 } = {},
55 ) => {
56 const emitter = new NodeEvents.EventEmitter();
57 const pending: Array<() => void> = [];
58 const focusChanges: Array<() => void> = [];
59 const sent: Array<unknown> = [];
60 const methods: Array<string> = [];
61 const rejects: Array<() => void> = [];
62 const sendWaiters: Array<() => void> = [];
63 const focusEmulation: Array<boolean> = [];
64 const debuggee = Object.assign(emitter, {
65 sendCommand: (
66 method: string,
67 params?: { id?: number; enabled?: boolean },
68 sessionId?: string,
69 ) =>
70 new Promise((resolve, reject) => {
71 if (options.refuse?.(method, sessionId)) {
72 reject(new Error("Refused"));
73 return;
74 }
75 if (method === "Target.getTargetInfo") {
76 resolve({ targetInfo: { targetId: "GUEST" } });
77 return;
78 }
79 if (method === "Emulation.setFocusEmulationEnabled") {
80 focusEmulation.push(params?.enabled === true);
81 if (options.deferFocus) focusChanges.push(() => resolve({}));
82 else resolve({});
83 return;
84 }
85 sent.push(params?.id);
86 methods.push(method);
87 rejects.push(() => reject(new Error("Refused")));
88 pending.push(() => resolve({ method }));
89 sendWaiters.shift()?.();
90 }),
91 });
92 let destroyed = false;
93 const webContents = Object.assign(new NodeEvents.EventEmitter(), {
94 getURL: () => "http://localhost/",
95 getTitle: () => "Page",
96 getUserAgent: () => "Electron",
97 isLoadingMainFrame: () => options.loading === true,
98 isDestroyed: () => destroyed,
99 });
100 return {
101 tab: {
102 webContents: webContents as unknown as Electron.WebContents,
103 debugger: debuggee as unknown as Electron.Debugger,
104 },
105 emit: (method: string, params: unknown) => emitter.emit("message", {}, method, params, ""),
106 navigate: () => webContents.emit("did-navigate"),
107 domReady: () => webContents.emit("dom-ready"),
108 destroy: () => {
109 destroyed = true;
110 },
111 failLoad: (code: number) =>
112 webContents.emit("did-fail-load", {}, code, "Failed", "http://localhost/", true),
113 /** Ids of the commands the debugger received, in order. */
114 sent,
115 /** Methods of the same commands, in order. */
116 methods,
117 /** Refuses the pending command the debugger received with this id. */
118 refuse: (id: number) => rejects[sent.indexOf(id)]?.(),
119 focusEmulation,
120 nextSend: () => new Promise<void>((resolve) => sendWaiters.push(resolve)),
121 release: () => pending.splice(0).forEach((resolve) => resolve()),
122 releaseFirst: () => pending.shift()?.(),
123 settleFocus: () => focusChanges.splice(0).forEach((resolve) => resolve()),
124 };
125 };
126
127 /** Commands wait behind a focus emulation change; it settles within a macrotask. */
128 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
129 const settle = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
130
131 const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], count: number) =>
132 host.events.pipe(
133 Stream.take(count),
134 Stream.runCollect,
135 Effect.map((lines) => lines.map((line) => decodeEvent(new TextDecoder().decode(line)))),
136 );
137
138 /**
139 * Ids of the replies the host sends, in order. A screenshot's reply leaves after its turn
140 * has passed on, so by then the next waiting screenshot, if any, has been sent. Subscribe
141 * before sending commands: a new subscriber releases the tab's relay. Screencast frames
142 * go to `frames` by the session they were sent to.
143 */
144 const watchReplies = (
145 host: DesktopBrowserHost.DesktopBrowserHost["Service"],
146 frames: Array<string | undefined> = [],
147 ) =>
148 Effect.gen(function* () {
149 const replies = yield* Queue.unbounded<number>();
150 yield* host.events.pipe(
151 Stream.map((line) => decodeEvent(new TextDecoder().decode(line))),
152 Stream.runForEach((event) => {
153 if (event.type !== "cdp") return Effect.void;
154 const { id, method, sessionId } = decodeCdpMessage(event.message);
155 if (id !== undefined) return Queue.offer(replies, id);
156 if (method === "Page.screencastFrame") frames.push(sessionId);
157 return Effect.void;
158 }),
159 Effect.forkScoped,
160 );
161 yield* Effect.yieldNow;
162 return replies;
163 });
164
165 /** Whether the client should paint the guest, each time that changes. */
166 const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =>
167 Effect.gen(function* () {
168 const painting: Array<boolean> = [];
169 yield* host.painting.pipe(
170 Stream.runForEach(({ active }) => Effect.sync(() => painting.push(active))),
171 Effect.forkScoped,
172 );
173 yield* Effect.yieldNow;
174 return painting;
175 });
176
177 describe("DesktopBrowserHost", () => {
178 it.effect("announces tabs already attached to a backend that starts later", () =>
179 Effect.gen(function* () {
180 const host = yield* makeDrawnHost;
181 host.attach(key, makeDebuggee().tab);
182
183 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
184 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
185 }),
186 );
187
188 it.effect("announces a guest still loading its first page only once that page is up", () =>
189 Effect.gen(function* () {
190 const host = yield* makeDrawnHost;
191 const loading = makeDebuggee({ loading: true });
192 const other = { ...key, tabId: "tab-2" };
193 const reader = yield* takeEvents(host, 3).pipe(Effect.forkScoped);
194
195 yield* Effect.yieldNow;
196 host.attach(key, loading.tab);
197 host.setShown(key, true);
198 host.attach(other, makeDebuggee().tab);
199 loading.domReady();
200
201 expect(yield* Fiber.join(reader)).toEqual([
202 { type: "attached", ...other },
203 { type: "attached", ...key },
204 { type: "shown", ...key, shown: true },
205 ]);
206 }),
207 );
208
209 it.effect(
210 "keeps a loading guest unannounced across a replaced navigation and a new backend",
211 () =>
212 Effect.gen(function* () {
213 const host = yield* makeDrawnHost;
214 const loading = makeDebuggee({ loading: true });
215 const other = { ...key, tabId: "tab-2" };
216 host.attach(key, loading.tab);
217 loading.failLoad(-3);
218 const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
219
220 yield* Effect.yieldNow;
221 host.attach(other, makeDebuggee().tab);
222 loading.domReady();
223
224 expect(yield* Fiber.join(reader)).toEqual([
225 { type: "attached", ...other },
226 { type: "attached", ...key },
227 ]);
228 }),
229 );
230
231 it.effect(
232 "announces a first page that never comes up, but never a tab closed or destroyed first",
233 () =>
234 Effect.gen(function* () {
235 const host = yield* makeDrawnHost;
236 const closed = { ...key, tabId: "tab-2" };
237 const destroyed = { ...key, tabId: "tab-3" };
238 const destroyedGuest = makeDebuggee({ loading: true });
239 const reader = yield* takeEvents(host, 1).pipe(Effect.forkScoped);
240
241 yield* Effect.yieldNow;
242 host.attach(closed, makeDebuggee({ loading: true }).tab);
243 host.detach(closed);
244 host.attach(destroyed, destroyedGuest.tab);
245 destroyedGuest.destroy();
246 host.attach(key, makeDebuggee({ loading: true }).tab);
247 yield* TestClock.adjust("5 seconds");
248
249 expect(yield* Fiber.join(reader)).toEqual([{ type: "attached", ...key }]);
250 }),
251 );
252
253 it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () =>
254 Effect.gen(function* () {
255 const host = yield* makeDrawnHost;
256 host.attach(key, makeDebuggee().tab);
257 host.setShown(key, true);
258 const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped);
259
260 yield* Effect.yieldNow;
261 host.detach(key);
262 host.attach(key, makeDebuggee().tab);
263
264 expect(yield* Fiber.join(reader)).toEqual([
265 { type: "attached", ...key },
266 { type: "shown", ...key, shown: true },
267 { type: "detached", ...key },
268 { type: "attached", ...key },
269 { type: "shown", ...key, shown: true },
270 ]);
271 }),
272 );
273
274 it.effect("replays an explicit hidden report before announcing another tab", () =>
275 Effect.gen(function* () {
276 const host = yield* makeDrawnHost;
277 const other = { ...key, tabId: "tab-2" };
278 host.setShown(key, false);
279 host.attach(key, makeDebuggee().tab);
280 host.setShown(other, true);
281 host.attach(other, makeDebuggee().tab);
282
283 expect(yield* takeEvents(host, 3)).toEqual([
284 { type: "attached", ...key },
285 { type: "shown", ...key, shown: false },
286 { type: "attached", ...other },
287 ]);
288 }),
289 );
290
291 it.effect("drops replies from a relay the server released", () =>
292 Effect.gen(function* () {
293 const host = yield* makeDrawnHost;
294 const debuggee = makeDebuggee();
295 host.attach(key, debuggee.tab);
296 const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
297
298 yield* Effect.yieldNow;
299 const command = (id: number, method: string) =>
300 host.handleCommandLine(
301 encodeJson({
302 type: "cdp",
303 ...key,
304 message: encodeJson({ id, method, sessionId: "t3-preview-page" }),
305 }),
306 );
307 yield* command(1, "Page.captureScreenshot");
308 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
309 yield* command(2, "DOM.enable");
310 yield* settle;
311 debuggee.release();
312 const [, reply] = yield* Fiber.join(reader);
313
314 expect(reply).toMatchObject({ type: "cdp" });
315 expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2);
316 }),
317 );
318
319 it.effect("sends a page one screenshot at a time", () =>
320 Effect.gen(function* () {
321 const host = yield* makeDrawnHost;
322 const debuggee = makeDebuggee();
323 host.attach(key, debuggee.tab);
324 const replies = yield* watchReplies(host);
325
326 yield* command(host, 1, "Page.captureScreenshot");
327 yield* command(host, 2, "Page.captureScreenshot");
328 yield* command(host, 3, "DOM.enable");
329 yield* settle;
330 expect(debuggee.sent).toEqual([1, 3]);
331
332 debuggee.releaseFirst();
333 expect(yield* Queue.take(replies)).toBe(1);
334 expect(debuggee.sent).toEqual([1, 3, 2]);
335 }),
336 );
337
338 it.effect(
339 "sends a screenshot once the client draws the guest at full detail, or soon after",
340 () =>
341 Effect.gen(function* () {
342 const host = yield* DesktopBrowserHost.make;
343 const debuggee = makeDebuggee();
344 host.attach(key, debuggee.tab);
345 const replies = yield* watchReplies(host);
346
347 yield* command(host, 1, "Page.captureScreenshot");
348 yield* settle;
349 expect(debuggee.sent).toEqual([]);
350 host.setCaptureDrawn(key, true);
351 yield* settle;
352 expect(debuggee.sent).toEqual([1]);
353 debuggee.releaseFirst();
354 expect(yield* Queue.take(replies)).toBe(1);
355
356 // A client that never draws, such as a hidden window, only delays the capture.
357 host.setCaptureDrawn(key, false);
358 yield* command(host, 2, "Page.captureScreenshot");
359 yield* settle;
360 expect(debuggee.sent).toEqual([1]);
361 yield* TestClock.adjust("1 second");
362 yield* settle;
363 expect(debuggee.sent).toEqual([1, 2]);
364 }).pipe(Effect.scoped),
365 );
366
367 it.effect("stops waiting on a screenshot the page navigated away from", () =>
368 Effect.gen(function* () {
369 const host = yield* makeDrawnHost;
370 const debuggee = makeDebuggee();
371 host.attach(key, debuggee.tab);
372 const replies = yield* watchReplies(host);
373
374 yield* command(host, 1, "Page.captureScreenshot");
375 yield* command(host, 2, "Page.captureScreenshot");
376 yield* command(host, 3, "Page.captureScreenshot");
377 yield* settle;
378 debuggee.navigate();
379 expect(debuggee.sent).toEqual([1, 2]);
380
381 // The superseded screenshot answering late must not start a third beside the second.
382 debuggee.releaseFirst();
383 expect(yield* Queue.take(replies)).toBe(1);
384 expect(debuggee.sent).toEqual([1, 2]);
385
386 debuggee.releaseFirst();
387 expect(yield* Queue.take(replies)).toBe(2);
388 expect(debuggee.sent).toEqual([1, 2, 3]);
389 }),
390 );
391
392 it.effect("drops screenshots a released relay left waiting", () =>
393 Effect.gen(function* () {
394 const host = yield* makeDrawnHost;
395 const debuggee = makeDebuggee();
396 host.attach(key, debuggee.tab);
397
398 yield* command(host, 1, "Page.captureScreenshot");
399 yield* command(host, 2, "Page.captureScreenshot");
400 yield* settle;
401 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
402 yield* command(host, 3, "Page.captureScreenshot");
403 expect(debuggee.sent).toEqual([1]);
404
405 const sent = debuggee.nextSend();
406 debuggee.release();
407 yield* Effect.promise(() => sent);
408 expect(debuggee.sent).toEqual([1, 3]);
409 }),
410 );
411
412 it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () =>
413 Effect.gen(function* () {
414 const host = yield* makeDrawnHost;
415 const debuggee = makeDebuggee();
416 host.attach(key, debuggee.tab);
417
418 yield* command(host, 1, "DOM.enable");
419 yield* settle;
420 expect(debuggee.focusEmulation).toEqual([true]);
421 expect(debuggee.sent).toEqual([1]);
422 debuggee.release();
423 yield* settle;
424
425 yield* TestClock.adjust("4 seconds");
426 yield* command(host, 2, "Input.dispatchMouseEvent");
427 yield* settle;
428 debuggee.release();
429 yield* settle;
430 yield* TestClock.adjust("4 seconds");
431 expect(debuggee.focusEmulation).toEqual([true]);
432
433 yield* TestClock.adjust("10 seconds");
434 expect(debuggee.focusEmulation).toEqual([true, false]);
435
436 yield* command(host, 3, "Page.captureScreenshot");
437 yield* settle;
438 expect(debuggee.focusEmulation).toEqual([true, false, true]);
439 expect(debuggee.sent).toEqual([1, 2, 3]);
440 }),
441 );
442
443 it.effect("keeps a guest focused while a command it is running is still pending", () =>
444 Effect.gen(function* () {
445 const host = yield* makeDrawnHost;
446 const debuggee = makeDebuggee();
447 host.attach(key, debuggee.tab);
448 const replies = yield* watchReplies(host);
449
450 // An evaluation awaiting the page's next frame, which a throttled guest never paints.
451 yield* command(host, 1, "Runtime.evaluate");
452 yield* settle;
453 expect(debuggee.sent).toEqual([1]);
454 yield* TestClock.adjust("1 minute");
455 expect(debuggee.focusEmulation).toEqual([true]);
456
457 debuggee.release();
458 expect(yield* Queue.take(replies)).toBe(1);
459 yield* TestClock.adjust("1 minute");
460 expect(debuggee.focusEmulation).toEqual([true, false]);
461 }),
462 );
463
464 it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () =>
465 Effect.gen(function* () {
466 const host = yield* makeDrawnHost;
467 const debuggee = makeDebuggee();
468 host.attach(key, debuggee.tab);
469
470 yield* command(host, 1, "Runtime.evaluate");
471 yield* settle;
472 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
473 yield* TestClock.adjust("1 minute");
474 expect(debuggee.focusEmulation).toEqual([true, false]);
475
476 // A command the old document never answers.
477 yield* command(host, 2, "Page.captureScreenshot");
478 yield* settle;
479 expect(debuggee.sent).toEqual([1, 2]);
480 debuggee.navigate();
481 yield* TestClock.adjust("1 minute");
482 expect(debuggee.focusEmulation).toEqual([true, false, true, false]);
483 }),
484 );
485
486 it.effect("keeps a guest focused for the screenshot a navigation lets start", () =>
487 Effect.gen(function* () {
488 const host = yield* makeDrawnHost;
489 const debuggee = makeDebuggee();
490 host.attach(key, debuggee.tab);
491
492 yield* command(host, 1, "Page.captureScreenshot");
493 yield* command(host, 2, "Page.captureScreenshot");
494 yield* settle;
495 debuggee.navigate();
496 expect(debuggee.sent).toEqual([1, 2]);
497 yield* TestClock.adjust("1 minute");
498 expect(debuggee.focusEmulation).toEqual([true]);
499 }),
500 );
501
502 it.effect("never sends a screenshot a navigation superseded while focus was changing", () =>
503 Effect.gen(function* () {
504 const host = yield* makeDrawnHost;
505 const debuggee = makeDebuggee({ deferFocus: true });
506 host.attach(key, debuggee.tab);
507
508 yield* command(host, 1, "Page.captureScreenshot");
509 yield* command(host, 2, "Page.captureScreenshot");
510 yield* settle;
511 debuggee.navigate();
512 debuggee.settleFocus();
513 yield* settle;
514 // Two captures in flight would undo the one-at-a-time guard.
515 expect(debuggee.sent).toEqual([2]);
516 }),
517 );
518
519 it.effect("keeps a guest focused when its turn starts after the agent's first command", () =>
520 Effect.gen(function* () {
521 const host = yield* makeDrawnHost;
522 const debuggee = makeDebuggee();
523 host.attach(key, debuggee.tab);
524 const turn = (active: boolean) =>
525 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
526
527 yield* command(host, 1, "Input.dispatchKeyEvent");
528 yield* settle;
529 yield* turn(true);
530 debuggee.release();
531 yield* settle;
532 yield* TestClock.adjust("1 minute");
533 expect(debuggee.focusEmulation).toEqual([true]);
534
535 yield* turn(false);
536 yield* TestClock.adjust("1 minute");
537 expect(debuggee.focusEmulation).toEqual([true, false]);
538 }),
539 );
540
541 it.effect("lets a guest throttle through a turn that only sent it housekeeping", () =>
542 Effect.gen(function* () {
543 const host = yield* makeDrawnHost;
544 const debuggee = makeDebuggee();
545 host.attach(key, debuggee.tab);
546 yield* host.handleCommandLine(
547 encodeJson({ type: "turn", threadId: key.threadId, active: true }),
548 );
549
550 // Playwright re-enabling a domain after a reload is not the agent using the tab.
551 yield* command(host, 1, "Runtime.enable");
552 yield* settle;
553 // The relay resets Runtime before a connection's first enable: answer the disable, then the enable.
554 debuggee.release();
555 yield* settle;
556 debuggee.release();
557 yield* settle;
558 yield* TestClock.adjust("1 minute");
559 expect(debuggee.focusEmulation).toEqual([true, false]);
560
561 yield* command(host, 2, "Runtime.evaluate");
562 yield* settle;
563 debuggee.release();
564 yield* settle;
565 yield* TestClock.adjust("1 minute");
566 expect(debuggee.focusEmulation).toEqual([true, false, true]);
567 }),
568 );
569
570 it.effect("keeps a guest the agent used focused through its turn's pauses", () =>
571 Effect.gen(function* () {
572 const host = yield* makeDrawnHost;
573 const debuggee = makeDebuggee();
574 host.attach(key, debuggee.tab);
575 const turn = (active: boolean) =>
576 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
577
578 yield* turn(true);
579 yield* TestClock.adjust("1 minute");
580 expect(debuggee.focusEmulation).toEqual([]);
581
582 yield* command(host, 1, "Input.dispatchKeyEvent");
583 yield* settle;
584 debuggee.release();
585 yield* settle;
586 // The model thinks between steps; a focus-sensitive menu must not blur meanwhile.
587 yield* TestClock.adjust("1 minute");
588 expect(debuggee.focusEmulation).toEqual([true]);
589
590 yield* turn(false);
591 yield* TestClock.adjust("1 minute");
592 expect(debuggee.focusEmulation).toEqual([true, false]);
593 }),
594 );
595
596 it.effect(
597 "ends a command's hold with the turn that sent it, even if Chromium never answers",
598 () =>
599 Effect.gen(function* () {
600 const host = yield* makeDrawnHost;
601 const debuggee = makeDebuggee();
602 host.attach(key, debuggee.tab);
603 yield* host.handleCommandLine(
604 encodeJson({ type: "turn", threadId: key.threadId, active: true }),
605 );
606
607 // A screenshot of a hidden guest the server already gave up on.
608 yield* command(host, 1, "Page.captureScreenshot");
609 yield* settle;
610 expect(debuggee.sent).toEqual([1]);
611 yield* host.handleCommandLine(
612 encodeJson({ type: "turn", threadId: key.threadId, active: false }),
613 );
614 yield* TestClock.adjust("1 minute");
615 expect(debuggee.focusEmulation).toEqual([true, false]);
616 }),
617 );
618
619 it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () =>
620 Effect.gen(function* () {
621 const host = yield* makeDrawnHost;
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 const turn = (active: boolean) =>
628 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
629
630 // The server's own CDP session, evaluating a promise that never settles.
631 yield* turn(true);
632 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
633 expect(yield* Queue.take(replies)).toBe(1);
634 yield* raw({ id: 2, method: "Runtime.evaluate", sessionId: "t3-preview-page-1" });
635 yield* settle;
636 yield* turn(false);
637 yield* TestClock.adjust("1 minute");
638 expect(debuggee.focusEmulation).toEqual([true, false]);
639
640 // A viewer streaming the guest keeps it focused through a turn's end.
641 yield* turn(true);
642 yield* raw({ id: 3, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
643 expect(yield* Queue.take(replies)).toBe(3);
644 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
645 yield* settle;
646 yield* turn(false);
647 yield* TestClock.adjust("1 minute");
648 expect(debuggee.focusEmulation).toEqual([true, false, true]);
649 }),
650 );
651
652 it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () =>
653 Effect.gen(function* () {
654 const host = yield* makeDrawnHost;
655 const debuggee = makeDebuggee();
656 host.attach(key, debuggee.tab);
657 const replies = yield* watchReplies(host);
658 const painting = yield* watchPainting(host);
659 const raw = (message: Record<string, unknown>) =>
660 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
661
662 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
663 expect(yield* Queue.take(replies)).toBe(1);
664 yield* raw({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
665 yield* settle;
666 yield* raw({
667 id: 3,
668 method: "Target.detachFromTarget",
669 params: { sessionId: "t3-preview-page-1" },
670 });
671 expect(yield* Queue.take(replies)).toBe(3);
672 expect(painting).toEqual([true]);
673
674 // The agent's screenshot waits its turn; painting lets the abandoned one finish first.
675 yield* command(host, 4, "Page.captureScreenshot");
676 yield* settle;
677 expect(painting).toEqual([true]);
678 debuggee.release();
679 expect(yield* Queue.take(replies)).toBe(2);
680 yield* settle;
681 expect(debuggee.sent).toEqual([undefined, 4]);
682 expect(painting).toEqual([true]);
683 debuggee.release();
684 expect(yield* Queue.take(replies)).toBe(4);
685 yield* settle;
686 expect(painting).toEqual([true, false]);
687 }),
688 );
689
690 it.effect("stops painting for a queued screenshot once its session detaches", () =>
691 Effect.gen(function* () {
692 const host = yield* makeDrawnHost;
693 const debuggee = makeDebuggee();
694 host.attach(key, debuggee.tab);
695 const replies = yield* watchReplies(host);
696 const painting = yield* watchPainting(host);
697 const raw = (message: Record<string, unknown>) =>
698 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
699 const turn = (active: boolean) =>
700 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
701
702 // The agent's screenshot is abandoned at turn end; a viewer's waits behind it, then leaves.
703 yield* turn(true);
704 yield* command(host, 1, "Page.captureScreenshot");
705 yield* settle;
706 yield* turn(false);
707 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
708 expect(yield* Queue.take(replies)).toBe(2);
709 yield* raw({ id: 3, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
710 yield* settle;
711 expect(painting).toEqual([true]);
712 yield* raw({
713 id: 4,
714 method: "Target.detachFromTarget",
715 params: { sessionId: "t3-preview-page-1" },
716 });
717 expect(yield* Queue.take(replies)).toBe(4);
718
719 // The agent's answers late; the viewer's is dropped unsent, so nothing is left to paint.
720 debuggee.release();
721 yield* settle;
722 expect(debuggee.sent).toEqual([1]);
723 expect(painting).toEqual([true, false]);
724 yield* TestClock.adjust("1 minute");
725 expect(debuggee.focusEmulation).toEqual([true, false]);
726 }),
727 );
728
729 it.effect("never sends a screenshot whose session detached while focus was changing", () =>
730 Effect.gen(function* () {
731 const host = yield* makeDrawnHost;
732 const debuggee = makeDebuggee({ deferFocus: true });
733 host.attach(key, debuggee.tab);
734 const replies = yield* watchReplies(host);
735 const raw = (message: Record<string, unknown>) =>
736 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
737
738 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
739 expect(yield* Queue.take(replies)).toBe(1);
740 yield* raw({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
741 yield* raw({
742 id: 3,
743 method: "Target.detachFromTarget",
744 params: { sessionId: "t3-preview-page-1" },
745 });
746 expect(yield* Queue.take(replies)).toBe(3);
747 debuggee.settleFocus();
748 yield* settle;
749 expect(debuggee.sent).toEqual([]);
750 }),
751 );
752
753 it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () =>
754 Effect.gen(function* () {
755 const host = yield* makeDrawnHost;
756 const debuggee = makeDebuggee();
757 host.attach(key, debuggee.tab);
758 const painting = yield* watchPainting(host);
759 const turn = (active: boolean) =>
760 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
761
762 yield* turn(true);
763 yield* command(host, 1, "Page.captureScreenshot");
764 yield* command(host, 2, "Page.captureScreenshot");
765 yield* settle;
766 yield* turn(false);
767 yield* settle;
768 expect(painting).toEqual([true]);
769
770 // The first answers late; the second still goes in turn, painting but holding no focus.
771 debuggee.releaseFirst();
772 yield* settle;
773 expect(debuggee.sent).toEqual([1, 2]);
774 yield* TestClock.adjust("1 minute");
775 expect(debuggee.focusEmulation).toEqual([true, false]);
776 expect(painting).toEqual([true]);
777 debuggee.release();
778 yield* settle;
779 expect(painting).toEqual([true, false]);
780 }),
781 );
782
783 it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () =>
784 Effect.gen(function* () {
785 const host = yield* makeDrawnHost;
786 const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" });
787 host.attach(key, debuggee.tab);
788 const replies = yield* watchReplies(host);
789 const painting = yield* watchPainting(host);
790 const raw = (message: Record<string, unknown>) =>
791 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
792
793 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
794 expect(yield* Queue.take(replies)).toBe(1);
795 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
796 expect(yield* Queue.take(replies)).toBe(2);
797 yield* settle;
798 expect(painting).toEqual([true, false]);
799 yield* TestClock.adjust("1 minute");
800 expect(debuggee.focusEmulation).toEqual([true, false]);
801 }),
802 );
803
804 it.effect("lets a guest throttle after a person's input through a viewer that then closed", () =>
805 Effect.gen(function* () {
806 const host = yield* makeDrawnHost;
807 const debuggee = makeDebuggee();
808 host.attach(key, debuggee.tab);
809 const replies = yield* watchReplies(host);
810 const raw = (message: Record<string, unknown>) =>
811 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
812
813 yield* host.handleCommandLine(
814 encodeJson({ type: "turn", threadId: key.threadId, active: true }),
815 );
816 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
817 expect(yield* Queue.take(replies)).toBe(1);
818 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
819 yield* raw({ id: 3, method: "Input.dispatchMouseEvent", sessionId: "t3-preview-page-1" });
820 yield* settle;
821 debuggee.release();
822 yield* raw({
823 id: 4,
824 method: "Target.detachFromTarget",
825 params: { sessionId: "t3-preview-page-1" },
826 });
827 yield* settle;
828 yield* TestClock.adjust("1 minute");
829 expect(debuggee.focusEmulation).toEqual([true, false]);
830 }),
831 );
832
833 it.effect("keeps a page's screencast when a child session's screencast is refused", () =>
834 Effect.gen(function* () {
835 const host = yield* makeDrawnHost;
836 const debuggee = makeDebuggee({
837 refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined,
838 });
839 host.attach(key, debuggee.tab);
840 const replies = yield* watchReplies(host);
841 const raw = (message: Record<string, unknown>) =>
842 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
843
844 yield* command(host, 1, "Page.startScreencast");
845 yield* settle;
846 debuggee.release();
847 expect(yield* Queue.take(replies)).toBe(1);
848 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "child-frame" });
849 expect(yield* Queue.take(replies)).toBe(2);
850 yield* TestClock.adjust("1 minute");
851 expect(debuggee.focusEmulation).toEqual([true]);
852 }),
853 );
854
855 it.effect("ignores a screencast that arrives on a session after it detached", () =>
856 Effect.gen(function* () {
857 const host = yield* makeDrawnHost;
858 const debuggee = makeDebuggee();
859 host.attach(key, debuggee.tab);
860 const replies = yield* watchReplies(host);
861 const raw = (message: Record<string, unknown>) =>
862 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
863
864 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
865 expect(yield* Queue.take(replies)).toBe(1);
866 yield* raw({
867 id: 2,
868 method: "Target.detachFromTarget",
869 params: { sessionId: "t3-preview-page-1" },
870 });
871 expect(yield* Queue.take(replies)).toBe(2);
872 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
873 yield* settle;
874 debuggee.release();
875 yield* settle;
876 yield* TestClock.adjust("1 minute");
877 expect(debuggee.focusEmulation).toEqual([true, false]);
878 }),
879 );
880
881 it.effect("lets a guest throttle once the session waiting on its command detaches", () =>
882 Effect.gen(function* () {
883 const host = yield* makeDrawnHost;
884 const debuggee = makeDebuggee();
885 host.attach(key, debuggee.tab);
886 const replies = yield* watchReplies(host);
887 const raw = (message: Record<string, unknown>) =>
888 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
889
890 // A viewer's own CDP session, closed while its still of a hidden guest is pending.
891 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
892 expect(yield* Queue.take(replies)).toBe(1);
893 yield* raw({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
894 yield* settle;
895 yield* TestClock.adjust("1 minute");
896 expect(debuggee.focusEmulation).toEqual([true]);
897
898 yield* raw({
899 id: 3,
900 method: "Target.detachFromTarget",
901 params: { sessionId: "t3-preview-page-1" },
902 });
903 yield* TestClock.adjust("1 minute");
904 expect(debuggee.focusEmulation).toEqual([true, false]);
905 }),
906 );
907
908 it.effect("never sends a screenshot queued by a session that has since detached", () =>
909 Effect.gen(function* () {
910 const host = yield* makeDrawnHost;
911 const debuggee = makeDebuggee();
912 host.attach(key, debuggee.tab);
913 const replies = yield* watchReplies(host);
914 const raw = (message: Record<string, unknown>) =>
915 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
916
917 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
918 expect(yield* Queue.take(replies)).toBe(1);
919 yield* command(host, 2, "Page.captureScreenshot");
920 yield* raw({ id: 3, method: "Page.captureScreenshot", sessionId: "t3-preview-page-1" });
921 yield* raw({
922 id: 4,
923 method: "Target.detachFromTarget",
924 params: { sessionId: "t3-preview-page-1" },
925 });
926 yield* settle;
927 debuggee.release();
928 expect(yield* Queue.take(replies)).toBe(4);
929 // The dropped screenshot's error reply leaves as the first frees its turn.
930 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([3, 2]);
931 yield* settle;
932 expect(debuggee.sent).toEqual([2]);
933
934 yield* TestClock.adjust("1 minute");
935 expect(debuggee.focusEmulation).toEqual([true, false]);
936 }),
937 );
938
939 it.effect("keeps a streamed guest focused until its screencast ends", () =>
940 Effect.gen(function* () {
941 const host = yield* makeDrawnHost;
942 const debuggee = makeDebuggee();
943 host.attach(key, debuggee.tab);
944
945 yield* command(host, 1, "Page.startScreencast");
946 yield* TestClock.adjust("1 minute");
947 expect(debuggee.focusEmulation).toEqual([true]);
948
949 yield* command(host, 2, "Page.stopScreencast");
950 yield* settle;
951 debuggee.release();
952 yield* settle;
953 yield* TestClock.adjust("1 minute");
954 expect(debuggee.focusEmulation).toEqual([true, false]);
955
956 // A viewer whose connection went away without stopping its screencast.
957 yield* command(host, 3, "Page.startScreencast");
958 yield* settle;
959 debuggee.release();
960 yield* settle;
961 yield* TestClock.adjust("1 minute");
962 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
963 yield* TestClock.adjust("1 minute");
964 expect(debuggee.focusEmulation).toEqual([true, false, true, false]);
965 }),
966 );
967
968 it.effect("keeps a guest focused while any of its screencasts runs", () =>
969 Effect.gen(function* () {
970 const host = yield* makeDrawnHost;
971 const debuggee = makeDebuggee();
972 host.attach(key, debuggee.tab);
973 const replies = yield* watchReplies(host);
974 const raw = (message: Record<string, unknown>) =>
975 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
976
977 // Two viewers, or a viewer and a recording, each on its own session.
978 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
979 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
980 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]);
981 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
982 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
983 yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" });
984 yield* settle;
985 debuggee.release();
986 yield* settle;
987 yield* TestClock.adjust("1 minute");
988 expect(debuggee.focusEmulation).toEqual([true]);
989
990 yield* raw({
991 id: 6,
992 method: "Target.detachFromTarget",
993 params: { sessionId: "t3-preview-page-2" },
994 });
995 yield* TestClock.adjust("1 minute");
996 expect(debuggee.focusEmulation).toEqual([true, false]);
997 }),
998 );
999
1000 it.effect("paints a hidden guest only while the screenshot it is taking is pending", () =>
1001 Effect.gen(function* () {
1002 const host = yield* makeDrawnHost;
1003 const debuggee = makeDebuggee();
1004 host.attach(key, debuggee.tab);
1005 const painting = yield* watchPainting(host);
1006
1007 yield* command(host, 1, "DOM.enable");
1008 yield* settle;
1009 expect(painting).toEqual([]);
1010
1011 yield* command(host, 2, "Page.captureScreenshot");
1012 yield* command(host, 3, "Page.captureScreenshot");
1013 yield* settle;
1014 expect(painting).toEqual([true]);
1015
1016 // The first answers once the guest paints; the queued one then takes its turn.
1017 debuggee.release();
1018 yield* settle;
1019 expect(debuggee.sent).toEqual([1, 2, 3]);
1020 debuggee.release();
1021 yield* settle;
1022 expect(painting).toEqual([true, false]);
1023 }),
1024 );
1025
1026 it.effect("stops painting for a screenshot Chromium never answers once its document goes", () =>
1027 Effect.gen(function* () {
1028 const host = yield* makeDrawnHost;
1029 const debuggee = makeDebuggee();
1030 host.attach(key, debuggee.tab);
1031 const painting = yield* watchPainting(host);
1032 const turn = (active: boolean) =>
1033 host.handleCommandLine(encodeJson({ type: "turn", threadId: key.threadId, active }));
1034
1035 // The server gave up on it, and the agent's turn ends; Chromium still holds the capture.
1036 yield* turn(true);
1037 yield* command(host, 1, "Page.captureScreenshot");
1038 yield* settle;
1039 yield* turn(false);
1040 yield* settle;
1041 expect(painting).toEqual([true]);
1042
1043 // The page loads a new document, which also frees the screenshot turn.
1044 debuggee.navigate();
1045 expect(painting).toEqual([true, false]);
1046 yield* command(host, 2, "Page.captureScreenshot");
1047 yield* settle;
1048 debuggee.navigate();
1049 yield* settle;
1050 expect(painting).toEqual([true, false, true, false]);
1051
1052 // The server releases the relay; Chromium still holds the capture.
1053 yield* command(host, 3, "Page.captureScreenshot");
1054 yield* settle;
1055 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
1056 yield* settle;
1057 expect(painting).toEqual([true, false, true, false, true]);
1058
1059 // The guest detaches; a replacement starts with no screenshot pending.
1060 const replacement = makeDebuggee();
1061 host.attach(key, replacement.tab);
1062 expect(painting).toEqual([true, false, true, false, true, false]);
1063 yield* command(host, 4, "Page.captureScreenshot");
1064 yield* settle;
1065 host.detach(key);
1066 yield* settle;
1067 expect(painting).toEqual([true, false, true, false, true, false, true, false]);
1068 }),
1069 );
1070
1071 it.effect("paints a streamed guest until its last screencast ends", () =>
1072 Effect.gen(function* () {
1073 const host = yield* makeDrawnHost;
1074 const debuggee = makeDebuggee();
1075 host.attach(key, debuggee.tab);
1076 const replies = yield* watchReplies(host);
1077 const painting = yield* watchPainting(host);
1078 const raw = (message: Record<string, unknown>) =>
1079 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1080
1081 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1082 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1083 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]);
1084 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
1085 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
1086 yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" });
1087 yield* settle;
1088 debuggee.release();
1089 yield* settle;
1090 expect(painting).toEqual([true]);
1091
1092 yield* raw({
1093 id: 6,
1094 method: "Target.detachFromTarget",
1095 params: { sessionId: "t3-preview-page-2" },
1096 });
1097 yield* settle;
1098 expect(painting).toEqual([true, false]);
1099 }),
1100 );
1101
1102 it.effect("keeps a guest's one screencast running until its last streaming session stops", () =>
1103 Effect.gen(function* () {
1104 const host = yield* DesktopBrowserHost.make;
1105 const debuggee = makeDebuggee();
1106 host.attach(key, debuggee.tab);
1107 const frames: Array<string | undefined> = [];
1108 const replies = yield* watchReplies(host, frames);
1109 const raw = (message: Record<string, unknown>) =>
1110 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1111 const nativeStops = () =>
1112 debuggee.methods.filter((method) => method === "Page.stopScreencast").length;
1113
1114 // A viewer and a recording share Chromium's single screencast for the guest.
1115 yield* raw({ id: 0, method: "Target.setAutoAttach", params: { autoAttach: true } });
1116 expect(yield* Queue.take(replies)).toBe(0);
1117 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1118 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1119 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]);
1120 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
1121 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
1122 yield* settle;
1123 debuggee.release();
1124 yield* raw({ id: 5, method: "Page.stopScreencast", sessionId: "t3-preview-page-1" });
1125 yield* settle;
1126 expect(nativeStops(), "stopped the screencast another session still streams").toBe(0);
1127 debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 1 });
1128 yield* settle;
1129 expect(frames, "sent a stopped or idle session the screencast's frames").toEqual([
1130 "t3-preview-page-2",
1131 ]);
1132
1133 yield* raw({ id: 6, method: "Page.stopScreencast", sessionId: "t3-preview-page-2" });
1134 yield* settle;
1135 expect(nativeStops()).toBe(1);
1136 }),
1137 );
1138
1139 it.effect("keeps a session's screencast when another of its starts is refused", () =>
1140 Effect.gen(function* () {
1141 const host = yield* DesktopBrowserHost.make;
1142 const debuggee = makeDebuggee();
1143 host.attach(key, debuggee.tab);
1144 const frames: Array<string | undefined> = [];
1145 const replies = yield* watchReplies(host, frames);
1146 const raw = (message: Record<string, unknown>) =>
1147 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1148
1149 yield* raw({ id: 0, method: "Target.setAutoAttach", params: { autoAttach: true } });
1150 expect(yield* Queue.take(replies)).toBe(0);
1151 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1152 expect(yield* Queue.take(replies)).toBe(1);
1153 yield* raw({
1154 id: 2,
1155 method: "Page.startScreencast",
1156 params: { id: 2 },
1157 sessionId: "t3-preview-page-1",
1158 });
1159 yield* raw({
1160 id: 3,
1161 method: "Page.startScreencast",
1162 params: { id: 3 },
1163 sessionId: "t3-preview-page-1",
1164 });
1165 yield* settle;
1166 debuggee.refuse(2);
1167 debuggee.release();
1168 expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([2, 3]);
1169 yield* settle;
1170 expect(debuggee.methods).not.toContain("Page.stopScreencast");
1171 debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 1 });
1172 yield* settle;
1173 expect(frames).toContain("t3-preview-page-1");
1174
1175 // A refused replacement leaves the session's running stream, shared with another session.
1176 yield* raw({ id: 4, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1177 expect(yield* Queue.take(replies)).toBe(4);
1178 yield* raw({
1179 id: 5,
1180 method: "Page.startScreencast",
1181 params: { id: 5 },
1182 sessionId: "t3-preview-page-2",
1183 });
1184 yield* raw({
1185 id: 6,
1186 method: "Page.startScreencast",
1187 params: { id: 6 },
1188 sessionId: "t3-preview-page-1",
1189 });
1190 yield* settle;
1191 debuggee.refuse(6);
1192 debuggee.release();
1193 expect([yield* Queue.take(replies), yield* Queue.take(replies)].toSorted()).toEqual([5, 6]);
1194 yield* raw({
1195 id: 7,
1196 method: "Page.screencastFrameAck",
1197 params: { sessionId: 1 },
1198 sessionId: "t3-preview-page-1",
1199 });
1200 expect(yield* Queue.take(replies)).toBe(7);
1201 yield* settle;
1202 frames.length = 0;
1203 debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 2 });
1204 yield* settle;
1205 expect(frames).toEqual(["t3-preview-page-1", "t3-preview-page-2"]);
1206 }),
1207 );
1208
1209 it.effect("stops a guest's screencast once its last streaming session detaches", () =>
1210 Effect.gen(function* () {
1211 const host = yield* DesktopBrowserHost.make;
1212 const debuggee = makeDebuggee();
1213 host.attach(key, debuggee.tab);
1214 const replies = yield* watchReplies(host);
1215 const raw = (message: Record<string, unknown>) =>
1216 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1217 const nativeStops = () =>
1218 debuggee.methods.filter((method) => method === "Page.stopScreencast").length;
1219
1220 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1221 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1222 expect([yield* Queue.take(replies), yield* Queue.take(replies)]).toEqual([1, 2]);
1223 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
1224 yield* raw({ id: 4, method: "Page.startScreencast", sessionId: "t3-preview-page-2" });
1225 yield* settle;
1226 debuggee.release();
1227 // Streamers go without stopping, such as viewers that closed.
1228 yield* raw({
1229 id: 5,
1230 method: "Target.detachFromTarget",
1231 params: { sessionId: "t3-preview-page-1" },
1232 });
1233 yield* settle;
1234 expect(nativeStops(), "stopped the screencast another session still streams").toBe(0);
1235 yield* raw({
1236 id: 6,
1237 method: "Target.detachFromTarget",
1238 params: { sessionId: "t3-preview-page-2" },
1239 });
1240 const answered = [];
1241 for (let reply = 0; reply < 4; reply++) answered.push(yield* Queue.take(replies));
1242 expect(answered.toSorted()).toEqual([3, 4, 5, 6]);
1243 yield* settle;
1244 expect(nativeStops()).toBe(1);
1245 }),
1246 );
1247
1248 it.effect("stops a screencast whose start lands after its session detached", () =>
1249 Effect.gen(function* () {
1250 const host = yield* DesktopBrowserHost.make;
1251 const debuggee = makeDebuggee({ deferFocus: true });
1252 host.attach(key, debuggee.tab);
1253 const replies = yield* watchReplies(host);
1254 const raw = (message: Record<string, unknown>) =>
1255 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1256
1257 yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1258 expect(yield* Queue.take(replies)).toBe(1);
1259 // The start waits on focus emulation while the viewer closes.
1260 yield* raw({ id: 2, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
1261 yield* raw({
1262 id: 3,
1263 method: "Target.detachFromTarget",
1264 params: { sessionId: "t3-preview-page-1" },
1265 });
1266 expect(yield* Queue.take(replies)).toBe(3);
1267 debuggee.settleFocus();
1268 yield* settle;
1269 debuggee.release();
1270 expect(yield* Queue.take(replies)).toBe(2);
1271 yield* settle;
1272 expect(debuggee.methods.at(-1), "left the late screencast running").toBe(
1273 "Page.stopScreencast",
1274 );
1275 }),
1276 );
1277
1278 it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
1279 Effect.gen(function* () {
1280 const host = yield* makeDrawnHost;
1281 const debuggee = makeDebuggee();
1282 host.attach(key, debuggee.tab);
1283 const replies = yield* watchReplies(host);
1284 const paths: Array<string> = [];
1285 const item = {
1286 setSavePath: (path: string) => void paths.push(path),
1287 } as unknown as Electron.DownloadItem;
1288
1289 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);
1290 const sent = debuggee.nextSend();
1291 yield* host.handleCommandLine(
1292 encodeJson({
1293 type: "cdp",
1294 ...key,
1295 message: encodeJson({
1296 id: 1,
1297 method: "Browser.setDownloadBehavior",
1298 params: { behavior: "allowAndName", downloadPath: "/srv/downloads" },
1299 }),
1300 }),
1301 );
1302 yield* Effect.promise(() => sent);
1303 debuggee.release();
1304 expect(yield* Queue.take(replies)).toBe(1);
1305 debuggee.emit("Page.downloadWillBegin", { guid: "guid-1", suggestedFilename: "r.csv" });
1306 expect(host.placeDownload(makeDebuggee().tab.webContents, item)).toBe(false);
1307 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true);
1308 expect(paths).toEqual(["/srv/downloads/guid-1"]);
1309 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);
1310 }),
1311 );
1312
1313 it.effect("tells a download the person clicked from one the agent's input started", () =>
1314 Effect.gen(function* () {
1315 const host = yield* makeDrawnHost;
1316 const debuggee = makeDebuggee();
1317 host.attach(key, debuggee.tab);
1318
1319 yield* host.handleCommandLine(
1320 encodeJson({
1321 type: "cdp",
1322 ...key,
1323 message: encodeJson({ id: 1, method: "DOM.getDocument", params: {} }),
1324 }),
1325 );
1326 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(true);
1327 yield* host.handleCommandLine(
1328 encodeJson({
1329 type: "cdp",
1330 ...key,
1331 message: encodeJson({
1332 id: 2,
1333 method: "Input.dispatchMouseEvent",
1334 params: { type: "mousePressed", x: 1, y: 1 },
1335 }),
1336 }),
1337 );
1338 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false);
1339 }),
1340 );
1341
1342 it.effect("stops crediting the agent once a person acts through a viewer", () =>
1343 Effect.gen(function* () {
1344 const host = yield* DesktopBrowserHost.make;
1345 const debuggee = makeDebuggee();
1346 host.attach(key, debuggee.tab);
1347 const replies = yield* watchReplies(host);
1348 const raw = (message: Record<string, unknown>) =>
1349 host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) }));
1350 const viewer = (id: number, method: string, type: string) =>
1351 raw({ id, method, params: { type }, sessionId: "t3-preview-page-1" });
1352 const led = () => host.agentLedPage(debuggee.tab.webContents);
1353
1354 yield* command(host, 1, "DOM.getDocument");
1355 expect(led()).toBe(false);
1356 yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } });
1357 expect(yield* Queue.take(replies)).toBe(2);
1358 yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" });
1359
1360 for (const [method, type] of [
1361 ["Input.dispatchKeyEvent", "rawKeyDown"],
1362 ["Input.dispatchMouseEvent", "mousePressed"],
1363 ["Input.dispatchTouchEvent", "touchStart"],
1364 ] as const) {
1365 yield* command(host, 4, "Runtime.evaluate");
1366 expect(led()).toBe(true);
1367 // The viewer's pointer only passes over the page the agent drives.
1368 yield* viewer(5, "Input.dispatchMouseEvent", "mouseMoved");
1369 yield* viewer(6, "Input.dispatchMouseEvent", "mouseWheel");
1370 expect(led()).toBe(true);
1371 yield* viewer(7, method, type);
1372 expect(led()).toBe(false);
1373 }
1374 }).pipe(Effect.scoped),
1375 );
1376
1377 it.effect("detaches only the tab whose CDP event is too large to relay", () =>
1378 Effect.gen(function* () {
1379 const host = yield* makeDrawnHost;
1380 const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()];
1381 const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand");
1382 const keys = [key, { threadId: "thread-2", tabId: "tab-2" }];
1383 const events = yield* Queue.unbounded<DesktopBrowserEvent>();
1384 yield* host.events.pipe(
1385 Stream.runForEach((line) =>
1386 Queue.offer(events, decodeEvent(new TextDecoder().decode(line))),
1387 ),
1388 Effect.forkScoped,
1389 );
1390 for (const [index, tabKey] of keys.entries()) {
1391 host.attach(tabKey, tabs[index]!.tab);
1392 expect(yield* Queue.take(events)).toEqual({ type: "attached", ...tabKey });
1393 yield* host.handleCommandLine(
1394 encodeJson({
1395 type: "cdp",
1396 ...tabKey,
1397 message: encodeJson({ id: 1, method: "Target.setAutoAttach" }),
1398 }),
1399 );
1400 // The command's reply and the page announcement.
1401 yield* Queue.takeN(events, 2);
1402 }
1403
1404 yield* host.handleCommandLine(
1405 encodeJson({
1406 type: "cdp",
1407 ...key,
1408 message: encodeJson({
1409 id: 2,
1410 method: "Target.setAutoAttach",
1411 params: { autoAttach: true, waitForDebuggerOnStart: true, flatten: true },
1412 sessionId: "t3-preview-page",
1413 }),
1414 }),
1415 );
1416 yield* command(host, 3, "Page.startScreencast");
1417 tabs[0]!.emit("Runtime.consoleAPICalled", {
1418 args: Array(2048).fill("x".repeat(40 * 1024)),
1419 });
1420 tabs[1]!.emit("Page.loadEventFired", { timestamp: 1 });
1421 const [detached, next] = yield* Queue.takeN(events, 2);
1422
1423 const { type, threadId, tabId } = detached!;
1424 expect({ type, threadId, tabId }).toEqual({ type: "detached", ...key });
1425 expect(send).toHaveBeenCalledWith("Target.setAutoAttach", {
1426 autoAttach: false,
1427 waitForDebuggerOnStart: false,
1428 flatten: true,
1429 });
1430 tabs[0]!.settleFocus();
1431 yield* settle;
1432 expect(send).not.toHaveBeenCalledWith("Target.setAutoAttach", {
1433 autoAttach: true,
1434 waitForDebuggerOnStart: true,
1435 flatten: true,
1436 });
1437 expect(send).toHaveBeenCalledWith("Page.stopScreencast");
1438 expect(tabs[0]!.focusEmulation).toEqual([true, false]);
1439 expect(next).toMatchObject({ type: "cdp", ...keys[1] });
1440 expect(JSON.parse((next as { message: string }).message)).toMatchObject({
1441 method: "Page.loadEventFired",
1442 });
1443 }),
1444 );
1445 });