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

browserRecording.ts

843 lines27.2 KB

1import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
2import type { DesktopPreviewRecordingArtifact, ScopedThreadRef } from "@t3tools/contracts";
3import { useAtomValue } from "@effect/atom-react";
4import * as Schema from "effect/Schema";
5import { Atom } from "effect/reactivity";
6​
7import { previewBridge } from "~/components/preview/previewBridge";
8import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings";
9import { appAtomRegistry } from "~/rpc/atomRegistry";
10​
11import { createRecordingCompositor } from "./recordingCompositor";
12​
13import { acquireBrowserSurfaceActivity } from "./browserSurfaceStore";
14​
15export class BrowserRecordingUnavailableError extends Schema.TaggedError<BrowserRecordingUnavailableError>()(
16 "BrowserRecordingUnavailableError",
17 {
18 tabId: Schema.String,
19 },
20) {
21 override get message(): string {
22 return `Browser recording is unavailable for tab ${this.tabId}.`;
23 }
25​
26export class BrowserRecordingConflictError extends Schema.TaggedError<BrowserRecordingConflictError>()(
27 "BrowserRecordingConflictError",
28 {
29 requestedTabId: Schema.String,
30 activeTabId: Schema.String,
31 },
32) {
33 override get message(): string {
34 return `Cannot record tab ${this.requestedTabId} while tab ${this.activeTabId} is already being recorded.`;
35 }
37​
38export class BrowserRecordingStartCancelledError extends Schema.TaggedError<BrowserRecordingStartCancelledError>()(
39 "BrowserRecordingStartCancelledError",
40 {
41 tabId: Schema.String,
42 },
43) {
44 override get message(): string {
45 return `Browser recording start was cancelled for tab ${this.tabId}.`;
46 }
48​
49export class BrowserRecordingFormatUnavailableError extends Schema.TaggedError<BrowserRecordingFormatUnavailableError>()(
50 "BrowserRecordingFormatUnavailableError",
51 { tabId: Schema.String },
52) {
53 override get message(): string {
54 return `MediaRecorder did not report an output format for tab ${this.tabId}.`;
55 }
57​
58export class BrowserRecordingCaptureTimeoutError extends Schema.TaggedError<BrowserRecordingCaptureTimeoutError>()(
59 "BrowserRecordingCaptureTimeoutError",
60 {
61 tabId: Schema.String,
62 timeoutMs: Schema.Number,
63 },
64) {
65 override get message(): string {
66 return `Browser recording media capture for tab ${this.tabId} did not settle within ${this.timeoutMs}ms.`;
67 }
69​
70export class BrowserRecordingOperationError extends Schema.TaggedError<BrowserRecordingOperationError>()(
71 "BrowserRecordingOperationError",
72 {
73 operation: Schema.Literals([
74 "initialize-media-recorder",
75 "capture-media-stream",
76 "start-media-recorder",
77 "start-screencast",
78 "stop-screencast",
79 "wait-startup",
80 "stop-media-recorder",
81 "save-artifact",
82 "cleanup",
83 ]),
84 tabId: Schema.String,
85 cause: Schema.Defect(),
86 },
87) {
88 override get message(): string {
89 return `Browser recording operation ${this.operation} failed for tab ${this.tabId}.`;
90 }
92​
93const isBrowserRecordingOperationError = Schema.is(BrowserRecordingOperationError);
94const isBrowserRecordingCaptureTimeoutError = Schema.is(BrowserRecordingCaptureTimeoutError);
95export const isBrowserRecordingStartCancelledError = Schema.is(BrowserRecordingStartCancelledError);
96​
97interface StartingBrowserRecordingLifecycle {
98 readonly phase: "starting";
99 queuedForGrant: boolean | null;
100 grantStarted: boolean;
101 stopRequestedBeforeGrant: boolean;
102 cancelledBeforeGrant: boolean;
103 readonly cancelledBeforeGrantSignal: Promise<void>;
104 readonly cancelBeforeGrant: () => void;
105 readonly setQueuedForGrant: (queued: boolean) => void;
107​
108type BrowserRecordingLifecycle =
109 | StartingBrowserRecordingLifecycle
110 | { readonly phase: "recording" }
111 | {
112 readonly phase: "stopping";
113 readonly stopPromise: Promise<DesktopPreviewRecordingArtifact | null>;
114 };
115​
116interface ActiveRecording {
117 readonly tabId: string;
118 readonly serverTabId: string;
119 readonly threadRef: ScopedThreadRef | null;
120 readonly chunks: Blob[];
121 readonly startedAt: string;
122 readonly startupSettled: Promise<void>;
123 releaseSurfaceActivity: (() => void) | null;
124 stream: MediaStream | null;
125 recorder: MediaRecorder | null;
126 compositor: Awaited<ReturnType<typeof createRecordingCompositor>>;
127 savedBlob?: Blob;
128 uploadPromise?: Promise<string>;
129 lifecycle: BrowserRecordingLifecycle;
131​
132export interface ActiveBrowserRecordingTarget {
133 readonly runtimeTabId: string;
134 readonly serverTabId: string;
136​
137interface ActiveBrowserRecordingIndex {
138 readonly tabIds: ReadonlySet<string>;
140​
141const activeBrowserRecordingTabIdsAtom = Atom.make<ActiveBrowserRecordingIndex>({
142 tabIds: new Set<string>(),
143}).pipe(Atom.keepAlive, Atom.withLabel("preview:active-browser-recording-tabs"));
144​
145export function useActiveBrowserRecordingTabIds(): ReadonlySet<string> {
146 return useAtomValue(activeBrowserRecordingTabIdsAtom).tabIds;
148​
149const activeRecordings = new Map<string, ActiveRecording>();
150let displayMediaGrantTail = Promise.resolve();
151let displayMediaGrantQueueDepth = 0;
152​
153const makeStartingBrowserRecordingLifecycle = (): StartingBrowserRecordingLifecycle => {
154 let signalCancellation!: () => void;
155 const cancelledBeforeGrantSignal = new Promise<void>((resolve) => {
156 signalCancellation = resolve;
157 });
158 const lifecycle: StartingBrowserRecordingLifecycle = {
159 phase: "starting",
160 queuedForGrant: null,
161 grantStarted: false,
162 stopRequestedBeforeGrant: false,
163 cancelledBeforeGrant: false,
164 cancelledBeforeGrantSignal,
165 cancelBeforeGrant: () => {
166 lifecycle.stopRequestedBeforeGrant = true;
167 if (lifecycle.queuedForGrant && !lifecycle.grantStarted && !lifecycle.cancelledBeforeGrant) {
168 lifecycle.cancelledBeforeGrant = true;
169 signalCancellation();
170 }
171 },
172 setQueuedForGrant: (queued) => {
173 lifecycle.queuedForGrant = queued;
174 if (queued && lifecycle.stopRequestedBeforeGrant) lifecycle.cancelBeforeGrant();
175 },
176 };
177 return lifecycle;
178};
179​
180const queueDisplayMediaGrant = <T>(
181 useGrant: () => Promise<T>,
182): { readonly queued: boolean; readonly result: Promise<T> } => {
183 const queued = displayMediaGrantQueueDepth > 0;
184 displayMediaGrantQueueDepth += 1;
185 const result = displayMediaGrantTail.then(useGrant);
186 const settleGrant = () => {
187 displayMediaGrantQueueDepth -= 1;
188 };
189 displayMediaGrantTail = result.then(
190 () => settleGrant(),
191 () => settleGrant(),
192 );
193 return { queued, result };
194};
195​
196const publishActiveRecordingTabIds = (): void => {
197 appAtomRegistry.set(activeBrowserRecordingTabIdsAtom, {
198 tabIds: new Set(activeRecordings.keys()),
199 });
200};
201​
202export const BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS = 5_000;
203export const BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS = 250;
204​
205export function readActiveBrowserRecordingTabIds(threadRef?: ScopedThreadRef): ReadonlySet<string> {
206 const tabIds = new Set<string>();
207 for (const recording of activeRecordings.values()) {
208 if (
209 threadRef === undefined ||
210 (recording.threadRef?.environmentId === threadRef.environmentId &&
211 recording.threadRef.threadId === threadRef.threadId)
212 ) {
213 tabIds.add(recording.tabId);
214 }
215 }
216 return tabIds;
218​
219export function readActiveBrowserRecordingTargets(
220 threadRef: ScopedThreadRef,
221): ReadonlyArray<ActiveBrowserRecordingTarget> {
222 return Array.from(activeRecordings.values()).flatMap((recording) =>
223 recording.threadRef?.environmentId === threadRef.environmentId &&
224 recording.threadRef.threadId === threadRef.threadId
225 ? [{ runtimeTabId: recording.tabId, serverTabId: recording.serverTabId }]
226 : [],
227 );
229​
230export function findActiveBrowserRecordingRuntimeTabId(
231 threadRef: ScopedThreadRef,
232 serverTabId: string,
233): string | null {
234 return (
235 readActiveBrowserRecordingTargets(threadRef).find(
236 (recording) => recording.serverTabId === serverTabId,
237 )?.runtimeTabId ?? null
238 );
240​
241const preferredMimeTypes = [
242 "video/mp4;codecs=avc1",
243 "video/mp4;codecs=avc1.640028",
244 "video/mp4;codecs=avc1.42e01e",
245 "video/webm;codecs=vp9",
246 "video/webm;codecs=vp8",
247 "video/webm",
248] as const;
249​
250const createMediaRecorder = (stream: MediaStream): MediaRecorder => {
251 const mimeType = preferredMimeTypes.find((candidate) => MediaRecorder.isTypeSupported(candidate));
252 const settings = stream.getVideoTracks()[0]?.getSettings();
253 const videoBitsPerSecond = Math.round(
254 Math.min(
255 50_000_000,
256 Math.max(
257 2_500_000,
258 (settings?.width ?? 1920) * (settings?.height ?? 1080) * (settings?.frameRate ?? 30) * 0.05,
259 ),
260 ),
261 );
262 return new MediaRecorder(stream, { ...(mimeType ? { mimeType } : {}), videoBitsPerSecond });
263};
264​
265const captureTabMediaStream = (frameRate: number): Promise<MediaStream> =>
266 // The desktop main process routes this request to the tab that `startScreencast` armed, so the
267 // stream already arrives at that tab's native size and needs no source or dimension constraints.
268 navigator.mediaDevices.getDisplayMedia({
269 audio: false,
270 video: { frameRate: { ideal: frameRate, max: frameRate } },
271 });
272​
273const stopMediaRecorder = async (recorder: MediaRecorder | null): Promise<void> => {
274 if (!recorder || recorder.state === "inactive") return;
275 const stopped = new Promise<void>((resolve) =>
276 recorder.addEventListener("stop", () => resolve(), { once: true }),
277 );
278 recorder.stop();
279 await stopped;
280};
281​
282const stopMediaStream = (stream: MediaStream | null): void => {
283 for (const track of stream?.getTracks() ?? []) track.stop();
284};
285​
286interface PendingTabMediaCapture {
287 readonly start: () => void;
289​
290const pendingTabMediaCaptures = new Map<string, PendingTabMediaCapture>();
291​
292const prepareTabMediaCapture = (tabId: string, frameRate: number) => {
293 let acceptStream = true;
294 let capturedStream: MediaStream | null = null;
295 let resolveCapture!: (stream: MediaStream | PromiseLike<MediaStream>) => void;
296 let rejectCapture!: (cause: unknown) => void;
297 const capturePromise = new Promise<MediaStream>((resolve, reject) => {
298 resolveCapture = resolve;
299 rejectCapture = reject;
300 }).then((stream) => {
301 capturedStream = stream;
302 if (!acceptStream) {
303 stopMediaStream(stream);
304 capturedStream = null;
305 }
306 return stream;
307 });
308 const pending: PendingTabMediaCapture = {
309 start: () => {
310 try {
311 // Electron invokes this callback through executeJavaScript(..., true), so even automated
312 // and delayed queued starts satisfy getDisplayMedia's transient-activation requirement.
313 resolveCapture(captureTabMediaStream(frameRate));
314 } catch (cause) {
315 rejectCapture(cause);
316 }
317 },
318 };
319 pendingTabMediaCaptures.set(tabId, pending);
320 return {
321 capturePromise,
322 cancel: () => {
323 acceptStream = false;
324 if (capturedStream) {
325 stopMediaStream(capturedStream);
326 capturedStream = null;
327 }
328 if (pendingTabMediaCaptures.get(tabId) === pending) pendingTabMediaCaptures.delete(tabId);
329 void capturePromise.catch(() => undefined);
330 },
331 };
332};
333​
334const triggerTabMediaCapture = (tabId: unknown): boolean => {
335 if (typeof tabId !== "string") return false;
336 const pending = pendingTabMediaCaptures.get(tabId);
337 if (!pending) return false;
338 pendingTabMediaCaptures.delete(tabId);
339 pending.start();
340 return true;
341};
342​
343Object.defineProperty(globalThis, DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER, {
344 configurable: true,
345 value: triggerTabMediaCapture,
346});
347​
348const captureTabMediaStreamWithTimeout = async (
349 tabId: string,
350 capturePromise: Promise<MediaStream>,
351): Promise<MediaStream> => {
352 let acceptStream = true;
353 let timeoutId: number | null = null;
354 const streamPromise = capturePromise.then((stream) => {
355 if (!acceptStream) stopMediaStream(stream);
356 return stream;
357 });
358 try {
359 return await Promise.race([
360 streamPromise,
361 new Promise<never>((_, reject) => {
362 timeoutId = window.setTimeout(
363 () =>
364 reject(
365 new BrowserRecordingCaptureTimeoutError({
366 tabId,
367 timeoutMs: BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
368 }),
369 ),
370 BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
371 );
372 }),
373 ]);
374 } finally {
375 acceptStream = false;
376 if (timeoutId !== null) window.clearTimeout(timeoutId);
377 }
378};
379​
380const clearActiveRecording = (recording: ActiveRecording): void => {
381 recording.compositor?.dispose();
382 recording.compositor = null;
383 recording.releaseSurfaceActivity?.();
384 recording.releaseSurfaceActivity = null;
385 if (activeRecordings.get(recording.tabId) !== recording) return;
386 activeRecordings.delete(recording.tabId);
387 publishActiveRecordingTabIds();
388};
389​
390const waitForBrowserRecordingPaint = async (): Promise<void> => {
391 let firstFrameId: number | null = null;
392 let secondFrameId: number | null = null;
393 let timeoutId: number | null = null;
394 const painted = new Promise<void>((resolve) => {
395 firstFrameId = window.requestAnimationFrame(() => {
396 firstFrameId = null;
397 secondFrameId = window.requestAnimationFrame(() => {
398 secondFrameId = null;
399 resolve();
400 });
401 });
402 });
403 const timedOut = new Promise<void>((resolve) => {
404 timeoutId = window.setTimeout(resolve, BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS);
405 });
406 try {
407 await Promise.race([painted, timedOut]);
408 } finally {
409 if (timeoutId !== null) window.clearTimeout(timeoutId);
410 if (firstFrameId !== null) window.cancelAnimationFrame(firstFrameId);
411 if (secondFrameId !== null) window.cancelAnimationFrame(secondFrameId);
412 }
413};
414​
415const cleanupFailedRecordingStart = async (
416 bridge: NonNullable<typeof previewBridge>,
417 recording: ActiveRecording,
418): Promise<unknown | undefined> => {
419 const errors: unknown[] = [];
420 try {
421 await bridge.recording.stopScreencast(recording.tabId);
422 } catch (error) {
423 errors.push(error);
424 }
425 try {
426 await stopMediaRecorder(recording.recorder);
427 } catch (error) {
428 errors.push(error);
429 }
430 try {
431 stopMediaStream(recording.stream);
432 } catch (error) {
433 errors.push(error);
434 } finally {
435 clearActiveRecording(recording);
436 }
437 if (errors.length === 0) return undefined;
438 if (errors.length === 1) return errors[0];
439 return new AggregateError(
440 errors,
441 `Browser recording startup cleanup failed for tab ${recording.tabId}.`,
442 { cause: errors[0] },
443 );
444};
445​
446const recordingStartupCancelledError = (
447 recording: ActiveRecording,
448 cause: unknown = new Error(`Browser recording startup was cancelled for tab ${recording.tabId}.`),
449): BrowserRecordingOperationError =>
450 new BrowserRecordingOperationError({
451 operation: "start-screencast",
452 tabId: recording.tabId,
453 cause,
454 });
455​
456const isRecordingStarting = (recording: ActiveRecording): boolean =>
457 activeRecordings.get(recording.tabId) === recording && recording.lifecycle.phase === "starting";
458​
459const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Promise<void> => {
460 let timeout: ReturnType<typeof setTimeout> | null = null;
461 try {
462 await Promise.race([
463 recording.startupSettled,
464 new Promise<void>((_, reject) => {
465 timeout = setTimeout(() => {
466 reject(new Error(`Browser recording startup did not settle for tab ${recording.tabId}.`));
467 }, BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);
468 }),
469 ]);
470 } catch (cause) {
471 throw new BrowserRecordingOperationError({
472 operation: "wait-startup",
473 tabId: recording.tabId,
474 cause,
475 });
476 } finally {
477 if (timeout !== null) clearTimeout(timeout);
478 }
479};
480​
481const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperationError =>
482 isBrowserRecordingOperationError(error) && error.operation === "wait-startup";
483​
484export async function startBrowserRecording(
485 tabId: string,
486 threadRef: ScopedThreadRef | null = null,
487 serverTabId = tabId,
488): Promise<string> {
489 const bridge = previewBridge;
490 if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
491 const activeRecording = activeRecordings.get(tabId);
492 if (activeRecording) {
493 if (activeRecording.lifecycle.phase === "recording") {
494 return activeRecording.startedAt;
495 }
496 throw new BrowserRecordingConflictError({
497 requestedTabId: tabId,
498 activeTabId: activeRecording.tabId,
499 });
500 }
501 const activeLogicalRecording =
502 threadRef === null ? null : findActiveBrowserRecordingRuntimeTabId(threadRef, serverTabId);
503 if (activeLogicalRecording !== null) {
504 throw new BrowserRecordingConflictError({
505 requestedTabId: tabId,
506 activeTabId: activeLogicalRecording,
507 });
508 }
509 const startedAt = new Date().toISOString();
510 const chunks: Blob[] = [];
511 let settleStartup: (() => void) | undefined;
512 const startupSettled = new Promise<void>((resolve) => {
513 settleStartup = resolve;
514 });
515 const startingLifecycle = makeStartingBrowserRecordingLifecycle();
516 const releaseSurfaceActivity = acquireBrowserSurfaceActivity(tabId);
517 const recording: ActiveRecording = {
518 tabId,
519 serverTabId,
520 threadRef,
521 chunks,
522 startedAt,
523 startupSettled,
524 releaseSurfaceActivity,
525 stream: null,
526 recorder: null,
527 compositor: null,
528 lifecycle: startingLifecycle,
529 };
530 activeRecordings.set(tabId, recording);
531 publishActiveRecordingTabIds();
532 try {
533 await ensureClientSettingsHydrated().catch((cause: unknown) => {
534 clearActiveRecording(recording);
535 throw cause;
536 });
537 const settings = getClientSettings();
538 const frameRate = settings.browserRecordingFrameRate;
539 await waitForBrowserRecordingPaint();
540 const throwIfStartupCancelled = async (): Promise<void> => {
541 if (activeRecordings.get(tabId) === recording) return;
542 try {
543 await bridge.recording.stopScreencast(tabId);
544 } catch (cause) {
545 throw recordingStartupCancelledError(
546 recording,
547 new AggregateError(
548 [new Error(`Browser recording startup was cancelled for tab ${tabId}.`), cause],
549 `Browser recording startup cancellation failed for tab ${tabId}.`,
550 { cause },
551 ),
552 );
553 }
554 throw recordingStartupCancelledError(recording);
555 };
556 // The desktop process exposes one display-media grant at a time. Keep only the
557 // arm-to-capture handoff exclusive; acquired streams can record concurrently.
558 const grant = queueDisplayMediaGrant(async () => {
559 if (startingLifecycle.cancelledBeforeGrant) {
560 throw new BrowserRecordingStartCancelledError({ tabId });
561 }
562 startingLifecycle.grantStarted = true;
563 await throwIfStartupCancelled();
564 const capture = prepareTabMediaCapture(tabId, frameRate);
565 try {
566 await bridge.recording.startScreencast(tabId);
567 } catch (cause) {
568 capture.cancel();
569 if (!isRecordingStarting(recording)) {
570 throw recordingStartupCancelledError(recording, cause);
571 }
572 clearActiveRecording(recording);
573 throw new BrowserRecordingOperationError({
574 operation: "start-screencast",
575 tabId,
576 cause,
577 });
578 }
579 try {
580 await throwIfStartupCancelled();
581 } catch (cause) {
582 capture.cancel();
583 throw cause;
584 }
585 try {
586 recording.stream = await captureTabMediaStreamWithTimeout(tabId, capture.capturePromise);
587 return recording.stream;
588 } catch (cause) {
589 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
590 if (isBrowserRecordingCaptureTimeoutError(cause) && cleanupCause === undefined) throw cause;
591 throw new BrowserRecordingOperationError({
592 operation: "capture-media-stream",
593 tabId,
594 cause:
595 cleanupCause === undefined
596 ? cause
597 : new AggregateError(
598 [cause, cleanupCause],
599 `Browser media capture and cleanup failed for tab ${tabId}.`,
600 { cause },
601 ),
602 });
603 }
604 });
605 startingLifecycle.setQueuedForGrant(grant.queued);
606 const stream = await Promise.race([
607 grant.result,
608 startingLifecycle.cancelledBeforeGrantSignal.then(() => {
609 throw new BrowserRecordingStartCancelledError({ tabId });
610 }),
611 ]);
612 await throwIfStartupCancelled();
613​
614 let recorder: MediaRecorder;
615 try {
616 recording.compositor = await createRecordingCompositor(
617 stream,
618 {
619 showKeyPresses: settings.browserRecordingShowKeyPresses,
620 showMousePresses: settings.browserRecordingShowMousePresses,
621 frameRate,
622 },
623 (listener) =>
624 bridge.recording.onInput((event) => {
625 if (event.tabId === tabId) listener(event.input);
626 }),
627 );
628 recorder = createMediaRecorder(recording.compositor?.stream ?? stream);
629 recording.recorder = recorder;
630 recorder.addEventListener("dataavailable", (event) => {
631 if (event.data.size > 0) chunks.push(event.data);
632 });
633 } catch (cause) {
634 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
635 throw new BrowserRecordingOperationError({
636 operation: "initialize-media-recorder",
637 tabId,
638 cause:
639 cleanupCause === undefined
640 ? cause
641 : new AggregateError(
642 [cause, cleanupCause],
643 `Browser recording initialization and cleanup failed for tab ${tabId}.`,
644 { cause },
645 ),
646 });
647 }
648 try {
649 recorder.start(1_000);
650 } catch (cause) {
651 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
652 throw new BrowserRecordingOperationError({
653 operation: "start-media-recorder",
654 tabId,
655 cause:
656 cleanupCause === undefined
657 ? cause
658 : new AggregateError(
659 [cause, cleanupCause],
660 `Browser media recorder start and cleanup failed for tab ${tabId}.`,
661 { cause },
662 ),
663 });
664 }
665 if (recording.lifecycle.phase === "starting") {
666 recording.lifecycle = { phase: "recording" };
667 }
668 return startedAt;
669 } finally {
670 settleStartup?.();
671 }
673​
674const finalizeBrowserRecording = async (
675 bridge: NonNullable<typeof previewBridge>,
676 recording: ActiveRecording,
677): Promise<DesktopPreviewRecordingArtifact | null> => {
678 const { tabId } = recording;
679 let result:
680 | {
681 readonly _tag: "Success";
682 readonly artifact: DesktopPreviewRecordingArtifact | null;
683 }
684 | { readonly _tag: "Failure"; readonly error: unknown };
685 try {
686 await waitForRecordingStartupToSettle(recording);
687 try {
688 await bridge.recording.stopScreencast(tabId);
689 } catch (cause) {
690 throw new BrowserRecordingOperationError({
691 operation: "stop-screencast",
692 tabId,
693 cause,
694 });
695 }
696 if (!recording.recorder) {
697 result = { _tag: "Success", artifact: null };
698 } else {
699 try {
700 await stopMediaRecorder(recording.recorder);
701 } catch (cause) {
702 throw new BrowserRecordingOperationError({
703 operation: "stop-media-recorder",
704 tabId,
705 cause,
706 });
707 }
708 recording.compositor?.dispose();
709 recording.compositor = null;
710 stopMediaStream(recording.stream);
711 recording.stream = null;
712 const mimeType =
713 recording.recorder.mimeType ||
714 recording.chunks.find((chunk) => chunk.type.length > 0)?.type;
715 if (!mimeType) {
716 throw new BrowserRecordingFormatUnavailableError({ tabId });
717 }
718 try {
719 const blob = new Blob(recording.chunks, { type: mimeType });
720 const artifact = await bridge.recording.save(
721 tabId,
722 mimeType,
723 new Uint8Array(await blob.arrayBuffer()),
724 );
725 recording.savedBlob = blob;
726 result = { _tag: "Success", artifact };
727 } catch (cause) {
728 throw new BrowserRecordingOperationError({
729 operation: "save-artifact",
730 tabId,
731 cause,
732 });
733 }
734 }
735 } catch (error) {
736 result = { _tag: "Failure", error };
737 }
738​
739 if (result._tag === "Failure" && isStartupWaitTimeout(result.error)) {
740 // Do not clear `active` yet. The renderer-side start promise can still
741 // resolve later, and its cancellation path will call `stopScreencast`.
742 // Keeping the slot reserved prevents a newer recording for this tab from
743 // being started and then accidentally stopped by the older late cleanup.
744 throw result.error;
745 }
746​
747 const cleanupErrors: unknown[] = [];
748 try {
749 await stopMediaRecorder(recording.recorder);
750 } catch (cause) {
751 cleanupErrors.push(cause);
752 }
753 try {
754 stopMediaStream(recording.stream);
755 } catch (cause) {
756 cleanupErrors.push(cause);
757 } finally {
758 clearActiveRecording(recording);
759 }
760 const cleanupError =
761 cleanupErrors.length === 0
762 ? undefined
763 : new BrowserRecordingOperationError({
764 operation: "cleanup",
765 tabId,
766 cause:
767 cleanupErrors.length === 1
768 ? cleanupErrors[0]
769 : new AggregateError(
770 cleanupErrors,
771 `Browser recording media cleanup failed for tab ${tabId}.`,
772 { cause: cleanupErrors[0] },
773 ),
774 });
775​
776 if (result._tag === "Failure") {
777 if (cleanupError) {
778 throw new BrowserRecordingOperationError({
779 operation: "cleanup",
780 tabId,
781 cause: new AggregateError(
782 [result.error, cleanupError],
783 `Browser recording stop and cleanup failed for tab ${tabId}.`,
784 { cause: result.error },
785 ),
786 });
787 }
788 throw result.error;
789 }
790 if (cleanupError) throw cleanupError;
791 return result.artifact;
792};
793​
794const discardBrowserRecording = async (
795 bridge: NonNullable<typeof previewBridge>,
796 recording: ActiveRecording,
797): Promise<null> => {
798 try {
799 await bridge.recording.stopScreencast(recording.tabId).catch(() => undefined);
800 await stopMediaRecorder(recording.recorder).catch(() => undefined);
801 stopMediaStream(recording.stream);
802 return null;
803 } finally {
804 clearActiveRecording(recording);
805 }
806};
807​
808export function stopBrowserRecording(
809 tabId: string,
810): Promise<DesktopPreviewRecordingArtifact | null> {
811 const bridge = previewBridge;
812 const recording = activeRecordings.get(tabId);
813 if (!bridge || !recording) return Promise.resolve(null);
814 if (recording.lifecycle.phase === "stopping") return recording.lifecycle.stopPromise;
815 if (recording.lifecycle.phase === "starting") recording.lifecycle.cancelBeforeGrant();
816​
817 const stopPromise = Promise.resolve()
818 .then(() => finalizeBrowserRecording(bridge, recording))
819 .catch((error) => {
820 if (isStartupWaitTimeout(error) && activeRecordings.get(recording.tabId) === recording) {
821 const cleanupAfterStartup = recording.startupSettled.then(() =>
822 discardBrowserRecording(bridge, recording),
823 );
824 recording.lifecycle = { phase: "stopping", stopPromise: cleanupAfterStartup };
825 void cleanupAfterStartup.catch(() => undefined);
826 }
827 throw error;
828 });
829 recording.lifecycle = { phase: "stopping", stopPromise };
830 return stopPromise;
832​
833export async function stopBrowserRecordingForUpload(
834 tabId: string,
835 upload: (artifact: DesktopPreviewRecordingArtifact, blob: Blob) => Promise<string>,
836): Promise<(DesktopPreviewRecordingArtifact & { uploadedAttachmentId: string }) | null> {
837 const recording = activeRecordings.get(tabId);
838 if (!recording) return null;
839 const artifact = await stopBrowserRecording(tabId);
840 if (!artifact || !recording.savedBlob) return null;
841 recording.uploadPromise ??= upload(artifact, recording.savedBlob);
842 return { ...artifact, uploadedAttachmentId: await recording.uploadPromise };