Open History to see the last commit
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;
34}
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 /** Whether a desktop window draws the tab on screen, which no streamed viewer counts. */
48 readonly isShown: (key: DesktopTabKey) => boolean;
49 readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
50 readonly pointer: (
51 key: DesktopTabKey,
52 pointer: { readonly phase: "move" | "click"; readonly x: number; readonly y: number },
53 ) => Effect.Effect<void>;
54 /** Never fails. A failed write means a broken channel; the next backend starts with no turns. */
55 readonly turn: (threadId: string, active: boolean) => Effect.Effect<void>;
56 }
57>()("t3/preview/DesktopBrowserChannel") {}
58
59const make = Effect.gen(function* () {
60 const config = yield* ServerConfig.ServerConfig;
61 const inputFd = config.desktopBrowserFd;
62 const controlFd = config.desktopBrowserControlFd;
63 const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
64 const attachedTabs = new Set<string>();
65 // Missing reports protect desktop tabs until the renderer explicitly marks them hidden.
66 const shownTabs = new Map<string, boolean>();
67 const inbound = new Map<string, Queue.Queue<string>>();
68 const writeLock = yield* Semaphore.make(1);
69
70 if (inputFd === undefined || controlFd === undefined) {
71 return DesktopBrowserChannel.of({
72 available: false,
73 awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function () {
74 return Effect.succeed(false);
75 }),
76 detached: Stream.empty,
77 attached: Stream.empty,
78 isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function () {
79 return Effect.succeed(false);
80 }),
81 endpoint: Effect.fn("DesktopBrowserChannel.endpoint")(function () {
82 return Effect.die("No desktop app is attached to this server.");
83 }),
84 turn: Effect.fn("DesktopBrowserChannel.turn")(function () {
85 return Effect.void;
86 }),
87 pointer: Effect.fn("DesktopBrowserChannel.pointer")(function () {
88 return Effect.void;
89 }),
90 isShown: () => false,
91 });
92 }
93
94 const command = (message: DesktopBrowserCommandType) =>
95 writeLock.withPermits(1)(
96 encodeCommand(message).pipe(
97 Effect.flatMap((line) => writeAllToFileDescriptor(controlFd, Buffer.from(`${line}\n`))),
98 Effect.catchCause((cause) =>
99 Effect.logWarning("desktop browser command failed", { cause }),
100 ),
101 ),
102 );
103
104 // Use cancellable socket reads; filesystem pipe reads keep Node alive after scope shutdown.
105 const readable = yield* Effect.acquireRelease(
106 Effect.sync(() => new NodeNet.Socket({ fd: inputFd, readable: true, writable: false })),
107 (stream) => Effect.sync(() => stream.destroy()),
108 );
109 yield* NodeStream.fromReadable<Uint8Array, Error>({
110 evaluate: () => readable,
111 closeOnDone: true,
112 onError: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
113 }).pipe(
114 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
115 Stream.mapEffect((value) => decodeEvent(value).pipe(Effect.option)),
116 Stream.runForEach((decoded) => {
117 if (Option.isNone(decoded)) return Effect.void;
118 const event = decoded.value;
119 const key = { threadId: event.threadId, tabId: event.tabId };
120 const id = keyOf(key);
121 switch (event.type) {
122 case "cdp": {
123 const queue = inbound.get(id);
124 return queue ? Queue.offer(queue, event.message).pipe(Effect.asVoid) : Effect.void;
125 }
126 case "attached":
127 attachedTabs.add(id);
128 return PubSub.publish(changes, { key, attached: true });
129 case "detached": {
130 attachedTabs.delete(id);
131 shownTabs.delete(id);
132 const queue = inbound.get(id);
133 return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
134 Effect.andThen(PubSub.publish(changes, { key, attached: false })),
135 );
136 }
137 case "shown":
138 shownTabs.set(id, event.shown);
139 return Effect.void;
140 }
141 }),
142 Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
143 Effect.ensuring(Effect.sync(() => shownTabs.clear())),
144 Effect.forkScoped,
145 );
146
147 const endpoint = Effect.fn("DesktopBrowserChannel.endpoint")(function* (key: DesktopTabKey) {
148 const id = keyOf(key);
149 const secret = NodeCrypto.randomBytes(24).toString("base64url");
150 const server = yield* NodeSocketServer.makeWebSocket({
151 host: "127.0.0.1",
152 port: 0,
153 path: `/${secret}`,
154 }).pipe(Effect.orDie);
155 const queue = yield* Queue.unbounded<string>();
156 inbound.set(id, queue);
157 // A detach before this registration shut down no queue, so check again.
158 if (!attachedTabs.has(id)) {
159 inbound.delete(id);
160 return yield* Effect.die("The desktop tab detached before the server connected.");
161 }
162 yield* Effect.addFinalizer(() =>
163 Effect.gen(function* () {
164 if (inbound.get(id) === queue) inbound.delete(id);
165 yield* Queue.shutdown(queue);
166 yield* command({ type: "release", ...key });
167 }),
168 );
169 // The relay serves one Playwright connection; a second would see the first's sessions.
170 let connected = false;
171 yield* server
172 .run((socket) =>
173 Effect.gen(function* () {
174 if (connected) return;
175 connected = true;
176 const writer = yield* socket.writer;
177 const reader = yield* socket.reader;
178 yield* Stream.fromQueue(queue).pipe(
179 Stream.runForEach((message) => writer.write(message)),
180 Effect.forkScoped,
181 );
182 const decoder = new TextDecoder();
183 return yield* reader.pull.pipe(
184 Effect.flatMap((frames) =>
185 Effect.forEach(
186 frames,
187 (frame) =>
188 command({
189 type: "cdp",
190 ...key,
191 message: typeof frame === "string" ? frame : decoder.decode(frame),
192 }),
193 { discard: true },
194 ),
195 ),
196 Effect.forever,
197 );
198 }).pipe(Effect.scoped, Effect.ignore),
199 )
200 .pipe(Effect.forkScoped);
201 const address = server.address;
202 if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
203 return `ws://127.0.0.1:${address.port}/${secret}`;
204 });
205
206 return DesktopBrowserChannel.of({
207 available: true,
208 awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function (key, timeout) {
209 return Effect.scoped(
210 Effect.gen(function* () {
211 const subscription = yield* PubSub.subscribe(changes);
212 if (attachedTabs.has(keyOf(key))) return true;
213 return yield* Stream.fromSubscription(subscription).pipe(
214 Stream.filter((change) => change.attached && keyOf(change.key) === keyOf(key)),
215 Stream.runHead,
216 Effect.map(Option.isSome),
217 Effect.timeoutOption(timeout),
218 Effect.map((result) => Option.getOrElse(result, () => false)),
219 );
220 }),
221 );
222 }),
223 detached: Stream.fromPubSub(changes).pipe(
224 Stream.filter((change) => !change.attached),
225 Stream.map((change) => change.key),
226 ),
227 attached: Stream.fromPubSub(changes).pipe(
228 Stream.filter((change) => change.attached),
229 Stream.map((change) => change.key),
230 ),
231 isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) {
232 return Effect.sync(() => attachedTabs.has(keyOf(key)));
233 }),
234 isShown: (key) => shownTabs.get(keyOf(key)) ?? true,
235 endpoint,
236 turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {
237 return command({ type: "turn", threadId, active });
238 }),
239 pointer: Effect.fn("DesktopBrowserChannel.pointer")(function (key, pointer) {
240 return command({ type: "pointer", ...key, ...pointer });
241 }),
242 });
243});
244
245export const layer = Layer.effect(DesktopBrowserChannel, make);