hermes-agent/apps/desktop/electron/application-menu-startup.ts
teknium1 40c5986d3e fix(desktop): install the macOS application menu after the first window exists
The updater's relaunch of the macOS shell died twice (#115332) with
EXC_BAD_ACCESS inside AppKit's key-equivalent routing: a keystroke landed on
the freshly launched app, AppKit asked the application menu's delegate to
populate, and Electron's delegate crashed because no window existed yet.

main.ts installed our menu inside app.whenReady() before createWindow(), and
Electron installs its own default menu even earlier — at
`will-finish-launching` — whenever the app has not called
Menu.setApplicationMenu before that event. On macOS a later
Menu.setApplicationMenu(null) never removes an installed NSMenu, so the
suppression has to run at module scope.

Now: Menu.setApplicationMenu(null) at module scope suppresses Electron's
default menu, and installApplicationMenuAfterFirstWindow() (new pure helper,
DI-tested) creates the first BrowserWindow and only then installs the real
menu on macOS. Windows/Linux keep shipping without an application menu.

Not live-run on macOS: no macOS runner is available here; the ordering is
proven by the helper's vitest cases and by code-path reading of Electron
40.10.2's lib/browser/init.ts + default-menu.ts.
2026-09-20 12:24:46 -07:00

34 lines
1.4 KiB
TypeScript

/**
* Orders the macOS application menu relative to the first BrowserWindow.
*
* AppKit routes every key equivalent through the installed application
* menu's delegate (`_populateFromDelegateWithEventProvider`), and Electron's
* delegate segfaults when that callback fires before any window exists. The
* updater's relaunch races the user's keystroke against startup, so the shell
* died on both post-update relaunches reported in #115332.
*
* Two facts shape the fix:
* - Electron installs its own default menu at `will-finish-launching` (before
* `ready`) unless `Menu.setApplicationMenu` has already been called, so the
* suppression must run at module scope, not inside `whenReady`.
* - On macOS `Menu.setApplicationMenu(null)` never removes an already
* installed NSMenu; it only suppresses the default when it runs first.
*
* `installApplicationMenuAfterFirstWindow` is the ready-phase half: create the
* first window, then install the menu (macOS only; the other platforms ship
* without an application menu).
*/
export interface ApplicationMenuStartupDeps<TMenu> {
isMac: boolean
buildMenu: () => TMenu
setApplicationMenu: (menu: TMenu | null) => void
createWindow: () => void
}
export function installApplicationMenuAfterFirstWindow<TMenu>(deps: ApplicationMenuStartupDeps<TMenu>): void {
deps.createWindow()
if (deps.isMac) {
deps.setApplicationMenu(deps.buildMenu())
}
}