hermes-agent/apps/desktop/electron/remote-owner-cache.ts
Brooklyn Nicholson 88f5a5c07c fix(desktop): bound the remote-owner memo in the main process
The #85834 remote-owner memo (`remoteOwnerBySessionId`) only ever
INSERTS: the 30s TTL marks entries stale but never evicts them, so a
long-lived main process kept one Map entry per session id it had ever
resolved a hint-less /api/sessions/:id read for. Session ids churn
through normal use, so this is unbounded growth on the main-process
heap — the half the renderer-side leak fixes (#77311 series) never
touched (#58485).

The memo now lives in `remote-owner-cache.ts` as a pure, injectable
(cache limit / clock / TTL) FIFO-bounded cache — the same shape as
titleCache's bound (500 entries). Survey of the other main.ts
registries named in the issue: titleCache (500 FIFO), hermesLog (300),
recentFileReveals (self-pruning), renderTitleQueue (drained by 2
concurrent 8s-timeout jobs), sshConnections (full lifecycle), and the
baseUrl-keyed caches (gatewayAuthProvidersCache, _nativeTokens — one
entry per configured remote) are all bounded on current main.

Refs #58485
2026-09-29 17:35:16 -05:00

48 lines
1.5 KiB
TypeScript

/**
* Main-process memo: which remote profile owns a session id when the caller gave
* no profile hint (#85834).
*
* #58485: the memo only ever INSERTS — the TTL marks entries stale but never
* evicts — so a long-lived main process kept one entry per session id it had
* ever resolved. That is unbounded growth on the main-process heap (the
* renderer-side leak fixes never touched it). Entries are FIFO-evicted past
* `limit`, the same shape as titleCache's bound.
*/
export interface RemoteOwnerEntry {
at: number
profile: null | string
}
export interface RemoteOwnerCache {
/** Fresh memo for `sessionId`, else null (absent or older than `ttlMs`). */
fresh(sessionId: string): null | RemoteOwnerEntry
/** Record a lookup result, FIFO-evicting the oldest entry past `limit`. */
remember(sessionId: string, profile: null | string): void
/** Test/inspection hook: current size. */
size(): number
}
export function createRemoteOwnerCache({
limit = 500,
now = () => Date.now(),
ttlMs = 30_000
}: { limit?: number; now?: () => number; ttlMs?: number } = {}): RemoteOwnerCache {
const entries = new Map<string, RemoteOwnerEntry>()
return {
fresh(sessionId) {
const cached = entries.get(sessionId)
return cached && now() - cached.at < ttlMs ? cached : null
},
remember(sessionId, profile) {
if (entries.size >= limit) {
entries.delete(entries.keys().next().value)
}
entries.set(sessionId, { at: now(), profile })
},
size: () => entries.size
}
}