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