Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(preview): bound automation waits and screenshot captures #4685

Mergedjuliusmarmingemerged 6 commits intomain fromrefs/pull/4685/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Preview automation could lose an unavailable-overlay error to the broker's timeout, fail on a transient Chromium capture error, or hold the tab's control session indefinitely when capturePage() never settled.

This change reserves response time before the broker deadline and uses one host deadline across setup and overlay polling. Polling sleeps and status probes share that deadline. One-shot screenshots and snapshots retry up to three times, with 120 ms between attempts and a one-second timeout per attempt. Guest identity is checked before each attempt and after capture, so replacement cannot produce a stale screenshot.

Verification

  • 84 focused PreviewManager tests and 16 host-budget/readiness tests pass. Desktop and web typechecks, scoped formatting, and scoped lint pass. Web lint retains an existing React refs warning.
  • Regression tests fail without the fixes: replacement during retry delay and during capture incorrectly succeeds; an indefinitely pending capture blocks a queued evaluation. The fixed snapshot path releases control after its capture attempts expire. A new boundary regression fails before the fix and passes after it: a ready status that wins the deadline race is accepted, while a status arriving after the timeout is ignored.
  • Authenticated the isolated web app through its pairing URL. Browser probes with a 100 ms request budget returned unavailable/stalled at 80 ms and available immediately.
  • Ran the rebuilt Electron 43.4.1 app on Linux against disposable state. The screenshot button saved an image. A background preview snapshot returned a complete 483×700 image in 128 ms, subsequent interaction succeeded, and the guest returned offscreen after activity ended. Verification processes were stopped.

Timing evidence from the previous implementation and this revision, using deterministic timers:

100 ms request, overlay unavailableBeforeAfter
No setup delay100 ms80 ms
30 ms setup delay130 ms80 ms

There is no layout change. The captured image below is additional runtime evidence from the background snapshot path.

Image returned by a background preview snapshot in the rebuilt Electron app

The capture timeout bounds the image-capture portion. Other debugger operations and navigation/viewport waits retain their existing behavior. Electron does not expose cancellation for the native capture operation; late results are ignored. Background guest placement already exists on main and is reused here.

Prepared with GPT-6 in Codex.


Note

Medium Risk Changes timing and failure modes for preview automation screenshots and overlay readiness—core agent browser control paths—but behavior is heavily regression-tested and failures become bounded rather than hanging.

Overview Preview automation and desktop capture paths get bounded, deadline-aware waits so broker timeouts and hung Chromium compositors do not mask real failures or block the tab control session.

Desktop (PreviewManager) adds capturePageWithRetry and wires captureScreenshot and automationSnapshot through it instead of a single capturePage() call. Each operation gets up to three attempts (120 ms apart) with a 1 s per-attempt timeout, retries transient errors like UnknownVizError, and verifies the tab still owns the same guest before and after capture so swapped webviews cannot persist stale images or keep retrying after replacement.

Web (PreviewAutomationHosts) introduces resolveHostWaitBudgetMs and waitForHostReadiness: one absolute host deadline (request timeout minus a response margin) covers session sync, tab setup, and overlay polling. waitForDesktopOverlay races status probes against that deadline and stops before the broker times out, so unavailable-overlay errors can still be reported.

Tests extend Manager.test for retry success/failure, guest swap during retry or in-flight capture, and snapshot control release when capture stalls; new previewAutomationHostBudget tests cover budget math and polling behavior.

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

Note

Bound preview screenshot captures to 3 retries and add deadline to automation host waits

  • Adds capturePageWithRetry to PreviewManager with a 1,000 ms per-attempt timeout, three attempts, and 120 ms spacing; both captureScreenshot and automationSnapshot now use it instead of unbounded capturePage calls
  • Capture results from a destroyed or replaced guest web contents are rejected so stale artifacts are never written
  • Replaces per-phase timeouts in PreviewAutomationHost with a single absolute deadline shared across session sync, tab setup, and overlay readiness; resolveHostWaitBudgetMs reserves the smaller of 1,500 ms or 20% of the request timeout
  • waitForHostReadiness now polls at 50 ms intervals, races each probe against the remaining deadline, and returns false on expiry instead of waiting indefinitely on stalled probes
  • Behavioral Change: capturePage attempts that previously hung forever now fail after ~1,100 ms; automation requests that previously gave each phase a full timeout now share one budget, so slow session-sync or tab-setup can reduce the time left for overlay readiness
