Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(preview): stabilize background browser automation #8981

Closedmaria-rckswants to merge 14 commits intomain fromrefs/pull/8981/headopened View on GitHub

maria-rckscommented

Note

Written by gpt-5.6-sol on behalf of Maria

Background preview webviews now stay inside the compositor viewport while leased, snapshot copy has a 2500ms deadline with replacement recovery outside the debugger semaphore, and broker and overlay budgets reserve response headroom. Recording uses the supported setDisplayMediaRequestHandler and getDisplayMedia path from #8957 with no capturePage warmup, while debugger commands and notifications including screencast-frame acknowledgements drain before guest or window teardown. Verified on Linux x86_64 with 151 desktop, 47 web, and 26 server tests, all four affected typechecks, lint, and git diff --check. The required packaged mac arm64 Electron 43.4.1 and 44.1.0 matrix remains blocked on this host; exact host evidence is Electron 43.4.1 as ELF x86-64 on Linux 6.18.46 x86_64, exiting because libnspr4.so is unavailable, so no mac artifact is attached and maintainer mac validation remains required before merge.


Note

High Risk Touches app quit, window close, update install, CDP lifecycle, and IPC contract changes for snapshots and recording—core desktop preview paths where races or regressions would be user-visible.

Overview Hardens desktop preview automation around ordered teardown, bounded captures, and sanitized failures so quit, window close, and webview removal do not race in-flight debugger work or leak secrets into logs.

Shutdown and lifecycle now run preparePreviewTeardown / prepareForWindowTeardown before destroying windows or completing app quit; typed teardown errors block quit, reset quitting, and log structured annotations without raw cause payloads. Update install and main-window close follow the same path.

Preview manager gains phased CDP sessions with in-flight command draining, timeouts for snapshot capture and teardown drains, prepareWebviewRemoval, capture-surface recovery events (subscribeCaptureRecoveries), and IPC prepareWebviewRemoval plus preload onCaptureRecovery. Recording switches from getMediaSourceId / capturePage warmup to a single display-media arm per host session (setDisplayMediaRequestHandler), with arm conflicts surfaced as PreviewRecordingArmConflictError.

Automation snapshot over IPC returns a Success / Failure result with filtered native capture messages instead of throwing; the MCP broker subtracts response headroom from the caller timeout when routing to the desktop host.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7a896dbece657e30aa0b8aa9a9c75aa31c7ebbb9. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Stabilize preview background automation with bounded captures and orderly teardown

  • Recording now uses getDisplayMedia with an arm-and-claim model instead of getUserMedia with precomputed source dimensions; startRecording returns void and may fail with PreviewRecordingArmConflictError.
  • Automation snapshots gain bounded capture/drain timeouts, phase-aware control sessions that reject commands during teardown, and automatic capture-surface recovery on failure.
  • Window close, app quit, and update install now wait for prepareForWindowTeardown to drain captures and detach debugger sessions before proceeding; failures block close and log sanitized annotations.
  • Renderer keeps retired capture webviews visible during recovery, tracks compositing readiness via data-preview-compositing, and coordinates retirement through new prepareWebviewRemoval and onCaptureRecovery bridge APIs.
  • Behavioral Change: automation.snapshot IPC returns a Success/Failure result union instead of rejecting; DesktopPreviewRecordingSource removed; startScreencast returns void; new channels PREVIEW_PREPARE_WEBVIEW_REMOVAL_CHANNEL and PREVIEW_CAPTURE_RECOVERY_CHANNEL added.
📊 Macroscope summarized e3ffebd. 5 files reviewed, 6 issues evaluated, 6 issues filtered, 0 comments posted

🗂️ Filtered Issues

apps/desktop/src/preview/Manager.ts — 0 comments posted, 4 evaluated, 4 filtered
  • line 604: captureNative permanently rejects once frameCaptureWindowOpen is false. prepareForWindowTeardown now sets that flag false before its bounded drains; when a drain times out, DesktopWindow prevents the close and resets only its closePreparationRunning guard, while this manager resets the flag only in a later setMainWindow. Thus a user who cancels/retries a blocked close is left with the existing window open but every subsequent screenshot, PiP frame, annotation crop, and recording warmup failing with "Preview window is closing." Restore the flag when teardown fails (or defer clearing it until the close is committed). [ Previously rejected ]
  • line 2561: A failed capture drain also leaves the existing debugger session permanently unusable while the close is blocked. Teardown marks each BrowserControlSession as closing before awaiting its capture drain; on the timeout path it exits without removing that session. Later ensureControlSession returns this same session without checking closing, while its proxied sendCommand rejects every command. Thus, after the user remains in the window following a capture-drain timeout, color-scheme updates and server/CDP automation for this guest fail until teardown is retried or the window is recreated. The new tracked capture at this line supplies the pending capture that triggers that timeout. [ Previously rejected ]
  • line 2561: After a teardown failure that blocks the window close, native captures are permanently disabled for the still-open window. prepareForWindowTeardown sets frameCaptureWindowOpen = false before its drains; DesktopWindow leaves the window open on that error, and this flag is only restored by a later setMainWindow, not by a failed close. Consequently this new captureNative call rejects all subsequent PiP-frame captures (and the same wrapper also rejects screenshots, annotation captures, and recording warmup) with “Preview window is closing.” A capture/debugger drain timeout is an established trigger (and is explicitly tested), so dismissing the failed close leaves the preview’s capture features unusable until the window is recreated. [ Already posted ]
  • line 3394: prepareForWindowTeardown clears frameCaptureWindowOpen before any of its fallible drains. If a capture/debugger drain times out, the window close handler deliberately cancels the close and leaves the window open, but this flag is never restored; thereafter every captureNative immediately rejects with "Preview window is closing." This permanently breaks screenshots, PiP frame capture, and recording warmup in the still-running window (including during the period in which the user must retry closing). Restore the flag when teardown fails, or only set it once teardown is known to succeed. [ Already posted ]
