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