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

DesktopBrowserChannel.ts

234 lines9.3 KB

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