The best way to control Claude Code, Codex and more from any computer or phone

main
ts 312 lines 12.3 KB
Raw
1 import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest";
2 import {
3 AuthOrchestrationReadScope,
4 AuthPreviewOperateScope,
5 PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
6 PreviewStreamHostSetup,
7 } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Queue from "effect/Queue";
11 import * as Schema from "effect/Schema";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Path from "effect/Path";
14 import {
15 HttpPlatform,
16 HttpRouter,
17 HttpServerRequest,
18 HttpServerResponse,
19 Multipart,
20 } from "effect/http";
21 import * as Socket from "effect/socket/Socket";
22
23 import { authenticateMediaRequest, failEnvironmentInternal } from "../auth/http.ts";
24 import * as SessionStore from "../auth/SessionStore.ts";
25 import { assetResponseHeaders } from "../http.ts";
26 import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";
27 import * as ServerBrowser from "./ServerBrowser.ts";
28 import { requestUrl } from "../requestUrl.ts";
29
30 const PREVIEW_STREAM_ROUTE_PREFIX = "/api/preview-stream";
31 const TAB_GONE_CODE = 4404;
32
33 const DEFAULT_QUALITY = 70;
34 const MAX_SOCKET_BUFFER_BYTES = 8 * 1024 * 1024;
35 const textDecoder = new TextDecoder();
36
37 const intParam = (params: URLSearchParams, name: string, fallback: number, max: number) => {
38 const value = Number(params.get(name));
39 return Number.isFinite(value) && value > 0 ? Math.min(Math.round(value), max) : fallback;
40 };
41
42 type Frame = Extract<ServerBrowser.ServerBrowserViewerOutput, { readonly _tag: "frame" }>;
43
44 const isAck = (message: unknown) =>
45 typeof message === "object" && message !== null && "type" in message && message.type === "ack";
46
47 const parseMessage = (chunk: Uint8Array | string): unknown => {
48 try {
49 return JSON.parse(typeof chunk === "string" ? chunk : textDecoder.decode(chunk));
50 } catch {
51 return null;
52 }
53 };
54
55 // Request middleware owns tracing, including long-lived WebSocket sessions.
56 const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBrowser["Service"]) {
57 const request = yield* HttpServerRequest.HttpServerRequest;
58 const url = requestUrl(request);
59 if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 });
60 if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) {
61 return yield* serveDownload(browser, url.value.searchParams);
62 }
63 if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) {
64 return request.method === "POST"
65 ? yield* receiveUpload(browser, url.value.searchParams)
66 : HttpServerResponse.text("Method Not Allowed", { status: 405 });
67 }
68 if (
69 url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` ||
70 request.headers.upgrade?.toLowerCase() !== "websocket"
71 ) {
72 return HttpServerResponse.text("Not Found", { status: 404 });
73 }
74 const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);
75 const params = url.value.searchParams;
76 const canOperate =
77 session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";
78 const threadId = params.get("threadId") ?? "";
79 const tabId = params.get("tabId") ?? "";
80 if (threadId.length === 0 || tabId.length === 0) {
81 return HttpServerResponse.text("Not Found", { status: 404 });
82 }
83 const sessions = yield* SessionStore.SessionStore;
84 const stream = Effect.scoped(
85 Effect.gen(function* () {
86 const attached = yield* browser
87 .attachViewer({
88 threadId,
89 tabId,
90 canOperate,
91 maxWidth: intParam(params, "maxWidth", 1280, 7680),
92 maxHeight: intParam(params, "maxHeight", 800, 4320),
93 quality: intParam(params, "quality", DEFAULT_QUALITY, 100),
94 })
95 .pipe(
96 Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),
97 Effect.catchTags({
98 ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }),
99 ServerBrowserLaunchError: (error) => {
100 const setup = hostSetup(error.cause);
101 return setup === undefined
102 ? Effect.fail(error)
103 : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) });
104 },
105 }),
106 );
107 const incoming = NodeHttpServerRequest.toIncomingMessage(request);
108 // JPEGs are already compressed. Disabling deflate also keeps all
109 // pending writes in the socket buffer we bound below, not a zlib queue.
110 delete incoming.headers["sec-websocket-extensions"];
111 const transport = incoming.socket;
112 const socket = yield* request.upgrade;
113 const reader = yield* socket.reader;
114 const writer = yield* socket.writer;
115 // A refused upgrade reads as an auth failure to ticket clients, so a
116 // missing tab is a close code they stop on.
117 const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed"));
118 if (attached._tag === "gone") {
119 yield* gone;
120 return HttpServerResponse.empty();
121 }
122 if (attached._tag === "hostSetup") {
123 yield* writer.write(
124 new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason),
125 );
126 return HttpServerResponse.empty();
127 }
128 const viewer = attached.viewer;
129 // `write` returns once the frame is queued, so Chromium's ack for each
130 // frame waits for the viewer's `ack` message instead. Only one frame
131 // is on the wire and only the newest waits behind it, so replies never
132 // queue behind stale images on a slow link.
133 let inFlight: Effect.Effect<void> | null = null;
134 let pending: Frame | null = null;
135 const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(
136 Effect.andThen(Effect.interrupt),
137 );
138 const write = (data: Uint8Array | string) =>
139 Effect.suspend(() => {
140 const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
141 if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) {
142 return disconnectSlowViewer;
143 }
144 return writer.write(data);
145 });
146 const sendFrame = (frame: Frame) => {
147 inFlight = frame.ack;
148 return write(frame.data);
149 };
150 const sendOutput = Queue.take(viewer.output).pipe(
151 Effect.flatMap((output) => {
152 switch (output._tag) {
153 case "frame": {
154 if (inFlight === null) return sendFrame(output);
155 const superseded = pending;
156 pending = output;
157 // Never sent, but Chromium still waits for its ack.
158 return superseded ? Effect.forkScoped(superseded.ack) : Effect.void;
159 }
160 case "viewport":
161 case "control":
162 case "clipboard":
163 case "download":
164 case "fileChooser":
165 case "fileChooserClosed":
166 case "popup":
167 case "pointer":
168 case "probe": {
169 const { _tag: type, ...data } = output;
170 return write(JSON.stringify({ type, ...data }));
171 }
172 case "gone":
173 return gone.pipe(Effect.andThen(Effect.interrupt));
174 case "reconnect":
175 return writer
176 .write(new Socket.CloseEvent(1012, "reconnect"))
177 .pipe(Effect.andThen(Effect.interrupt));
178 }
179 }),
180 );
181 // Incoming messages share the session span; frame acknowledgements are frequent.
182 const receive = Effect.fnUntraced(function* (chunk: Uint8Array | string) {
183 const message = parseMessage(chunk);
184 // Ownership serializes actions in the service. Keep reading so dialog
185 // replies and takeover can unblock an action already waiting on the page.
186 if (!isAck(message))
187 return yield* canOperate
188 ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
189 : Effect.void;
190 const ack = inFlight;
191 const next = pending;
192 inFlight = null;
193 pending = null;
194 // Forked: Chromium acks are paced and must not hold up input.
195 return yield* Effect.andThen(
196 ack ? Effect.forkScoped(ack) : Effect.void,
197 next ? sendFrame(next) : Effect.void,
198 );
199 });
200 const receiveInput = reader.pull.pipe(
201 Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
202 );
203 return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput)).pipe(
204 Effect.onInterrupt(() => Effect.sync(() => transport.destroy())),
205 );
206 }),
207 ).pipe(
208 Effect.catchTags({
209 ServerBrowserLaunchError: (error) =>
210 Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(
211 Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),
212 ),
213 }),
214 Effect.orElseSucceed(() => HttpServerResponse.empty()),
215 );
216 return yield* Effect.raceFirst(
217 stream,
218 sessions.awaitInvalidation(session.sessionId).pipe(
219 Effect.as(HttpServerResponse.empty()),
220 Effect.catchTags({
221 SessionCredentialVerificationError: (error) =>
222 failEnvironmentInternal("internal_error", error),
223 }),
224 ),
225 );
226 });
227
228 const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined =>
229 isSandboxError(cause)
230 ? { need: "sandbox", command: cause.setupCommand }
231 : isLibrariesError(cause)
232 ? { need: "libraries", command: cause.setupCommand }
233 : undefined;
234 const isSandboxError = Schema.is(PreviewBrowserHost.PreviewBrowserSandboxError);
235 const isLibrariesError = Schema.is(PreviewBrowserHost.PreviewBrowserLibrariesError);
236 const encodeHostSetup = Schema.encodeSync(Schema.fromJsonString(PreviewStreamHostSetup));
237
238 // The request span already covers this download route.
239 const serveDownload = Effect.fnUntraced(function* (
240 browser: ServerBrowser.ServerBrowser["Service"],
241 params: URLSearchParams,
242 ) {
243 yield* authenticateMediaRequest(AuthOrchestrationReadScope);
244 const download = yield* browser.openDownload({
245 threadId: params.get("threadId") ?? "",
246 tabId: params.get("tabId") ?? "",
247 downloadId: params.get("id") ?? "",
248 });
249 if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });
250 return yield* HttpServerResponse.file(download.value.path, {
251 headers: assetResponseHeaders(download.value.path, {
252 download: true,
253 fileName: download.value.fileName,
254 }),
255 });
256 });
257
258 const UPLOAD_MAX_FILE_BYTES = 100 * 1024 * 1024;
259 const UPLOAD_MAX_FILES = 20;
260
261 // The request span already covers this upload route.
262 const receiveUpload = Effect.fnUntraced(
263 function* (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) {
264 yield* authenticateMediaRequest(AuthPreviewOperateScope);
265 const request = yield* HttpServerRequest.HttpServerRequest;
266 const fs = yield* FileSystem.FileSystem;
267 const parts = yield* request.multipart.pipe(
268 Effect.provideContext(
269 Multipart.limitsServices({
270 maxParts: UPLOAD_MAX_FILES,
271 maxFileSize: UPLOAD_MAX_FILE_BYTES,
272 maxTotalSize: UPLOAD_MAX_FILE_BYTES,
273 }),
274 ),
275 );
276 const files = yield* Effect.forEach(
277 Object.values(parts).flatMap((value) =>
278 Array.isArray(value) ? value.filter(Multipart.isPersistedFile) : [],
279 ),
280 (file) =>
281 fs.readFile(file.path).pipe(
282 Effect.map((bytes) => ({
283 name: file.name,
284 mimeType: file.contentType,
285 buffer: Buffer.from(bytes),
286 })),
287 ),
288 );
289 const answered = yield* browser.answerFileChooser({
290 threadId: params.get("threadId") ?? "",
291 tabId: params.get("tabId") ?? "",
292 chooserId: params.get("chooser") ?? "",
293 files,
294 });
295 return answered
296 ? HttpServerResponse.empty({ status: 204 })
297 : HttpServerResponse.text("The page's file picker is no longer open.", { status: 409 });
298 },
299 (effect, _browser, _params) => effect.pipe(Effect.scoped),
300 );
301
302 export const routeLayer = HttpRouter.use((router) =>
303 Effect.gen(function* () {
304 const browser = yield* ServerBrowser.ServerBrowser;
305 const platform = yield* Effect.context<
306 HttpPlatform.HttpPlatform | FileSystem.FileSystem | Path.Path
307 >();
308 const handler = makeHandler(browser).pipe(Effect.provideContext(platform));
309 yield* router.add("GET", `${PREVIEW_STREAM_ROUTE_PREFIX}/*`, handler);
310 yield* router.add("POST", `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`, handler);
311 }),
312 );