Skip to content

fix(window): stop viewport reflow from moving screen geometry - #10543

Merged
nwparker merged 6 commits into
mainfrom
nwparker/viewport-emulation-hardening
Jul 25, 2026
Merged

nwparker merged 6 commits into
mainfrom
nwparker/viewport-emulation-hardening

Conversation

@nwparker

@nwparker nwparker commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

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

reflowRendererViewport passed screenSize: viewSize and viewPosition: {x:0,y:0} alongside screenPosition: 'desktop', on the documented assumption that both fields are mobile-only no-ops. They are not. Blink's ScreenMetricsEmulator::Apply checks each one before the desktop/mobile branch:

if (!emulation_params_.screen_size.IsEmpty()) {
    screen_rect = gfx::Rect(gfx::Size(emulation_params_.screen_size));
  } else if (!emulating_desktop()) {   // <-- desktop check is the fallback

if (emulation_params_.view_position) {
    widget_pos = emulation_params_.view_position.value();
    window_pos = widget_pos;
  } else if (!emulating_desktop()) {

So for the full 32 ms hold, screen.width/availWidth reported the content size and the window origin was forced to 0,0.

Concrete failure: BrowserPane.tsx:3167-3168 translates OS cursor coords via event.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 screenSize is the actual documented "no override", and an omitted viewPosition stays nullopt — Electron's converter only assigns when the key is present (blink_converter.cc reads it into a local behind an if (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() exhausts VIEWPORT_REFLOW_RESTORE_ATTEMPTS on a live webContents, 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 a viewport_reflow_restore_failed breadcrumb.

Testing

18 tests in renderer-viewport-reflow.test.ts (2 new), all mutation-verified:

mutation caught
restore screenSize: viewSize 2 tests
re-add viewPosition: {x:0,y:0} 2 tests
drop the give-up breadcrumb 1 test

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

Made with Orca 🐋

nwparker and others added 6 commits July 25, 2026 02:38
… 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]>
@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

System 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the required template and omits Summary, Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections, including a concise Summary, Screenshots/No visual change, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: preventing viewport reflow from moving screen geometry.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8b9b5c and 8a6fab8.

📒 Files selected for processing (5)
  • src/main/system-resume-broadcast.test.ts
  • src/main/system-resume-broadcast.ts
  • src/main/window/createMainWindow.test.ts
  • src/main/window/renderer-viewport-reflow.test.ts
  • src/main/window/renderer-viewport-reflow.ts

Comment on lines +241 to +252
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'
])
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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)
})

@nwparker
nwparker merged commit 7d47e9e into main Jul 25, 2026
2 checks passed
@nwparker
nwparker deleted the nwparker/viewport-emulation-hardening branch July 25, 2026 10:36
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant