Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverBrowserStream.ts

537 lines16.9 KB

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