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