Skip to content

The agent that grows with you

fix(desktop): track plugin gateway listeners in the bundled loader and ctx.onEvent

teknium1ca396e0f7f04
diff --git a/apps/desktop/src/contrib/events.test.ts b/apps/desktop/src/contrib/events.test.ts
deleted file mode 100644
index b3cba02739f..00000000000
--- a/apps/desktop/src/contrib/events.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-
-import { emitGatewayEvent, onGatewayEvent } from './events'
-
-describe('onGatewayEvent', () => {
- it('keeps the legacy direct subscription and disposer behavior outside plugin registration', () => {
- const listener = vi.fn()
- const dispose = onGatewayEvent('gateway.ready', listener)
-
- emitGatewayEvent({ type: 'gateway.ready' } as never)
- expect(listener).toHaveBeenCalledTimes(1)
-
- dispose()
- emitGatewayEvent({ type: 'gateway.ready' } as never)
- expect(listener).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/apps/desktop/src/contrib/plugin.test.ts b/apps/desktop/src/contrib/plugin.test.ts
index 8210f212d1a..9e46b3c9862 100644
--- a/apps/desktop/src/contrib/plugin.test.ts
+++ b/apps/desktop/src/contrib/plugin.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import { dispatchPluginNativeNotification } from '@/store/native-notifications'
+import { emitGatewayEvent } from './events'
import { createPluginContext } from './plugin'
vi.mock('@/store/native-notifications', () => ({ dispatchPluginNativeNotification: vi.fn() }))
@@ -24,6 +25,26 @@ describe('createPluginContext.onDispose', () => {
})
})
+describe('createPluginContext.onEvent', () => {
+ it('retires the gateway listener with the plugin, even when subscribed after register()', () => {
+ // Runtime plugins are re-imported as a fresh module on every hot reload; a
+ // gateway subscription the loader cannot see outlives its incarnation and
+ // one event then fires once per reload (#112366). The ctx door is tracked.
+ const disposers: Array<() => void> = []
+ const ctx = createPluginContext('demo', dispose => disposers.push(dispose))
+ const seen: string[] = []
+
+ // Deliberately outside any loader register() scope — the late-subscription case.
+ ctx.onEvent('gateway.reconnecting', event => seen.push(event.type))
+ emitGatewayEvent({ type: 'gateway.reconnecting', payload: { attempt: 1 } } as never)
+ expect(seen).toEqual(['gateway.reconnecting'])
+
+ disposers.forEach(dispose => dispose())
+ emitGatewayEvent({ type: 'gateway.reconnecting', payload: { attempt: 2 } } as never)
+ expect(seen).toEqual(['gateway.reconnecting'])
+ })
+})
+
describe('createPluginContext.os', () => {
it('dispatches a native notification attributed to the plugin', () => {
const ctx = createPluginContext('demo')
diff --git a/apps/desktop/src/contrib/plugin.ts b/apps/desktop/src/contrib/plugin.ts
index 648f4571184..0953c6816bd 100644
--- a/apps/desktop/src/contrib/plugin.ts
+++ b/apps/desktop/src/contrib/plugin.ts
@@ -17,6 +17,7 @@ import { createPluginI18n, type PluginI18n } from '@/i18n'
import { readKey, writeKey } from '@/lib/storage'
import { dispatchPluginNativeNotification, type PluginNativeNotificationInput } from '@/store/native-notifications'
+import { type GatewayEventListener, onGatewayEvent } from './events'
import { registry } from './registry'
import type { Contribution } from './types'
@@ -83,6 +84,12 @@ export interface PluginContext {
* that aren't contributions or sockets (store subscriptions, timers). Runs
* alongside every other disposer when the plugin deactivates. */
onDispose: (fn: () => void) => void
+ /** Hear the gateway stream by event type (`'*'` = everything). Tracked like
+ * every other registration: unload/reload/disable removes the listener, so
+ * a subscription made after `register()` returns (a timer, a socket
+ * callback) can never outlive the plugin the way a bare `host.onEvent`
+ * there would. */
+ onEvent: (type: string, listener: GatewayEventListener) => () => void
/** REST to this plugin's own backend namespace (`/api/plugins/<id>`); `path`
* is relative ('/board'). The sanctioned door for a plugin that ships a
* `plugin_api.py` — profile-aware, namespace-scoped by construction. Use
@@ -211,6 +218,7 @@ export function createPluginContext(pluginId: string, onDispose?: (dispose: () =
register: c => track(registry.register(scope(c))),
registerMany: cs => track(registry.registerMany(cs.map(scope))),
onDispose: fn => void track(fn),
+ onEvent: (type, listener) => track(onGatewayEvent(type, listener)),
rest: <T>(path: string, opts?: PluginRestOptions) => pluginRest<T>(pluginId, path, opts),
socket: (path, onMessage) => track(pluginSocket(pluginId, path, onMessage)),
os: createPluginOs(pluginId),
diff --git a/apps/desktop/src/contrib/plugins.ts b/apps/desktop/src/contrib/plugins.ts
index 5c1a8fa847d..3708c3b0d0c 100644
--- a/apps/desktop/src/contrib/plugins.ts
+++ b/apps/desktop/src/contrib/plugins.ts
@@ -13,6 +13,7 @@
* — the agent's/user's doors, watched + hot-reloaded by the runtime loader.
*/
+import { trackGatewayEventDisposers } from './events'
import { createPluginContext, type HermesPlugin } from './plugin'
import { pluginActive, publishPlugin } from './plugins-store'
import { watchRuntimePlugins } from './runtime-loader'
@@ -58,7 +59,10 @@ export function discoverBundledPlugins(): void {
disposers = []
try {
- plugin.register(createPluginContext(plugin.id, dispose => disposers.push(dispose)))
+ trackGatewayEventDisposers(
+ dispose => disposers.push(dispose),
+ () => plugin.register(createPluginContext(plugin.id, dispose => disposers.push(dispose)))
+ )
publishPlugin({ ...record, status: 'loaded' })
} catch (error) {
console.error(`[plugins] ${plugin.id} failed to register`, error)
diff --git a/apps/desktop/src/contrib/runtime-loader.test.ts b/apps/desktop/src/contrib/runtime-loader.test.ts
index 68ef06cef9c..6f24058f883 100644
--- a/apps/desktop/src/contrib/runtime-loader.test.ts
+++ b/apps/desktop/src/contrib/runtime-loader.test.ts
@@ -3,8 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { HermesReadDirResult } from '@/global'
import type * as HermesModule from '@/hermes'
-import { $pluginRecords, publishPlugin, setPluginEnabled } from './plugins-store'
import { emitGatewayEvent } from './events'
+import { $pluginRecords, publishPlugin, setPluginEnabled } from './plugins-store'
import { discoverRuntimePlugins, loadRuntimePlugin, unloadRuntimePlugin, watchRuntimePlugins } from './runtime-loader'
// getStatus would supply the connected backend's hermes_home — a REMOTE path in
@@ -354,7 +354,8 @@ describe('plugin source reads (512 KiB preview-cap bug)', () => {
it('disposes runtime host event subscriptions before a hot reload (#112366)', async () => {
const restore = blobToDataUrl()
const marker = '__runtimeEventReloadCount'
- ;(globalThis as unknown as Record<string, number>)[marker] = 0
+ const counters = globalThis as unknown as Record<string, number | undefined>
+ counters[marker] = 0
try {
const source = `
@@ -371,14 +372,14 @@ describe('plugin source reads (512 KiB preview-cap bug)', () => {
await loadRuntimePlugin(source, 'second runtime event registration')
emitGatewayEvent({ type: 'bot_relay.outbox.pending' } as never)
- expect((globalThis as unknown as Record<string, number>)[marker]).toBe(1)
+ expect(counters[marker]).toBe(1)
unloadRuntimePlugin('runtime-event-reload')
emitGatewayEvent({ type: 'bot_relay.outbox.pending' } as never)
- expect((globalThis as unknown as Record<string, number>)[marker]).toBe(1)
+ expect(counters[marker]).toBe(1)
} finally {
unloadRuntimePlugin('runtime-event-reload')
- delete (globalThis as unknown as Record<string, number | undefined>)[marker]
+ delete counters[marker]
restore()
}
})
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index e7ec8c99e2e..d39ce7402b8 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1365,7 +1365,11 @@ export const host = {
/** HEAR the gateway stream (message deltas, session lifecycle, tool
* activity, …) by event type — `'*'` for everything. Returns a disposer.
- * Listeners are isolated; a throw can't affect app dispatch. */
+ * Listeners are isolated; a throw can't affect app dispatch. A subscription
+ * made while your plugin's `register()` runs is retired with the plugin on
+ * unload/reload/disable; one made later (a timer, a socket callback) is
+ * yours to wire to `ctx.onDispose` — or use `ctx.onEvent`, which is
+ * tracked wherever it is called. */
onEvent: onGatewayEvent,
/** Restart the backend gateway (progress surfaces in the core statusbar). */
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 481c40ba590..099c0bf75a6 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -175,6 +175,8 @@ interface PluginContext {
rest: <T>(path: string, opts?: PluginRestOptions) => Promise<T>
/** Live WebSocket to this plugin's own namespace. Returns a disposer. */
socket: (path: string, onMessage: (data: unknown) => void) => () => void
+ /** Gateway event stream by type (`'*'` = all). Tracked: removed on unload/reload/disable. */
+ onEvent: (type: string, listener: (event: GatewayEvent) => void) => () => void
/** The curated OS door: native notification, open-external, reveal-in-file-manager, clipboard. */
os: PluginOs
/** Plugin-scoped JSON persistence (keys live under `hermes.plugin.<id>.`). */
@@ -511,7 +513,9 @@ host.openWorkspace(id, { render, title?, minWidth?, onClose? })
// workspace zone and reveal it; returns a disposer
host.paneVisibility(paneId) // ReadableAtom<boolean> — is a contributed pane
// actually on screen (its zone's active tab)?
-host.onEvent(type, fn) // gateway event stream ('*' = all); returns disposer
+host.onEvent(type, fn) // gateway event stream ('*' = all); returns disposer.
+ // Calls made during register() are retired with the
+ // plugin; elsewhere prefer ctx.onEvent (always tracked)
host.logs(...) // tail an app log file
host.status() // one-shot system status snapshot
host.restartGateway() // restart the backend gateway