fix(desktop): stop a browser pane's focus hook from freezing the window

Merged
KI
6d ago
+452-106

Problem

The desktop window froze for good whenever a browser pane had an Angular app open (seen with a SaaS login page). The window renderer sat at 120–145% CPU and climbed past 2 GB; the guest pane and the main process were busy too. Restarting didn't help, because the pane is restored on launch.

Root cause

Found by CPU-profiling the window renderer from first paint (main process --inspect-brk, then webContents.debugger attached as the window is created):

86%  processRootScheduleInMicrotask → performSyncWorkOnRoot   (React sync render loop)
 8%  electronTrpc onPaneFocus.onData → actions.focus → setActivePane → setState
15%  IPC onMessage
  1. setupFocusForward injects NEXT_MOUSEDOWN_SCRIPT with executeJavaScript, which runs in the page's main world. Zone.js replaces window.Promise, so the script returns a ZoneAwarePromise. executeJavaScript doesn't await it and resolves at once with {"__zone_symbol__state":null,"__zone_symbol__value":[]} (reproduced live on the frozen pane).
  2. The loop treated anything but false as a press, so it emitted pane-focus and re-armed with no yield, forever.
  3. Each emit ran setActivePane, which built a new tabs array even when the pane was already active, so every pane in the workspace re-rendered on every event.

Changes

  • Focus: Electron's before-mouse-event, no script in the page. setupFocusForward now listens for mouseDown on the guest webContents (watchGuestMouseDown in focus-forward.ts). Electron emits it from the input pipeline, so a page cannot block, replace or spin it, and it also fires for clicks inside cross-origin iframes, which the injected hook missed. (WebContents.on("focus") was tried in #7421 and does not fire for <webview> guests.)
  • Pinch zoom: isolated world, owned by main. The same main-world loop existed in attachBrowserViewportZoom (~6–7k injections/s on a Zone.js page). Main now runs NEXT_PAGE_VIEWPORT_ZOOM_SCRIPT with executeJavaScriptInIsolatedWorld (world 1999, viewport-zoom-forward.ts), validates each result, re-arms on dom-ready, and pushes viewports over a new browser.onViewportZoom subscription. The renderer only applies them. Pinch zoom works on Zone.js pages again.
  • packages/panes setActivePane: returns the current state when the pane is already active, so no focus source can cause a re-render storm.
  • App-state hygiene (prune-tabs-state.ts): at boot, drop persisted v1 tabs/panes (plus focus, active-tab and history entries) of workspaces no longer in local.db. Deleting a workspace never removed them, so app-state.json grew without bound: one real profile had 1,704 tabs / 2,925 panes for 12 live tabs (2.1 MB, rewritten whole on each flush). It runs every boot, is idempotent, keeps exactly what readV1TerminalPanes returns for live workspaces, and skips itself if workspaces can't be read. A failed write logs and startup continues. Not the freeze cause, but unbounded persisted state with no deletion path (see apps/desktop/AGENTS.md).

Verification

Dev desktop, real input over CDP into the window (routed to the guest like a user click), repro page loads zone.js@0.15.0. "Injections" = Debugger.scriptParsed in the guest, all worlds. Each candidate fix was applied alone on main to see which one actually fixes it.

Focus loop (Zone.js page; pinch zoom left as on main, so its loop is still running):

VariantWindowFocus events idle1 click → eventsVerdict
mainfrozen~16,000/s–bug
isolated world only2 ms01fixes
async wrapper only (main world)2 ms01fixes
strict === true guard only2 ms00hides it: clicks stop focusing the pane
store no-op only23 ms~12,000/s19,709mitigates: loop still runs, main 215% CPU
before-mouse-event (Electron)5 ms01fixes, nothing injected
input-event (Electron)6 ms01fixes, nothing injected

On main, moving the pane to a plain page stops the loop, but the window stays frozen (renderer 106%) while it drains the backlog.

Pinch-zoom loop (focus on before-mouse-event, so all injections are zoom):

VariantInjections/s (Zone.js)Pinch on Zone.js pagePinch on plain page
main~6,300–7,000brokenworks
stop on non-viewport (previous commit)0brokenworks
async wrapper0worksworks
isolated world via main (this PR)0worksworks

This PR, end to end: window responds in 1–2 ms, 0 injections, about 0% CPU, 1 focus event per click on Zone.js and plain pages and after navigation, pinch works on both. A click inside a cross-origin iframe gives 1 focus event (previous injected-hook approach: 0).

  • bun test: focus-forward.test.ts, viewport-zoom-forward.test.ts (waits, stops on a Zone.js result, drops a late result after cancel), browser-viewport-zoom.test.ts, prune-tabs-state.test.ts, and a setActivePane no-notify test. Desktop tsc and Biome are clean.
  • Prune on the real 2.1 MB backup (local, private data not committed): 1,704 → 12 tabs and 2,925 → 16 panes in 12 ms. collectV1TerminalPanes output is identical for every live workspace; a second run is a no-op.
  • Not done: a packaged build of this branch, real OS (non-CDP) trackpad pinch, Windows/Linux. Tested on macOS arm64 only.

Follow-ups (not in this PR)

  • Retire tabsState entirely. Since #9875 only the v1→v2 migration reads it. Snapshot terminal cwds into v1_migration_state once migration covers all v1 workspaces, then drop tabsState/tabsStateByWindow/v1AgentSessions.
  • Design mode still awaits a main-world executeJavaScript (design-mode-controller.ts). It is one-shot and validated, so no loop, but on a Zone.js page it likely fails at once with "invalid payload". Move it to an isolated world too.
  • Guardrail: route all app-owned guest scripts through one helper that always uses an isolated world, and lint against raw executeJavaScript on guests (keeping evaluateJS as the explicit page-world escape hatch).

🤖 Generated with Claude Code


Summary by cubic

Fixes the desktop freeze when a browser pane loads a page that replaces window.Promise (Zone.js in Angular apps, e.g. a SaaS login page). The focus-forward and pinch-zoom loops ran their injected scripts in the page's main world, so executeJavaScript resolved immediately with a non-native promise; the focus loop read that as a press and emitted focus events in a hot spin (re-rendering every workspace pane), and the zoom loop re-injected its script thousands of times a second.

  • Focus forwarding no longer injects a script: it listens for Electron's before-mouse-event on the guest, which the page can't block or spin, and it now also catches clicks inside cross-origin iframes.
  • Pinch zoom moved from the renderer into the main process, runs its script in an isolated world so Zone.js can't affect it, and streams viewports to the renderer over a new browser.onViewportZoom subscription; zoom works again on Zone.js pages.
  • setActivePane returns the current state when the pane is already active, so a repeated focus source can't cause a re-render storm.
  • At boot, persisted v1 tabs/panes of deleted workspaces are pruned from app-state.json; a failed prune write now logs instead of blocking startup.

Summary by CodeRabbit

  • Bug Fixes
    • Removed tabs and related pane state for workspaces that are no longer available, including in saved window layouts.
    • Improved focus handling for clicks in embedded browser pages, including after navigation.
    • Selecting the pane that is already active no longer triggers unnecessary state updates.
    • Invalid browser viewport data is ignored, preventing unintended zoom changes.
  • Improvements
    • Embedded browser viewport zoom now updates in the corresponding pane and stops updating when the pane is detached.