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

DesktopBrowserHost.ts

246 lines9.4 KB

1// @effect-diagnostics nodeBuiltinImport:off - Names download files on the shared disk.
2/**
3 * The desktop end of the desktop browser channel (see `DesktopBrowserEvent` in
4 * contracts). The primary backend gets two file descriptors at spawn: this
5 * service writes events for the desktop's tabs to one and reads commands from
6 * the other. Each attached tab is reachable only through its `CdpRelay`.
7 *
8 * A tab is attached once its `<webview>` registers with a key the web app
9 * gave it. The preview manager owns the tab's single debugger session and hands
10 * it here; the relay shares it.
11 */
12import {
13 DesktopBrowserCommand,
14 DesktopBrowserEvent,
15 type DesktopBrowserEvent as DesktopBrowserEventType,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as NodePath from "node:path";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as PubSub from "effect/PubSub";
23import * as Schema from "effect/Schema";
24import * as Stream from "effect/Stream";
25​
26import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
27import { sendPageCommand } from "./GuestInput.ts";
28​
29const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
30const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
31const lineEncoder = new TextEncoder();
32/** CDP commands through which an agent clicks, types, or navigates the page. */
33const AGENT_INPUT_COMMAND =
34 /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/;
35/** How long after an agent's input a download still counts as the agent's. */
36const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
37​
38export interface DesktopBrowserTabKey {
39 readonly threadId: string;
40 readonly tabId: string;
42​
43/** A tab's debugger, as the preview manager lends it to the relay. */
44export interface DesktopBrowserTabDebugger {
45 readonly webContents: Electron.WebContents;
46 readonly debugger: Electron.Debugger;
48​
49const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
50​
51interface AttachedTab {
52 readonly key: DesktopBrowserTabKey;
53 readonly debuggee: DesktopBrowserTabDebugger;
54 relay: CdpRelayConnection | null;
55 /** Where the server wants this tab's downloads; null keeps Electron's own handling. */
56 downloadDirectory: string | null;
57 /** The guid CDP gave the download that is about to start. */
58 pendingDownloadGuid: string | null;
59 /** When the server last sent this page input, which only an agent does. */
60 agentInputAt: number;
61 readonly onMessage: (
62 event: Electron.Event,
63 method: string,
64 params: unknown,
65 sessionId: string,
66 ) => void;
68​
69export class DesktopBrowserHost extends Context.Service<
70 DesktopBrowserHost,
71 {
72 /**
73 * Newline-delimited events for a backend's browser fd. Each run starts by
74 * announcing the tabs already attached, so a restarted backend hears them.
75 */
76 readonly events: Stream.Stream<Uint8Array>;
77 /** One line from the backend's browser control fd. */
78 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
79 /** Offers a server tab's `<webview>` to the server. */
80 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
81 /** Withdraws it: closed, swapped, crashed, or devtools needs the debugger. */
82 readonly detach: (key: DesktopBrowserTabKey) => void;
83 /**
84 * Whether a server tab's download came from the person at this desktop:
85 * the server sent the page no input just before it started.
86 */
87 readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
88 /** Points a server tab's download at the server; false for any other download. */
89 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
90 /** The agent's cursor positions for attached tabs, keyed by their server tab. */
91 readonly pointers: Stream.Stream<{
92 readonly key: DesktopBrowserTabKey;
93 readonly phase: "move" | "click";
94 readonly x: number;
95 readonly y: number;
96 }>;
97 }
98>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
99​
100export const make = Effect.gen(function* () {
101 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
102 const pointers = yield* PubSub.sliding<{
103 readonly key: DesktopBrowserTabKey;
104 readonly phase: "move" | "click";
105 readonly x: number;
106 readonly y: number;
107 }>(16);
108 const runFork = Effect.runForkWith(yield* Effect.context<never>());
109 const tabs = new Map<string, AttachedTab>();
110 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
111​
112 const relayFor = (tab: AttachedTab) => {
113 if (tab.relay) return tab.relay;
114 const { webContents, debugger: debuggee } = tab.debuggee;
115 const relay: CdpRelayConnection = createCdpRelayConnection(
116 {
117 send: (method, params, sessionId) =>
118 sessionId === undefined
119 ? sendPageCommand(webContents, debuggee, method, params)
120 : debuggee.sendCommand(method, params, sessionId),
121 targetId: () =>
122 debuggee
123 .sendCommand("Target.getTargetInfo")
124 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
125 url: () => webContents.getURL(),
126 title: () => webContents.getTitle(),
127 userAgent: () => webContents.getUserAgent(),
128 setDownloadDirectory: (directory) => {
129 tab.downloadDirectory = directory;
130 },
131 },
132 // A released relay's late replies belong to a connection that is gone.
133 (message) => {
134 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
135 emit({ type: "cdp", ...tab.key, message });
136 }
137 },
138 );
139 tab.relay = relay;
140 return relay;
141 };
142​
143 /**
144 * Saves a download from a server tab where the server's Playwright expects
145 * it. Without a path Electron would open its Save dialog over the app for a
146 * file the agent asked for. CDP names the download just before this runs.
147 */
148 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
149 const tab = [...tabs.values()].find(
150 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
151 );
152 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
153 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
154 tab.pendingDownloadGuid = null;
155 return true;
156 };
157​
158 const detach = (key: DesktopBrowserTabKey) => {
159 const id = keyOf(key);
160 const tab = tabs.get(id);
161 if (!tab) return;
162 tabs.delete(id);
163 tab.debuggee.debugger.off("message", tab.onMessage);
164 emit({ type: "detached", ...key });
165 };
166​
167 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
168 const id = keyOf(key);
169 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
170 detach(key);
171 const tab: AttachedTab = {
172 key,
173 debuggee,
174 relay: null,
175 downloadDirectory: null,
176 pendingDownloadGuid: null,
177 agentInputAt: Number.NEGATIVE_INFINITY,
178 onMessage: (_event, method, params, sessionId) => {
179 if (method === "Browser.downloadWillBegin") {
180 const guid = (params as { guid?: unknown } | undefined)?.guid;
181 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
182 }
183 tab.relay?.event(method, params, sessionId);
184 },
185 };
186 tabs.set(id, tab);
187 debuggee.debugger.on("message", tab.onMessage);
188 emit({ type: "attached", ...key });
189 };
190​
191 const handleCommandLine = (line: string) =>
192 Effect.sync(() => {
193 const command = decodeCommand(line);
194 if (Option.isNone(command)) return;
195 const tab = tabs.get(keyOf(command.value));
196 if (!tab) return;
197 if (command.value.type === "pointer") {
198 const { threadId, tabId, phase, x, y } = command.value;
199 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
200 return;
201 }
202 if (command.value.type === "release") {
203 // A new server connection starts with a fresh relay and fresh sessions.
204 tab.relay = null;
205 return;
206 }
207 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
208 relayFor(tab).receive(command.value.message);
209 });
210​
211 const humanStartedDownload = (source: Electron.WebContents) => {
212 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
213 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
214 };
215​
216 // Read when a backend starts, not when the host is built.
217 const announceAll = Effect.suspend(() =>
218 Effect.forEach(
219 [...tabs.values()],
220 (tab) => {
221 tab.relay = null;
222 return PubSub.publish(outbox, { type: "attached", ...tab.key });
223 },
224 { discard: true },
225 ),
226 );
227​
228 return DesktopBrowserHost.of({
229 pointers: Stream.fromPubSub(pointers),
230 // Subscribes before announcing, so no attach falls between the two.
231 events: Stream.unwrap(
232 Effect.gen(function* () {
233 const subscription = yield* PubSub.subscribe(outbox);
234 yield* announceAll;
235 return Stream.fromSubscription(subscription);
236 }),
237 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
238 handleCommandLine,
239 attach,
240 detach,
241 placeDownload,
242 humanStartedDownload,
243 });
244});
245​
246export const layer = Layer.effect(DesktopBrowserHost, make);