apps/desktop/src/updates/DesktopUpdates.ts — 0 comments posted, 2 evaluated, 2 filtered
  • line 634: A cancelled install also leaves screenshot capture disabled even when there are no control sessions. preparePreviewTeardown immediately sets PreviewManager's frameCaptureWindowOpen = false; if the install is then interrupted while stopping a backend, this flow's onInterrupt restores quitting and keeps the existing main window alive, but never restores that flag. captureScreenshot consequently returns PreviewMainWindowClosedError for the still-visible window until it is recreated. Roll back preview teardown state (or defer it until cancellation is no longer possible) when the install is interrupted. [ Already posted ]
  • line 634: Interrupting an update install while preparePreviewTeardown is draining a control session leaves the still-open window's preview automation permanently unusable. The install's onInterrupt only resets quitting/marker state, but prepareForWindowTeardown has already set control.closing = true; if interrupted before detachControlSession deletes it, later ensureControlSession returns that existing session and its debugger proxy rejects every command as closing. This is a realistic path because installs are explicitly interruptible (and DesktopUpdates.test.ts interrupts one); only invoke this irreversible teardown once install can no longer be cancelled, or clean up/recreate partial sessions on interruption. [ Previously rejected ]
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. apps/desktop/src/preview/Manager.ts line 1097OutdatedResolvedby maria-rcks
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/b532b101085b93f0d5c7a79d4a5ac6cdae015a75/apps/desktop/src/preview/Manager.ts#L1405

      When ensureControlSession fails during teardown or initialization, the action timeline entry remains status: "running" indefinitely, so later snapshots report an action that never completed. withControlSession calls ensureControlSession after pushAction but installs Effect.onExit(finalize) only afterward; attach finalization around the session acquisition as well, or explicitly finalize the entry when acquisition fails.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/desktop/src/preview/Manager.ts around line 1405:
      
      When `ensureControlSession` fails during teardown or initialization, the action timeline entry remains `status: "running"` indefinitely, so later snapshots report an action that never completed. `withControlSession` calls `ensureControlSession` after `pushAction` but installs `Effect.onExit(finalize)` only afterward; attach finalization around the session acquisition as well, or explicitly finalize the entry when acquisition fails.
    3. Both findings are the same convention issue at two ends of the same path: raw underlying error text is being promoted from cause into caller-visible message/detail payloads instead of normalized, bounded structural attributes.

      Posted via Macroscope — Effect Service Conventions
    4. Two runtime-behavior findings in the changed web UI code, both about readiness/capture paths that only work under conditions the desktop app does not guarantee (background-throttled window; agent-driven automation with no user activation).

      Posted via Macroscope — UI Consistency
      apps/web/src/browser/browserRecording.ts lines 271 to 277OutdatedResolvedby maria-rcks
    5. Note

      Written by gpt-5.6-sol on behalf of Maria

      Fixed in 3e165cdaa. Session acquisition now runs the same action finalizer on failure, and the focused test verifies that the later snapshot reports the failed action instead of a running entry.

    6. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR substantially changes production preview capture and debugger lifecycles, including window close, app shutdown, relaunch, update installation, and tab teardown. The new asynchronous coordination and timeout/recovery state introduce broad runtime and concurrency risk beyond an auto-approvable bug fix.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    7. apps/web/src/browser/HostedBrowserWebview.tsx line 292OutdatedResolvedby maria-rcks
      apps/desktop/src/preview/Manager.ts lines 3350 to 3358OutdatedResolvedby maria-rcks
    8. apps/desktop/src/preview/Manager.ts line 2277OutdatedResolvedby maria-rcks
    9. apps/desktop/src/preview/Manager.ts line 3723OutdatedResolvedby maria-rcks
    10. apps/desktop/src/preview/Manager.ts line 3353OutdatedResolvedby maria-rcks
      apps/web/src/browser/HostedBrowserWebview.tsx line 447OutdatedResolvedby maria-rcks
    11. Three findings, all inline: typed Effect error channels are being erased at Promise/Record boundaries instead of being handled inside Effect with the tagged union. The rest of the service work (new PreviewManager interface members declared inline on the Context.Service, namespace imports, Schema.TaggedErrorClass failures with structural attributes and exported Schema.is predicates) follows the conventions.

      Posted via Macroscope — Effect Service Conventions
      apps/desktop/src/window/DesktopWindow.ts lines 611 to 615OutdatedResolvedby maria-rcks
    12. apps/web/src/browser/ElectronBrowserHost.tsx lines 69 to 73OutdatedResolvedby maria-rcks
    13. apps/desktop/src/preview/Manager.ts lines 4298 to 4298OutdatedResolvedby maria-rcks
    14. apps/desktop/src/app/DesktopLifecycle.ts line 221OutdatedResolvedby maria-rcks
    15. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 6e0a39f3e9ef0dbea768ed10b4c93468bf310a5a. Configure [here](https://www.cursor.com/dashboard/bugbot).
    16. apps/web/src/browser/HostedBrowserWebview.tsx line 187OutdatedResolvedby maria-rcks
    17. apps/web/src/browser/ElectronBrowserHost.tsx lines 96 to 102OutdatedResolvedby maria-rcks

Sign in to join this conversation.