Skip to content

The agent that grows with you

fix(desktop): break win32 fs.watch event storms by falling back to polling

Austin Pickett3ae62879c32a
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 41ae617cb86..3d38b1a78ac 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -447,6 +447,7 @@ import { readPreUpdateBackupEnabled } from './pre-update-backup-config'
import { capturePreviewContents } from './preview-capture'
import { onPreviewWatchOwnerDestroyed, sendPreviewFileChangedToOwner } from './preview-file-watch'
import { hasClosePreviewFlag, previewGuestInputAction } from './preview-guest-escape'
+import { guardedWatch } from './watch-storm-breaker'
import { PreviewReachRegistry } from './preview-reach'
import {
createPrimaryRemoteConnection,
@@ -6257,28 +6258,45 @@ async function watchPreviewFile(owner, rawUrl) {
// it by whole quit-cycles waiting on a change event that never comes.
const offOwnerDestroyed = onPreviewWatchOwnerDestroyed(owner, () => stopPreviewFileWatch(id))
- const watcher = fs.watch(watchDir, (_eventType, filename) => {
- const changedName = filename ? path.basename(String(filename)) : ''
-
- if (changedName && changedName !== targetName) {
+ const emit = () => {
+ if (!fileExists(filePath)) {
return
}
- if (timer) {
- clearTimeout(timer)
- }
+ sendPreviewFileChangedToOwner(owner, { id, path: filePath, url: pathToFileURL(filePath).toString() }, () =>
+ stopPreviewFileWatch(id)
+ )
+ }
- timer = setTimeout(() => {
- timer = null
+ // guardedWatch: a win32 event storm closes the raw fs.watch and falls back
+ // to a slow stat poll instead of pinning the main thread (#118974).
+ const watcher = guardedWatch({
+ platform: process.platform,
+ watch: listener => fs.watch(watchDir, listener),
+ onEvent: (_eventType, filename) => {
+ const changedName = filename ? path.basename(String(filename)) : ''
- if (!fileExists(filePath)) {
+ if (changedName && changedName !== targetName) {
return
}
- sendPreviewFileChangedToOwner(owner, { id, path: filePath, url: pathToFileURL(filePath).toString() }, () =>
- stopPreviewFileWatch(id)
- )
- }, PREVIEW_WATCH_DEBOUNCE_MS)
+ if (timer) {
+ clearTimeout(timer)
+ }
+
+ timer = setTimeout(() => {
+ timer = null
+ emit()
+ }, PREVIEW_WATCH_DEBOUNCE_MS)
+ },
+ snapshot: () => {
+ const stat = fs.statSync(filePath)
+
+ return `${stat.mtimeMs}:${stat.size}`
+ },
+ onPollChange: emit,
+ onTrip: ({ events, windowMs }) =>
+ console.warn(`[hermes] fs.watch storm on ${watchDir} (${events} events within ${windowMs}ms); polling instead`)
})
previewWatchers.set(id, {
@@ -6345,17 +6363,31 @@ function watchDirectory(owner, rawDir) {
// watch must not keep polling the disk-plugin door until quit.
const offOwnerDestroyed = onPreviewWatchOwnerDestroyed(owner, () => stopPreviewFileWatch(id))
- const watcher = fs.watch(watchDir, () => {
- if (timer) {
- clearTimeout(timer)
- }
+ const emit = () => {
+ sendPreviewFileChangedToOwner(owner, { id, path: watchDir, url: pathToFileURL(watchDir).toString() }, () =>
+ stopPreviewFileWatch(id)
+ )
+ }
- timer = setTimeout(() => {
- timer = null
- sendPreviewFileChangedToOwner(owner, { id, path: watchDir, url: pathToFileURL(watchDir).toString() }, () =>
- stopPreviewFileWatch(id)
- )
- }, PREVIEW_WATCH_DEBOUNCE_MS)
+ // A win32 event storm here pinned a core at 100% (#118974): the breaker
+ // closes the raw watch and falls back to the readdir poll it replaced.
+ const watcher = guardedWatch({
+ platform: process.platform,
+ watch: listener => fs.watch(watchDir, listener),
+ onEvent: () => {
+ if (timer) {
+ clearTimeout(timer)
+ }
+
+ timer = setTimeout(() => {
+ timer = null
+ emit()
+ }, PREVIEW_WATCH_DEBOUNCE_MS)
+ },
+ snapshot: () => fs.readdirSync(watchDir).sort().join('\0'),
+ onPollChange: emit,
+ onTrip: ({ events, windowMs }) =>
+ console.warn(`[hermes] fs.watch storm on ${watchDir} (${events} events within ${windowMs}ms); polling instead`)
})
previewWatchers.set(id, {
diff --git a/apps/desktop/electron/watch-storm-breaker.test.ts b/apps/desktop/electron/watch-storm-breaker.test.ts
new file mode 100644
index 00000000000..6bbd1b4d0c1
--- /dev/null
+++ b/apps/desktop/electron/watch-storm-breaker.test.ts
@@ -0,0 +1,182 @@
+/**
+ * Rate breaker for raw fs.watch handles (#118974): a win32 event storm must
+ * close the watcher and fall back to a slow snapshot poll.
+ */
+
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+
+import {
+ guardedWatch,
+ type GuardedWatchOptions,
+ stormBreakerArmed,
+ WATCH_STORM_MAX_EVENTS,
+ WATCH_STORM_POLL_MS,
+ WATCH_STORM_WINDOW_MS,
+ type WatchListener
+} from './watch-storm-breaker'
+
+function fakeWatcher() {
+ let listener: WatchListener | null = null
+ const close = vi.fn()
+
+ return {
+ close,
+ emit(times = 1, filename = 'x') {
+ for (let i = 0; i < times; i += 1) {
+ listener?.('rename', filename)
+ }
+ },
+ watch: (l: WatchListener) => {
+ listener = l
+
+ return { close }
+ }
+ }
+}
+
+function setup(platform: string, overrides: Partial<GuardedWatchOptions> = {}) {
+ const fw = fakeWatcher()
+ let snap = 'a'
+ const onEvent = vi.fn()
+ const onPollChange = vi.fn()
+ const onTrip = vi.fn()
+
+ const guard = guardedWatch({
+ platform,
+ watch: fw.watch,
+ onEvent,
+ snapshot: () => snap,
+ onPollChange,
+ onTrip,
+ ...overrides
+ })
+
+ return {
+ fw,
+ guard,
+ onEvent,
+ onPollChange,
+ onTrip,
+ setSnap: (s: string) => {
+ snap = s
+ }
+ }
+}
+
+describe('guardedWatch', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ test('arms only on win32', () => {
+ expect(stormBreakerArmed('win32')).toBe(true)
+ expect(stormBreakerArmed('darwin')).toBe(false)
+ expect(stormBreakerArmed('linux')).toBe(false)
+ })
+
+ test('forwards events under the threshold and stays on the watcher', () => {
+ const { fw, guard, onEvent } = setup('win32')
+
+ fw.emit(WATCH_STORM_MAX_EVENTS)
+
+ expect(onEvent).toHaveBeenCalledTimes(WATCH_STORM_MAX_EVENTS)
+ expect(fw.close).not.toHaveBeenCalled()
+ expect(guard.mode()).toBe('watch')
+ })
+
+ test('the window resets, so a steady rate under the threshold never trips', () => {
+ const { fw, guard } = setup('win32')
+
+ for (let i = 0; i < 5; i += 1) {
+ fw.emit(WATCH_STORM_MAX_EVENTS)
+ vi.advanceTimersByTime(WATCH_STORM_WINDOW_MS)
+ }
+
+ expect(guard.mode()).toBe('watch')
+ expect(fw.close).not.toHaveBeenCalled()
+ })
+
+ test('a win32 storm closes the watcher, drops further events, and polls', () => {
+ const { fw, guard, onEvent, onPollChange, onTrip, setSnap } = setup('win32')
+
+ fw.emit(WATCH_STORM_MAX_EVENTS + 50_000)
+
+ expect(fw.close).toHaveBeenCalledTimes(1)
+ expect(guard.mode()).toBe('poll')
+ expect(onTrip).toHaveBeenCalledTimes(1)
+ expect(onEvent).toHaveBeenCalledTimes(WATCH_STORM_MAX_EVENTS)
+
+ // Unchanged snapshot: no change reported.
+ vi.advanceTimersByTime(WATCH_STORM_POLL_MS * 3)
+ expect(onPollChange).not.toHaveBeenCalled()
+
+ // Changed snapshot: reported once per change on the next poll.
+ setSnap('b')
+ vi.advanceTimersByTime(WATCH_STORM_POLL_MS - 1)
+ expect(onPollChange).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(1)
+ expect(onPollChange).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(WATCH_STORM_POLL_MS * 2)
+ expect(onPollChange).toHaveBeenCalledTimes(1)
+ })
+
+ test('the same storm on other platforms is forwarded untouched', () => {
+ const { fw, guard, onEvent, onTrip } = setup('darwin')
+
+ fw.emit(WATCH_STORM_MAX_EVENTS * 3)
+
+ expect(onEvent).toHaveBeenCalledTimes(WATCH_STORM_MAX_EVENTS * 3)
+ expect(fw.close).not.toHaveBeenCalled()
+ expect(onTrip).not.toHaveBeenCalled()
+ expect(guard.mode()).toBe('watch')
+ })
+
+ test('close() stops the poll and is idempotent', () => {
+ const { fw, guard, onPollChange, setSnap } = setup('win32')
+
+ fw.emit(WATCH_STORM_MAX_EVENTS + 1)
+ guard.close()
+ guard.close()
+
+ setSnap('b')
+ vi.advanceTimersByTime(WATCH_STORM_POLL_MS * 3)
+
+ expect(onPollChange).not.toHaveBeenCalled()
+ expect(fw.close).toHaveBeenCalledTimes(1)
+ expect(guard.mode()).toBe('closed')
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ test('close() before a trip closes the watcher once', () => {
+ const { fw, guard } = setup('win32')
+
+ guard.close()
+
+ expect(fw.close).toHaveBeenCalledTimes(1)
+ expect(guard.mode()).toBe('closed')
+ })
+
+ test('a throwing snapshot (target vanished) is treated as a change, not a crash', () => {
+ let gone = false
+
+ const { fw, onPollChange } = setup('win32', {
+ snapshot: () => {
+ if (gone) {
+ throw new Error('ENOENT')
+ }
+
+ return 'a'
+ }
+ })
+
+ fw.emit(WATCH_STORM_MAX_EVENTS + 1)
+ gone = true
+ vi.advanceTimersByTime(WATCH_STORM_POLL_MS)
+
+ expect(onPollChange).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/desktop/electron/watch-storm-breaker.ts b/apps/desktop/electron/watch-storm-breaker.ts
new file mode 100644
index 00000000000..77b5d01eb9c
--- /dev/null
+++ b/apps/desktop/electron/watch-storm-breaker.ts
@@ -0,0 +1,141 @@
+/**
+ * Rate breaker for raw fs.watch handles (#118974).
+ *
+ * On Windows, ReadDirectoryChangesW can flood a single fs.watch handle with
+ * hundreds of thousands of `rename` events per second (observed: 180k/s on
+ * the desktop-plugins dir). The JS debounce in main.ts only guards the IPC
+ * dispatch; libuv still calls the listener for every event, pinning a core
+ * until the watcher is closed.
+ *
+ * guardedWatch counts events per window. Past the threshold it closes the
+ * FSWatcher and falls back to a slow poll of a cheap snapshot (readdir names
+ * or stat), reporting a change only when the snapshot differs — the same
+ * shape as the 5s readdir poll the directory watch replaced. The breaker is
+ * armed on win32 only: that is where the storm happens, and elsewhere a
+ * legitimate burst would needlessly demote a watch to polling.
+ */
+
+export const WATCH_STORM_MAX_EVENTS = 1000
+export const WATCH_STORM_WINDOW_MS = 1000
+export const WATCH_STORM_POLL_MS = 5000
+
+export type WatchListener = (eventType: string, filename: string | Buffer | null) => void
+
+export interface ClosableWatcher {
+ close(): void
+}
+
+export interface GuardedWatchOptions {
+ /** Platform as data (process.platform in production) so tests can pick. */
+ platform: string
+ /** Create the underlying watcher (fs.watch in production). */
+ watch: (listener: WatchListener) => ClosableWatcher
+ /** Forwarded for every event while in watch mode. */
+ onEvent: WatchListener
+ /** Cheap fingerprint of the watched target, compared between polls. */
+ snapshot: () => string
+ /** Called in poll mode when the snapshot changed since the last poll. */
+ onPollChange: () => void
+ /** Called once when the breaker trips (logging). */
+ onTrip?: (info: { events: number; windowMs: number }) => void
+ now?: () => number
+ setInterval?: (fn: () => void, ms: number) => unknown
+ clearInterval?: (handle: unknown) => void
+ maxEvents?: number
+ windowMs?: number
+ pollMs?: number
+}
+
+export interface GuardedWatch {
+ close(): void
+ mode(): 'watch' | 'poll' | 'closed'
+}
+
+export function stormBreakerArmed(platform: string): boolean {
+ return platform === 'win32'
+}
+
+function safeSnapshot(snapshot: () => string): string {
+ try {
+ return snapshot()
+ } catch {
+ return ''
+ }
+}
+
+export function guardedWatch(options: GuardedWatchOptions): GuardedWatch {
+ const now = options.now ?? Date.now
+ const startInterval = options.setInterval ?? ((fn, ms) => setInterval(fn, ms))
+ const stopInterval = options.clearInterval ?? (handle => clearInterval(handle as ReturnType<typeof setInterval>))
+ const maxEvents = options.maxEvents ?? WATCH_STORM_MAX_EVENTS
+ const windowMs = options.windowMs ?? WATCH_STORM_WINDOW_MS
+ const pollMs = options.pollMs ?? WATCH_STORM_POLL_MS
+ const armed = stormBreakerArmed(options.platform)
+
+ let state: 'watch' | 'poll' | 'closed' = 'watch'
+ let windowStart = now()
+ let count = 0
+ let pollHandle: unknown = null
+ let watcher: ClosableWatcher | null = null
+
+ const trip = () => {
+ state = 'poll'
+ watcher?.close()
+ watcher = null
+ options.onTrip?.({ events: count, windowMs })
+
+ let last = safeSnapshot(options.snapshot)
+
+ pollHandle = startInterval(() => {
+ const next = safeSnapshot(options.snapshot)
+
+ if (next !== last) {
+ last = next
+ options.onPollChange()
+ }
+ }, pollMs)
+ }
+
+ watcher = options.watch((eventType, filename) => {
+ if (state !== 'watch') {
+ return
+ }
+
+ if (armed) {
+ const t = now()
+
+ if (t - windowStart >= windowMs) {
+ windowStart = t
+ count = 0
+ }
+
+ count += 1
+
+ if (count > maxEvents) {
+ trip()
+
+ return
+ }
+ }
+
+ options.onEvent(eventType, filename)
+ })
+
+ return {
+ close() {
+ if (state === 'closed') {
+ return
+ }
+
+ state = 'closed'
+ watcher?.close()
+ watcher = null
+
+ if (pollHandle !== null) {
+ stopInterval(pollHandle)
+ pollHandle = null
+ }
+ },
+ mode: () => state
+ }
+}