Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(preview): resize hidden browser tabs reliably #8469

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 20 commits intomain fromfix/preview-hidden-viewport-v2opened View on GitHub

preview_resize could update the server and React layout while a hidden desktop webview kept its old native viewport. Failed or timed-out resizes could also leave the server, client store, and guest on different viewport values.

This fixes #3712. Desktop now applies the logical viewport through CDP while the preview is hidden, scales desktop dimensions for page zoom, and clears native metrics in fill mode. The client uses server revisions and guarded rollback writes so a late response cannot replace a newer viewport. Ordered revisions take priority over wall-clock timestamps, including when the server clock moves backward.

The rebase preserves the current hidden-preview activity lease, recording state, and macOS paintability behavior. Guilherme Barros's original commits from #7303 keep their authorship in this branch.

Tests:

  • vp test run packages/contracts/src/preview.test.ts apps/server/src/preview/Manager.test.ts apps/web/src/browser/browserViewportActions.test.ts apps/web/src/components/preview/previewGuestViewport.test.ts apps/web/src/components/preview/previewViewportReadiness.test.ts apps/web/src/components/preview/previewViewportRollback.test.ts apps/web/src/components/preview/previewAutomationOpenReadiness.test.ts apps/web/src/components/preview/previewAutomationTarget.test.ts apps/web/src/previewStateStore.test.ts apps/desktop/src/preview/Manager.test.ts (206 passed)
  • vp run --filter @t3tools/contracts typecheck
  • vp run --filter t3 typecheck
  • vp run --filter @t3tools/web typecheck
  • vp run --filter @t3tools/desktop typecheck
  • Focused lint, format, and git diff --check

A manual Electron pass is still needed before merge. This audit did not use browser or computer control.

Made with GPT-5.6 Sol using Codex.


Note

Medium Risk Large cross-layer concurrency and a breaking preview.resize success shape (PreviewResizeResult); behavior is heavily tested but still needs manual Electron validation.

Overview Fixes preview resizes that updated server/React layout while a hidden desktop webview kept stale native dimensions, and reduces drift after failed or racing resize operations.

Desktop adds human setViewport and agent automationSetViewport IPC paths that apply logical sizes via CDP Emulation.setDeviceMetricsOverride (scaled for tab zoom, cleared in fill mode), persist intent across webview swaps/DevTools, and roll back or reconcile when applies fail or overlap.

Server preview.resize now returns PreviewResizeResult with stateVersion and previousViewport, and rejects stale rollback writes via PreviewResizeConflictError when expectedStateVersion does not match the tab’s viewport revision.

Web tracks per-tab server revisions in previewStateStore, serializes viewport mutations with absolute deadlines so timed-out commits cannot block newer ones, syncs the guest through applyPreviewGuestViewport on webview attach and viewport changes, and on automation resize failure runs server-first guarded rollback before touching the guest CDP override.

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

Note

Fix preview automation viewport resize with per-tab revisions and deadline-bound mutations

  • Adds per-tab server revision tracking to previewStateStore so stale resize responses and authoritative lists can no longer overwrite newer tab state, even when wall-clock timestamps are out of order
  • Introduces optimistic concurrency control on PreviewManager.resize: requests carry an optional expectedStateVersion (epoch + revision); a mismatch returns PreviewResizeConflictError without mutating state or emitting events, and successful writes return the new version and previous viewport for rollback
  • Replaces relative timeouts with absolute deadlines across the viewport mutation queue (queueBrowserViewportMutation), preview automation polling (waitForRenderedViewport), and visible commits (commitBrowserViewportChange); a front-of-queue mutation that hits its deadline releases later mutations instead of blocking them
  • Adds a guest viewport bridge with new IPC channels (PREVIEW_SET_VIEWPORT_CHANNEL, PREVIEW_AUTOMATION_SET_VIEWPORT_CHANNEL) and applyPreviewGuestViewport to push the authoritative stored viewport to the guest after webview attachment; fill mode maps to a clear request and fixed dimensions map to explicit width/height
  • New automation tabs opened in fill mode now receive DEFAULT_PREVIEW_AUTOMATION_VIEWPORT instead of inheriting a fill setting, and needsPreviewAutomationSessionSync forces a server refresh when the local serverEpoch is null
  • Behavioral Change: PreviewManager.resize now returns PreviewResizeResult instead of PreviewSessionSnapshot; rpc.WsPreviewResizeRpc and ipc.EnvironmentApi.preview.resize are updated to match. Older servers without stateVersion/previousViewport fields remain backward-compatible since both are optional in the decoder. commitBrowserViewportChange now enforces a 15-second deadline from invocation time including queue wait.
