Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBrowserHost.ts

524 lines19.9 KB

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