Open History to see the last commit
1// @effect-diagnostics globalTimers:off globalFetch:off - This browser and WebView transport runs without an Effect runtime.
2import { type DeviceHubAccess, withDeviceHubQuery } from "../device/hubAccess.ts";
3import {
4 PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
5 type PreviewStreamHostSetup,
6 type PreviewViewportSetting,
7} from "@t3tools/contracts";
8
9export const PREVIEW_STREAM_BASE_PATH = "/api/preview-stream";
10
11export interface PreviewStreamViewport {
12 readonly width: number;
13 readonly height: number;
14}
15
16export type PreviewStreamMouseButton = "none" | "left" | "middle" | "right";
17
18export interface PreviewStreamControl {
19 readonly canOperate: boolean;
20 readonly controller: "agent" | "you" | "another-viewer" | "unclaimed";
21 readonly generation: number;
22 readonly dialog: null | {
23 readonly type: string;
24 readonly message: string;
25 readonly defaultValue: string;
26 };
27}
28
29/** Status line shown above a viewer; `null` control means the socket is not connected. */
30export const previewStreamControlLabel = (control: PreviewStreamControl | null): string =>
31 !control
32 ? "Connecting..."
33 : !control.canOperate
34 ? "Read-only"
35 : control.controller === "you"
36 ? "You have control"
37 : control.controller === "agent"
38 ? "Agent has control"
39 : control.controller === "another-viewer"
40 ? "Another viewer has control"
41 : "Watching";
42
43const isPreviewStreamDialog = (value: unknown): value is PreviewStreamControl["dialog"] =>
44 value === null ||
45 (typeof value === "object" &&
46 "type" in value &&
47 typeof value.type === "string" &&
48 "message" in value &&
49 typeof value.message === "string" &&
50 "defaultValue" in value &&
51 typeof value.defaultValue === "string");
52
53/** Client-to-server messages. Coordinates are page CSS px. */
54export type PreviewStreamInput =
55 | { readonly type: "takeControl" }
56 | { readonly type: "releaseControl" }
57 | { readonly type: "dialog"; readonly accept: boolean; readonly promptText?: string }
58 | { readonly type: "viewport"; readonly setting: PreviewViewportSetting }
59 | {
60 readonly type: "mouse";
61 readonly action: "move" | "down" | "up";
62 readonly x: number;
63 readonly y: number;
64 readonly button: PreviewStreamMouseButton;
65 /** Pressed buttons: left 1, right 2, middle 4. */
66 readonly buttons: number;
67 readonly clickCount: number;
68 readonly modifiers: number;
69 }
70 | {
71 readonly type: "wheel";
72 readonly x: number;
73 readonly y: number;
74 readonly deltaX: number;
75 readonly deltaY: number;
76 readonly modifiers: number;
77 }
78 | {
79 readonly type: "key";
80 readonly action: "down" | "up";
81 readonly key: string;
82 readonly code: string;
83 /** Windows virtual key code (DOM `keyCode`); Enter, Backspace, and arrows need it. */
84 readonly keyCode?: number;
85 /** Only for printable keys without Ctrl or Meta. */
86 readonly text?: string;
87 readonly modifiers: number;
88 }
89 | { readonly type: "text"; readonly text: string }
90 | { readonly type: "resize"; readonly width: number; readonly height: number }
91 | { readonly type: "navigate"; readonly url: string }
92 | { readonly type: "history"; readonly delta: -1 | 1 }
93 | { readonly type: "reload"; readonly ignoreCache?: boolean }
94 /** Asks whether the page point takes text. Touch viewers send it on touch start. */
95 | { readonly type: "probe"; readonly x: number; readonly y: number };
96
97export interface PreviewStreamDownload {
98 readonly fileName: string;
99 readonly sizeBytes: number;
100 /** Authenticated with the stream's own access; cookie sessions must send credentials. */
101 readonly url: string;
102}
103
104export interface PreviewStreamFileChooser {
105 readonly multiple: boolean;
106 /** The input's `accept` attribute, ready for a local `<input type=file>`. */
107 readonly accept: string;
108 /** POST multipart `file` parts here; an empty form cancels the page's picker. */
109 readonly uploadUrl: string;
110 /** Cookie sessions must send credentials with the upload. */
111 readonly credentials: boolean;
112}
113
114const previewStreamUploadUrl = (
115 target: Pick<PreviewStreamTarget, "access" | "threadId" | "tabId">,
116 chooser: string,
117): string =>
118 withDeviceHubQuery(
119 `${target.access.httpBase}/upload?${new URLSearchParams({
120 threadId: target.threadId,
121 tabId: target.tabId,
122 chooser,
123 }).toString()}`,
124 target.access,
125 );
126
127/** Sends files to a page's open picker. Rejects when the server refuses them. */
128export async function uploadPreviewStreamFiles(
129 chooser: PreviewStreamFileChooser,
130 files: ReadonlyArray<Blob & { readonly name?: string }>,
131): Promise<void> {
132 const body = new FormData();
133 for (const file of files) body.append("file", file, file.name ?? "file");
134 const response = await fetch(chooser.uploadUrl, {
135 method: "POST",
136 body,
137 credentials: chooser.credentials ? "include" : "omit",
138 });
139 if (!response.ok) throw new Error((await response.text()) || "The upload was refused.");
140}
141
142const previewStreamDownloadUrl = (
143 target: Pick<PreviewStreamTarget, "access" | "threadId" | "tabId">,
144 id: string,
145): string =>
146 withDeviceHubQuery(
147 `${target.access.httpBase}/download?${new URLSearchParams({
148 threadId: target.threadId,
149 tabId: target.tabId,
150 id,
151 }).toString()}`,
152 target.access,
153 );
154
155/** Answer to a `probe`, echoing its point. */
156export interface PreviewStreamProbe {
157 readonly x: number;
158 readonly y: number;
159 readonly editable: boolean;
160}
161
162/** Where an agent action is about to land, in page CSS pixels. */
163export interface PreviewStreamPointer {
164 readonly phase: "move" | "click";
165 readonly x: number;
166 readonly y: number;
167 readonly sequence: number;
168}
169
170/** CDP modifier bitmask: Alt 1, Ctrl 2, Meta 4, Shift 8. */
171export const previewStreamModifiers = (event: {
172 readonly altKey: boolean;
173 readonly ctrlKey: boolean;
174 readonly metaKey: boolean;
175 readonly shiftKey: boolean;
176}): number =>
177 (event.altKey ? 1 : 0) |
178 (event.ctrlKey ? 2 : 0) |
179 (event.metaKey ? 4 : 0) |
180 (event.shiftKey ? 8 : 0);
181
182export interface PreviewStreamTarget {
183 readonly access: DeviceHubAccess;
184 readonly threadId: string;
185 readonly tabId: string;
186 /** Viewer backing-store size in device px. The server never sends larger frames. */
187 readonly maxWidth: number;
188 readonly maxHeight: number;
189 /** Passive viewers reduce their own access, including automatic control grants. */
190 readonly interactive?: boolean;
191}
192
193export interface PreviewStreamEvents {
194 /** One complete JPEG frame. */
195 readonly onFrame: (jpeg: ArrayBuffer) => void;
196 readonly onViewport: (viewport: PreviewStreamViewport) => void;
197 readonly onProbe?: (probe: PreviewStreamProbe) => void;
198 /** The agent's cursor moved to, or clicked at, a page point. */
199 readonly onPointer?: (pointer: PreviewStreamPointer) => void;
200 readonly onControl?: (control: PreviewStreamControl) => void;
201 /** Text the page just copied or cut while this viewer had control. */
202 readonly onClipboard?: (text: string) => void;
203 /** A file the page downloaded while this viewer had control. */
204 readonly onDownload?: (download: PreviewStreamDownload) => void;
205 /** The page opened a file picker (`null` once answered or replaced). */
206 readonly onFileChooser?: (chooser: PreviewStreamFileChooser | null) => void;
207 /** Input sent while disconnected is dropped. */
208 readonly onConnectedChange: (connected: boolean) => void;
209 /** The upgrade was refused; refresh access and start a new client. */
210 readonly onUnauthorized: () => void;
211 /** The tab was closed on the server. The client has stopped. */
212 readonly onGone?: () => void;
213 /** The server's browser cannot start until its host is set up. The client has stopped. */
214 readonly onHostSetup?: (setup: PreviewStreamHostSetup) => void;
215}
216
217export interface PreviewStreamClient {
218 /** False when the socket is not open and the message was dropped. */
219 readonly send: (input: PreviewStreamInput) => boolean;
220 readonly stop: () => void;
221}
222
223const ACK_MESSAGE = JSON.stringify({ type: "ack" });
224export function createPreviewStreamClient(
225 target: PreviewStreamTarget,
226 events: PreviewStreamEvents,
227): PreviewStreamClient {
228 const query = new URLSearchParams({
229 threadId: target.threadId,
230 tabId: target.tabId,
231 maxWidth: String(Math.max(1, Math.round(target.maxWidth))),
232 maxHeight: String(Math.max(1, Math.round(target.maxHeight))),
233 });
234 if (target.interactive === false) query.set("interactive", "false");
235 const url = withDeviceHubQuery(`${target.access.wsBase}/ws?${query.toString()}`, target.access);
236 let stopped = false;
237 let socket: WebSocket | null = null;
238 let retryTimer: ReturnType<typeof setTimeout> | null = null;
239 let failures = 0;
240 let control: PreviewStreamControl | null = null;
241 let fileChooser: string | null = null;
242
243 const connect = () => {
244 if (stopped) return;
245 const ws = new WebSocket(url);
246 ws.binaryType = "arraybuffer";
247 socket = ws;
248 let opened = false;
249 ws.addEventListener("open", () => {
250 if (socket !== ws) return;
251 opened = true;
252 events.onConnectedChange(true);
253 });
254 ws.addEventListener("message", (event) => {
255 if (socket !== ws) return;
256 if (event.data instanceof ArrayBuffer) {
257 failures = 0;
258 ws.send(ACK_MESSAGE);
259 events.onFrame(event.data);
260 return;
261 }
262 if (typeof event.data !== "string") return;
263 let message: unknown;
264 try {
265 message = JSON.parse(event.data);
266 } catch {
267 return;
268 }
269 if (typeof message !== "object" || message === null) return;
270 const {
271 type,
272 x,
273 y,
274 width,
275 height,
276 editable,
277 canOperate,
278 controller,
279 generation,
280 dialog,
281 text,
282 id,
283 fileName,
284 sizeBytes,
285 multiple,
286 accept,
287 phase,
288 sequence,
289 } = message as Record<string, unknown>;
290 if (
291 type === "fileChooser" &&
292 typeof id === "string" &&
293 typeof multiple === "boolean" &&
294 typeof accept === "string"
295 ) {
296 fileChooser = id;
297 events.onFileChooser?.({
298 multiple,
299 accept,
300 uploadUrl: previewStreamUploadUrl(target, id),
301 credentials: target.access.credentials,
302 });
303 } else if (type === "fileChooserClosed" && typeof id === "string") {
304 if (fileChooser !== id) return;
305 fileChooser = null;
306 events.onFileChooser?.(null);
307 } else if (
308 type === "pointer" &&
309 (phase === "move" || phase === "click") &&
310 typeof x === "number" &&
311 typeof y === "number" &&
312 typeof sequence === "number"
313 ) {
314 events.onPointer?.({ phase, x, y, sequence });
315 } else if (type === "clipboard" && typeof text === "string") {
316 events.onClipboard?.(text);
317 } else if (
318 type === "download" &&
319 typeof id === "string" &&
320 typeof fileName === "string" &&
321 typeof sizeBytes === "number"
322 ) {
323 events.onDownload?.({
324 fileName,
325 sizeBytes,
326 url: previewStreamDownloadUrl(target, id),
327 });
328 } else if (type === "viewport" && typeof width === "number" && typeof height === "number") {
329 failures = 0;
330 events.onViewport({ width, height });
331 } else if (
332 type === "probe" &&
333 typeof x === "number" &&
334 typeof y === "number" &&
335 typeof editable === "boolean"
336 ) {
337 events.onProbe?.({ x, y, editable });
338 } else if (
339 type === "control" &&
340 typeof canOperate === "boolean" &&
341 (controller === "agent" ||
342 controller === "you" ||
343 controller === "another-viewer" ||
344 controller === "unclaimed") &&
345 typeof generation === "number" &&
346 isPreviewStreamDialog(dialog)
347 ) {
348 const nextControl: PreviewStreamControl = {
349 canOperate,
350 controller,
351 generation,
352 dialog,
353 };
354 control = nextControl;
355 events.onControl?.(nextControl);
356 }
357 });
358 ws.addEventListener("close", (event) => {
359 if (socket !== ws) return;
360 socket = null;
361 control = null;
362 if (opened) events.onConnectedChange(false);
363 if (stopped) return;
364 if (event.code === 4404) {
365 stopped = true;
366 events.onGone?.();
367 return;
368 }
369 if (event.code === PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE) {
370 stopped = true;
371 events.onHostSetup?.(decodeHostSetup(event.reason));
372 return;
373 }
374 // Rejected upgrades surface as 1006 before open for both cookies and tickets.
375 if (event.code === 1008 || event.code === 4401 || (!opened && event.code === 1006)) {
376 stopped = true;
377 events.onUnauthorized();
378 return;
379 }
380 retryTimer = setTimeout(connect, Math.min(500 * 2 ** failures++, 10_000));
381 });
382 ws.addEventListener("error", () => ws.close());
383 };
384
385 connect();
386
387 return {
388 send: (input) => {
389 if (socket?.readyState !== WebSocket.OPEN) return false;
390 if (!control?.canOperate) return false;
391 if (input.type !== "takeControl" && control.controller !== "you") return false;
392 socket.send(JSON.stringify(input));
393 return true;
394 },
395 stop: () => {
396 stopped = true;
397 if (retryTimer !== null) clearTimeout(retryTimer);
398 const ws = socket;
399 socket = null;
400 control = null;
401 ws?.close();
402 },
403 };
404}
405
406export interface PreviewFramePainter {
407 readonly paint: (jpeg: ArrayBuffer) => void;
408 readonly stop: () => void;
409}
410
411/** One decode at a time, keeping only the latest waiting frame for slow viewers. */
412export function createPreviewFramePainter(
413 canvas: HTMLCanvasElement,
414 onPainted?: () => void,
415): PreviewFramePainter {
416 const context = canvas.getContext("2d");
417 let stopped = false;
418 let decoding = false;
419 let waiting: ArrayBuffer | null = null;
420 const draw = (jpeg: ArrayBuffer) => {
421 decoding = true;
422 void createImageBitmap(new Blob([jpeg], { type: "image/jpeg" }))
423 .then((bitmap) => {
424 if (stopped || !context) {
425 bitmap.close();
426 return;
427 }
428 if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {
429 canvas.width = bitmap.width;
430 canvas.height = bitmap.height;
431 }
432 context.drawImage(bitmap, 0, 0);
433 bitmap.close();
434 onPainted?.();
435 })
436 // A frame that fails to decode is skipped; the next one repaints.
437 .catch(() => undefined)
438 .finally(() => {
439 decoding = false;
440 const next = waiting;
441 waiting = null;
442 if (next && !stopped) draw(next);
443 });
444 };
445 return {
446 paint: (jpeg) => {
447 if (stopped) return;
448 if (decoding) waiting = jpeg;
449 else draw(jpeg);
450 },
451 stop: () => {
452 stopped = true;
453 waiting = null;
454 },
455 };
456}
457
458/** A malformed reason still stops the viewer and offers the usual command. */
459const decodeHostSetup = (reason: string): PreviewStreamHostSetup => {
460 try {
461 const value = JSON.parse(reason) as Partial<PreviewStreamHostSetup>;
462 if (
463 (value.need === "sandbox" || value.need === "libraries") &&
464 typeof value.command === "string"
465 ) {
466 return { need: value.need, command: value.command };
467 }
468 } catch {}
469 return { need: "sandbox", command: "sudo npx t3 browser setup" };
470};
471
472/** What a viewer tells the person; `command` is shown beside it, ready to copy. */
473export const previewStreamHostSetupMessage = (setup: PreviewStreamHostSetup) =>
474 setup.need === "sandbox"
475 ? "This server's host blocks the sandbox its browser runs in. Run this once on the host, then try again:"
476 : "This server's host is missing libraries its browser needs. Run this once on the host, then try again:";