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