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

DesktopBrowserHost.ts

269 lines9.6 KB

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