The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): defer tray hide and log main-process stalls
brooklyn!da77a7e2e876
diff --git a/apps/desktop/electron/main-process-lag-watchdog.test.ts b/apps/desktop/electron/main-process-lag-watchdog.test.tsnew file mode 100644index 00000000000..f4019bc57ec--- /dev/null+++ b/apps/desktop/electron/main-process-lag-watchdog.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest'++import { createMainProcessLagWatchdog } from './main-process-lag-watchdog'++type TimerCallback = () => void+const TIMER = {} as ReturnType<typeof setInterval>++function harness({ now = 0, cadenceMs = 1_000, thresholdMs = 2_000 } = {}) {+ let clock = now+ let callback: TimerCallback | undefined+ let cleared: unknown+ const logs: string[] = []++ const watchdog = createMainProcessLagWatchdog({+ cadenceMs,+ now: () => clock,+ log: message => logs.push(message),+ setInterval: tick => {+ callback = tick++ return TIMER+ },+ clearInterval: timer => {+ cleared = timer+ },+ thresholdMs+ })++ return {+ watchdog,+ logs,+ tick: (at: number) => {+ clock = at+ callback?.()+ },+ cleared: () => cleared+ }+}++describe('createMainProcessLagWatchdog', () => {+ it('does not log while ticks arrive on their expected cadence', () => {+ const subject = harness()++ subject.watchdog.start()+ subject.tick(1_000)+ subject.tick(2_000)++ expect(subject.logs).toEqual([])+ })++ it('records actionable timing when a main-process tick arrives late', () => {+ const subject = harness()++ subject.watchdog.start()+ subject.tick(3_500)++ expect(subject.logs).toEqual([+ '[diagnostics] main-process event loop lagged 2500ms (expected tick at 1000ms, observed at 3500ms)'+ ])+ })++ it('cleans up its interval and does not log after stop', () => {+ const subject = harness()++ subject.watchdog.start()+ subject.watchdog.stop()+ subject.tick(5_000)++ expect(subject.cleared()).toBe(TIMER)+ expect(subject.logs).toEqual([])+ })++ it('is safe to stop during shutdown before it has started', () => {+ const subject = harness()++ subject.watchdog.stop()+ subject.watchdog.stop()++ expect(subject.cleared()).toBeUndefined()+ })+})diff --git a/apps/desktop/electron/main-process-lag-watchdog.ts b/apps/desktop/electron/main-process-lag-watchdog.tsnew file mode 100644index 00000000000..17725734abf--- /dev/null+++ b/apps/desktop/electron/main-process-lag-watchdog.ts@@ -0,0 +1,65 @@+type IntervalHandle = ReturnType<typeof setInterval>++interface MainProcessLagWatchdogOptions {+ cadenceMs: number+ thresholdMs: number+ now: () => number+ log: (message: string) => void+ setInterval: (callback: () => void, delayMs: number) => IntervalHandle+ clearInterval: (timer: IntervalHandle) => void+}++/**+ * Records delayed main-process timer callbacks after the event loop resumes.+ * It intentionally observes only; a stall must never change window or tray+ * behavior while the application is recovering.+ */+export function createMainProcessLagWatchdog({+ cadenceMs,+ thresholdMs,+ now,+ log,+ setInterval,+ clearInterval+}: MainProcessLagWatchdogOptions) {+ let timer: IntervalHandle | undefined+ let expectedAt = 0++ const tick = () => {+ if (!timer) {+ return+ }++ const observedAt = now()+ const lagMs = Math.max(0, observedAt - expectedAt)++ if (lagMs >= thresholdMs) {+ log(+ `[diagnostics] main-process event loop lagged ${lagMs}ms (expected tick at ${expectedAt}ms, observed at ${observedAt}ms)`+ )+ }++ // Rebase after every callback: one late tick is evidence, not a reason to+ // report the same delay again on every healthy future cadence.+ expectedAt = observedAt + cadenceMs+ }++ return {+ start: () => {+ if (timer) {+ return+ }++ expectedAt = now() + cadenceMs+ timer = setInterval(tick, cadenceMs)+ },+ stop: () => {+ if (!timer) {+ return+ }++ clearInterval(timer)+ timer = undefined+ }+ }+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex bf4bbc67390..840ac592426 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -300,6 +300,7 @@ import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-liimport { localSkinProfileKey, readLocalSkinPayload } from './local-skin'import { ACTIVE_LOG_POLL_MS, planLogRotation, reclaimActiveLogIfOversized } from './log-rotation'import { registerMachineProfile } from './machine-profile'+import { createMainProcessLagWatchdog } from './main-process-lag-watchdog'import { ensureMainWindow } from './main-window-lifecycle'import {assertManagedUpdatePreflightClear,@@ -1904,6 +1905,18 @@ function rememberLog(chunk) {scheduleDesktopLogFlush()}+// Main-process stalls leave renderer-scoped lifecycle logging unable to run.+// When the loop resumes, retain the delayed timer's timing in desktop.log so a+// Windows AppHang report can be correlated without changing tray semantics.+const mainProcessLagWatchdog = createMainProcessLagWatchdog({+ cadenceMs: 1_000,+ thresholdMs: 2_000,+ now: Date.now,+ log: rememberLog,+ setInterval,+ clearInterval+})+installCrashForensics({ flush: flushDesktopLogBufferSync, log: rememberLog })// A rejected loadURL leaves a blank window and, unhandled, no trace anywhere@@ -18024,6 +18037,7 @@ app.whenReady().then(() => {registerPowerResumeListeners()keepAwake.set(readPersistedKeepAwake())void minimizeToTray.start()+ mainProcessLagWatchdog.start()f12Blocked = readPersistedDisableF12()// Seed this before the first window exists: a picker can open before// startHermes() finishes resolving the configured backend.@@ -18223,6 +18237,7 @@ app.on('before-quit', event => {}minimizeToTray.beginQuit()+ mainProcessLagWatchdog.stop()// A detached remote updater can outlive this Electron process. Do not tear// down its SSH observer/restore transaction at the generic SSH shutdowndiff --git a/apps/desktop/electron/minimize-to-tray.test.ts b/apps/desktop/electron/minimize-to-tray.test.tsindex 1c1f174892b..90bd7d735a2 100644--- a/apps/desktop/electron/minimize-to-tray.test.ts+++ b/apps/desktop/electron/minimize-to-tray.test.ts@@ -53,6 +53,7 @@ class Window extends EventEmitter {minimized = falsedestroyed = falseskipped = false+ focused = falsewebContents = { send: vi.fn() }isDestroyed() {return this.destroyed@@ -68,8 +69,16 @@ class Window extends EventEmitter {}hide() {this.visible = false+ this.focused = falsethis.emit('hide')}+ show() {+ this.visible = true+ this.emit('show')+ }+ focus() {+ this.focused = true+ }showInactive() {this.visible = truethis.emit('show')@@ -133,6 +142,68 @@ function setup() {}}+function flushDeferredHide() {+ return new Promise<void>(resolve => setImmediate(resolve))+}++const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')++function setPlatform(platform: string) {+ Object.defineProperty(process, 'platform', { value: platform })+}++function restorePlatform() {+ if (originalPlatform) {+ Object.defineProperty(process, 'platform', originalPlatform)+ }+}++test('tray hide defers past the minimize dispatch (#119252)', async () => {+ const { controller, main } = setup()+ await controller.start()+ await controller.setEnabled(true)++ // Hiding synchronously inside the minimize dispatch wedges the native+ // minimized flag on Windows; hide must run after dispatch returns.+ main.minimize()+ expect(main.visible).toBe(true)+ await flushDeferredHide()+ expect(main.visible).toBe(false)+})++test('Windows restore re-activates the window instead of showInactive (#119252)', async () => {+ setPlatform('win32')++ try {+ const { controller, main } = setup()+ await controller.start()+ await controller.setEnabled(true)++ main.minimize()+ await flushDeferredHide()+ controller.restore()+ expect(main.visible).toBe(true)+ expect(main.minimized).toBe(false)+ expect(main.skipped).toBe(false)+ expect(main.focused).toBe(true)+ } finally {+ restorePlatform()+ }+})++test('a restore before the deferred hide fires cancels the stale hide', async () => {+ const { controller, main } = setup()+ await controller.start()+ await controller.setEnabled(true)++ main.minimize()+ // User restores (taskbar/shortcut) before the deferred hide fires.+ main.restore()+ await flushDeferredHide()+ expect(main.visible).toBe(true)+ expect(main.minimized).toBe(false)+})+test('opt-in minimize and primary Close preserve windows while explicit Quit still exits', async () => {const { controller, main, peer } = setup()expect(await controller.start()).toEqual({ enabled: false, available: false })@@ -142,6 +213,7 @@ test('opt-in minimize and primary Close preserve windows while explicit Quit stiawait native.ipc.get('hermes:minimize-to-tray:set')!(null, true)expect(native.ipc.get('hermes:minimize-to-tray:get')!()).toEqual({ enabled: true, available: true })main.minimize()+ await flushDeferredHide()expect(main.destroyed).toBe(false)expect(main.visible).toBe(false)expect(peer.visible).toBe(true)@@ -151,6 +223,7 @@ test('opt-in minimize and primary Close preserve windows while explicit Quit sti}peer.minimize()+ await flushDeferredHide()expect(peer.visible).toBe(false)if (process.platform === 'darwin') {@@ -173,6 +246,7 @@ test('opt-in minimize and primary Close preserve windows while explicit Quit sti// A cancelled guard doesn't call beginQuit; hide remains enabled.controller.restore()main.minimize()+ await flushDeferredHide()expect(main.destroyed).toBe(false)expect(main.visible).toBe(false)// X/Alt+F4 hides the primary, but an accepted explicit quit closes it.diff --git a/apps/desktop/electron/minimize-to-tray.ts b/apps/desktop/electron/minimize-to-tray.tsindex 7fa99f3943f..2218b0b97b6 100644--- a/apps/desktop/electron/minimize-to-tray.ts+++ b/apps/desktop/electron/minimize-to-tray.ts@@ -89,7 +89,15 @@ export function createMinimizeToTray(options: Options) {win.restore()}- win.showInactive()+ if (process.platform === 'win32') {+ // showInactive() never activates the window. A restored-but-inactive+ // window can come back painted yet dead to input (AppHangB1, #119252),+ // so genuinely activate it like focusWindow in main.ts does.+ win.show()+ win.focus()+ } else {+ win.showInactive()+ }}}@@ -182,6 +190,10 @@ export function createMinimizeToTray(options: Options) {windows.add(win)const hide = () => {+ if (win.isDestroyed()) {+ return false+ }+if (!enabled || !status().available || quitting || options.isQuittingForHandoff()) {return false}@@ -198,7 +210,23 @@ export function createMinimizeToTray(options: Options) {return true}- win.on('minimize', hide)+ // Hide past the native minimize dispatch, not inside it: hiding+ // synchronously here re-enters window-state changes mid-flight and on+ // Windows wedges isMinimized(), so the later restore takes the+ // restore-on-hidden path back to a painted-but-dead window (#119252).+ // Guards are re-evaluated at fire time inside hide(); the close handler+ // below keeps its synchronous hide so preventDefault still works.+ win.on('minimize', () => {+ setImmediate(() => {+ // The user may have restored the window in the meantime (taskbar or+ // shortcut); a stale hide must not snatch it back.+ if (!win.isDestroyed() && !win.isMinimized() && win.isVisible()) {+ return+ }++ hide()+ })+ })if (closeToTray) {win.on('close', event => {