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

DesktopBrowserHost.ts

217 lines7.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 downloadDirectory: string | null;
47 pendingDownloadGuid: string | null;
48 agentInputAt: number;
49 readonly onMessage: (
50 event: Electron.Event,
51 method: string,
52 params: unknown,
53 sessionId: string,
54 ) => 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 relayFor = (tab: AttachedTab) => {
88 if (tab.relay) return tab.relay;
89 const { webContents, debugger: debuggee } = tab.debuggee;
90 const relay: CdpRelayConnection = createCdpRelayConnection(
91 {
92 send: (method, params, sessionId) =>
93 sessionId === undefined
94 ? sendPageCommand(webContents, debuggee, method, params)
95 : debuggee.sendCommand(method, params, sessionId),
96 targetId: () =>
97 debuggee
98 .sendCommand("Target.getTargetInfo")
99 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
100 url: () => webContents.getURL(),
101 title: () => webContents.getTitle(),
102 userAgent: () => webContents.getUserAgent(),
103 setDownloadDirectory: (directory) => {
104 tab.downloadDirectory = directory;
105 },
106 },
107 (message) => {
108 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
109 emit({ type: "cdp", ...tab.key, message });
110 }
111 },
112 );
113 tab.relay = relay;
114 return relay;
115 };
116​
117 /**
118 * Without a path Electron would open its Save dialog over the app for a file
119 * the agent asked for. CDP names the download just before this runs.
120 */
121 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
122 const tab = [...tabs.values()].find(
123 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
124 );
125 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
126 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
127 tab.pendingDownloadGuid = null;
128 return true;
129 };
130​
131 const detach = (key: DesktopBrowserTabKey) => {
132 const id = keyOf(key);
133 const tab = tabs.get(id);
134 if (!tab) return;
135 tabs.delete(id);
136 tab.debuggee.debugger.off("message", tab.onMessage);
137 emit({ type: "detached", ...key });
138 };
139​
140 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
141 const id = keyOf(key);
142 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
143 detach(key);
144 const tab: AttachedTab = {
145 key,
146 debuggee,
147 relay: null,
148 downloadDirectory: null,
149 pendingDownloadGuid: null,
150 agentInputAt: Number.NEGATIVE_INFINITY,
151 onMessage: (_event, method, params, sessionId) => {
152 if (method === "Browser.downloadWillBegin") {
153 const guid = (params as { guid?: unknown } | undefined)?.guid;
154 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
155 }
156 tab.relay?.event(method, params, sessionId);
157 },
158 };
159 tabs.set(id, tab);
160 debuggee.debugger.on("message", tab.onMessage);
161 emit({ type: "attached", ...key });
162 };
163​
164 const handleCommandLine = (line: string) =>
165 Effect.sync(() => {
166 const command = decodeCommand(line);
167 if (Option.isNone(command)) return;
168 const tab = tabs.get(keyOf(command.value));
169 if (!tab) return;
170 if (command.value.type === "pointer") {
171 const { threadId, tabId, phase, x, y } = command.value;
172 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
173 return;
174 }
175 if (command.value.type === "release") {
176 tab.relay = null;
177 return;
178 }
179 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
180 relayFor(tab).receive(command.value.message);
181 });
182​
183 const humanStartedDownload = (source: Electron.WebContents) => {
184 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
185 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
186 };
187​
188 const announceAll = Effect.suspend(() =>
189 Effect.forEach(
190 [...tabs.values()],
191 (tab) => {
192 tab.relay = null;
193 return PubSub.publish(outbox, { type: "attached", ...tab.key });
194 },
195 { discard: true },
196 ),
197 );
198​
199 return DesktopBrowserHost.of({
200 pointers: Stream.fromPubSub(pointers),
201 // Subscribes before announcing, so no attach falls between the two.
202 events: Stream.unwrap(
203 Effect.gen(function* () {
204 const subscription = yield* PubSub.subscribe(outbox);
205 yield* announceAll;
206 return Stream.fromSubscription(subscription);
207 }),
208 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
209 handleCommandLine,
210 attach,
211 detach,
212 placeDownload,
213 humanStartedDownload,
214 });
215});
216​
217export const layer = Layer.effect(DesktopBrowserHost, make);