diff --git a/src/renderer/src/components/status-bar/StatusBar.tsx b/src/renderer/src/components/status-bar/StatusBar.tsx index a1f4df1e0..59e593ba0 100644 --- a/src/renderer/src/components/status-bar/StatusBar.tsx +++ b/src/renderer/src/components/status-bar/StatusBar.tsx @@ -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 diff --git a/src/renderer/src/components/status-bar/inline-usage-bars.test.tsx b/src/renderer/src/components/status-bar/inline-usage-bars.test.tsx index 00d27391e..a956695c8 100644 --- a/src/renderer/src/components/status-bar/inline-usage-bars.test.tsx +++ b/src/renderer/src/components/status-bar/inline-usage-bars.test.tsx @@ -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() + + 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() + + expect(markup).toContain('32% used now') + }) + it('shows remaining copy and remaining meter fill', async () => { mocks.usagePercentageDisplay = 'remaining' const { InlineUsageBars } = await import('./StatusBar') diff --git a/src/renderer/src/hooks/useResetCountdownClock.test.ts b/src/renderer/src/hooks/useResetCountdownClock.test.ts new file mode 100644 index 000000000..b594cc9a5 --- /dev/null +++ b/src/renderer/src/hooks/useResetCountdownClock.test.ts @@ -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) + }) +}) diff --git a/src/renderer/src/hooks/useResetCountdownClock.ts b/src/renderer/src/hooks/useResetCountdownClock.ts new file mode 100644 index 000000000..dbd5d8fee --- /dev/null +++ b/src/renderer/src/hooks/useResetCountdownClock.ts @@ -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 +} diff --git a/src/shared/rate-limit-reset-format.test.ts b/src/shared/rate-limit-reset-format.test.ts index 1598c4c42..36d04d824 100644 --- a/src/shared/rate-limit-reset-format.test.ts +++ b/src/shared/rate-limit-reset-format.test.ts @@ -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) + }) +}) diff --git a/src/shared/rate-limit-reset-format.ts b/src/shared/rate-limit-reset-format.ts index 2c1b48809..be4a6a232 100644 --- a/src/shared/rate-limit-reset-format.ts +++ b/src/shared/rate-limit-reset-format.ts @@ -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 +}