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} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as NodePath from "node:path";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as PubSub from "effect/PubSub";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17
18import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
19import { sendPageCommand } from "./GuestInput.ts";
20
21const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
22const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
23const lineEncoder = new TextEncoder();
24const AGENT_INPUT_COMMAND =
25 /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/;
26/** The same commands as above, by method, for the relay's sends. */
27const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/;
28const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
29const FOCUS_IDLE = "5 seconds";
30/** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */
31const FIRST_PAGE_TIMEOUT = "5 seconds";
32const ERR_ABORTED = -3;
33
34export interface DesktopBrowserTabKey {
35 readonly threadId: string;
36 readonly tabId: string;
37}
38
39export interface DesktopBrowserTabDebugger {
40 readonly webContents: Electron.WebContents;
41 readonly debugger: Electron.Debugger;
42}
43
44const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
45
46interface AttachedTab {
47 readonly key: DesktopBrowserTabKey;
48 readonly debuggee: DesktopBrowserTabDebugger;
49 relay: CdpRelayConnection | null;
50 screenshotTurn: object | null;
51 /** Each holds focus and painting while `held` and whoever queued it still waits on it. */
52 readonly waitingScreenshots: Array<{
53 readonly start: () => void;
54 readonly live: () => boolean;
55 held: boolean;
56 }>;
57 downloadDirectory: string | null;
58 pendingDownloadGuid: string | null;
59 agentInputAt: number;
60 focusEmulated: boolean;
61 focusChange: Promise<void> | null;
62 focusUses: number;
63 /** Each pending command, by the extra session waiting on it; the main connection's have none. */
64 readonly focusPending: Map<
65 object,
66 { readonly owner: string | undefined; readonly paints: boolean }
67 >;
68 /** Whether the client keeps the guest painting, as published on `painting`. */
69 painting: boolean;
70 /**
71 * Driven by the agent since its thread's last turn ended or the guest last throttled. A
72 * turn's start can reach us after its first command, so this holds focus once it does.
73 */
74 agentUsed: boolean;
75 focusReleasing: boolean;
76 /** The sessions streaming the guest; one stopping leaves the others' screencasts running. */
77 readonly screencasts: Set<string | undefined>;
78 readonly onMessage: (
79 event: Electron.Event,
80 method: string,
81 params: unknown,
82 sessionId: string,
83 ) => void;
84 readonly onNewDocument: () => void;
85 /** Stops waiting for the first page; set until the tab is announced. */
86 stopWaiting: (() => void) | null;
87}
88
89export class DesktopBrowserHost extends Context.Service<
90 DesktopBrowserHost,
91 {
92 readonly events: Stream.Stream<Uint8Array>;
93 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
94 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
95 readonly detach: (key: DesktopBrowserTabKey) => void;
96 readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
97 readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
98 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
99 readonly pointers: Stream.Stream<{
100 readonly key: DesktopBrowserTabKey;
101 readonly phase: "move" | "click";
102 readonly x: number;
103 readonly y: number;
104 }>;
105 /** Whether a guest needs its frames painted while the panel hides it. */
106 readonly painting: Stream.Stream<{
107 readonly key: DesktopBrowserTabKey;
108 readonly active: boolean;
109 }>;
110 }
111>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
112
113export const make = Effect.gen(function* () {
114 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
115 const pointers = yield* PubSub.sliding<{
116 readonly key: DesktopBrowserTabKey;
117 readonly phase: "move" | "click";
118 readonly x: number;
119 readonly y: number;
120 }>(16);
121 const painting = yield* PubSub.unbounded<{
122 readonly key: DesktopBrowserTabKey;
123 readonly active: boolean;
124 }>();
125 const runFork = Effect.runForkWith(yield* Effect.context<never>());
126 const tabs = new Map<string, AttachedTab>();
127 /** Threads whose agent turn runs, by the server's account. */
128 const agentTurns = new Set<string>();
129 // Kept apart from attachment: the renderer can show a webview before its debugger attaches,
130 // and the server forgets `shown` on detach, for example while DevTools holds the debugger.
131 const shownTabs = new Map<string, boolean>();
132 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
133
134 const nextScreenshot = (tab: AttachedTab) => {
135 tab.screenshotTurn = null;
136 tab.waitingScreenshots.shift()?.start();
137 releaseFocusWhenIdle(tab);
138 syncPainting(tab);
139 };
140
141 /**
142 * Chromium below 157 crashes the whole app when a guest's renderer exits with a
143 * screenshot copy in flight (crbug.com/567321049). Overlapping screenshots make that
144 * far likelier, and one the server gave up on stays pending in Chromium, so each guest
145 * gets one at a time. One whose relay or session has since gone is dropped unsent.
146 */
147 const takeScreenshot = (
148 tab: AttachedTab,
149 relay: CdpRelayConnection,
150 ownerLive: () => boolean,
151 /** Sends only while `current` holds; holds focus and painting only while `held`. */
152 capture: (current: () => boolean, held: boolean) => Promise<unknown>,
153 ) =>
154 new Promise<unknown>((resolve, reject) => {
155 const live = () => tab.relay === relay && ownerLive();
156 const waiting = {
157 start: () => {
158 if (!live()) {
159 reject(new Error("The preview connection that asked for this screenshot closed."));
160 nextScreenshot(tab);
161 return;
162 }
163 const turn = {};
164 tab.screenshotTurn = turn;
165 capture(() => tab.screenshotTurn === turn && live(), waiting.held)
166 .finally(() => {
167 if (tab.screenshotTurn === turn) nextScreenshot(tab);
168 })
169 .then(resolve, reject);
170 },
171 live,
172 held: true,
173 };
174 if (tab.screenshotTurn === null) waiting.start();
175 else {
176 // The one ahead may be abandoned mid-capture; it needs frames to finish and free its turn.
177 tab.waitingScreenshots.push(waiting);
178 setFocusEmulation(tab, true);
179 syncPainting(tab);
180 }
181 });
182
183 /**
184 * Chromium counts a focus-emulated guest as captured, so a guest the panel hides would
185 * never throttle. Without it, a hidden guest paints no frames and focus() fires no focus
186 * events, so the guest is emulated focused while the server drives it or streams it.
187 */
188 const setFocusEmulation = (tab: AttachedTab, enabled: boolean) => {
189 if (tab.focusEmulated === enabled) return;
190 tab.focusEmulated = enabled;
191 // A guest that refuses it, or a debugger already gone, behaves as unfocused.
192 const change: Promise<void> = tab.debuggee.debugger
193 .sendCommand("Emulation.setFocusEmulationEnabled", { enabled })
194 .then(
195 () => undefined,
196 () => undefined,
197 )
198 .finally(() => {
199 if (tab.focusChange === change) tab.focusChange = null;
200 });
201 tab.focusChange = change;
202 };
203
204 const waitingHolds = (tab: AttachedTab) =>
205 tab.waitingScreenshots.some((waiting) => waiting.held && waiting.live());
206
207 const releaseFocusWhenIdle = (tab: AttachedTab) => {
208 if (tab.focusReleasing) return;
209 tab.focusReleasing = true;
210 runFork(
211 Effect.gen(function* () {
212 let uses: number;
213 do {
214 uses = tab.focusUses;
215 yield* Effect.sleep(FOCUS_IDLE);
216 } while (uses !== tab.focusUses);
217 tab.focusReleasing = false;
218 // The last pending command to settle starts another idle wait.
219 if (tab.focusPending.size > 0 || tab.screencasts.size > 0 || waitingHolds(tab)) {
220 return;
221 }
222 // The agent pauses to think between steps; its tab stays focused until the turn ends.
223 if (tab.agentUsed && agentTurns.has(tab.key.threadId)) return;
224 tab.agentUsed = false;
225 if (tabs.get(keyOf(tab.key)) === tab) setFocusEmulation(tab, false);
226 }),
227 );
228 };
229
230 /**
231 * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame
232 * that never comes. The client paints the guest behind the app while one is pending; the
233 * capture then finishes on its own, and the guest goes back offscreen once none is.
234 */
235 const syncPainting = (tab: AttachedTab) => {
236 const active =
237 tabs.get(keyOf(tab.key)) === tab &&
238 (tab.screencasts.size > 0 ||
239 waitingHolds(tab) ||
240 [...tab.focusPending.values()].some((hold) => hold.paints));
241 if (tab.painting === active) return;
242 tab.painting = active;
243 runFork(PubSub.publish(painting, { key: tab.key, active }));
244 };
245
246 /** A command may wait on the page's next frame, so the guest stays focused until it settles. */
247 const holdFocus = <A>(
248 tab: AttachedTab,
249 method: string,
250 owner: string | undefined,
251 work: () => Promise<A>,
252 ) => {
253 const pending = {};
254 tab.focusPending.set(pending, { owner, paints: method === "Page.captureScreenshot" });
255 tab.focusUses += 1;
256 setFocusEmulation(tab, true);
257 releaseFocusWhenIdle(tab);
258 syncPainting(tab);
259 return work().finally(() => {
260 if (!tab.focusPending.delete(pending)) return;
261 tab.focusUses += 1;
262 releaseFocusWhenIdle(tab);
263 syncPainting(tab);
264 });
265 };
266
267 /**
268 * Chromium can leave a command unanswered, so the screenshot guard's release points
269 * also end every hold: a released relay has no one waiting, and a new document answers
270 * nothing pending from the old one. A released relay's screencast has no viewer to stop it.
271 */
272 const dropFocusHolds = (tab: AttachedTab) => {
273 tab.focusPending.clear();
274 releaseFocusWhenIdle(tab);
275 syncPainting(tab);
276 };
277
278 const dropRelay = (tab: AttachedTab) => {
279 tab.relay = null;
280 tab.screencasts.clear();
281 tab.agentUsed = false;
282 dropFocusHolds(tab);
283 };
284
285 /** A detached session, such as a closed viewer, waits on nothing it sent. */
286 const dropSessionHolds = (tab: AttachedTab, owner: string) => {
287 tab.screencasts.delete(owner);
288 for (const [pending, hold] of tab.focusPending) {
289 if (hold.owner === owner) tab.focusPending.delete(pending);
290 }
291 releaseFocusWhenIdle(tab);
292 syncPainting(tab);
293 };
294
295 /**
296 * A command the server stopped waiting on, such as a timed-out screenshot or evaluation,
297 * may never settle; the turn's end ends every hold. The agent also sends on its own extra
298 * session, so this cannot spare other sessions; a viewer's screencast still holds.
299 */
300 const endAgentTurn = (threadId: string) => {
301 agentTurns.delete(threadId);
302 for (const tab of tabs.values()) {
303 if (tab.key.threadId !== threadId) continue;
304 tab.agentUsed = false;
305 // Still sent in turn, so the queue keeps moving, but no longer kept painting.
306 for (const waiting of tab.waitingScreenshots) waiting.held = false;
307 dropFocusHolds(tab);
308 }
309 };
310
311 const relayFor = (tab: AttachedTab) => {
312 if (tab.relay) return tab.relay;
313 const { webContents, debugger: debuggee } = tab.debuggee;
314 const send = (method: string, params: Record<string, unknown>, sessionId?: string) =>
315 sendPageCommand(webContents, debuggee, method, params, sessionId);
316 const detachedOwners = new Set<string>();
317 /** Viewers and recordings stream; the agent's own sessions never do. */
318 const streamingOwners = new Set<string>();
319 const relay: CdpRelayConnection = createCdpRelayConnection(
320 {
321 send: (method, params, sessionId, owner) => {
322 // A child session's screencast is not the page's, such as a late one on a detached session.
323 if (sessionId === undefined && method === "Page.startScreencast") {
324 tab.screencasts.add(owner);
325 if (owner !== undefined) streamingOwners.add(owner);
326 } else if (sessionId === undefined && method === "Page.stopScreencast") {
327 tab.screencasts.delete(owner);
328 }
329 // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's.
330 if (
331 AGENT_INPUT_METHOD.test(method) &&
332 (owner === undefined || !streamingOwners.has(owner))
333 ) {
334 tab.agentUsed = true;
335 }
336 // Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
337 const forward = (current?: () => boolean) => {
338 const change = tab.focusChange;
339 const run = () =>
340 tab.relay === relay && (current === undefined || current())
341 ? send(method, params, sessionId)
342 : Promise.reject(new Error("The page this screenshot was for has moved on."));
343 return change === null ? run() : change.then(run);
344 };
345 return method === "Page.captureScreenshot"
346 ? takeScreenshot(
347 tab,
348 relay,
349 () => owner === undefined || !detachedOwners.has(owner),
350 (current, held) =>
351 held ? holdFocus(tab, method, owner, () => forward(current)) : forward(current),
352 )
353 : method === "Page.startScreencast"
354 ? holdFocus(tab, method, owner, forward).catch((cause: unknown) => {
355 // A viewer can outlive a refused stream; nothing is streaming for it.
356 if (sessionId === undefined && tab.relay === relay) tab.screencasts.delete(owner);
357 releaseFocusWhenIdle(tab);
358 syncPainting(tab);
359 throw cause;
360 })
361 : holdFocus(tab, method, owner, forward);
362 },
363 sessionDetached: (owner) => {
364 detachedOwners.add(owner);
365 dropSessionHolds(tab, owner);
366 },
367 targetId: () =>
368 debuggee
369 .sendCommand("Target.getTargetInfo")
370 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
371 url: () => webContents.getURL(),
372 title: () => webContents.getTitle(),
373 userAgent: () => webContents.getUserAgent(),
374 setDownloadDirectory: (directory) => {
375 tab.downloadDirectory = directory;
376 },
377 },
378 (message) => {
379 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
380 emit({ type: "cdp", ...tab.key, message });
381 }
382 },
383 // Announcing the tab again would reconnect Playwright, and the page could
384 // replay the same oversized event, so the tab stays detached.
385 () => {
386 if (tab.relay !== relay || tabs.get(keyOf(tab.key)) !== tab) return;
387 // Disabling auto-attach detaches child sessions and releases their debugger pauses.
388 void debuggee
389 .sendCommand("Target.setAutoAttach", {
390 autoAttach: false,
391 waitForDebuggerOnStart: false,
392 flatten: true,
393 })
394 .catch(() => {});
395 if (tab.screencasts.size > 0) {
396 void debuggee.sendCommand("Page.stopScreencast").catch(() => {});
397 }
398 setFocusEmulation(tab, false);
399 detach(tab.key);
400 },
401 );
402 tab.relay = relay;
403 return relay;
404 };
405
406 // CDP supplies the path before this runs; otherwise Electron opens a Save dialog.
407 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
408 const tab = [...tabs.values()].find(
409 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
410 );
411 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
412 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
413 tab.pendingDownloadGuid = null;
414 return true;
415 };
416
417 const detach = (key: DesktopBrowserTabKey) => {
418 const id = keyOf(key);
419 const tab = tabs.get(id);
420 if (!tab) return;
421 tabs.delete(id);
422 const announced = tab.stopWaiting === null;
423 tab.stopWaiting?.();
424 tab.relay = null;
425 tab.debuggee.debugger.off("message", tab.onMessage);
426 tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
427 syncPainting(tab);
428 if (announced) emit({ type: "detached", ...key });
429 };
430
431 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
432 const id = keyOf(key);
433 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
434 detach(key);
435 const tab: AttachedTab = {
436 key,
437 debuggee,
438 relay: null,
439 screenshotTurn: null,
440 waitingScreenshots: [],
441 downloadDirectory: null,
442 pendingDownloadGuid: null,
443 agentInputAt: Number.NEGATIVE_INFINITY,
444 focusEmulated: false,
445 focusChange: null,
446 focusUses: 0,
447 focusPending: new Map(),
448 painting: false,
449 agentUsed: false,
450 focusReleasing: false,
451 screencasts: new Set(),
452 onMessage: (_event, method, params, sessionId) => {
453 if (method === "Page.downloadWillBegin") {
454 const guid = (params as { guid?: unknown } | undefined)?.guid;
455 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
456 }
457 tab.relay?.event(method, params, sessionId);
458 },
459 // A screenshot pending when the page loads a new document, a reload included, can
460 // stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
461 onNewDocument: () => {
462 // Before the next screenshot starts, so its own hold survives.
463 dropFocusHolds(tab);
464 if (tab.screenshotTurn !== null) nextScreenshot(tab);
465 },
466 stopWaiting: null,
467 };
468 tabs.set(id, tab);
469 debuggee.debugger.on("message", tab.onMessage);
470 debuggee.webContents.on("did-navigate", tab.onNewDocument);
471 const announce = () => {
472 emit({ type: "attached", ...key });
473 const shown = shownTabs.get(id);
474 if (shown !== undefined) emit({ type: "shown", ...key, shown });
475 };
476 if (!debuggee.webContents.isLoadingMainFrame()) {
477 announce();
478 return;
479 }
480 // Electron does not pause a guest for the debugger, so Playwright connecting during its first
481 // commit builds its utility world in the discarded document and every wait on it hangs.
482 const { webContents } = debuggee;
483 // ERR_ABORTED is a newer navigation replacing this one, whose commit is still to come.
484 const onFailLoad = (
485 _event: Electron.Event,
486 code: number,
487 _description: string,
488 _url: string,
489 isMainFrame: boolean,
490 ) => {
491 if (isMainFrame && code !== ERR_ABORTED) ready();
492 };
493 const ready = () => {
494 if (tab.stopWaiting === null) return;
495 // The manager's cleanup for a destroyed guest can still be queued behind another tab's attach.
496 if (webContents.isDestroyed()) return detach(key);
497 tab.stopWaiting();
498 announce();
499 };
500 const timeout = runFork(
501 Effect.sleep(FIRST_PAGE_TIMEOUT).pipe(Effect.andThen(Effect.sync(ready))),
502 );
503 tab.stopWaiting = () => {
504 tab.stopWaiting = null;
505 webContents.off("dom-ready", ready);
506 webContents.off("did-stop-loading", ready);
507 webContents.off("did-fail-load", onFailLoad);
508 runFork(Fiber.interrupt(timeout));
509 };
510 webContents.on("dom-ready", ready);
511 webContents.on("did-stop-loading", ready);
512 webContents.on("did-fail-load", onFailLoad);
513 };
514
515 const setShown = (key: DesktopBrowserTabKey, shown: boolean | undefined) => {
516 const id = keyOf(key);
517 if (shown === undefined) {
518 shownTabs.delete(id);
519 return;
520 }
521 if (shownTabs.get(id) === shown) return;
522 shownTabs.set(id, shown);
523 if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
524 };
525
526 const handleCommandLine = (line: string) =>
527 Effect.sync(() => {
528 const command = decodeCommand(line);
529 if (Option.isNone(command)) return;
530 if (command.value.type === "turn") {
531 if (command.value.active) agentTurns.add(command.value.threadId);
532 else endAgentTurn(command.value.threadId);
533 return;
534 }
535 const tab = tabs.get(keyOf(command.value));
536 if (!tab) return;
537 if (command.value.type === "pointer") {
538 const { threadId, tabId, phase, x, y } = command.value;
539 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
540 return;
541 }
542 if (command.value.type === "release") {
543 dropRelay(tab);
544 return;
545 }
546 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
547 relayFor(tab).receive(command.value.message);
548 });
549
550 const humanStartedDownload = (source: Electron.WebContents) => {
551 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
552 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
553 };
554
555 const announceAll = Effect.suspend(() => {
556 // A new backend: the old one's turns ended without telling us.
557 agentTurns.clear();
558 return Effect.forEach(
559 [...tabs.values()],
560 (tab) => {
561 dropRelay(tab);
562 // Announced once its first page is up.
563 if (tab.stopWaiting !== null) return Effect.void;
564 const shown = shownTabs.get(keyOf(tab.key));
565 return PubSub.publish(outbox, { type: "attached", ...tab.key }).pipe(
566 Effect.andThen(
567 shown !== undefined
568 ? PubSub.publish(outbox, { type: "shown", ...tab.key, shown })
569 : Effect.void,
570 ),
571 );
572 },
573 { discard: true },
574 );
575 });
576
577 return DesktopBrowserHost.of({
578 pointers: Stream.fromPubSub(pointers),
579 painting: Stream.fromPubSub(painting),
580 // Subscribes before announcing, so no attach falls between the two.
581 events: Stream.unwrap(
582 Effect.gen(function* () {
583 const subscription = yield* PubSub.subscribe(outbox);
584 yield* announceAll;
585 return Stream.fromSubscription(subscription);
586 }),
587 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
588 handleCommandLine,
589 attach,
590 detach,
591 setShown,
592 placeDownload,
593 humanStartedDownload,
594 });
595});
596
597export const layer = Layer.effect(DesktopBrowserHost, make);