Skip to content

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

🗞️ feat: Make Context Usage Responsive and Condensed (#17018)

lia-by-librechat[bot]e081b566a42d
diff --git a/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx b/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx
index b89c15a5a0..7d6e48e5e5 100644
--- a/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx
+++ b/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx
@@ -555,9 +555,9 @@ describe('TokenUsage Breakdown', () => {
await userEvent.click(toggle());
const totals = within(screen.getByTestId('token-usage-totals'));
- expect(
- totals.getByText('com_ui_context_subagents_all').parentElement?.nextElementSibling,
- ).toHaveTextContent('1K');
+ expect(totals.getByText('com_ui_context_subagents_all').nextElementSibling).toHaveTextContent(
+ '1K',
+ );
});
});
@@ -594,11 +594,11 @@ describe('TokenUsage Breakdown', () => {
expect(screen.queryByTestId('token-usage-totals')).not.toBeInTheDocument();
expect(screen.getByTestId('token-usage-all-branches')).toHaveTextContent('800');
if (showCost) {
- expect(screen.getByTestId('token-usage-cost')).toHaveTextContent(
- 'com_ui_context_cost_total',
- );
+ expect(
+ within(screen.getByTestId('token-usage-all-branches')).getByTestId('usage-cost'),
+ ).toHaveTextContent('com_ui_context_cost_total');
} else {
- expect(screen.queryByTestId('token-usage-cost')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
}
},
);
@@ -655,10 +655,9 @@ describe('TokenUsage Breakdown', () => {
expect(all.getByText('com_ui_cache_read').parentElement?.parentElement).toHaveTextContent(
'900',
);
- const cost = within(screen.getByTestId('token-usage-cost'));
- expect(cost.getByText('com_ui_context_cost_last_turn')).toBeInTheDocument();
- expect(cost.getByText('com_ui_context_cost_branch')).toBeInTheDocument();
- expect(cost.getByText('com_ui_context_cost_total')).toBeInTheDocument();
+ 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');
});
it('exposes all-branches token differences without requiring cost coverage', async () => {
@@ -680,12 +679,12 @@ describe('TokenUsage Breakdown', () => {
});
await userEvent.click(toggle());
expect(screen.getByTestId('token-usage-all-branches')).toHaveTextContent('25');
- expect(screen.getByTestId('token-usage-cost')).toHaveTextContent(
- 'com_ui_context_cost_last_turn',
- );
- expect(screen.getByTestId('token-usage-cost')).not.toHaveTextContent(
- 'com_ui_context_cost_branch',
- );
+ expect(
+ within(screen.getByTestId('token-usage-last-turn')).getByTestId('usage-cost'),
+ ).toHaveTextContent('com_ui_context_cost_last_turn');
+ expect(
+ within(screen.getByTestId('token-usage-totals')).queryByTestId('usage-cost'),
+ ).not.toBeInTheDocument();
});
it('shows waiting and unavailable states without presenting old totals as the current turn', async () => {
@@ -728,9 +727,9 @@ describe('TokenUsage Breakdown', () => {
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(
'com_ui_context_current_turn',
);
- expect(screen.getByTestId('token-usage-cost')).toHaveTextContent(
- 'com_ui_context_cost_current_turn',
- );
+ expect(
+ within(screen.getByTestId('token-usage-last-turn')).getByTestId('usage-cost'),
+ ).toHaveTextContent('com_ui_context_cost_current_turn');
});
it('keeps a known zero cost and hides a missing cost', async () => {
@@ -753,12 +752,12 @@ describe('TokenUsage Breakdown', () => {
expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(
'com_ui_context_last_turn',
);
- expect(screen.getByTestId('token-usage-cost')).toHaveTextContent(
- 'com_ui_context_cost_last_turn',
- );
- expect(screen.getByTestId('token-usage-cost')).not.toHaveTextContent(
- 'com_ui_context_cost_branch',
- );
+ expect(
+ within(screen.getByTestId('token-usage-last-turn')).getByTestId('usage-cost'),
+ ).toHaveTextContent('com_ui_context_cost_last_turn');
+ expect(
+ within(screen.getByTestId('token-usage-totals')).queryByTestId('usage-cost'),
+ ).not.toBeInTheDocument();
});
});
diff --git a/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx b/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx
index 540f1c95d3..68c61bc9c2 100644
--- a/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx
+++ b/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx
@@ -16,9 +16,10 @@ import {
import type { MeterSegment } from '@librechat/client';
import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';
import type { CurrencyConfig } from '~/utils';
-import { groupToolTokens, formatTokens, formatCost, normalizeTokenCount, cn } from '~/utils';
+import { groupToolTokens, formatTokens, normalizeTokenCount, cn } from '~/utils';
import { contextBreakdownExpandedAtom } from './store';
import { useLocalize } from '~/hooks';
+import Usage from './Usage';
interface RowProps {
label: string;
@@ -351,7 +352,7 @@ export default function Breakdown({
hoveredSegment != null && hoverIsValid(hoveredSegment) ? hoveredSegment : null;
return (
- <div className="w-full" role="region" aria-label={localize('com_ui_context_usage')}>
+ <div className="@container w-full" role="region" aria-label={localize('com_ui_context_usage')}>
<Collapsible open={expanded} onOpenChange={setExpanded}>
<CollapsibleTrigger
focusOutline="hidden"
@@ -389,355 +390,286 @@ export default function Breakdown({
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">
- <div className="mt-3 space-y-3">
- {(pressure !== 'none' || insights.length > 0) && (
- <div className="relative flex items-center justify-between gap-2">
- {pressure !== 'none' ? (
- <p
- className={cn(
- 'flex min-w-0 items-center gap-1.5 text-xs',
- pressure === 'danger' ? 'text-text-destructive' : 'text-text-warning',
- )}
- >
- <TriangleAlert className="size-3.5 shrink-0" aria-hidden="true" />
- {localize(
- pressure === 'danger'
- ? 'com_ui_context_pressure_danger'
- : 'com_ui_context_pressure_warn',
- )}
- </p>
- ) : (
- <span />
- )}
- {insights.length > 0 && (
- <HoverCard open={insightsOpen} onOpenChange={setInsightsOpen}>
- <HoverCardTrigger asChild>
- <Button
- type="button"
- variant="quiet"
- size="icon"
- aria-label={localize('com_ui_context_insights')}
- aria-expanded={insightsOpen}
- aria-controls={insightsOpen ? insightsId : undefined}
- data-testid="context-insights-toggle"
- className="size-6"
- onFocus={() => setInsightsOpen(true)}
- onBlur={() => setInsightsOpen(false)}
- onClick={() => setInsightsOpen(true)}
- >
- <Info className="size-3.5" aria-hidden="true" />
- </Button>
- </HoverCardTrigger>
- <HoverCardPortal>
- <HoverCardContent
- id={insightsId}
- 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"
- align="end"
- >
- {insights.map((insight, index) => (
- <p className="text-text-secondary text-xs break-words" key={index}>
- {insight}
- </p>
- ))}
- </HoverCardContent>
- </HoverCardPortal>
- </HoverCard>
- )}
- </div>
- )}
- <div
- className="space-y-1.5"
- data-testid={breakdown ? 'context-breakdown' : 'context-estimate'}
- >
- {breakdown ? (
- <>
- {segments.map(({ id, label, value, ...segment }) => {
- const shouldRender =
- value > 0 || (id === 'tool-calls' && toolCallTokens != null);
- if (!shouldRender) {
- return null;
- }
- return (
- <Fragment key={id}>
- {id === 'tool-calls' && hasToolCounts ? (
+ <div
+ className="mt-3 grid min-w-0 grid-cols-1 items-start gap-3 @min-[38rem]:grid-cols-2"
+ data-testid="context-details"
+ >
+ <div className="min-w-0 space-y-3">
+ {(pressure !== 'none' || insights.length > 0) && (
+ <div className="relative flex items-center justify-between gap-2">
+ {pressure !== 'none' ? (
+ <p
+ className={cn(
+ 'flex min-w-0 items-center gap-1.5 text-xs',
+ pressure === 'danger' ? 'text-text-destructive' : 'text-text-warning',
+ )}
+ >
+ <TriangleAlert className="size-3.5 shrink-0" aria-hidden="true" />
+ {localize(
+ pressure === 'danger'
+ ? 'com_ui_context_pressure_danger'
+ : 'com_ui_context_pressure_warn',
+ )}
+ </p>
+ ) : (
+ <span />
+ )}
+ {insights.length > 0 && (
+ <HoverCard open={insightsOpen} onOpenChange={setInsightsOpen}>
+ <HoverCardTrigger asChild>
+ <Button
+ type="button"
+ variant="quiet"
+ size="icon"
+ aria-label={localize('com_ui_context_insights')}
+ aria-expanded={insightsOpen}
+ aria-controls={insightsOpen ? insightsId : undefined}
+ data-testid="context-insights-toggle"
+ className="size-6"
+ onFocus={() => setInsightsOpen(true)}
+ onBlur={() => setInsightsOpen(false)}
+ onClick={() => setInsightsOpen(true)}
+ >
+ <Info className="size-3.5" aria-hidden="true" />
+ </Button>
+ </HoverCardTrigger>
+ <HoverCardPortal>
+ <HoverCardContent
+ id={insightsId}
+ 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"
+ align="end"
+ >
+ {insights.map((insight, index) => (
+ <p className="text-text-secondary text-xs break-words" key={index}>
+ {insight}
+ </p>
+ ))}
+ </HoverCardContent>
+ </HoverCardPortal>
+ </HoverCard>
+ )}
+ </div>
+ )}
+ <div
+ className="space-y-1.5"
+ data-testid={breakdown ? 'context-breakdown' : 'context-estimate'}
+ >
+ {breakdown ? (
+ <>
+ {segments.map(({ id, label, value, ...segment }) => {
+ const shouldRender =
+ value > 0 || (id === 'tool-calls' && toolCallTokens != null);
+ if (!shouldRender) {
+ return null;
+ }
+ return (
+ <Fragment key={id}>
+ {id === 'tool-calls' && hasToolCounts ? (
+ <Row
+ label={label}
+ value={value}
+ max={maxTokens}
+ segment={segment}
+ id={id}
+ onHoverChange={setHoveredSegment}
+ onClick={() => setToolsExpanded((open) => !open)}
+ expanded={toolsExpanded}
+ controls={toolsExpanded ? toolBreakdownId : undefined}
+ />
+ ) : (
+ <Row
+ label={label}
+ value={value}
+ max={maxTokens}
+ segment={segment}
+ id={id}
+ onHoverChange={setHoveredSegment}
+ />
+ )}
+ {id === 'tool-calls' && toolsExpanded && hasToolCounts && (
+ <div id={toolBreakdownId} className="space-y-1 pl-6">
+ <p className="text-text-tertiary text-xs font-medium">
+ {localize('com_ui_context_tool_breakdown')}
+ </p>
+ {toolBreakdown.map((tool) => (
+ <Row key={tool.name} label={tool.name} value={tool.tokens} />
+ ))}
+ </div>
+ )}
+ {id === 'system' && dynamicInstructionTokens > 0 && (
+ <div className="pl-6">
+ <Row
+ label={localize('com_ui_context_dynamic_instructions')}
+ value={dynamicInstructionTokens}
+ />
+ </div>
+ )}
+ </Fragment>
+ );
+ })}
+ {/** 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
+ * tokens twice and the visible rows would sum past the meter. */}
+ {(normalizeTokenCount(view.cacheRead) > 0 ||
+ normalizeTokenCount(view.cacheWrite) > 0) && (
+ <div className="space-y-1.5 pl-6">
+ <p className="text-text-tertiary text-xs font-medium">
+ {localize('com_ui_context_cache_last_call')}
+ </p>
+ {normalizeTokenCount(view.cacheRead) > 0 && (
<Row
- label={label}
- value={value}
+ label={localize('com_ui_context_cached')}
+ value={normalizeTokenCount(view.cacheRead)}
max={maxTokens}
- segment={segment}
- id={id}
- onHoverChange={setHoveredSegment}
- onClick={() => setToolsExpanded((open) => !open)}
- expanded={toolsExpanded}
- controls={toolsExpanded ? toolBreakdownId : undefined}
/>
- ) : (
+ )}
+ {normalizeTokenCount(view.cacheWrite) > 0 && (
<Row
- label={label}
- value={value}
+ label={localize('com_ui_context_cache_write')}
+ value={normalizeTokenCount(view.cacheWrite)}
max={maxTokens}
- segment={segment}
- id={id}
- onHoverChange={setHoveredSegment}
/>
)}
- {id === 'tool-calls' && toolsExpanded && hasToolCounts && (
- <div id={toolBreakdownId} className="space-y-1 pl-6">
- <p className="text-text-tertiary text-xs font-medium">
- {localize('com_ui_context_tool_breakdown')}
- </p>
- {toolBreakdown.map((tool) => (
- <Row key={tool.name} label={tool.name} value={tool.tokens} />
- ))}
- </div>
- )}
- {id === 'system' && dynamicInstructionTokens > 0 && (
- <div className="pl-6">
- <Row
- label={localize('com_ui_context_dynamic_instructions')}
- value={dynamicInstructionTokens}
- />
- </div>
- )}
- </Fragment>
- );
- })}
- {/** 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
- * tokens twice and the visible rows would sum past the meter. */}
- {(normalizeTokenCount(view.cacheRead) > 0 ||
- normalizeTokenCount(view.cacheWrite) > 0) && (
- <div className="space-y-1.5 pl-6">
- <p className="text-text-tertiary text-xs font-medium">
- {localize('com_ui_context_cache_last_call')}
- </p>
- {normalizeTokenCount(view.cacheRead) > 0 && (
- <Row
- label={localize('com_ui_context_cached')}
- value={normalizeTokenCount(view.cacheRead)}
- max={maxTokens}
- />
- )}
- {normalizeTokenCount(view.cacheWrite) > 0 && (
- <Row
- label={localize('com_ui_context_cache_write')}
- value={normalizeTokenCount(view.cacheWrite)}
- max={maxTokens}
- />
- )}
- </div>
- )}
- {freeTokens != null && (
- <Row
- label={localize('com_ui_context_free')}
- value={freeTokens}
- max={maxTokens}
- track
- id="free"
- onHoverChange={setHoveredSegment}
- />
- )}
- </>
- ) : (
- <>
- {normalizeTokenCount(view.branchTotals.summaryBaseline) > 0 && (
- <Row
- label={localize('com_ui_context_summary')}
- value={view.branchTotals.summaryBaseline}
- max={maxTokens}
- />
- )}
- {view.messagesPruned ? (
- /** Over-window: the per-category split no longer describes what's
- * sent, so show the pruned message total (incl. in-flight). */
- <Row
- label={localize('com_ui_context_messages')}
- value={view.messageTokens + view.liveTokens}
- max={maxTokens}
- />
- ) : (
- <>
- <Row label={localize('com_ui_input')} value={view.branchTotals.input} />
+ </div>
+ )}
+ {freeTokens != null && (
<Row
- label={localize('com_ui_output')}
- value={view.branchTotals.output + view.liveTokens}
+ label={localize('com_ui_context_free')}
+ value={freeTokens}
+ max={maxTokens}
+ track
+ id="free"
+ onHoverChange={setHoveredSegment}
/>
- {normalizeTokenCount(view.estimatedTokens) > 0 && (
- <Row
- label={localize('com_ui_context_estimated')}
- value={view.estimatedTokens}
- />
- )}
- </>
- )}
- {/** 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
- * `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
- * subtracting it would corrupt them. */}
- {normalizeTokenCount(view.toolCallTokens) > 0 && (
- <div className="pl-6">
+ )}
+ </>
+ ) : (
+ <>
+ {normalizeTokenCount(view.branchTotals.summaryBaseline) > 0 && (
<Row
- label={localize('com_ui_context_tool_calls')}
- value={normalizeTokenCount(view.toolCallTokens)}
+ label={localize('com_ui_context_summary')}
+ value={view.branchTotals.summaryBaseline}
+ max={maxTokens}
/>
- </div>
- )}
- {view.overheadTokens > 0 && (
- <Row label={localize('com_ui_context_system')} value={view.overheadTokens} />
- )}
- {maxTokens == null && (
- <p className="text-text-secondary text-xs">
- {localize('com_ui_context_unknown')}
- </p>
- )}
- <p className="text-text-secondary text-xs italic">
- {localize('com_ui_estimated')}
- </p>
- </>
- )}
- </div>
-
- <div className="border-border-light border-t" role="separator" />
- <div className="space-y-1.5" data-testid="token-usage-last-turn">
- <h3 className="text-text-tertiary text-xs font-semibold tracking-wider uppercase">
- {view.turnInProgress
- ? localize('com_ui_context_current_turn')
- : localize('com_ui_context_last_turn')}
- </h3>
- {view.lastTurnUsage != null ? (
- <>
- <Row
- label={localize('com_ui_context_uncached_input')}
- value={view.lastTurnUsage.input}
- />
- <Row label={localize('com_ui_cache_read')} value={view.lastTurnUsage.cacheRead} />
- <Row
- label={localize('com_ui_cache_write')}
- value={view.lastTurnUsage.cacheWrite}
- />
- <Row label={localize('com_ui_output')} value={view.lastTurnUsage.output} />
- </>
- ) : (
- <p className="text-text-secondary text-xs">
- {view.turnInProgress
- ? localize('com_ui_context_waiting_usage')
- : localize('com_ui_context_unavailable_usage')}
- </p>
- )}
- </div>
-
- {hasUsage && (
- <>
- <div className="border-border-light border-t" role="separator" />
- <div className="space-y-1.5" data-testid="token-usage-totals">
- <div className="flex items-baseline justify-between gap-2">
- <h3 className="text-text-tertiary text-xs font-semibold tracking-wider uppercase">
- {localize('com_ui_context_totals')}
- </h3>
- <span className="text-text-tertiary text-xs">
- {localize('com_ui_context_this_branch')}
- </span>
- </div>
- <Row
- label={localize('com_ui_context_uncached_input')}
- value={branchUsage.input}
- />
- <Row label={localize('com_ui_output')} value={branchUsage.output} />
- {normalizeTokenCount(branchUsage.cacheRead) > 0 && (
- <Row label={localize('com_ui_cache_read')} value={branchUsage.cacheRead} />
- )}
- {normalizeTokenCount(branchUsage.cacheWrite) > 0 && (
- <Row label={localize('com_ui_cache_write')} value={branchUsage.cacheWrite} />
- )}
- {/** Subagent calls are accumulated per conversation for the session
- * and are not attributed to a response; label them all-branches. */}
- {subagentTokens > 0 && (
- <Row label={localize('com_ui_context_subagents_all')} value={subagentTokens} />
- )}
- </div>
- </>
- )}
- {showTotal && (
- <div
- className="border-border-light space-y-1.5 border-t pt-2"
- data-testid="token-usage-all-branches"
- >
- <h3 className="text-text-tertiary text-xs font-semibold tracking-wider uppercase">
- {localize('com_ui_context_cost_total')}
- </h3>
- <Row
- label={localize('com_ui_context_uncached_input')}
- value={view.totalUsage.input}
- />
- <Row label={localize('com_ui_output')} value={view.totalUsage.output} />
- {normalizeTokenCount(view.totalUsage.cacheRead) > 0 && (
- <Row label={localize('com_ui_cache_read')} value={view.totalUsage.cacheRead} />
- )}
- {normalizeTokenCount(view.totalUsage.cacheWrite) > 0 && (
- <Row label={localize('com_ui_cache_write')} value={view.totalUsage.cacheWrite} />
- )}
- </div>
- )}
-
- {showCost &&
- (view.lastTurnUsage?.costKnown === true ||
- (hasUsage && branchUsage.costKnown) ||
- (showTotal && view.totalUsage.costKnown)) && (
- <>
- <div className="border-border-light border-t" role="separator" />
- <div className="space-y-1.5" data-testid="token-usage-cost">
- {view.lastTurnUsage?.costKnown === true && (
- <div className="flex items-center justify-between gap-4 text-sm">
- <span className="text-text-secondary">
- {localize(
- view.turnInProgress
- ? 'com_ui_context_cost_current_turn'
- : 'com_ui_context_cost_last_turn',
- )}
- </span>
- <span className="text-text-primary font-medium">
- {formatCost(view.lastTurnUsage.cost, currency)}
- </span>
- </div>
)}
- {hasUsage && branchUsage.costKnown && (
- <div className="flex items-center justify-between gap-4 text-sm">
- <span className="text-text-secondary">
- {showTotal
- ? localize('com_ui_context_cost_branch')
- : localize('com_ui_context_cost')}
- </span>
- <span className="text-text-primary font-medium">
- {formatCost(view.branchCost, currency)}
- </span>
- </div>
+ {view.messagesPruned ? (
+ /** Over-window: the per-category split no longer describes what's
+ * sent, so show the pruned message total (incl. in-flight). */
+ <Row
+ label={localize('com_ui_context_messages')}
+ value={view.messageTokens + view.liveTokens}
+ max={maxTokens}
+ />
+ ) : (
+ <>
+ <Row label={localize('com_ui_input')} value={view.branchTotals.input} />
+ <Row
+ label={localize('com_ui_output')}
+ value={view.branchTotals.output + view.liveTokens}
+ />
+ {normalizeTokenCount(view.estimatedTokens) > 0 && (
+ <Row
+ label={localize('com_ui_context_estimated')}
+ value={view.estimatedTokens}
+ />
+ )}
+ </>
)}
- {showTotal && view.totalUsage.costKnown && (
- <div className="flex items-center justify-between gap-4 text-xs">
- <span className="text-text-secondary">
- {localize('com_ui_context_cost_total')}
- </span>
- <span className="text-text-secondary">
- {formatCost(view.totalCost, currency)}
- </span>
+ {/** 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
+ * `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
+ * subtracting it would corrupt them. */}
+ {normalizeTokenCount(view.toolCallTokens) > 0 && (
+ <div className="pl-6">
+ <Row
+ label={localize('com_ui_context_tool_calls')}
+ value={normalizeTokenCount(view.toolCallTokens)}
+ />
</div>
)}
- </div>
- </>
+ {view.overheadTokens > 0 && (
+ <Row label={localize('com_ui_context_system')} value={view.overheadTokens} />
+ )}
+ {maxTokens == null && (
+ <p className="text-text-secondary text-xs">
+ {localize('com_ui_context_unknown')}
+ </p>
+ )}
+ <p className="text-text-secondary text-xs italic">
+ {localize('com_ui_estimated')}
+ </p>
+ </>
+ )}
+ </div>
+ </div>
+ <div className="min-w-0 space-y-3">
+ <Usage
+ title={localize(
+ view.turnInProgress ? 'com_ui_context_current_turn' : 'com_ui_context_last_turn',
+ )}
+ usage={view.lastTurnUsage}
+ unavailable={localize(
+ view.turnInProgress
+ ? 'com_ui_context_waiting_usage'
+ : 'com_ui_context_unavailable_usage',
+ )}
+ cost={
+ showCost && view.lastTurnUsage?.costKnown ? view.lastTurnUsage.cost : undefined
+ }
+ costLabel={localize(
+ view.turnInProgress
+ ? 'com_ui_context_cost_current_turn'
+ : 'com_ui_context_cost_last_turn',
+ )}
+ currency={currency}
+ testId="token-usage-last-turn"
+ />
+ {hasUsage && (
+ <Usage
+ title={localize('com_ui_context_totals')}
+ subtitle={localize('com_ui_context_this_branch')}
+ usage={branchUsage}
+ cost={showCost && branchUsage.costKnown ? view.branchCost : undefined}
+ costLabel={localize(
+ showTotal ? 'com_ui_context_cost_branch' : 'com_ui_context_cost',
+ )}
+ currency={currency}
+ subagentTokens={subagentTokens}
+ testId="token-usage-totals"
+ />
+ )}
+ {showTotal && (
+ <Usage
+ title={localize('com_ui_context_cost_total')}
+ usage={view.totalUsage}
+ cost={showCost && view.totalUsage.costKnown ? view.totalCost : undefined}
+ costLabel={localize('com_ui_context_cost_total')}
+ currency={currency}
+ testId="token-usage-all-branches"
+ />
)}
+ </div>
{langfuseSessionUrl && (
<>
- <div className="border-border-light border-t" role="separator" />
- <Button asChild variant="link" size="bare" className="w-full justify-between">
+ <div
+ className="border-border-light border-t @min-[38rem]:col-span-2"
+ role="separator"
+ />
+ <Button
+ asChild
+ variant="link"
+ size="bare"
+ className="w-full justify-between @min-[38rem]:col-span-2"
+ >
<a href={langfuseSessionUrl} target="_blank" rel="noopener noreferrer">
<span>{localize('com_ui_langfuse_view_session')}</span>
<ExternalLink className="size-4 shrink-0" aria-hidden="true" />
diff --git a/client/src/components/Chat/Input/TokenUsage/Usage.spec.tsx b/client/src/components/Chat/Input/TokenUsage/Usage.spec.tsx
new file mode 100644
index 0000000000..29d80938a6
--- /dev/null
+++ b/client/src/components/Chat/Input/TokenUsage/Usage.spec.tsx
@@ -0,0 +1,112 @@
+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';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+const usage: BranchUsage = {
+ input: 37_900,
+ output: 551_600,
+ cacheRead: 60_900_000,
+ cacheWrite: 4_900_000,
+ cost: 39.45,
+ costKnown: true,
+};
+
+const renderUsage = (props: Partial<React.ComponentProps<typeof Usage>> = {}) =>
+ render(
+ <Usage
+ title="com_ui_context_current_turn"
+ usage={usage}
+ cost={usage.cost}
+ costLabel="com_ui_context_cost_current_turn"
+ testId="usage"
+ {...props}
+ />,
+ );
+
+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' });
+ 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',
+ ]) {
+ expect(within(section).getByText(label).tagName).toBe('DT');
+ }
+ expect(section.querySelector('dl')).toHaveClass('grid-cols-2');
+ });
+
+ it('discloses full-size details with Enter and Space without duplicating metrics', async () => {
+ renderUsage();
+ const trigger = screen.getByRole('button');
+ trigger.focus();
+ await userEvent.keyboard('{Enter}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const content = document.getElementById(trigger.getAttribute('aria-controls')!);
+ expect(content).toContainElement(screen.getByText('60.9M'));
+ expect(content?.querySelector('dl')).toHaveClass('text-sm');
+ expect(screen.getAllByText('37.9K')).toHaveLength(1);
+ await userEvent.keyboard(' ');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.getByText('37.9K')).toBeVisible();
+ });
+
+ it('shows known zeroes, but never substitutes missing usage with zero', () => {
+ const { rerender } = renderUsage({
+ usage: { ...usage, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ cost: 0,
+ });
+ expect(screen.getAllByText('0')).toHaveLength(4);
+ 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"
+ testId="usage"
+ />,
+ );
+ expect(screen.getByRole('button')).toBeDisabled();
+ expect(screen.getByText('com_ui_context_waiting_usage')).toBeVisible();
+ expect(screen.queryByText('0')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
+ });
+
+ it('keeps the subagent subtotal explicitly all-branches and honors currency', () => {
+ renderUsage({
+ subagentTokens: 44_600_000,
+ currency: { code: 'EUR', rate: 2 },
+ });
+ expect(screen.getByText('com_ui_context_subagents_all').nextElementSibling).toHaveTextContent(
+ '44.6M',
+ );
+ expect(screen.getByTestId('usage-cost')).toHaveTextContent('€78.90');
+ });
+
+ it('omits unknown and non-finite costs', () => {
+ const { rerender } = renderUsage({ cost: undefined });
+ expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
+ rerender(
+ <Usage
+ title="com_ui_context_current_turn"
+ usage={usage}
+ cost={NaN}
+ costLabel="com_ui_context_cost_current_turn"
+ testId="usage"
+ />,
+ );
+ expect(screen.queryByTestId('usage-cost')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Chat/Input/TokenUsage/Usage.tsx b/client/src/components/Chat/Input/TokenUsage/Usage.tsx
new file mode 100644
index 0000000000..bd8ecf0d46
--- /dev/null
+++ b/client/src/components/Chat/Input/TokenUsage/Usage.tsx
@@ -0,0 +1,126 @@
+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';
+
+interface UsageProps {
+ title: string;
+ subtitle?: string;
+ usage?: BranchUsage;
+ unavailable?: string;
+ cost?: number;
+ costLabel: string;
+ currency?: CurrencyConfig;
+ subagentTokens?: number;
+ testId: string;
+}
+
+export default function Usage({
+ title,
+ subtitle,
+ usage,
+ unavailable,
+ cost,
+ costLabel,
+ currency,
+ subagentTokens = 0,
+ testId,
+}: UsageProps) {
+ const localize = useLocalize();
+ const headingId = useId();
+ const [expanded, setExpanded] = useState(false);
+ const rows =
+ usage == null
+ ? []
+ : [
+ { label: localize('com_ui_context_uncached_input'), value: usage.input },
+ { label: localize('com_ui_output'), value: usage.output },
+ { label: localize('com_ui_cache_read'), value: usage.cacheRead },
+ { label: localize('com_ui_cache_write'), value: usage.cacheWrite },
+ ];
+ if (subagentTokens > 0) {
+ rows.push({ label: localize('com_ui_context_subagents_all'), value: subagentTokens });
+ }
+ const reading = (detailed: boolean) => (
+ <dl
+ className={cn(
+ 'tabular-nums',
+ detailed ? 'space-y-1.5 text-sm' : 'grid grid-cols-2 gap-x-3 gap-y-1.5 text-xs',
+ )}
+ >
+ {rows.map(({ label, value }, index) => (
+ <div
+ key={label}
+ className={cn(
+ 'flex flex-wrap items-baseline gap-y-1',
+ detailed ? 'justify-between gap-x-3' : 'gap-x-1.5',
+ !detailed && index === 4 && 'col-span-2',
+ !detailed && index >= 2 && 'text-text-secondary',
+ )}
+ >
+ <dt className="text-text-secondary min-w-0 break-words">{label}</dt>
+ <dd className="font-medium whitespace-nowrap">
+ {formatTokens(normalizeTokenCount(value))}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ );
+
+ return (
+ <section
+ aria-labelledby={headingId}
+ data-testid={testId}
+ className="border-border-light rounded-theme-menu-panel min-w-0 border p-3"
+ >
+ <Collapsible open={expanded} onOpenChange={setExpanded}>
+ <h3 aria-labelledby={headingId}>
+ <CollapsibleTrigger
+ disabled={usage == null}
+ className="group flex w-full items-start justify-between text-left"
+ >
+ <span className="min-w-0">
+ <span
+ id={headingId}
+ className="text-text-primary block text-sm font-medium break-words"
+ >
+ {title}
+ </span>
+ {subtitle != null && (
+ <span className="text-text-secondary block text-xs">{subtitle}</span>
+ )}
+ </span>
+ <span className="ml-3 flex shrink-0 items-center gap-2">
+ {cost != null && Number.isFinite(cost) && (
+ <span
+ className="text-text-primary text-sm font-medium tabular-nums"
+ data-testid="usage-cost"
+ >
+ <span className="sr-only">{costLabel}: </span>
+ {formatCost(cost, currency)}
+ </span>
+ )}
+ {usage != null && (
+ <ChevronDown
+ aria-hidden="true"
+ className="text-text-secondary size-3.5 shrink-0 transition-transform group-data-[state=open]:rotate-180 motion-reduce:transition-none"
+ />
+ )}
+ </span>
+ </CollapsibleTrigger>
+ </h3>
+ {usage == null ? (
+ <p className="text-text-secondary mt-2 text-xs">{unavailable}</p>
+ ) : (
+ <>
+ {!expanded && <div className="mt-2">{reading(false)}</div>}
+ <CollapsibleContent className="mt-2">{reading(true)}</CollapsibleContent>
+ </>
+ )}
+ </Collapsible>
+ </section>
+ );
+}
diff --git a/client/src/components/Chat/Input/TokenUsage/index.spec.tsx b/client/src/components/Chat/Input/TokenUsage/index.spec.tsx
index aed883412b..a776599ad4 100644
--- a/client/src/components/Chat/Input/TokenUsage/index.spec.tsx
+++ b/client/src/components/Chat/Input/TokenUsage/index.spec.tsx
@@ -1,8 +1,10 @@
+import { Provider, createStore } from 'jotai';
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 { contextBreakdownExpandedAtom } from './store';
import TokenUsage from './index';
const mockStartupConfig = jest.fn();
@@ -144,6 +146,30 @@ describe('TokenUsage gauge', () => {
);
});
+ it('sizes expanded context relative to the viewport without widening balance-only cards', async () => {
+ mockStartupConfig.mockReturnValue(config());
+ mockTokenUsage.mockReturnValue(usage(83_200));
+ const store = createStore();
+ store.set(contextBreakdownExpandedAtom, true);
+ const { rerender } = render(
+ <Provider store={store}>
+ <TokenUsage index={0} conversation={conversation} isSubmitting={false} />
+ </Provider>,
+ );
+ await openCard();
+ expect(screen.getByTestId('token-usage-card')).toHaveClass(
+ 'w-[min(44rem,calc(100vw-2.5rem))]',
+ 'max-w-full',
+ );
+ mockTokenUsage.mockReturnValue(usage(0));
+ rerender(
+ <Provider store={store}>
+ <TokenUsage index={0} conversation={{ ...conversation }} isSubmitting={false} />
+ </Provider>,
+ );
+ expect(screen.getByTestId('token-usage-card')).toHaveClass('w-72');
+ });
+
it('tints the balance-only ring with the balance tone, amber until empty', () => {
mockStartupConfig.mockReturnValue(config({ contextUsage: false }));
mockBalance.mockReturnValue({ ...balance, tokenCredits: 400_000 });
diff --git a/client/src/components/Chat/Input/TokenUsage/index.tsx b/client/src/components/Chat/Input/TokenUsage/index.tsx
index e8b88d703e..5f226f8873 100644
--- a/client/src/components/Chat/Input/TokenUsage/index.tsx
+++ b/client/src/components/Chat/Input/TokenUsage/index.tsx
@@ -1,4 +1,5 @@
import { memo } from 'react';
+import { useAtomValue } from 'jotai';
import { Spinner } from '@librechat/client';
import { Constants } from 'librechat-data-provider';
import type { TConversation } from 'librechat-data-provider';
@@ -9,8 +10,9 @@ import { useGetLangfuseSessionLinkQuery, useGetStartupConfig } from '~/data-prov
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 { formatTokens } from '~/utils';
+import { cn, formatTokens } from '~/utils';
import { useLocalize } from '~/hooks';
import UsagePopover from './Popover';
import Breakdown from './Breakdown';
@@ -96,6 +98,7 @@ function TokenUsageIndicator({
balanceEnabled: boolean;
}) {
const localize = useLocalize();
+ const expanded = useAtomValue(contextBreakdownExpandedAtom);
const view = useTokenUsage({ index, conversation, isSubmitting });
/** Owned here, not in the popover: `unmountOnHide` would otherwise lose the
* in-flight state the moment the pointer leaves. */
@@ -149,9 +152,13 @@ function TokenUsageIndicator({
)
}
>
- {/* 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">
+ <div
+ className={cn(
+ 'max-w-full space-y-3',
+ hasContext && expanded ? 'w-[min(44rem,calc(100vw-2.5rem))]' : 'w-72',
+ )}
+ data-testid="token-usage-card"
+ >
{hasContext && (
<ContextCard
view={view}
diff --git a/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts b/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts
index 73d7575b45..854a813e8b 100644
--- a/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts
+++ b/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts
@@ -138,7 +138,7 @@ test.describe('persisted context usage', () => {
await expect(lastTurn.getByText('Cache write').locator('../..')).toContainText('50');
await expect(branch.getByText('This branch')).toBeVisible();
await expect(branch.getByText('Cache read').locator('../..')).toContainText('500');
- await expect(popover.getByTestId('token-usage-cost')).toContainText('Cost (last turn)');
+ await expect(lastTurn.getByTestId('usage-cost')).toContainText('Cost (last turn)');
await expect(popover.getByTestId('token-usage-all-branches')).toHaveCount(0);
await page.keyboard.press('Escape');
};
diff --git a/e2e/specs/mock/scenarios/series-eight-theme.spec.ts b/e2e/specs/mock/scenarios/series-eight-theme.spec.ts
index e0301e0bb8..4cf5633055 100644
--- a/e2e/specs/mock/scenarios/series-eight-theme.spec.ts
+++ b/e2e/specs/mock/scenarios/series-eight-theme.spec.ts
@@ -119,6 +119,10 @@ test.describe('series-eight theme resolution', () => {
const messagesSwatch = popover.locator('span.bg-series-1');
await expect(messagesSwatch).toHaveCount(1);
await expect(messagesSwatch).toHaveCSS('background-color', 'rgb(120, 200, 255)');
+ const totals = popover.getByTestId('token-usage-totals');
+ await expect(totals.locator('dt').first()).toHaveCSS('color', 'rgb(215, 215, 215)');
+ await expect(totals.locator('dd').first()).toHaveCSS('color', 'rgb(250, 250, 250)');
+ await expect(totals.getByRole('button')).toHaveAttribute('aria-expanded', 'false');
});
test('named series eight overrides fallback @scenario:named-series-eight-overrides-fallback', async ({
diff --git a/e2e/specs/mock/scenarios/subagent-context-total.spec.ts b/e2e/specs/mock/scenarios/subagent-context-total.spec.ts
index 578649385d..6d0b3c9824 100644
--- a/e2e/specs/mock/scenarios/subagent-context-total.spec.ts
+++ b/e2e/specs/mock/scenarios/subagent-context-total.spec.ts
@@ -100,12 +100,13 @@ test.describe('subagent context usage totals', () => {
await expect(totals.getByText('Input (uncached)', { exact: true })).toBeVisible();
await expect(totals.getByText('Output', { exact: true })).toBeVisible();
- const subagentRow = totals
- .locator('div.flex.w-full.items-center.justify-between')
- .filter({ hasText: 'Subagents (all branches)' });
- await expect(subagentRow).toHaveCount(1);
+ const subagentTerm = totals
+ .getByRole('term')
+ .filter({ hasText: /^Subagents \(all branches\)$/ });
+ await expect(subagentTerm).toHaveCount(1);
+ await expect(subagentTerm).toBeVisible();
await expect(
- subagentRow.locator(':scope > span').nth(1),
+ subagentTerm.locator('..').getByRole('definition'),
// The value is compact-formatted when large; a leading non-zero digit
// proves the all-branches usage emitted by the child is not zero.
).toHaveText(/^[1-9]\d*(?:\.\d+)?[KMB]?$/);
diff --git a/e2e/specs/mock/scenarios/v4-rendering.spec.ts b/e2e/specs/mock/scenarios/v4-rendering.spec.ts
index 003f992e21..7631e64c04 100644
--- a/e2e/specs/mock/scenarios/v4-rendering.spec.ts
+++ b/e2e/specs/mock/scenarios/v4-rendering.spec.ts
@@ -342,6 +342,7 @@ test.describe('Tailwind v4 rendering', () => {
await openArtifactPanel(page, conversationId);
const forbidden = await page.evaluate(() => {
+ // Container queries are intentional and covered by usage.spec.ts.
const tokens = [
'h-19',
'w-19',
@@ -350,7 +351,6 @@ test.describe('Tailwind v4 rendering', () => {
'max-w-11/12',
'border-1',
'scrollbar-none',
- '@container',
];
const selectors: string[] = [];
const visit = (rules: CSSRuleList) => {
diff --git a/e2e/specs/mock/usage.spec.ts b/e2e/specs/mock/usage.spec.ts
index 0d42a3286e..c77448d237 100644
--- a/e2e/specs/mock/usage.spec.ts
+++ b/e2e/specs/mock/usage.spec.ts
@@ -1,3 +1,4 @@
+import AxeBuilder from '@axe-core/playwright';
import { expect, test } from '@playwright/test';
import type { Page, Locator } from '@playwright/test';
import {
@@ -92,10 +93,10 @@ test.describe('context usage gauge', () => {
* token-config endpoint prices mock models at the default rate, and the
* fake model emits usage — so a $ value must render. A single (unbranched)
* conversation shows only the branch cost, no all-branches total line. */
- const costSection = popover.getByTestId('token-usage-cost');
+ const costSection = popover.getByTestId('token-usage-totals').getByTestId('usage-cost');
await expect(costSection).toBeVisible();
await expect(costSection.getByText(/\$\d|<\$0\.01/).first()).toBeVisible();
- await expect(costSection.getByText('All branches')).toHaveCount(0);
+ await expect(popover.getByTestId('token-usage-all-branches')).toHaveCount(0);
await page.keyboard.press('Escape');
/** Persistence (Parts A + B): after reload the breakdown rehydrates from
@@ -107,7 +108,7 @@ test.describe('context usage gauge', () => {
const reloaded = await openBreakdown(page);
await expect(reloaded.getByTestId('context-breakdown')).toBeVisible({ timeout: 10000 });
await expect(reloaded.getByTestId('token-usage-last-turn')).toContainText('Input (uncached)');
- const reloadedCost = reloaded.getByTestId('token-usage-cost');
+ const reloadedCost = reloaded.getByTestId('token-usage-totals').getByTestId('usage-cost');
await expect(reloadedCost).toBeVisible();
await expect(reloadedCost.getByText(/\$\d|<\$0\.01/).first()).toBeVisible();
});
@@ -133,7 +134,7 @@ test.describe('context usage gauge', () => {
/** Single branch: branch cost == total, so no all-branches line renders. */
let popover = await openBreakdown(page);
- await expect(popover.getByTestId('token-usage-cost')).toBeVisible();
+ await expect(popover.getByTestId('token-usage-totals').getByTestId('usage-cost')).toBeVisible();
await expect(popover.getByText('All branches')).toHaveCount(0);
await page.keyboard.press('Escape');
@@ -153,7 +154,7 @@ test.describe('context usage gauge', () => {
/** Branch cost is shown live for the regenerated branch. */
popover = await openBreakdown(page);
- await expect(popover.getByTestId('token-usage-cost')).toBeVisible();
+ await expect(popover.getByTestId('token-usage-totals').getByTestId('usage-cost')).toBeVisible();
await page.keyboard.press('Escape');
/** After reload both branches rehydrate from persisted metadata.usage, so
@@ -162,10 +163,12 @@ test.describe('context usage gauge', () => {
await page.reload({ timeout: 15000 });
await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
const reloaded = await openBreakdown(page);
- const costSection = reloaded.getByTestId('token-usage-cost');
+ const costSection = reloaded.getByTestId('token-usage-totals').getByTestId('usage-cost');
await expect(costSection).toBeVisible();
- await expect(costSection.getByText('Cost (this branch)')).toBeVisible();
- await expect(costSection.getByText('All branches')).toBeVisible();
+ await expect(costSection).toContainText('Cost (this branch)');
+ await expect(
+ reloaded.getByTestId('token-usage-all-branches').getByTestId('usage-cost'),
+ ).toBeVisible();
});
test('preserves the granular breakdown after switching branches', async ({ page }) => {
@@ -206,7 +209,7 @@ test.describe('context usage gauge', () => {
* flushed usage is restored from the sticky usage history even though its
* cache message lacks metadata.usage and B's regenerate dropped it. */
const popover = page.getByRole('region', { name: 'Context usage' });
- const costSection = popover.getByTestId('token-usage-cost');
+ const costSection = popover.getByTestId('token-usage-totals').getByTestId('usage-cost');
await expect(costSection).toBeVisible();
/** Branch A also has siblings, so both a branch-cost row and an all-branches
* total render — assert at least one cost value is present. */
@@ -254,6 +257,86 @@ test.describe('context usage gauge', () => {
await expect(popover.getByTestId('token-usage-totals')).toBeVisible({ timeout: 10000 });
});
+ test('reflows condensed sections inside the viewport with keyboard-accessible details', async ({
+ page,
+ }, testInfo) => {
+ test.setTimeout(120000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await sendAndAwaitReply(page, 'hello');
+ const popover = await openBreakdown(page);
+ await expect(popover).toHaveCSS('container-type', 'inline-size');
+ const dialog = page.getByRole('dialog', { name: 'Context usage' });
+ const details = popover.getByTestId('context-details');
+ const lastTurn = popover.getByTestId('token-usage-last-turn');
+ const disclosure = lastTurn.getByRole('button');
+ await expect(disclosure).toHaveAttribute('aria-expanded', 'false');
+ await expect(lastTurn.getByText('Cache read', { exact: true })).toBeVisible();
+
+ for (const viewport of [
+ { width: 1280, height: 900, columns: 2 },
+ { width: 768, height: 800, columns: 2 },
+ { width: 375, height: 812, columns: 1 },
+ { width: 320, height: 568, columns: 1 },
+ { width: 1280, height: 450, columns: 2 },
+ ]) {
+ await page.setViewportSize({ width: viewport.width, height: viewport.height });
+ await expect
+ .poll(() =>
+ details.evaluate((element) =>
+ getComputedStyle(element).gridTemplateColumns.split(' ').length,
+ ),
+ )
+ .toBe(viewport.columns);
+ await expect
+ .poll(async () => {
+ const box = await dialog.boundingBox();
+ return (
+ box != null &&
+ box.x >= 7 &&
+ box.y >= 7 &&
+ box.x + box.width <= viewport.width - 7 &&
+ box.y + box.height <= viewport.height - 7
+ );
+ })
+ .toBe(true);
+ await expect
+ .poll(() => dialog.evaluate((element) => element.scrollWidth <= element.clientWidth))
+ .toBe(true);
+ }
+
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await disclosure.focus();
+ await page.keyboard.press('Enter');
+ await expect(disclosure).toHaveAttribute('aria-expanded', 'true');
+ await expect(lastTurn.getByText('Cache write', { exact: true })).toBeVisible();
+ await page.keyboard.press('Space');
+ await expect(disclosure).toHaveAttribute('aria-expanded', 'false');
+ await expect(lastTurn.getByText('Input (uncached)', { exact: true })).toBeVisible();
+
+ const accessibility = await new AxeBuilder({ page })
+ .include('[data-testid="token-usage-card"]')
+ .withTags(['wcag2a', 'wcag2aa', 'wcag21aa'])
+ .analyze();
+ expect(accessibility.violations).toEqual([]);
+ await testInfo.attach('context-panel-desktop', {
+ body: await dialog.screenshot(),
+ contentType: 'image/png',
+ });
+ await page.setViewportSize({ width: 375, height: 812 });
+ await expect
+ .poll(() =>
+ details.evaluate((element) =>
+ getComputedStyle(element).gridTemplateColumns.split(' ').length,
+ ),
+ )
+ .toBe(1);
+ await testInfo.attach('context-panel-mobile', {
+ body: await dialog.screenshot(),
+ contentType: 'image/png',
+ });
+ });
+
test('hides on a new chat, then reveals the breakdown on hover and pins it on click', async ({
page,
}) => {