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

browserRecording.ts

455 lines13.9 KB

1import type {
2 DesktopPreviewRecordingArtifact,
3 DesktopPreviewRecordingFrame,
4} from "@t3tools/contracts";
5import { useAtomValue } from "@effect/atom-react";
6import * as Schema from "effect/Schema";
7import { Atom } from "effect/unstable/reactivity";
8​
9import { previewBridge } from "~/components/preview/previewBridge";
10import { appAtomRegistry } from "~/rpc/atomRegistry";
11import { useBrowserSurfaceStore } from "./browserSurfaceStore";
12​
13export class BrowserRecordingUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingUnavailableError>()(
14 "BrowserRecordingUnavailableError",
15 {
16 tabId: Schema.String,
17 },
18) {
19 override get message(): string {
20 return `Browser recording is unavailable for tab ${this.tabId}.`;
21 }
23​
24export class BrowserRecordingConflictError extends Schema.TaggedErrorClass<BrowserRecordingConflictError>()(
25 "BrowserRecordingConflictError",
26 {
27 requestedTabId: Schema.String,
28 activeTabId: Schema.String,
29 },
30) {
31 override get message(): string {
32 return `Cannot record tab ${this.requestedTabId} while tab ${this.activeTabId} is already being recorded.`;
33 }
35​
36export class BrowserRecordingCanvasUnavailableError extends Schema.TaggedErrorClass<BrowserRecordingCanvasUnavailableError>()(
37 "BrowserRecordingCanvasUnavailableError",
38 {
39 tabId: Schema.String,
40 width: Schema.Number,
41 height: Schema.Number,
42 },
43) {
44 override get message(): string {
45 return `Browser recording canvas ${this.width}x${this.height} is unavailable for tab ${this.tabId}.`;
46 }
48​
49export class BrowserRecordingRequiresVisibleTabError extends Schema.TaggedErrorClass<BrowserRecordingRequiresVisibleTabError>()(
50 "BrowserRecordingRequiresVisibleTabError",
51 {
52 tabId: Schema.String,
53 },
54) {
55 override get message(): string {
56 return `Browser recording requires tab ${this.tabId} to be visible.`;
57 }
59​
60export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<BrowserRecordingOperationError>()(
61 "BrowserRecordingOperationError",
62 {
63 operation: Schema.Literals([
64 "initialize-media-recorder",
65 "subscribe-frames",
66 "start-media-recorder",
67 "start-screencast",
68 "stop-screencast",
69 "wait-startup",
70 "stop-media-recorder",
71 "save-artifact",
72 "cleanup",
73 ]),
74 tabId: Schema.String,
75 cause: Schema.Defect(),
76 },
77) {
78 override get message(): string {
79 return `Browser recording operation ${this.operation} failed for tab ${this.tabId}.`;
80 }
82​
83const isBrowserRecordingOperationError = Schema.is(BrowserRecordingOperationError);
84​
85type BrowserRecordingLifecycle =
86 | { readonly phase: "starting" }
87 | { readonly phase: "recording" }
88 | {
89 readonly phase: "stopping";
90 readonly stopPromise: Promise<DesktopPreviewRecordingArtifact | null>;
91 };
92​
93interface ActiveRecording {
94 readonly tabId: string;
95 readonly canvas: HTMLCanvasElement;
96 readonly context: CanvasRenderingContext2D;
97 readonly recorder: MediaRecorder;
98 readonly chunks: Blob[];
99 readonly mimeType: string;
100 readonly startedAt: string;
101 readonly startupSettled: Promise<void>;
102 lifecycle: BrowserRecordingLifecycle;
104​
105const activeBrowserRecordingTabIdAtom = Atom.make<string | null>(null).pipe(
106 Atom.keepAlive,
107 Atom.withLabel("preview:active-browser-recording-tab"),
108);
109​
110export function useActiveBrowserRecordingTabId(): string | null {
111 return useAtomValue(activeBrowserRecordingTabIdAtom);
113​
114let active: ActiveRecording | null = null;
115let unsubscribeFrames: (() => void) | null = null;
116​
117export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;
118​
119export function readActiveBrowserRecordingTabId(): string | null {
120 return active?.tabId ?? null;
122​
123const preferredMimeType = (): string => {
124 const candidates = ["video/mp4;codecs=avc1.42E01E", "video/webm;codecs=vp9", "video/webm"];
125 return candidates.find((candidate) => MediaRecorder.isTypeSupported(candidate)) ?? "video/webm";
126};
127​
128const drawFrame = (frame: DesktopPreviewRecordingFrame): void => {
129 const recording = active;
130 if (!recording || recording.tabId !== frame.tabId) return;
131 const image = new Image();
132 image.addEventListener(
133 "load",
134 () => {
135 if (active !== recording) return;
136 recording.context.drawImage(image, 0, 0, recording.canvas.width, recording.canvas.height);
137 },
138 { once: true },
139 );
140 image.src = `data:image/jpeg;base64,${frame.data}`;
141};
142​
143const stopMediaRecorder = async (recorder: MediaRecorder): Promise<void> => {
144 if (recorder.state === "inactive") return;
145 const stopped = new Promise<void>((resolve) =>
146 recorder.addEventListener("stop", () => resolve(), { once: true }),
147 );
148 recorder.stop();
149 await stopped;
150};
151​
152const clearActiveRecording = (recording: ActiveRecording): void => {
153 if (active !== recording) return;
154 active = null;
155 unsubscribeFrames?.();
156 unsubscribeFrames = null;
157 appAtomRegistry.set(activeBrowserRecordingTabIdAtom, null);
158};
159​
160const recordingStartupCancelledError = (
161 recording: ActiveRecording,
162 cause: unknown = new Error(`Browser recording startup was cancelled for tab ${recording.tabId}.`),
163): BrowserRecordingOperationError =>
164 new BrowserRecordingOperationError({
165 operation: "start-screencast",
166 tabId: recording.tabId,
167 cause,
168 });
169​
170const isRecordingStarting = (recording: ActiveRecording): boolean =>
171 active === recording && recording.lifecycle.phase === "starting";
172​
173const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Promise<void> => {
174 let timeout: ReturnType<typeof setTimeout> | null = null;
175 try {
176 await Promise.race([
177 recording.startupSettled,
178 new Promise<void>((_, reject) => {
179 timeout = setTimeout(() => {
180 reject(new Error(`Browser recording startup did not settle for tab ${recording.tabId}.`));
181 }, BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);
182 }),
183 ]);
184 } catch (cause) {
185 throw new BrowserRecordingOperationError({
186 operation: "wait-startup",
187 tabId: recording.tabId,
188 cause,
189 });
190 } finally {
191 if (timeout !== null) clearTimeout(timeout);
192 }
193};
194​
195const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperationError =>
196 isBrowserRecordingOperationError(error) && error.operation === "wait-startup";
197​
198export async function startBrowserRecording(tabId: string): Promise<string> {
199 const bridge = previewBridge;
200 if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
201 if (active) {
202 if (active.tabId === tabId && active.lifecycle.phase === "recording") {
203 return active.startedAt;
204 }
205 throw new BrowserRecordingConflictError({
206 requestedTabId: tabId,
207 activeTabId: active.tabId,
208 });
209 }
210 const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
211 if (!surface?.visible) throw new BrowserRecordingRequiresVisibleTabError({ tabId });
212 const recordingSize = surface?.content ?? surface?.rect;
213 const canvas = document.createElement("canvas");
214 canvas.width = Math.max(1, recordingSize?.width ?? 1280);
215 canvas.height = Math.max(1, recordingSize?.height ?? 800);
216 const context = canvas.getContext("2d", { alpha: false });
217 if (!context) {
218 throw new BrowserRecordingCanvasUnavailableError({
219 tabId,
220 width: canvas.width,
221 height: canvas.height,
222 });
223 }
224 let mimeType: string;
225 let recorder: MediaRecorder;
226 try {
227 mimeType = preferredMimeType();
228 recorder = new MediaRecorder(canvas.captureStream(12), {
229 mimeType,
230 videoBitsPerSecond: 4_000_000,
231 });
232 } catch (cause) {
233 throw new BrowserRecordingOperationError({
234 operation: "initialize-media-recorder",
235 tabId,
236 cause,
237 });
238 }
239 const startedAt = new Date().toISOString();
240 const chunks: Blob[] = [];
241 let settleStartup: (() => void) | undefined;
242 const startupSettled = new Promise<void>((resolve) => {
243 settleStartup = resolve;
244 });
245 recorder.addEventListener("dataavailable", (event) => {
246 if (event.data.size > 0) chunks.push(event.data);
247 });
248 const recording: ActiveRecording = {
249 tabId,
250 canvas,
251 context,
252 recorder,
253 chunks,
254 mimeType,
255 startedAt,
256 startupSettled,
257 lifecycle: { phase: "starting" },
258 };
259 active = recording;
260 try {
261 try {
262 unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
263 } catch (cause) {
264 clearActiveRecording(recording);
265 throw new BrowserRecordingOperationError({
266 operation: "subscribe-frames",
267 tabId,
268 cause,
269 });
270 }
271 try {
272 recorder.start(1_000);
273 } catch (cause) {
274 clearActiveRecording(recording);
275 throw new BrowserRecordingOperationError({
276 operation: "start-media-recorder",
277 tabId,
278 cause,
279 });
280 }
281 if (!isRecordingStarting(recording)) {
282 throw recordingStartupCancelledError(recording);
283 }
284 try {
285 await bridge.recording.startScreencast(tabId);
286 } catch (cause) {
287 if (!isRecordingStarting(recording)) {
288 throw recordingStartupCancelledError(recording, cause);
289 }
290 let cleanupCause: unknown;
291 try {
292 await stopMediaRecorder(recorder);
293 } catch (error) {
294 cleanupCause = error;
295 } finally {
296 clearActiveRecording(recording);
297 }
298 throw new BrowserRecordingOperationError({
299 operation: "start-screencast",
300 tabId,
301 cause:
302 cleanupCause === undefined
303 ? cause
304 : new AggregateError(
305 [cause, cleanupCause],
306 `Browser recording start and cleanup failed for tab ${tabId}.`,
307 { cause },
308 ),
309 });
310 }
311 if (!isRecordingStarting(recording)) {
312 try {
313 await bridge.recording.stopScreencast(tabId);
314 } catch (cause) {
315 throw recordingStartupCancelledError(
316 recording,
317 new AggregateError(
318 [new Error(`Browser recording startup was cancelled for tab ${tabId}.`), cause],
319 `Browser recording startup cancellation failed for tab ${tabId}.`,
320 { cause },
321 ),
322 );
323 }
324 throw recordingStartupCancelledError(recording);
325 }
326 recording.lifecycle = { phase: "recording" };
327 appAtomRegistry.set(activeBrowserRecordingTabIdAtom, tabId);
328 return startedAt;
329 } finally {
330 settleStartup?.();
331 }
333​
334const finalizeBrowserRecording = async (
335 bridge: NonNullable<typeof previewBridge>,
336 recording: ActiveRecording,
337): Promise<DesktopPreviewRecordingArtifact> => {
338 const { tabId } = recording;
339 let result:
340 | { readonly _tag: "Success"; readonly artifact: DesktopPreviewRecordingArtifact }
341 | { readonly _tag: "Failure"; readonly error: unknown };
342 try {
343 try {
344 await bridge.recording.stopScreencast(tabId);
345 } catch (cause) {
346 throw new BrowserRecordingOperationError({
347 operation: "stop-screencast",
348 tabId,
349 cause,
350 });
351 }
352 await waitForRecordingStartupToSettle(recording);
353 try {
354 await stopMediaRecorder(recording.recorder);
355 } catch (cause) {
356 throw new BrowserRecordingOperationError({
357 operation: "stop-media-recorder",
358 tabId,
359 cause,
360 });
361 }
362 try {
363 const blob = new Blob(recording.chunks, { type: recording.mimeType });
364 const artifact = await bridge.recording.save(
365 tabId,
366 recording.mimeType,
367 new Uint8Array(await blob.arrayBuffer()),
368 );
369 result = { _tag: "Success", artifact };
370 } catch (cause) {
371 throw new BrowserRecordingOperationError({
372 operation: "save-artifact",
373 tabId,
374 cause,
375 });
376 }
377 } catch (error) {
378 result = { _tag: "Failure", error };
379 }
380​
381 if (result._tag === "Failure" && isStartupWaitTimeout(result.error)) {
382 // Do not clear `active` yet. The renderer-side start promise can still
383 // resolve later, and its cancellation path will call `stopScreencast`.
384 // Keeping the slot reserved prevents a newer recording for this tab from
385 // being started and then accidentally stopped by the older late cleanup.
386 throw result.error;
387 }
388​
389 let cleanupError: BrowserRecordingOperationError | undefined;
390 try {
391 await stopMediaRecorder(recording.recorder);
392 } catch (cause) {
393 cleanupError = new BrowserRecordingOperationError({
394 operation: "stop-media-recorder",
395 tabId,
396 cause,
397 });
398 } finally {
399 clearActiveRecording(recording);
400 }
401​
402 if (result._tag === "Failure") {
403 if (cleanupError) {
404 throw new BrowserRecordingOperationError({
405 operation: "cleanup",
406 tabId,
407 cause: new AggregateError(
408 [result.error, cleanupError],
409 `Browser recording stop and cleanup failed for tab ${tabId}.`,
410 { cause: result.error },
411 ),
412 });
413 }
414 throw result.error;
415 }
416 if (cleanupError) throw cleanupError;
417 return result.artifact;
418};
419​
420const discardBrowserRecording = async (
421 bridge: NonNullable<typeof previewBridge>,
422 recording: ActiveRecording,
423): Promise<null> => {
424 try {
425 await bridge.recording.stopScreencast(recording.tabId).catch(() => undefined);
426 await stopMediaRecorder(recording.recorder).catch(() => undefined);
427 return null;
428 } finally {
429 clearActiveRecording(recording);
430 }
431};
432​
433export function stopBrowserRecording(
434 tabId: string,
435): Promise<DesktopPreviewRecordingArtifact | null> {
436 const bridge = previewBridge;
437 const recording = active;
438 if (!bridge || !recording || recording.tabId !== tabId) return Promise.resolve(null);
439 if (recording.lifecycle.phase === "stopping") return recording.lifecycle.stopPromise;
440​
441 const stopPromise = Promise.resolve()
442 .then(() => finalizeBrowserRecording(bridge, recording))
443 .catch((error) => {
444 if (isStartupWaitTimeout(error) && active === recording) {
445 const cleanupAfterStartup = recording.startupSettled.then(() =>
446 discardBrowserRecording(bridge, recording),
447 );
448 recording.lifecycle = { phase: "stopping", stopPromise: cleanupAfterStartup };
449 void cleanupAfterStartup.catch(() => undefined);
450 }
451 throw error;
452 });
453 recording.lifecycle = { phase: "stopping", stopPromise };
454 return stopPromise;