Macroscope summarized 643cef6.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 589584f0-2aba-438e-80ea-e7f1c98be710

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `t3code/preview-automation-reliability`

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. Stale Bugbot comment from a previous run.

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

      Approvability

      Verdict: Approved at 643cef6

      Macroscope's review found this PR approvable — This is a localized preview reliability fix that bounds existing capture and readiness operations without changing APIs, schemas, or user-facing capabilities. The new retry, timeout, guest-replacement, and deadline behavior is directly covered by focused regression tests.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. Destreyf(GitHub profile, opens in a new tab)commented

      Hey @juliusmarminge I was running into a lot of this recently, had gpt-5.6-sol dig through it and it came up with a "fix" that seems align with the approach you have here, I don't want to put up a potentially competeing PR.

      • Temporarily moves the agent’s background tab into compositor bounds before capture, fixing the actual offscreen-tab failure.
      • Adds a hard timeout around each capturePage() attempt, preventing a hung capture from blocking all later automation.

      Commit on my fork: https://github.com/Destreyf/t3code/commit/3ebfbc69043f168ca3ec0c2536d35a1e80ca11c9

      For more context this is my agents summary of the additions my branch has:

      Agent Slop Summary

      ### Background preview capture reliability follow-up
      
      Reference implementation: [Destreyf/t3code@3ebfbc690](https://github.com/Destreyf/t3code/commit/3ebfbc69043f168ca3ec0c2536d35a1e80ca11c9)
      
      This builds on #4685’s `capturePage()` retry and host-timeout improvements. The additional reliability work addresses captures that remain permanently pending because the target `<webview>` is outside Electron’s compositor bounds.
      
      #### Additional improvements
      
      - **Temporarily composite the exact capture target.** Before a snapshot, the agent-pinned background tab is moved from `-100000px` to an in-window position behind the interface (`z-index: -1`, no pointer events). The currently visible browser tab is not moved, focused, or selected.
      - **Restore normal parking afterward.** Capture presentation is reference-counted and released in `finally`, returning the background tab offscreen after concurrent captures finish.
      - **Wait for presentation before capture.** Snapshot execution waits for React to commit the compositor-safe placement and for an additional presentation tick before calling Electron.
      - **Bound captures that never settle.** Each `capturePage()` attempt has a one-second deadline, with up to three attempts spaced 120 ms apart. Retries alone cannot recover a promise that never resolves.
      - **Prevent poisoned automation sessions.** A stuck snapshot can no longer hold the tab’s serialized control session indefinitely; subsequent evaluation and interaction can proceed after the bounded failure.
      - **Protect against guest replacement.** Retries stop if the tab is destroyed or replaced, preventing capture from a detached or stale `WebContents`.
      
      #### Regression coverage
      
      - Agent-pinned background tab capture while another browser tab remains visible.
      - Capture placement affects only the requested tab and is restored afterward.
      - Transient screenshot and snapshot failures retry successfully.
      - Never-resolving capture releases later automation.
      - Guest replacement stops retries.
      - Persistent failures still surface normally.
      
      A real Electron harness reproduced the original behavior: direct capture at `-100000px` timed out, while the temporary presentation lease returned a full 800×500 capture and restored offscreen parking afterward.
      
      The production portion is approximately **180 additions and 11 deletions across six files**. The focused suite passes **58 tests**, and both web and desktop typechecks pass.
      
      Upstream context and related Electron issues are documented [here](https://github.com/Destreyf/t3code/blob/t3code/fix-electron-preview-screenshots/docs/internals/research/electron-background-preview-capture.md).
    6. juliusmarminge changed the title

    7. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful main measurement shown below.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire13.8 KiB13.5 KiB−241 B (−1.7%)15.1 KiB✅
      CodexThread snapshot wire7.0 KiB7.0 KiB+4 B (+0.1%)7.3 KiB✅
      CodexLive turn WebSocket wire6.7 KiB6.5 KiB−245 B (−3.5%)7.8 KiB✅
      CodexLive turn WebSocket decoded58.5 KiB57.0 KiB−1.5 KiB (−2.6%)66.4 KiB✅
      CodexLive turn messages108−2 (−20.0%)21✅
      ClaudeTotal thread wire13.5 KiB13.6 KiB+44 B (+0.3%)15.1 KiB✅
      ClaudeThread snapshot wire7.0 KiB7.0 KiB−1 B (−0.0%)7.3 KiB✅
      ClaudeLive turn WebSocket wire6.5 KiB6.6 KiB+45 B (+0.7%)7.8 KiB✅
      ClaudeLive turn WebSocket decoded57.8 KiB57.9 KiB+88 B (+0.1%)66.4 KiB✅
      ClaudeLive turn messages810+2 (+25.0%)21✅

      Baseline: d28077e · PR result: 643cef6 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 113.8 KiB
      • Claude decoded thread snapshot: 114.5 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    8. Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

      Fix All in Cursor Bugbot Autofix is [ON](https://www.cursor.com/dashboard/bugbot), but a cloud agent failed to start. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 09b5c2a725aaba76ecb70b06bc8427120d0c7a3e. Configure [here](https://www.cursor.com/dashboard/bugbot).
    9. juliusmarminge changed the title

    10. juliusmarminge merged thisde1b798

    11. juliusmarminge closed this

Sign in to join this conversation.