fix(preview): stabilize background browser automation #8981
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/browser/ElectronBrowserHost.tsx line 90OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -39,0 +70,21 @@70+ document.querySelectorAll<HTMLElement & { getWebContentsId: () => number }>(71+ "webview[data-preview-tab]",72+ ),73+ ).find((candidate) => candidate.getAttribute("data-preview-tab") === runtimeTabId);74+ if (!webview) {75+ removeRetired(runtimeTabId);76+ return;77+ }78+ if (!preview.prepareWebviewRemoval) {79+ removeRetired(runtimeTabId);80+ return;81+ }82+ let webContentsId: number;83+ try {84+ webContentsId = webview.getWebContentsId();85+ } catch {86+ removeRetired(runtimeTabId);87+ return;88+ }89+ retirementTimersRef.current.set(runtimeTabId, null);90+ void preview.prepareWebviewRemoval(runtimeTabId, webContentsId).then(apps/desktop/src/app/DesktopLifecycle.ts line 96Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -84,7 +84,12 @@8484 const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(8585 function* (8686 afterBoundsFlush: Effect.Effect<void> = Effect.void,87- ): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow> {87+ ): Effect.fn.Return<88+ void,89+ DesktopWindow.DesktopWindowError,90+ DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow91+ > {8892 const shutdown = yield* DesktopShutdown.DesktopShutdown;8993 const desktopWindow = yield* DesktopWindow.DesktopWindow;9094 yield* desktopWindow.flushMainWindowBounds;95+ yield* desktopWindow.preparePreviewTeardown;@@ -1049,5 +1080,18 @@1080+ replaceMap(diagnostics, (copy) => {1081+ copy.delete(webContentsId);1082+ }),1083+ );10491084 return;10501085 }1051- yield* Ref.update(diagnosticsRef, (diagnostics) =>1052- replaceMap(diagnostics, (copy) => {1053- copy.delete(webContentsId);1086+ yield* control.lifecycleSemaphore.withPermit(1087+ Effect.gen(function* () {1088+ if (control.phase === "detached") return;1089+ control.phase = "quiescing";1090+ const wc = webContents.fromId(webContentsId);1091+ yield* Scope.close(control.scope, Exit.void).pipe(Effect.ignore);1092+ const pending = Array.from(control.inFlightCommands);1093+ if (pending.length > 0) {1094+ const drained = yield* Effect.promise(() => Promise.allSettled(pending)).pipe(1095+ Effect.timeoutOption(PREVIEW_DEBUGGER_DRAIN_TIMEOUT_MS),1096+ );1097+ if (Option.isNone(drained)) {
- apps/web/src/components/preview/previewAutomationErrors.ts lines 249 to 299OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -220,0 +279,21 @@279+ };280+ }281+ const flattenedOwnedTimeout = message.match(282+ /\b(Preview [^\n]{0,160}? timed out during ([a-z][a-z0-9-]*) after \d+ms[^\n]*)/,283+ );284+ if (flattenedOwnedTimeout?.[1] && flattenedOwnedTimeout[2]) {285+ return {286+ name: "PreviewAutomationTimeoutError",287+ message: flattenedOwnedTimeout[1].slice(0, MAX_SAFE_ERROR_MESSAGE_LENGTH),288+ stage: flattenedOwnedTimeout[2],289+ };290+ }291+ const tag = typeof record["_tag"] === "string" ? record["_tag"] : "";292+ if (tag.endsWith("TimeoutError") && message.length > 0) {293+ return {294+ name: tag,295+ message: message.slice(0, MAX_SAFE_ERROR_MESSAGE_LENGTH),296+ ...(stage === undefined ? {} : { stage }),297+ };298+ }299+ return null;apps/desktop/src/preview/Manager.ts lines 4348 to 4362OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4003,10 +4345,18 @@40034345 return error.cause instanceof Error ? error.cause.message : String(error.cause);40044346 }400543474348+ private safeCauseMessage(): string | null {4349+ if (!(this.cause instanceof Error)) return null;4350+ if (this.cause.name !== "AbortError" && this.cause.name !== "UnknownVizError") return null;4351+ return `${this.cause.name}: ${this.cause.message.slice(0, 512)}`;4352+ }4353+40064354 override get message(): string {40074355 const context = [40084356 this.tabId === undefined ? undefined : `tab ${this.tabId}`,40094357 this.webContentsId === undefined ? undefined : `WebContents ${this.webContentsId}`,40104358 this.artifactPath === undefined ? undefined : `artifact ${this.artifactPath}`,40114359 ].filter((value): value is string => value !== undefined);4012- return `Desktop preview operation failed: ${this.operation}${context.length === 0 ? "" : ` (${context.join(", ")})`}`;4360+ const base = `Desktop preview operation failed: ${this.operation}${context.length === 0 ? "" : ` (${context.join(", ")})`}`;4361+ const safeCause = this.safeCauseMessage();4362+ return safeCause ? `${base}: ${safeCause}` : base;
- apps/desktop/src/preview/Manager.ts line 1811OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1889,3 +2042,4 @@1889204218902043 const closeTabUnlocked = Effect.fn("PreviewManager.closeTabUnlocked")(function* (tabId: string) {18912044 if (!(yield* SynchronizedRef.get(tabsRef)).has(tabId)) return;2045+ clearPendingRecording(tabId);apps/desktop/src/app/DesktopLifecycle.ts line 161Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -139,0 +136,21 @@136+ );137+ void quit.then(138+ () => {139+ markQuitAllowed();140+ void runEffect(141+ Effect.gen(function* () {142+ const electronApp = yield* ElectronApp.ElectronApp;143+ yield* electronApp.quit;144+ }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),145+ );146+ },147+ (error) => {148+ void runEffect(149+ Effect.gen(function* () {150+ const state = yield* DesktopState.DesktopState;151+ yield* Ref.set(state.quitting, false);152+ yield* logLifecycleError("preview teardown blocked desktop shutdown", { error });153+ }).pipe(Effect.withSpan("desktop.lifecycle.quitBlocked")),154+ );155+ },156+ );apps/desktop/src/preview/Manager.ts line 3573OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3320,0 +3553,21 @@3553+ };3554+ });3555+3556+ const recoverCaptureSurface = Effect.fn("PreviewManager.recoverCaptureSurface")(function* (3557+ tabId: string,3558+ wc: Electron.WebContents,3559+ ) {3560+ yield* withTabLifecycleLock(3561+ tabId,3562+ Effect.gen(function* () {3563+ const current = (yield* SynchronizedRef.get(tabsRef)).get(tabId);3564+ if (current?.webContentsId !== wc.id) return;3565+ clearPendingRecording(tabId);3566+ yield* Effect.all(3567+ [detachControlSession(wc.id), detachListeners(wc.id), cancelPickElement(tabId)],3568+ { concurrency: 3, discard: true },3569+ );3570+ const afterDetach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);3571+ if (afterDetach?.webContentsId !== wc.id) return;3572+ yield* update(tabId, { webContentsId: null });3573+ yield* emitCaptureRecovery({ tabId, webContentsId: wc.id });apps/web/src/components/preview/PreviewAutomationHosts.tsx line 633OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -630,4 +663,3 @@630663 }631664 case "waitFor": {632665 const ready = await requireReadyTab();633- return await ready.bridge.automation.waitFor(
- @@ -187,18 +183,5 @@187-const captureTabMediaStream = (188- source: DesktopPreviewRecordingSource,189- frameRate: number,190-): Promise<MediaStream> =>191- navigator.mediaDevices.getUserMedia({183+const captureTabMediaStream = (frameRate: number): Promise<MediaStream> =>184+ navigator.mediaDevices.getDisplayMedia({192185 audio: false,193- video: {194- mandatory: {195- chromeMediaSource: "tab",196- chromeMediaSourceId: source.sourceId,197- minWidth: source.width,198- maxWidth: source.width,199- minHeight: source.height,200- maxHeight: source.height,201- maxFrameRate: frameRate,202- },203- } as unknown as MediaTrackConstraints,186+ video: { frameRate: { max: frameRate } },204187 });apps/web/src/browser/HostedBrowserWebview.tsx lines 271 to 284OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -246,3 +268,17 @@246268 hiddenSize,247269 });248270271+ useEffect(() => {272+ setCompositingReady(false);273+ if (!renderingActive) return;274+ let secondFrameId: number | null = null;275+ const firstFrameId = window.requestAnimationFrame(() => {276+ secondFrameId = window.requestAnimationFrame(() => {277+ secondFrameId = null;278+ setCompositingReady(true);279+ });280+ });281+ return () => {282+ window.cancelAnimationFrame(firstFrameId);283+ if (secondFrameId !== null) window.cancelAnimationFrame(secondFrameId);284+ };
- apps/desktop/src/preview/Manager.ts line 3673OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3345,6 +3655,19 @@3655+ const currentAfterCapture = yield* requireWebContents(tabId);3656+ if (currentAfterCapture !== wc) {3657+ return yield* new PreviewWebContentsNotFoundError({ tabId, webContentsId: wc.id });3658+ }3659+ const sourceImage = sourceImageOption.value;3660+ const sourceSize = sourceImage.getSize();3661+ const image =3662+ sourceSize.width > MAX_SCREENSHOT_WIDTH3663+ ? sourceImage.resize({ width: MAX_SCREENSHOT_WIDTH })3664+ : sourceImage;3665+ const size = image.getSize();3666+ return {33453667 mimeType: "image/png" as const,33463668 data: image.toPNG().toString("base64"),33473669 width: size.width,33483670 height: size.height,3349- },3350- };3671+ };3672+ }).pipe(3673+ Effect.ensuring(
- apps/web/src/browser/ElectronBrowserHost.tsx line 110OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -39,0 +90,21 @@90+ void preview.prepareWebviewRemoval(runtimeTabId, webContentsId).then(91+ () => {92+ if (!currentSessionIdsRef.current.has(runtimeTabId)) {93+ removeRetired(runtimeTabId);94+ return;95+ }96+ const restore = () => {97+ if (!currentSessionIdsRef.current.has(runtimeTabId)) {98+ removeRetired(runtimeTabId);99+ return;100+ }101+ retirementTimersRef.current.set(runtimeTabId, null);102+ void preview.registerWebview(runtimeTabId, webContentsId).then(103+ () => removeRetired(runtimeTabId),104+ () => {105+ const timerId = window.setTimeout(restore, 250);106+ retirementTimersRef.current.set(runtimeTabId, timerId);107+ },108+ );109+ };110+ restore();
- @@ -248,0 +272,21 @@272+ setCompositingReady(false);273+ if (!renderingActive) return;274+ let secondFrameId: number | null = null;275+ let fallbackId: number | null = window.setTimeout(() => {276+ fallbackId = null;277+ setCompositingReady(true);278+ }, 250);279+ const firstFrameId = window.requestAnimationFrame(() => {280+ secondFrameId = window.requestAnimationFrame(() => {281+ secondFrameId = null;282+ if (fallbackId !== null) window.clearTimeout(fallbackId);283+ fallbackId = null;284+ setCompositingReady(true);285+ });286+ });287+ return () => {288+ if (fallbackId !== null) window.clearTimeout(fallbackId);289+ window.cancelAnimationFrame(firstFrameId);290+ if (secondFrameId !== null) window.cancelAnimationFrame(secondFrameId);291+ };292+ }, [@@ -3101,0 +3338,21 @@3338+3339+ const installDisplayMediaRequestHandler = Effect.fn(3340+ "PreviewManager.installDisplayMediaRequestHandler",3341+ )(function* (tabId: string, wc: Electron.WebContents, session: Session) {3342+ if (displayMediaHandlerSessions.has(session)) return;3343+ yield* attempt(3344+ {3345+ operation: "recording.installDisplayMediaRequestHandler",3346+ tabId,3347+ webContentsId: wc.id,3348+ },3349+ () =>3350+ session.setDisplayMediaRequestHandler((_request, callback) => {3351+ const target = pendingRecording?.webContents;3352+ pendingRecording = null;3353+ if (!target || target.isDestroyed()) {3354+ callback({});3355+ return;3356+ }3357+ callback({ video: target.mainFrame });3358+ }),
- @@ -2117,4 +2272,6 @@21172272 const expectedGeneration = tabLifecycleGenerations.get(tabId);21182273 return yield* withTabLifecycleLock(21192274 tabId,2120- registerWebviewUnlocked(tabId, webContentsId, expectedGeneration),2275+ Effect.gen(function* () {2276+ webviewRegistrationEpochs.set(tabId, (webviewRegistrationEpochs.get(tabId) ?? 0) + 1);2277+ yield* registerWebviewUnlocked(tabId, webContentsId, expectedGeneration);
- apps/web/src/browser/HostedBrowserWebview.tsx line 405OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -247,0 +385,21 @@385+ webpreferences={config.webPreferences}386+ {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}387+ data-preview-tab={runtimeTabId}388+ data-preview-server-tab={tabId}389+ data-preview-viewport-mode={effectiveViewport._tag}390+ data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}391+ data-preview-css-width={392+ fittedSourceViewport393+ ? fittedSourceViewport.width394+ : effectiveViewport._tag === "fill"395+ ? Math.max(1, Math.round(layout.viewportWidth / normalizedZoomFactor))396+ : effectiveViewport.width397+ }398+ data-preview-css-height={399+ fittedSourceViewport400+ ? fittedSourceViewport.height401+ : effectiveViewport._tag === "fill"402+ ? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))403+ : effectiveViewport.height404+ }405+ data-preview-capture-retired={retired ? "true" : undefined}@@ -3348,12 +3707,17 @@33483707 height: size.height,3349- },3350- };3708+ };3709+ }).pipe(3710+ Effect.ensuring(3711+ Effect.sync(() => {3712+ if (!nativeCaptureStarted) settle();3713+ }),3714+ ),3715+ );33513716 },33523717 );3353371833543719 const automationSnapshot = Effect.fn("PreviewManager.automationSnapshot")(function* (33553720 tabId: string,33563721 ) {33573722 const wc = yield* requireWebContents(tabId);3358- return yield* withControlSession(tabId, wc, "snapshot", (send) =>3359- captureAutomationSnapshot(tabId, wc, send),3723+ const snapshot = yield* withControlSession(tabId, wc, "snapshot", (send) =>
- @@ -3345,9 +3700,19 @@3700+ ? sourceImage.resize({ width: MAX_SCREENSHOT_WIDTH })3701+ : sourceImage;3702+ const size = image.getSize();3703+ return {33453704 mimeType: "image/png" as const,33463705 data: image.toPNG().toString("base64"),33473706 width: size.width,33483707 height: size.height,3349- },3350- };3708+ };3709+ }).pipe(3710+ Effect.ensuring(3711+ Effect.sync(() => {3712+ if (!nativeCaptureStarted) settle();3713+ }),3714+ ),3715+ );33513716 },33523717 );33533718@@ -295,18 +445,3 @@295- : effectiveViewport._tag === "fill"296- ? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))297- : effectiveViewport.height298- }299- aria-hidden={active ? undefined : true}300- className={cn(301- "absolute flex overflow-hidden bg-background",302- active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",303- )}304- style={{305- left: layout.viewportX,306- top: layout.viewportY,307- width: layout.viewportWidth / layout.viewportScale,308- height: layout.viewportHeight / layout.viewportScale,309- transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,310- transformOrigin: "top left",311- }}312- />445+ {retiredCaptureWebviews.map((retired) =>446+ renderWebview(retired.generation, retired.src, true),447+ )}
- @@ -595,2 +596,20 @@595- window.on("close", () => {596+ let closePrepared = false;597+ let closePreparationRunning = false;598+ window.on("close", (event) => {596599 runFork(flushBoundsPersist);600+ if (closePrepared || closePreparationRunning) {601+ if (!closePrepared) event.preventDefault();602+ return;603+ }604+ event.preventDefault();605+ closePreparationRunning = true;606+ void runPromise(previewManager.prepareForWindowTeardown).then(607+ () => {608+ closePrepared = true;609+ if (!window.isDestroyed()) window.close();610+ },611+ (error) => {612+ closePreparationRunning = false;613+ void runPromise(614+ logWindowWarning("preview teardown blocked main window close", {615+ message: error instanceof Error ? error.message : String(error),apps/desktop/src/ipc/methods/preview.ts lines 96 to 98OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -35,0 +78,21 @@78+ words.every((word) => SAFE_NATIVE_CAPTURE_MESSAGE_WORDS.has(word))79+ ? bounded80+ : "Preview capture failed.";81+};82+83+const snapshotFailure = (84+ error: PreviewManager.PreviewManagerError,85+): DesktopPreviewAutomationFailure => {86+ if (87+ PreviewManager.isPreviewOperationError(error) &&88+ error.cause instanceof Error &&89+ SAFE_NATIVE_CAPTURE_ERROR_NAMES.has(error.cause.name)90+ ) {91+ return {92+ name: error.cause.name,93+ message: safeNativeCaptureMessage(error.cause.message),94+ };95+ }96+ const record = error as unknown as Record<string, unknown>;97+ const name = typeof record["_tag"] === "string" ? record["_tag"] : "PreviewAutomationError";98+ const stage = typeof record["stage"] === "string" ? record["stage"] : undefined;apps/desktop/src/app/DesktopLifecycle.ts lines 147 to 152OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -136,4 +136,17 @@136- yield* electronApp.quit;137- }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),138- );139- });136+ );137+ void quit.then(138+ () => {139+ markQuitAllowed();140+ void runEffect(141+ Effect.gen(function* () {142+ const electronApp = yield* ElectronApp.ElectronApp;143+ yield* electronApp.quit;144+ }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),145+ );146+ },147+ (error) => {148+ void runEffect(149+ Effect.gen(function* () {150+ const state = yield* DesktopState.DesktopState;151+ yield* Ref.set(state.quitting, false);152+ yield* logLifecycleError("preview teardown blocked desktop shutdown", { error });
- apps/web/src/components/preview/PreviewAutomationHosts.tsx lines 149 to 150OutdatedResolvedby maria-rcks@@ -129,3 +146,5 @@129146 return wrapper?.getAttribute("data-preview-rendering") === "active";130147 };131148149+const isPreviewWebviewCompositing = (runtimeTabId: string): boolean => {150+ const wrapper = findPreviewWebview(runtimeTabId)?.closest<HTMLElement>("[data-preview-viewport]");@@ -39,0 +53,21 @@53+ useEffect(() => {54+ const preview = window.desktopBridge?.preview;55+ if (!preview) return;56+ const removeRetired = (runtimeTabId: string) => {57+ retirementTimersRef.current.delete(runtimeTabId);58+ setRetainedSessions((current) =>59+ currentSessionIdsRef.current.has(runtimeTabId)60+ ? current61+ : current.filter((session) => session.runtimeTabId !== runtimeTabId),62+ );63+ };64+ const prepareRemoval = (runtimeTabId: string) => {65+ if (currentSessionIdsRef.current.has(runtimeTabId)) {66+ retirementTimersRef.current.delete(runtimeTabId);67+ return;68+ }69+ const webview = Array.from(70+ document.querySelectorAll<HTMLElement & { getWebContentsId: () => number }>(71+ "webview[data-preview-tab]",72+ ),73+ ).find((candidate) => candidate.getAttribute("data-preview-tab") === runtimeTabId);apps/web/src/browser/HostedBrowserWebview.tsx lines 445 to 452OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -300,13 +445,8 @@300- className={cn(301- "absolute flex overflow-hidden bg-background",302- active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",303- )}304- style={{305- left: layout.viewportX,306- top: layout.viewportY,307- width: layout.viewportWidth / layout.viewportScale,308- height: layout.viewportHeight / layout.viewportScale,309- transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,310- transformOrigin: "top left",311- }}312- />445+ {retiredCaptureWebviews.map((retired) =>446+ renderWebview(retired.generation, retired.src, true),447+ )}448+ {renderWebview(449+ webviewGeneration,450+ webviewGeneration === 0 ? initialSrc : recoverySrc,451+ false,452+ )}
- @@ -3895,6 +4278,21 @@38954278 Ref.set(recordingFrameListenersRef, new Set()),4279+ Ref.set(captureRecoveryListenersRef, new Set()),38964280 ],38974281 { discard: true },38984282 );38994283 });390042844285+ const prepareForWindowTeardown = Effect.gen(function* () {4286+ pendingRecording = null;4287+ frameCaptureWindowOpen = false;4288+ yield* Effect.all([closeAllPictureInPicture(), stopAllRecordings()], {4289+ concurrency: 2,4290+ discard: true,4291+ });4292+ yield* waitForAutomationCaptures();4293+ const controls = yield* SynchronizedRef.get(controlSessionsRef);4294+ yield* Effect.forEach(controls.keys(), detachControlSession, {4295+ concurrency: "unbounded",4296+ discard: true,4297+ });4298+ }).pipe(Effect.withSpan("PreviewManager.prepareForWindowTeardown"));
- @@ -179,7 +214,8 @@179214 });180215 yield* electronApp.exit(0);181216 }).pipe(182- Effect.catchCause((cause) => {183- const error = new DesktopLifecycleRelaunchError({ reason, cause });184- return logLifecycleError(error.message, { error });185- }),217+ Effect.catchCause((cause) =>218+ Effect.gen(function* () {219+ yield* Ref.set(state.quitting, false);220+ const error = new DesktopLifecycleRelaunchError({ reason, cause });221+ yield* logLifecycleError(error.message, { error });
- @@ -596,0 +628,21 @@628+ }629+ event.preventDefault();630+ closePreparationRunning = true;631+ void runPromise(632+ previewManager.prepareForWindowTeardown.pipe(633+ Effect.matchEffect({634+ onSuccess: () =>635+ Effect.sync(() => {636+ closePrepared = true;637+ if (!window.isDestroyed()) window.close();638+ }),639+ onFailure: (error) =>640+ Effect.gen(function* () {641+ closePreparationRunning = false;642+ yield* logWindowWarning(643+ "preview teardown blocked main window close",644+ previewTeardownErrorLogAnnotations(error),645+ );646+ }),647+ }),648+ ),
- @@ -99,0 +167,21 @@167+ const bridge = previewBridge;168+ if (!bridge?.onCaptureRecovery) return;169+ return bridge.onCaptureRecovery((recovery) => {170+ const webview = webviewRef.current;171+ if (recovery.tabId !== runtimeTabId || !webview) {172+ return;173+ }174+ try {175+ if (webview.getWebContentsId() !== recovery.webContentsId) return;176+ } catch {177+ return;178+ }179+ setCompositingReady(false);180+ setRetiredCaptureWebviews((current) =>181+ current.some((candidate) => candidate.webContentsId === recovery.webContentsId)182+ ? current183+ : [184+ ...current,185+ {186+ generation: webviewGeneration,187+ src: webview.src,
- apps/desktop/src/preview/Manager.ts lines 3622 to 3628OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3320,0 +3608,21 @@3608+ Effect.gen(function* () {3609+ while (true) {3610+ yield* Effect.sleep(250);3611+ const exit = yield* Effect.exit(recoverCaptureSurfaceOnce(tabId, wc));3612+ if (Exit.isSuccess(exit)) return;3613+ const error = Option.getOrNull(Cause.findErrorOption(exit.cause));3614+ if (!isPreviewAutomationDebuggerDrainTimeoutError(error)) return;3615+ }3616+ }).pipe(3617+ Effect.ensuring(3618+ Effect.sync(() => {3619+ captureRecoveryRetryWebContentsIds.delete(wc.id);3620+ }),3621+ ),3622+ ),3623+ );3624+ };3625+3626+ const recoverCaptureSurface = Effect.fn("PreviewManager.recoverCaptureSurface")(function* (3627+ tabId: string,3628+ wc: Electron.WebContents,
- apps/desktop/src/preview/Manager.ts lines 3630 to 3636OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3320,0 +3616,21 @@3616+ }).pipe(3617+ Effect.ensuring(3618+ Effect.sync(() => {3619+ captureRecoveryRetryWebContentsIds.delete(wc.id);3620+ }),3621+ ),3622+ ),3623+ );3624+ };3625+3626+ const recoverCaptureSurface = Effect.fn("PreviewManager.recoverCaptureSurface")(function* (3627+ tabId: string,3628+ wc: Electron.WebContents,3629+ ) {3630+ const exit = yield* Effect.exit(recoverCaptureSurfaceOnce(tabId, wc));3631+ if (Exit.isSuccess(exit)) return;3632+ const error = Option.getOrNull(Cause.findErrorOption(exit.cause));3633+ if (isPreviewAutomationDebuggerDrainTimeoutError(error)) {3634+ scheduleCaptureSurfaceRecovery(tabId, wc);3635+ }3636+ return yield* Effect.failCause(exit.cause);
- apps/web/src/browser/HostedBrowserWebview.tsx lines 132 to 133OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -91,9 +117,17 @@9111792118 const [webviewGeneration, setWebviewGeneration] = useState(0);93119 const [recoverySrc, setRecoverySrc] = useState(initialSrc);120+ const [retiredCaptureWebviews, setRetiredCaptureWebviews] = useState<121+ ReadonlyArray<RetiredCaptureWebview>122+ >([]);123+ const captureRetirementTimersRef = useRef(new Map<number, number | null>());94124 const latestUrlRef = useRef(initialUrl);9512596126 useEffect(() => {97127 latestUrlRef.current = initialUrl;98128 }, [initialUrl]);99129130+ const prepareRetiredCaptureWebview = useCallback(131+ (webContentsId: number) => {132+ const prepareWebviewRemoval = previewBridge?.prepareWebviewRemoval;133+ if (!prepareWebviewRemoval || captureRetirementTimersRef.current.has(webContentsId)) {@@ -39,0 +82,21 @@82+ let webContentsId: number;83+ try {84+ webContentsId = webview.getWebContentsId();85+ } catch {86+ removeRetired(runtimeTabId);87+ return;88+ }89+ retirementTimersRef.current.set(runtimeTabId, null);90+ void preview.prepareWebviewRemoval(runtimeTabId, webContentsId).then(91+ () => {92+ if (!currentSessionIdsRef.current.has(runtimeTabId)) {93+ removeRetired(runtimeTabId);94+ return;95+ }96+ const restore = () => {97+ if (!currentSessionIdsRef.current.has(runtimeTabId)) {98+ removeRetired(runtimeTabId);99+ return;100+ }101+ retirementTimersRef.current.set(runtimeTabId, null);102+ void preview.registerWebview(runtimeTabId, webContentsId).then(
- apps/web/src/browser/HostedBrowserWebview.tsx line 187OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -99,0 +167,21 @@167+ const bridge = previewBridge;168+ if (!bridge?.onCaptureRecovery) return;169+ return bridge.onCaptureRecovery((recovery) => {170+ const webview = webviewRef.current;171+ if (recovery.tabId !== runtimeTabId || !webview) {172+ return;173+ }174+ try {175+ if (webview.getWebContentsId() !== recovery.webContentsId) return;176+ } catch {177+ return;178+ }179+ setCompositingReady(false);180+ setRetiredCaptureWebviews((current) =>181+ current.some((candidate) => candidate.webContentsId === recovery.webContentsId)182+ ? current183+ : [184+ ...current,185+ {186+ generation: webviewGeneration,187+ src: webviewGeneration === 0 ? initialSrc : recoverySrc,
- apps/web/src/components/preview/previewAutomationErrors.ts line 283OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -220,0 +263,21 @@263+264+const timeoutMessage = (stage?: string): string =>265+ stage === undefined266+ ? "Preview automation timed out."267+ : `Preview automation timed out during ${stage}.`;268+269+const safeErrorCause = (270+ cause: unknown,271+): { readonly name: string; readonly message: string; readonly stage?: string } | null => {272+ if (isPreviewAutomationDesktopFailureError(cause)) {273+ return {274+ name: cause.nativeName,275+ message: cause.safeMessage,276+ ...(cause.stage === undefined ? {} : { stage: cause.stage }),277+ };278+ }279+ if (typeof cause !== "object" || cause === null) return null;280+ const record = cause as Record<string, unknown>;281+ const name = typeof record["name"] === "string" ? record["name"] : "";282+ const message = typeof record["message"] === "string" ? record["message"] : "";283+ const stage = typeof record["stage"] === "string" ? record["stage"] : undefined;
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed