@@ -80,6 +80,8 @@ export class BrowserRecordingOperationError extends Schema.TaggedErrorClass<Brow
8080 }
8181}
8282
83+ const isBrowserRecordingOperationError = Schema . is ( BrowserRecordingOperationError ) ;
84+
8385type BrowserRecordingLifecycle =
8486 | { readonly phase : "starting" }
8587 | { readonly phase : "recording" }
@@ -190,6 +192,9 @@ const waitForRecordingStartupToSettle = async (recording: ActiveRecording): Prom
190192 }
191193} ;
192194
195+ const isStartupWaitTimeout = ( error : unknown ) : error is BrowserRecordingOperationError =>
196+ isBrowserRecordingOperationError ( error ) && error . operation === "wait-startup" ;
197+
193198export async function startBrowserRecording ( tabId : string ) : Promise < string > {
194199 const bridge = previewBridge ;
195200 if ( ! bridge ) throw new BrowserRecordingUnavailableError ( { tabId } ) ;
@@ -373,6 +378,14 @@ const finalizeBrowserRecording = async (
373378 result = { _tag : "Failure" , error } ;
374379 }
375380
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+
376389 let cleanupError : BrowserRecordingOperationError | undefined ;
377390 try {
378391 await stopMediaRecorder ( recording . recorder ) ;
@@ -412,7 +425,18 @@ export function stopBrowserRecording(
412425 if ( ! bridge || ! recording || recording . tabId !== tabId ) return Promise . resolve ( null ) ;
413426 if ( recording . lifecycle . phase === "stopping" ) return recording . lifecycle . stopPromise ;
414427
415- const stopPromise = Promise . resolve ( ) . then ( ( ) => finalizeBrowserRecording ( bridge , recording ) ) ;
428+ const stopPromise = Promise . resolve ( )
429+ . then ( ( ) => finalizeBrowserRecording ( bridge , recording ) )
430+ . catch ( ( error ) => {
431+ if ( isStartupWaitTimeout ( error ) && active === recording ) {
432+ const cleanupAfterStartup = recording . startupSettled . then ( ( ) =>
433+ finalizeBrowserRecording ( bridge , recording ) ,
434+ ) ;
435+ recording . lifecycle = { phase : "stopping" , stopPromise : cleanupAfterStartup } ;
436+ void cleanupAfterStartup . catch ( ( ) => undefined ) ;
437+ }
438+ throw error ;
439+ } ) ;
416440 recording . lifecycle = { phase : "stopping" , stopPromise } ;
417441 return stopPromise ;
418442}
0 commit comments