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

browserRecording.ts

627 lines20.2 KB

1import type {
2 DesktopPreviewRecordingArtifact,
3 DesktopPreviewRecordingFrame,
4 ScopedThreadRef,
5} from "@t3tools/contracts";
6import { useAtomValue } from "@effect/atom-react";
7import * as Schema from "effect/Schema";
8import { Atom } from "effect/unstable/reactivity";
9​
10import { previewBridge } from "~/components/preview/previewBridge";
11import { appAtomRegistry } from "~/rpc/atomRegistry";
12import { useBrowserSurfaceStore } from "./browserSurfaceStore";
13​
14export class BrowserRecordingUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingUnavailableError>()(
15 "BrowserRecordingUnavailableError",
16 {
17 tabId: Schema.String,
18 },
19) {
20 override get message(): string {
21 return `Browser recording is unavailable for tab ${this.tabId}.`;
22 }
24​
25export class BrowserRecordingConflictError extends Schema.TaggedErrorClass<BrowserRecordingConflictError>()(
26 "BrowserRecordingConflictError",
27 {
28 requestedTabId: Schema.String,
29 activeTabId: Schema.String,
30 },
31) {
32 override get message(): string {
33 return `Cannot record tab ${this.requestedTabId} while tab ${this.activeTabId} is already being recorded.`;
34 }
36​
37export class BrowserRecordingCanvasUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingCanvasUnavailableError>()(
38 "BrowserRecordingCanvasUnavailableError",
39 {
40 tabId: Schema.String,
41 width: Schema.Number,
42 height: Schema.Number,
43 },
44) {
45 override get message(): string {
46 return `Browser recording canvas ${this.width}x${this.height} is unavailable for tab ${this.tabId}.`;
47 }
49​
50export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<BrowserRecordingOperationError>()(
51 "BrowserRecordingOperationError",
52 {
53 operation: Schema.Literals([
54 "initialize-media-recorder",
55 "subscribe-frames",
56 "start-media-recorder",
57 "start-screencast",
58 "stop-screencast",
59 "wait-first-frame",
60 "wait-startup",
61 "stop-media-recorder",
62 "save-artifact",
63 "cleanup",
64 ]),
65 tabId: Schema.String,
66 cause: Schema.Defect(),
67 },
68) {
69 override get message(): string {
70 return `Browser recording operation ${this.operation} failed for tab ${this.tabId}.`;
71 }
73​
74const isBrowserRecordingOperationError = Schema.is(BrowserRecordingOperationError);
75​
76type BrowserRecordingLifecycle =
77 | { readonly phase: "starting" }
78 | { readonly phase: "recording" }
79 | {
80 readonly phase: "stopping";
81 readonly stopPromise: Promise<DesktopPreviewRecordingArtifact | null>;
82 };
83​
84interface ActiveRecording {
85 /** Desktop-scoped identity used by capture and surface stores. */
86 readonly tabId: string;
87 /** Server-local identity returned by preview automation tools. */
88 readonly serverTabId: string;
89 readonly threadRef: ScopedThreadRef | null;
90 readonly canvas: HTMLCanvasElement;
91 readonly context: CanvasRenderingContext2D;
92 readonly chunks: Blob[];
93 readonly startedAt: string;
94 readonly startupSettled: Promise<void>;
95 readonly firstFrameSize: Promise<"frame" | "cancelled">;
96 readonly settleFirstFrameSize: (outcome: "frame" | "cancelled") => void;
97 recorder: MediaRecorder | null;
98 mimeType: string | null;
99 frameSizeEstablished: boolean;
100 frameSequence: number;
101 lastDrawnFrameSequence: number;
102 lifecycle: BrowserRecordingLifecycle;
104​
105export interface ActiveBrowserRecordingTarget {
106 readonly runtimeTabId: string;
107 readonly serverTabId: string;
109​
110interface ActiveBrowserRecordingIndex {
111 readonly tabIds: ReadonlySet<string>;
113​
114const activeBrowserRecordingTabIdsAtom = Atom.make<ActiveBrowserRecordingIndex>({
115 tabIds: new Set<string>(),
116}).pipe(Atom.keepAlive, Atom.withLabel("preview:active-browser-recording-tabs"));
117​
118export function useActiveBrowserRecordingTabIds(): ReadonlySet<string> {
119 return useAtomValue(activeBrowserRecordingTabIdsAtom).tabIds;
121​
122const activeRecordings = new Map<string, ActiveRecording>();
123let unsubscribeFrames: (() => void) | null = null;
124​
125export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;
126export const BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS = 5_000;
127​
128export function readActiveBrowserRecordingTabIds(threadRef?: ScopedThreadRef): ReadonlySet<string> {
129 const tabIds = new Set<string>();
130 for (const recording of activeRecordings.values()) {
131 if (
132 threadRef === undefined ||
133 (recording.threadRef?.environmentId === threadRef.environmentId &&
134 recording.threadRef.threadId === threadRef.threadId)
135 ) {
136 tabIds.add(recording.tabId);
137 }
138 }
139 return tabIds;
141​
142export function readActiveBrowserRecordingTargets(
143 threadRef: ScopedThreadRef,
144): ReadonlyArray<ActiveBrowserRecordingTarget> {
145 return Array.from(activeRecordings.values()).flatMap((recording) =>
146 recording.threadRef?.environmentId === threadRef.environmentId &&
147 recording.threadRef.threadId === threadRef.threadId
148 ? [{ runtimeTabId: recording.tabId, serverTabId: recording.serverTabId }]
149 : [],
150 );
152​
153export function findActiveBrowserRecordingRuntimeTabId(
154 threadRef: ScopedThreadRef,
155 serverTabId: string,
156): string | null {
157 return (
158 readActiveBrowserRecordingTargets(threadRef).find(
159 (recording) => recording.serverTabId === serverTabId,
160 )?.runtimeTabId ?? null
161 );
163​
164const preferredMimeType = (): string => {
165 const candidates = ["video/mp4;codecs=avc1.42E01E", "video/webm;codecs=vp9", "video/webm"];
166 return candidates.find((candidate) => MediaRecorder.isTypeSupported(candidate)) ?? "video/webm";
167};
168​
169const drawFrame = (frame: DesktopPreviewRecordingFrame): void => {
170 const recording = activeRecordings.get(frame.tabId);
171 if (!recording) return;
172 if (
173 !Number.isFinite(frame.width) ||
174 !Number.isFinite(frame.height) ||
175 frame.width <= 0 ||
176 frame.height <= 0
177 ) {
178 return;
179 }
180 const width = Math.max(1, Math.round(frame.width));
181 const height = Math.max(1, Math.round(frame.height));
182 if (!recording.frameSizeEstablished) {
183 recording.canvas.width = width;
184 recording.canvas.height = height;
185 recording.frameSizeEstablished = true;
186 recording.settleFirstFrameSize("frame");
187 }
188 const frameSequence = ++recording.frameSequence;
189 const image = new Image();
190 image.addEventListener(
191 "load",
192 () => {
193 if (
194 activeRecordings.get(frame.tabId) !== recording ||
195 frameSequence <= recording.lastDrawnFrameSequence
196 ) {
197 return;
198 }
199 recording.lastDrawnFrameSequence = frameSequence;
200 const scale = Math.min(recording.canvas.width / width, recording.canvas.height / height);
201 const targetWidth = width * scale;
202 const targetHeight = height * scale;
203 const targetX = (recording.canvas.width - targetWidth) / 2;
204 const targetY = (recording.canvas.height - targetHeight) / 2;
205 recording.context.fillStyle = "#000000";
206 recording.context.fillRect(0, 0, recording.canvas.width, recording.canvas.height);
207 recording.context.drawImage(image, targetX, targetY, targetWidth, targetHeight);
208 },
209 { once: true },
210 );
211 image.src = `data:image/jpeg;base64,${frame.data}`;
212};
213​
214const stopMediaRecorder = async (recorder: MediaRecorder | null): Promise<void> => {
215 if (!recorder || recorder.state === "inactive") return;
216 const stopped = new Promise<void>((resolve) =>
217 recorder.addEventListener("stop", () => resolve(), { once: true }),
218 );
219 recorder.stop();
220 await stopped;
221};
222​
223const clearActiveRecording = (recording: ActiveRecording): void => {
224 if (activeRecordings.get(recording.tabId) !== recording) return;
225 recording.settleFirstFrameSize("cancelled");
226 activeRecordings.delete(recording.tabId);
227 if (activeRecordings.size === 0) {
228 unsubscribeFrames?.();
229 unsubscribeFrames = null;
230 }
231 appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
232 tabIds: new Set(activeRecordings.keys()),
233 });
234};
235​
236const cleanupFailedRecordingStart = async (
237 bridge: NonNullable<typeof previewBridge>,
238 recording: ActiveRecording,
239): Promise<unknown | undefined> => {
240 const errors: unknown[] = [];
241 try {
242 await bridge.recording.stopScreencast(recording.tabId);
243 } catch (error) {
244 errors.push(error);
245 }
246 try {
247 await stopMediaRecorder(recording.recorder);
248 } catch (error) {
249 errors.push(error);
250 } finally {
251 clearActiveRecording(recording);
252 }
253 if (errors.length === 0) return undefined;
254 if (errors.length === 1) return errors[0];
255 return new AggregateError(
256 errors,
257 `Browser recording startup cleanup failed for tab ${recording.tabId}.`,
258 { cause: errors[0] },
259 );
260};
261​
262const recordingStartupCancelledError = (
263 recording: ActiveRecording,
264 cause: unknown = new Error(`Browser recording startup was cancelled for tab ${recording.tabId}.`),
265): BrowserRecordingOperationError =>
266 new BrowserRecordingOperationError({
267 operation: "start-screencast",
268 tabId: recording.tabId,
269 cause,
270 });
271​
272const isRecordingStarting = (recording: ActiveRecording): boolean =>
273 activeRecordings.get(recording.tabId) === recording && recording.lifecycle.phase === "starting";
274​
275const waitForFirstFrameSize = async (recording: ActiveRecording): Promise<boolean> => {
276 if (recording.frameSizeEstablished) return true;
277 let timeout: ReturnType<typeof setTimeout> | null = null;
278 const outcome = await Promise.race([
279 recording.firstFrameSize,
280 new Promise<"timeout">((resolve) => {
281 timeout = setTimeout(() => resolve("timeout"), BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS);
282 }),
283 ]);
284 if (timeout !== null) clearTimeout(timeout);
285 return outcome === "frame";
286};
287​
288const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Promise<void> => {
289 let timeout: ReturnType<typeof setTimeout> | null = null;
290 try {
291 await Promise.race([
292 recording.startupSettled,
293 new Promise<void>((_, reject) => {
294 timeout = setTimeout(() => {
295 reject(new Error(`Browser recording startup did not settle for tab ${recording.tabId}.`));
296 }, BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);
297 }),
298 ]);
299 } catch (cause) {
300 throw new BrowserRecordingOperationError({
301 operation: "wait-startup",
302 tabId: recording.tabId,
303 cause,
304 });
305 } finally {
306 if (timeout !== null) clearTimeout(timeout);
307 }
308};
309​
310const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperationError =>
311 isBrowserRecordingOperationError(error) && error.operation === "wait-startup";
312​
313export async function startBrowserRecording(
314 tabId: string,
315 threadRef: ScopedThreadRef | null = null,
316 serverTabId = tabId,
317): Promise<string> {
318 const bridge = previewBridge;
319 if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
320 const activeRecording = activeRecordings.get(tabId);
321 if (activeRecording) {
322 if (activeRecording.lifecycle.phase === "recording") {
323 return activeRecording.startedAt;
324 }
325 throw new BrowserRecordingConflictError({
326 requestedTabId: tabId,
327 activeTabId: activeRecording.tabId,
328 });
329 }
330 const activeLogicalRecording =
331 threadRef === null ? null : findActiveBrowserRecordingRuntimeTabId(threadRef, serverTabId);
332 if (activeLogicalRecording !== null) {
333 throw new BrowserRecordingConflictError({
334 requestedTabId: tabId,
335 activeTabId: activeLogicalRecording,
336 });
337 }
338 const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
339 const recordingSize = surface?.content ?? surface?.rect;
340 const canvas = document.createElement("canvas");
341 canvas.width = Math.max(1, recordingSize?.width ?? 1280);
342 canvas.height = Math.max(1, recordingSize?.height ?? 800);
343 const context = canvas.getContext("2d", { alpha: false });
344 if (!context) {
345 throw new BrowserRecordingCanvasUnavailableError({
346 tabId,
347 width: canvas.width,
348 height: canvas.height,
349 });
350 }
351 const startedAt = new Date().toISOString();
352 const chunks: Blob[] = [];
353 let settleStartup: (() => void) | undefined;
354 const startupSettled = new Promise<void>((resolve) => {
355 settleStartup = resolve;
356 });
357 let settleFirstFrameSize: ((outcome: "frame" | "cancelled") => void) | undefined;
358 const firstFrameSize = new Promise<"frame" | "cancelled">((resolve) => {
359 settleFirstFrameSize = resolve;
360 });
361 const recording: ActiveRecording = {
362 tabId,
363 serverTabId,
364 threadRef,
365 canvas,
366 context,
367 chunks,
368 startedAt,
369 startupSettled,
370 firstFrameSize,
371 settleFirstFrameSize: (outcome) => settleFirstFrameSize?.(outcome),
372 recorder: null,
373 mimeType: null,
374 frameSizeEstablished: false,
375 frameSequence: 0,
376 lastDrawnFrameSequence: 0,
377 lifecycle: { phase: "starting" },
378 };
379 activeRecordings.set(tabId, recording);
380 try {
381 try {
382 unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
383 } catch (cause) {
384 clearActiveRecording(recording);
385 throw new BrowserRecordingOperationError({
386 operation: "subscribe-frames",
387 tabId,
388 cause,
389 });
390 }
391 try {
392 await bridge.recording.startScreencast(tabId);
393 } catch (cause) {
394 if (!isRecordingStarting(recording)) {
395 throw recordingStartupCancelledError(recording, cause);
396 }
397 clearActiveRecording(recording);
398 throw new BrowserRecordingOperationError({
399 operation: "start-screencast",
400 tabId,
401 cause,
402 });
403 }
404 const throwIfStartupCancelled = async (): Promise<void> => {
405 // A stop requested during startup should let startup finish so the
406 // caller receives a real artifact. Only replacement/removal cancels it.
407 if (activeRecordings.get(tabId) === recording) return;
408 try {
409 await bridge.recording.stopScreencast(tabId);
410 } catch (cause) {
411 throw recordingStartupCancelledError(
412 recording,
413 new AggregateError(
414 [new Error(`Browser recording startup was cancelled for tab ${tabId}.`), cause],
415 `Browser recording startup cancellation failed for tab ${tabId}.`,
416 { cause },
417 ),
418 );
419 }
420 throw recordingStartupCancelledError(recording);
421 };
422 await throwIfStartupCancelled();
423 const hasFirstFrame = await waitForFirstFrameSize(recording);
424 await throwIfStartupCancelled();
425 if (!hasFirstFrame) {
426 const cause = new Error(`No valid recording frame arrived for tab ${tabId}.`);
427 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
428 throw new BrowserRecordingOperationError({
429 operation: "wait-first-frame",
430 tabId,
431 cause:
432 cleanupCause === undefined
433 ? cause
434 : new AggregateError(
435 [cause, cleanupCause],
436 `Browser recording frame wait and cleanup failed for tab ${tabId}.`,
437 { cause },
438 ),
439 });
440 }
441​
442 let mimeType: string;
443 let recorder: MediaRecorder;
444 try {
445 mimeType = preferredMimeType();
446 recorder = new MediaRecorder(canvas.captureStream(12), {
447 mimeType,
448 videoBitsPerSecond: 4_000_000,
449 });
450 recording.mimeType = mimeType;
451 recording.recorder = recorder;
452 recorder.addEventListener("dataavailable", (event) => {
453 if (event.data.size > 0) chunks.push(event.data);
454 });
455 } catch (cause) {
456 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
457 throw new BrowserRecordingOperationError({
458 operation: "initialize-media-recorder",
459 tabId,
460 cause:
461 cleanupCause === undefined
462 ? cause
463 : new AggregateError(
464 [cause, cleanupCause],
465 `Browser recording initialization and cleanup failed for tab ${tabId}.`,
466 { cause },
467 ),
468 });
469 }
470 try {
471 recorder.start(1_000);
472 } catch (cause) {
473 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
474 throw new BrowserRecordingOperationError({
475 operation: "start-media-recorder",
476 tabId,
477 cause:
478 cleanupCause === undefined
479 ? cause
480 : new AggregateError(
481 [cause, cleanupCause],
482 `Browser media recorder start and cleanup failed for tab ${tabId}.`,
483 { cause },
484 ),
485 });
486 }
487 if (recording.lifecycle.phase === "starting") {
488 recording.lifecycle = { phase: "recording" };
489 }
490 appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
491 tabIds: new Set(activeRecordings.keys()),
492 });
493 return startedAt;
494 } finally {
495 settleStartup?.();
496 }
498​
499const finalizeBrowserRecording = async (
500 bridge: NonNullable<typeof previewBridge>,
501 recording: ActiveRecording,
502): Promise<DesktopPreviewRecordingArtifact | null> => {
503 const { tabId } = recording;
504 let result:
505 | {
506 readonly _tag: "Success";
507 readonly artifact: DesktopPreviewRecordingArtifact | null;
508 }
509 | { readonly _tag: "Failure"; readonly error: unknown };
510 try {
511 await waitForRecordingStartupToSettle(recording);
512 try {
513 await bridge.recording.stopScreencast(tabId);
514 } catch (cause) {
515 throw new BrowserRecordingOperationError({
516 operation: "stop-screencast",
517 tabId,
518 cause,
519 });
520 }
521 if (!recording.recorder || !recording.mimeType) {
522 result = { _tag: "Success", artifact: null };
523 } else {
524 try {
525 await stopMediaRecorder(recording.recorder);
526 } catch (cause) {
527 throw new BrowserRecordingOperationError({
528 operation: "stop-media-recorder",
529 tabId,
530 cause,
531 });
532 }
533 try {
534 const blob = new Blob(recording.chunks, { type: recording.mimeType });
535 const artifact = await bridge.recording.save(
536 tabId,
537 recording.mimeType,
538 new Uint8Array(await blob.arrayBuffer()),
539 );
540 result = { _tag: "Success", artifact };
541 } catch (cause) {
542 throw new BrowserRecordingOperationError({
543 operation: "save-artifact",
544 tabId,
545 cause,
546 });
547 }
548 }
549 } catch (error) {
550 result = { _tag: "Failure", error };
551 }
552​
553 if (result._tag === "Failure" && isStartupWaitTimeout(result.error)) {
554 // Do not clear `active` yet. The renderer-side start promise can still
555 // resolve later, and its cancellation path will call `stopScreencast`.
556 // Keeping the slot reserved prevents a newer recording for this tab from
557 // being started and then accidentally stopped by the older late cleanup.
558 throw result.error;
559 }
560​
561 let cleanupError: BrowserRecordingOperationError | undefined;
562 try {
563 await stopMediaRecorder(recording.recorder);
564 } catch (cause) {
565 cleanupError = new BrowserRecordingOperationError({
566 operation: "stop-media-recorder",
567 tabId,
568 cause,
569 });
570 } finally {
571 clearActiveRecording(recording);
572 }
573​
574 if (result._tag === "Failure") {
575 if (cleanupError) {
576 throw new BrowserRecordingOperationError({
577 operation: "cleanup",
578 tabId,
579 cause: new AggregateError(
580 [result.error, cleanupError],
581 `Browser recording stop and cleanup failed for tab ${tabId}.`,
582 { cause: result.error },
583 ),
584 });
585 }
586 throw result.error;
587 }
588 if (cleanupError) throw cleanupError;
589 return result.artifact;
590};
591​
592const discardBrowserRecording = async (
593 bridge: NonNullable<typeof previewBridge>,
594 recording: ActiveRecording,
595): Promise<null> => {
596 try {
597 await bridge.recording.stopScreencast(recording.tabId).catch(() => undefined);
598 await stopMediaRecorder(recording.recorder).catch(() => undefined);
599 return null;
600 } finally {
601 clearActiveRecording(recording);
602 }
603};
604​
605export function stopBrowserRecording(
606 tabId: string,
607): Promise<DesktopPreviewRecordingArtifact | null> {
608 const bridge = previewBridge;
609 const recording = activeRecordings.get(tabId);
610 if (!bridge || !recording) return Promise.resolve(null);
611 if (recording.lifecycle.phase === "stopping") return recording.lifecycle.stopPromise;
612​
613 const stopPromise = Promise.resolve()
614 .then(() => finalizeBrowserRecording(bridge, recording))
615 .catch((error) => {
616 if (isStartupWaitTimeout(error) && activeRecordings.get(recording.tabId) === recording) {
617 const cleanupAfterStartup = recording.startupSettled.then(() =>
618 discardBrowserRecording(bridge, recording),
619 );
620 recording.lifecycle = { phase: "stopping", stopPromise: cleanupAfterStartup };
621 void cleanupAfterStartup.catch(() => undefined);
622 }
623 throw error;
624 });
625 recording.lifecycle = { phase: "stopping", stopPromise };
626 return stopPromise;