The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): deliver file-watch events to owning window (#108189)
Yida Wenge8c1ce8df290
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex b8a1bc6dac4..0f3ad0c6aa0 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -383,6 +383,10 @@ import { createPortalSession } from './portal-session'import { createKeepAwake } from './power-save'import { readPreUpdateBackupEnabled } from './pre-update-backup-config'import { capturePreviewContents } from './preview-capture'+import {+ onPreviewWatchOwnerDestroyed,+ sendPreviewFileChangedToOwner+} from './preview-file-watch'import { PreviewReachRegistry } from './preview-reach'import {createPrimaryRemoteConnection,@@ -5788,27 +5792,20 @@ async function filePathFromPreviewUrl(rawUrl) {return resolvedPath}-function sendPreviewFileChanged(payload) {- if (!mainWindow || mainWindow.isDestroyed()) {- return- }-- const { webContents } = mainWindow-- if (!webContents || webContents.isDestroyed()) {- return- }-- webContents.send('hermes:preview-file-changed', payload)-}--async function watchPreviewFile(rawUrl) {+async function watchPreviewFile(owner, rawUrl) {const filePath = await filePathFromPreviewUrl(rawUrl)const watchDir = path.dirname(filePath)const targetName = path.basename(filePath)const id = crypto.randomBytes(12).toString('base64url')let timer = null+ // Proactive teardown: the watch must not outlive the window that asked for+ // 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)) : ''@@ -5827,12 +5824,18 @@ async function watchPreviewFile(rawUrl) {return}- sendPreviewFileChanged({ id, path: filePath, url: pathToFileURL(filePath).toString() })+ sendPreviewFileChangedToOwner(+ owner,+ { id, path: filePath, url: pathToFileURL(filePath).toString() },+ () => stopPreviewFileWatch(id)+ )}, PREVIEW_WATCH_DEBOUNCE_MS)})previewWatchers.set(id, {+ owner,close: () => {+ offOwnerDestroyed()if (timer) {clearTimeout(timer)}@@ -5878,7 +5881,7 @@ function requestOptionsWithHeaders(options: any = {}, headers = {}) {* readdir poll. Same registry + change channel as the preview file watchers* (the renderer reconciles on any tick; per-file edits stay on their own* watches), so stopPreviewFileWatch/closePreviewWatchers manage these too. */-function watchDirectory(rawDir) {+function watchDirectory(owner, rawDir) {const watchDir = path.resolve(String(rawDir || ''))if (!fs.existsSync(watchDir) || !fs.statSync(watchDir).isDirectory()) {@@ -5888,6 +5891,13 @@ function watchDirectory(rawDir) {const id = crypto.randomBytes(12).toString('base64url')let timer = null+ // Same proactive teardown as a file watch: a closed window's directory+ // 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)@@ -5895,12 +5905,18 @@ function watchDirectory(rawDir) {timer = setTimeout(() => {timer = null- sendPreviewFileChanged({ id, path: watchDir, url: pathToFileURL(watchDir).toString() })+ sendPreviewFileChangedToOwner(+ owner,+ { id, path: watchDir, url: pathToFileURL(watchDir).toString() },+ () => stopPreviewFileWatch(id)+ )}, PREVIEW_WATCH_DEBOUNCE_MS)})previewWatchers.set(id, {+ owner,close: () => {+ offOwnerDestroyed()if (timer) {clearTimeout(timer)}@@ -16856,9 +16872,13 @@ ipcMain.handle('hermes:normalizePreviewTarget', (_event, target, baseDir) =>normalizePreviewTarget(String(target || ''), baseDir ? String(baseDir) : ''))-ipcMain.handle('hermes:watchPreviewFile', (_event, url) => watchPreviewFile(String(url || '')))+ipcMain.handle('hermes:watchPreviewFile', (event, url) =>+ watchPreviewFile(event.sender, String(url || ''))+)-ipcMain.handle('hermes:watchDirectory', (_event, dir) => watchDirectory(String(dir || '')))+ipcMain.handle('hermes:watchDirectory', (event, dir) =>+ watchDirectory(event.sender, String(dir || ''))+)ipcMain.handle('hermes:stopPreviewFileWatch', (_event, id) => stopPreviewFileWatch(String(id || '')))diff --git a/apps/desktop/electron/preview-file-watch.test.ts b/apps/desktop/electron/preview-file-watch.test.tsnew file mode 100644index 00000000000..ebf3356b504--- /dev/null+++ b/apps/desktop/electron/preview-file-watch.test.ts@@ -0,0 +1,133 @@+/**+ * Unit tests for owner-routed preview/plugin file-watch delivery (#108189).+ * Secondary windows filter by their own watch id, so events must land on the+ * registering WebContents — never the primary alone.+ */++import assert from 'node:assert/strict'++import { describe, test } from 'vitest'++import {+ onPreviewWatchOwnerDestroyed,+ PREVIEW_FILE_CHANGED_CHANNEL,+ type PreviewFileChangedPayload,+ type PreviewWatchOwner,+ sendPreviewFileChangedToOwner+} from './preview-file-watch'++function makeOwner(): PreviewWatchOwner & {+ sends: Array<{ channel: string; payload: unknown }>+ destroy: () => void+ emitDestroyed: () => void+} {+ const sends: Array<{ channel: string; payload: unknown }> = []+ let destroyed = false+ const destroyedListeners = new Set<() => void>()++ return {+ sends,+ isDestroyed: () => destroyed,+ destroy() {+ destroyed = true+ },+ emitDestroyed() {+ for (const listener of destroyedListeners) {+ listener()+ }+ },+ once(event: 'destroyed', listener: () => void) {+ destroyedListeners.add(listener)++ return this+ },+ removeListener(event: 'destroyed', listener: () => void) {+ destroyedListeners.delete(listener)+ },+ send(channel: string, payload: unknown) {+ sends.push({ channel, payload })+ }+ }+}++const payload: PreviewFileChangedPayload = {+ id: 'watch-secondary',+ path: '/tmp/plugin.js',+ url: 'file:///tmp/plugin.js'+}++describe('sendPreviewFileChangedToOwner', () => {+ test('delivers to the owning WebContents, not a different window', () => {+ const owner = makeOwner()+ const other = makeOwner()++ assert.equal(sendPreviewFileChangedToOwner(owner, payload), true)+ assert.deepEqual(owner.sends, [{ channel: PREVIEW_FILE_CHANGED_CHANNEL, payload }])+ assert.deepEqual(other.sends, [])+ })++ test('tears the watch down when the owner is destroyed', () => {+ const owner = makeOwner()+ owner.destroy()+ let tornDown = false++ assert.equal(+ sendPreviewFileChangedToOwner(owner, payload, () => {+ tornDown = true+ }),+ false+ )+ assert.equal(tornDown, true)+ assert.deepEqual(owner.sends, [])+ })++ test('tears the watch down when the owner is missing', () => {+ let tornDown = false++ assert.equal(+ sendPreviewFileChangedToOwner(null, payload, () => {+ tornDown = true+ }),+ false+ )+ assert.equal(tornDown, true)+ })+})++describe('onPreviewWatchOwnerDestroyed', () => {+ test('runs the teardown the moment the owner window is destroyed', () => {+ const owner = makeOwner()+ let tornDown = 0++ onPreviewWatchOwnerDestroyed(owner, () => {+ tornDown += 1+ })++ // No teardown before the window dies, exactly one at destruction.+ assert.equal(tornDown, 0)+ owner.emitDestroyed()+ assert.equal(tornDown, 1)+ })++ test('an explicit watch close detaches the destroyed listener', () => {+ const owner = makeOwner()+ let tornDown = 0++ const off = onPreviewWatchOwnerDestroyed(owner, () => {+ tornDown += 1+ })++ off()+ owner.emitDestroyed()++ // The watch's own close() must not leave a stale teardown armed — and+ // must not resurrect a second one through the same listener.+ assert.equal(tornDown, 0)+ })++ test('tolerates a missing owner without exploding', () => {+ const off = onPreviewWatchOwnerDestroyed(null, () => {})++ assert.equal(off(), undefined)+ })+})diff --git a/apps/desktop/electron/preview-file-watch.ts b/apps/desktop/electron/preview-file-watch.tsnew file mode 100644index 00000000000..a94f09231ba--- /dev/null+++ b/apps/desktop/electron/preview-file-watch.ts@@ -0,0 +1,61 @@+/**+ * Owner-routed delivery for desktop preview/plugin file watches (#108189).+ *+ * Each watch is owned by the WebContents that registered it. Change events+ * must go back to THAT renderer — secondary windows filter+ * `hermes:preview-file-changed` by their own watch id, so delivering only to+ * the main window drops the event.+ */++export const PREVIEW_FILE_CHANGED_CHANNEL = 'hermes:preview-file-changed'++/** The events a watch needs from the WebContents that registered it. */+export type PreviewWatchOwner = Pick<Electron.WebContents, 'isDestroyed' | 'send'> & {+ once(event: 'destroyed', listener: () => void): unknown+ removeListener(event: 'destroyed', listener: () => void): unknown+}++export type PreviewFileChangedPayload = {+ id: string+ path: string+ url: string+}++/**+ * Deliver a change payload to the watch owner. Returns false when the owner+ * is missing or destroyed so callers can tear the watch down.+ */+export function sendPreviewFileChangedToOwner(+ owner: PreviewWatchOwner | null | undefined,+ payload: PreviewFileChangedPayload,+ onDestroyed?: () => void+): boolean {+ if (!owner || owner.isDestroyed()) {+ onDestroyed?.()+ return false+ }++ owner.send(PREVIEW_FILE_CHANGED_CHANNEL, payload)+ return true+}++/**+ * Tear `teardown` down the moment the owner window dies, not at the next+ * (never-arriving) change event: an fs.watch handle for a closed window+ * otherwise lingers until quit. Returns the unsubscribe for the watch's own+ * close().+ */+export function onPreviewWatchOwnerDestroyed(+ owner: PreviewWatchOwner | null | undefined,+ teardown: () => void+): () => void {+ if (!owner || typeof owner.once !== 'function') {+ return () => {}+ }++ owner.once('destroyed', teardown)++ return () => {+ owner.removeListener('destroyed', teardown)+ }+}