Macroscope summarized 9425d6e.
    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: 2f92fdcd-4721-4ce1-93bf-cc0f3b60e19d

      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

      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. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire13.4 KiB13.4 KiB+6 B (+0.0%)15.1 KiB✅
      CodexThread snapshot wire6.9 KiB6.9 KiB−1 B (−0.0%)7.3 KiB✅
      CodexLive turn WebSocket wire6.5 KiB6.6 KiB+7 B (+0.1%)7.8 KiB✅
      CodexLive turn WebSocket decoded57.0 KiB57.0 KiB0 B (0.0%)66.4 KiB✅
      CodexLive turn messages10100 (0.0%)21✅
      ClaudeTotal thread wire13.5 KiB13.5 KiB+1 B (+0.0%)15.1 KiB✅
      ClaudeThread snapshot wire6.9 KiB6.9 KiB−2 B (−0.0%)7.3 KiB✅
      ClaudeLive turn WebSocket wire6.6 KiB6.6 KiB+3 B (+0.0%)7.8 KiB✅
      ClaudeLive turn WebSocket decoded57.8 KiB57.8 KiB0 B (0.0%)66.4 KiB✅
      ClaudeLive turn messages10100 (0.0%)21✅

      Baseline: fc53b27 · PR result: 9425d6e · 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: 109.4 KiB
      • Claude decoded thread snapshot: 110.1 KiB

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

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This is a large cross-layer runtime change affecting CDP viewport state, server revisioning, automation timeouts, rollback behavior, and product defaults. The unresolved failure and session-restoration concerns make manual review and validation necessary.

      Not approved because:

      • 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

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

      Changing zoom updates the guest but leaves an active viewport override at its old dimensions, so a viewport saved as 1024x768 remains 1024x768 after switching to 50% instead of becoming 512x384. applyZoom must reapply the saved viewport intent after committing the new zoom factor.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/desktop/src/preview/Manager.ts around line 2340:
      
      Changing zoom updates the guest but leaves an active viewport override at its old dimensions, so a viewport saved as `1024x768` remains `1024x768` after switching to 50% instead of becoming `512x384`. `applyZoom` must reapply the saved viewport intent after committing the new zoom factor.
    6. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      The renderer already reapplies the stored viewport after zoom changes. HostedBrowserWebview includes normalizedZoomFactor in the viewport effect dependencies, then calls applyPreviewGuestViewport on the next frame. The desktop manager reads the committed zoom when it converts that logical viewport to native metrics. I kept applyZoom unchanged because adding CDP settlement there creates separate commit, failure, and guest-replacement races.

    7. @@ -197,3 +211,10 @@
      197211 deviceToolbarVisible,
      198212 aspectRatio: lockedAspectRatio,
      199213 });
      214+ const guestViewportKey = browserViewportSettingKey(effectiveViewport);
      215+ guestViewportRef.current = effectiveViewport;
      216+ useEffect(() => {
      217+ const setViewport = previewBridge?.setViewport;
      218+ if (!setViewport || !hasWebContents) return;
      219+ const frame = window.requestAnimationFrame(() => {
      220+ void applyPreviewGuestViewport(setViewport, runtimeTabId, guestViewportRef.current).catch(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium browser/HostedBrowserWebview.tsx:220

      When setViewport rejects after a server-side resize, the UI/server remain at the new effectiveViewport while the native guest stays at its previous size. The effect catches the rejection with () => undefined, and because neither guestViewportKey nor hasWebContents changes, there is no retry or rollback; please retry the native update or restore the prior viewport on failure.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/browser/HostedBrowserWebview.tsx around line 220:
      
      When `setViewport` rejects after a server-side resize, the UI/server remain at the new `effectiveViewport` while the native guest stays at its previous size. The effect catches the rejection with `() => undefined`, and because neither `guestViewportKey` nor `hasWebContents` changes, there is no retry or rollback; please retry the native update or restore the prior viewport on failure.
    8. 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 9425d6e2fc2d1f451c4ae424719bc9889a67da89. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -2613,0 +2824,21 @@
      2824+ applied = current.intent;
      2825+ appliedWebContents = current.wc;
      2826+ }
      2827+ });
      2828+
      2829+ // Human/toolbar path. Must not take agent control or write a resize action.
      2830+ const setViewport = Effect.fn("PreviewManager.setViewport")(function* (
      2831+ tabId: string,
      2832+ input: PreviewViewportOverride,
      2833+ ) {
      2834+ const prepared = yield* prepareViewportIntent(tabId, input);
      2835+ yield* settleViewportIntent(
      2836+ tabId,
      2837+ prepared.wc,
      2838+ prepared.intent,
      2839+ prepared.generation,
      2840+ (latest) => applyViewportOverride(tabId, prepared.wc, latest),
      2841+ ).pipe(
      2842+ Effect.tap(() => acceptViewportOverride(prepared.intent)),
      2843+ Effect.onError(() => rollbackViewportOverride(tabId, prepared.intent, prepared.generation)),
      2844+ );

      Guest rollback fights server viewport

      Medium Severity

      Human resizes persist the new viewport on the server and in the React layout first, then call setViewport. On CDP failure (DevTools open, debugger attach, transient guest error) desktop marks that intent rejected and restores the previous native metrics, while the renderer swallows the error and does not retry. After DevTools close, restoreControlSession reapplies the rolled-back intent, so the chrome shows the new size and the page stays on the old override until another resize or zoom.

      Additional Locations (1)
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9425d6e2fc2d1f451c4ae424719bc9889a67da89. Configure [here](https://www.cursor.com/dashboard/bugbot).
    9. Note: GPT-6 on behalf of shivam (@shivamhwp).

      The toolbar/DevTools finding is still present at 9425d6e. setViewport receives a setting already saved by the renderer, but its error handler rejects that intent and restores the prior native setting. Closing DevTools therefore replays the old size.

      The local correction accepts and retains the toolbar intent before native application, keeping the error visible to the caller. The next control-session attach replays the saved size. automationSetViewport keeps its existing rollback behavior because an agent resize is still provisional. A transient CDP failure can leave the guest behind until a successful apply or reattach; this does not provide an automatic retry for every native error.

      Keep the zoom multiplication. Chromium divides these desktop CDP dimensions by page zoom; removing the multiplication produces the wrong logical viewport at non-default zoom.

    10. Note

      🤖 GPT-6 Sol responding on behalf of Victor

      I saw preview_resize time out twice after 15 seconds when selecting the iphone-12-pro preset. Before the resize, preview_open reported a saved size of 1280×800 but a measured size of 1683×1052.

      After the timeouts, preview_evaluate returned “No preview automation host is available,” and preview_snapshot failed with PreviewAutomationNoAvailableHostError. The viewport mismatch appears to match this PR. I could not tell whether it also covers the host becoming unavailable. Could the manual Electron check include this sequence?

    11. juliusmarminge added labelsmacroscope-review

    12. terminal-preview-24 feasibility: blocked on a rewrite against the current native preview architecture and Electron verification; no changes pushed.

      Current main removed the automation-host paths this PR modifies. Agent resizing now goes through ServerBrowser; desktop-backed tabs skip its headless settings path, and the desktop preview manager owns the debugger session. A smaller implementation must use that current shared CDP session rather than restore retired automation IPC.

      The published head also retains the toolbar/DevTools failure mismatch: native apply rolls back, while the UI/server retain the requested viewport, so closing DevTools can replay the old native intent. The reported local correction is not in the head.

      A desktop maintainer needs to rebuild and verify:

      • Hide the panel, resize through the agent to iphone-12-pro, and assert page innerWidth/innerHeight are 390×844 while hidden. Switch to fill and confirm the override clears.
      • Repeat at non-default zoom and Windows high DPI. Retain the original CSS/device-independent-pixel conversion unless actual Electron measurements disprove it.
      • Resize from the toolbar with DevTools open, then close DevTools: page and toolbar must converge. Repeat after webview swap/crash reload.
      • On macOS, check hidden webviews recover instead of remaining blank. Repeat the reported two-resize timeout sequence and confirm the automation host remains available.

      The old green CI predates the architecture change and cannot validate this integration. This fixes a different bug from the page-backing/profile lifecycle work in #18217, so neither is being closed as a duplicate.

    13. Windows Nightly 3512 Retest

      Tested on Windows with official 0.1.2-nightly.20261022.3512, source 3b95e7831b11b17627dff16843bc087bfca397ec, Electron 44.9.3. The installed executable and application/server archives match the signed official installer.

      An initial agent-created incognito tab at https://example.com/ hit this sequence:

      1. Open and initial DOM evaluation succeeded.
      2. Recording start timed out after 15 seconds.
      3. Resize to 390 × 844 timed out after 10 seconds.
      4. The next evaluation returned "No preview automation host is available for evaluate", although status still reported the tab available in Fill mode.

      A later fresh incognito tab in the same application session worked:

      • Requested 1920 × 1080. The resize response returned 1280 × 800, but the next DOM read and subsequent reads during recording measured 1920 × 1080.
      • Recording start and stop succeeded. The resulting 12-second H.264 clip is 1920 × 1080.
      • After a manual change to 414 × 896, the DOM also measured 414 × 896. The user reported that it looked fine.

      These results show an intermittent automation failure and an inaccurate resize response in one successful run. They do not establish the earlier zoom mismatch. The successful recording measured DPR 1; non-default browser zoom was not verified. The failed recording preceded the first resize failure, but causation is unproven. This also was not the requested two-resize sequence or a test of this PR's exact head.

      Keeping these observations here alongside the related capture work in #22743.

      Prepared with GPT-6.1-Sol through the Codex harness in T3 Code.

    14. juliusmarminge requested changes

      Thanks for the work on this. Main now keeps the browser host mounted and handles viewport resizes without an open preview panel in #25462 (f05c38f), so that part of this older implementation is covered. Please cut this down to the remaining failure/race handling against the current server-browser architecture: a resize commits its setting before application, and the current snapshot ordering still relies on timestamps. Please retain only changes needed to prevent inconsistent or stale viewport state and their focused proof.

    15. tanstack-source added labelsbug

    16. Thanks for this. Before a bug fix is taken further, the bug is reproduced on current main, and here it did not appear.

      I ran the steps from the description on current main (56b9dbc87b) in the desktop app on Linux, with a fresh database and a Codex thread calling the preview tools on a local static page in a new tab, with the preview panel hidden. A freeform 1920x1200 resize with a 15 second timeout succeeded immediately. The stored setting, the measured viewport, the page's own innerWidth/innerHeight and a direct read of the hidden webview all came out 1920x1200. The snapshot was the same frame scaled to 1280 wide. The iphone-12-pro portrait preset gave 390x844 everywhere, and fill went back to the tab's 1280x800 default size.

      I also tried the harder cases. With the tab zoomed to 150% and the panel hidden, a 1000x700 resize gave a 1000x700 page at devicePixelRatio 1.5. A resize forced to time out (timeoutMs 1) left setting, measured viewport and page in agreement with no partial state. A later resize stuck with no late revert, and back-to-back resizes ended on the last one sent. I repeated the main sequence at a 2x screen scale, close to the 2.19 in the original report, with the same results. Showing the panel afterwards showed the size the tab actually had.

      The guarded rollback and revision ordering may still be worth having. But the problem users hit, a hidden tab whose real viewport disagrees with what the preview tools report after a resize, no longer reproduces on main. If you have a sequence that still shows a mismatch on current main, please share it and we'll look again.

      Closing this pull request. If it still happens for you, please open an issue with the exact steps, what you see, and the version and platform you are on; a fix is picked up from there.

    17. juliusmarminge closed this

Sign in to join this conversation.