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 desktop main process routes this request to the tab that `startScreencast` armed, so the
288 // stream already arrives at that tab's native size and needs no source or dimension constraints.
289 navigator.mediaDevices.getDisplayMedia({
290 audio: false,
291 video: { frameRate: { ideal: frameRate, max: frameRate } },
292 });
293
294const stopMediaRecorder = async (recorder: MediaRecorder | null): Promise<void> => {
295 if (!recorder || recorder.state === "inactive") return;
296 const stopped = new Promise<void>((resolve) =>
297 recorder.addEventListener("stop", () => resolve(), { once: true }),
298 );
299 recorder.stop();
300 await stopped;
301};
302
303const stopMediaStream = (stream: MediaStream | null): void => {
304 for (const track of stream?.getTracks() ?? []) track.stop();
305};
306
307interface PendingTabMediaCapture {
308 readonly start: () => void;
309}
310
311const pendingTabMediaCaptures = new Map<string, PendingTabMediaCapture>();
312
313const prepareTabMediaCapture = (tabId: string, frameRate: number) => {
314 let acceptStream = true;
315 let capturedStream: MediaStream | null = null;
316 let resolveCapture!: (stream: MediaStream | PromiseLike<MediaStream>) => void;
317 let rejectCapture!: (cause: unknown) => void;
318 const capturePromise = new Promise<MediaStream>((resolve, reject) => {
319 resolveCapture = resolve;
320 rejectCapture = reject;
321 }).then((stream) => {
322 capturedStream = stream;
323 if (!acceptStream) {
324 stopMediaStream(stream);
325 capturedStream = null;
326 }
327 return stream;
328 });
329 const pending: PendingTabMediaCapture = {
330 start: () => {
331 try {
332 // Electron invokes this callback through executeJavaScript(..., true), so even automated
333 // and delayed queued starts satisfy getDisplayMedia's transient-activation requirement.
334 resolveCapture(captureTabMediaStream(frameRate));
335 } catch (cause) {
336 rejectCapture(cause);
337 }
338 },
339 };
340 pendingTabMediaCaptures.set(tabId, pending);
341 return {
342 capturePromise,
343 cancel: () => {
344 acceptStream = false;
345 if (capturedStream) {
346 stopMediaStream(capturedStream);
347 capturedStream = null;
348 }
349 if (pendingTabMediaCaptures.get(tabId) === pending) pendingTabMediaCaptures.delete(tabId);
350 void capturePromise.catch(() => undefined);
351 },
352 };
353};
354
355const triggerTabMediaCapture = (tabId: unknown): boolean => {
356 if (typeof tabId !== "string") return false;
357 const pending = pendingTabMediaCaptures.get(tabId);
358 if (!pending) return false;
359 pendingTabMediaCaptures.delete(tabId);
360 pending.start();
361 return true;
362};
363
364Object.defineProperty(globalThis, DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER, {
365 configurable: true,
366 value: triggerTabMediaCapture,
367});
368
369const captureTabMediaStreamWithTimeout = async (
370 tabId: string,
371 capturePromise: Promise<MediaStream>,
372): Promise<MediaStream> => {
373 let acceptStream = true;
374 let timeoutId: number | null = null;
375 const streamPromise = capturePromise.then((stream) => {
376 if (!acceptStream) stopMediaStream(stream);
377 return stream;
378 });
379 try {
380 return await Promise.race([
381 streamPromise,
382 new Promise<never>((_, reject) => {
383 timeoutId = window.setTimeout(
384 () =>
385 reject(
386 new BrowserRecordingCaptureTimeoutError({
387 tabId,
388 timeoutMs: BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
389 }),
390 ),
391 BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
392 );
393 }),
394 ]);
395 } finally {
396 acceptStream = false;
397 if (timeoutId !== null) window.clearTimeout(timeoutId);
398 }
399};
400
401const clearActiveRecording = (recording: ActiveRecording): void => {
402 recording.compositor?.dispose();
403 recording.compositor = null;
404 recording.releaseSurfaceActivity?.();
405 recording.releaseSurfaceActivity = null;
406 if (activeRecordings.get(recording.tabId) !== recording) return;
407 activeRecordings.delete(recording.tabId);
408 publishActiveRecordingTabIds();
409};
410
411const waitForBrowserRecordingPaint = async (): Promise<void> => {
412 let firstFrameId: number | null = null;
413 let secondFrameId: number | null = null;
414 let timeoutId: number | null = null;
415 const painted = new Promise<void>((resolve) => {
416 firstFrameId = window.requestAnimationFrame(() => {
417 firstFrameId = null;
418 secondFrameId = window.requestAnimationFrame(() => {
419 secondFrameId = null;
420 resolve();
421 });
422 });
423 });
424 const timedOut = new Promise<void>((resolve) => {
425 timeoutId = window.setTimeout(resolve, BROWSER_RECORDING_PAINT_SETTLE_TIMEOUT_MS);
426 });
427 try {
428 await Promise.race([painted, timedOut]);
429 } finally {
430 if (timeoutId !== null) window.clearTimeout(timeoutId);
431 if (firstFrameId !== null) window.cancelAnimationFrame(firstFrameId);
432 if (secondFrameId !== null) window.cancelAnimationFrame(secondFrameId);
433 }
434};
435
436const cleanupFailedRecordingStart = async (
437 bridge: NonNullable<typeof previewBridge>,
438 recording: ActiveRecording,
439): Promise<unknown | undefined> => {
440 const errors: unknown[] = [];
441 try {
442 await bridge.recording.stopScreencast(recording.tabId);
443 } catch (error) {
444 errors.push(error);
445 }
446 try {
447 await stopMediaRecorder(recording.recorder);
448 } catch (error) {
449 errors.push(error);
450 }
451 try {
452 stopMediaStream(recording.stream);
453 } catch (error) {
454 errors.push(error);
455 } finally {
456 clearActiveRecording(recording);
457 }
458 if (errors.length === 0) return undefined;
459 if (errors.length === 1) return errors[0];
460 return new AggregateError(
461 errors,
462 `Browser recording startup cleanup failed for tab ${recording.tabId}.`,
463 { cause: errors[0] },
464 );
465};
466
467const recordingStartupCancelledError = (
468 recording: ActiveRecording,
469 cause: unknown = new Error(`Browser recording startup was cancelled for tab ${recording.tabId}.`),
470): BrowserRecordingOperationError =>
471 new BrowserRecordingOperationError({
472 operation: "start-screencast",
473 tabId: recording.tabId,
474 cause,
475 });
476
477const isRecordingStarting = (recording: ActiveRecording): boolean =>
478 activeRecordings.get(recording.tabId) === recording && recording.lifecycle.phase === "starting";
479
480const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Promise<void> => {
481 let timeout: ReturnType<typeof setTimeout> | null = null;
482 try {
483 await Promise.race([
484 recording.startupSettled,
485 new Promise<void>((_, reject) => {
486 timeout = setTimeout(() => {
487 reject(new Error(`Browser recording startup did not settle for tab ${recording.tabId}.`));
488 }, BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS);
489 }),
490 ]);
491 } catch (cause) {
492 throw new BrowserRecordingOperationError({
493 operation: "wait-startup",
494 tabId: recording.tabId,
495 cause,
496 });
497 } finally {
498 if (timeout !== null) clearTimeout(timeout);
499 }
500};
501
502const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperationError =>
503 isBrowserRecordingOperationError(error) && error.operation === "wait-startup";
504
505export async function startBrowserRecording(
506 tabId: string,
507 threadRef: ScopedThreadRef | null = null,
508 serverTabId = tabId,
509): Promise<string> {
510 const bridge = previewBridge;
511 if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
512 const activeRecording = activeRecordings.get(tabId);
513 if (activeRecording) {
514 if (activeRecording.lifecycle.phase === "recording") {
515 return activeRecording.startedAt;
516 }
517 throw new BrowserRecordingConflictError({
518 requestedTabId: tabId,
519 activeTabId: activeRecording.tabId,
520 });
521 }
522 const activeLogicalRecording =
523 threadRef === null ? null : findActiveBrowserRecordingRuntimeTabId(threadRef, serverTabId);
524 if (activeLogicalRecording !== null) {
525 throw new BrowserRecordingConflictError({
526 requestedTabId: tabId,
527 activeTabId: activeLogicalRecording,
528 });
529 }
530 const startedAt = new Date().toISOString();
531 const chunks: Blob[] = [];
532 let settleStartup: (() => void) | undefined;
533 const startupSettled = new Promise<void>((resolve) => {
534 settleStartup = resolve;
535 });
536 const startingLifecycle = makeStartingBrowserRecordingLifecycle();
537 const releaseSurfaceActivity = acquireBrowserSurfaceActivity(tabId);
538 const recording: ActiveRecording = {
539 tabId,
540 serverTabId,
541 threadRef,
542 chunks,
543 startedAt,
544 startupSettled,
545 releaseSurfaceActivity,
546 stream: null,
547 recorder: null,
548 compositor: null,
549 lifecycle: startingLifecycle,
550 };
551 activeRecordings.set(tabId, recording);
552 publishActiveRecordingTabIds();
553 try {
554 await ensureClientSettingsHydrated().catch((cause: unknown) => {
555 clearActiveRecording(recording);
556 throw cause;
557 });
558 const settings = getClientSettings();
559 const frameRate = settings.browserRecordingFrameRate;
560 await waitForBrowserRecordingPaint();
561 const throwIfStartupCancelled = async (): Promise<void> => {
562 if (activeRecordings.get(tabId) === recording) return;
563 try {
564 await bridge.recording.stopScreencast(tabId);
565 } catch (cause) {
566 throw recordingStartupCancelledError(
567 recording,
568 new AggregateError(
569 [new Error(`Browser recording startup was cancelled for tab ${tabId}.`), cause],
570 `Browser recording startup cancellation failed for tab ${tabId}.`,
571 { cause },
572 ),
573 );
574 }
575 throw recordingStartupCancelledError(recording);
576 };
577 // The desktop process exposes one display-media grant at a time. Keep only the
578 // arm-to-capture handoff exclusive; acquired streams can record concurrently.
579 const grant = queueDisplayMediaGrant(async () => {
580 if (startingLifecycle.cancelledBeforeGrant) {
581 throw new BrowserRecordingStartCancelledError({ tabId });
582 }
583 startingLifecycle.grantStarted = true;
584 await throwIfStartupCancelled();
585 const capture = prepareTabMediaCapture(tabId, frameRate);
586 try {
587 await bridge.recording.startScreencast(tabId);
588 } catch (cause) {
589 capture.cancel();
590 if (!isRecordingStarting(recording)) {
591 throw recordingStartupCancelledError(recording, cause);
592 }
593 clearActiveRecording(recording);
594 throw new BrowserRecordingOperationError({
595 operation: "start-screencast",
596 tabId,
597 cause,
598 });
599 }
600 try {
601 await throwIfStartupCancelled();
602 } catch (cause) {
603 capture.cancel();
604 throw cause;
605 }
606 try {
607 recording.stream = await captureTabMediaStreamWithTimeout(tabId, capture.capturePromise);
608 return recording.stream;
609 } catch (cause) {
610 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
611 if (isBrowserRecordingCaptureTimeoutError(cause) && cleanupCause === undefined) throw cause;
612 throw new BrowserRecordingOperationError({
613 operation: "capture-media-stream",
614 tabId,
615 cause:
616 cleanupCause === undefined
617 ? cause
618 : new AggregateError(
619 [cause, cleanupCause],
620 `Browser media capture and cleanup failed for tab ${tabId}.`,
621 { cause },
622 ),
623 });
624 }
625 });
626 startingLifecycle.setQueuedForGrant(grant.queued);
627 const stream = await Promise.race([
628 grant.result,
629 startingLifecycle.cancelledBeforeGrantSignal.then(() => {
630 throw new BrowserRecordingStartCancelledError({ tabId });
631 }),
632 ]);
633 await throwIfStartupCancelled();
634
635 let recorder: MediaRecorder;
636 try {
637 recording.compositor = await createRecordingCompositor(
638 stream,
639 {
640 showKeyPresses: settings.browserRecordingShowKeyPresses,
641 showMousePresses: settings.browserRecordingShowMousePresses,
642 frameRate,
643 },
644 (listener) =>
645 bridge.recording.onInput((event) => {
646 if (event.tabId === tabId) listener(event.input);
647 }),
648 );
649 recorder = createMediaRecorder(recording.compositor?.stream ?? stream);
650 recording.recorder = recorder;
651 recorder.addEventListener("dataavailable", (event) => {
652 if (event.data.size > 0) chunks.push(event.data);
653 });
654 } catch (cause) {
655 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
656 throw new BrowserRecordingOperationError({
657 operation: "initialize-media-recorder",
658 tabId,
659 cause:
660 cleanupCause === undefined
661 ? cause
662 : new AggregateError(
663 [cause, cleanupCause],
664 `Browser recording initialization and cleanup failed for tab ${tabId}.`,
665 { cause },
666 ),
667 });
668 }
669 try {
670 recorder.start(1_000);
671 } catch (cause) {
672 const cleanupCause = await cleanupFailedRecordingStart(bridge, recording);
673 throw new BrowserRecordingOperationError({
674 operation: "start-media-recorder",
675 tabId,
676 cause:
677 cleanupCause === undefined
678 ? cause
679 : new AggregateError(
680 [cause, cleanupCause],
681 `Browser media recorder start and cleanup failed for tab ${tabId}.`,
682 { cause },
683 ),
684 });
685 }
686 if (recording.lifecycle.phase === "starting") {
687 recording.lifecycle = { phase: "recording" };
688 }
689 return startedAt;
690 } finally {
691 settleStartup?.();
692 }
693}
694
695const finalizeBrowserRecording = async (
696 bridge: NonNullable<typeof previewBridge>,
697 recording: ActiveRecording,
698): Promise<DesktopPreviewRecordingArtifact | null> => {
699 const { tabId } = recording;
700 let result:
701 | {
702 readonly _tag: "Success";
703 readonly artifact: DesktopPreviewRecordingArtifact | null;
704 }
705 | { readonly _tag: "Failure"; readonly error: unknown };
706 try {
707 await waitForRecordingStartupToSettle(recording);
708 try {
709 await bridge.recording.stopScreencast(tabId);
710 } catch (cause) {
711 throw new BrowserRecordingOperationError({
712 operation: "stop-screencast",
713 tabId,
714 cause,
715 });
716 }
717 if (!recording.recorder) {
718 result = { _tag: "Success", artifact: null };
719 } else {
720 try {
721 await stopMediaRecorder(recording.recorder);
722 } catch (cause) {
723 throw new BrowserRecordingOperationError({
724 operation: "stop-media-recorder",
725 tabId,
726 cause,
727 });
728 }
729 recording.compositor?.dispose();
730 recording.compositor = null;
731 stopMediaStream(recording.stream);
732 recording.stream = null;
733 const mimeType =
734 recording.recorder.mimeType ||
735 recording.chunks.find((chunk) => chunk.type.length > 0)?.type;
736 if (!mimeType) {
737 throw new BrowserRecordingFormatUnavailableError({ tabId });
738 }
739 try {
740 const blob = new Blob(recording.chunks, { type: mimeType });
741 const artifact = await bridge.recording.save(
742 tabId,
743 mimeType,
744 new Uint8Array(await blob.arrayBuffer()),
745 );
746 recording.savedBlob = blob;
747 result = { _tag: "Success", artifact };
748 } catch (cause) {
749 throw new BrowserRecordingOperationError({
750 operation: "save-artifact",
751 tabId,
752 cause,
753 });
754 }
755 }
756 } catch (error) {
757 result = { _tag: "Failure", error };
758 }
759
760 if (result._tag === "Failure" && isStartupWaitTimeout(result.error)) {
761 // Do not clear `active` yet. The renderer-side start promise can still
762 // resolve later, and its cancellation path will call `stopScreencast`.
763 // Keeping the slot reserved prevents a newer recording for this tab from
764 // being started and then accidentally stopped by the older late cleanup.
765 throw result.error;
766 }
767
768 const cleanupErrors: unknown[] = [];
769 try {
770 await stopMediaRecorder(recording.recorder);
771 } catch (cause) {
772 cleanupErrors.push(cause);
773 }
774 try {
775 stopMediaStream(recording.stream);
776 } catch (cause) {
777 cleanupErrors.push(cause);
778 } finally {
779 clearActiveRecording(recording);
780 }
781 const cleanupError =
782 cleanupErrors.length === 0
783 ? undefined
784 : new BrowserRecordingOperationError({
785 operation: "cleanup",
786 tabId,
787 cause:
788 cleanupErrors.length === 1
789 ? cleanupErrors[0]
790 : new AggregateError(
791 cleanupErrors,
792 `Browser recording media cleanup failed for tab ${tabId}.`,
793 { cause: cleanupErrors[0] },
794 ),
795 });
796
797 if (result._tag === "Failure") {
798 if (cleanupError) {
799 throw new BrowserRecordingOperationError({
800 operation: "cleanup",
801 tabId,
802 cause: new AggregateError(
803 [result.error, cleanupError],
804 `Browser recording stop and cleanup failed for tab ${tabId}.`,
805 { cause: result.error },
806 ),
807 });
808 }
809 throw result.error;
810 }
811 if (cleanupError) throw cleanupError;
812 return result.artifact;
813};
814
815const discardBrowserRecording = async (
816 bridge: NonNullable<typeof previewBridge>,
817 recording: ActiveRecording,
818): Promise<null> => {
819 try {
820 await bridge.recording.stopScreencast(recording.tabId).catch(() => undefined);
821 await stopMediaRecorder(recording.recorder).catch(() => undefined);
822 stopMediaStream(recording.stream);
823 return null;
824 } finally {
825 clearActiveRecording(recording);
826 }
827};
828
829export function stopBrowserRecording(
830 tabId: string,
831): Promise<DesktopPreviewRecordingArtifact | null> {
832 const bridge = previewBridge;
833 const recording = activeRecordings.get(tabId);
834 if (!bridge || !recording) return Promise.resolve(null);
835 if (recording.lifecycle.phase === "stopping") return recording.lifecycle.stopPromise;
836 if (recording.lifecycle.phase === "starting") recording.lifecycle.cancelBeforeGrant();
837
838 const stopPromise = Promise.resolve()
839 .then(() => finalizeBrowserRecording(bridge, recording))
840 .catch((error) => {
841 if (isStartupWaitTimeout(error) && activeRecordings.get(recording.tabId) === recording) {
842 const cleanupAfterStartup = recording.startupSettled.then(() =>
843 discardBrowserRecording(bridge, recording),
844 );
845 recording.lifecycle = { phase: "stopping", stopPromise: cleanupAfterStartup };
846 void cleanupAfterStartup.catch(() => undefined);
847 }
848 throw error;
849 });
850 recording.lifecycle = { phase: "stopping", stopPromise };
851 return stopPromise;
852}
853
854export async function stopBrowserRecordingForUpload(
855 tabId: string,
856 upload: (artifact: DesktopPreviewRecordingArtifact, blob: Blob) => Promise<string>,
857): Promise<(DesktopPreviewRecordingArtifact & { uploadedAttachmentId: string }) | null> {
858 const recording = activeRecordings.get(tabId);
859 if (!recording) return null;
860 const artifact = await stopBrowserRecording(tabId);
861 if (!artifact || !recording.savedBlob) return null;
862 recording.uploadPromise ??= upload(artifact, recording.savedBlob);
863 return { ...artifact, uploadedAttachmentId: await recording.uploadPromise };
864}