From 6a7a09e7c14a9cf3da59d23fa8ea6545c7e2b4e4 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:00:51 -0700 Subject: [PATCH 1/4] fix(window): restore the macOS 26 reflow without touching the native frame #10253 stopped the main-thread deadlock by skipping the repaint size nudge on macOS 26, but invalidate() repaints without reflowing, so the h-dvh root kept a stale viewport height and the status bar stayed clipped off-screen (STA-2383) on every Tahoe reveal, restore and wake. Drive the reflow through device emulation instead: a +1px emulated viewport, reverted a frame later, makes the renderer recompute layout without any NSWindow mutation, so the FrontBoardServices re-entrancy that wedged the main thread for 109 minutes is still never triggered. Verified against real Electron 43.1.0 on macOS 26.3.1 (Darwin 25.3.0): the renderer sees the resize and relayouts, the native frame is untouched, the viewport and devicePixelRatio restore exactly across zoom levels, overlapping calls collapse to one cycle, and a 1px delta never crosses a terminal cell boundary so no pane reports new geometry (no SIGWINCH to running shells). Also close two gaps in the surrounding code: - the pre-Tahoe size jiggle now clears its WeakSet latch in a finally block, so a throwing setSize can no longer suppress every later repaint for that window - cover powerMonitor 'resume' under the Tahoe guard, the other AppKit dispatch context implicated in the freeze --- src/main/window/createMainWindow.test.ts | 82 ++++++++++- src/main/window/createMainWindow.ts | 29 +++- .../window/renderer-viewport-reflow.test.ts | 138 ++++++++++++++++++ src/main/window/renderer-viewport-reflow.ts | 71 +++++++++ 4 files changed, 311 insertions(+), 9 deletions(-) create mode 100644 src/main/window/renderer-viewport-reflow.test.ts create mode 100644 src/main/window/renderer-viewport-reflow.ts diff --git a/src/main/window/createMainWindow.test.ts b/src/main/window/createMainWindow.test.ts index 293ad0832ee4..f8f2afc460bc 100644 --- a/src/main/window/createMainWindow.test.ts +++ b/src/main/window/createMainWindow.test.ts @@ -481,7 +481,9 @@ describe('createMainWindow', () => { send: vi.fn(), isDevToolsOpened: vi.fn(), openDevTools: vi.fn(), - closeDevTools: vi.fn() + closeDevTools: vi.fn(), + enableDeviceEmulation: vi.fn(), + disableDeviceEmulation: vi.fn() } const browserWindowInstance = { webContents, @@ -494,6 +496,7 @@ describe('createMainWindow', () => { isMaximized: vi.fn(() => false), isFullScreen: vi.fn(() => false), getSize: vi.fn(() => [1200, 800]), + getContentSize: vi.fn(() => [1200, 800]), setSize: vi.fn(), maximize: vi.fn(), show: vi.fn(), @@ -513,6 +516,83 @@ describe('createMainWindow', () => { vi.advanceTimersByTime(300) expect(webContents.invalidate).toHaveBeenCalledTimes(2) expect(browserWindowInstance.setSize).not.toHaveBeenCalled() + + // Why (STA-2383): invalidate repaints but never reflows, so Tahoe still has to recompute the + // dvh root — via the emulated viewport, which leaves the deadlock-prone frame untouched. + expect(webContents.enableDeviceEmulation).toHaveBeenCalledWith({ + screenPosition: 'desktop', + screenSize: { width: 1200, height: 801 }, + viewPosition: { x: 0, y: 0 }, + deviceScaleFactor: 0, + viewSize: { width: 1200, height: 801 }, + scale: 1 + }) + expect(webContents.disableDeviceEmulation).toHaveBeenCalled() + expect(browserWindowInstance.setSize).not.toHaveBeenCalled() + }) + + it('reflows without the size nudge when macOS 26 wakes from sleep', () => { + vi.useFakeTimers() + macosTahoeMock.value = true + const windowHandlers = new Map void)[]>() + const webContents = { + on: vi.fn(), + setZoomLevel: vi.fn(), + setBackgroundThrottling: vi.fn(), + invalidate: vi.fn(), + isDestroyed: vi.fn(() => false), + setWindowOpenHandler: vi.fn(), + send: vi.fn(), + isDevToolsOpened: vi.fn(), + openDevTools: vi.fn(), + closeDevTools: vi.fn(), + enableDeviceEmulation: vi.fn(), + disableDeviceEmulation: vi.fn() + } + const browserWindowInstance = { + webContents, + on: vi.fn((event: string, handler: (...args: any[]) => void) => { + const handlers = windowHandlers.get(event) ?? [] + handlers.push(handler) + windowHandlers.set(event, handlers) + }), + isDestroyed: vi.fn(() => false), + isMaximized: vi.fn(() => false), + isFullScreen: vi.fn(() => false), + getSize: vi.fn(() => [1200, 800]), + getContentSize: vi.fn(() => [1200, 800]), + setSize: vi.fn(), + maximize: vi.fn(), + show: vi.fn(), + loadFile: vi.fn(), + loadURL: vi.fn() + } + browserWindowMock.mockImplementation(function () { + return browserWindowInstance + }) + + withPlatform('darwin', () => createMainWindow(null)) + + // Why: 'resume' is the other AppKit dispatch context implicated in the 109-minute freeze, + // so it must take the frame-free path too — not just show/restore. + const resumeHandler = powerMonitorOnMock.mock.calls.find( + ([event]) => event === 'resume' + )?.[1] as (() => void) | undefined + expect(resumeHandler).toBeDefined() + resumeHandler?.() + + expect(webContents.invalidate).toHaveBeenCalled() + vi.advanceTimersByTime(300) + expect(browserWindowInstance.setSize).not.toHaveBeenCalled() + expect(webContents.enableDeviceEmulation).toHaveBeenCalledWith({ + screenPosition: 'desktop', + screenSize: { width: 1200, height: 801 }, + viewPosition: { x: 0, y: 0 }, + deviceScaleFactor: 0, + viewSize: { width: 1200, height: 801 }, + scale: 1 + }) + expect(webContents.disableDeviceEmulation).toHaveBeenCalled() }) it('supports all minus key variants for terminal zoom out', () => { diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index f357cdc7fb02..011466ccd574 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -49,6 +49,7 @@ import { rectHasVisibleAreaOnAnyDisplay } from './window-bounds-validation' import { closeDashboardPopout } from './dashboard-popout-window' import { installPrivilegedWindowNavigationPolicy } from './privileged-window-navigation' import { isMacosTahoeOrNewer } from './macos-tahoe-release' +import { reflowRendererViewport } from './renderer-viewport-reflow' // Why: show/restore/resume can overlap before the size nudge resets; never capture the temporary width as the next baseline. const activeRepaintJiggles = new WeakSet() @@ -63,8 +64,10 @@ function forceRepaint(window: BrowserWindow): void { if (window.isMaximized() || window.isFullScreen() || activeRepaintJiggles.has(window)) { return } - // Why: macOS 26 scene-backed windows can deadlock the main thread on re-entrant frame updates; invalidate alone recovers the compositor there. + // Why: macOS 26 scene-backed windows deadlock the main thread on frame mutation, but invalidate + // alone never reflows the dvh root (STA-2383); emulation reflows without touching the frame. if (isMacosTahoeOrNewer()) { + reflowRendererViewport(window) return } activeRepaintJiggles.add(window) @@ -75,16 +78,26 @@ function forceRepaint(window: BrowserWindow): void { return } const [width, height] = window.getSize() - window.setSize(width + 1, height) + // Why: if the nudge throws mid-flight the WeakSet entry must still clear, or this window + // never repaints again. + try { + window.setSize(width + 1, height) + } catch { + activeRepaintJiggles.delete(window) + return + } setTimeout(() => { - if (!window.isDestroyed()) { - const [currentWidth, currentHeight] = window.getSize() - // Why: a real user resize during the jiggle owns the final bounds. - if (currentWidth === width + 1 && currentHeight === height) { - window.setSize(width, height) + try { + if (!window.isDestroyed()) { + const [currentWidth, currentHeight] = window.getSize() + // Why: a real user resize during the jiggle owns the final bounds. + if (currentWidth === width + 1 && currentHeight === height) { + window.setSize(width, height) + } } + } finally { + activeRepaintJiggles.delete(window) } - activeRepaintJiggles.delete(window) }, 32) }, 0) } diff --git a/src/main/window/renderer-viewport-reflow.test.ts b/src/main/window/renderer-viewport-reflow.test.ts new file mode 100644 index 000000000000..3c88b182792c --- /dev/null +++ b/src/main/window/renderer-viewport-reflow.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' +import type { BrowserWindow } from 'electron' +import { reflowRendererViewport, VIEWPORT_REFLOW_SETTLE_MS } from './renderer-viewport-reflow' + +function createWindow(overrides: Record = {}): BrowserWindow { + const webContents = { + isDestroyed: vi.fn(() => false), + enableDeviceEmulation: vi.fn(), + disableDeviceEmulation: vi.fn() + } + return { + webContents, + isDestroyed: vi.fn(() => false), + getContentSize: vi.fn(() => [1200, 800]), + setSize: vi.fn(), + setBounds: vi.fn(), + ...overrides + } as unknown as BrowserWindow +} + +describe('reflowRendererViewport', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('never mutates the native window frame', () => { + const window = createWindow() + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.setSize).not.toHaveBeenCalled() + expect(window.setBounds).not.toHaveBeenCalled() + }) + + it('defers the emulation off the caller stack, then restores the real viewport', () => { + const window = createWindow() + reflowRendererViewport(window) + // Why: nothing may run while AppKit's callout frame is still on the stack. + expect(window.webContents.enableDeviceEmulation).not.toHaveBeenCalled() + + vi.advanceTimersByTime(0) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledWith({ + screenPosition: 'desktop', + screenSize: { width: 1200, height: 801 }, + viewPosition: { x: 0, y: 0 }, + deviceScaleFactor: 0, + viewSize: { width: 1200, height: 801 }, + scale: 1 + }) + expect(window.webContents.disableDeviceEmulation).not.toHaveBeenCalled() + + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS) + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(1) + }) + + it('collapses a burst of reveals into one emulation cycle', () => { + const window = createWindow() + for (let i = 0; i < 5; i += 1) { + reflowRendererViewport(window) + } + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(1) + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(1) + }) + + it('re-arms once the cycle finishes', () => { + const window = createWindow() + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(2) + }) + + it('skips a window destroyed before the deferred turn runs', () => { + const window = createWindow() + reflowRendererViewport(window) + vi.mocked(window.isDestroyed).mockReturnValue(true) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).not.toHaveBeenCalled() + }) + + it('skips a webContents destroyed before the deferred turn runs', () => { + const window = createWindow() + reflowRendererViewport(window) + vi.mocked(window.webContents.isDestroyed).mockReturnValue(true) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).not.toHaveBeenCalled() + }) + + it('does not leave emulation on when the window dies mid-cycle', () => { + const window = createWindow() + reflowRendererViewport(window) + vi.advanceTimersByTime(0) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(1) + + vi.mocked(window.isDestroyed).mockReturnValue(true) + expect(() => vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS)).not.toThrow() + expect(window.webContents.disableDeviceEmulation).not.toHaveBeenCalled() + + // Why: a stuck latch would silently disable every later reflow for this window. + vi.mocked(window.isDestroyed).mockReturnValue(false) + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) + }) + + it('recovers the latch when enabling emulation throws', () => { + const window = createWindow() + vi.mocked(window.webContents.enableDeviceEmulation).mockImplementationOnce(() => { + throw new Error('Object has been destroyed') + }) + reflowRendererViewport(window) + expect(() => vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1)).not.toThrow() + // Why: nothing was applied, so no restore should be attempted. + expect(window.webContents.disableDeviceEmulation).not.toHaveBeenCalled() + + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) + }) + + it('recovers the latch when disabling emulation throws', () => { + const window = createWindow() + vi.mocked(window.webContents.disableDeviceEmulation).mockImplementationOnce(() => { + throw new Error('Object has been destroyed') + }) + reflowRendererViewport(window) + expect(() => vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1)).not.toThrow() + + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/window/renderer-viewport-reflow.ts b/src/main/window/renderer-viewport-reflow.ts new file mode 100644 index 000000000000..5654421585a7 --- /dev/null +++ b/src/main/window/renderer-viewport-reflow.ts @@ -0,0 +1,71 @@ +import type { BrowserWindow } from 'electron' + +// Why: long enough for the emulated viewport to reach the renderer and lay out, short enough +// that a user never sees the 1px overshoot. +export const VIEWPORT_REFLOW_SETTLE_MS = 32 + +// Why: overlapping reveals must not stack emulation calls; the outer one owns the restore. +const activeViewportReflows = new WeakSet() + +function isWindowGone(window: BrowserWindow): boolean { + return window.isDestroyed() || window.webContents.isDestroyed() +} + +/** + * Force the renderer to recompute its viewport without touching the native window frame. + * + * Why: `webContents.invalidate()` repaints but never reflows, so a stale `dvh` root keeps the + * status bar clipped off-screen (STA-2383). The frame jiggle that used to fix that mutates + * NSWindow, which self-deadlocks the main thread on macOS 26's scene-backed windows. Device + * emulation drives the same resize through the compositor instead — real reflow, no scene update. + */ +export function reflowRendererViewport(window: BrowserWindow): void { + if (activeViewportReflows.has(window) || isWindowGone(window)) { + return + } + activeViewportReflows.add(window) + // Why: reveal/resume fire from inside AppKit's dispatch; start on a fresh turn so nothing + // native runs while that callout frame is still on the stack. + setTimeout(() => { + if (isWindowGone(window)) { + activeViewportReflows.delete(window) + return + } + let emulating = false + try { + const [width, height] = window.getContentSize() + // Why: emulating the current size is a no-op — the +1 delta is what triggers the reflow. + const viewSize = { width, height: height + 1 } + window.webContents.enableDeviceEmulation({ + screenPosition: 'desktop', + // Why: Electron types every field as required, so the rest carry their documented + // defaults — screenSize is mobile-only, and 0 keeps the real device scale factor. + screenSize: viewSize, + viewPosition: { x: 0, y: 0 }, + deviceScaleFactor: 0, + viewSize, + scale: 1 + }) + emulating = true + } catch { + // Why: a teardown race can destroy the webContents mid-call; nothing was applied. + } + if (!emulating) { + activeViewportReflows.delete(window) + return + } + // Why: emulation must always be undone — leaving it on strands the renderer at the + // overshot viewport for the rest of the window's life. + setTimeout(() => { + try { + if (!isWindowGone(window)) { + window.webContents.disableDeviceEmulation() + } + } catch { + // Why: same teardown race; the emulated viewport dies with the webContents. + } finally { + activeViewportReflows.delete(window) + } + }, VIEWPORT_REFLOW_SETTLE_MS) + }, 0) +} From 321f2cb2c3dc360865b8ab392c4852261a1004c2 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:02:49 -0700 Subject: [PATCH 2/4] fix(tray): keep NSStatusItem scene updates off the AppKit callout stack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The main-window repaint was only one of the two doors into the macOS 26 FrontBoardServices deadlock. Showing or restoring the window calls setTrayAttention(false) straight from the window event handler, and tray.setImage/setToolTip drive an NSStatusItem scene update — the same re-entrant scene mutation from inside AppKit's own dispatch, matching the stackshot in openai/codex#23695. Defer the native mutation to a fresh event-loop turn so the callout frame is vacated first. The attention flag itself still flips synchronously: rapid show/hide would otherwise mis-dedupe against a value that had not landed yet. Bursts collapse to a single repaint, and because the deferred pass reads current module state rather than a captured value, a coalesced schedule can never apply a stale icon. applyTrayImage already no-ops on a destroyed tray, so a repaint still queued when the tray goes away is harmless. --- src/main/appkit-scene-mutation.test.ts | 32 ++++++++++ src/main/appkit-scene-mutation.ts | 6 ++ src/main/tray/system-tray.test.ts | 86 +++++++++++++++++++++++++- src/main/tray/system-tray.ts | 25 +++++++- 4 files changed, 146 insertions(+), 3 deletions(-) create mode 100644 src/main/appkit-scene-mutation.test.ts create mode 100644 src/main/appkit-scene-mutation.ts diff --git a/src/main/appkit-scene-mutation.test.ts b/src/main/appkit-scene-mutation.test.ts new file mode 100644 index 000000000000..7b2f5e5dcb1d --- /dev/null +++ b/src/main/appkit-scene-mutation.test.ts @@ -0,0 +1,32 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { deferAppKitSceneMutation } from './appkit-scene-mutation' + +beforeEach(() => { + vi.useFakeTimers() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('deferAppKitSceneMutation', () => { + it('runs the mutation on a later turn, never inside the caller stack', () => { + const mutate = vi.fn() + + deferAppKitSceneMutation(mutate) + expect(mutate).not.toHaveBeenCalled() + + vi.advanceTimersByTime(0) + expect(mutate).toHaveBeenCalledOnce() + }) + + it('keeps scheduled mutations in call order', () => { + const order: string[] = [] + + deferAppKitSceneMutation(() => order.push('first')) + deferAppKitSceneMutation(() => order.push('second')) + vi.advanceTimersByTime(0) + + expect(order).toEqual(['first', 'second']) + }) +}) diff --git a/src/main/appkit-scene-mutation.ts b/src/main/appkit-scene-mutation.ts new file mode 100644 index 000000000000..dc777ec8623b --- /dev/null +++ b/src/main/appkit-scene-mutation.ts @@ -0,0 +1,6 @@ +// Why: macOS 26 backs AppKit objects (windows, NSStatusItem) with scenes, and a scene +// update sent re-entrantly from inside AppKit's own dispatch self-deadlocks the main +// thread in FrontBoardServices; a fresh event-loop turn vacates that callout frame. +export function deferAppKitSceneMutation(mutate: () => void): void { + setTimeout(mutate, 0) +} diff --git a/src/main/tray/system-tray.test.ts b/src/main/tray/system-tray.test.ts index eff554db8740..2c5c07728822 100644 --- a/src/main/tray/system-tray.test.ts +++ b/src/main/tray/system-tray.test.ts @@ -142,7 +142,14 @@ function builtMenuItems(): MenuItem[] { return menuFromTemplateMock.mock.calls.at(-1)?.[0] as MenuItem[] } +// Why: tray image/tooltip writes are deferred off the caller's stack to keep the +// NSStatusItem scene update out of AppKit's dispatch; run the pending turn. +function flushTraySceneMutation(): void { + vi.advanceTimersByTime(0) +} + beforeEach(() => { + vi.useFakeTimers() trayInstances.length = 0 menuFromTemplateMock.mockClear() composeAttentionMock.mockClear() @@ -180,6 +187,7 @@ beforeEach(() => { afterEach(() => { setPlatform(originalPlatform) + vi.useRealTimers() vi.restoreAllMocks() }) @@ -296,6 +304,7 @@ describe('dev instance indicator', () => { createSystemTray(createOptions({ isDevInstance: true, devInstanceLabel: 'my-branch' })) setTrayAttention(true) + flushTraySceneMutation() expect(tintTemplateMock).toHaveBeenCalledWith(devBadgeImage, false) }) @@ -334,8 +343,10 @@ describe('dev instance indicator', () => { created.setToolTip.mockClear() setTrayAttention(true) + flushTraySceneMutation() expect(created.setToolTip).toHaveBeenCalledWith('Orca DEV (my-branch) - activity waiting') setTrayAttention(false) + flushTraySceneMutation() expect(created.setToolTip).toHaveBeenLastCalledWith('Orca DEV (my-branch)') }) @@ -388,9 +399,11 @@ describe('setTrayAttention', () => { created.setImage.mockClear() setTrayAttention(true) + flushTraySceneMutation() expect(composeAttentionMock).toHaveBeenCalledWith(resizedImage) expect(created.setImage).toHaveBeenCalledWith(attentionImage) setTrayAttention(false) + flushTraySceneMutation() expect(created.setImage).toHaveBeenLastCalledWith(resizedImage) }) @@ -403,6 +416,7 @@ describe('setTrayAttention', () => { created.setToolTip.mockClear() setTrayAttention(true) + flushTraySceneMutation() expect(tintTemplateMock).toHaveBeenCalledWith(baseMacImage, false) expect(composeAttentionMock).toHaveBeenCalledWith(tintedMacImage) // Why: the attention image is rebuilt from 1x pixels, so the @2x @@ -417,6 +431,7 @@ describe('setTrayAttention', () => { expect(created.setToolTip).toHaveBeenCalledWith('Orca - activity waiting') setTrayAttention(false) + flushTraySceneMutation() expect(baseMacImage.setTemplateImage).toHaveBeenLastCalledWith(true) expect(created.setImage).toHaveBeenLastCalledWith(baseMacImage) expect(created.setToolTip).toHaveBeenLastCalledWith('Orca') @@ -427,11 +442,15 @@ describe('setTrayAttention', () => { const { createSystemTray, setTrayAttention } = await loadModule() createSystemTray(createOptions()) setTrayAttention(true) + flushTraySceneMutation() tintTemplateMock.mockClear() nativeThemeMock.shouldUseDarkColors = true themeState.updatedListener?.() + // Why: appearance changes arrive on an AppKit dispatch too, so the recompose defers. + expect(tintTemplateMock).not.toHaveBeenCalled() + flushTraySceneMutation() expect(tintTemplateMock).toHaveBeenCalledWith(baseMacImage, true) }) @@ -453,10 +472,74 @@ describe('setTrayAttention', () => { setTrayAttention(true) setTrayAttention(true) + flushTraySceneMutation() expect(created.setImage).toHaveBeenCalledTimes(1) }) + it('never touches the NSStatusItem scene inside the caller stack', async () => { + setPlatform('darwin') + const { createSystemTray, setTrayAttention } = await loadModule() + createSystemTray(createOptions()) + const created = trayInstances[0] + created.setImage.mockClear() + created.setToolTip.mockClear() + + // Why: show/restore call this from AppKit's window-state dispatch; a scene + // update sent there self-deadlocks the main thread on macOS 26. + setTrayAttention(true) + expect(created.setImage).not.toHaveBeenCalled() + expect(created.setToolTip).not.toHaveBeenCalled() + + flushTraySceneMutation() + expect(created.setImage).toHaveBeenCalledWith(attentionImage) + }) + + it('collapses a burst of toggles into one deferred repaint', async () => { + setPlatform('darwin') + const { createSystemTray, setTrayAttention } = await loadModule() + createSystemTray(createOptions()) + const created = trayInstances[0] + created.setImage.mockClear() + + setTrayAttention(true) + setTrayAttention(false) + setTrayAttention(true) + flushTraySceneMutation() + + expect(created.setImage).toHaveBeenCalledTimes(1) + expect(created.setImage).toHaveBeenCalledWith(attentionImage) + }) + + it('still dedupes after the deferred repaint has run', async () => { + setPlatform('darwin') + const { createSystemTray, setTrayAttention } = await loadModule() + createSystemTray(createOptions()) + const created = trayInstances[0] + created.setImage.mockClear() + + setTrayAttention(true) + flushTraySceneMutation() + setTrayAttention(true) + flushTraySceneMutation() + + expect(created.setImage).toHaveBeenCalledTimes(1) + }) + + it('does not throw when the tray is destroyed before the deferred repaint runs', async () => { + setPlatform('darwin') + const { createSystemTray, destroySystemTray, setTrayAttention } = await loadModule() + createSystemTray(createOptions()) + const created = trayInstances[0] + created.setImage.mockClear() + + setTrayAttention(true) + destroySystemTray() + + expect(() => flushTraySceneMutation()).not.toThrow() + expect(created.setImage).not.toHaveBeenCalled() + }) + it('keeps a pending attention dot across a macOS hide/show toggle', async () => { setPlatform('darwin') const { setMacMenuBarIconVisible, setTrayAttention } = await loadModule() @@ -514,7 +597,8 @@ describe('macOS hardening', () => { throw new Error('native image failure') }) - expect(() => setTrayAttention(true)).not.toThrow() + setTrayAttention(true) + expect(() => flushTraySceneMutation()).not.toThrow() expect(created.setImage).toHaveBeenLastCalledWith(baseMacImage) expect(created.setToolTip).toHaveBeenLastCalledWith('Orca') expect(warn).toHaveBeenCalledWith( diff --git a/src/main/tray/system-tray.ts b/src/main/tray/system-tray.ts index cf5aed13687c..f9d960eef653 100644 --- a/src/main/tray/system-tray.ts +++ b/src/main/tray/system-tray.ts @@ -1,6 +1,7 @@ import { Menu, Tray, nativeImage, nativeTheme, type NativeImage } from 'electron' import menuBarIconPath from '../../../resources/tray/orca-menu-barTemplate.png?asset&asarUnpack' import menuBarIconRetinaPath from '../../../resources/tray/orca-menu-barTemplate@2x.png?asset&asarUnpack' +import { deferAppKitSceneMutation } from '../appkit-scene-mutation' import { createAppIconImage } from '../app-icon' import { translateMain } from '../i18n/main-i18n' import { composeTrayAttentionIcon, tintTrayTemplateForAttention } from './tray-attention-icon' @@ -107,6 +108,23 @@ function applyTrayImage(): void { tray.setImage(attentionActive ? composeTrayAttentionIcon(baseTrayImage) : baseTrayImage) } +// Why: collapse bursts (rapid show/hide) into one repaint; the deferred pass reads +// current module state, so a dropped schedule can never land a stale icon. +let trayImageRepaintPending = false + +// Why: tray.setImage/setToolTip drive an NSStatusItem scene update, which deadlocks +// the main thread when sent from inside an AppKit callout; run it on a fresh turn. +function scheduleTrayImage(): void { + if (trayImageRepaintPending) { + return + } + trayImageRepaintPending = true + deferAppKitSceneMutation(() => { + trayImageRepaintPending = false + applyTrayImage() + }) +} + function createMacMenuBarImage(): NativeImage | null { const image = nativeImage.createFromPath(menuBarIconPath) const { width, height } = image.getSize() @@ -172,7 +190,8 @@ function watchMacAppearance(): void { } nativeThemeUpdatedListener = () => { if (attentionActive) { - applyTrayImage() + // Why: 'updated' fires from AppKit's appearance-change dispatch. + scheduleTrayImage() } } nativeTheme.on('updated', nativeThemeUpdatedListener) @@ -299,8 +318,10 @@ export function setTrayAttention(active: boolean): void { if (attentionActive === active) { return } + // Why: the dedup latch must settle synchronously or rapid show/hide mis-dedupes; + // only the native scene mutation moves off the caller's (AppKit) stack. attentionActive = active - applyTrayImage() + scheduleTrayImage() } /** Destroys the tray icon if present. Safe to call repeatedly or with no tray. */ From 7e995e554a9a73a7dc2482e025a7881c6bba69ec Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:17:29 -0700 Subject: [PATCH 3/4] fix(window): reflow maximized and fullscreen windows on macOS 26 too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The maximized/fullscreen bail-out predates the Tahoe path and exists only to keep the size nudge from resizing a window out of those states. Emulation never touches the frame, so that guard was suppressing the reflow for no reason — and a maximized window strands its dvh layout exactly like a normal one. Run the Tahoe branch before the guard. Verified on macOS 26.3.1 that the emulated viewport reflows a maximized and a fullscreen window while leaving both states intact. --- src/main/window/createMainWindow.test.ts | 52 ++++++++++++++++++++++++ src/main/window/createMainWindow.ts | 8 ++-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/main/window/createMainWindow.test.ts b/src/main/window/createMainWindow.test.ts index f8f2afc460bc..5ea4cad581f8 100644 --- a/src/main/window/createMainWindow.test.ts +++ b/src/main/window/createMainWindow.test.ts @@ -531,6 +531,58 @@ describe('createMainWindow', () => { expect(browserWindowInstance.setSize).not.toHaveBeenCalled() }) + it('still reflows a maximized macOS 26 window, which the size nudge had to skip', () => { + vi.useFakeTimers() + macosTahoeMock.value = true + const windowHandlers = new Map void)[]>() + const webContents = { + on: vi.fn(), + setZoomLevel: vi.fn(), + setBackgroundThrottling: vi.fn(), + invalidate: vi.fn(), + isDestroyed: vi.fn(() => false), + setWindowOpenHandler: vi.fn(), + send: vi.fn(), + isDevToolsOpened: vi.fn(), + openDevTools: vi.fn(), + closeDevTools: vi.fn(), + enableDeviceEmulation: vi.fn(), + disableDeviceEmulation: vi.fn() + } + const browserWindowInstance = { + webContents, + on: vi.fn((event: string, handler: (...args: any[]) => void) => { + const handlers = windowHandlers.get(event) ?? [] + handlers.push(handler) + windowHandlers.set(event, handlers) + }), + isDestroyed: vi.fn(() => false), + // Why: the maximized/fullscreen bail-out only ever protected setSize from un-maximizing + // the window; emulation leaves the frame alone, so the reflow must still happen here. + isMaximized: vi.fn(() => true), + isFullScreen: vi.fn(() => true), + getSize: vi.fn(() => [1200, 800]), + getContentSize: vi.fn(() => [1200, 800]), + setSize: vi.fn(), + maximize: vi.fn(), + show: vi.fn(), + loadFile: vi.fn(), + loadURL: vi.fn() + } + browserWindowMock.mockImplementation(function () { + return browserWindowInstance + }) + + withPlatform('darwin', () => createMainWindow(null)) + + windowHandlers.get('show')?.[0]?.() + vi.advanceTimersByTime(300) + + expect(webContents.enableDeviceEmulation).toHaveBeenCalled() + expect(webContents.disableDeviceEmulation).toHaveBeenCalled() + expect(browserWindowInstance.setSize).not.toHaveBeenCalled() + }) + it('reflows without the size nudge when macOS 26 wakes from sleep', () => { vi.useFakeTimers() macosTahoeMock.value = true diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 011466ccd574..29e92a8de109 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -61,15 +61,17 @@ function forceRepaint(window: BrowserWindow): void { return } window.webContents.invalidate() - if (window.isMaximized() || window.isFullScreen() || activeRepaintJiggles.has(window)) { - return - } // Why: macOS 26 scene-backed windows deadlock the main thread on frame mutation, but invalidate // alone never reflows the dvh root (STA-2383); emulation reflows without touching the frame. + // Runs before the maximized/fullscreen bail-out below, which only exists to protect setSize — + // emulation leaves those states intact, and a maximized window goes stale just the same. if (isMacosTahoeOrNewer()) { reflowRendererViewport(window) return } + if (window.isMaximized() || window.isFullScreen() || activeRepaintJiggles.has(window)) { + return + } activeRepaintJiggles.add(window) // Why: show/restore fire from inside AppKit's window-state dispatch; mutating the frame there re-enters scene handling, so nudge on a fresh turn. setTimeout(() => { From 9a5181b931d92daf5889bced9c98ace7f37f47f2 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:35:25 -0700 Subject: [PATCH 4/4] fix(window): retry the viewport restore instead of stranding the renderer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If disableDeviceEmulation threw while the webContents was still alive, the previous code swallowed the error and cleared the latch anyway, leaving the renderer pinned at the emulated 1px-taller viewport for the rest of the window's life — and letting the next reveal stack a fresh cycle on top of it. Retry the restore on a bounded schedule and hold the latch while a retry is pending. A destroyed webContents still short-circuits, since the emulated viewport dies with it, and the attempt budget keeps a permanently failing restore from pinning the latch forever. --- .../window/renderer-viewport-reflow.test.ts | 64 ++++++++++++++++++- src/main/window/renderer-viewport-reflow.ts | 36 ++++++++--- 2 files changed, 87 insertions(+), 13 deletions(-) diff --git a/src/main/window/renderer-viewport-reflow.test.ts b/src/main/window/renderer-viewport-reflow.test.ts index 3c88b182792c..affe08cfb97d 100644 --- a/src/main/window/renderer-viewport-reflow.test.ts +++ b/src/main/window/renderer-viewport-reflow.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import type { BrowserWindow } from 'electron' -import { reflowRendererViewport, VIEWPORT_REFLOW_SETTLE_MS } from './renderer-viewport-reflow' +import { + reflowRendererViewport, + VIEWPORT_REFLOW_RESTORE_ATTEMPTS, + VIEWPORT_REFLOW_SETTLE_MS +} from './renderer-viewport-reflow' function createWindow(overrides: Record = {}): BrowserWindow { const webContents = { @@ -123,16 +127,70 @@ describe('reflowRendererViewport', () => { expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) }) - it('recovers the latch when disabling emulation throws', () => { + it('retries the restore rather than stranding a live renderer at the overshot viewport', () => { const window = createWindow() vi.mocked(window.webContents.disableDeviceEmulation).mockImplementationOnce(() => { - throw new Error('Object has been destroyed') + throw new Error('transient failure') }) reflowRendererViewport(window) expect(() => vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1)).not.toThrow() + // Why: the webContents is still alive, so the emulated viewport is still applied — giving up + // here would leave the renderer stuck at the overshot height forever. + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(2) + + // Why: the retry succeeded, so the latch is free and later reveals still reflow. + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) + }) + + it('holds the latch while a restore is still being retried', () => { + const window = createWindow() + vi.mocked(window.webContents.disableDeviceEmulation).mockImplementation(() => { + throw new Error('still failing') + }) + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + + // Why: stacking a second emulation over an unrestored viewport would compound the overshoot. + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(1) + }) + + it('stops retrying the restore and re-arms after the attempt budget', () => { + 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(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes( + VIEWPORT_REFLOW_RESTORE_ATTEMPTS + 1 + ) + + // Why: an unbounded retry would pin the latch and silently kill every later reflow. + vi.mocked(window.webContents.disableDeviceEmulation).mockImplementation(() => undefined) reflowRendererViewport(window) vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) expect(window.webContents.enableDeviceEmulation).toHaveBeenCalledTimes(2) }) + + it('abandons the restore once the webContents is gone', () => { + const window = createWindow() + vi.mocked(window.webContents.disableDeviceEmulation).mockImplementation(() => { + throw new Error('always fails') + }) + reflowRendererViewport(window) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS + 1) + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(1) + + // Why: a destroyed renderer takes its emulated viewport with it; retrying is pointless. + vi.mocked(window.webContents.isDestroyed).mockReturnValue(true) + vi.advanceTimersByTime(VIEWPORT_REFLOW_SETTLE_MS * 5) + expect(window.webContents.disableDeviceEmulation).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/main/window/renderer-viewport-reflow.ts b/src/main/window/renderer-viewport-reflow.ts index 5654421585a7..3c518e2bd3f1 100644 --- a/src/main/window/renderer-viewport-reflow.ts +++ b/src/main/window/renderer-viewport-reflow.ts @@ -4,6 +4,10 @@ import type { BrowserWindow } from 'electron' // that a user never sees the 1px overshoot. export const VIEWPORT_REFLOW_SETTLE_MS = 32 +// Why: a restore that keeps failing on a live webContents would loop forever; give up and +// release the latch so a later reveal can try a fresh cycle. +export const VIEWPORT_REFLOW_RESTORE_ATTEMPTS = 3 + // Why: overlapping reveals must not stack emulation calls; the outer one owns the restore. const activeViewportReflows = new WeakSet() @@ -56,16 +60,28 @@ export function reflowRendererViewport(window: BrowserWindow): void { } // Why: emulation must always be undone — leaving it on strands the renderer at the // overshot viewport for the rest of the window's life. - setTimeout(() => { - try { - if (!isWindowGone(window)) { - window.webContents.disableDeviceEmulation() - } - } catch { - // Why: same teardown race; the emulated viewport dies with the webContents. - } finally { + restoreRealViewport(window, 0) + }, 0) +} + +function restoreRealViewport(window: BrowserWindow, attempt: number): void { + setTimeout(() => { + if (isWindowGone(window)) { + // Why: the emulated viewport dies with the webContents, so there is nothing to restore. + activeViewportReflows.delete(window) + return + } + try { + window.webContents.disableDeviceEmulation() + activeViewportReflows.delete(window) + } catch { + // Why: the webContents is still alive, so the renderer is stuck at the overshot viewport; + // keep retrying and hold the latch so no second cycle stacks on the unrestored state. + if (attempt >= VIEWPORT_REFLOW_RESTORE_ATTEMPTS) { activeViewportReflows.delete(window) + return } - }, VIEWPORT_REFLOW_SETTLE_MS) - }, 0) + restoreRealViewport(window, attempt + 1) + } + }, VIEWPORT_REFLOW_SETTLE_MS) }