Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Names download files on the shared disk.
2/** The manager owns the single debugger attachment; the relay shares it. */
3import {
4 DesktopBrowserCommand,
5 DesktopBrowserEvent,
6 type DesktopBrowserEvent as DesktopBrowserEventType,
7 type PreviewAutomationLoadError,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as NodePath from "node:path";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as PubSub from "effect/PubSub";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18
19import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
20import {
21 type FrameDetachWatch,
22 type PointerRoute,
23 routeMouseToFrame,
24 sendPageCommand,
25} from "./GuestInput.ts";
26
27const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
28const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
29const lineEncoder = new TextEncoder();
30const AGENT_INPUT_COMMAND =
31 /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/;
32/** The same commands as above, by method, for the relay's sends. */
33const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/;
34const AGENT_INPUT_WINDOW_MS = 5_000;
35/** A viewer's pointer travelling over the stream activates nothing on the page. */
36const POINTER_TRAVEL = new Set<unknown>(["mouseMoved", "mouseWheel"]);
37const ANNOTATING_MESSAGE =
38 "This page is being annotated in the desktop app. Input resumes when the annotation ends.";
39const FOCUS_IDLE = "5 seconds";
40/** How long a screenshot waits for the client to draw its guest at full detail. */
41const CAPTURE_DRAW_WAIT = "1 second";
42/** Most waits settle within a frame or two of this, so a quick one is never prodded. */
43const PAINT_NUDGE_FIRST_MS = 250;
44/** A long wait, such as a page awaiting a timer, is prodded less often as it goes on. */
45const PAINT_NUDGE_LONGEST_MS = 2_000;
46/** Electron's capture has no deadline and a cold guest can stall one, so a second may follow. */
47const PAINT_NUDGE_IN_FLIGHT = 2;
48/** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */
49const FIRST_PAGE_TIMEOUT = "5 seconds";
50const ERR_ABORTED = -3;
51
52export interface DesktopBrowserTabKey {
53 readonly threadId: string;
54 readonly tabId: string;
55}
56
57export interface DesktopBrowserTabDebugger {
58 readonly webContents: Electron.WebContents;
59 readonly debugger: Electron.Debugger;
60 /** Runs after the server clears the tab's cookies, so state kept beside them goes too. */
61 readonly cookiesCleared?: () => Promise<void>;
62 /** Whether the person at this window is annotating the page, whose overlay is theirs alone. */
63 readonly annotating?: () => boolean;
64}
65
66const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
67
68const trackFrameSession = (
69 tab: {
70 readonly frameSessions: Map<string, string>;
71 readonly frameDetachListeners: Map<string, Set<() => void>>;
72 },
73 method: string,
74 params: unknown,
75) => {
76 if (method === "Target.attachedToTarget") {
77 const { sessionId, targetInfo } = params as {
78 readonly sessionId?: string;
79 readonly targetInfo?: { readonly targetId?: string; readonly type?: string };
80 };
81 if (targetInfo?.type === "iframe" && targetInfo.targetId && sessionId) {
82 tab.frameSessions.set(targetInfo.targetId, sessionId);
83 }
84 } else if (method === "Target.detachedFromTarget") {
85 const { sessionId } = params as { readonly sessionId?: string };
86 for (const [frameId, frameSession] of tab.frameSessions) {
87 if (frameSession === sessionId) tab.frameSessions.delete(frameId);
88 }
89 if (sessionId === undefined) return;
90 const listeners = tab.frameDetachListeners.get(sessionId);
91 tab.frameDetachListeners.delete(sessionId);
92 for (const listener of listeners ?? []) listener();
93 }
94};
95
96const watchFrameDetach =
97 (tab: {
98 readonly frameSessions: Map<string, string>;
99 readonly frameDetachListeners: Map<string, Set<() => void>>;
100 }): FrameDetachWatch =>
101 (sessionId, listener) => {
102 if (![...tab.frameSessions.values()].includes(sessionId)) {
103 listener();
104 return () => {};
105 }
106 const listeners = tab.frameDetachListeners.get(sessionId) ?? new Set();
107 tab.frameDetachListeners.set(sessionId, listeners);
108 listeners.add(listener);
109 return () => {
110 listeners.delete(listener);
111 if (listeners.size === 0 && tab.frameDetachListeners.get(sessionId) === listeners) {
112 tab.frameDetachListeners.delete(sessionId);
113 }
114 };
115 };
116
117interface AttachedTab {
118 readonly key: DesktopBrowserTabKey;
119 readonly debuggee: DesktopBrowserTabDebugger;
120 relay: CdpRelayConnection | null;
121 screenshotTurn: object | null;
122 /** Each keeps the guest painting while whoever queued it still waits, and focused while `held`. */
123 readonly waitingScreenshots: Array<{
124 readonly start: () => void;
125 readonly live: () => boolean;
126 held: boolean;
127 }>;
128 downloadDirectory: string | null;
129 pendingDownloadGuid: string | null;
130 agentInputAt: number;
131 /** When the agent last drove the page with no person's input through a viewer since. */
132 agentLedAt: number;
133 focusEmulated: boolean;
134 focusChange: Promise<void> | null;
135 focusUses: number;
136 /** Each pending command, by the extra session waiting on it; the main connection's have none. */
137 readonly focusPending: Map<object, string | undefined>;
138 /** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */
139 readonly capturing: Set<object>;
140 /** Each wait on the guest's next frame, as whether it still waits; the guest is prodded until none do. */
141 readonly frameWaits: Set<() => boolean>;
142 /** Sessions of the guest's cross-site frames that Chromium attached, by frame id. */
143 readonly frameSessions: Map<string, string>;
144 /** Input sent to a frame session, waiting to learn if the frame detaches first. */
145 readonly frameDetachListeners: Map<string, Set<() => void>>;
146 nudging: Fiber.Fiber<void> | null;
147 /** A wait outlasted its first nudge, so the guest is painted and unthrottled like a capture. */
148 frameStalled: boolean;
149 /** Whether the client keeps the guest painting, as published on `painting`. */
150 painting: boolean;
151 /**
152 * Driven by the agent since its thread's last turn ended or the guest last throttled. A
153 * turn's start can reach us after its first command, so this holds focus once it does.
154 */
155 agentUsed: boolean;
156 focusReleasing: boolean;
157 /** The sessions sharing the guest's one Chromium screencast; it stops with the last of them. */
158 readonly screencasts: Map<string | undefined, { started: boolean; pending: number }>;
159 readonly onMessage: (
160 event: Electron.Event,
161 method: string,
162 params: unknown,
163 sessionId: string,
164 ) => void;
165 readonly onNewDocument: () => void;
166 /** Stops waiting for the first page; set until the tab is announced. */
167 stopWaiting: (() => void) | null;
168}
169
170export class DesktopBrowserHost extends Context.Service<
171 DesktopBrowserHost,
172 {
173 readonly events: Stream.Stream<Uint8Array>;
174 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
175 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
176 readonly detach: (key: DesktopBrowserTabKey) => void;
177 readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void;
178 readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
179 /** Whether the client draws the guest at full detail while it is captured. */
180 readonly setCaptureDrawn: (key: DesktopBrowserTabKey, drawn: boolean | undefined) => void;
181 readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
182 /** Whether what the page does now follows the agent's input, not a viewer's. */
183 readonly agentLedPage: (source: Electron.WebContents) => boolean;
184 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
185 readonly pointers: Stream.Stream<{
186 readonly key: DesktopBrowserTabKey;
187 readonly phase: "move" | "click";
188 readonly x: number;
189 readonly y: number;
190 }>;
191 /** Whether a guest needs its frames painted while the panel hides it. */
192 readonly painting: Stream.Stream<{
193 readonly key: DesktopBrowserTabKey;
194 readonly active: boolean;
195 }>;
196 }
197>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
198
199export const make = Effect.gen(function* () {
200 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
201 const pointers = yield* PubSub.sliding<{
202 readonly key: DesktopBrowserTabKey;
203 readonly phase: "move" | "click";
204 readonly x: number;
205 readonly y: number;
206 }>(16);
207 const painting = yield* PubSub.unbounded<{
208 readonly key: DesktopBrowserTabKey;
209 readonly active: boolean;
210 }>();
211 const runFork = Effect.runForkWith(yield* Effect.context<never>());
212 const tabs = new Map<string, AttachedTab>();
213 /** Threads whose agent turn runs, by the server's account. */
214 const agentTurns = new Set<string>();
215 // Kept apart from attachment: the renderer can show a webview before its debugger attaches,
216 // and the server forgets `shown` on detach, for example while DevTools holds the debugger.
217 const shownTabs = new Map<string, boolean>();
218 const drawnTabs = new Set<string>();
219 const drawWaiters = new Map<string, Set<() => void>>();
220 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
221
222 const nextScreenshot = (tab: AttachedTab) => {
223 tab.screenshotTurn = null;
224 tab.waitingScreenshots.shift()?.start();
225 releaseFocusWhenIdle(tab);
226 syncPainting(tab);
227 };
228
229 /**
230 * Chromium below 157 crashes the whole app when a guest's renderer exits with a
231 * screenshot copy in flight (crbug.com/567321049). Overlapping screenshots make that
232 * far likelier, and one the server gave up on stays pending in Chromium, so each guest
233 * gets one at a time. One whose relay or session has since gone is dropped unsent.
234 */
235 const takeScreenshot = (
236 tab: AttachedTab,
237 relay: CdpRelayConnection,
238 ownerLive: () => boolean,
239 /** Sends only while `current` holds; holds focus only while `held`. */
240 capture: (current: () => boolean, held: boolean) => Promise<unknown>,
241 ) =>
242 new Promise<unknown>((resolve, reject) => {
243 const live = () => tab.relay === relay && ownerLive();
244 const waiting = {
245 start: () => {
246 if (!live()) {
247 reject(new Error("The preview connection that asked for this screenshot closed."));
248 nextScreenshot(tab);
249 return;
250 }
251 const turn = {};
252 tab.screenshotTurn = turn;
253 capture(() => tab.screenshotTurn === turn && live(), waiting.held)
254 .finally(() => {
255 if (tab.screenshotTurn === turn) nextScreenshot(tab);
256 })
257 .then(resolve, reject);
258 },
259 live,
260 held: true,
261 };
262 if (tab.screenshotTurn === null) waiting.start();
263 else {
264 // The one ahead may be abandoned mid-capture; it needs frames to finish and free its turn.
265 tab.waitingScreenshots.push(waiting);
266 setFocusEmulation(tab, true);
267 syncPainting(tab);
268 }
269 });
270
271 /**
272 * Chromium counts a focus-emulated guest as captured, so a guest the panel hides would
273 * never throttle. Without it, a hidden guest paints no frames and focus() fires no focus
274 * events, so the guest is emulated focused while the server drives it or streams it.
275 */
276 const setFocusEmulation = (tab: AttachedTab, enabled: boolean) => {
277 if (tab.focusEmulated === enabled) return;
278 tab.focusEmulated = enabled;
279 // A guest that refuses it, or a debugger already gone, behaves as unfocused.
280 const change: Promise<void> = tab.debuggee.debugger
281 .sendCommand("Emulation.setFocusEmulationEnabled", { enabled })
282 .then(
283 () => undefined,
284 () => undefined,
285 )
286 .finally(() => {
287 if (tab.focusChange === change) tab.focusChange = null;
288 });
289 tab.focusChange = change;
290 };
291
292 const waitingHolds = (tab: AttachedTab) =>
293 tab.waitingScreenshots.some((waiting) => waiting.held && waiting.live());
294
295 const releaseFocusWhenIdle = (tab: AttachedTab) => {
296 if (tab.focusReleasing) return;
297 tab.focusReleasing = true;
298 runFork(
299 Effect.gen(function* () {
300 let uses: number;
301 do {
302 uses = tab.focusUses;
303 yield* Effect.sleep(FOCUS_IDLE);
304 } while (uses !== tab.focusUses);
305 tab.focusReleasing = false;
306 // The last pending command to settle starts another idle wait.
307 if (tab.focusPending.size > 0 || tab.screencasts.size > 0 || waitingHolds(tab)) {
308 return;
309 }
310 // The agent pauses to think between steps; its tab stays focused until the turn ends.
311 if (tab.agentUsed && agentTurns.has(tab.key.threadId)) return;
312 tab.agentUsed = false;
313 if (tabs.get(keyOf(tab.key)) === tab) setFocusEmulation(tab, false);
314 }),
315 );
316 };
317
318 /**
319 * Electron composites no offscreen guest, so a screenshot, screencast or stalled command waits for a frame
320 * that never comes. The client paints the guest behind the app while one is pending; the
321 * capture then finishes on its own, and the guest goes back offscreen once none is.
322 */
323 const syncPainting = (tab: AttachedTab) => {
324 const active =
325 tabs.get(keyOf(tab.key)) === tab &&
326 (tab.screencasts.size > 0 ||
327 tab.capturing.size > 0 ||
328 tab.frameStalled ||
329 tab.waitingScreenshots.some((waiting) => waiting.live()));
330 if (tab.painting === active) return;
331 tab.painting = active;
332 runFork(PubSub.publish(painting, { key: tab.key, active }));
333 };
334
335 /** By guest rather than attachment, since reopening DevTools reattaches the same guest. */
336 const nativeCaptures = new WeakMap<Electron.WebContents, number>();
337 const startNudging = (tab: AttachedTab) => {
338 tab.nudging ??= runFork(nudgePaint(tab, PAINT_NUDGE_FIRST_MS));
339 };
340
341 const endNudging = (tab: AttachedTab) => {
342 tab.nudging = null;
343 if (!tab.frameStalled) return;
344 tab.frameStalled = false;
345 syncPainting(tab);
346 };
347
348 /**
349 * A hidden, minimized or covered window (which Electron reports as visible) stops drawing its
350 * guest, so a wait on its next frame never ends. Electron's own capture still draws one.
351 */
352 const nudgePaint = (tab: AttachedTab, delayMs: number): Effect.Effect<void> =>
353 Effect.sleep(delayMs).pipe(
354 Effect.andThen(
355 Effect.suspend(() => {
356 const { webContents } = tab.debuggee;
357 for (const waits of tab.frameWaits) if (!waits()) tab.frameWaits.delete(waits);
358 if (
359 tab.frameWaits.size === 0 ||
360 tabs.get(keyOf(tab.key)) !== tab ||
361 webContents.isDestroyed()
362 ) {
363 endNudging(tab);
364 return Effect.void;
365 }
366 // On Windows a hidden window's throttled guest draws nothing, and capturePage cannot wake it.
367 if (!tab.frameStalled) {
368 tab.frameStalled = true;
369 syncPainting(tab);
370 }
371 const inFlight = nativeCaptures.get(webContents) ?? 0;
372 if (inFlight < PAINT_NUDGE_IN_FLIGHT) {
373 nativeCaptures.set(webContents, inFlight + 1);
374 const settled = () => {
375 nativeCaptures.set(webContents, (nativeCaptures.get(webContents) ?? 1) - 1);
376 };
377 webContents.capturePage().then(settled, settled);
378 }
379 return nudgePaint(tab, Math.min(delayMs * 2, PAINT_NUDGE_LONGEST_MS));
380 }),
381 ),
382 );
383
384 /** Prods the guest while `work` is pending and `waits` holds; one loop serves all of a tab's waits. */
385 const nudgedUntilSettled = <A>(
386 tab: AttachedTab,
387 waits: () => boolean,
388 work: () => Promise<A>,
389 ) => {
390 tab.frameWaits.add(waits);
391 startNudging(tab);
392 return work().finally(() => {
393 tab.frameWaits.delete(waits);
394 if (tab.frameWaits.size > 0 || tab.nudging === null) return;
395 runFork(Fiber.interrupt(tab.nudging));
396 endNudging(tab);
397 });
398 };
399
400 /** A command may wait on the page's next frame, so the guest stays focused until it settles. */
401 const holdFocus = <A>(tab: AttachedTab, owner: string | undefined, work: () => Promise<A>) => {
402 const pending = {};
403 tab.focusPending.set(pending, owner);
404 tab.focusUses += 1;
405 setFocusEmulation(tab, true);
406 releaseFocusWhenIdle(tab);
407 // Dropping the hold, at a turn's end or a new document, stops the prods too.
408 return nudgedUntilSettled(tab, () => tab.focusPending.has(pending), work).finally(() => {
409 if (!tab.focusPending.delete(pending)) return;
410 tab.focusUses += 1;
411 releaseFocusWhenIdle(tab);
412 });
413 };
414
415 /**
416 * A scaled guest rasters at its on-screen size until the client draws it at full detail,
417 * and a screenshot taken before that copies the blurred frame. A client that cannot draw
418 * (a hidden window, say) only delays the capture.
419 */
420 const whenDrawn = (tab: AttachedTab) =>
421 new Promise<void>((resolve) => {
422 const id = keyOf(tab.key);
423 const waiters = drawWaiters.get(id) ?? new Set();
424 drawWaiters.set(id, waiters);
425 const done = () => {
426 waiters.delete(done);
427 if (waiters.size === 0 && drawWaiters.get(id) === waiters) drawWaiters.delete(id);
428 resolve();
429 };
430 waiters.add(done);
431 runFork(Effect.sleep(CAPTURE_DRAW_WAIT).pipe(Effect.andThen(Effect.sync(done))));
432 });
433
434 /** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */
435 const paintUntilAnswered = <A>(tab: AttachedTab, send: () => Promise<A>) => {
436 const sent = {};
437 tab.capturing.add(sent);
438 syncPainting(tab);
439 const sendNudged = () => nudgedUntilSettled(tab, () => tab.capturing.has(sent), send);
440 // Sent at once when already drawn, so it keeps its place among the commands after it.
441 return (drawnTabs.has(keyOf(tab.key)) ? sendNudged() : whenDrawn(tab).then(sendNudged)).finally(
442 () => {
443 tab.capturing.delete(sent);
444 syncPainting(tab);
445 },
446 );
447 };
448
449 /**
450 * Chromium can leave a command unanswered, so the screenshot guard's release points
451 * also end every focus hold: a released relay has no one waiting, and a new document
452 * answers nothing pending from the old one. A released relay's screencast has no viewer.
453 */
454 const dropFocusHolds = (tab: AttachedTab) => {
455 tab.focusPending.clear();
456 releaseFocusWhenIdle(tab);
457 syncPainting(tab);
458 };
459
460 const dropRelay = (tab: AttachedTab) => {
461 tab.relay = null;
462 tab.screencasts.clear();
463 tab.agentUsed = false;
464 dropFocusHolds(tab);
465 };
466
467 /** An owner that leaves without stopping would otherwise keep the screencast running unseen. */
468 const leaveScreencast = (tab: AttachedTab, owner: string | undefined) => {
469 if (!tab.screencasts.delete(owner) || tab.screencasts.size > 0) return;
470 void tab.debuggee.debugger.sendCommand("Page.stopScreencast").catch(() => {});
471 };
472
473 /** A detached session, such as a closed viewer, waits on nothing it sent. */
474 const dropSessionHolds = (tab: AttachedTab, owner: string) => {
475 leaveScreencast(tab, owner);
476 for (const [pending, holder] of tab.focusPending) {
477 if (holder === owner) tab.focusPending.delete(pending);
478 }
479 releaseFocusWhenIdle(tab);
480 syncPainting(tab);
481 };
482
483 /**
484 * A command the server stopped waiting on, such as a timed-out screenshot or evaluation,
485 * may never settle; the turn's end ends every focus hold. The agent also sends on its own extra
486 * session, so this cannot spare other sessions; a viewer's screencast still holds.
487 */
488 const endAgentTurn = (threadId: string) => {
489 agentTurns.delete(threadId);
490 for (const tab of tabs.values()) {
491 if (tab.key.threadId !== threadId) continue;
492 tab.agentUsed = false;
493 // Still sent in turn, so the queue keeps moving, but no longer kept focused.
494 for (const waiting of tab.waitingScreenshots) waiting.held = false;
495 dropFocusHolds(tab);
496 }
497 };
498
499 const relayFor = (tab: AttachedTab) => {
500 if (tab.relay) return tab.relay;
501 const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee;
502 const routeHidden = routeMouseToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab));
503 // Read when the pointer queue reaches the event: a guest the window shows routes its own input.
504 const routeMouse: PointerRoute = (params) =>
505 shownTabs.get(keyOf(tab.key)) === true ? Promise.resolve(null) : routeHidden(params);
506 // The annotation overlay lives in the guest and takes any input sent there as the
507 // person's at this window, so relayed input waits until they finish.
508 const annotated = (method: string) =>
509 method.startsWith("Input.") && tab.debuggee.annotating?.() === true;
510 const send = async (method: string, params: Record<string, unknown>, sessionId?: string) => {
511 // Asked again at each dispatch: an annotation can start while the input waits its turn.
512 const refuseAnnotated = () => {
513 if (annotated(method)) throw new Error(ANNOTATING_MESSAGE);
514 };
515 refuseAnnotated();
516 const result = await sendPageCommand(
517 webContents,
518 debuggee,
519 method,
520 params,
521 sessionId,
522 routeMouse,
523 refuseAnnotated,
524 );
525 if (method === "Network.clearBrowserCookies") await cookiesCleared?.();
526 return result;
527 };
528 const detachedOwners = new Set<string>();
529 /** Viewers and recordings stream; the agent's own sessions never do. */
530 const streamingOwners = new Set<string>();
531 const relay: CdpRelayConnection = createCdpRelayConnection(
532 {
533 send: (method, params, sessionId, owner) => {
534 // A child session's screencast is not the page's, such as a late one on a detached session.
535 const stream =
536 sessionId === undefined && method === "Page.startScreencast"
537 ? (tab.screencasts.get(owner) ?? { started: false, pending: 0 })
538 : undefined;
539 if (stream) {
540 stream.pending += 1;
541 tab.screencasts.set(owner, stream);
542 if (owner !== undefined) streamingOwners.add(owner);
543 syncPainting(tab);
544 } else if (sessionId === undefined && method === "Page.stopScreencast") {
545 tab.screencasts.delete(owner);
546 syncPainting(tab);
547 if (tab.screencasts.size > 0) return Promise.resolve({});
548 }
549 if (annotated(method)) return Promise.reject(new Error(ANNOTATING_MESSAGE));
550 // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's.
551 if (AGENT_INPUT_METHOD.test(method)) {
552 if (owner === undefined || !streamingOwners.has(owner)) {
553 tab.agentUsed = true;
554 tab.agentLedAt = performance.now();
555 } else if (method.startsWith("Input.") && !POINTER_TRAVEL.has(params["type"])) {
556 tab.agentLedAt = Number.NEGATIVE_INFINITY;
557 }
558 }
559 // Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
560 const forward = (current?: () => boolean) => {
561 const change = tab.focusChange;
562 const stale = () => tab.relay !== relay || (current !== undefined && !current());
563 const sendUnlessStale = () =>
564 stale()
565 ? Promise.reject(new Error("The page this screenshot was for has moved on."))
566 : send(method, params, sessionId);
567 const run = () =>
568 current === undefined || stale()
569 ? sendUnlessStale()
570 : paintUntilAnswered(tab, sendUnlessStale);
571 return change === null ? run() : change.then(run);
572 };
573 return method === "Page.captureScreenshot"
574 ? takeScreenshot(
575 tab,
576 relay,
577 () => owner === undefined || !detachedOwners.has(owner),
578 (current, held) =>
579 held ? holdFocus(tab, owner, () => forward(current)) : forward(current),
580 )
581 : method === "Page.startScreencast"
582 ? holdFocus(tab, owner, forward).then(
583 (result) => {
584 if (stream) {
585 stream.pending -= 1;
586 stream.started = true;
587 // A detach's stop can overtake a start still waiting on focus; nobody owns it now.
588 if (tab.screencasts.get(owner) !== stream && tab.screencasts.size === 0) {
589 void debuggee.sendCommand("Page.stopScreencast").catch(() => {});
590 }
591 }
592 return result;
593 },
594 (cause: unknown) => {
595 if (stream) stream.pending -= 1;
596 // A viewer can outlive a refused start; its running or pending stream still holds it.
597 if (
598 stream &&
599 !stream.started &&
600 stream.pending === 0 &&
601 tab.relay === relay &&
602 tab.screencasts.get(owner) === stream
603 ) {
604 leaveScreencast(tab, owner);
605 }
606 releaseFocusWhenIdle(tab);
607 syncPainting(tab);
608 throw cause;
609 },
610 )
611 : holdFocus(tab, owner, forward);
612 },
613 sessionDetached: (owner) => {
614 detachedOwners.add(owner);
615 dropSessionHolds(tab, owner);
616 },
617 receivesScreencast: (owner) => tab.screencasts.has(owner),
618 ackScreencastFrame: (frameId) =>
619 void debuggee
620 .sendCommand("Page.screencastFrameAck", { sessionId: frameId })
621 .catch(() => {}),
622 targetId: () =>
623 debuggee
624 .sendCommand("Target.getTargetInfo")
625 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
626 url: () => webContents.getURL(),
627 title: () => webContents.getTitle(),
628 userAgent: () => webContents.getUserAgent(),
629 setDownloadDirectory: (directory) => {
630 tab.downloadDirectory = directory;
631 },
632 },
633 (message) => {
634 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
635 emit({ type: "cdp", ...tab.key, message });
636 }
637 },
638 // Announcing the tab again would reconnect Playwright, and the page could
639 // replay the same oversized event, so the tab stays detached.
640 () => {
641 if (tab.relay !== relay || tabs.get(keyOf(tab.key)) !== tab) return;
642 // Disabling auto-attach detaches child sessions and releases their debugger pauses.
643 void debuggee
644 .sendCommand("Target.setAutoAttach", {
645 autoAttach: false,
646 waitForDebuggerOnStart: false,
647 flatten: true,
648 })
649 .catch(() => {});
650 if (tab.screencasts.size > 0) {
651 void debuggee.sendCommand("Page.stopScreencast").catch(() => {});
652 }
653 setFocusEmulation(tab, false);
654 detach(tab.key);
655 },
656 );
657 tab.relay = relay;
658 return relay;
659 };
660
661 // CDP supplies the path before this runs; otherwise Electron opens a Save dialog.
662 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
663 const tab = [...tabs.values()].find(
664 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
665 );
666 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
667 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
668 tab.pendingDownloadGuid = null;
669 return true;
670 };
671
672 const detach = (key: DesktopBrowserTabKey) => {
673 const id = keyOf(key);
674 const tab = tabs.get(id);
675 if (!tab) return;
676 tabs.delete(id);
677 const announced = tab.stopWaiting === null;
678 tab.stopWaiting?.();
679 tab.relay = null;
680 tab.debuggee.debugger.off("message", tab.onMessage);
681 tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
682 // Input routed to a frame would wait for a detach event the tab no longer hears.
683 const listeners = [...tab.frameDetachListeners.values()].flatMap((set) => [...set]);
684 tab.frameDetachListeners.clear();
685 // A route resolved after this would find no session and go to the page.
686 tab.frameSessions.clear();
687 for (const listener of listeners) listener();
688 syncPainting(tab);
689 if (announced) emit({ type: "detached", ...key });
690 };
691
692 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
693 const id = keyOf(key);
694 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
695 detach(key);
696 const tab: AttachedTab = {
697 key,
698 debuggee,
699 relay: null,
700 screenshotTurn: null,
701 waitingScreenshots: [],
702 downloadDirectory: null,
703 pendingDownloadGuid: null,
704 agentInputAt: Number.NEGATIVE_INFINITY,
705 agentLedAt: Number.NEGATIVE_INFINITY,
706 focusEmulated: false,
707 focusChange: null,
708 focusUses: 0,
709 focusPending: new Map(),
710 capturing: new Set(),
711 frameWaits: new Set(),
712 frameSessions: new Map(),
713 frameDetachListeners: new Map(),
714 nudging: null,
715 frameStalled: false,
716 painting: false,
717 agentUsed: false,
718 focusReleasing: false,
719 screencasts: new Map(),
720 onMessage: (_event, method, params, sessionId) => {
721 if (method === "Page.downloadWillBegin") {
722 const guid = (params as { guid?: unknown } | undefined)?.guid;
723 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
724 }
725 trackFrameSession(tab, method, params);
726 tab.relay?.event(method, params, sessionId);
727 },
728 // A screenshot pending when the page loads a new document, a reload included, can
729 // stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
730 onNewDocument: () => {
731 // Before the next screenshot starts, so its own holds survive.
732 tab.capturing.clear();
733 dropFocusHolds(tab);
734 if (tab.screenshotTurn !== null) nextScreenshot(tab);
735 },
736 stopWaiting: null,
737 };
738 tabs.set(id, tab);
739 debuggee.debugger.on("message", tab.onMessage);
740 debuggee.webContents.on("did-navigate", tab.onNewDocument);
741 const announce = () => {
742 emit({ type: "attached", ...key });
743 const shown = shownTabs.get(id);
744 if (shown !== undefined) emit({ type: "shown", ...key, shown });
745 };
746 if (!debuggee.webContents.isLoadingMainFrame()) {
747 announce();
748 return;
749 }
750 // Electron does not pause a guest for the debugger, so Playwright connecting during its first
751 // commit builds its utility world in the discarded document and every wait on it hangs.
752 const { webContents } = debuggee;
753 // ERR_ABORTED is a newer navigation replacing this one, whose commit is still to come.
754 const onFailLoad = (
755 _event: Electron.Event,
756 code: number,
757 _description: string,
758 _url: string,
759 isMainFrame: boolean,
760 ) => {
761 if (isMainFrame && code !== ERR_ABORTED) ready();
762 };
763 const ready = () => {
764 if (tab.stopWaiting === null) return;
765 // The manager's cleanup for a destroyed guest can still be queued behind another tab's attach.
766 if (webContents.isDestroyed()) return detach(key);
767 tab.stopWaiting();
768 announce();
769 };
770 const timeout = runFork(
771 Effect.sleep(FIRST_PAGE_TIMEOUT).pipe(Effect.andThen(Effect.sync(ready))),
772 );
773 tab.stopWaiting = () => {
774 tab.stopWaiting = null;
775 webContents.off("dom-ready", ready);
776 webContents.off("did-stop-loading", ready);
777 webContents.off("did-fail-load", onFailLoad);
778 runFork(Fiber.interrupt(timeout));
779 };
780 webContents.on("dom-ready", ready);
781 webContents.on("did-stop-loading", ready);
782 webContents.on("did-fail-load", onFailLoad);
783 };
784
785 const setShown = (key: DesktopBrowserTabKey, shown: boolean | undefined) => {
786 const id = keyOf(key);
787 if (shown === undefined) {
788 shownTabs.delete(id);
789 return;
790 }
791 if (shownTabs.get(id) === shown) return;
792 shownTabs.set(id, shown);
793 if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
794 };
795
796 const setCaptureDrawn = (key: DesktopBrowserTabKey, drawn: boolean | undefined) => {
797 const id = keyOf(key);
798 if (!drawn) {
799 drawnTabs.delete(id);
800 return;
801 }
802 drawnTabs.add(id);
803 for (const done of drawWaiters.get(id) ?? []) done();
804 drawWaiters.delete(id);
805 };
806
807 const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => {
808 if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure });
809 };
810
811 const handleCommandLine = (line: string) =>
812 Effect.sync(() => {
813 const command = decodeCommand(line);
814 if (Option.isNone(command)) return;
815 if (command.value.type === "turn") {
816 if (command.value.active) agentTurns.add(command.value.threadId);
817 else endAgentTurn(command.value.threadId);
818 return;
819 }
820 const tab = tabs.get(keyOf(command.value));
821 if (!tab) return;
822 if (command.value.type === "pointer") {
823 const { threadId, tabId, phase, x, y } = command.value;
824 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
825 return;
826 }
827 if (command.value.type === "release") {
828 dropRelay(tab);
829 return;
830 }
831 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
832 relayFor(tab).receive(command.value.message);
833 });
834
835 const humanStartedDownload = (source: Electron.WebContents) => {
836 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
837 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_INPUT_WINDOW_MS;
838 };
839
840 const agentLedPage = (source: Electron.WebContents) => {
841 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
842 return tab !== undefined && performance.now() - tab.agentLedAt <= AGENT_INPUT_WINDOW_MS;
843 };
844
845 const announceAll = Effect.suspend(() => {
846 // A new backend: the old one's turns ended without telling us.
847 agentTurns.clear();
848 return Effect.forEach(
849 [...tabs.values()],
850 (tab) => {
851 dropRelay(tab);
852 // Announced once its first page is up.
853 if (tab.stopWaiting !== null) return Effect.void;
854 const shown = shownTabs.get(keyOf(tab.key));
855 return PubSub.publish(outbox, { type: "attached", ...tab.key }).pipe(
856 Effect.andThen(
857 shown !== undefined
858 ? PubSub.publish(outbox, { type: "shown", ...tab.key, shown })
859 : Effect.void,
860 ),
861 );
862 },
863 { discard: true },
864 );
865 });
866
867 return DesktopBrowserHost.of({
868 pointers: Stream.fromPubSub(pointers),
869 painting: Stream.fromPubSub(painting),
870 // Subscribes before announcing, so no attach falls between the two.
871 events: Stream.unwrap(
872 Effect.gen(function* () {
873 const subscription = yield* PubSub.subscribe(outbox);
874 yield* announceAll;
875 return Stream.fromSubscription(subscription);
876 }),
877 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
878 handleCommandLine,
879 attach,
880 detach,
881 loadFailed,
882 setShown,
883 setCaptureDrawn,
884 placeDownload,
885 humanStartedDownload,
886 agentLedPage,
887 });
888});
889
890export const layer = Layer.effect(DesktopBrowserHost, make);