Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): bound the pending-rename retry with a per-entry budget (R1-M1)

Diego Zacariasebbbdd3793bd
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
index b0ce37ce7..075d63c2d 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
@@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, waitFor } from '@testing-library/react'
import { parseSessionsListResult } from '../../../../../src/rpcProxyClient'
import type { ChatIndex } from '../../../../../src/types'
+import { MAX_RENAME_SYNC_ATTEMPTS } from '../useChatListController'
import { renderController } from './__fixtures__/controllerHarness'
import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'
@@ -511,3 +512,156 @@ describe('rename pending queue — user-identity teardown (spec 15 §2.5 / R1-H1
expect(titleInList(result.current, 'c1')).toBe('renamed')
})
})
+
+describe('rename pending queue — bounded retry (spec 15 §2.5 / R1-M1)', () => {
+ // R1-M1 repro (fails at the R1-H1 head): a deterministic failure (5xx/501 →
+ // 'network' → offline, or a never-materializing 404) retried on EVERY `online`
+ // event forever. The budget must stop the auto-retry after a bounded number of
+ // attempts while KEEPING the optimistic local title. Assert the observable: the
+ // PATCH count stops growing and the shown title stays put (pr-discipline T4).
+ it('stops PATCHing after a bounded number of failed attempts and keeps the local title', async () => {
+ wireStatefulIndex(clerum, [{ id: 'c1', title: 'old' }])
+ // Deterministic network failure on every attempt → the entry never confirms.
+ clerum.rpc.renameSession.mockRejectedValue(new Error('fetch failed'))
+
+ const { result } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+ // The optimistic title is shown and the first attempt failed (queued offline).
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+
+ // Simulate 12 reconnects. Without a budget each one fires a fresh PATCH.
+ const RECONNECTS = 12
+ for (let i = 0; i < RECONNECTS; i += 1) {
+ await act(async () => {
+ window.dispatchEvent(new Event('online'))
+ await flushMicrotasks()
+ })
+ }
+
+ // Bounded to EXACTLY the budget: 1 rename + 12 online would be 13 unbounded;
+ // the deterministic offline failure caps auto-retries at MAX_RENAME_SYNC_ATTEMPTS.
+ const patchesAfterReconnects = clerum.rpc.renameSession.mock.calls.length
+ expect(patchesAfterReconnects).toBe(MAX_RENAME_SYNC_ATTEMPTS)
+
+ // Further reconnects add NO more PATCHes — the entry is retired.
+ for (let i = 0; i < 5; i += 1) {
+ await act(async () => {
+ window.dispatchEvent(new Event('online'))
+ await flushMicrotasks()
+ })
+ }
+ expect(clerum.rpc.renameSession.mock.calls.length).toBe(patchesAfterReconnects)
+
+ // The optimistic local title is kept (close-by-writing: no rollback).
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ })
+
+ // Happy path F must keep working within the budget: an offline entry that
+ // reconnects and succeeds before the budget is spent still syncs.
+ it('still syncs an offline rename that reconnects within the budget', async () => {
+ wireStatefulIndex(clerum, [{ id: 'c1', title: 'old' }])
+ // First attempt fails offline; the reconnect retry succeeds.
+ clerum.rpc.renameSession
+ .mockRejectedValueOnce(new Error('fetch failed'))
+ .mockResolvedValue({ title: 'renamed' })
+
+ const { result } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ window.dispatchEvent(new Event('online'))
+ await flushMicrotasks()
+ })
+
+ // The reconnect retry ran and confirmed — the title stays and the queue drains.
+ await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2))
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+
+ // A later reconnect does NOT re-PATCH a confirmed (drained) entry.
+ await act(async () => {
+ window.dispatchEvent(new Event('online'))
+ await flushMicrotasks()
+ })
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2)
+ })
+
+ // Regression guard for the budget's first cut (fails at the pre-amend 81f193ab):
+ // a brand-new chat renamed before its first turn 404s while it materializes. The
+ // budget must NOT count those 404s and `online` churn must NOT retire the entry —
+ // once the session materializes in a poll the rename MUST still sync. Asserts the
+ // observable (T4): the PATCH is emitted after materialization and the entry drains.
+ it('a 404-while-materializing rename survives online churn and syncs on the poll', async () => {
+ wireStatefulIndex(clerum, [{ id: 'c1', title: 'old' }])
+ // Session not materialized yet: the poll lists nothing; the first rename 404s,
+ // the retry (once it materializes) succeeds. Churn never calls renameSession
+ // (in-flight is skipped on `online`), so mockRejectedValueOnce cleanly models
+ // "first PATCH 404s, next PATCH 200".
+ clerum.rpc.listSessions.mockResolvedValue(reportedSessions([]))
+ clerum.rpc.renameSession
+ .mockRejectedValueOnce(new Error('Rename session failed (404)'))
+ .mockResolvedValue({ title: 'renamed' })
+
+ const { result, rerender } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+ // Optimistic title shown; the first PATCH 404'd (in-flight, awaiting the session).
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1)
+
+ // Network flapping: more online events than the budget (5). An 'in-flight'
+ // entry must NOT retry on `online` (a 404 is not resolved by reconnecting) and
+ // must NOT be retired by the budget — so no extra PATCH and the entry survives.
+ // Literal count (not MAX_RENAME_SYNC_ATTEMPTS) on purpose: run verbatim against
+ // the pre-fix head this loop must still iterate, so the red is behavioral — the
+ // symbol did not exist there and `NaN` would silently skip the churn (false green).
+ for (let i = 0; i < 8; i += 1) {
+ await act(async () => {
+ window.dispatchEvent(new Event('online'))
+ await flushMicrotasks()
+ })
+ }
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1)
+
+ // The session materializes. Swap in a fresh listSessions source (a new function
+ // ref invalidates useChatStore's TTL catalog cache) that now reports c1, then a
+ // cross-agent poll (agentNames rerender) reports the session present and the
+ // in-flight rename finally syncs.
+ clerum.rpc.listSessions = vi.fn(async () =>
+ reportedSessions([{ chatId: 'c1', title: 'server' }])
+ )
+ await act(async () => {
+ rerender({ agentNames: ['agent-x'] })
+ await flushMicrotasks()
+ })
+ await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2))
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+
+ // The entry drained (confirmed) — a later reconnect does not re-PATCH it.
+ await act(async () => {
+ window.dispatchEvent(new Event('online'))
+ await flushMicrotasks()
+ })
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 8617a8bfb..2620728fe 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -9,6 +9,19 @@ import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } from
const SESSION_CATALOG_PAGE_LIMIT = 50
+// R1-M1: an 'offline' pending rename (a genuine network / 5xx failure) retries on
+// every listSessions poll and every `window 'online'` event. A deterministic 5xx
+// / 501 would otherwise re-issue the PATCH forever, so cap the auto-retries per
+// entry: 5 rides out a transient blip and a few poll cycles before giving up,
+// while keeping the request volume bounded. Only 'offline' failures count toward
+// this budget — a 404 ('in-flight', waiting for the session to materialize) is a
+// wait, not a failure, and is bounded instead by the flush gate (it only retries
+// when a poll reports its session present), so a never-materializing session
+// simply stops PATCHing without ever exhausting a budget. On exhaustion the
+// optimistic local title is KEPT (no rollback, no more PATCH); an explicit fresh
+// user rename replaces the entry and starts a new budget.
+export const MAX_RENAME_SYNC_ATTEMPTS = 5
+
/**
* useChatListController (spec-v2 §4.4) — owns the whole sidebar chat-list
* subsystem extracted from the god-hook:
@@ -190,6 +203,15 @@ export function useChatListController({
// from `state` (which is the durable 'in-flight'/'offline' pending kind):
// this gates re-entrancy so a flush poll never fires a duplicate PATCH.
sending: boolean
+ // R1-M1: count of GENUINE ('offline' network / 5xx) failed sync attempts
+ // for THIS entry (never reset while the entry lives). A 404 ('in-flight')
+ // does NOT increment it — that is a wait for materialization, not a
+ // failure. Drives the retry budget below.
+ failureCount: number
+ // R1-M1: budget exhausted — keep the optimistic local title but stop
+ // auto-retrying on polls/online. Only 'offline' entries can reach this;
+ // a fresh user rename makes a new entry.
+ retriesExhausted: boolean
}
>
>(new Map())
@@ -761,6 +783,8 @@ export function useChatListController({
previousTitle: string
state: PendingRename
sending: boolean
+ failureCount: number
+ retriesExhausted: boolean
}) => {
const key = pendingRenameKey(entry.agentRef, entry.chatId)
// FIX 1: never fire a duplicate PATCH for a key whose entry is already
@@ -800,6 +824,20 @@ export function useChatListController({
// 404 → keep 'in-flight' (retry once the session exists server-side);
// network / 5xx → 'offline' (retry on reconnect). Never rolled back.
entry.state = kind === 'network' ? 'offline' : 'in-flight'
+ // R1-M1: bound the auto-retry, but count ONLY genuine failures (network /
+ // 5xx → 'offline'). A 404 ('in-flight') is not a failure — it is a WAIT
+ // for the session to materialize server-side, and it must survive for as
+ // long as that takes; counting it would retire a legitimate slow-to-
+ // materialize rename before its PATCH could be accepted (a silent rename
+ // loss). On the budget's last genuine failure, stop the entry
+ // auto-retrying on future polls/online while keeping its optimistic title
+ // (case E/F keeps resolving local until a fresh rename replaces it).
+ if (kind === 'network') {
+ entry.failureCount += 1
+ if (entry.failureCount >= MAX_RENAME_SYNC_ATTEMPTS) {
+ entry.retriesExhausted = true
+ }
+ }
} finally {
// Clearing on the entry object is safe even if it was deleted from the
// Map (a superseding rename owns a different object).
@@ -810,10 +848,12 @@ export function useChatListController({
)
/**
- * Retry pending renames (spec 15 §2.5). With `serverChatKeys` (a listSessions
- * poll), retry an 'in-flight' entry only once its session actually appears
- * server-side (the 404 → turn-1 case); 'offline' entries retry unconditionally
- * (the reconnect case). Without keys (a `window 'online'` event) retry all.
+ * Retry pending renames (spec 15 §2.5). An 'in-flight' entry (a 404 awaiting the
+ * session to materialize server-side) is retried ONLY when a listSessions poll
+ * reports its session present (`serverChatKeys` has the key) — a reconnect does
+ * not make the session exist, so a bare `window 'online'` event (no keys) never
+ * retries it. 'offline' entries (a network / 5xx failure) retry unconditionally,
+ * which is exactly the reconnect case.
*/
const flushPendingRenames = useCallback(
async (serverChatKeys?: Set<string>) => {
@@ -821,8 +861,21 @@ export function useChatListController({
// FIX 1: skip a key with a PATCH already in flight (attemptRenameRpc
// guards this too, but skipping avoids spawning a no-op).
if (entry.sending) continue
+ // R1-M1: skip an entry whose retry budget is spent — its optimistic title
+ // stays, but it no longer PATCHes on polls/online. Only 'offline' entries
+ // can ever reach this state (in-flight never counts toward the budget).
+ if (entry.retriesExhausted) continue
const key = pendingRenameKey(entry.agentRef, entry.chatId)
- if (entry.state === 'in-flight' && serverChatKeys && !serverChatKeys.has(key)) continue
+ // An 'in-flight' (404 waiting for materialization) retries ONLY when this
+ // flush is a poll that reports its session present. `online` (no keys) and
+ // a poll that does not list the session both skip it — a 404 is not
+ // resolved by reconnecting, only by the session existing server-side.
+ // Deliberately NOT budgeted: counting the 404 is what silently dropped a
+ // legitimate slow-to-materialize rename. The accepted trade is that a
+ // session which IS listed yet whose rename keeps 404ing (a backend
+ // list-vs-rename inconsistency) re-PATCHes once per poll unbounded — a
+ // pathological, self-resolving state, preferred over dropping the rename.
+ if (entry.state === 'in-flight' && !serverChatKeys?.has(key)) continue
await attemptRenameRpc(entry)
}
},
@@ -860,6 +913,8 @@ export function useChatListController({
previousTitle,
state: 'in-flight' as PendingRename,
sending: false,
+ failureCount: 0,
+ retriesExhausted: false,
}
pendingRenamesRef.current.set(key, entry)
await attemptRenameRpc(entry)