Repository navigation
fix(window): stop viewport reflow from moving screen geometry - #10543
Conversation
… as freezes Renderer timers stop across OS sleep, so a multi-hour `renderer_memory` heartbeat gap looks identical to a wedged renderer. That ambiguity sent the uber-crash investigation down a deadlock path that the telemetry later disproved -- and a healthy machine's own trace shows a 427-minute mid-session gap with reason=interval, so the gap alone proves nothing either way. powerMonitor 'resume' was already wired for renderer wake recovery but left no breadcrumb. Stamp suspend and report the measured span on resume so the next freeze report can be told apart from a laptop lid.
Adversarial review flagged that the first cut would flood the 30-entry breadcrumb ring and evict the crash evidence it exists to explain. Measured on 7 days of pmset history: 70 user-visible sleep cycles, worst 60-min burst of 7. Median span is 2 SECONDS -- only ~24% run past 60s, so most of that traffic could never explain a gap anyway. Cycles are counted Sleep -> next FULL Wake, since powerMonitor's resume maps to NSWorkspaceDidWake, which does not fire for dark wake. Drop the suspend breadcrumb (suspend now only stamps a timestamp) and emit a single `system_slept` on resume, gated at 60s. That cuts 70 cycles to 17 over the same week (worst burst 3) while still catching every sleep long enough to swallow a 60s renderer heartbeat.
The off mock deleted by event name alone, so teardown detaching a different closure than the one registered still passed -- a leak of the real powerMonitor listener would have gone unnoticed. For 'suspend' that leak has no other observable effect through the public API. Co-authored-by: Orca <[email protected]>
powerMonitor 'resume' maps to NSWorkspaceDidWake, which does not fire for dark wake, so macOS can deliver suspend -> suspend -> resume. Overwriting the stamp reported only the trailing segment, and when that segment fell under the 60s gate a 90-minute sleep recorded nothing at all -- leaving the gap looking like the unexplained freeze this is meant to rule out. Co-authored-by: Orca <[email protected]>
The comment claimed maintenance sleeps would flood the ring. Re-measuring pmset over 6 days (78 sleeps, 29 full wakes, 51 dark wakes) shows they resolve as DarkWake, which never fires 'resume', so they never recorded a breadcrumb at all. Real rate is 29 breadcrumbs / 6 days, worst 60-minute burst 4 against a 30-entry ring. The gate's actual job is narrower: skip sleeps shorter than the 60s heartbeat, which cannot open a gap to explain. Co-authored-by: Orca <[email protected]>
Blink's ScreenMetricsEmulator::Apply checks screen_size and view_position before the desktop/mobile branch, so screenPosition:'desktop' does not make them inert -- despite Electron documenting both as mobile-only. Passing the content size and 0,0 overrode screen.width/availWidth and the window origin for the whole 32ms hold, so a browser context menu opened mid-reflow would translate against 0,0 and land in the wrong place (BrowserPane.tsx:3167). Empty screenSize means 'no override', and an omitted viewPosition stays nullopt in Electron's converter, so the real position survives. Only the scale factor moves now, which is what the reflow actually needs. Also record a breadcrumb when the restore exhausts its attempt budget: the renderer is left at the wrong scale factor until some later reveal fixes it, and that was previously silent. Co-authored-by: Orca <[email protected]>
📝 WalkthroughWalkthroughSystem resume handling now observes suspend and resume events, records breadcrumbs for reportable sleep intervals, and unregisters both lifecycle listeners during cleanup. Renderer viewport reflow uses zero screen dimensions without an explicit view position and records a breadcrumb when restoration retries are exhausted. Tests cover sleep timing, dark wake, unsubscribe behavior, viewport geometry, restore outcomes, and updated macOS repaint expectations. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 959ab06e-a4e4-481b-ad0f-e2173b7d9e9a
📒 Files selected for processing (5)
src/main/system-resume-broadcast.test.tssrc/main/system-resume-broadcast.tssrc/main/window/createMainWindow.test.tssrc/main/window/renderer-viewport-reflow.test.tssrc/main/window/renderer-viewport-reflow.ts
| it('leaves evidence when it gives up with the viewport still emulated', () => { | ||
| const window = createWindow() | ||
| vi.mocked(window.webContents.disableDeviceEmulation).mockImplementation(() => { | ||
| throw new Error('always fails') | ||
| }) | ||
| reflowRendererViewport(window) | ||
| vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS * (VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 4)) | ||
|
|
||
| expect(getCrashBreadcrumbSnapshot().map((crumb) => crumb.name)).toEqual([ | ||
| 'viewport_reflow_restore_failed' | ||
| ]) | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert the breadcrumb payload and latch release.
This test only checks the breadcrumb name, so it would pass with an incorrect attempts value or a permanently held reflow latch. Assert the recorded data and start a second reflow after exhaustion to verify that the latch was released.
Suggested assertions
- expect(getCrashBreadcrumbSnapshot().map((crumb) => crumb.name)).toEqual([
- 'viewport_reflow_restore_failed'
- ])
+ expect(getCrashBreadcrumbSnapshot()).toEqual([
+ expect.objectContaining({
+ name: 'viewport_reflow_restore_failed',
+ data: { attempts: VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 1 }
+ })
+ ])
+ expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(
+ VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 1
+ )
+ reflowRendererViewport(window)
+ vi.advanceTimersByTime(0)
+ expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| it('leaves evidence when it gives up with the viewport still emulated', () => { | |
| const window = createWindow() | |
| vi.mocked(window.webContents.disableDeviceEmulation).mockImplementation(() => { | |
| throw new Error('always fails') | |
| }) | |
| reflowRendererViewport(window) | |
| vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS * (VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 4)) | |
| expect(getCrashBreadcrumbSnapshot().map((crumb) => crumb.name)).toEqual([ | |
| 'viewport_reflow_restore_failed' | |
| ]) | |
| }) | |
| it('leaves evidence when it gives up with the viewport still emulated', () => { | |
| const window = createWindow() | |
| vi.mocked(window.webContents.disableDeviceEmulation).mockImplementation(() => { | |
| throw new Error('always fails') | |
| }) | |
| reflowRendererViewport(window) | |
| vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS * (VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 4)) | |
| expect(getCrashBreadcrumbSnapshot()).toEqual([ | |
| expect.objectContaining({ | |
| name: 'viewport_reflow_restore_failed', | |
| data: { attempts: VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 1 } | |
| }) | |
| ]) | |
| expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes( | |
| VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 1 | |
| ) | |
| reflowRendererViewport(window) | |
| vi.advanceTimersByTime(0) | |
| expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) | |
| }) |
…ai#10543) * feat(diagnostics): record OS suspend/resume so sleep gaps aren't read as freezes Renderer timers stop across OS sleep, so a multi-hour `renderer_memory` heartbeat gap looks identical to a wedged renderer. That ambiguity sent the uber-crash investigation down a deadlock path that the telemetry later disproved -- and a healthy machine's own trace shows a 427-minute mid-session gap with reason=interval, so the gap alone proves nothing either way. powerMonitor 'resume' was already wired for renderer wake recovery but left no breadcrumb. Stamp suspend and report the measured span on resume so the next freeze report can be told apart from a laptop lid. * fix(diagnostics): only record sleeps long enough to hide a heartbeat Adversarial review flagged that the first cut would flood the 30-entry breadcrumb ring and evict the crash evidence it exists to explain. Measured on 7 days of pmset history: 70 user-visible sleep cycles, worst 60-min burst of 7. Median span is 2 SECONDS -- only ~24% run past 60s, so most of that traffic could never explain a gap anyway. Cycles are counted Sleep -> next FULL Wake, since powerMonitor's resume maps to NSWorkspaceDidWake, which does not fire for dark wake. Drop the suspend breadcrumb (suspend now only stamps a timestamp) and emit a single `system_slept` on resume, gated at 60s. That cuts 70 cycles to 17 over the same week (worst burst 3) while still catching every sleep long enough to swallow a 60s renderer heartbeat. * test(diagnostics): assert resume listeners detach by identity The off mock deleted by event name alone, so teardown detaching a different closure than the one registered still passed -- a leak of the real powerMonitor listener would have gone unnoticed. For 'suspend' that leak has no other observable effect through the public API. Co-authored-by: Orca <[email protected]> * fix(diagnostics): span from the first suspend across dark wake powerMonitor 'resume' maps to NSWorkspaceDidWake, which does not fire for dark wake, so macOS can deliver suspend -> suspend -> resume. Overwriting the stamp reported only the trailing segment, and when that segment fell under the 60s gate a 90-minute sleep recorded nothing at all -- leaving the gap looking like the unexplained freeze this is meant to rule out. Co-authored-by: Orca <[email protected]> * docs(diagnostics): correct the threshold rationale to match measurement The comment claimed maintenance sleeps would flood the ring. Re-measuring pmset over 6 days (78 sleeps, 29 full wakes, 51 dark wakes) shows they resolve as DarkWake, which never fires 'resume', so they never recorded a breadcrumb at all. Real rate is 29 breadcrumbs / 6 days, worst 60-minute burst 4 against a 30-entry ring. The gate's actual job is narrower: skip sleeps shorter than the 60s heartbeat, which cannot open a gap to explain. Co-authored-by: Orca <[email protected]> * fix(window): stop viewport reflow from moving screen geometry Blink's ScreenMetricsEmulator::Apply checks screen_size and view_position before the desktop/mobile branch, so screenPosition:'desktop' does not make them inert -- despite Electron documenting both as mobile-only. Passing the content size and 0,0 overrode screen.width/availWidth and the window origin for the whole 32ms hold, so a browser context menu opened mid-reflow would translate against 0,0 and land in the wrong place (BrowserPane.tsx:3167). Empty screenSize means 'no override', and an omitted viewPosition stays nullopt in Electron's converter, so the real position survives. Only the scale factor moves now, which is what the reflow actually needs. Also record a breadcrumb when the restore exhausts its attempt budget: the renderer is left at the wrong scale factor until some later reveal fixes it, and that was previously silent. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
Why
Follow-up hardening on #10473/#10485, from an adversarial audit of the merged emulation path. Neither PR is reverted — both fix a real macOS 26 frame-mutation hazard. This corrects two defects in the final implementation.
1. "Scale-only" emulation was also moving screen geometry
reflowRendererViewportpassedscreenSize: viewSizeandviewPosition: {x:0,y:0}alongsidescreenPosition: 'desktop', on the documented assumption that both fields are mobile-only no-ops. They are not. Blink'sScreenMetricsEmulator::Applychecks each one before the desktop/mobile branch:So for the full 32 ms hold,
screen.width/availWidthreported the content size and the window origin was forced to 0,0.Concrete failure:
BrowserPane.tsx:3167-3168translates OS cursor coords viaevent.screenX - window.screenX. A browser context menu opened during a reveal/resume reflow computes against a bogus origin and lands in the wrong place.Fix: empty
screenSizeis the actual documented "no override", and an omittedviewPositionstaysnullopt— Electron's converter only assigns when the key is present (blink_converter.ccreads it into a local behind anif (dict.Get(...)), unlike the other fields). Electron's TS types mark it required, hence the narrow cast. Only the scale factor moves now, which is all the reflow needs.2. Giving up on the restore was silent
When
disableDeviceEmulation()exhaustsVIEWPORT_REFLOW_RESTORE_ATTEMPTSon a livewebContents, the latch is released and the renderer is left at the wrong scale factor until some later reveal happens to fix it. Releasing the latch is the right call — pinning it would kill every future reflow — but the invariant breach left no trace, so it would surface as an unexplained rendering bug. Now records aviewport_reflow_restore_failedbreadcrumb.Testing
18 tests in
renderer-viewport-reflow.test.ts(2 new), all mutation-verified:screenSize: viewSizeviewPosition: {x:0,y:0}Also asserts the success path records nothing, so the breadcrumb can't leak into the 30-entry ring on healthy reveals.
Related suites: 30 files / 320 tests pass. Typecheck clean on all three projects; lint and format clean.
Audit findings not acted on
before-quitsetsisQuittingsynchronously atindex.ts:2479-2486andgetExpectedTeardownScopeonly returnsapp-shutdownfrom that state, so a main thread deadlocked in AppKit could not have run those callbacks. Not a code defect.Made with Orca 🐋