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

DesktopBrowserHost.ts

263 lines9.5 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)")/;
25const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
26​
27export interface DesktopBrowserTabKey {
28 readonly threadId: string;
29 readonly tabId: string;
31​
32export interface DesktopBrowserTabDebugger {
33 readonly webContents: Electron.WebContents;
34 readonly debugger: Electron.Debugger;
36​
37const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
38​
39interface AttachedTab {
40 readonly key: DesktopBrowserTabKey;
41 readonly debuggee: DesktopBrowserTabDebugger;
42 relay: CdpRelayConnection | null;
43 screenshotTurn: object | null;
44 readonly waitingScreenshots: Array<() => void>;
45 downloadDirectory: string | null;
46 pendingDownloadGuid: string | null;
47 agentInputAt: number;
48 readonly onMessage: (
49 event: Electron.Event,
50 method: string,
51 params: unknown,
52 sessionId: string,
53 ) => void;
54 readonly onNewDocument: () => void;
56​
57export class DesktopBrowserHost extends Context.Service<
58 DesktopBrowserHost,
59 {
60 readonly events: Stream.Stream<Uint8Array>;
61 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
62 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
63 readonly detach: (key: DesktopBrowserTabKey) => void;
64 readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
65 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
66 readonly pointers: Stream.Stream<{
67 readonly key: DesktopBrowserTabKey;
68 readonly phase: "move" | "click";
69 readonly x: number;
70 readonly y: number;
71 }>;
72 }
73>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
74​
75export const make = Effect.gen(function* () {
76 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
77 const pointers = yield* PubSub.sliding<{
78 readonly key: DesktopBrowserTabKey;
79 readonly phase: "move" | "click";
80 readonly x: number;
81 readonly y: number;
82 }>(16);
83 const runFork = Effect.runForkWith(yield* Effect.context<never>());
84 const tabs = new Map<string, AttachedTab>();
85 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
86​
87 const nextScreenshot = (tab: AttachedTab) => {
88 tab.screenshotTurn = null;
89 tab.waitingScreenshots.shift()?.();
90 };
91​
92 /**
93 * Chromium below 157 crashes the whole app when a guest's renderer exits with a
94 * screenshot copy in flight (crbug.com/567321049). Overlapping screenshots make that
95 * far likelier, and one the server gave up on stays pending in Chromium, so each guest
96 * gets one at a time. One queued by a relay released since then is dropped unsent.
97 */
98 const takeScreenshot = (
99 tab: AttachedTab,
100 relay: CdpRelayConnection,
101 capture: () => Promise<unknown>,
102 ) =>
103 new Promise<unknown>((resolve, reject) => {
104 const start = () => {
105 if (tab.relay !== relay) {
106 reject(new Error("The preview connection that asked for this screenshot closed."));
107 nextScreenshot(tab);
108 return;
109 }
110 const turn = {};
111 tab.screenshotTurn = turn;
112 capture()
113 .finally(() => {
114 if (tab.screenshotTurn === turn) nextScreenshot(tab);
115 })
116 .then(resolve, reject);
117 };
118 if (tab.screenshotTurn === null) start();
119 else tab.waitingScreenshots.push(start);
120 });
121​
122 const relayFor = (tab: AttachedTab) => {
123 if (tab.relay) return tab.relay;
124 const { webContents, debugger: debuggee } = tab.debuggee;
125 const send = (method: string, params: Record<string, unknown>, sessionId?: string) =>
126 sessionId === undefined
127 ? sendPageCommand(webContents, debuggee, method, params)
128 : debuggee.sendCommand(method, params, sessionId);
129 const relay: CdpRelayConnection = createCdpRelayConnection(
130 {
131 send: (method, params, sessionId) =>
132 method === "Page.captureScreenshot"
133 ? takeScreenshot(tab, relay, () => send(method, params, sessionId))
134 : send(method, params, sessionId),
135 targetId: () =>
136 debuggee
137 .sendCommand("Target.getTargetInfo")
138 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
139 url: () => webContents.getURL(),
140 title: () => webContents.getTitle(),
141 userAgent: () => webContents.getUserAgent(),
142 setDownloadDirectory: (directory) => {
143 tab.downloadDirectory = directory;
144 },
145 },
146 (message) => {
147 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
148 emit({ type: "cdp", ...tab.key, message });
149 }
150 },
151 );
152 tab.relay = relay;
153 return relay;
154 };
155​
156 // CDP supplies the path before this runs; otherwise Electron opens a Save dialog.
157 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
158 const tab = [...tabs.values()].find(
159 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
160 );
161 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
162 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
163 tab.pendingDownloadGuid = null;
164 return true;
165 };
166​
167 const detach = (key: DesktopBrowserTabKey) => {
168 const id = keyOf(key);
169 const tab = tabs.get(id);
170 if (!tab) return;
171 tabs.delete(id);
172 tab.relay = null;
173 tab.debuggee.debugger.off("message", tab.onMessage);
174 tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
175 emit({ type: "detached", ...key });
176 };
177​
178 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
179 const id = keyOf(key);
180 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
181 detach(key);
182 const tab: AttachedTab = {
183 key,
184 debuggee,
185 relay: null,
186 screenshotTurn: null,
187 waitingScreenshots: [],
188 downloadDirectory: null,
189 pendingDownloadGuid: null,
190 agentInputAt: Number.NEGATIVE_INFINITY,
191 onMessage: (_event, method, params, sessionId) => {
192 if (method === "Browser.downloadWillBegin") {
193 const guid = (params as { guid?: unknown } | undefined)?.guid;
194 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
195 }
196 tab.relay?.event(method, params, sessionId);
197 },
198 // A screenshot pending when the page loads a new document, a reload included, can
199 // stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
200 onNewDocument: () => {
201 if (tab.screenshotTurn !== null) nextScreenshot(tab);
202 },
203 };
204 tabs.set(id, tab);
205 debuggee.debugger.on("message", tab.onMessage);
206 debuggee.webContents.on("did-navigate", tab.onNewDocument);
207 emit({ type: "attached", ...key });
208 };
209​
210 const handleCommandLine = (line: string) =>
211 Effect.sync(() => {
212 const command = decodeCommand(line);
213 if (Option.isNone(command)) return;
214 const tab = tabs.get(keyOf(command.value));
215 if (!tab) return;
216 if (command.value.type === "pointer") {
217 const { threadId, tabId, phase, x, y } = command.value;
218 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
219 return;
220 }
221 if (command.value.type === "release") {
222 tab.relay = null;
223 return;
224 }
225 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
226 relayFor(tab).receive(command.value.message);
227 });
228​
229 const humanStartedDownload = (source: Electron.WebContents) => {
230 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
231 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
232 };
233​
234 const announceAll = Effect.suspend(() =>
235 Effect.forEach(
236 [...tabs.values()],
237 (tab) => {
238 tab.relay = null;
239 return PubSub.publish(outbox, { type: "attached", ...tab.key });
240 },
241 { discard: true },
242 ),
243 );
244​
245 return DesktopBrowserHost.of({
246 pointers: Stream.fromPubSub(pointers),
247 // Subscribes before announcing, so no attach falls between the two.
248 events: Stream.unwrap(
249 Effect.gen(function* () {
250 const subscription = yield* PubSub.subscribe(outbox);
251 yield* announceAll;
252 return Stream.fromSubscription(subscription);
253 }),
254 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
255 handleCommandLine,
256 attach,
257 detach,
258 placeDownload,
259 humanStartedDownload,
260 });
261});
262​
263export const layer = Layer.effect(DesktopBrowserHost, make);