📊 refactor: Move the Context Usage Popover Into @librechat/chat (#17799)

* refactor: Move the Context Usage Popover Pieces Into @librechat/chat

* test: Cover the Context Usage Pieces in the Chat Package

* fix: Ship the Collapsible Animations With the Shared Tailwind Preset

* test: Keep the Expanded Breakdown Choice Across Remounts

* test: Assert the Absent Compaction Hint by Its Fixed Copy

* refactor: Give Collapsible and HoverCard the Breakdown Disclosure Styles

* test: Cover the Breakdown Roll and Remembered Choice in the Browser

* chore: Retest Against Current Dev
This commit is contained in:
Marco Beretta 2026-11-05 22:36:51 +01:00 • committed by GitHub
parent 62cc2ffc19
commit 84a36630a0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 609 additions and 367 deletions

View file

@ -36,9 +36,22 @@ jest.mock('~/hooks/Chat/useCompactConversation', () => ({
supportsCompaction: () => false,
}));
jest.mock('./Breakdown', () => ({
__esModule: true,
default: () => <div data-testid="context-breakdown-stub" />,
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
ContextBreakdown: ({
expanded,
onExpandedChange,
}: {
expanded: boolean;
onExpandedChange: (expanded: boolean) => void;
}) => (
<button
type="button"
data-testid="context-breakdown-stub"
aria-expanded={expanded}
onClick={() => onExpandedChange(!expanded)}
/>
),
}));
const NOW = Date.parse('2026-07-05T00:00:00.000Z');
@ -170,6 +183,29 @@ describe('TokenUsage gauge', () => {
expect(screen.getByTestId('token-usage-card')).toHaveClass('w-72');
});
it('keeps the expanded breakdown choice across remounts', async () => {
localStorage.clear();
mockStartupConfig.mockReturnValue(config());
mockTokenUsage.mockReturnValue(usage(83_200));
const tree = () => (
<Provider store={createStore()}>
<TokenUsage index={0} conversation={conversation} isSubmitting={false} />
</Provider>
);
const first = render(tree());
await openCard();
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
expect(screen.getByTestId('context-breakdown-stub')).toHaveAttribute('aria-expanded', 'false');
await user.click(screen.getByTestId('context-breakdown-stub'));
expect(screen.getByTestId('context-breakdown-stub')).toHaveAttribute('aria-expanded', 'true');
first.unmount();
render(tree());
await openCard();
expect(screen.getByTestId('context-breakdown-stub')).toHaveAttribute('aria-expanded', 'true');
localStorage.clear();
});
it('tints the balance-only ring with the balance tone, amber until empty', () => {
mockStartupConfig.mockReturnValue(config({ contextUsage: false }));
mockBalance.mockReturnValue({ ...balance, tokenCredits: 400_000 });

View file

@ -1,7 +1,13 @@
import { memo } from 'react';
import { useAtomValue } from 'jotai';
import { Spinner } from '@librechat/client';
import { useAtom, useAtomValue } from 'jotai';
import { Constants } from 'librechat-data-provider';
import {
CompactAction,
ContextBreakdown as Breakdown,
ContextGauge as Gauge,
ContextUsagePopover as UsagePopover,
} from '@librechat/chat/components';
import type { TConversation } from 'librechat-data-provider';
import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';
import type { CurrencyConfig } from '~/utils';
@ -11,12 +17,8 @@ import Balance, { Summary as BalanceSummary } from '~/components/Balance';
import useBalanceSummary from '~/hooks/useBalanceSummary';
import useTokenUsage from '~/hooks/Chat/useTokenUsage';
import { contextBreakdownExpandedAtom } from './store';
import CompactAction from './CompactAction';
import { cn, formatTokens } from '~/utils';
import { useLocalize } from '~/hooks';
import UsagePopover from './Popover';
import Breakdown from './Breakdown';
import Gauge from './Gauge';
interface TokenUsageProps {
index: number;
@ -47,6 +49,7 @@ function ContextCard({
compaction,
compactionAvailable,
}: ContextCardProps) {
const [breakdownExpanded, setBreakdownExpanded] = useAtom(contextBreakdownExpandedAtom);
const canResolveLangfuseSession =
langfuseConnectionAccess &&
!isSubmitting &&
@ -66,6 +69,8 @@ function ContextCard({
compactionAvailable={compactionAvailable}
currency={currency}
langfuseSessionUrl={langfuseSession?.url ?? undefined}
expanded={breakdownExpanded}
onExpandedChange={setBreakdownExpanded}
/>
{compactionAvailable && (
<>

View file

@ -17,7 +17,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/Popover.tsx', ['size-theme-control', 'rounded-theme-control-round']],
['usage/Popover.tsx', ['size-theme-control', 'rounded-theme-control-round']],
/** The context rail's pills share one recipe built on the composer control classes. */
['chip.ts', ['composerControlClasses()']],
['CodeApprovalMenu.tsx', ['chipClasses']],

View file

@ -1,60 +0,0 @@
import { formatCost } from './tokens';
describe('formatCost', () => {
it('formats across magnitude bands (USD default, unchanged)', () => {
expect(formatCost(0)).toBe('$0.00');
expect(formatCost(0.004)).toBe('<$0.01');
expect(formatCost(0.0523)).toBe('$0.0523');
expect(formatCost(1.234)).toBe('$1.23');
});
it('applies the static USD→local rate', () => {
expect(formatCost(2, { code: 'USD', rate: 0.5 })).toBe('$1.00');
expect(formatCost(10, { code: 'USD', rate: 0.1 })).toBe('$1.00');
});
it('formats in the configured currency', () => {
const eur = formatCost(5, { code: 'EUR', rate: 1 });
expect(eur).toContain('€');
expect(eur).toContain('5');
});
it('respects zero-decimal currencies', () => {
const jpy = formatCost(5, { code: 'JPY', rate: 1 });
expect(jpy).toContain('¥');
expect(jpy).not.toContain('.');
});
it('falls back to USD on a malformed currency code', () => {
expect(formatCost(5, { code: 'invalid', rate: 1 })).toBe('$5.00');
});
it('drops the rate too when the currency code is unsupported', () => {
/** A typo in `code` must not leave a converted amount under the $ symbol. */
expect(formatCost(10, { code: 'EURO', rate: 0.92 })).toBe('$10.00');
});
it('rejects well-formed but non-ISO codes that Intl would accept', () => {
/** `EUU`/`RMB` are 3 letters so Intl does not throw; the ISO-4217 set must
* still reject them and fall back to USD (no converted amount, no rate). */
expect(formatCost(10, { code: 'EUU', rate: 0.92 })).toBe('$10.00');
expect(formatCost(10, { code: 'RMB', rate: 0.5 })).toBe('$10.00');
});
it('uses the currency minor unit for three-decimal currencies', () => {
/** KWD has 3 fractional digits, so the tiny threshold is 0.001, not 0.01. */
const small = formatCost(0.005, { code: 'KWD', rate: 1 });
expect(small).toContain('0.005');
expect(small).not.toContain('<');
expect(formatCost(0.0005, { code: 'KWD', rate: 1 })).toContain('0.001');
});
it('falls back to rate 1 when rate is not a finite positive number', () => {
/** Partial admin override (code set before rate) must never render NaN. */
const eur = formatCost(10, { code: 'EUR', rate: undefined as unknown as number });
expect(eur).toContain('€');
expect(eur).toContain('10');
expect(eur).not.toContain('NaN');
expect(formatCost(10, { code: 'USD', rate: Number.NaN })).toBe('$10.00');
});
});

View file

@ -3,6 +3,7 @@ export type {
BranchTotals,
BranchUsage,
CostUnits,
CurrencyConfig,
TokenEntry,
ToolTokenGroups,
} from '@librechat/chat';
@ -16,6 +17,7 @@ export {
collectAnchorSeries,
countTrailingOutputChars,
estimateTokens,
formatCost,
formatTokens,
findBranchSnapshotAnchor,
getOutputChars,
@ -43,101 +45,3 @@ export {
upsertEntries,
usageHistory,
} from '@librechat/chat';
/** Display currency for the context cost. `rate` is a static USD→local
* multiplier (no live FX); `code` is an ISO-4217 currency for Intl formatting. */
export interface CurrencyConfig {
code: string;
rate: number;
}
const DEFAULT_CURRENCY: CurrencyConfig = { code: 'USD', rate: 1 };
const currencyFormatters = new Map<string, Intl.NumberFormat>();
const currencyDigits = new Map<string, number>();
let supportedCurrencies: Set<string> | null | undefined;
/** True only for codes recognized as ISO-4217. `Intl.NumberFormat` accepts any
* well-formed three-letter code (e.g. `EUU`, `RMB`) without throwing, so the
* ISO-4217 set is the real guard against typo'd / non-ISO codes. */
function isSupportedCurrency(code: unknown): code is string {
if (typeof code !== 'string' || code.length === 0) {
return false;
}
const upper = code.toUpperCase();
if (supportedCurrencies === undefined) {
const supportedValuesOf = (
Intl as typeof Intl & { supportedValuesOf?: (key: string) => string[] }
).supportedValuesOf;
supportedCurrencies =
typeof supportedValuesOf === 'function' ? new Set(supportedValuesOf('currency')) : null;
}
if (supportedCurrencies != null) {
return supportedCurrencies.has(upper);
}
/** Older runtime without `supportedValuesOf`: accept any code Intl can build. */
try {
new Intl.NumberFormat(undefined, { style: 'currency', currency: upper });
return true;
} catch {
return false;
}
}
/** Default fraction digits for a validated currency: USD→2, JPY→0, KWD→3. */
function maxFractionDigits(code: string): number {
const cached = currencyDigits.get(code);
if (cached !== undefined) {
return cached;
}
const digits =
new Intl.NumberFormat(undefined, { style: 'currency', currency: code }).resolvedOptions()
.maximumFractionDigits ?? 2;
currencyDigits.set(code, digits);
return digits;
}
function currencyFormatter(code: string, minDigits: number, maxDigits: number): Intl.NumberFormat {
const key = `${code}:${minDigits}:${maxDigits}`;
let formatter = currencyFormatters.get(key);
if (formatter == null) {
formatter = new Intl.NumberFormat(undefined, {
style: 'currency',
currency: code,
minimumFractionDigits: minDigits,
maximumFractionDigits: maxDigits,
});
currencyFormatters.set(key, formatter);
}
return formatter;
}
export function formatCost(usd: number, currency: CurrencyConfig = DEFAULT_CURRENCY): string {
/** Resolve to a safe (code, rate): an unsupported code falls back to USD AND
* rate 1 — never present a converted amount under the wrong symbol. A
* non-finite/negative rate (e.g. a partial admin override that set `code`
* before `rate`) falls back to 1 so a cost never renders as `NaN`. */
let code = DEFAULT_CURRENCY.code;
let rate = 1;
if (isSupportedCurrency(currency?.code)) {
code = currency.code.toUpperCase();
rate = Number.isFinite(currency?.rate) && (currency.rate as number) > 0 ? currency.rate : 1;
}
const base = maxFractionDigits(code);
const amount = (Number.isFinite(usd) && usd > 0 ? usd : 0) * rate;
/** The currency's own minor unit — USD/EUR→0.01, JPY→1, KWD→0.001. */
const smallest = Math.pow(10, -base);
if (amount <= 0) {
return currencyFormatter(code, base, base).format(0);
}
if (amount < smallest) {
return `<${currencyFormatter(code, base, base).format(smallest)}`;
}
if (amount < 1 && base > 0) {
/** Extra precision for sub-unit costs; trailing zeros trim to the currency's
* own scale (min = base). */
return currencyFormatter(code, base, base + 2).format(amount);
}
return currencyFormatter(code, base, base).format(amount);
}

View file

@ -30,18 +30,6 @@ module.exports = {
from: { height: 'var(--radix-accordion-content-height)' },
to: { height: 0 },
},
/** Radix Collapsible exposes its own height variable, not the accordion one.
* The fade rides along so the rows dissolve instead of squashing. Opening
* decelerates into place; closing accelerates away, because a decelerating
* close stalls over its final pixels before the unmount. */
'collapsible-down': {
from: { height: 0, opacity: 0 },
to: { height: 'var(--radix-collapsible-content-height)', opacity: 1 },
},
'collapsible-up': {
from: { height: 'var(--radix-collapsible-content-height)', opacity: 1 },
to: { height: 0, opacity: 0 },
},
'slide-in-right': {
'0%': { transform: 'translateX(calc(100% * var(--dir-sign, 1)))' },
'100%': { transform: 'translateX(0)' },
@ -81,8 +69,6 @@ module.exports = {
'fade-in': 'fadeIn 0.5s ease-out forwards',
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
'collapsible-down': 'collapsible-down 0.3s cubic-bezier(0, 0, 0.2, 1)',
'collapsible-up': 'collapsible-up 0.2s cubic-bezier(0.4, 0, 1, 1)',
'slide-in-right': 'slide-in-right 300ms cubic-bezier(0.25, 0.1, 0.25, 1)',
'slide-in-left': 'slide-in-left 300ms cubic-bezier(0.25, 0.1, 0.25, 1)',
'slide-out-left': 'slide-out-left 300ms cubic-bezier(0.25, 0.1, 0.25, 1)',

View file

@ -1,5 +1,6 @@
import { randomUUID } from 'crypto';
import { expect, test } from '@playwright/test';
import type { Locator } from '@playwright/test';
import { getE2EUser } from '../../../setup/user';
import { deleteConversations, deleteMessagesByConversation, withMongo } from '../db';
@ -345,4 +346,91 @@ test.describe('persisted context usage', () => {
expect(used).toBeDefined();
expect(peerSum).toBe(Number(used));
});
/** The roll is defined in the shared Tailwind preset because the breakdown now ships from
* @librechat/chat, so an animation name of `none` here means the keyframes never reached
* the app's stylesheet and the panel snaps open. The expanded choice is the host's: the
* package only reads it through props, so a reload proves the app still persists it. */
test('rolls the breakdown open and keeps the choice across a reload @scenario:context-breakdown-rolls-open-and-remembers', async ({
page,
}) => {
test.setTimeout(120000);
const conversationId = randomUUID();
cleanupConversationIds.push(conversationId);
await insertConversation(conversationId, 'Breakdown disclosure fixture', [
{
messageId: 'disclosure-user-1',
parentMessageId: NO_PARENT,
text: 'Disclosure prompt',
isCreatedByUser: true,
sender: 'User',
tokenCount: 8,
},
{
messageId: 'disclosure-assistant-1',
parentMessageId: 'disclosure-user-1',
text: 'Disclosure reply',
isCreatedByUser: false,
sender: 'Assistant',
tokenCount: 5,
metadata: {
usage: { input: 20, output: 5, cacheRead: 0, cacheWrite: 0, cost: 0.01 },
contextUsage: {
runId: 'disclosure-run',
contextBudget: 300,
breakdown: {
maxContextTokens: 300,
instructionTokens: 20,
messageTokens: 80,
toolCount: 0,
messageCount: 2,
},
},
},
},
]);
const openPopover = async () => {
await expect(page.getByText('Disclosure reply')).toBeVisible({ timeout: 30000 });
await expect(page.getByTestId('token-usage')).toBeVisible({ timeout: 30000 });
await page.getByTestId('token-usage').click();
const popover = page.getByRole('region', { name: 'Context usage' });
await expect(popover).toBeVisible({ timeout: 10000 });
return popover;
};
const panelAnimation = (popover: Locator) =>
popover
.getByTestId('context-details')
.locator('..')
.evaluate((panel) => getComputedStyle(panel).animationName);
await page.goto(`/c/${conversationId}`, { timeout: 30000 });
const popover = await openPopover();
const toggle = popover.getByTestId('context-breakdown-toggle');
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(popover.getByTestId('context-details')).toHaveCount(0);
await toggle.focus();
await page.keyboard.press('Enter');
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await expect(popover.getByTestId('context-details')).toBeVisible();
expect(await panelAnimation(popover)).toBe('collapsible-down');
await page.keyboard.press('Escape');
await page.reload({ timeout: 30000 });
const reloaded = await openPopover();
const reloadedToggle = reloaded.getByTestId('context-breakdown-toggle');
await expect(reloadedToggle).toHaveAttribute('aria-expanded', 'true');
await expect(reloaded.getByTestId('context-details')).toBeVisible();
/** Reduced motion skips the roll in both directions and the panel still toggles. */
await page.emulateMedia({ reducedMotion: 'reduce' });
await reloadedToggle.click();
await expect(reloadedToggle).toHaveAttribute('aria-expanded', 'false');
await expect(reloaded.getByTestId('context-details')).toHaveCount(0);
await reloadedToggle.click();
await expect(reloaded.getByTestId('context-details')).toBeVisible();
expect(await panelAnimation(reloaded)).toBe('none');
});
});

View file

@ -116,11 +116,6 @@
"count": 3
}
},
"client/src/components/Chat/Input/TokenUsage/Breakdown.tsx": {
"shadcn/no-restyle": {
"count": 10
}
},
"client/src/components/Chat/Input/chip.ts": {
"design/disabled-recipe": {
"count": 1

View file

@ -184,6 +184,16 @@ export { default as ReasoningControl } from './components/composer/bar/Reasoning
export type { ReasoningControlProps } from './components/composer/bar/Reasoning';
export { default as ThinkingControl } from './components/composer/bar/Thinking';
export type { ThinkingControlProps } from './components/composer/bar/Thinking';
export { default as ContextUsage } from './components/composer/usage/Usage';
export type { UsageProps as ContextUsageProps } from './components/composer/usage/Usage';
export { default as ContextGauge } from './components/composer/usage/Gauge';
export type { GaugeProps as ContextGaugeProps, GaugeTone } from './components/composer/usage/Gauge';
export { default as ContextUsagePopover } from './components/composer/usage/Popover';
export type { UsagePopoverProps as ContextUsagePopoverProps } from './components/composer/usage/Popover';
export { default as CompactAction } from './components/composer/usage/CompactAction';
export type { CompactActionProps } from './components/composer/usage/CompactAction';
export { default as ContextBreakdown } from './components/composer/usage/Breakdown';
export type { BreakdownProps as ContextBreakdownProps } from './components/composer/usage/Breakdown';
export { default as EscalateNowButton } from './components/composer/EscalateNowButton';
export { default as DuringRunSendButton } from './components/composer/DuringRunSendButton';
export { composerHintId } from './components/composer/bar/Hints';

View file

@ -1,5 +1,4 @@
import { Fragment, useId, useMemo, useState } from 'react';
import { useAtom } from 'jotai';
import { ChevronDown, ExternalLink, Info, TriangleAlert } from 'lucide-react';
import {
Button,
@ -12,13 +11,12 @@ import {
SegmentedMeter,
CollapsibleContent,
CollapsibleTrigger,
useLocalize,
cn,
} from '@librechat/client';
import type { MeterSegment } from '@librechat/client';
import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';
import type { CurrencyConfig } from '~/utils';
import { groupToolTokens, formatTokens, normalizeTokenCount, cn } from '~/utils';
import { contextBreakdownExpandedAtom } from './store';
import { useLocalize } from '~/hooks';
import type { CurrencyConfig, TokenUsageView } from '../../../core/usage';
import { groupToolTokens, formatTokens, normalizeTokenCount } from '../../../core/usage';
import Usage from './Usage';
interface RowProps {
@ -101,12 +99,15 @@ function Row({
);
}
interface BreakdownProps {
export interface BreakdownProps {
view: TokenUsageView;
showCost: boolean;
compactionAvailable?: boolean;
currency?: CurrencyConfig;
langfuseSessionUrl?: string;
/** Whether the totals disclosure is open; owned by the host so it survives remounts */
expanded: boolean;
onExpandedChange: (expanded: boolean) => void;
}
export default function Breakdown({
@ -115,9 +116,10 @@ export default function Breakdown({
compactionAvailable = false,
currency,
langfuseSessionUrl,
}: BreakdownProps) {
expanded,
onExpandedChange,
}: BreakdownProps): React.JSX.Element {
const localize = useLocalize();
const [expanded, setExpanded] = useAtom(contextBreakdownExpandedAtom);
const [hoveredSegment, setHoveredSegment] = useState<string | null>(null);
const [toolsExpanded, setToolsExpanded] = useState(false);
const [insightsOpen, setInsightsOpen] = useState(false);
@ -147,7 +149,7 @@ export default function Breakdown({
/** Every normalized bucket of the subagent calls: a cached call reports its
* prompt under `cacheRead`/`cacheWrite`, so summing input+output alone
* under-reports it — and hides a fully cached call with no output entirely,
* under-reports it: and hides a fully cached call with no output entirely,
* while the Totals rows above still count its cache traffic. */
const subagentTokens =
normalizeTokenCount(view.subagentUsage?.input) +
@ -201,10 +203,8 @@ export default function Breakdown({
const { largestTool, toolBreakdown } = useMemo(() => {
const counts = view.toolMessageTokenCounts;
if (counts == null) {
return {
largestTool: null,
toolBreakdown: [] as Array<{ name: string; tokens: number }>,
};
const empty: Array<{ name: string; tokens: number }> = [];
return { largestTool: null, toolBreakdown: empty };
}
const candidates: Array<{ name: string; tokens: number }> = [];
for (const name in counts) {
@ -260,7 +260,7 @@ export default function Breakdown({
/** Single source of truth for both the meter and its legend: a row carries a
* swatch if and only if it is a segment, so the two can never disagree.
* Deferred tools keep their family's slot and are hatched — same identity,
* Deferred tools keep their family's slot and are hatched: same identity,
* held out of the active set. */
const segments: Array<MeterSegment & { label: string }> =
breakdown == null
@ -353,10 +353,11 @@ export default function Breakdown({
return (
<div className="@container w-full" role="region" aria-label={localize('com_ui_context_usage')}>
<Collapsible open={expanded} onOpenChange={setExpanded}>
<Collapsible open={expanded} onOpenChange={onExpandedChange}>
<CollapsibleTrigger
focusOutline="hidden"
className="group focus-visible:ring-text-primary flex w-full flex-wrap items-center justify-between gap-2 rounded-sm focus-visible:ring-2"
appearance="disclosure"
className="group flex w-full flex-wrap items-center justify-between"
data-testid="context-breakdown-toggle"
>
<span className="text-text-primary min-w-0 text-start text-sm font-medium">
@ -389,7 +390,7 @@ export default function Breakdown({
so it collapses with the height. On the parent it would be a margin
outside the animation, and unmounting the content would drop it in a
single 12px jump after the height reached zero. */}
<CollapsibleContent className="data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down overflow-hidden motion-reduce:data-[state=closed]:animate-none motion-reduce:data-[state=open]:animate-none">
<CollapsibleContent motion="height" className="overflow-hidden">
<div
className="mt-3 grid min-w-0 grid-cols-1 items-start gap-3 @min-[38rem]:grid-cols-2"
data-testid="context-details"
@ -439,7 +440,7 @@ export default function Breakdown({
role="region"
aria-label={localize('com_ui_context_insights')}
data-testid="context-hints"
className="max-w-[calc(100vw-2rem)] motion-reduce:data-[state=closed]:animate-none motion-reduce:data-[state=open]:animate-none"
className="max-w-[calc(100vw-2rem)]"
align="end"
>
{insights.map((insight, index) => (
@ -513,7 +514,7 @@ export default function Breakdown({
{/** The reconciling call's cached prompt share is already inside
* the segments above (reconciliation counted it in `usedTokens`),
* so it renders indented, like the estimate path's tool-call
* share — as peer rows a fully cached prompt would show its
* share: as peer rows a fully cached prompt would show its
* tokens twice and the visible rows would sum past the meter. */}
{(normalizeTokenCount(view.cacheRead) > 0 ||
normalizeTokenCount(view.cacheWrite) > 0) && (
@ -582,7 +583,7 @@ export default function Breakdown({
)}
{/** Retained tool traffic is already inside the message rows above
* (their clamped tool-content share), so it renders as an indented
* subtotal — as a peer row the visible rows would sum past
* subtotal: as a peer row the visible rows would sum past
* `usedTokens`. The snapshot path instead subtracts it from
* Messages, which is exact there; here the counted Input/Output
* rows are provider counts and this share is a char estimate, so

View file

@ -1,12 +1,12 @@
import { memo, useId } from 'react';
import { ScrollText } from 'lucide-react';
import { Button, Spinner, TooltipAnchor } from '@librechat/client';
import { useLocalize } from '~/hooks';
import { Button, Spinner, TooltipAnchor, useLocalize } from '@librechat/client';
import type { NamedExoticComponent } from 'react';
/** The usage popover sits at z-200, above the tooltip default (150). */
const TOOLTIP_Z_INDEX = 250;
interface CompactActionProps {
export interface CompactActionProps {
compact: () => void;
canCompact: boolean;
isCompacting: boolean;
@ -17,7 +17,11 @@ interface CompactActionProps {
* Presentational on purpose: the popover unmounts on hide, so the hook that
* drives the submission lives in the always-mounted indicator above.
*/
function CompactAction({ compact, canCompact, isCompacting }: CompactActionProps) {
function CompactAction({
compact,
canCompact,
isCompacting,
}: CompactActionProps): React.JSX.Element {
const localize = useLocalize();
const descriptionId = useId();
const description = localize('com_ui_context_compact_info');
@ -58,4 +62,6 @@ function CompactAction({ compact, canCompact, isCompacting }: CompactActionProps
);
}
export default memo(CompactAction);
const MemoCompactAction: NamedExoticComponent<CompactActionProps> = memo(CompactAction);
export default MemoCompactAction;

View file

@ -1,21 +1,22 @@
import type { BalanceTone } from '~/utils';
import { cn } from '~/utils';
import { cn } from '@librechat/client';
export type GaugeTone = 'normal' | 'warning' | 'danger';
const SIZE = 20;
const STROKE_WIDTH = 2.5;
const RADIUS = (SIZE - STROKE_WIDTH) / 2;
const CIRCUMFERENCE = 2 * Math.PI * RADIUS;
interface GaugeProps {
/** 0–100, clamped by the caller */
export interface GaugeProps {
/** 0 to 100, clamped by the caller */
percent: number;
/** Max context unknown — render an empty track only */
/** 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;
tone?: GaugeTone;
}
function getStrokeClass(percent: number, indeterminate: boolean, tone?: BalanceTone): string {
function getStrokeClass(percent: number, indeterminate: boolean, tone?: GaugeTone): string {
if (indeterminate) {
return 'stroke-text-secondary';
}
@ -37,7 +38,7 @@ function getStrokeClass(percent: number, indeterminate: boolean, tone?: BalanceT
return 'stroke-text-secondary';
}
export default function Gauge({ percent, indeterminate, tone }: GaugeProps) {
export default function Gauge({ percent, indeterminate, tone }: GaugeProps): React.JSX.Element {
const offset = CIRCUMFERENCE - (percent / 100) * CIRCUMFERENCE;
return (

View file

@ -1,14 +1,14 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { cn } from '@librechat/client';
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 {
export interface UsagePopoverProps {
/** Pending hover work is dropped when this changes (the viewed conversation) */
resetKey: string;
/** Accessible name of the gauge button */
@ -33,7 +33,7 @@ export default function UsagePopover({
busy = false,
trigger,
children,
}: UsagePopoverProps) {
}: UsagePopoverProps): React.JSX.Element {
const popover = Ariakit.usePopoverStore({ placement: 'top' });
const popoverOpen = Ariakit.useStoreState(popover, 'open');
const disclosureRef = useRef<HTMLButtonElement>(null);
@ -172,7 +172,9 @@ export default function UsagePopover({
/* 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)}
hideOnInteractOutside={(event) =>
!(event.target instanceof Node && disclosureRef.current?.contains(event.target) === true)
}
aria-label={cardLabel}
onPointerEnter={cancelTimers}
onPointerLeave={(e) => {

View file

@ -1,12 +1,16 @@
import { useId, useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@librechat/client';
import type { BranchUsage } from '~/utils/tokens';
import type { CurrencyConfig } from '~/utils';
import { formatTokens, formatCost, normalizeTokenCount, cn } from '~/utils';
import { useLocalize } from '~/hooks';
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
useLocalize,
cn,
} from '@librechat/client';
import type { BranchUsage, CurrencyConfig } from '../../../core/usage';
import { formatTokens, formatCost, normalizeTokenCount } from '../../../core/usage';
interface UsageProps {
export interface UsageProps {
title: string;
subtitle?: string;
usage?: BranchUsage;
@ -28,7 +32,7 @@ export default function Usage({
currency,
subagentTokens = 0,
testId,
}: UsageProps) {
}: UsageProps): React.JSX.Element {
const localize = useLocalize();
const headingId = useId();
const [expanded, setExpanded] = useState(false);

View file

@ -1,14 +1,18 @@
/**
* @jest-environment jsdom
*/
import '@testing-library/jest-dom/extend-expect';
import { Provider } from 'jotai';
import { useState } from 'react';
import userEvent from '@testing-library/user-event';
import { Constants, Tools } from 'librechat-data-provider';
import { render, screen, within, fireEvent, waitFor } from '@testing-library/react';
import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';
import Breakdown from './Breakdown';
import type { TokenUsageView } from '../../../../core/usage';
import { initEnglish } from '../../../../__fixtures__/i18n';
import Breakdown from '../Breakdown';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
beforeAll(async () => {
await initEnglish();
});
const view = {
usedTokens: 10,
@ -87,19 +91,32 @@ toolSplitView.snapshot!.breakdown.toolMessageTokens = 150;
toolSplitView.snapshot!.breakdown.toolMessageTokenCounts = { read_file: 100 };
toolSplitView.toolMessageTokenCounts = toolSplitView.snapshot!.breakdown.toolMessageTokenCounts;
const renderBreakdown = (props: Partial<React.ComponentProps<typeof Breakdown>> = {}) =>
render(
<Provider>
<Breakdown view={view} showCost={false} {...props} />
</Provider>,
type BreakdownProps = React.ComponentProps<typeof Breakdown>;
type HostProps = Omit<BreakdownProps, 'expanded' | 'onExpandedChange'> & {
initialExpanded?: boolean;
onExpandedChange?: BreakdownProps['onExpandedChange'];
};
/** Stands in for the app container, which owns the expanded state. */
function Host({ initialExpanded = false, onExpandedChange, ...props }: HostProps) {
const [expanded, setExpanded] = useState(initialExpanded);
return (
<Breakdown
{...props}
expanded={expanded}
onExpandedChange={(next) => {
setExpanded(next);
onExpandedChange?.(next);
}}
/>
);
}
const renderBreakdown = (props: Partial<HostProps> = {}) =>
render(<Host view={view} showCost={false} {...props} />);
const toggle = () => screen.getByTestId('context-breakdown-toggle');
beforeEach(() => {
localStorage.clear();
});
describe('TokenUsage Breakdown', () => {
describe('collapse', () => {
it('opens showing only the gauge, with the detail behind the disclosure', () => {
@ -119,12 +136,19 @@ describe('TokenUsage Breakdown', () => {
expect(screen.getByTestId('token-usage-totals')).toBeInTheDocument();
});
it('persists the expanded choice across mounts', async () => {
const { unmount } = renderBreakdown();
await userEvent.click(toggle());
unmount();
it('reports the expanded choice to the host', async () => {
const onExpandedChange = jest.fn();
renderBreakdown({ onExpandedChange });
renderBreakdown();
await userEvent.click(toggle());
expect(onExpandedChange).toHaveBeenLastCalledWith(true);
await userEvent.click(toggle());
expect(onExpandedChange).toHaveBeenLastCalledWith(false);
});
it('renders expanded when the host starts it expanded', () => {
renderBreakdown({ initialExpanded: true });
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByTestId('token-usage-totals')).toBeInTheDocument();
@ -178,9 +202,8 @@ describe('TokenUsage Breakdown', () => {
const rowFor = (label: string) =>
within(breakdown).getByText(label).parentElement as HTMLElement;
const system = rowFor('com_ui_context_tools_system').firstElementChild as HTMLElement;
const deferred = rowFor('com_ui_context_tools_system_deferred')
.firstElementChild as HTMLElement;
const system = rowFor('System tools').firstElementChild as HTMLElement;
const deferred = rowFor('System tools (deferred)').firstElementChild as HTMLElement;
expect(system).toHaveClass('bg-series-4');
expect(deferred).toHaveClass('bg-series-4');
@ -191,9 +214,8 @@ describe('TokenUsage Breakdown', () => {
renderBreakdown({ view: snapshotView });
await userEvent.click(toggle());
const messages = within(screen.getByTestId('context-breakdown')).getByText(
'com_ui_context_messages',
).parentElement?.firstElementChild as HTMLElement;
const messages = within(screen.getByTestId('context-breakdown')).getByText('Messages')
.parentElement?.firstElementChild as HTMLElement;
expect(messages).toHaveClass('bg-series-1');
expect(messages.className).not.toContain('ring-series-1');
@ -209,12 +231,12 @@ describe('TokenUsage Breakdown', () => {
.getByText(label)
.closest('div') as HTMLElement;
fireEvent.pointerEnter(rowFor('com_ui_context_messages'));
fireEvent.pointerEnter(rowFor('Messages'));
expect(segments[0].className).not.toContain('opacity-40');
segments.slice(1).forEach((segment) => expect(segment).toHaveClass('opacity-40'));
fireEvent.pointerLeave(rowFor('com_ui_context_messages'));
fireEvent.pointerLeave(rowFor('Messages'));
segments.forEach((segment) => expect(segment.className).not.toContain('opacity-40'));
});
@ -229,7 +251,7 @@ describe('TokenUsage Breakdown', () => {
.getByText(label)
.closest('div') as HTMLElement;
fireEvent.pointerEnter(rowFor('com_ui_context_free'));
fireEvent.pointerEnter(rowFor('Free space'));
segments.forEach((segment) => expect(segment).toHaveClass('opacity-40'));
});
@ -247,26 +269,18 @@ describe('TokenUsage Breakdown', () => {
.getByText(label)
.closest('div') as HTMLElement;
fireEvent.pointerEnter(rowFor('com_ui_context_subagents'));
fireEvent.pointerEnter(rowFor('Subagents'));
segments().forEach((segment, index) =>
expect(segment.classList.contains('opacity-40')).toBe(index !== 7),
);
rerender(
<Provider>
<Breakdown view={noSubagents} showCost={false} />
</Provider>,
);
rerender(<Host view={noSubagents} showCost={false} />);
segments().forEach((segment) => expect(segment.className).not.toContain('opacity-40'));
/** The hover state is cleared, not masked: the row reappearing on a later
* live update must not bring the stale dimming back. */
rerender(
<Provider>
<Breakdown view={snapshotView} showCost={false} />
</Provider>,
);
rerender(<Host view={snapshotView} showCost={false} />);
segments().forEach((segment) => expect(segment.className).not.toContain('opacity-40'));
});
@ -301,11 +315,11 @@ describe('TokenUsage Breakdown', () => {
.reduce((sum, child) => sum + Number(child.lastElementChild?.textContent ?? 0), 0);
/** 300 input + 200 output + 100 estimated = 600 used. The tool share is a
* subset of those rows, so it may only appear as an indented subtotal —
* subset of those rows, so it may only appear as an indented subtotal:
* as a peer row the visible rows would claim 750 of a 600-token window. */
expect(peerTotal).toBe(600);
const toolRow = within(estimate).getByText('com_ui_context_tool_calls').parentElement
const toolRow = within(estimate).getByText('Tool calls').parentElement
?.parentElement as HTMLElement;
expect(toolRow.parentElement?.className).toContain('ps-6');
expect(toolRow.textContent).toContain('150');
@ -319,8 +333,8 @@ describe('TokenUsage Breakdown', () => {
within(breakdown).getByText(label).parentElement?.parentElement as HTMLElement;
/** 1000 used − 400 instructions − 50 summary − 150 tool calls = 400 */
expect(rowFor('com_ui_context_messages').textContent).toContain('400');
expect(rowFor('com_ui_context_tool_calls').textContent).toContain('150');
expect(rowFor('Messages').textContent).toContain('400');
expect(rowFor('Tool calls').textContent).toContain('150');
});
it('widens the tool-call row for retained results without exceeding used tokens', async () => {
@ -338,16 +352,15 @@ describe('TokenUsage Breakdown', () => {
/** 1075 used − 400 instructions − 50 summary − 225 tool calls = 400
* messages: the 75 retained tokens sit outside the pre-invoke 550 total. */
expect(rowFor('com_ui_context_messages').textContent).toContain('400');
expect(rowFor('com_ui_context_tool_calls').textContent).toContain('225');
expect(rowFor('Messages').textContent).toContain('400');
expect(rowFor('Tool calls').textContent).toContain('225');
/** The free track is the only visible peer outside the used context; all
* other peer rows must still add up exactly to the meter total. */
const peerTotal = Array.from(breakdown.children)
.filter(
(child) =>
!child.className.includes('ps-6') &&
!child.textContent?.includes('com_ui_context_free'),
!child.className.includes('ps-6') && !child.textContent?.includes('Free space'),
)
.reduce(
(sum, child) => sum + Number.parseInt(child.lastElementChild?.textContent ?? '0', 10),
@ -371,10 +384,9 @@ describe('TokenUsage Breakdown', () => {
renderBreakdown({ view: manyTools });
await userEvent.click(toggle());
await userEvent.click(screen.getByRole('button', { name: /com_ui_context_tool_calls/ }));
await userEvent.click(screen.getByRole('button', { name: /Tool calls/ }));
const details = screen.getByText('com_ui_context_tool_breakdown')
.parentElement as HTMLElement;
const details = screen.getByText('By tool').parentElement as HTMLElement;
for (const name of [
'alpha',
'beta',
@ -399,10 +411,9 @@ describe('TokenUsage Breakdown', () => {
renderBreakdown({ view: knownZero });
await userEvent.click(toggle());
const breakdown = screen.getByTestId('context-breakdown');
expect(within(breakdown).getByText('com_ui_context_tool_calls')).toBeInTheDocument();
expect(within(breakdown).getByText('Tool calls')).toBeInTheDocument();
expect(
within(breakdown).getByText('com_ui_context_tool_calls').parentElement?.parentElement
?.textContent,
within(breakdown).getByText('Tool calls').parentElement?.parentElement?.textContent,
).toContain('0');
});
@ -410,16 +421,16 @@ describe('TokenUsage Breakdown', () => {
renderBreakdown({ view: toolSplitView });
await userEvent.click(toggle());
const toolButton = screen.getByRole('button', { name: /com_ui_context_tool_calls/ });
const toolButton = screen.getByRole('button', { name: /Tool calls/ });
expect(toolButton).toHaveAttribute('aria-expanded', 'false');
toolButton.focus();
await userEvent.keyboard('{Enter}');
expect(toolButton).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByText('com_ui_context_tool_breakdown')).toBeInTheDocument();
expect(screen.getByText('By tool')).toBeInTheDocument();
expect(document.getElementById(toolButton.getAttribute('aria-controls')!)).toContainElement(
screen.getByText('com_ui_context_tool_breakdown'),
screen.getByText('By tool'),
);
await userEvent.keyboard(' ');
expect(toolButton).toHaveAttribute('aria-expanded', 'false');
@ -430,10 +441,9 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
const breakdown = screen.getByTestId('context-breakdown');
expect(within(breakdown).queryByText('com_ui_context_tool_calls')).toBeNull();
expect(within(breakdown).queryByText('Tool calls')).toBeNull();
expect(
within(breakdown).getByText('com_ui_context_messages').parentElement?.parentElement
?.textContent,
within(breakdown).getByText('Messages').parentElement?.parentElement?.textContent,
).toContain('550');
});
@ -447,14 +457,16 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
const breakdown = screen.getByTestId('context-breakdown');
const cachedRow = within(breakdown).getByText('com_ui_context_cached').parentElement
const cachedRow = within(breakdown).getByText('Cached').parentElement
?.parentElement as HTMLElement;
/** Reconciliation already counted the cached prompt inside the segments
* above, so these may only appear indented — as peer rows a fully cached
* above, so these may only appear indented: as peer rows a fully cached
* prompt would show its tokens twice and the visible rows would sum past
* the meter. */
expect(within(breakdown).getByText('com_ui_context_cache_last_call')).toBeInTheDocument();
expect(
within(breakdown).getByText('Cached input in the context snapshot'),
).toBeInTheDocument();
expect(cachedRow.parentElement?.className).toContain('ps-6');
expect(cachedRow.textContent).toContain('30');
/** The share column is keyed to the window, like every row above: without
@ -464,9 +476,7 @@ describe('TokenUsage Breakdown', () => {
const peers = Array.from(breakdown.children).filter(
(child) => !child.className.includes('ps-6'),
);
expect(peers.some((peer) => peer.textContent?.includes('com_ui_context_cache_write'))).toBe(
false,
);
expect(peers.some((peer) => peer.textContent?.includes('Cache write'))).toBe(false);
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '50');
});
@ -478,8 +488,8 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
await userEvent.click(screen.getByTestId('context-insights-toggle'));
const hints = await screen.findByTestId('context-hints');
expect(hints.textContent).toContain('com_ui_context_runway');
expect(hints.textContent).not.toContain('com_ui_context_compaction');
expect(hints.textContent).toContain('≈2 more turns at this growth');
expect(hints.textContent).not.toContain('Summarizing now could reclaim');
});
it('warns under pressure inline, with insights behind the ⓘ button', async () => {
@ -497,15 +507,15 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
/** Pressure warns inline; insights stay hidden until the ⓘ is hovered */
expect(screen.getByText('com_ui_context_pressure_warn')).toBeInTheDocument();
expect(screen.getByText('Context window is filling up')).toBeInTheDocument();
expect(screen.queryByTestId('context-hints')).toBeNull();
const info = screen.getByTestId('context-insights-toggle');
await userEvent.click(info);
const hints = await screen.findByTestId('context-hints');
expect(hints.textContent).toContain('com_ui_context_largest_tool');
expect(hints.textContent).toContain('com_ui_context_runway');
expect(hints.textContent).toContain('com_ui_context_compaction');
expect(hints.textContent).toContain('Largest tool: grep (150)');
expect(hints.textContent).toContain('≈2 more turns at this growth');
expect(hints.textContent).toContain('Summarizing now could reclaim ≈90K tokens');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(screen.queryByTestId('context-hints')).toBeNull());
@ -518,7 +528,7 @@ describe('TokenUsage Breakdown', () => {
renderBreakdown({ view: critical });
await userEvent.click(toggle());
expect(screen.getByText('com_ui_context_pressure_danger')).toBeInTheDocument();
expect(screen.getByText('Context window is almost full')).toBeInTheDocument();
});
});
@ -529,7 +539,7 @@ describe('TokenUsage Breakdown', () => {
expect(
within(screen.getByTestId('token-usage-totals')).getByRole('heading', {
name: 'com_ui_context_totals',
name: 'Totals',
}),
).toBeInTheDocument();
});
@ -555,7 +565,7 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
const totals = within(screen.getByTestId('token-usage-totals'));
expect(totals.getByText('com_ui_context_subagents_all').nextElementSibling).toHaveTextContent(
expect(totals.getByText('Subagents (all branches)').nextElementSibling).toHaveTextContent(
'1K',
);
});
@ -596,7 +606,7 @@ describe('TokenUsage Breakdown', () => {
if (showCost) {
expect(
within(screen.getByTestId('token-usage-all-branches')).getByTestId('usage-cost'),
).toHaveTextContent('com_ui_context_cost_total');
).toHaveTextContent('All branches');
} else {
expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
}
@ -639,25 +649,17 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
const last = within(screen.getByTestId('token-usage-last-turn'));
expect(last.getByRole('heading', { name: 'com_ui_context_last_turn' })).toBeInTheDocument();
expect(last.getByText('com_ui_cache_read').parentElement?.parentElement).toHaveTextContent(
'700',
);
expect(last.getByText('com_ui_cache_write').parentElement?.parentElement).toHaveTextContent(
'90',
);
expect(last.getByRole('heading', { name: 'Last turn' })).toBeInTheDocument();
expect(last.getByText('Cache read').parentElement?.parentElement).toHaveTextContent('700');
expect(last.getByText('Cache write').parentElement?.parentElement).toHaveTextContent('90');
const totals = within(screen.getByTestId('token-usage-totals'));
expect(totals.getByText('com_ui_context_this_branch')).toBeInTheDocument();
expect(totals.getByText('com_ui_cache_read').parentElement?.parentElement).toHaveTextContent(
'800',
);
expect(totals.getByText('This branch')).toBeInTheDocument();
expect(totals.getByText('Cache read').parentElement?.parentElement).toHaveTextContent('800');
const all = within(screen.getByTestId('token-usage-all-branches'));
expect(all.getByText('com_ui_cache_read').parentElement?.parentElement).toHaveTextContent(
'900',
);
expect(last.getByTestId('usage-cost')).toHaveTextContent('com_ui_context_cost_last_turn');
expect(totals.getByTestId('usage-cost')).toHaveTextContent('com_ui_context_cost_branch');
expect(all.getByTestId('usage-cost')).toHaveTextContent('com_ui_context_cost_total');
expect(all.getByText('Cache read').parentElement?.parentElement).toHaveTextContent('900');
expect(last.getByTestId('usage-cost')).toHaveTextContent('Cost (last turn)');
expect(totals.getByTestId('usage-cost')).toHaveTextContent('Cost (this branch)');
expect(all.getByTestId('usage-cost')).toHaveTextContent('All branches');
});
it('exposes all-branches token differences without requiring cost coverage', async () => {
@ -681,7 +683,7 @@ describe('TokenUsage Breakdown', () => {
expect(screen.getByTestId('token-usage-all-branches')).toHaveTextContent('25');
expect(
within(screen.getByTestId('token-usage-last-turn')).getByTestId('usage-cost'),
).toHaveTextContent('com_ui_context_cost_last_turn');
).toHaveTextContent('Cost (last turn)');
expect(
within(screen.getByTestId('token-usage-totals')).queryByTestId('usage-cost'),
).not.toBeInTheDocument();
@ -689,21 +691,17 @@ describe('TokenUsage Breakdown', () => {
it('shows waiting and unavailable states without presenting old totals as the current turn', async () => {
const { rerender } = render(
<Provider>
<Breakdown view={{ ...view, lastTurnUsage: undefined, turnInProgress: true }} showCost />
</Provider>,
<Host view={{ ...view, lastTurnUsage: undefined, turnInProgress: true }} showCost />,
);
await userEvent.click(toggle());
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(
'com_ui_context_waiting_usage',
'Waiting for model usage...',
);
rerender(
<Provider>
<Breakdown view={{ ...view, lastTurnUsage: undefined, turnInProgress: false }} showCost />
</Provider>,
<Host view={{ ...view, lastTurnUsage: undefined, turnInProgress: false }} showCost />,
);
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(
'com_ui_context_unavailable_usage',
'Usage not available for this turn',
);
});
@ -725,11 +723,11 @@ describe('TokenUsage Breakdown', () => {
});
await userEvent.click(toggle());
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(
'com_ui_context_current_turn',
'Current turn (so far)',
);
expect(
within(screen.getByTestId('token-usage-last-turn')).getByTestId('usage-cost'),
).toHaveTextContent('com_ui_context_cost_current_turn');
).toHaveTextContent('Cost (current turn so far)');
});
it('keeps a known zero cost and hides a missing cost', async () => {
@ -749,12 +747,10 @@ describe('TokenUsage Breakdown', () => {
showCost: true,
});
await userEvent.click(toggle());
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(
'com_ui_context_last_turn',
);
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent('Last turn');
expect(
within(screen.getByTestId('token-usage-last-turn')).getByTestId('usage-cost'),
).toHaveTextContent('com_ui_context_cost_last_turn');
).toHaveTextContent('Cost (last turn)');
expect(
within(screen.getByTestId('token-usage-totals')).queryByTestId('usage-cost'),
).not.toBeInTheDocument();
@ -768,7 +764,7 @@ describe('TokenUsage Breakdown', () => {
renderBreakdown({ langfuseSessionUrl: url });
await userEvent.click(toggle());
expect(screen.getByRole('link', { name: 'com_ui_langfuse_view_session' })).toHaveAttribute(
expect(screen.getByRole('link', { name: 'View session in Langfuse' })).toHaveAttribute(
'href',
url,
);

View file

@ -1,11 +1,15 @@
/**
* @jest-environment jsdom
*/
import userEvent from '@testing-library/user-event';
import { render, screen, within } from '@testing-library/react';
import type { BranchUsage } from '~/utils/tokens';
import Usage from './Usage';
import type { BranchUsage } from '../../../../core/usage';
import { initEnglish } from '../../../../__fixtures__/i18n';
import Usage from '../Usage';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
beforeAll(async () => {
await initEnglish();
});
const usage: BranchUsage = {
input: 37_900,
@ -19,10 +23,10 @@ const usage: BranchUsage = {
const renderUsage = (props: Partial<React.ComponentProps<typeof Usage>> = {}) =>
render(
<Usage
title="com_ui_context_current_turn"
title="Current turn (so far)"
usage={usage}
cost={usage.cost}
costLabel="com_ui_context_cost_current_turn"
costLabel="Cost (current turn so far)"
testId="usage"
{...props}
/>,
@ -32,17 +36,12 @@ describe('Token usage summary', () => {
it('keeps all metrics visible in a condensed, labelled summary', () => {
renderUsage();
expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'false');
const section = screen.getByRole('region', { name: 'com_ui_context_current_turn' });
const section = screen.getByRole('region', { name: 'Current turn (so far)' });
expect(within(section).getByRole('heading')).toHaveTextContent('$39.45');
for (const value of ['37.9K', '551.6K', '60.9M', '4.9M']) {
expect(within(section).getByText(value)).toBeVisible();
}
for (const label of [
'com_ui_context_uncached_input',
'com_ui_output',
'com_ui_cache_read',
'com_ui_cache_write',
]) {
for (const label of ['Input (uncached)', 'Output', 'Cache read', 'Cache write']) {
expect(within(section).getByText(label).tagName).toBe('DT');
}
expect(section.querySelector('dl')).toHaveClass('grid-cols-2');
@ -72,14 +71,14 @@ describe('Token usage summary', () => {
expect(screen.getByTestId('usage-cost')).toHaveTextContent('$0.00');
rerender(
<Usage
title="com_ui_context_current_turn"
unavailable="com_ui_context_waiting_usage"
costLabel="com_ui_context_cost_current_turn"
title="Current turn (so far)"
unavailable="Waiting for model usage..."
costLabel="Cost (current turn so far)"
testId="usage"
/>,
);
expect(screen.getByRole('button')).toBeDisabled();
expect(screen.getByText('com_ui_context_waiting_usage')).toBeVisible();
expect(screen.getByText('Waiting for model usage...')).toBeVisible();
expect(screen.queryByText('0')).not.toBeInTheDocument();
expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
});
@ -89,7 +88,7 @@ describe('Token usage summary', () => {
subagentTokens: 44_600_000,
currency: { code: 'EUR', rate: 2 },
});
expect(screen.getByText('com_ui_context_subagents_all').nextElementSibling).toHaveTextContent(
expect(screen.getByText('Subagents (all branches)').nextElementSibling).toHaveTextContent(
'44.6M',
);
expect(screen.getByTestId('usage-cost')).toHaveTextContent('€78.90');
@ -100,10 +99,10 @@ describe('Token usage summary', () => {
expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
rerender(
<Usage
title="com_ui_context_current_turn"
title="Current turn (so far)"
usage={usage}
cost={NaN}
costLabel="com_ui_context_cost_current_turn"
costLabel="Cost (current turn so far)"
testId="usage"
/>,
);

View file

@ -1,4 +1,4 @@
import { formatTokens } from '../format';
import { formatCost, formatTokens } from '../format';
describe('formatTokens', () => {
it('renders malformed token counts as a bounded zero', () => {
@ -18,3 +18,62 @@ describe('formatTokens', () => {
expect(formatTokens(1_250)).toBe(compact.format(1_250));
});
});
describe('formatCost', () => {
it('formats across magnitude bands (USD default, unchanged)', () => {
expect(formatCost(0)).toBe('$0.00');
expect(formatCost(0.004)).toBe('<$0.01');
expect(formatCost(0.0523)).toBe('$0.0523');
expect(formatCost(1.234)).toBe('$1.23');
});
it('applies the static USD→local rate', () => {
expect(formatCost(2, { code: 'USD', rate: 0.5 })).toBe('$1.00');
expect(formatCost(10, { code: 'USD', rate: 0.1 })).toBe('$1.00');
});
it('formats in the configured currency', () => {
const eur = formatCost(5, { code: 'EUR', rate: 1 });
expect(eur).toContain('€');
expect(eur).toContain('5');
});
it('respects zero-decimal currencies', () => {
const jpy = formatCost(5, { code: 'JPY', rate: 1 });
expect(jpy).toContain('¥');
expect(jpy).not.toContain('.');
});
it('falls back to USD on a malformed currency code', () => {
expect(formatCost(5, { code: 'invalid', rate: 1 })).toBe('$5.00');
});
it('drops the rate too when the currency code is unsupported', () => {
/** A typo in `code` must not leave a converted amount under the $ symbol. */
expect(formatCost(10, { code: 'EURO', rate: 0.92 })).toBe('$10.00');
});
it('rejects well-formed but non-ISO codes that Intl would accept', () => {
/** `EUU`/`RMB` are 3 letters so Intl does not throw; the ISO-4217 set must
* still reject them and fall back to USD (no converted amount, no rate). */
expect(formatCost(10, { code: 'EUU', rate: 0.92 })).toBe('$10.00');
expect(formatCost(10, { code: 'RMB', rate: 0.5 })).toBe('$10.00');
});
it('uses the currency minor unit for three-decimal currencies', () => {
/** KWD has 3 fractional digits, so the tiny threshold is 0.001, not 0.01. */
const small = formatCost(0.005, { code: 'KWD', rate: 1 });
expect(small).toContain('0.005');
expect(small).not.toContain('<');
expect(formatCost(0.0005, { code: 'KWD', rate: 1 })).toContain('0.001');
});
it('falls back to rate 1 when rate is not a finite positive number', () => {
/** Partial admin override (code set before rate) must never render NaN. */
const eur = formatCost(10, { code: 'EUR', rate: undefined as unknown as number });
expect(eur).toContain('€');
expect(eur).toContain('10');
expect(eur).not.toContain('NaN');
expect(formatCost(10, { code: 'USD', rate: Number.NaN })).toBe('$10.00');
});
});

View file

@ -11,3 +11,109 @@ export function formatTokens(count: number): string {
const formatted = tokenFormatter.format(normalizeTokenCount(count));
return formatted.replace(/\.0(?=[A-Za-z]|$)/, '');
}
/** Display currency for the context cost. `rate` is a static USD to local
* multiplier (no live FX); `code` is an ISO-4217 currency for Intl formatting. */
export interface CurrencyConfig {
code: string;
rate: number;
}
const DEFAULT_CURRENCY: CurrencyConfig = { code: 'USD', rate: 1 };
const currencyFormatters = new Map<string, Intl.NumberFormat>();
const currencyDigits = new Map<string, number>();
let supportedCurrencies: Set<string> | null | undefined;
/** `Intl.supportedValuesOf` is absent from older runtimes and from this package's lib target. */
function listCurrencies(): string[] | null {
const supportedValuesOf: unknown = Reflect.get(Intl, 'supportedValuesOf');
if (typeof supportedValuesOf !== 'function') {
return null;
}
const values: unknown = supportedValuesOf.call(Intl, 'currency');
return Array.isArray(values) ? values.filter((v) => typeof v === 'string') : null;
}
/** True only for codes recognized as ISO-4217. `Intl.NumberFormat` accepts any
* well-formed three-letter code (e.g. `EUU`, `RMB`) without throwing, so the
* ISO-4217 set is the real guard against typo'd / non-ISO codes. */
function isSupportedCurrency(code: unknown): code is string {
if (typeof code !== 'string' || code.length === 0) {
return false;
}
const upper = code.toUpperCase();
if (supportedCurrencies === undefined) {
const codes = listCurrencies();
supportedCurrencies = codes != null ? new Set(codes) : null;
}
if (supportedCurrencies != null) {
return supportedCurrencies.has(upper);
}
/** Older runtime without `supportedValuesOf`: accept any code Intl can build. */
try {
new Intl.NumberFormat(undefined, { style: 'currency', currency: upper });
return true;
} catch {
return false;
}
}
/** Default fraction digits for a validated currency: USD: 2, JPY: 0, KWD: 3. */
function maxFractionDigits(code: string): number {
const cached = currencyDigits.get(code);
if (cached !== undefined) {
return cached;
}
const digits =
new Intl.NumberFormat(undefined, { style: 'currency', currency: code }).resolvedOptions()
.maximumFractionDigits ?? 2;
currencyDigits.set(code, digits);
return digits;
}
function currencyFormatter(code: string, minDigits: number, maxDigits: number): Intl.NumberFormat {
const key = `${code}:${minDigits}:${maxDigits}`;
let formatter = currencyFormatters.get(key);
if (formatter == null) {
formatter = new Intl.NumberFormat(undefined, {
style: 'currency',
currency: code,
minimumFractionDigits: minDigits,
maximumFractionDigits: maxDigits,
});
currencyFormatters.set(key, formatter);
}
return formatter;
}
export function formatCost(usd: number, currency: CurrencyConfig = DEFAULT_CURRENCY): string {
/** Resolve to a safe (code, rate): an unsupported code falls back to USD AND
* rate 1 (never present a converted amount under the wrong symbol). A
* non-finite/negative rate (e.g. a partial admin override that set `code`
* before `rate`) falls back to 1 so a cost never renders as `NaN`. */
let code = DEFAULT_CURRENCY.code;
let rate = 1;
if (isSupportedCurrency(currency?.code)) {
code = currency.code.toUpperCase();
const candidate: number = currency.rate;
rate = Number.isFinite(candidate) && candidate > 0 ? candidate : 1;
}
const base = maxFractionDigits(code);
const amount = (Number.isFinite(usd) && usd > 0 ? usd : 0) * rate;
/** The currency's own minor unit: USD/EUR: 0.01, JPY: 1, KWD: 0.001. */
const smallest = Math.pow(10, -base);
if (amount <= 0) {
return currencyFormatter(code, base, base).format(0);
}
if (amount < smallest) {
return `<${currencyFormatter(code, base, base).format(smallest)}`;
}
if (amount < 1 && base > 0) {
/** Extra precision for sub-unit costs; trailing zeros trim to the currency's
* own scale (min = base). */
return currencyFormatter(code, base, base + 2).format(amount);
}
return currencyFormatter(code, base, base).format(amount);
}

View file

@ -0,0 +1,47 @@
import { render, screen } from '@testing-library/react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './Collapsible';
const renderPair = (trigger: { appearance?: 'disclosure' }, content: { motion?: 'height' }) =>
render(
<Collapsible defaultOpen>
<CollapsibleTrigger {...trigger} className="group">
Toggle
</CollapsibleTrigger>
<CollapsibleContent {...content} className="overflow-hidden" data-testid="panel">
Body
</CollapsibleContent>
</Collapsible>,
);
describe('Collapsible', () => {
it('adds no appearance or motion unless asked', () => {
renderPair({}, {});
expect(screen.getByRole('button', { name: 'Toggle' })).toHaveAttribute('class', 'group');
expect(screen.getByTestId('panel')).toHaveAttribute('class', 'overflow-hidden');
});
it('gives a disclosure trigger its focus ring and shape beside the caller layout', () => {
renderPair({ appearance: 'disclosure' }, {});
expect(screen.getByRole('button', { name: 'Toggle' })).toHaveClass(
'group',
'focus-visible:ring-text-primary',
'focus-visible:ring-2',
'rounded-sm',
'gap-2',
);
});
it('rolls a height-motion panel, skipping the roll under reduced motion', () => {
renderPair({}, { motion: 'height' });
expect(screen.getByTestId('panel')).toHaveClass(
'overflow-hidden',
'data-[state=open]:animate-collapsible-down',
'data-[state=closed]:animate-collapsible-up',
'motion-reduce:data-[state=open]:animate-none',
'motion-reduce:data-[state=closed]:animate-none',
);
});
});

View file

@ -14,8 +14,19 @@ type CollapsibleTriggerProps = ComponentPropsWithoutRef<
typeof CollapsiblePrimitive.CollapsibleTrigger
> & {
focusOutline?: FocusOutline;
/** `disclosure`: a row that toggles a panel, with its own focus ring. */
appearance?: 'disclosure';
};
type CollapsibleContentProps = CollapsiblePrimitive.CollapsibleContentProps & {
/** `height`: rolls the panel open and closed, and skips the roll under reduced motion. */
motion?: 'height';
};
const DISCLOSURE_TRIGGER = 'focus-visible:ring-text-primary gap-2 rounded-sm focus-visible:ring-2';
const HEIGHT_MOTION =
'data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down motion-reduce:data-[state=closed]:animate-none motion-reduce:data-[state=open]:animate-none';
const Collapsible: ForwardRefExoticComponent<
CollapsiblePrimitive.CollapsibleProps & RefAttributes<HTMLDivElement>
> = CollapsiblePrimitive.Root;
@ -23,10 +34,16 @@ const Collapsible: ForwardRefExoticComponent<
const CollapsibleTrigger: ForwardRefExoticComponent<
CollapsibleTriggerProps & RefAttributes<HTMLButtonElement>
> = forwardRef<ElementRef<typeof CollapsiblePrimitive.CollapsibleTrigger>, CollapsibleTriggerProps>(
({ className, focusOutline, ...props }, ref) => (
({ className, focusOutline, appearance, ...props }, ref) => (
<CollapsiblePrimitive.CollapsibleTrigger
ref={ref}
className={cx(focusOutlineVariants({ focusOutline }), className) || undefined}
className={
cx(
focusOutlineVariants({ focusOutline }),
appearance === 'disclosure' && DISCLOSURE_TRIGGER,
className,
) || undefined
}
{...props}
/>
),
@ -34,7 +51,16 @@ const CollapsibleTrigger: ForwardRefExoticComponent<
CollapsibleTrigger.displayName = CollapsiblePrimitive.CollapsibleTrigger.displayName;
const CollapsibleContent: ForwardRefExoticComponent<
CollapsiblePrimitive.CollapsibleContentProps & RefAttributes<HTMLDivElement>
> = CollapsiblePrimitive.CollapsibleContent;
CollapsibleContentProps & RefAttributes<HTMLDivElement>
> = forwardRef<ElementRef<typeof CollapsiblePrimitive.CollapsibleContent>, CollapsibleContentProps>(
({ className, motion, ...props }, ref) => (
<CollapsiblePrimitive.CollapsibleContent
ref={ref}
className={cx(motion === 'height' && HEIGHT_MOTION, className) || undefined}
{...props}
/>
),
);
CollapsibleContent.displayName = CollapsiblePrimitive.CollapsibleContent.displayName;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };

View file

@ -15,4 +15,20 @@ describe('HoverCardContent', () => {
expect(screen.getByText('Details')).toHaveClass('rounded-theme-menu-panel');
});
it('skips the enter and exit animation under reduced motion', () => {
render(
<HoverCard open>
<HoverCardTrigger asChild>
<button type="button">Trigger</button>
</HoverCardTrigger>
<HoverCardContent>Details</HoverCardContent>
</HoverCard>,
);
expect(screen.getByText('Details')).toHaveClass(
'motion-reduce:data-[state=open]:animate-none',
'motion-reduce:data-[state=closed]:animate-none',
);
});
});

View file

@ -36,7 +36,7 @@ const HoverCardContent: React.ForwardRefExoticComponent<
sideOffset={sideOffset}
style={{ ...nestedStyle, ...style }}
className={cn(
'border-border-light bg-surface-secondary text-text-primary data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 rounded-theme-menu-panel z-50 w-64 max-w-[min(calc(100vw-1rem),var(--radix-hover-card-content-available-width))] origin-(--radix-hover-card-content-transform-origin) border p-4 shadow-md outline-hidden',
'border-border-light bg-surface-secondary text-text-primary data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 rounded-theme-menu-panel z-50 w-64 max-w-[min(calc(100vw-1rem),var(--radix-hover-card-content-available-width))] origin-(--radix-hover-card-content-transform-origin) border p-4 shadow-md outline-hidden motion-reduce:data-[state=closed]:animate-none motion-reduce:data-[state=open]:animate-none',
className,
)}
{...props}

View file

@ -139,12 +139,27 @@ module.exports = {
'0%,70%,100%': { opacity: '1' },
'20%,50%': { opacity: '0' },
},
/** Radix Collapsible exposes its own height variable, not the accordion one. Lives in
* the preset because chat components that ship from @librechat/chat animate with it.
* The fade rides along so the rows dissolve instead of squashing. Opening
* decelerates into place; closing accelerates away, because a decelerating
* close stalls over its final pixels before the unmount. */
'collapsible-down': {
from: { height: 0, opacity: 0 },
to: { height: 'var(--radix-collapsible-content-height)', opacity: 1 },
},
'collapsible-up': {
from: { height: 'var(--radix-collapsible-content-height)', opacity: 1 },
to: { height: 0, opacity: 0 },
},
},
animation: {
'loading-dot': 'loading-dot 1.2s ease-in-out var(--loading-dot-delay, 0ms) infinite',
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
'caret-blink': 'caret-blink 1.25s ease-out infinite',
'collapsible-down': 'collapsible-down 0.3s cubic-bezier(0, 0, 0.2, 1)',
'collapsible-up': 'collapsible-up 0.2s cubic-bezier(0.4, 0, 1, 1)',
},
/**
* `rounded-sm` through `rounded-3xl` are not restated here: `@librechat/client/theme.css`