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

DesktopBrowserChannel.ts

223 lines8.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - Bridges Playwright's WebSocket transport to the desktop's fds.
2/**
3 * Playwright connects over CDP only through a WebSocket URL, so each attached
4 * desktop tab gets a loopback endpoint with an unguessable path. Its frames
5 * cross the bootstrap file descriptors to the desktop's relay, which owns the
6 * tab's `webContents.debugger`.
7 */
8import * as NodeStream from "@effect/platform-node/NodeStream";
9import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer";
10import {
11 DesktopBrowserCommand,
12 DesktopBrowserEvent,
13 type DesktopBrowserCommand as DesktopBrowserCommandType,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Schema from "effect/Schema";
23import * as Scope from "effect/Scope";
24import * as Semaphore from "effect/Semaphore";
25import * as Stream from "effect/Stream";
26import * as Ndjson from "effect/encoding/Ndjson";
27import * as NodeCrypto from "node:crypto";
28import * as NodeNet from "node:net";
29​
30import * as ServerConfig from "../config.ts";
31import { writeAllToFileDescriptor } from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
32​
33const decodeEvent = Schema.decodeUnknownEffect(DesktopBrowserEvent);
34const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(DesktopBrowserCommand));
35​
36export interface DesktopTabKey {
37 readonly threadId: string;
38 readonly tabId: string;
40​
41const keyOf = ({ threadId, tabId }: DesktopTabKey) => `${threadId}\u0000${tabId}`;
42​
43export class DesktopBrowserChannel extends Context.Service<
44 DesktopBrowserChannel,
45 {
46 readonly available: boolean;
47 /**
48 * Subscribes before it checks, so an attach landing in between is never
49 * missed.
50 */
51 readonly awaitAttached: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect<boolean>;
52 readonly detached: Stream.Stream<DesktopTabKey>;
53 readonly attached: Stream.Stream<DesktopTabKey>;
54 readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
55 readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
56 readonly pointer: (
57 key: DesktopTabKey,
58 pointer: { readonly phase: "move" | "click"; readonly x: number; readonly y: number },
59 ) => Effect.Effect<void>;
60 }
61>()("t3/preview/DesktopBrowserChannel") {}
62​
63const make = Effect.gen(function* () {
64 const config = yield* ServerConfig.ServerConfig;
65 const inputFd = config.desktopBrowserFd;
66 const controlFd = config.desktopBrowserControlFd;
67 const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
68 const attachedTabs = new Set<string>();
69 const inbound = new Map<string, Queue.Queue<string>>();
70 const writeLock = yield* Semaphore.make(1);
71​
72 if (inputFd === undefined || controlFd === undefined) {
73 return DesktopBrowserChannel.of({
74 available: false,
75 awaitAttached: () => Effect.succeed(false),
76 detached: Stream.empty,
77 attached: Stream.empty,
78 isAttached: () => Effect.succeed(false),
79 endpoint: () => Effect.die("No desktop app is attached to this server."),
80 pointer: () => Effect.void,
81 });
82 }
83​
84 const command = (message: DesktopBrowserCommandType) =>
85 writeLock.withPermits(1)(
86 encodeCommand(message).pipe(
87 Effect.flatMap((line) => writeAllToFileDescriptor(controlFd, Buffer.from(`${line}\n`))),
88 Effect.catchCause((cause) =>
89 Effect.logWarning("desktop browser command failed", { cause }),
90 ),
91 ),
92 );
93​
94 // Socket reads can be cancelled while the desktop keeps its write end open.
95 // Filesystem reads on this pipe keep Node alive after scope shutdown.
96 const readable = yield* Effect.acquireRelease(
97 Effect.sync(() => new NodeNet.Socket({ fd: inputFd, readable: true, writable: false })),
98 (stream) => Effect.sync(() => stream.destroy()),
99 );
100 yield* NodeStream.fromReadable<Uint8Array, Error>({
101 evaluate: () => readable,
102 closeOnDone: true,
103 onError: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
104 }).pipe(
105 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
106 Stream.mapEffect((value) => decodeEvent(value).pipe(Effect.option)),
107 Stream.runForEach((decoded) => {
108 if (Option.isNone(decoded)) return Effect.void;
109 const event = decoded.value;
110 const key = { threadId: event.threadId, tabId: event.tabId };
111 const id = keyOf(key);
112 switch (event.type) {
113 case "cdp": {
114 const queue = inbound.get(id);
115 return queue ? Queue.offer(queue, event.message).pipe(Effect.asVoid) : Effect.void;
116 }
117 case "attached":
118 attachedTabs.add(id);
119 return PubSub.publish(changes, { key, attached: true });
120 case "detached": {
121 attachedTabs.delete(id);
122 const queue = inbound.get(id);
123 return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
124 Effect.andThen(PubSub.publish(changes, { key, attached: false })),
125 );
126 }
127 }
128 }),
129 Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
130 Effect.forkScoped,
131 );
132​
133 const endpoint = (key: DesktopTabKey) =>
134 Effect.gen(function* () {
135 const id = keyOf(key);
136 const secret = NodeCrypto.randomBytes(24).toString("base64url");
137 const server = yield* NodeSocketServer.makeWebSocket({
138 host: "127.0.0.1",
139 port: 0,
140 path: `/${secret}`,
141 }).pipe(Effect.orDie);
142 const queue = yield* Queue.unbounded<string>();
143 inbound.set(id, queue);
144 // A detach before this registration shut down no queue, so check again.
145 if (!attachedTabs.has(id)) {
146 inbound.delete(id);
147 return yield* Effect.die("The desktop tab detached before the server connected.");
148 }
149 yield* Effect.addFinalizer(() =>
150 Effect.gen(function* () {
151 if (inbound.get(id) === queue) inbound.delete(id);
152 yield* Queue.shutdown(queue);
153 yield* command({ type: "release", ...key });
154 }),
155 );
156 // The relay serves one Playwright connection; a second would see the first's sessions.
157 let connected = false;
158 yield* server
159 .run((socket) =>
160 Effect.gen(function* () {
161 if (connected) return;
162 connected = true;
163 const writer = yield* socket.writer;
164 const reader = yield* socket.reader;
165 yield* Stream.fromQueue(queue).pipe(
166 Stream.runForEach((message) => writer.write(message)),
167 Effect.forkScoped,
168 );
169 const decoder = new TextDecoder();
170 return yield* reader.pull.pipe(
171 Effect.flatMap((frames) =>
172 Effect.forEach(
173 frames,
174 (frame) =>
175 command({
176 type: "cdp",
177 ...key,
178 message: typeof frame === "string" ? frame : decoder.decode(frame),
179 }),
180 { discard: true },
181 ),
182 ),
183 Effect.forever,
184 );
185 }).pipe(Effect.scoped, Effect.ignore),
186 )
187 .pipe(Effect.forkScoped);
188 const address = server.address;
189 if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
190 return `ws://127.0.0.1:${address.port}/${secret}`;
191 });
192​
193 return DesktopBrowserChannel.of({
194 available: true,
195 awaitAttached: (key, timeout) =>
196 Effect.scoped(
197 Effect.gen(function* () {
198 const subscription = yield* PubSub.subscribe(changes);
199 if (attachedTabs.has(keyOf(key))) return true;
200 return yield* Stream.fromSubscription(subscription).pipe(
201 Stream.filter((change) => change.attached && keyOf(change.key) === keyOf(key)),
202 Stream.runHead,
203 Effect.map(Option.isSome),
204 Effect.timeoutOption(timeout),
205 Effect.map((result) => Option.getOrElse(result, () => false)),
206 );
207 }),
208 ),
209 detached: Stream.fromPubSub(changes).pipe(
210 Stream.filter((change) => !change.attached),
211 Stream.map((change) => change.key),
212 ),
213 attached: Stream.fromPubSub(changes).pipe(
214 Stream.filter((change) => change.attached),
215 Stream.map((change) => change.key),
216 ),
217 isAttached: (key) => Effect.sync(() => attachedTabs.has(keyOf(key))),
218 endpoint,
219 pointer: (key, pointer) => command({ type: "pointer", ...key, ...pointer }),
220 });
221});
222​
223export const layer = Layer.effect(DesktopBrowserChannel, make);