Skip to content

The agent that grows with you

fix(desktop): bound the two bot-rail caches that grew for the window's life

Brooklyn Nicholson716564531b80
diff --git a/apps/desktop/src/plugins/hermes-bots/pet.test.tsx b/apps/desktop/src/plugins/hermes-bots/pet.test.tsx
index f12c7f6ab3a..6e913cb28b0 100644
--- a/apps/desktop/src/plugins/hermes-bots/pet.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/pet.test.tsx
@@ -15,8 +15,15 @@
import { render, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-const { hostMock, useQueryMock } = vi.hoisted(() => ({
+const { hostMock, UnboundedCache, useQueryMock } = vi.hoisted(() => ({
hostMock: { notify: vi.fn(), request: vi.fn() },
+ // Stand-in for the SDK's LruCache. Its ceiling has its own unit test and no
+ // fixture here approaches it, so the double just drops the bound.
+ UnboundedCache: class extends Map {
+ constructor(_max: number) {
+ super()
+ }
+ },
useQueryMock: vi.fn()
}))
@@ -26,6 +33,7 @@ vi.mock('@hermes/plugin-sdk', () => ({
GlyphSpinner: () => <span />,
host: hostMock,
Input: (props: React.ComponentProps<'input'>) => <input {...props} />,
+ LruCache: UnboundedCache,
RowButton: (props: React.ComponentProps<'button'>) => <button {...props} />,
useQuery: useQueryMock
}))
diff --git a/apps/desktop/src/plugins/hermes-bots/pet.tsx b/apps/desktop/src/plugins/hermes-bots/pet.tsx
index a3eb3c4df2e..700e1b98f46 100644
--- a/apps/desktop/src/plugins/hermes-bots/pet.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/pet.tsx
@@ -3,7 +3,7 @@
* frame as the bot's profile picture.
*/
-import { Button, cn, GlyphSpinner, host, Input, RowButton, useQuery } from '@hermes/plugin-sdk'
+import { Button, cn, GlyphSpinner, host, Input, LruCache, RowButton, useQuery } from '@hermes/plugin-sdk'
import { useEffect, useState } from 'react'
import { useBots } from './i18n'
@@ -18,7 +18,12 @@ import { ID } from './shared'
// so opening the tab doesn't fire dozens of 2MB fetches at once.
const PET_FRAME_W = 192
const PET_FRAME_H = 208
-const petFrameCache = new Map<string, Promise<null | string>>()
+// The gallery is 4500+ pets browsed 24 at a time, and each entry is a decoded
+// PNG data URL — an unbounded cache holds every pet the user ever scrolled
+// past for the life of the window. Five pages' worth keeps scrolling back up
+// instant; past that a revisit pays the fetch and crop again.
+const PET_FRAME_CACHE_MAX = 120
+const petFrameCache = new LruCache<string, Promise<null | string>>(PET_FRAME_CACHE_MAX)
let petFetchActive = 0
const petFetchQueue: Array<() => Promise<void>> = []
@@ -194,9 +199,7 @@ export function PetTab({ image, onImage }: PetTabProps) {
return (
<div className="grid w-full gap-2">
- <div className="text-center text-[0.65rem] text-(--ui-text-quaternary)">
- {b.avatar.pickPet}
- </div>
+ <div className="text-center text-[0.65rem] text-(--ui-text-quaternary)">{b.avatar.pickPet}</div>
<Input
className="h-7 text-xs"
onChange={event => {
@@ -224,10 +227,10 @@ export function PetTab({ image, onImage }: PetTabProps) {
<div className="py-3 text-center text-xs text-(--ui-text-quaternary)">No pets match.</div>
) : (
<div
+ className="overflow-y-auto"
onScroll={onScroll}
style={{
- maxHeight: 220,
- overflowY: 'auto'
+ maxHeight: 220
}}
>
<div className="grid grid-cols-3 gap-1.5">
diff --git a/apps/desktop/src/plugins/hermes-bots/relay.test.ts b/apps/desktop/src/plugins/hermes-bots/relay.test.ts
index 9514e0643b8..55ba196b35d 100644
--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts
@@ -26,7 +26,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ProfileRoute } from './types'
-const { clearBotAttentionMock, hostMock, noteBotAttentionMock } = vi.hoisted(() => ({
+const { clearBotAttentionMock, hostMock, noteBotAttentionMock, UnboundedCache } = vi.hoisted(() => ({
clearBotAttentionMock: vi.fn(),
hostMock: {
onEvent: vi.fn(),
@@ -34,10 +34,17 @@ const { clearBotAttentionMock, hostMock, noteBotAttentionMock } = vi.hoisted(()
requestProfile: vi.fn(),
retainProfileSocket: vi.fn()
} as Record<string, unknown>,
- noteBotAttentionMock: vi.fn()
+ noteBotAttentionMock: vi.fn(),
+ // Stand-in for the SDK's LruCache. Its ceiling has its own unit test and no
+ // fixture here approaches it, so the double just drops the bound.
+ UnboundedCache: class extends Map {
+ constructor(_max: number) {
+ super()
+ }
+ }
}))
-vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock }))
+vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock, LruCache: UnboundedCache }))
vi.mock('./data', () => ({
botHandle: (name: string) => (name === 'default' ? 'hermes' : name),
diff --git a/apps/desktop/src/plugins/hermes-bots/relay.ts b/apps/desktop/src/plugins/hermes-bots/relay.ts
index be097b263d5..47ac5aa4d8c 100644
--- a/apps/desktop/src/plugins/hermes-bots/relay.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts
@@ -2,11 +2,12 @@
* The cross-connection bot relay: the Desktop-as-router loops that let a bot
* on one gateway reach a bot on another.
*
- * Every `let` below is module state mutated only by these loops. plugin.tsx
- * drives the two lifecycle doors, startBotRelay / stopBotRelay.
+ * There is one relay per renderer, so its lifecycle lives in the module-scoped
+ * `relay` record below rather than in an atom — no UI reads it. plugin.tsx
+ * drives the two doors, startBotRelay / stopBotRelay.
*/
-import { host } from '@hermes/plugin-sdk'
+import { host, LruCache } from '@hermes/plugin-sdk'
import { botHandle, clearBotAttention, noteBotAttention } from './data'
import type { ProfileRoute, RosterRow } from './types'
@@ -37,17 +38,33 @@ const RELAY_DRAIN_INTERVAL_MS = 30_000
// to ONE drain. The interval poll above stays as the backstop for older
// backends (and connections whose events don't reach the tap).
const RELAY_PUSH_DEBOUNCE_MS = 250
-let relayDisposed = false
-let relayRosterTimer: ReturnType<typeof setInterval> | null = null
-let relayDrainTimer: ReturnType<typeof setInterval> | null = null
-let relayRosterBusy = false
-let relayDrainBusy = false
-let relayPushUnsub: (() => void) | null = null
-let relayPushDebounceTimer: ReturnType<typeof setTimeout> | null = null
-// A push landing while a drain is ALREADY running would be lost forever —
-// the gateway signature is monotone (one event per new envelope, never
-// re-broadcast) — so remember it and re-schedule after the drain finishes.
-let relayDrainRerun = false
+
+/** Everything the two loops mutate. */
+interface RelayLifecycle {
+ disposed: boolean
+ drainBusy: boolean
+ /** A push landing while a drain is ALREADY running would be lost forever —
+ * the gateway signature is monotone (one event per new envelope, never
+ * re-broadcast) — so remember it and re-schedule after the drain finishes. */
+ drainRerun: boolean
+ drainTimer: null | ReturnType<typeof setInterval>
+ pushDebounceTimer: null | ReturnType<typeof setTimeout>
+ pushUnsub: (() => void) | null
+ rosterBusy: boolean
+ rosterTimer: null | ReturnType<typeof setInterval>
+}
+
+const relay: RelayLifecycle = {
+ disposed: false,
+ drainBusy: false,
+ drainRerun: false,
+ drainTimer: null,
+ pushDebounceTimer: null,
+ pushUnsub: null,
+ rosterBusy: false,
+ rosterTimer: null
+}
+
// Relay-route socket retention (#93594): connection id → release fn. While
// the relay is active each registered connection's pooled socket is pinned
// open (host.retainProfileSocket) so drain RPCs reuse ONE persistent
@@ -104,7 +121,7 @@ function syncRelayRetention(connections: RelayConnection[]) {
}
}
- if (relayDisposed) {
+ if (relay.disposed) {
return
}
@@ -190,16 +207,21 @@ async function relayAgentsOn(connection: RelayConnection): Promise<RelayAgentRow
}
/** Last good agent rows per connection id — reused when a fetch blips so a
- * transient failure never reads as "everyone on that machine went away". */
-const relayAgentsCache = new Map<string, RelayAgentRow[]>()
+ * transient failure never reads as "everyone on that machine went away".
+ * The sweep below drops disconnected ids, but only on a cycle that had two
+ * or more connections to relay between; the ceiling is what bounds the rest.
+ * Every live connection is rewritten each cycle, so eviction can only ever
+ * reach ids that stopped being fetched. */
+const RELAY_AGENTS_CACHE_MAX = 32
+const relayAgentsCache = new LruCache<string, RelayAgentRow[]>(RELAY_AGENTS_CACHE_MAX)
/** Push every gateway the union roster of agents on the OTHER connections. */
async function syncRelayRosters() {
- if (relayDisposed || relayRosterBusy) {
+ if (relay.disposed || relay.rosterBusy) {
return
}
- relayRosterBusy = true
+ relay.rosterBusy = true
try {
const connections = await relayConnections()
@@ -256,7 +278,7 @@ async function syncRelayRosters() {
})
)
} finally {
- relayRosterBusy = false
+ relay.rosterBusy = false
}
}
@@ -264,20 +286,20 @@ async function syncRelayRosters() {
* connection's own socket; the reply (or error) is posted back to the
* sender gateway for its waiter. */
async function drainRelayOutboxes() {
- if (relayDisposed) {
+ if (relay.disposed) {
return
}
- if (relayDrainBusy) {
+ if (relay.drainBusy) {
// A push signal raced an in-flight drain. The gateway never re-sends it
// (monotone signature), so without this flag the envelope would wait out
// the full poll interval — exactly the latency the push path removes.
- relayDrainRerun = true
+ relay.drainRerun = true
return
}
- relayDrainBusy = true
+ relay.drainBusy = true
try {
const connections = await relayConnections()
@@ -308,7 +330,7 @@ async function drainRelayOutboxes() {
}
for (const envelope of envelopes) {
- if (relayDisposed) {
+ if (relay.disposed) {
return
}
@@ -372,12 +394,12 @@ async function drainRelayOutboxes() {
}
}
} finally {
- relayDrainBusy = false
+ relay.drainBusy = false
- if (relayDrainRerun && !relayDisposed) {
+ if (relay.drainRerun && !relay.disposed) {
// Envelopes signaled mid-drain: schedule one follow-up pass (debounced)
// instead of leaving them to the interval poll.
- relayDrainRerun = false
+ relay.drainRerun = false
scheduleRelayPushDrain()
}
}
@@ -386,22 +408,22 @@ async function drainRelayOutboxes() {
/** Push-notified drain (#93091): collapse a burst of pending signals into
* one drain call ~RELAY_PUSH_DEBOUNCE_MS after the first signal. */
function scheduleRelayPushDrain() {
- if (relayDisposed || typeof setTimeout !== 'function') {
+ if (relay.disposed || typeof setTimeout !== 'function') {
return
}
- if (relayPushDebounceTimer !== null) {
+ if (relay.pushDebounceTimer !== null) {
return
}
- relayPushDebounceTimer = setTimeout(() => {
- relayPushDebounceTimer = null
+ relay.pushDebounceTimer = setTimeout(() => {
+ relay.pushDebounceTimer = null
void drainRelayOutboxes()
}, RELAY_PUSH_DEBOUNCE_MS)
}
export function startBotRelay() {
- relayDisposed = false
+ relay.disposed = false
// Source-shape test harnesses evaluate plugin.js without DOM timers —
// the relay only runs where a real event loop exists.
@@ -409,55 +431,55 @@ export function startBotRelay() {
return
}
- if (relayRosterTimer === null) {
- relayRosterTimer = setInterval(() => void syncRelayRosters(), RELAY_ROSTER_INTERVAL_MS)
+ if (relay.rosterTimer === null) {
+ relay.rosterTimer = setInterval(() => void syncRelayRosters(), RELAY_ROSTER_INTERVAL_MS)
void syncRelayRosters()
}
- if (relayDrainTimer === null) {
- relayDrainTimer = setInterval(() => void drainRelayOutboxes(), RELAY_DRAIN_INTERVAL_MS)
+ if (relay.drainTimer === null) {
+ relay.drainTimer = setInterval(() => void drainRelayOutboxes(), RELAY_DRAIN_INTERVAL_MS)
}
// Push path: the gateway change watcher broadcasts when an envelope hits
// the outbox; drain immediately (debounced) instead of waiting the poll
// out. Feature-detected — older shells have no host.onEvent — and the 4s
// poll above stays untouched as the backstop either way.
- if (relayPushUnsub === null && typeof host.onEvent === 'function') {
- relayPushUnsub = host.onEvent('bot_relay.outbox.pending', () => scheduleRelayPushDrain())
+ if (relay.pushUnsub === null && typeof host.onEvent === 'function') {
+ relay.pushUnsub = host.onEvent('bot_relay.outbox.pending', () => scheduleRelayPushDrain())
}
}
export function stopBotRelay() {
- relayDisposed = true
+ relay.disposed = true
// A rerun remembered mid-drain must not leak into the next start —
// it would fire one stale drain after restart.
- relayDrainRerun = false
+ relay.drainRerun = false
// Unpin every relay-retained socket (#93594): with the relay stopped the
// pooled entries return to dispose-at-refcount-0 semantics.
releaseRelayRetention()
- if (relayRosterTimer !== null) {
- clearInterval(relayRosterTimer)
- relayRosterTimer = null
+ if (relay.rosterTimer !== null) {
+ clearInterval(relay.rosterTimer)
+ relay.rosterTimer = null
}
- if (relayDrainTimer !== null) {
- clearInterval(relayDrainTimer)
- relayDrainTimer = null
+ if (relay.drainTimer !== null) {
+ clearInterval(relay.drainTimer)
+ relay.drainTimer = null
}
- if (relayPushDebounceTimer !== null) {
- clearTimeout(relayPushDebounceTimer)
- relayPushDebounceTimer = null
+ if (relay.pushDebounceTimer !== null) {
+ clearTimeout(relay.pushDebounceTimer)
+ relay.pushDebounceTimer = null
}
- if (relayPushUnsub !== null) {
+ if (relay.pushUnsub !== null) {
try {
- relayPushUnsub()
+ relay.pushUnsub()
} catch {
// Disposer from an older shell shape — never break teardown.
}
- relayPushUnsub = null
+ relay.pushUnsub = null
}
}