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

serverBrowserStream.ts

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