Skip to content

The agent that grows with you

fix(desktop): stop the status-stack poll storming a dead session with 4001s

Justin Johnsonc19849cd02f5
diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
index 93f14c8e52d..27ed53c3422 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx
@@ -21,6 +21,7 @@ import {
dismissBackgroundProcess,
groupStatusItems,
refreshBackgroundProcesses,
+ resetBackgroundPollingGuard,
type StatusGroup,
stopBackgroundProcess
} from '@/store/composer-status'
@@ -105,6 +106,10 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro
// process tool completions) live in use-message-stream.
useEffect(() => {
if (sessionId) {
+ // Opening/rebinding a session is a fresh runtime binding: clear any
+ // gone-latch left by a previous runtime under this id so the poll below
+ // is allowed to run again (see resetBackgroundPollingGuard).
+ resetBackgroundPollingGuard(sessionId)
void refreshBackgroundProcesses(sessionId)
void refreshSessionGoal(sessionId)
}
diff --git a/apps/desktop/src/store/composer-status.test.ts b/apps/desktop/src/store/composer-status.test.ts
index 19373667fe2..65bb0447497 100644
--- a/apps/desktop/src/store/composer-status.test.ts
+++ b/apps/desktop/src/store/composer-status.test.ts
@@ -1,6 +1,14 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { $backgroundStatusBySession, dismissBackgroundProcess, reconcileBackgroundProcesses } from './composer-status'
+import {
+ $backgroundStatusBySession,
+ dismissBackgroundProcess,
+ isSessionGoneForBackgroundPolling,
+ reconcileBackgroundProcesses,
+ refreshBackgroundProcesses,
+ resetBackgroundPollingGuard
+} from './composer-status'
+import { $gateway } from './gateway'
const SID = 'sess-1'
@@ -151,3 +159,107 @@ describe('reconcileBackgroundProcesses', () => {
expect(itemsOf('sess-arm')).toEqual([])
})
})
+
+// ── Dead-session polling guard (#94219 fallout) ──────────────────────────────
+// The status stack polls `process.list` every 5s while a background row is on
+// screen. `process.list` is session-scoped: against a runtime id the gateway no
+// longer holds it returns 4001 "session not found". That failure was swallowed
+// as "transient socket loss", so the poll re-sent the SAME dead id every 5s for
+// the life of the window — 18,614 rejections against a single runtime id in one
+// day on a real machine, and the log line the user reads as "session not found".
+//
+// A gone session is terminal, not transient: stop polling it.
+describe('refreshBackgroundProcesses dead-session guard', () => {
+ beforeEach(() => {
+ $backgroundStatusBySession.set({})
+ resetBackgroundPollingGuard()
+ })
+
+ afterEach(() => {
+ $gateway.set(null as never)
+ resetBackgroundPollingGuard()
+ })
+
+ it('classifies a 4001 session-not-found as gone, and a timeout as transient', () => {
+ expect(isSessionGoneForBackgroundPolling(new Error('session not found'))).toBe(true)
+ expect(isSessionGoneForBackgroundPolling(new Error('4001 session not found'))).toBe(true)
+ expect(isSessionGoneForBackgroundPolling(new Error('Session Not Found'))).toBe(true)
+
+ // Transient failures must NOT latch the guard — the session may still be alive.
+ expect(isSessionGoneForBackgroundPolling(new Error('request timed out after 30s: process.list'))).toBe(false)
+ expect(isSessionGoneForBackgroundPolling(new Error('not connected'))).toBe(false)
+ })
+
+ it('stops re-polling a session after the gateway reports it gone', async () => {
+ const request = vi.fn(async () => {
+ throw new Error('session not found')
+ })
+
+ $gateway.set({ request } as never)
+
+ // First poll discovers the session is gone.
+ await refreshBackgroundProcesses(SID)
+ expect(request).toHaveBeenCalledTimes(1)
+
+ // Every subsequent tick must be suppressed. Before the fix these all went
+ // to the wire and each produced another gateway-side 4001.
+ await refreshBackgroundProcesses(SID)
+ await refreshBackgroundProcesses(SID)
+ await refreshBackgroundProcesses(SID)
+
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps polling after a transient failure', async () => {
+ const request = vi.fn(async () => {
+ throw new Error('request timed out after 30s: process.list')
+ })
+
+ $gateway.set({ request } as never)
+
+ await refreshBackgroundProcesses(SID)
+ await refreshBackgroundProcesses(SID)
+
+ // A timeout is not proof of death — the poll must retry.
+ expect(request).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not suppress a different, healthy session', async () => {
+ const request = vi.fn(async (_method: string, params?: Record<string, unknown>) => {
+ if (params?.session_id === SID) {
+ throw new Error('session not found')
+ }
+
+ return { processes: [] }
+ })
+
+ $gateway.set({ request } as never)
+
+ await refreshBackgroundProcesses(SID)
+ await refreshBackgroundProcesses(SID)
+ await refreshBackgroundProcesses('sess-healthy')
+ await refreshBackgroundProcesses('sess-healthy')
+
+ const targets = request.mock.calls.map(c => (c[1] as { session_id?: string } | undefined)?.session_id)
+ expect(targets.filter(t => t === SID)).toHaveLength(1)
+ expect(targets.filter(t => t === 'sess-healthy')).toHaveLength(2)
+ })
+
+ it('resumes polling a session that comes back (guard cleared on rebind)', async () => {
+ const request = vi.fn(async () => {
+ throw new Error('session not found')
+ })
+
+ $gateway.set({ request } as never)
+
+ await refreshBackgroundProcesses(SID)
+ await refreshBackgroundProcesses(SID)
+ expect(request).toHaveBeenCalledTimes(1)
+
+ // A fresh runtime bound to this session id clears the guard.
+ resetBackgroundPollingGuard(SID)
+ await refreshBackgroundProcesses(SID)
+
+ expect(request).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/apps/desktop/src/store/composer-status.ts b/apps/desktop/src/store/composer-status.ts
index c7d6f07102b..4b627fe73fb 100644
--- a/apps/desktop/src/store/composer-status.ts
+++ b/apps/desktop/src/store/composer-status.ts
@@ -377,11 +377,42 @@ export function reconcileBackgroundProcesses(sid: string, procs: GatewayProcessE
writeBackground(sid, next)
}
+/** Session ids the gateway has told us are gone. A session-scoped RPC against a
+ * runtime the gateway no longer holds fails 4001 "session not found" — a
+ * TERMINAL condition, not the transient socket loss the catch below assumes.
+ *
+ * The status stack re-polls `process.list` every 5s while a running row is on
+ * screen, so treating 4001 as transient meant re-sending the same dead id
+ * forever: one runtime id accumulated 18,614 gateway rejections in a single day
+ * (#94219 fallout). Latch the id here and skip it until something rebinds it. */
+const goneSessions = new Set<string>()
+
+/** A gone session is unrecoverable for THIS runtime id; a timeout or transport
+ * blip is not. Only the former may stop the poll — misclassifying a transient
+ * failure would silently freeze the status stack on a healthy session. */
+export function isSessionGoneForBackgroundPolling(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error ?? '')
+
+ return /session not found/i.test(message)
+}
+
+/** Clear the gone-latch. Called with a session id when a fresh runtime binds to
+ * it (so polling resumes), or with no argument to reset everything (tests). */
+export function resetBackgroundPollingGuard(sid?: string): void {
+ if (sid) {
+ goneSessions.delete(sid)
+
+ return
+ }
+
+ goneSessions.clear()
+}
+
/** Pull the session's live process snapshot from the gateway. */
export async function refreshBackgroundProcesses(sid: string): Promise<void> {
const gateway = $gateway.get()
- if (!sid || !gateway) {
+ if (!sid || !gateway || goneSessions.has(sid)) {
return
}
@@ -389,7 +420,15 @@ export async function refreshBackgroundProcesses(sid: string): Promise<void> {
const result = await gateway.request<{ processes?: GatewayProcessEntry[] }>('process.list', { session_id: sid })
reconcileBackgroundProcesses(sid, result?.processes ?? [])
- } catch {
+ } catch (error) {
+ // A gone session never comes back under this runtime id: stop polling it,
+ // or the 5s timer hammers the gateway with 4001s for the window's lifetime.
+ if (isSessionGoneForBackgroundPolling(error)) {
+ goneSessions.add(sid)
+
+ return
+ }
+
// Transient socket loss — the next trigger (event or poll) retries.
}
}
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index c3f13dcb053..64d9157c166 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -372,6 +372,13 @@ def test_prompt_submit_unknown_session_logs_warning(caplog):
"session-scoped RPC rejected" in rec.message and "gone-sid" in rec.message
for rec in caplog.records
)
+ # The method name must be in the line. Without it this warning cannot
+ # identify WHICH client call is looping on a stale runtime id — the gap
+ # that made a 5s `process.list` poll storm (18,614 rejections against one
+ # id) unattributable from the logs alone.
+ assert any(
+ "method=prompt.submit" in rec.message for rec in caplog.records
+ )
def test_prompt_submit_fails_open_inline_when_compute_host_dispatch_breaks(monkeypatch):
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index beff50c2564..3fd2ba9226f 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -384,6 +384,16 @@ _current_runtime_session_record: contextvars.ContextVar[dict | None] = (
contextvars.ContextVar("hermes_gateway_runtime_session_record", default=None)
)
+# JSON-RPC method being dispatched on this thread/task. Purely diagnostic: the
+# 4001 "session not found" warning below is the only signal a stale-runtime
+# retry loop leaves behind, and without the method name it cannot say WHICH
+# client poll is looping (a 5s `process.list` poll produced 18,614 rejections
+# against one id before the caller could be identified). Never used for
+# authorization — the method string is client-supplied.
+_current_rpc_method: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "hermes_gateway_rpc_method", default=""
+)
+
# Reserve real stdout for JSON-RPC only; redirect Python's stdout to stderr
# so stray print() from libraries/tools becomes harmless gateway.stderr instead
# of corrupting the JSON protocol.
@@ -2444,7 +2454,11 @@ def handle_request(req: dict) -> dict | None:
fn = _methods.get(method)
if not fn:
return _err(rid, -32601, f"unknown method: {method}")
- return fn(rid, params)
+ token = _current_rpc_method.set(method)
+ try:
+ return fn(rid, params)
+ finally:
+ _current_rpc_method.reset(token)
def _current_session_steer_authority(
@@ -2894,8 +2908,9 @@ def _sess_nowait(params, rid):
# report is diagnosable as "request arrived and was rejected" instead of
# "request never arrived" (see #90428).
logger.warning(
- "session-scoped RPC rejected: session_id=%r not in memory "
+ "session-scoped RPC rejected: method=%s session_id=%r not in memory "
"(detached/reaped runtime; client should resume the stored session), rid=%r",
+ _current_rpc_method.get() or "?",
sid,
rid,
)