The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): make the relay delivery deadline outlive the backend ceiling
Max Hsu544ad1aa6141
diff --git a/apps/desktop/src/plugins/hermes-bots/relay-deliver-budget.test.ts b/apps/desktop/src/plugins/hermes-bots/relay-deliver-budget.test.tsnew file mode 100644index 00000000000..186a1f96fa2--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/relay-deliver-budget.test.ts@@ -0,0 +1,60 @@+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'++import { describe, expect, it } from 'vitest'++// #93911 review follow-up: the Desktop deadline for bot_relay.deliver mirrors+// three backend numbers. Nothing in the type system links a TS constant to a+// Python default, so this file is the seam: it reads the backend sources and+// fails when a mirror drifts or the settlement margin stops being positive.+// Without it, raising the backend turn timeout would silently reintroduce+// #93911 — the client giving up before a valid typed settlement arrives.++const relaySource = readFileSync(fileURLToPath(new URL('./relay.ts', import.meta.url)), 'utf8')+const repoRoot = new URL('../../../../../', import.meta.url)+const configDefaults = readFileSync(fileURLToPath(new URL('hermes_cli/config_defaults.py', repoRoot)), 'utf8')+const relayHandler = readFileSync(fileURLToPath(new URL('tui_gateway/methods_bot_relay.py', repoRoot)), 'utf8')++function tsConstant(name: string): number {+ const match = relaySource.match(new RegExp(`const ${name} = ([0-9_]+)`))+ expect(match, `${name} must stay a literal so this test can read it`).toBeTruthy()++ return Number(match![1].replaceAll('_', ''))+}++describe('bot_relay.deliver budget mirrors', () => {+ it('mirrors the backend turn-lock default', () => {+ const lockWaitMatch = configDefaults.match(/"turn_wait_seconds":\s*(\d+)/)++ expect(lockWaitMatch, 'bot_mode.turn_wait_seconds default must exist in config_defaults.py').toBeTruthy()+ expect(tsConstant('RELAY_TURN_LOCK_WAIT_MS')).toBe(Number(lockWaitMatch![1]) * 1000)+ })++ it('mirrors the backend per-attempt turn timeout', () => {+ const attemptTimeouts = [...relayHandler.matchAll(/timeout=(\d+)/g)].map(m => Number(m[1]))++ expect(attemptTimeouts.length, 'expected the attempt and its policy-gated retry').toBeGreaterThanOrEqual(2)+ // Every attempt shares one bound; if they ever diverge, the mirror below is+ // no longer a faithful ceiling and this must be revisited deliberately.+ expect(new Set(attemptTimeouts).size, `attempt timeouts diverged: ${attemptTimeouts}`).toBe(1)+ expect(tsConstant('RELAY_TURN_ATTEMPT_MS')).toBe(attemptTimeouts[0] * 1000)+ expect(tsConstant('RELAY_TURN_MAX_ATTEMPTS')).toBe(attemptTimeouts.length)+ })++ it('keeps the client deadline strictly greater than the backend ceiling', () => {+ const margin = tsConstant('RELAY_DELIVER_SETTLEMENT_MARGIN_MS')++ // Strictly greater, not equal: a backend that answers at its own limit+ // still has to serialize and transport that answer.+ expect(margin, 'settlement margin must be positive').toBeGreaterThan(0)++ // The call site must pass the composed budget, not a bare literal.+ const drain = relaySource.slice(+ relaySource.indexOf('async function drainRelayOutboxes'),+ relaySource.indexOf('export function startBotRelay')+ )++ expect(drain).toMatch(/'bot_relay\.deliver'[\s\S]{0,400}RELAY_DELIVER_TIMEOUT_MS/)+ expect(drain).not.toMatch(/'bot_relay\.deliver'[\s\S]{0,400}\d{6,}/)+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/relay.ts b/apps/desktop/src/plugins/hermes-bots/relay.tsindex a529aa2979e..d3ef91367da 100644--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@ -34,12 +34,32 @@ const RELAY_ROSTER_INTERVAL_MS = 60_000// fresh WebSocket dial + teardown per registered connection every 4s.const RELAY_DRAIN_INTERVAL_MS = 30_000// #93911: a delivered turn runs on the target gateway, so the client must-// outlive the backend's own bound — worst case is the turn lock wait-// (bot_mode.turn_wait_seconds, default 120s) plus a 600s turn, doubled when-// the retry policy grants one bounded re-run (methods_bot_relay.py). Without-// this the call fell to the pool's generic 30s deadline and every long turn-// (Computer Use, deep research) came back as an unclassified failure.-const RELAY_DELIVER_TIMEOUT_MS = 1_320_000+// outlive the backend's own bound. Without this the call fell to the pool's+// generic 30s deadline and every long turn (Computer Use, deep research) came+// back as an unclassified failure.+//+// The backend's MAXIMUM WORK budget is spelled out below. The client deadline+// must be strictly GREATER than it: after those bounded waits the handler still+// has to classify the failure, build and run the retry, classify/serialize the+// terminal result, unwind the temp-file and lock scopes, and get the JSON-RPC+// response back through the event loop. A call that consumes nearly all of the+// work budget would otherwise lose the race to this timer by milliseconds and+// reproduce #93911 at the upper boundary — the backend knowing a typed reason+// while Desktop reports its generic timeout first.+//+// These three are mirrors of backend values, so a change there must not+// silently invalidate this constant: relay-deliver-budget.test.ts reads+// hermes_cli/config_defaults.py and tui_gateway/methods_bot_relay.py and fails+// if the mirrors drift or the margin stops being positive.+const RELAY_TURN_LOCK_WAIT_MS = 120_000 // bot_mode.turn_wait_seconds default+const RELAY_TURN_ATTEMPT_MS = 600_000 // subprocess.run(..., timeout=600)+const RELAY_TURN_MAX_ATTEMPTS = 2 // first attempt + the policy-gated re-run+const RELAY_DELIVER_BACKEND_CEILING_MS =+ RELAY_TURN_LOCK_WAIT_MS + RELAY_TURN_ATTEMPT_MS * RELAY_TURN_MAX_ATTEMPTS+// Settlement + transport headroom on top of the ceiling, so a backend that+// answers at its own limit still wins the race against this timer.+const RELAY_DELIVER_SETTLEMENT_MARGIN_MS = 180_000+const RELAY_DELIVER_TIMEOUT_MS = RELAY_DELIVER_BACKEND_CEILING_MS + RELAY_DELIVER_SETTLEMENT_MARGIN_MS// Push path (#93091): the gateway broadcasts `bot_relay.outbox.pending` when// an envelope lands on disk; a burst of signals inside this window collapses// to ONE drain. The interval poll above stays as the backstop for olderdiff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.tsindex c61127f5f67..e989aa729c6 100644--- a/apps/desktop/src/sdk/profile-routing.test.ts+++ b/apps/desktop/src/sdk/profile-routing.test.ts@@ -362,6 +362,68 @@ describe('connection-aware plugin host APIs', () => {)})+ it('survives a backend that settles at its own ceiling, and only fails past the client deadline', async () => {+ // #93911 review follow-up (adversarial): the failure mode is not "no+ // timeout" but "a timeout equal to the backend's ceiling". Model the+ // documented worst case on a virtual clock — the turn lock wait, a full+ // timed attempt, the policy-gated re-run, and then the settlement the+ // handler still has to serialize and transport — and assert that a+ // deadline set AT the ceiling loses that race while one with margin wins.+ const LOCK_WAIT_MS = 120_000+ const ATTEMPT_MS = 600_000+ const ATTEMPTS = 2+ const CEILING_MS = LOCK_WAIT_MS + ATTEMPT_MS * ATTEMPTS+ const SETTLEMENT_MS = 1_000++ const route = {+ connectionId: 'source-a',+ mode: 'remote' as const,+ profile: 'remote-worker',+ targetProfile: 'backend-worker'+ }++ // A gateway that answers only after the full ceiling plus settlement, and+ // aborts at whatever deadline the caller handed down.+ const backendAtItsLimit = async (+ _connectionId: string,+ _profile: string,+ _method: string,+ _params: Record<string, unknown>,+ timeoutMs?: number+ ) =>+ new Promise((resolve, reject) => {+ setTimeout(() => resolve({ reply: 'delivered', reason: 'ok' }), CEILING_MS + SETTLEMENT_MS)++ if (timeoutMs !== undefined) {+ setTimeout(() => reject(new Error('request timed out')), timeoutMs)+ }+ })++ vi.useFakeTimers()++ try {+ vi.mocked(requestGatewayForAgent).mockImplementation(backendAtItsLimit as never)++ // Deadline exactly at the ceiling: the typed settlement loses the race.+ const atCeiling = host.requestProfile(route, 'bot_relay.deliver', {}, CEILING_MS)+ const atCeilingSettled = expect(atCeiling).rejects.toThrow(/timed out/)+ await vi.advanceTimersByTimeAsync(CEILING_MS + SETTLEMENT_MS)+ await atCeilingSettled++ // Same backend, deadline with settlement margin: the answer gets through.+ const withMargin = host.requestProfile(route, 'bot_relay.deliver', {}, CEILING_MS + SETTLEMENT_MS * 180)+ const withMarginSettled = expect(withMargin).resolves.toEqual({+ reason: 'ok',+ reply: 'delivered'+ })+ await vi.advanceTimersByTimeAsync(CEILING_MS + SETTLEMENT_MS)+ await withMarginSettled+ } finally {+ vi.useRealTimers()+ vi.mocked(requestGatewayForAgent).mockReset()+ }+ })+it('leaves callers that pass no timeout on the pool default', async () => {const route = {connectionId: 'source-a',