Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
💳 feat: Show Balance in the Context Gauge as Credits, Currency, or Percent (#16762)
Danny Avila82cde522f248
diff --git a/client/src/components/Balance/Summary.tsx b/client/src/components/Balance/Summary.tsxnew file mode 100644index 0000000000..62dcd27073--- /dev/null+++ b/client/src/components/Balance/Summary.tsx@@ -0,0 +1,151 @@+import { memo, useId } from 'react';+import { useTranslation } from 'react-i18next';+import { Progress, Skeleton } from '@librechat/client';+import type { BalanceSummary, BalanceTone, CurrencyConfig } from '~/utils';+import type { BalanceState } from '~/hooks/useBalanceSummary';+import { formatBalanceAmount, formatTimeUntil, cn } from '~/utils';+import useTimeTick from '~/hooks/useTimeTick';+import { useLocalize } from '~/hooks';++const TONE_VARIANT = {+ normal: 'default',+ warning: 'warning',+ danger: 'error',+} as const satisfies Record<BalanceTone, 'default' | 'warning' | 'error'>;++const TONE_TEXT: Record<BalanceTone, string> = {+ normal: 'text-text-secondary',+ warning: 'text-text-warning',+ danger: 'text-text-destructive',+};++interface SummaryProps {+ state: BalanceState;+ currency?: CurrencyConfig;+ className?: string;+}++function useRefillText(summary: BalanceSummary, currency?: CurrencyConfig): string {+ const localize = useLocalize();+ const { i18n } = useTranslation();+ /** Re-render once a minute so "in 5 minutes" counts down while the view stays open */+ useTimeTick();++ const { display, refillAmount, nextRefill } = summary;+ if (refillAmount == null) {+ return localize('com_ui_balance_no_refill');+ }+ const when =+ nextRefill != null ? formatTimeUntil(nextRefill, Date.now(), i18n.resolvedLanguage) : null;+ if (display === 'percent') {+ return when != null+ ? localize('com_ui_balance_refill_in', { 0: when })+ : localize('com_ui_balance_refill_when_empty');+ }+ const amount = formatBalanceAmount(refillAmount, display, currency);+ return when != null+ ? localize('com_ui_balance_refill_amount_in', { 0: amount, 1: when })+ : localize('com_ui_balance_refill_amount_when_empty', { 0: amount });+}++function Reading({ summary, currency }: { summary: BalanceSummary; currency?: CurrencyConfig }) {+ const localize = useLocalize();+ const refillText = useRefillText(summary, currency);+ const { display, credits, usedPercent, tone } = summary;++ let value: string;+ if (display === 'percent') {+ value =+ usedPercent != null+ ? localize('com_ui_balance_used', { 0: String(usedPercent) })+ : localize('com_ui_balance_usage_unavailable');+ } else if (display === 'currency') {+ value = formatBalanceAmount(credits, display, currency);+ } else {+ value = localize('com_ui_balance_credits', {+ 0: formatBalanceAmount(credits, display, currency),+ });+ }++ let status: string | null = null;+ if (tone === 'danger') {+ status = localize('com_ui_balance_empty');+ } else if (display !== 'percent' && usedPercent != null) {+ status = localize('com_ui_balance_used', { 0: String(usedPercent) });+ }++ return (+ <>+ <span+ className={cn('justify-self-end text-xs font-medium whitespace-nowrap', TONE_TEXT[tone])}+ data-testid="balance-value"+ >+ {value}+ </span>+ {usedPercent != null && (+ <Progress+ value={usedPercent}+ aria-label={localize('com_ui_balance_used_label')}+ className="col-span-2"+ variant={TONE_VARIANT[tone]}+ />+ )}+ <span className="text-text-secondary min-w-0 text-xs" data-testid="balance-refill">+ {refillText}+ </span>+ {status != null && (+ <span+ className={cn('justify-self-end text-xs whitespace-nowrap', TONE_TEXT[tone])}+ data-testid="balance-status"+ >+ {status}+ </span>+ )}+ </>+ );+}++/**+ * The balance reading shared by the context gauge popover and the settings dialog:+ * a title with the figure the deployment chose to show, the share of the allotment+ * spent, and when the next refill lands.+ */+function Summary({ state, currency, className }: SummaryProps) {+ const localize = useLocalize();+ const headingId = useId();++ if (state.status === 'empty') {+ return null;+ }++ const percentOnly = state.status === 'success' && state.summary.display === 'percent';+ return (+ <section+ aria-labelledby={headingId}+ aria-busy={state.status === 'loading'}+ data-testid="balance-summary"+ className={cn('grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 gap-y-2', className)}+ >+ <h3 id={headingId} className="text-text-primary text-sm font-medium">+ {localize(percentOnly ? 'com_ui_balance_usage_limit' : 'com_nav_balance')}+ </h3>+ {state.status === 'loading' && (+ <>+ <Skeleton className="h-3 w-16" />+ <Skeleton className="col-span-2 h-2 w-full rounded-full" />+ </>+ )}+ {state.status === 'error' && (+ <>+ <span />+ <p className="text-text-destructive col-span-2 text-xs" role="alert">+ {localize('com_ui_balance_error')}+ </p>+ </>+ )}+ {state.status === 'success' && <Reading summary={state.summary} currency={currency} />}+ </section>+ );+}++export default memo(Summary);diff --git a/client/src/components/Balance/__tests__/Summary.spec.tsx b/client/src/components/Balance/__tests__/Summary.spec.tsxnew file mode 100644index 0000000000..0afaddb794--- /dev/null+++ b/client/src/components/Balance/__tests__/Summary.spec.tsx@@ -0,0 +1,124 @@+import { render, screen } from '@testing-library/react';+import type { TBalanceResponse } from 'librechat-data-provider';+import type { BalanceState } from '~/hooks/useBalanceSummary';+import { summarizeBalance } from '~/utils';+import Summary from '../Summary';++const NOW = Date.parse('2026-07-05T00:00:00.000Z');++const record: TBalanceResponse = {+ tokenCredits: 3_100_000,+ autoRefillEnabled: true,+ refillAmount: 5_000_000,+ refillIntervalValue: 7,+ refillIntervalUnit: 'days',+ lastRefill: '2026-07-01T00:00:00.000Z',+};++const success = (+ display: 'credits' | 'currency' | 'percent',+ over: Partial<TBalanceResponse> = {},+): BalanceState => ({+ status: 'success',+ summary: summarizeBalance({ ...record, ...over }, { display, startBalance: 20_000 }),+});++describe('balance Summary', () => {+ beforeEach(() => {+ jest.useFakeTimers().setSystemTime(NOW);+ });+ afterEach(() => {+ jest.useRealTimers();+ });++ it('shows credits, the share spent and the next refill', () => {+ render(<Summary state={success('credits')} />);+ expect(screen.getByRole('heading', { name: 'Balance' })).toBeInTheDocument();+ expect(screen.getByTestId('balance-value')).toHaveTextContent('3,100,000 credits');+ expect(screen.getByRole('progressbar', { name: 'Share of balance used' })).toHaveAttribute(+ 'aria-valuenow',+ '38',+ );+ expect(screen.getByTestId('balance-refill')).toHaveTextContent(+ '+5,000,000 available in 3 days',+ );+ expect(screen.getByTestId('balance-status')).toHaveTextContent('38% used');+ });++ it('shows money in currency mode', () => {+ render(<Summary state={success('currency')} currency={{ code: 'EUR', rate: 0.5 }} />);+ expect(screen.getByTestId('balance-value')).toHaveTextContent('€1.55');+ expect(screen.getByTestId('balance-refill')).toHaveTextContent('+€2.50 available in 3 days');+ });++ it('shows no credit or money figure in percent mode', () => {+ const { container } = render(<Summary state={success('percent')} />);+ expect(screen.getByRole('heading', { name: 'Usage limit' })).toBeInTheDocument();+ expect(screen.getByTestId('balance-value')).toHaveTextContent('38% used');+ expect(screen.getByTestId('balance-refill')).toHaveTextContent('Refill available in 3 days');+ expect(container).not.toHaveTextContent(/credits|5,000,000|3,100,000|\$/);+ });++ it('says when a due refill will land rather than a past date', () => {+ render(<Summary state={success('percent', { lastRefill: '2026-06-01T00:00:00.000Z' })} />);+ expect(screen.getByTestId('balance-refill')).toHaveTextContent('Refills when you run out');+ });++ it('flags an empty balance', () => {+ render(<Summary state={success('credits', { tokenCredits: 0 })} />);+ expect(screen.getByTestId('balance-status')).toHaveTextContent('Out of credits');+ expect(screen.getByTestId('balance-value')).toHaveClass('text-text-destructive');+ });++ it('says usage is unavailable in percent mode when nothing measures the spend', () => {+ const state: BalanceState = {+ status: 'success',+ summary: summarizeBalance(+ { tokenCredits: 900, autoRefillEnabled: false },+ { display: 'percent', startBalance: 0 },+ ),+ };+ render(<Summary state={state} />);+ expect(screen.getByTestId('balance-value')).toHaveTextContent('Usage unavailable');+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();+ });++ it('reads an empty balance as fully used even without an allotment', () => {+ const state: BalanceState = {+ status: 'success',+ summary: summarizeBalance(+ { tokenCredits: 0, autoRefillEnabled: false },+ { display: 'percent', startBalance: 0 },+ ),+ };+ render(<Summary state={state} />);+ expect(screen.getByTestId('balance-value')).toHaveTextContent('100% used');+ expect(screen.getByTestId('balance-status')).toHaveTextContent('Out of credits');+ });++ it('omits the bar when nothing measures the spend', () => {+ const state: BalanceState = {+ status: 'success',+ summary: summarizeBalance({ tokenCredits: 900, autoRefillEnabled: false }),+ };+ render(<Summary state={state} />);+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();+ expect(screen.getByTestId('balance-refill')).toHaveTextContent("Doesn't refill automatically");+ });++ it('marks itself busy while loading', () => {+ render(<Summary state={{ status: 'loading' }} />);+ expect(screen.getByTestId('balance-summary')).toHaveAttribute('aria-busy', 'true');+ expect(screen.queryByTestId('balance-value')).not.toBeInTheDocument();+ });++ it('reports a failed load', () => {+ render(<Summary state={{ status: 'error' }} />);+ expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load your balance");+ });++ it('renders nothing when the server has no balance for the user', () => {+ const { container } = render(<Summary state={{ status: 'empty' }} />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/components/Balance/index.tsx b/client/src/components/Balance/index.tsxnew file mode 100644index 0000000000..e5450b377b--- /dev/null+++ b/client/src/components/Balance/index.tsx@@ -0,0 +1,13 @@+import useBalanceSummary from '~/hooks/useBalanceSummary';+import Summary from './Summary';++/** The user's balance, or nothing when the deployment does not meter credits. */+export default function Balance({ className }: { className?: string }) {+ const { enabled, state, currency } = useBalanceSummary();+ if (!enabled) {+ return null;+ }+ return <Summary state={state} currency={currency} className={className} />;+}++export { Summary };diff --git a/client/src/components/Chat/Input/TokenUsage/Gauge.tsx b/client/src/components/Chat/Input/TokenUsage/Gauge.tsxindex a61151cc23..ac91ab6149 100644--- a/client/src/components/Chat/Input/TokenUsage/Gauge.tsx+++ b/client/src/components/Chat/Input/TokenUsage/Gauge.tsx@@ -1,3 +1,4 @@+import type { BalanceTone } from '~/utils';import { cn } from '~/utils';const SIZE = 20;@@ -10,12 +11,23 @@ interface GaugeProps {percent: number;/** Max context unknown — render an empty track only */indeterminate: boolean;+ /** A tone the caller already classified (the balance's), in place of the context thresholds */+ tone?: BalanceTone;}-function getStrokeClass(percent: number, indeterminate: boolean): string {+function getStrokeClass(percent: number, indeterminate: boolean, tone?: BalanceTone): string {if (indeterminate) {return 'stroke-text-secondary';}+ if (tone === 'danger') {+ return 'stroke-status-error';+ }+ if (tone === 'warning') {+ return 'stroke-status-warning';+ }+ if (tone === 'normal') {+ return 'stroke-text-secondary';+ }if (percent > 90) {return 'stroke-status-error';}@@ -25,7 +37,7 @@ function getStrokeClass(percent: number, indeterminate: boolean): string {return 'stroke-text-secondary';}-export default function Gauge({ percent, indeterminate }: GaugeProps) {+export default function Gauge({ percent, indeterminate, tone }: GaugeProps) {const offset = CIRCUMFERENCE - (percent / 100) * CIRCUMFERENCE;return (@@ -55,7 +67,7 @@ export default function Gauge({ percent, indeterminate }: GaugeProps) {strokeDasharray={CIRCUMFERENCE}strokeDashoffset={indeterminate ? CIRCUMFERENCE : offset}strokeLinecap="round"- className={cn('transition-all duration-300', getStrokeClass(percent, indeterminate))}+ className={cn('transition-all duration-300', getStrokeClass(percent, indeterminate, tone))}/></svg>);diff --git a/client/src/components/Chat/Input/TokenUsage/Popover.tsx b/client/src/components/Chat/Input/TokenUsage/Popover.tsxnew file mode 100644index 0000000000..b5707b6590--- /dev/null+++ b/client/src/components/Chat/Input/TokenUsage/Popover.tsx@@ -0,0 +1,194 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import * as Ariakit from '@ariakit/react';+import type { ReactNode } from 'react';+import { cn } from '~/utils';++/** Hover pacing: a brief intent delay so sweeping past the gauge doesn't pop+ * the card open, and a grace period for the pointer to travel into it. */+const SHOW_DELAY_MS = 100;+const HIDE_DELAY_MS = 150;++interface UsagePopoverProps {+ /** Pending hover work is dropped when this changes (the viewed conversation) */+ resetKey: string;+ /** Accessible name of the gauge button */+ label: string;+ /** Accessible name of the opened card */+ cardLabel: string;+ busy?: boolean;+ /** The gauge face; receives whether the card is open */+ trigger: (open: boolean) => ReactNode;+ /** Card content, mounted only while the card is open */+ children: ReactNode;+}++/**+ * The composer gauge's disclosure: hover opens the card, a click pins it, and+ * keyboard and touch users get the same card through click / Enter / Space.+ */+export default function UsagePopover({+ resetKey,+ label,+ cardLabel,+ busy = false,+ trigger,+ children,+}: UsagePopoverProps) {+ const popover = Ariakit.usePopoverStore({ placement: 'top' });+ const popoverOpen = Ariakit.useStoreState(popover, 'open');+ const disclosureRef = useRef<HTMLButtonElement>(null);+ const showTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ /**+ * Ariakit only restores focus to the trigger on hide when it took focus on+ * show, so keep `autoFocusOnShow` on for click/keyboard opens (Escape returns+ * focus to the gauge) and off for hover so it never pulls focus off the+ * composer mid-typing.+ */+ const [focusOnShow, setFocusOnShow] = useState(true);+ /** A click pins an open popover: hover no longer holds it, so the pointer can+ * leave without it closing. Cleared when the popover closes by any path+ * (Escape, outside click, a second click). */+ const pinnedRef = useRef(false);+ /** The pin state as of the pointerdown that precedes a mouse click. The+ * pointerdown may hide the popover (hideOnInteractOutside does not exempt+ * the disclosure's inner elements), which clears `pinnedRef` via the close+ * effect before the click handler runs; the click must decide from this+ * snapshot instead. */+ const pinAtPointerDownRef = useRef(false);++ const cancelTimers = useCallback(() => {+ if (showTimerRef.current != null) {+ clearTimeout(showTimerRef.current);+ showTimerRef.current = null;+ }+ if (hideTimerRef.current != null) {+ clearTimeout(hideTimerRef.current);+ hideTimerRef.current = null;+ }+ }, []);+ const openByPointer = useCallback(() => {+ if (pinnedRef.current) {+ return;+ }+ cancelTimers();+ if (popover.getState().open) {+ return;+ }+ showTimerRef.current = setTimeout(() => {+ showTimerRef.current = null;+ setFocusOnShow(false);+ popover.show();+ }, SHOW_DELAY_MS);+ }, [cancelTimers, popover]);+ const scheduleHide = useCallback(() => {+ if (pinnedRef.current) {+ return;+ }+ cancelTimers();+ hideTimerRef.current = setTimeout(() => {+ hideTimerRef.current = null;+ popover.hide();+ }, HIDE_DELAY_MS);+ }, [cancelTimers, popover]);++ useEffect(() => {+ if (!popoverOpen) {+ pinnedRef.current = false;+ }+ }, [popoverOpen]);++ /** Pending hover work must not outlive its target: cancel it on unmount and+ * when the branch changes under the pointer, so a delayed show cannot open+ * the popover for a conversation the user has navigated away from. */+ useEffect(() => cancelTimers, [cancelTimers, resetKey]);++ return (+ <>+ {/* Hover shows the card; the disclosure keeps click / Enter / Space+ working for touch and keyboard users. Taps also emit pointer+ enter/leave, so the hover timers are gated to hover-capable pointers+ or a tap would hide the popover it just opened. */}+ <Ariakit.PopoverDisclosure+ ref={disclosureRef}+ store={popover}+ type="button"+ data-testid="token-usage"+ aria-label={label}+ aria-busy={busy}+ aria-haspopup="dialog"+ onPointerDown={() => {+ pinAtPointerDownRef.current = pinnedRef.current;+ }}+ onPointerEnter={(e) => {+ if (e.pointerType !== 'touch') {+ openByPointer();+ }+ }}+ onPointerLeave={(e) => {+ if (e.pointerType !== 'touch') {+ scheduleHide();+ }+ }}+ onClick={(e) => {+ cancelTimers();+ e.preventDefault();+ /** Mouse clicks (detail > 0) decide from the pointerdown snapshot:+ * the pointerdown may have hidden the popover and cleared the live+ * pin before this handler ran. Keyboard clicks carry no pointerdown,+ * so the live pin state is the truth there. */+ const wasPinned = e.detail > 0 ? pinAtPointerDownRef.current : pinnedRef.current;+ if (wasPinned) {+ pinnedRef.current = false;+ popover.hide();+ return;+ }+ if (!popover.getState().open) {+ setFocusOnShow(true);+ }+ pinnedRef.current = true;+ popover.show();+ }}+ className={cn(+ 'size-theme-control rounded-theme-control-round flex items-center justify-center transition-colors',+ 'hover:bg-surface-hover focus-visible:ring-text-primary focus-visible:ring-2 focus-visible:outline-hidden',+ 'animate-in fade-in zoom-in-95 duration-300',+ )}+ >+ {trigger(popoverOpen)}+ </Ariakit.PopoverDisclosure>+ {/* Focus the labelled dialog on keyboard/click open so screen readers+ enter and announce the card, and so focus stays contained instead+ of falling back to the body (which the composer's global focus logic+ would steal). The visible ring is suppressed via focus:outline-hidden,+ and finalFocus returns focus to the gauge trigger on close. */}+ <Ariakit.Popover+ store={popover}+ gutter={8}+ portal+ unmountOnHide+ autoFocusOnShow={focusOnShow}+ finalFocus={disclosureRef}+ /* Without this the gauge could not close its own popup: mousedown on+ the trigger counts as "outside", so Ariakit hid the popup and the+ button's own click immediately re-opened it. */+ hideOnInteractOutside={(event) => !disclosureRef.current?.contains(event.target as Node)}+ aria-label={cardLabel}+ onPointerEnter={cancelTimers}+ onPointerLeave={(e) => {+ if (e.pointerType !== 'touch') {+ scheduleHide();+ }+ }}+ className={cn(+ 'border-border-medium bg-surface-secondary text-text-primary z-[200] max-h-[calc(100dvh-1rem)] max-w-[calc(100vw-1rem)] overflow-y-auto overscroll-contain rounded-xl border p-3 shadow-lg focus:outline-hidden',+ 'origin-bottom translate-y-1 scale-95 opacity-0 transition duration-150 ease-out motion-reduce:transition-none',+ 'data-[enter]:translate-y-0 data-[enter]:scale-100 data-[enter]:opacity-100',+ 'data-[leave]:translate-y-1 data-[leave]:scale-95 data-[leave]:opacity-0',+ )}+ >+ {children}+ </Ariakit.Popover>+ </>+ );+}diff --git a/client/src/components/Chat/Input/TokenUsage/index.spec.tsx b/client/src/components/Chat/Input/TokenUsage/index.spec.tsxnew file mode 100644index 0000000000..aed883412b--- /dev/null+++ b/client/src/components/Chat/Input/TokenUsage/index.spec.tsx@@ -0,0 +1,236 @@+import userEvent from '@testing-library/user-event';+import { render, screen, within } from '@testing-library/react';+import type { TBalanceResponse, TConversation } from 'librechat-data-provider';+import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';+import { TokenCredits, AutoRefill } from '~/components/Nav/Settings/BillingControls';+import TokenUsage from './index';++const mockStartupConfig = jest.fn();+const mockBalance = jest.fn();+const mockTokenUsage = jest.fn();+const mockBalanceQuery = jest.fn();++jest.mock('~/data-provider', () => ({+ useGetStartupConfig: () => ({ data: mockStartupConfig() }),+ useGetUserBalance: (config?: { enabled?: boolean }) =>+ config?.enabled === false+ ? { data: undefined, isError: false, isFetched: false }+ : (mockBalanceQuery() ?? { data: mockBalance(), isError: false, isFetched: true }),+ useGetLangfuseSessionLinkQuery: () => ({ data: undefined }),+}));++jest.mock('~/hooks/AuthContext', () => ({+ useAuthContext: () => ({ isAuthenticated: true }),+}));++jest.mock('~/hooks/Chat/useTokenUsage', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockTokenUsage(...args),+}));++jest.mock('~/hooks/Chat/useCompactConversation', () => ({+ __esModule: true,+ default: () => ({ compact: jest.fn(), canCompact: false, isCompacting: false }),+ supportsCompaction: () => false,+}));++jest.mock('./Breakdown', () => ({+ __esModule: true,+ default: () => <div data-testid="context-breakdown-stub" />,+}));++const NOW = Date.parse('2026-07-05T00:00:00.000Z');++const balance: TBalanceResponse = {+ tokenCredits: 3_100_000,+ autoRefillEnabled: true,+ refillAmount: 5_000_000,+ refillIntervalValue: 7,+ refillIntervalUnit: 'days',+ lastRefill: '2026-07-01T00:00:00.000Z',+};++const config = ({+ balanceEnabled = true,+ display = 'credits',+ contextUsage,+}: {+ balanceEnabled?: boolean;+ display?: string;+ contextUsage?: boolean;+} = {}) => ({+ balance: { enabled: balanceEnabled, startBalance: 20_000, display },+ interface: { contextUsage, currency: { code: 'USD', rate: 1 } },+});++const usage = (usedTokens: number) =>+ ({ usedTokens, maxTokens: 200_000, percent: (usedTokens / 200_000) * 100 }) as TokenUsageView;++const conversation = { conversationId: 'convo-1', endpoint: 'openAI' } as TConversation;++const renderGauge = () =>+ render(<TokenUsage index={0} conversation={conversation} isSubmitting={false} />);++const openCard = async () => {+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });+ await user.click(screen.getByTestId('token-usage'));+ return screen.findByRole('dialog');+};++describe('TokenUsage gauge', () => {+ beforeEach(() => {+ jest.useFakeTimers().setSystemTime(NOW);+ mockBalance.mockReturnValue(balance);+ mockTokenUsage.mockReturnValue(usage(0));+ mockBalanceQuery.mockReset();+ });+ afterEach(() => {+ jest.useRealTimers();+ jest.clearAllMocks();+ });++ it('stays hidden on a fresh chat when balance is off', () => {+ mockStartupConfig.mockReturnValue(config({ balanceEnabled: false }));+ renderGauge();+ expect(screen.queryByTestId('token-usage')).not.toBeInTheDocument();+ });++ it('shows the balance on a fresh chat when balance is on', async () => {+ mockStartupConfig.mockReturnValue(config());+ renderGauge();+ const card = await openCard();+ expect(within(card).getByTestId('balance-summary')).toBeInTheDocument();+ expect(within(card).queryByTestId('context-breakdown-stub')).not.toBeInTheDocument();+ });++ it('places the balance below the context window', async () => {+ mockStartupConfig.mockReturnValue(config());+ mockTokenUsage.mockReturnValue(usage(83_200));+ renderGauge();+ const card = await openCard();+ const context = within(card).getByTestId('context-breakdown-stub');+ const summary = within(card).getByTestId('balance-summary');+ expect(context.compareDocumentPosition(summary)).toBe(Node.DOCUMENT_POSITION_FOLLOWING);+ });++ it('keeps a balance-only gauge when context usage is off, without reading context', async () => {+ mockStartupConfig.mockReturnValue(config({ contextUsage: false, display: 'percent' }));+ renderGauge();+ expect(mockTokenUsage).not.toHaveBeenCalled();+ expect(screen.getByRole('meter', { name: 'Share of balance used' })).toHaveAttribute(+ 'aria-valuenow',+ '38',+ );+ const card = await openCard();+ expect(within(card).getByTestId('balance-value')).toHaveTextContent('38% used');+ });++ it('reads an unknown display mode from an unvalidated override as credits', async () => {+ mockStartupConfig.mockReturnValue(config({ display: 'dollars' }));+ renderGauge();+ const card = await openCard();+ expect(within(card).getByRole('heading', { name: 'Balance' })).toBeInTheDocument();+ expect(within(card).getByTestId('balance-value')).toHaveTextContent('3,100,000 credits');+ });++ it('keeps the card inside the viewport', async () => {+ mockStartupConfig.mockReturnValue(config());+ renderGauge();+ const card = await openCard();+ expect(card).toHaveClass(+ 'max-h-[calc(100dvh-1rem)]',+ 'max-w-[calc(100vw-1rem)]',+ 'overflow-y-auto',+ );+ });++ it('tints the balance-only ring with the balance tone, amber until empty', () => {+ mockStartupConfig.mockReturnValue(config({ contextUsage: false }));+ mockBalance.mockReturnValue({ ...balance, tokenCredits: 400_000 });+ renderGauge();+ const meter = screen.getByRole('meter', { name: 'Share of balance used' });+ expect(meter).toHaveAttribute('aria-valuenow', '92');+ const ring = meter.querySelectorAll('circle')[1];+ expect(ring).toHaveClass('stroke-status-warning');+ expect(ring).not.toHaveClass('stroke-status-error');+ });++ it('exposes no valueless meter while the balance-only gauge has nothing to measure', () => {+ mockBalance.mockReturnValue({ tokenCredits: 900, autoRefillEnabled: false });+ mockStartupConfig.mockReturnValue({+ ...config({ contextUsage: false, display: 'percent' }),+ balance: { enabled: true, startBalance: 0, display: 'percent' },+ });+ renderGauge();+ expect(screen.getByTestId('token-usage')).toBeInTheDocument();+ expect(screen.queryByRole('meter')).not.toBeInTheDocument();+ });++ it('mounts nothing when both context usage and balance are off', () => {+ mockStartupConfig.mockReturnValue(config({ balanceEnabled: false, contextUsage: false }));+ const { container } = renderGauge();+ expect(container).toBeEmptyDOMElement();+ });++ it('agrees with the card when auto-refill is on but the refill amount is not positive', async () => {+ mockStartupConfig.mockReturnValue(config());+ mockBalance.mockReturnValue({ ...balance, refillAmount: 0 });+ renderGauge();+ const card = await openCard();+ expect(within(card).getByTestId('balance-refill')).toHaveTextContent(+ "Doesn't refill automatically",+ );+ const settings = render(<AutoRefill />);+ expect(settings.container).toHaveTextContent('Auto-Refill is disabled.');+ expect(settings.container).not.toHaveTextContent('Error loading auto-refill settings.');+ });++ it.each([+ ['loading', { data: undefined, isError: false, isFetched: false }, 'auto-refill-loading'],+ ['failed', { data: undefined, isError: true, isFetched: true }, 'alert'],+ ] as const)(+ 'shows the auto-refill row %s on its own when settings search hides the balance row',+ (_state, query, marker) => {+ mockStartupConfig.mockReturnValue(config());+ mockBalanceQuery.mockReturnValue(query);+ const settings = render(<AutoRefill />);+ const node =+ marker === 'alert'+ ? within(settings.container).getByRole('alert')+ : within(settings.container).getByTestId(marker);+ expect(node).toBeInTheDocument();+ if (marker === 'alert') {+ expect(node).toHaveTextContent('Error loading auto-refill settings.');+ }+ },+ );++ it.each(['credits', 'currency', 'percent'] as const)(+ 'shows the same %s reading in the gauge and in settings',+ async (display) => {+ mockStartupConfig.mockReturnValue(config({ display }));+ renderGauge();+ const card = await openCard();+ const gauge = within(card).getByTestId('balance-summary').textContent;++ const settings = render(+ <>+ <TokenCredits />+ <AutoRefill />+ </>,+ );+ const settingsSummary = within(settings.container).getByTestId('balance-summary');+ expect(settingsSummary.textContent).toBe(gauge);++ const refillRow = within(settings.container).queryByText('Refill Amount:');+ if (display === 'percent') {+ expect(refillRow).not.toBeInTheDocument();+ expect(settings.container).not.toHaveTextContent(/5,000,000|\$5\.00/);+ } else {+ const amount = display === 'currency' ? '$5.00' : '5,000,000';+ expect(refillRow?.nextElementSibling).toHaveTextContent(amount);+ expect(gauge).toContain(`+${amount}`);+ }+ },+ );+});diff --git a/client/src/components/Chat/Input/TokenUsage/index.tsx b/client/src/components/Chat/Input/TokenUsage/index.tsxindex 14b4270f45..c8abbaf163 100644--- a/client/src/components/Chat/Input/TokenUsage/index.tsx+++ b/client/src/components/Chat/Input/TokenUsage/index.tsx@@ -1,15 +1,18 @@-import { memo, useCallback, useEffect, useRef, useState } from 'react';-import * as Ariakit from '@ariakit/react';+import { memo } from 'react';import { Spinner } from '@librechat/client';import { Constants } from 'librechat-data-provider';import type { TConversation } from 'librechat-data-provider';+import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';import type { CurrencyConfig } from '~/utils';import useCompactConversation, { supportsCompaction } from '~/hooks/Chat/useCompactConversation';import { useGetLangfuseSessionLinkQuery, useGetStartupConfig } from '~/data-provider';+import Balance, { Summary as BalanceSummary } from '~/components/Balance';+import useBalanceSummary from '~/hooks/useBalanceSummary';import useTokenUsage from '~/hooks/Chat/useTokenUsage';import CompactAction from './CompactAction';-import { formatTokens, cn } from '~/utils';+import { formatTokens } from '~/utils';import { useLocalize } from '~/hooks';+import UsagePopover from './Popover';import Breakdown from './Breakdown';import Gauge from './Gauge';@@ -19,10 +22,62 @@ interface TokenUsageProps {isSubmitting: boolean;}-/** Hover pacing: a brief intent delay so sweeping past the gauge doesn't pop- * the card open, and a grace period for the pointer to travel into it. */-const SHOW_DELAY_MS = 100;-const HIDE_DELAY_MS = 150;+interface ContextCardProps {+ view: TokenUsageView;+ conversationId: string;+ isSubmitting: boolean;+ showCost: boolean;+ currency?: CurrencyConfig;+ langfuseConnectionAccess: boolean;+ compaction: ReturnType<typeof useCompactConversation>;+ compactionAvailable: boolean;+}++/** The context half of the card. Mounted only while the card is open, so the+ * Langfuse session link resolves on demand rather than per conversation. */+function ContextCard({+ view,+ conversationId,+ isSubmitting,+ showCost,+ currency,+ langfuseConnectionAccess,+ compaction,+ compactionAvailable,+}: ContextCardProps) {+ const canResolveLangfuseSession =+ langfuseConnectionAccess &&+ !isSubmitting &&+ conversationId !== '' &&+ conversationId !== Constants.NEW_CONVO &&+ conversationId !== Constants.PENDING_CONVO;+ const { data: langfuseSession } = useGetLangfuseSessionLinkQuery(+ conversationId,+ canResolveLangfuseSession,+ );++ return (+ <>+ <Breakdown+ view={view}+ showCost={showCost}+ compactionAvailable={compactionAvailable}+ currency={currency}+ langfuseSessionUrl={langfuseSession?.url ?? undefined}+ />+ {compactionAvailable && (+ <>+ <div className="border-border-light border-t" role="separator" />+ <CompactAction+ compact={compaction.compact}+ canCompact={compaction.canCompact}+ isCompacting={compaction.isCompacting}+ />+ </>+ )}+ </>+ );+}function TokenUsageIndicator({index,@@ -32,11 +87,13 @@ function TokenUsageIndicator({currency,langfuseConnectionAccess,compactionEnabled,+ balanceEnabled,}: TokenUsageProps & {showCost: boolean;currency?: CurrencyConfig;langfuseConnectionAccess: boolean;compactionEnabled: boolean;+ balanceEnabled: boolean;}) {const localize = useLocalize();const view = useTokenUsage({ index, conversation, isSubmitting });@@ -44,160 +101,39 @@ function TokenUsageIndicator({* in-flight state the moment the pointer leaves. */const compaction = useCompactConversation();const compactionAvailable = compactionEnabled && supportsCompaction(conversation?.endpoint);- const popover = Ariakit.usePopoverStore({ placement: 'top' });- const popoverOpen = Ariakit.useStoreState(popover, 'open');- const disclosureRef = useRef<HTMLButtonElement>(null);const conversationId = conversation?.conversationId ?? '';- const showTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- /**- * Ariakit only restores focus to the trigger on hide when it took focus on- * show, so keep `autoFocusOnShow` on for click/keyboard opens (Escape returns- * focus to the gauge) and off for hover so it never pulls focus off the- * composer mid-typing.- */- const [focusOnShow, setFocusOnShow] = useState(true);- /** A click pins an open popover: hover no longer holds it, so the pointer can- * leave without it closing. Cleared when the popover closes by any path- * (Escape, outside click, a second click). */- const pinnedRef = useRef(false);- /** The pin state as of the pointerdown that precedes a mouse click. The- * pointerdown may hide the popover (hideOnInteractOutside does not exempt- * the disclosure's inner elements), which clears `pinnedRef` via the close- * effect before the click handler runs; the click must decide from this- * snapshot instead. */- const pinAtPointerDownRef = useRef(false);-- const cancelTimers = useCallback(() => {- if (showTimerRef.current != null) {- clearTimeout(showTimerRef.current);- showTimerRef.current = null;- }- if (hideTimerRef.current != null) {- clearTimeout(hideTimerRef.current);- hideTimerRef.current = null;- }- }, []);- const openByPointer = useCallback(() => {- if (pinnedRef.current) {- return;- }- cancelTimers();- if (popover.getState().open) {- return;- }- showTimerRef.current = setTimeout(() => {- showTimerRef.current = null;- setFocusOnShow(false);- popover.show();- }, SHOW_DELAY_MS);- }, [cancelTimers, popover]);- const scheduleHide = useCallback(() => {- if (pinnedRef.current) {- return;- }- cancelTimers();- hideTimerRef.current = setTimeout(() => {- hideTimerRef.current = null;- popover.hide();- }, HIDE_DELAY_MS);- }, [cancelTimers, popover]);-- useEffect(() => {- if (!popoverOpen) {- pinnedRef.current = false;- }- }, [popoverOpen]);-- /** Pending hover work must not outlive its target: cancel it on unmount and- * when the branch changes under the pointer, so a delayed show cannot open- * the popover for a conversation the user has navigated away from. */- useEffect(() => cancelTimers, [cancelTimers, conversationId]);-- const canResolveLangfuseSession =- langfuseConnectionAccess &&- popoverOpen &&- !isSubmitting &&- conversationId !== '' &&- conversationId !== Constants.NEW_CONVO &&- conversationId !== Constants.PENDING_CONVO;- const { data: langfuseSession } = useGetLangfuseSessionLinkQuery(- conversationId,- canResolveLangfuseSession,- );+ const hasContext = view.usedTokens > 0;- /** Hide until the branch has data — keeps a fresh, message-less chat clean and- * lets the indicator animate into view once the first tokens land. */- if (view.usedTokens <= 0) {+ /** Without balance, hide until the branch has data — keeps a fresh,+ * message-less chat clean and lets the indicator animate into view once the+ * first tokens land. With balance, the card always has something to show. */+ if (!hasContext && !balanceEnabled) {return null;}const hasMax = view.maxTokens != null && view.maxTokens > 0;- const usageAriaLabel = hasMax- ? localize('com_ui_context_usage_label', {- 0: formatTokens(view.usedTokens),- 1: formatTokens(view.maxTokens ?? 0),- 2: String(Math.round(view.percent)),- })- : localize('com_ui_context_usage_label_unknown', { 0: formatTokens(view.usedTokens) });+ let usageAriaLabel = localize('com_nav_balance');+ if (hasContext) {+ usageAriaLabel = hasMax+ ? localize('com_ui_context_usage_label', {+ 0: formatTokens(view.usedTokens),+ 1: formatTokens(view.maxTokens ?? 0),+ 2: String(Math.round(view.percent)),+ })+ : localize('com_ui_context_usage_label_unknown', { 0: formatTokens(view.usedTokens) });+ }const ariaLabel = compaction.isCompacting? localize('com_ui_context_compacting'): usageAriaLabel;- const showCompactingIndicator = compaction.isCompacting && !popoverOpen;return (- <>- {/* Hover shows the breakdown; the disclosure keeps click / Enter / Space- working for touch and keyboard users. Taps also emit pointer- enter/leave, so the hover timers are gated to hover-capable pointers- or a tap would hide the popover it just opened. */}- <Ariakit.PopoverDisclosure- ref={disclosureRef}- store={popover}- type="button"- data-testid="token-usage"- aria-label={ariaLabel}- aria-busy={compaction.isCompacting}- aria-haspopup="dialog"- onPointerDown={() => {- pinAtPointerDownRef.current = pinnedRef.current;- }}- onPointerEnter={(e) => {- if (e.pointerType !== 'touch') {- openByPointer();- }- }}- onPointerLeave={(e) => {- if (e.pointerType !== 'touch') {- scheduleHide();- }- }}- onClick={(e) => {- cancelTimers();- e.preventDefault();- /** Mouse clicks (detail > 0) decide from the pointerdown snapshot:- * the pointerdown may have hidden the popover and cleared the live- * pin before this handler ran. Keyboard clicks carry no pointerdown,- * so the live pin state is the truth there. */- const wasPinned = e.detail > 0 ? pinAtPointerDownRef.current : pinnedRef.current;- if (wasPinned) {- pinnedRef.current = false;- popover.hide();- return;- }- if (!popover.getState().open) {- setFocusOnShow(true);- }- pinnedRef.current = true;- popover.show();- }}- className={cn(- 'size-theme-control rounded-theme-control-round flex items-center justify-center transition-colors',- 'hover:bg-surface-hover focus-visible:ring-text-primary focus-visible:ring-2 focus-visible:outline-hidden',- 'animate-in fade-in zoom-in-95 duration-300',- )}- >- {showCompactingIndicator ? (+ <UsagePopover+ resetKey={conversationId}+ label={ariaLabel}+ cardLabel={localize(hasContext ? 'com_ui_context_usage' : 'com_nav_balance')}+ busy={compaction.isCompacting}+ trigger={(open) =>+ compaction.isCompacting && !open ? (<Spinner className="text-text-secondary size-5" />) : (<span@@ -208,63 +144,78 @@ function TokenUsageIndicator({aria-label={localize('com_ui_context_usage')}className="flex items-center justify-center">- <Gauge percent={view.percent} indeterminate={!hasMax} />+ <Gauge percent={view.percent} indeterminate={hasContext && !hasMax} /></span>- )}- </Ariakit.PopoverDisclosure>- {/* Focus the labelled dialog on keyboard/click open so screen readers- enter and announce the breakdown, and so focus stays contained instead- of falling back to the body (which the composer's global focus logic- would steal). The visible ring is suppressed via focus:outline-hidden,- and finalFocus returns focus to the gauge trigger on close. */}- <Ariakit.Popover- store={popover}- gutter={8}- portal- unmountOnHide- autoFocusOnShow={focusOnShow}- finalFocus={disclosureRef}- /* Without this the gauge could not close its own popup: mousedown on- the trigger counts as "outside", so Ariakit hid the popup and the- button's own click immediately re-opened it. */- hideOnInteractOutside={(event) => !disclosureRef.current?.contains(event.target as Node)}- aria-label={localize('com_ui_context_usage')}- onPointerEnter={cancelTimers}- onPointerLeave={(e) => {- if (e.pointerType !== 'touch') {- scheduleHide();- }- }}- className={cn(- 'border-border-medium bg-surface-secondary text-text-primary z-[200] max-h-[calc(100dvh-1rem)] max-w-[calc(100vw-1rem)] overflow-y-auto overscroll-contain rounded-xl border p-3 shadow-lg focus:outline-hidden',- 'origin-bottom translate-y-1 scale-95 opacity-0 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none',- 'data-[enter]:translate-y-0 data-[enter]:scale-100 data-[enter]:opacity-100',- 'data-[leave]:translate-y-1 data-[leave]:scale-95 data-[leave]:opacity-0',- )}- >- {/* The popover owns its width, which the breakdown held only while it- was the sole child of a shrink-to-fit box. */}- <div className="w-72 max-w-full space-y-3">- <Breakdown+ )+ }+ >+ {/* The popover owns its width, which the breakdown held only while it+ was the sole child of a shrink-to-fit box. */}+ <div className="w-72 max-w-full space-y-3">+ {hasContext && (+ <ContextCardview={view}+ conversationId={conversationId}+ isSubmitting={isSubmitting}showCost={showCost}- compactionAvailable={compactionAvailable}currency={currency}- langfuseSessionUrl={langfuseSession?.url ?? undefined}+ langfuseConnectionAccess={langfuseConnectionAccess}+ compaction={compaction}+ compactionAvailable={compactionAvailable}/>- {compactionAvailable && (- <>- <div className="border-border-light border-t" role="separator" />- <CompactAction- compact={compaction.compact}- canCompact={compaction.canCompact}- isCompacting={compaction.isCompacting}- />- </>- )}- </div>- </Ariakit.Popover>- </>+ )}+ {balanceEnabled && (+ <Balance className={hasContext ? 'border-border-light border-t pt-3' : undefined} />+ )}+ </div>+ </UsagePopover>+ );+}++/** The gauge for a deployment that turned context usage off but meters credits:+ * its ring is the share of the balance allotment spent. */+function BalanceIndicator({ conversationId }: { conversationId: string }) {+ const localize = useLocalize();+ const { state, currency } = useBalanceSummary();+ if (state.status === 'empty') {+ return null;+ }+ const summary = state.status === 'success' ? state.summary : null;+ const usedPercent = summary?.usedPercent ?? null;+ const label = localize('com_nav_balance');++ return (+ <UsagePopover+ resetKey={conversationId}+ label={label}+ cardLabel={label}+ busy={state.status === 'loading'}+ trigger={() =>+ /** A meter has no indeterminate state: until there is a share to report+ * (loading, failed, nothing to measure against) the ring is decoration+ * and the button's label carries the name. */+ usedPercent != null ? (+ <span+ role="meter"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={usedPercent}+ aria-label={localize('com_ui_balance_used_label')}+ className="flex items-center justify-center"+ >+ <Gauge percent={usedPercent} indeterminate={false} tone={summary?.tone} />+ </span>+ ) : (+ <span aria-hidden="true" className="flex items-center justify-center">+ <Gauge percent={0} indeterminate />+ </span>+ )+ }+ >+ <div className="w-72 max-w-full">+ <BalanceSummary state={state} currency={currency} />+ </div>+ </UsagePopover>);}@@ -274,9 +225,15 @@ const TokenUsage = memo(function TokenUsage(props: TokenUsageProps) {/** Wait for config before mounting: until it loads `contextUsage === false`* reads as undefined, so a disabled deployment would briefly mount the* indicator and fire the token-config query on first load */- if (startupConfig == null || startupConfig.interface?.contextUsage === false) {+ if (startupConfig == null) {return null;}+ const balanceEnabled = startupConfig.balance?.enabled === true;+ if (startupConfig.interface?.contextUsage === false) {+ return balanceEnabled ? (+ <BalanceIndicator conversationId={props.conversation?.conversationId ?? ''} />+ ) : null;+ }return (<TokenUsageIndicator{...props}@@ -288,6 +245,7 @@ const TokenUsage = memo(function TokenUsage(props: TokenUsageProps) {* (a cached config from an older release) must not receive the request,* which it would run as an empty, billed ordinary turn. */compactionEnabled={startupConfig.compactionEnabled === true}+ balanceEnabled={balanceEnabled}/>);});diff --git a/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts b/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.tsindex ab247bb3d3..42a23ab855 100644--- a/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts+++ b/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts@@ -12,7 +12,7 @@ const themedControls = [/** The submit slot's faces share one recipe, which owns the coarse-pointer* tap-target floor as well as the geometry. */['DuringRunSendButton.tsx', ['composerSubmitClasses()']],- ['TokenUsage/index.tsx', ['size-theme-control', 'rounded-theme-control-round']],+ ['TokenUsage/Popover.tsx', ['size-theme-control', 'rounded-theme-control-round']],['Files/AttachFile.tsx', ['size-theme-control', 'rounded-theme-control-round']],['CodeApprovalMenu.tsx', ['composerControlClasses()', 'md:px-theme-control-x']],] as const;diff --git a/client/src/components/Messages/Content/Error/BalanceError.tsx b/client/src/components/Messages/Content/Error/BalanceError.tsxindex cab3eeb5a9..1792cda1a6 100644--- a/client/src/components/Messages/Content/Error/BalanceError.tsx+++ b/client/src/components/Messages/Content/Error/BalanceError.tsx@@ -1,12 +1,7 @@import type { ErrorRendererProps, JsonValue } from './parts';-import {- ErrorBody,- ErrorDetails,- formatCredits,- formatNumber,- readNumber,- readString,-} from './parts';+import { ErrorBody, ErrorDetails, formatNumber, readNumber, readString } from './parts';+import { useBalanceDisplay } from '~/hooks/useBalanceSummary';+import { formatBalanceAmount } from '~/utils';import { useLocalize } from '~/hooks';type GenerationRow = {@@ -42,6 +37,7 @@ function readGeneration(generation: JsonValue): GenerationRow | null {export default function BalanceError({ json }: ErrorRendererProps) {const localize = useLocalize();+ const { display, currency } = useBalanceDisplay();const balance = readNumber(json, 'balance');const tokenCost = readNumber(json, 'tokenCost');const promptTokens = readNumber(json, 'promptTokens');@@ -49,13 +45,21 @@ export default function BalanceError({ json }: ErrorRendererProps) {? json.generations.map(readGeneration).filter((row): row is GenerationRow => row != null): [];- const summary =- tokenCost != null && balance != null- ? localize('com_error_token_balance', {- 0: formatCredits(tokenCost),- 1: formatCredits(balance),- })- : localize('com_error_limit_reached');+ /** Same figures the balance summary shows: money for `currency`, none at all for `percent` */+ let summary = localize('com_error_limit_reached');+ if (tokenCost != null && balance != null) {+ if (display === 'percent') {+ summary = localize('com_error_token_balance_hidden');+ } else {+ summary = localize(+ display === 'currency' ? 'com_error_token_balance_currency' : 'com_error_token_balance',+ {+ 0: formatBalanceAmount(tokenCost, display, currency),+ 1: formatBalanceAmount(balance, display, currency),+ },+ );+ }+ }return (<ErrorBody>diff --git a/client/src/components/Messages/Content/Error/parts.tsx b/client/src/components/Messages/Content/Error/parts.tsxindex 9bc8e7d342..f28e23cb75 100644--- a/client/src/components/Messages/Content/Error/parts.tsx+++ b/client/src/components/Messages/Content/Error/parts.tsx@@ -355,10 +355,6 @@ export function ErrorAction({export const formatNumber = (value: number): string => new Intl.NumberFormat().format(value);-/** Token credits are a float balance; two decimals, matching the balance settings row. */-export const formatCredits = (value: number): string =>- new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value);-const isoTimestamp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;/**diff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsxindex ebdf167e7e..8212906edf 100644--- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx+++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx@@ -20,7 +20,11 @@ import Error from '../Error';let mockEndpointsData: Record<string, Record<string, unknown>> | undefined = {openAI: { userProvide: true },};-let mockStartupData: { compactionEnabled: boolean; interface?: { contextUsage?: boolean } } = {+let mockStartupData: {+ compactionEnabled: boolean;+ interface?: { contextUsage?: boolean; currency?: { code: string; rate: number } };+ balance?: { enabled: boolean; display: string };+} = {compactionEnabled: false,};let mockAccess: Record<string, boolean> = {};@@ -808,6 +812,28 @@ describe('Error — token balance and context budget', () => {).toBeInTheDocument();});+ it('states the shortfall in money when the deployment shows balance as currency', () => {+ mockStartupData = {+ compactionEnabled: false,+ balance: { enabled: true, display: 'currency' },+ interface: { currency: { code: 'USD', rate: 1 } },+ };+ renderError({ type: ViolationTypes.TOKEN_BALANCE, balance: 1_250_000, tokenCost: 8_400_000 });++ expect(+ screen.getByText(localized('com_error_token_balance_currency', '$8.40', '$1.25')),+ ).toBeInTheDocument();+ expect(document.body.textContent).not.toContain('credits');+ });++ it('shows no credit figures when the deployment shows balance as a percent', () => {+ mockStartupData = { compactionEnabled: false, balance: { enabled: true, display: 'percent' } };+ renderError({ type: ViolationTypes.TOKEN_BALANCE, balance: 1250, tokenCost: 8400 });++ expect(screen.getByText(catalog.com_error_token_balance_hidden)).toBeInTheDocument();+ expect(document.body.textContent).not.toMatch(/1,250|8,400|credits/);+ });+it('lists every generation charge rather than a truncated subset', () => {const generations = Array.from({ length: 25 }, (_, index) => ({model: `model-${index + 1}`,diff --git a/client/src/components/Nav/AccountSettings.tsx b/client/src/components/Nav/AccountSettings.tsxindex 8852cbd279..cb983dad7f 100644--- a/client/src/components/Nav/AccountSettings.tsx+++ b/client/src/components/Nav/AccountSettings.tsx@@ -16,7 +16,7 @@ import {} from 'lucide-react';import { ArchivedChatsModal } from '~/components/Nav/SettingsTabs/General/ArchivedChatsModal';import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';-import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';+import { useGetStartupConfig } from '~/data-provider';import { useAuthContext } from '~/hooks/AuthContext';import { settingsOpenAtom } from './Settings';import { openInNewTab } from '~/utils';@@ -96,11 +96,8 @@ function HelpSubmenu({function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {const localize = useLocalize();- const { user, isAuthenticated, logout } = useAuthContext();+ const { user, logout } = useAuthContext();const { data: startupConfig } = useGetStartupConfig();- const balanceQuery = useGetUserBalance({- enabled: !!isAuthenticated && startupConfig?.balance?.enabled,- });const setShowSettings = useSetAtom(settingsOpenAtom);const setShowFiles = useSetAtom(showFilesDialogAtom);const setFilesDialogTrigger = useSetAtom(filesDialogTriggerAtom);@@ -146,15 +143,6 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {{user?.email ?? localize('com_nav_user')}</div><DropdownMenuSeparator />- {startupConfig?.balance?.enabled === true && balanceQuery.data != null && (- <>- <div className="text-text-secondary mr-2 ml-3 py-2 text-sm" role="note">- {localize('com_nav_balance')}:{' '}- {new Intl.NumberFormat().format(Math.round(balanceQuery.data.tokenCredits))}- </div>- <DropdownMenuSeparator />- </>- )}<HelpSubmenuhelpAndFaqURL={startupConfig?.helpAndFaqURL}termsOfServiceURL={startupConfig?.interface?.termsOfService?.externalUrl}diff --git a/client/src/components/Nav/Settings/BillingControls.tsx b/client/src/components/Nav/Settings/BillingControls.tsxindex 0a177c9933..be35792984 100644--- a/client/src/components/Nav/Settings/BillingControls.tsx+++ b/client/src/components/Nav/Settings/BillingControls.tsx@@ -1,52 +1,60 @@-import type { TBalanceResponse } from 'librechat-data-provider';+import { Skeleton } from '@librechat/client';import AutoRefillSettings from '../SettingsTabs/Balance/AutoRefillSettings';-import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';-import TokenCreditsItem from '../SettingsTabs/Balance/TokenCreditsItem';-import { useAuthContext, useLocalize } from '~/hooks';--function useBalance(): Partial<TBalanceResponse> {- const { isAuthenticated } = useAuthContext();- const { data: startupConfig } = useGetStartupConfig();-- const balanceQuery = useGetUserBalance({- enabled: !!isAuthenticated && !!startupConfig?.balance?.enabled,- });-- return balanceQuery.data ?? {};-}+import useBalanceSummary from '~/hooks/useBalanceSummary';+import { formatBalanceAmount } from '~/utils';+import Balance from '~/components/Balance';+import { useLocalize } from '~/hooks';+/** The same reading the context gauge shows, so both surfaces agree. */export function TokenCredits() {- const { tokenCredits = 0 } = useBalance();- return <TokenCreditsItem tokenCredits={tokenCredits} />;+ return <Balance />;}export function AutoRefill() {const localize = useLocalize();- const {- autoRefillEnabled = false,- lastRefill,- refillAmount,- refillIntervalUnit,- refillIntervalValue,- } = useBalance();+ const { state, currency, balance } = useBalanceSummary();++ /** Settings search can show this row without the balance row beside it, so it carries its+ * own loading and failure states rather than relying on the summary's */+ if (state.status === 'loading') {+ return (+ <div className="space-y-2" aria-busy="true" data-testid="auto-refill-loading">+ <Skeleton className="h-4 w-1/2" />+ <Skeleton className="h-4 w-2/3" />+ </div>+ );+ }+ if (state.status === 'error') {+ return (+ <div className="text-text-destructive text-sm" role="alert">+ {localize('com_nav_balance_auto_refill_error')}+ </div>+ );+ }+ if (state.status !== 'success' || balance == null) {+ return null;+ }- const hasValidRefillSettings =- lastRefill !== undefined &&- refillAmount !== undefined &&- refillIntervalUnit !== undefined &&- refillIntervalValue !== undefined;+ const { summary } = state;+ const { lastRefill, refillIntervalUnit, refillIntervalValue } = balance;- if (!autoRefillEnabled) {+ /** A non-positive refill amount never refills (the server requires a positive one), the same+ * reading the balance summary gives it */+ if (!balance.autoRefillEnabled || summary.refillAmount == null) {return (- <div className="text-sm text-text-secondary">+ <div className="text-text-secondary text-sm">{localize('com_nav_balance_auto_refill_disabled')}</div>);}- if (!hasValidRefillSettings) {+ if (+ lastRefill === undefined ||+ refillIntervalUnit === undefined ||+ refillIntervalValue === undefined+ ) {return (- <div className="text-sm text-text-destructive">+ <div className="text-text-destructive text-sm">{localize('com_nav_balance_auto_refill_error')}</div>);@@ -55,7 +63,13 @@ export function AutoRefill() {return (<AutoRefillSettingslastRefill={lastRefill}- refillAmount={refillAmount}+ nextRefill={summary.nextRefill}+ /** Percent-only deployments show no credit figures anywhere */+ refillAmount={+ summary.display === 'percent'+ ? null+ : formatBalanceAmount(summary.refillAmount, summary.display, currency)+ }refillIntervalUnit={refillIntervalUnit}refillIntervalValue={refillIntervalValue}/>diff --git a/client/src/components/Nav/SettingsTabs/Balance/AutoRefillSettings.tsx b/client/src/components/Nav/SettingsTabs/Balance/AutoRefillSettings.tsxindex d040d15607..b503a8378c 100644--- a/client/src/components/Nav/SettingsTabs/Balance/AutoRefillSettings.tsx+++ b/client/src/components/Nav/SettingsTabs/Balance/AutoRefillSettings.tsx@@ -1,6 +1,5 @@import React from 'react';import { Label, InfoHoverCard, ESide } from '@librechat/client';-import { getRefillEligibilityDate } from 'librechat-data-provider';import type { RefillIntervalUnit, TBalanceResponse } from 'librechat-data-provider';import type { TranslationKeys } from '~/hooks';@@ -13,13 +12,17 @@ function ensureExhaustive(value: never): void {interface AutoRefillSettingsProps {lastRefill: NonNullable<TBalanceResponse['lastRefill']>;- refillAmount: number;+ /** When the next refill becomes eligible — the same date the balance summary counts down to */+ nextRefill: Date | null;+ /** Formatted in the deployment's display mode; null hides the row (percent-only) */+ refillAmount: string | null;refillIntervalUnit: RefillIntervalUnit;refillIntervalValue: number;}const AutoRefillSettings: React.FC<AutoRefillSettingsProps> = ({lastRefill,+ nextRefill,refillAmount,refillIntervalUnit,refillIntervalValue,@@ -28,9 +31,6 @@ const AutoRefillSettings: React.FC<AutoRefillSettingsProps> = ({const hour12 = useClockFormat();const lastRefillDate = lastRefill ? new Date(lastRefill) : null;- const refillEligibilityDate = lastRefillDate- ? getRefillEligibilityDate(lastRefillDate, refillIntervalValue, refillIntervalUnit)- : null;const getLocalizedIntervalUnit = (value: number, unit: RefillIntervalUnit): string => {let key: TranslationKeys;@@ -68,10 +68,12 @@ const AutoRefillSettings: React.FC<AutoRefillSettingsProps> = ({<span>{localize('com_nav_balance_last_refill')}</span><span>{lastRefillDate ? lastRefillDate.toLocaleString(undefined, { hour12 }) : '-'}</span></div>- <div className="mb-1 flex justify-between text-sm">- <span>{localize('com_nav_balance_refill_amount')}</span>- <span>{refillAmount !== undefined ? refillAmount : '-'}</span>- </div>+ {refillAmount != null && (+ <div className="mb-1 flex justify-between text-sm">+ <span>{localize('com_nav_balance_refill_amount')}</span>+ <span>{refillAmount}</span>+ </div>+ )}<div className="mb-1 flex justify-between text-sm"><span>{localize('com_nav_balance_interval')}</span><span>@@ -85,10 +87,8 @@ const AutoRefillSettings: React.FC<AutoRefillSettingsProps> = ({<InfoHoverCard side={ESide.Bottom} text={localize('com_nav_balance_next_refill_info')} /></div>- <span className="text-sm font-medium text-text-primary" role="note">- {refillEligibilityDate- ? refillEligibilityDate.toLocaleString(undefined, { hour12 })- : '-'}+ <span className="text-text-primary text-sm font-medium" role="note">+ {nextRefill ? nextRefill.toLocaleString(undefined, { hour12 }) : '-'}</span></div></div>diff --git a/client/src/components/Nav/SettingsTabs/Balance/TokenCreditsItem.tsx b/client/src/components/Nav/SettingsTabs/Balance/TokenCreditsItem.tsxdeleted file mode 100644index 9892ba108f..0000000000--- a/client/src/components/Nav/SettingsTabs/Balance/TokenCreditsItem.tsx+++ /dev/null@@ -1,28 +0,0 @@-import React from 'react';-import { Label, InfoHoverCard, ESide } from '@librechat/client';-import { useLocalize } from '~/hooks';--interface TokenCreditsItemProps {- tokenCredits?: number;-}--const TokenCreditsItem: React.FC<TokenCreditsItemProps> = ({ tokenCredits }) => {- const localize = useLocalize();-- return (- <div className="flex items-center justify-between">- {/* Left Section: Label */}- <div className="flex items-center space-x-2">- <Label className="font-light">{localize('com_nav_balance')}</Label>- <InfoHoverCard side={ESide.Bottom} text={localize('com_nav_info_balance')} />- </div>-- {/* Right Section: tokenCredits Value */}- <span className="text-sm font-medium text-text-primary" role="note">- {tokenCredits !== undefined ? tokenCredits.toFixed(2) : '0.00'}- </span>- </div>- );-};--export default TokenCreditsItem;diff --git a/client/src/hooks/useBalanceSummary.ts b/client/src/hooks/useBalanceSummary.tsnew file mode 100644index 0000000000..ea505c46d6--- /dev/null+++ b/client/src/hooks/useBalanceSummary.ts@@ -0,0 +1,74 @@+import { useMemo } from 'react';+import { BALANCE_DISPLAY_MODES } from 'librechat-data-provider';+import type { BalanceDisplay, TBalanceResponse } from 'librechat-data-provider';+import type { BalanceSummary, CurrencyConfig } from '~/utils';+import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';+import { useAuthContext } from '~/hooks/AuthContext';+import { summarizeBalance } from '~/utils';++export type BalanceState =+ | { status: 'loading' }+ | { status: 'error' }+ /** Balance is on in the startup config but the server sent no record for this user */+ | { status: 'empty' }+ | { status: 'success'; summary: BalanceSummary };++/** Hover opens the gauge card, which mounts a reader; within this window a reopen reuses+ * the reading. Streams refetch explicitly after each turn, which bypasses it. */+const BALANCE_STALE_MS = 30_000;++/** Admin config overrides persist without schema validation, so an unknown mode can arrive. */+const toDisplay = (value: unknown): BalanceDisplay =>+ BALANCE_DISPLAY_MODES.find((mode) => mode === value) ?? 'credits';++export interface BalanceView {+ enabled: boolean;+ state: BalanceState;+ currency?: CurrencyConfig;+ /** The raw record, for detail rows the summary does not carry */+ balance?: TBalanceResponse;+}++/** How the deployment shows balance figures, for surfaces that only format an amount. */+export function useBalanceDisplay(): { display: BalanceDisplay; currency?: CurrencyConfig } {+ const { data: startupConfig } = useGetStartupConfig();+ return {+ display: toDisplay(startupConfig?.balance?.display),+ currency: startupConfig?.interface?.currency,+ };+}++/**+ * The user's balance as every surface presents it. A stale reading wins over a+ * failed refetch, so a transient error never blanks a figure the user already saw.+ */+export default function useBalanceSummary(): BalanceView {+ const { isAuthenticated } = useAuthContext();+ const { data: startupConfig } = useGetStartupConfig();+ const { display, currency } = useBalanceDisplay();+ const config = startupConfig?.balance;+ const enabled = config?.enabled === true;+ const query = useGetUserBalance({+ enabled: isAuthenticated === true && enabled,+ staleTime: BALANCE_STALE_MS,+ });+ const { data, isError } = query;+ const startBalance = config?.startBalance;++ const state = useMemo<BalanceState>(() => {+ if (data != null && typeof data.tokenCredits === 'number') {+ return { status: 'success', summary: summarizeBalance(data, { display, startBalance }) };+ }+ if (isError) {+ return { status: 'error' };+ }+ return query.isFetched ? { status: 'empty' } : { status: 'loading' };+ }, [data, isError, query.isFetched, display, startBalance]);++ return {+ enabled,+ state,+ currency,+ balance: state.status === 'success' ? data : undefined,+ };+}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 43ab38d6e6..0821d079f4 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -59,6 +59,18 @@"com_ui_background_tasks_subagent_pending_guidance": "Finished subagent results are pending delivery. Poll to collect now or wait for the agent to resume.","com_ui_background_tasks_subagent_wakeup_guidance": "This subagent will automatically resume the agent when it finishes; there is no need to poll it repeatedly.","com_ui_background_tasks_subagent_poll_guidance": "This subagent's result is not delivered automatically; the agent checks on it again later.",+ "com_ui_balance_credits": "{{0}} credits",+ "com_ui_balance_empty": "Out of credits",+ "com_ui_balance_error": "Couldn't load your balance",+ "com_ui_balance_no_refill": "Doesn't refill automatically",+ "com_ui_balance_refill_amount_in": "+{{0}} available {{1}}",+ "com_ui_balance_refill_amount_when_empty": "+{{0}} when you run out",+ "com_ui_balance_refill_in": "Refill available {{0}}",+ "com_ui_balance_refill_when_empty": "Refills when you run out",+ "com_ui_balance_usage_limit": "Usage limit",+ "com_ui_balance_used": "{{0}}% used",+ "com_ui_balance_used_label": "Share of balance used",+ "com_ui_balance_usage_unavailable": "Usage unavailable","com_ui_repository_instructions": "Repository instructions","com_ui_repository_instructions_prefer": "Prefer repository conventions","com_ui_repository_instructions_defer": "Prefer agent conventions",@@ -673,8 +685,10 @@"com_error_stream_expired": "The response stream has expired or already completed. Please try again.","com_error_stt_limit": "You have reached the speech-to-text limit of {{0}} requests per {{1}}.","com_error_token_balance": "You do not have enough token credits for this request. It needs {{0}} credits and your balance is {{1}}.",+ "com_error_token_balance_currency": "You do not have enough balance for this request. It costs {{0}} and your balance is {{1}}.","com_error_token_balance_generation": "{{0}} — {{1}} prompt tokens, {{2}} completion tokens","com_error_token_balance_generations": "Recent generations",+ "com_error_token_balance_hidden": "You do not have enough balance left for this request.","com_error_token_balance_prompt": "Prompt size: {{0}} tokens.","com_error_tool_call_limit": "You have reached the tool call limit. Wait a moment and try again.","com_error_tts_limit": "You have reached the text-to-speech limit of {{0}} requests per {{1}}.",@@ -820,7 +834,6 @@"com_nav_font_size_xs": "Extra Small","com_nav_help": "Help","com_nav_help_faq": "Help & FAQ",- "com_nav_info_balance": "Balance shows how many token credits you have left to use. Token credits translate to monetary value (e.g., 1000 credits = $0.001 USD)","com_nav_info_client_image_resize": "When enabled, large images are downscaled in your browser before they are uploaded, which speeds up uploads and uses less bandwidth. Images already within the size limits are sent unchanged.","com_nav_info_client_image_resize_enforced": "This setting is managed by your administrator and cannot be changed here.","com_nav_info_client_image_resize_unavailable": "Image resizing is unavailable because the file settings could not be loaded. Reload the page to try again.",diff --git a/client/src/utils/__tests__/balance.spec.ts b/client/src/utils/__tests__/balance.spec.tsnew file mode 100644index 0000000000..5b1b4aa5c0--- /dev/null+++ b/client/src/utils/__tests__/balance.spec.ts@@ -0,0 +1,100 @@+import type { TBalanceResponse } from 'librechat-data-provider';+import { summarizeBalance, formatBalanceAmount, formatTimeUntil } from '../balance';++const refilling = (over: Partial<TBalanceResponse> = {}): TBalanceResponse => ({+ tokenCredits: 12_400,+ autoRefillEnabled: true,+ refillAmount: 20_000,+ refillIntervalValue: 7,+ refillIntervalUnit: 'days',+ lastRefill: '2026-07-01T00:00:00.000Z',+ ...over,+});++describe('summarizeBalance', () => {+ it('measures spend against the refill amount under auto-refill', () => {+ const summary = summarizeBalance(refilling(), { display: 'credits', startBalance: 50_000 });+ expect(summary.allotment).toBe(20_000);+ expect(summary.usedPercent).toBe(38);+ expect(summary.tone).toBe('normal');+ expect(summary.refillAmount).toBe(20_000);+ expect(summary.nextRefill?.toISOString()).toBe('2026-07-08T00:00:00.000Z');+ });++ it('falls back to the starting balance without auto-refill', () => {+ const summary = summarizeBalance(+ { tokenCredits: 5_000, autoRefillEnabled: false },+ { display: 'percent', startBalance: 20_000 },+ );+ expect(summary.allotment).toBe(20_000);+ expect(summary.usedPercent).toBe(75);+ expect(summary.refillAmount).toBeNull();+ expect(summary.nextRefill).toBeNull();+ });++ it('has no percent without an allotment to measure against', () => {+ const summary = summarizeBalance({ tokenCredits: 5_000, autoRefillEnabled: false });+ expect(summary.display).toBe('credits');+ expect(summary.usedPercent).toBeNull();+ expect(summary.tone).toBe('normal');+ });++ it('reads 0% used when saved-up credits exceed the allotment', () => {+ const summary = summarizeBalance(refilling({ tokenCredits: 45_000 }));+ expect(summary.usedPercent).toBe(0);+ });++ it('never reads 100% used while credits remain', () => {+ const summary = summarizeBalance(refilling({ tokenCredits: 1 }));+ expect(summary.usedPercent).toBe(99);+ expect(summary.tone).toBe('warning');+ });++ it('warns from 90% spent and is empty at zero credits', () => {+ expect(summarizeBalance(refilling({ tokenCredits: 2_000 })).tone).toBe('warning');+ expect(summarizeBalance(refilling({ tokenCredits: 2_001 })).tone).toBe('normal');+ const empty = summarizeBalance(refilling({ tokenCredits: 0 }));+ expect(empty.usedPercent).toBe(100);+ expect(empty.tone).toBe('danger');+ });++ it('is empty without an allotment once credits run out', () => {+ const empty = summarizeBalance({ tokenCredits: -5, autoRefillEnabled: false });+ expect(empty.tone).toBe('danger');+ expect(empty.usedPercent).toBe(100);+ });++ it('drops an unreadable last-refill date instead of inventing one', () => {+ expect(summarizeBalance(refilling({ lastRefill: 'not a date' })).nextRefill).toBeNull();+ });+});++describe('formatBalanceAmount', () => {+ it('formats credits without hiding fractional differences', () => {+ expect(formatBalanceAmount(3_100_000, 'credits')).toBe('3,100,000');+ expect(formatBalanceAmount(100.4, 'credits')).toBe('100.4');+ expect(formatBalanceAmount(100.3, 'credits')).toBe('100.3');+ expect(formatBalanceAmount(12_480.656, 'credits')).toBe('12,480.66');+ });++ it('converts credits to money at one million credits per dollar', () => {+ expect(formatBalanceAmount(3_100_000, 'currency')).toBe('$3.10');+ expect(formatBalanceAmount(5_000_000, 'currency', { code: 'EUR', rate: 0.5 })).toBe('€2.50');+ });+});++describe('formatTimeUntil', () => {+ const now = Date.parse('2026-10-05T00:00:00.000Z');+ const at = (ms: number) => new Date(now + ms);++ it('picks minutes, hours, then days', () => {+ expect(formatTimeUntil(at(5 * 60_000), now, 'en')).toBe('in 5 minutes');+ expect(formatTimeUntil(at(3 * 3_600_000), now, 'en')).toBe('in 3 hours');+ expect(formatTimeUntil(at(3 * 86_400_000), now, 'en')).toBe('in 3 days');+ });++ it('is null once the moment has passed', () => {+ expect(formatTimeUntil(at(0), now, 'en')).toBeNull();+ expect(formatTimeUntil(at(-1), now, 'en')).toBeNull();+ });+});diff --git a/client/src/utils/balance.ts b/client/src/utils/balance.tsnew file mode 100644index 0000000000..ce36fd913b--- /dev/null+++ b/client/src/utils/balance.ts@@ -0,0 +1,125 @@+import { CREDITS_PER_USD, getRefillEligibilityDate } from 'librechat-data-provider';+import type { BalanceDisplay, TBalanceResponse } from 'librechat-data-provider';+import type { CurrencyConfig } from './tokens';+import { formatCost } from './tokens';++/** Share of the allotment spent at which the balance reads as running low. */+export const BALANCE_WARNING_PERCENT = 90;++export type BalanceTone = 'normal' | 'warning' | 'danger';++/**+ * One reading of the user's balance. Every surface that shows the balance renders+ * from this, so the gauge popover and the settings dialog cannot disagree.+ */+export interface BalanceSummary {+ display: BalanceDisplay;+ credits: number;+ /** Credits one period grants: the refill amount under auto-refill, else the starting balance. */+ allotment: number | null;+ /** Whole percent of the allotment spent, 0–100; 100 once credits run out, else null without+ * an allotment to measure against. */+ usedPercent: number | null;+ tone: BalanceTone;+ /** Credits the next auto-refill adds; null without auto-refill. */+ refillAmount: number | null;+ /** When the next auto-refill becomes eligible; null without auto-refill. */+ nextRefill: Date | null;+}++interface SummaryOptions {+ display?: BalanceDisplay;+ startBalance?: number;+}++const positive = (value: unknown): number | null =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;++function getNextRefill(balance: TBalanceResponse): Date | null {+ const { lastRefill, refillIntervalValue, refillIntervalUnit } = balance;+ if (lastRefill == null || refillIntervalValue == null || refillIntervalUnit == null) {+ return null;+ }+ const last = new Date(lastRefill);+ if (Number.isNaN(last.getTime())) {+ return null;+ }+ return getRefillEligibilityDate(last, refillIntervalValue, refillIntervalUnit);+}++/**+ * Percent spent is floored while credits remain, so a nearly drained balance never+ * reads "100% used" before it is actually empty; an empty balance is fully spent+ * whatever it is measured against.+ */+function getUsedPercent(credits: number, allotment: number | null): number | null {+ if (credits <= 0) {+ return 100;+ }+ if (allotment == null) {+ return null;+ }+ const spent = (1 - credits / allotment) * 100;+ return Math.min(Math.max(Math.floor(spent), 0), 99);+}++export function summarizeBalance(+ balance: TBalanceResponse,+ { display = 'credits', startBalance }: SummaryOptions = {},+): BalanceSummary {+ const credits = Number.isFinite(balance.tokenCredits) ? balance.tokenCredits : 0;+ const refillAmount = balance.autoRefillEnabled ? positive(balance.refillAmount) : null;+ const allotment = refillAmount ?? positive(startBalance);+ const usedPercent = getUsedPercent(credits, allotment);++ let tone: BalanceTone = 'normal';+ if (credits <= 0) {+ tone = 'danger';+ } else if (usedPercent != null && usedPercent >= BALANCE_WARNING_PERCENT) {+ tone = 'warning';+ }++ return {+ display,+ credits,+ allotment,+ usedPercent,+ tone,+ refillAmount,+ nextRefill: balance.autoRefillEnabled ? getNextRefill(balance) : null,+ };+}++/** A credit amount in the configured display: money for `currency`, whole credits otherwise. */+export function formatBalanceAmount(+ credits: number,+ display: BalanceDisplay,+ currency?: CurrencyConfig,+): string {+ if (display === 'currency') {+ return formatCost(credits / CREDITS_PER_USD, currency);+ }+ /** Credits are fractional when pricing multipliers are; two places keep a shortfall like+ * 100.4 against 100.3 visible, and whole amounts still print without decimals */+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(credits);+}++const MINUTE_MS = 60_000;+const HOUR_MS = 60 * MINUTE_MS;+const DAY_MS = 24 * HOUR_MS;++/** "in 5 minutes" / "in 3 hours" / "in 4 days"; null once the moment has passed. */+export function formatTimeUntil(target: Date, now: number, locale?: string): string | null {+ const remaining = target.getTime() - now;+ if (!(remaining > 0)) {+ return null;+ }+ const format = new Intl.RelativeTimeFormat(locale, { numeric: 'always' });+ if (remaining < HOUR_MS) {+ return format.format(Math.max(1, Math.ceil(remaining / MINUTE_MS)), 'minute');+ }+ if (remaining < 2 * DAY_MS) {+ return format.format(Math.ceil(remaining / HOUR_MS), 'hour');+ }+ return format.format(Math.ceil(remaining / DAY_MS), 'day');+}diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex 3ca170582e..4b7c29ed72 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -32,6 +32,7 @@ export * from './textarea';export * from './messages';export * from './focus';export * from './tokens';+export * from './balance';export * from './redirect';export * from './links';export * from './languages';diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex deb401503a..fd4666cb83 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -308,9 +308,6 @@}},"client/src/components/Chat/Input/TokenUsage/index.tsx": {- "shadcn/no-arbitrary-values": {- "count": 1- },"shadcn/no-restyle": {"count": 1}diff --git a/librechat.example.yaml b/librechat.example.yamlindex 77759dd394..b11190aae4 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -440,6 +440,7 @@ registration:# refillIntervalUnit: 'days'# refillAmount: 10000# reservationTtlMs: 1800000 # How long an in-flight request's reserved credits count if never released+# display: 'credits' # credits | currency (uses interface.currency) | percent (share of the allotment used)# Example Transactions settings# Controls whether to save transaction records to the databasediff --git a/packages/client/src/components/Progress.spec.tsx b/packages/client/src/components/Progress.spec.tsxnew file mode 100644index 0000000000..eba0e20e5d--- /dev/null+++ b/packages/client/src/components/Progress.spec.tsx@@ -0,0 +1,83 @@+import '@testing-library/jest-dom';+import { join } from 'node:path';+import { readFileSync } from 'node:fs';+import { render, screen } from '@testing-library/react';+import type { ThemeDefinition } from '../theme/types';+import { resolveTheme, validateThemeDefinition, THEME_VERSION } from '../theme/registry';+import { applyResolvedTheme, clearAppliedTheme } from '../theme/utils/applyTheme';+import { Progress } from './Progress';++const indicator = () => screen.getByRole('progressbar').firstElementChild as HTMLElement;++describe('Progress', () => {+ it('reports its value to assistive tech', () => {+ render(<Progress value={38} aria-label="Used" />);+ const bar = screen.getByRole('progressbar', { name: 'Used' });+ expect(bar).toHaveAttribute('aria-valuenow', '38');+ expect(indicator().style.transform).toBe('translateX(-62%)');+ });++ it('fills with the inverted surface by default', () => {+ render(<Progress value={10} />);+ expect(indicator()).toHaveClass('bg-surface-inverted');+ });++ it.each([+ ['warning', 'bg-status-warning'],+ ['error', 'bg-status-error'],+ ] as const)('fills the %s variant from its status token', (variant, token) => {+ render(<Progress value={95} variant={variant} />);+ expect(indicator()).toHaveClass(token);+ expect(indicator()).not.toHaveClass('bg-surface-inverted');+ expect(screen.getByRole('progressbar')).toHaveClass('bg-surface-tertiary');+ });+});++/** AGENTS.md requires a deliberately different reference theme, to prove the+ * variants follow theme data rather than the bundled LibreChat values. */+const referenceTheme: ThemeDefinition = {+ version: THEME_VERSION,+ name: 'reference',+ modes: {+ light: {+ colors: {+ 'rgb-status-warning': '11 22 33',+ 'rgb-status-error': '44 55 66',+ 'rgb-surface-inverted': '77 88 99',+ },+ },+ },+};++describe('Progress under a reference theme', () => {+ afterEach(() => {+ clearAppliedTheme();+ });++ it('is accepted by the registry and lands on the variables the fills read', () => {+ expect(validateThemeDefinition(referenceTheme)).toEqual([]);+ applyResolvedTheme(resolveTheme(referenceTheme, 'light'));+ const root = document.documentElement;+ expect(root.style.getPropertyValue('--status-warning')).toBe('11 22 33');+ expect(root.style.getPropertyValue('--status-error')).toBe('44 55 66');+ expect(root.style.getPropertyValue('--surface-inverted')).toBe('77 88 99');++ const tokens = readFileSync(join(__dirname, '../theme/tokens.css'), 'utf8');+ expect(tokens).toContain('--color-status-warning: rgb(var(--status-warning));');+ expect(tokens).toContain('--color-status-error: rgb(var(--status-error));');+ expect(tokens).toContain('--color-surface-inverted: rgb(var(--surface-inverted));');+ });++ it('paints no colour of its own', () => {+ applyResolvedTheme(resolveTheme(referenceTheme, 'light'));+ const { container } = render(+ <>+ <Progress value={20} />+ <Progress value={92} variant="warning" />+ <Progress value={100} variant="error" />+ </>,+ );+ expect(container.innerHTML).not.toMatch(/#[0-9a-f]{3,8}\b/i);+ expect(container.innerHTML).not.toMatch(/\brgba?\((?!var\()/);+ });+});diff --git a/packages/client/src/components/Progress.tsx b/packages/client/src/components/Progress.tsxindex 0d9d7a1dfe..47dcdd6854 100644--- a/packages/client/src/components/Progress.tsx+++ b/packages/client/src/components/Progress.tsx@@ -1,28 +1,53 @@import * as React from 'react';+import { ClassProp } from 'class-variance-authority/types';import * as ProgressPrimitive from '@radix-ui/react-progress';+import { cva, type VariantProps } from 'class-variance-authority';import { cn } from '~/utils';+/** Fill tone for the indicator; the track stays neutral in every variant. */+const progressIndicatorVariants: (+ props?:+ | ({+ variant?: 'default' | 'warning' | 'error' | null | undefined;+ } & ClassProp)+ | undefined,+) => string = cva('h-full w-full flex-1 transition-all motion-reduce:transition-none', {+ variants: {+ variant: {+ default: 'bg-surface-inverted',+ warning: 'bg-status-warning',+ error: 'bg-status-error',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+});++export interface ProgressProps+ extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>,+ VariantProps<typeof progressIndicatorVariants> {}+const Progress: React.ForwardRefExoticComponent<- Omit<ProgressPrimitive.ProgressProps & React.RefAttributes<HTMLDivElement>, 'ref'> &- React.RefAttributes<HTMLDivElement>-> = React.forwardRef<- React.ElementRef<typeof ProgressPrimitive.Root>,- React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>->(({ className, value, ...props }, ref) => (- <ProgressPrimitive.Root- ref={ref}- className={cn(- 'relative h-2 w-full overflow-hidden rounded-full bg-surface-tertiary',- className,- )}- {...props}- >- <ProgressPrimitive.Indicator- className="h-full w-full flex-1 bg-surface-inverted transition-all"- style={{ transform: `translateX(-${100 - (value || 0)}%)` }}- />- </ProgressPrimitive.Root>-));+ ProgressProps & React.RefAttributes<HTMLDivElement>+> = React.forwardRef<React.ElementRef<typeof ProgressPrimitive.Root>, ProgressProps>(+ ({ className, variant, value, ...props }, ref) => (+ <ProgressPrimitive.Root+ ref={ref}+ value={value}+ className={cn(+ 'bg-surface-tertiary relative h-2 w-full overflow-hidden rounded-full',+ className,+ )}+ {...props}+ >+ <ProgressPrimitive.Indicator+ className={progressIndicatorVariants({ variant })}+ style={{ transform: `translateX(-${100 - (value || 0)}%)` }}+ />+ </ProgressPrimitive.Root>+ ),+);Progress.displayName = ProgressPrimitive.Root.displayName;export { Progress };diff --git a/packages/data-provider/src/balance.ts b/packages/data-provider/src/balance.tsindex ed199a3b11..17e2f07db2 100644--- a/packages/data-provider/src/balance.ts+++ b/packages/data-provider/src/balance.ts@@ -9,6 +9,15 @@ export const REFILL_INTERVAL_UNITS = [export type RefillIntervalUnit = (typeof REFILL_INTERVAL_UNITS)[number];+/** How the UI presents a balance: raw credits, their currency value, or the share of the+ * period's allotment already spent. */+export const BALANCE_DISPLAY_MODES = ['credits', 'currency', 'percent'] as const;++export type BalanceDisplay = (typeof BALANCE_DISPLAY_MODES)[number];++/** Token credits per US dollar: transaction rates are USD per million tokens. */+export const CREDITS_PER_USD = 1_000_000;+/** How long an unreleased in-flight balance reservation keeps counting against the balance. */export const DEFAULT_BALANCE_RESERVATION_TTL_MS = 30 * 60 * 1000;/** Shortest reservation TTL; a live reservation is renewed every half TTL. */diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 9f71c79ba1..23e4709aeb 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -30,6 +30,7 @@ import {} from './schemas';import {REFILL_INTERVAL_UNITS,+ BALANCE_DISPLAY_MODES,MIN_BALANCE_RESERVATION_TTL_MS,DEFAULT_BALANCE_RESERVATION_TTL_MS,} from './balance';@@ -3395,6 +3396,8 @@ export const balanceSchema = z.object({.min(MIN_BALANCE_RESERVATION_TTL_MS).optional().default(DEFAULT_BALANCE_RESERVATION_TTL_MS),+ /** How the UI presents the balance; `credits` keeps the raw figure. */+ display: z.enum(BALANCE_DISPLAY_MODES).optional().default('credits'),});export const transactionsSchema = z.object({