fix(status-bar): show live session reset countdown in collapsed usage bar (#5399)

Derive the collapsed session limit label from resetsAt and tick it live via a shared boundary-scheduled countdown clock (no polling). Combines #6252/#6585.

Fixes #5399.

Co-authored-by: gatsby74 <166927047+gatsby74@users.noreply.github.com>
This commit is contained in:
Neil
2026-07-18 15:16:10 -07:00
committed by GitHub
co-authored by gatsby74
parent 4930c87219
commit 4905b78282
6 changed files with 190 additions and 2 deletions
@@ -58,6 +58,7 @@ import {
import { ClaudeIcon, GeminiIcon, MiniMaxIcon, OpenAIIcon, OpenCodeGoIcon } from './icons'
import { AgentIcon } from '@/lib/agent-catalog'
import { formatRateLimitWindowChipLabel } from '@/lib/window-label-formatter'
import { useResetCountdownClock } from '@/hooks/useResetCountdownClock'
import { markLiveCodexSessionsForRestart } from '@/lib/codex-session-restart'
import { UpdateStatusSegment } from './UpdateStatusSegment'
import { isStatusBarItemAvailable } from './status-bar-agent-gating'
@@ -979,12 +980,17 @@ export function InlineUsageBars({
const display = normalizeUsagePercentageDisplay(
useAppStore((state) => state.usagePercentageDisplay)
)
// Why: tick the collapsed session countdown live (matches the popover) via one
// boundary-scheduled clock instead of only refreshing on the usage poll (#5399).
const now = useResetCountdownClock([limits.session?.resetsAt])
const usageWindows = [
limits.session
? {
key: 'session',
used: clampUsedPercent(limits.session.usedPercent),
label: translate('auto.components.status.bar.StatusBar.d79c3362c4', '5h')
// Why: show the live reset countdown (matches the popover); '5h' window
// length only when resetsAt is unknown (#5399).
label: formatRateLimitWindowChipLabel(limits.session, now)
}
: null,
limits.weekly
@@ -71,6 +71,34 @@ describe('InlineUsageBars', () => {
expect(markup).toContain('42% used Fable')
})
it('derives the collapsed session label from resetsAt (#5399)', async () => {
const { InlineUsageBars } = await import('./StatusBar')
const limits = claudeLimits()
// ~1h 20m away; +5s buffer keeps the floor-based formatter at '1h 20m'
// across the few ms between snapshot and render.
limits.session!.resetsAt = Date.now() + 80 * 60_000 + 5_000
const markup = renderToStaticMarkup(<InlineUsageBars limits={limits} isFetching={false} />)
expect(markup).toContain('32% used 1h 20m')
expect(markup).not.toContain('32% used 5h')
// Non-session bars keep their fixed labels.
expect(markup).toContain('16% used wk')
expect(markup).toContain('42% used Fable')
})
it('shows "now" for an already-expired session reset', async () => {
const { InlineUsageBars } = await import('./StatusBar')
const limits = claudeLimits()
limits.session!.resetsAt = Date.now() - 1000
const markup = renderToStaticMarkup(<InlineUsageBars limits={limits} isFetching={false} />)
expect(markup).toContain('32% used now')
})
it('shows remaining copy and remaining meter fill', async () => {
mocks.usagePercentageDisplay = 'remaining'
const { InlineUsageBars } = await import('./StatusBar')
@@ -0,0 +1,42 @@
// @vitest-environment happy-dom
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useResetCountdownClock } from './useResetCountdownClock'
const START = 1_000_000_000
const MIN = 60_000
describe('useResetCountdownClock', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(START)
})
afterEach(() => {
vi.useRealTimers()
})
it('advances `now` just after the next label boundary', () => {
// 90m 30s away -> the minute label flips in 30s.
const resetAt = START + 90 * MIN + 30_000
const { result } = renderHook(() => useResetCountdownClock([resetAt]))
expect(result.current).toBe(START)
act(() => {
vi.advanceTimersByTime(30_000 + 1)
})
// Woke exactly once, at the boundary — not every second.
expect(result.current).toBe(START + 30_000 + 1)
})
it('does not schedule a tick when there is no future reset', () => {
const { result } = renderHook(() => useResetCountdownClock([START - 1000]))
expect(result.current).toBe(START)
act(() => {
vi.advanceTimersByTime(10 * MIN)
})
// Nothing to count down -> `now` stays put (no wasted wakeups).
expect(result.current).toBe(START)
})
})
@@ -0,0 +1,50 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { getResetCountdownNextTickDelay } from '../../../shared/rate-limit-reset-format'
// Why: a single boundary-scheduled clock drives the status-bar reset countdowns
// so the collapsed badge ticks live (matching the popover) without a per-second
// interval. It wakes once, just after the next label boundary, and reschedules.
function resetTimesKey(resetTimes: readonly (number | null | undefined)[]): string {
return resetTimes
.filter((resetAt): resetAt is number => resetAt != null && Number.isFinite(resetAt))
.sort((a, b) => a - b)
.join('|')
}
function parseResetTimesKey(key: string): number[] {
return key.length === 0 ? [] : key.split('|').map((value) => Number(value))
}
/**
* Returns a `now` timestamp that advances whenever the soonest reset countdown
* label is due to change. Pass the window `resetsAt` values; feed the returned
* `now` into the label formatter so it stays live.
*/
export function useResetCountdownClock(resetTimes: readonly (number | null | undefined)[]): number {
const [scheduledNow, setScheduledNow] = useState(() => Date.now())
const key = useMemo(() => resetTimesKey(resetTimes), [resetTimes])
const times = useMemo(() => parseResetTimesKey(key), [key])
const previousKeyRef = useRef(key)
const immediateNowRef = useRef(scheduledNow)
// Why: when the set of reset times changes, refresh `now` immediately so the
// label reflects the new window without waiting for the next scheduled tick.
if (previousKeyRef.current !== key) {
previousKeyRef.current = key
immediateNowRef.current = Date.now()
}
const now = Math.max(scheduledNow, immediateNowRef.current)
useEffect(() => {
const delayMs = getResetCountdownNextTickDelay(now, times)
if (delayMs === null) {
return
}
const timeout = window.setTimeout(() => setScheduledNow(Date.now()), delayMs)
return () => window.clearTimeout(timeout)
}, [now, times])
return now
}
+34 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest'
import { formatResetCountdown, formatResetDuration } from './rate-limit-reset-format'
import {
formatResetCountdown,
formatResetDuration,
getResetCountdownNextTickDelay
} from './rate-limit-reset-format'
const MIN = 60_000
const HOUR = 60 * MIN
@@ -28,3 +32,32 @@ describe('formatResetCountdown', () => {
expect(formatResetCountdown(6 * DAY + 7 * HOUR)).toBe('Resets in 6d 7h')
})
})
describe('getResetCountdownNextTickDelay', () => {
const now = 1_000_000_000
it('returns null when there is nothing to count down', () => {
expect(getResetCountdownNextTickDelay(now, [])).toBeNull()
// Past / non-finite resets never schedule a tick.
expect(getResetCountdownNextTickDelay(now, [now - MIN, now])).toBeNull()
expect(getResetCountdownNextTickDelay(now, [Number.NaN, Number.POSITIVE_INFINITY])).toBeNull()
})
it('wakes just after the next minute boundary while under a day out', () => {
// 90m 30s away -> next label flip is at the 90m mark, i.e. after 30s.
expect(getResetCountdownNextTickDelay(now, [now + 90 * MIN + 30_000])).toBe(30_000 + 1)
})
it('ticks on hour boundaries when a reset is a day or more away', () => {
// 2d 3h 15m away -> hour-granular labels, next flip after 15m.
expect(getResetCountdownNextTickDelay(now, [now + 2 * DAY + 3 * HOUR + 15 * MIN])).toBe(
15 * MIN + 1
)
})
it('returns the soonest delay across multiple resets', () => {
const soon = now + 5 * MIN + 10_000 // 10s to next flip
const later = now + 42 * MIN + 40_000 // 40s to next flip
expect(getResetCountdownNextTickDelay(now, [later, soon])).toBe(10_000 + 1)
})
})
+29
View File
@@ -30,3 +30,32 @@ export function formatResetCountdown(ms: number): string {
const duration = formatResetDuration(ms)
return duration === 'now' ? 'Resets now' : `Resets in ${duration}`
}
const MINUTE_MS = 60_000
const HOUR_MS = 60 * MINUTE_MS
const DAY_MS = 24 * HOUR_MS
/**
* Delay (ms) until the soonest reset countdown label would change, or null when
* no future reset needs a tick. Because labels are floored to minutes (or hours
* past a day), a countdown clock only needs to wake just after the next unit
* boundary — not every second — so callers schedule one short-lived timeout
* instead of polling. Returns the minimum delay across all reset times.
*/
export function getResetCountdownNextTickDelay(
now: number,
resetTimes: readonly number[]
): number | null {
let nextDelay: number | null = null
for (const resetAt of resetTimes) {
if (!Number.isFinite(resetAt) || resetAt <= now) {
continue
}
const remainingMs = resetAt - now
const tickUnitMs = remainingMs >= DAY_MS ? HOUR_MS : MINUTE_MS
// Why: +1ms so the timeout fires just past the boundary the label flips on.
const delayMs = (remainingMs % tickUnitMs) + 1
nextDelay = nextDelay === null ? delayMs : Math.min(nextDelay, delayMs)
}
return nextDelay
}