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