Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🥧 feat: Show Last-Turn Token Usage Beside Conversation Totals (#16230)
lia-by-librechat[bot]33a11f3e6ad3
diff --git a/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx b/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsxindex 756e6e4612..b89c15a5a0 100644--- a/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx+++ b/client/src/components/Chat/Input/TokenUsage/Breakdown.spec.tsx@@ -454,6 +454,7 @@ describe('TokenUsage Breakdown', () => {* 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(cachedRow.parentElement?.className).toContain('pl-6');expect(cachedRow.textContent).toContain('30');/** The share column is keyed to the window, like every row above: without@@ -560,6 +561,207 @@ describe('TokenUsage Breakdown', () => {});});+ describe('last turn', () => {+ it.each([true, false])(+ 'shows sibling totals on an unrecorded branch, showCost=%s',+ async (showCost) => {+ renderBreakdown({+ view: {+ ...view,+ hasUsage: false,+ branchUsage: {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ cost: 0,+ costKnown: false,+ },+ branchCost: 0,+ totalUsage: {+ input: 40,+ output: 5,+ cacheRead: 800,+ cacheWrite: 30,+ cost: 0.02,+ costKnown: true,+ },+ totalCost: 0.02,+ },+ showCost,+ });+ await userEvent.click(toggle());+ 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',+ );+ } else {+ expect(screen.queryByTestId('token-usage-cost')).not.toBeInTheDocument();+ }+ },+ );++ it('distinguishes a recorded turn from branch and all-branches cache usage', async () => {+ renderBreakdown({+ view: {+ ...view,+ lastTurnUsage: {+ input: 20,+ output: 5,+ cacheRead: 700,+ cacheWrite: 90,+ cost: 0.004,+ costKnown: true,+ },+ branchUsage: {+ input: 120,+ output: 15,+ cacheRead: 800,+ cacheWrite: 90,+ cost: 0.01,+ costKnown: true,+ },+ totalUsage: {+ input: 140,+ output: 20,+ cacheRead: 900,+ cacheWrite: 90,+ cost: 0.02,+ costKnown: true,+ },+ branchCost: 0.01,+ totalCost: 0.02,+ },+ showCost: true,+ });+ 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',+ );+ 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',+ );+ const all = within(screen.getByTestId('token-usage-all-branches'));+ 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();+ });++ it('exposes all-branches token differences without requiring cost coverage', async () => {+ renderBreakdown({+ view: {+ ...view,+ lastTurnUsage: {+ input: 1,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ cost: 0,+ costKnown: true,+ },+ branchUsage: { ...view.branchUsage, costKnown: false },+ totalUsage: { ...view.totalUsage, cacheWrite: 25, costKnown: false },+ },+ showCost: true,+ });+ 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',+ );+ });++ 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>,+ );+ await userEvent.click(toggle());+ expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(+ 'com_ui_context_waiting_usage',+ );+ rerender(+ <Provider>+ <Breakdown view={{ ...view, lastTurnUsage: undefined, turnInProgress: false }} showCost />+ </Provider>,+ );+ expect(screen.getByTestId('token-usage-last-turn')).toHaveTextContent(+ 'com_ui_context_unavailable_usage',+ );+ });++ it('labels recorded in-flight cost as a partial current-turn figure', async () => {+ renderBreakdown({+ view: {+ ...view,+ turnInProgress: true,+ lastTurnUsage: {+ input: 10,+ output: 0,+ cacheRead: 20,+ cacheWrite: 0,+ cost: 0.01,+ costKnown: true,+ },+ },+ showCost: true,+ });+ await userEvent.click(toggle());+ 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',+ );+ });++ it('keeps a known zero cost and hides a missing cost', async () => {+ renderBreakdown({+ view: {+ ...view,+ lastTurnUsage: {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ cost: 0,+ costKnown: true,+ },+ branchUsage: { ...view.branchUsage, costKnown: false },+ },+ showCost: true,+ });+ await userEvent.click(toggle());+ 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',+ );+ });+ });+describe('langfuse', () => {const url = 'https://cloud.langfuse.com/project/project-1/sessions/conversation-1';diff --git a/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx b/client/src/components/Chat/Input/TokenUsage/Breakdown.tsxindex d05c4bad2b..55fca18cbe 100644--- a/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx+++ b/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx@@ -130,15 +130,19 @@ export default function Breakdown({percent = Math.min(Math.max(view.percent, 0), 100);}const { snapshot, snapshotActive, branchUsage, hasUsage } = view;- /** Show the all-branches total only when it (a) exceeds the active branch —- * epsilon guards against float summation order surfacing a spurious row in an- * unbranched conversation — and (b) has COMPLETE cost coverage, so a sibling- * branch saved without cost can't render an under-reported total. */+ /** Token differences are visible independently of cost display/coverage;+ * only compare costs when both sides are complete to avoid an apparent+ * all-branches total made from partially priced history. */const showTotal =- view.totalUsage.costKnown &&- Number.isFinite(view.totalCost) &&- Number.isFinite(view.branchCost) &&- view.totalCost - view.branchCost > 1e-9;+ view.totalUsage.input !== branchUsage.input ||+ view.totalUsage.output !== branchUsage.output ||+ view.totalUsage.cacheRead !== branchUsage.cacheRead ||+ view.totalUsage.cacheWrite !== branchUsage.cacheWrite ||+ (view.totalUsage.costKnown &&+ branchUsage.costKnown &&+ Number.isFinite(view.totalCost) &&+ Number.isFinite(view.branchCost) &&+ view.totalCost - view.branchCost > 1e-9);/** Every normalized bucket of the subagent calls: a cached call reports its* prompt under `cacheRead`/`cacheWrite`, so summing input+output alone@@ -509,6 +513,9 @@ export default function Breakdown({{(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 && (<Rowlabel={localize('com_ui_context_cached')}@@ -598,14 +605,51 @@ export default function Breakdown({)}</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">- <h3 className="text-text-tertiary text-xs font-semibold tracking-wider uppercase">- {localize('com_ui_context_totals')}- </h3>- <Row label={localize('com_ui_input')} value={branchUsage.input} />+ <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} />@@ -614,43 +658,81 @@ export default function Breakdown({<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, so they cannot be scoped to- * the viewed branch like the rows above; label them all-branches- * rather than imply branch scope. */}+ * 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 && hasUsage && branchUsage.costKnown && (- <>- <div className="border-border-light border-t" role="separator" />- <div className="space-y-1.5" data-testid="token-usage-cost">- <div className="flex items-center justify-between 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>+ {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>+ )}+ {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>+ </div>+ )}</div>- {showTotal && (- <div className="flex items-center justify-between text-xs">- <span className="text-text-secondary">- {localize('com_ui_context_cost_total')}- </span>- <span className="text-text-secondary">- {formatCost(view.totalCost, currency)}- </span>- </div>- )}- </div>- </>- )}+ </>+ )}{langfuseSessionUrl && (<>diff --git a/client/src/components/Chat/Input/TokenUsage/index.tsx b/client/src/components/Chat/Input/TokenUsage/index.tsxindex 5aa07de8f8..41d51f91f9 100644--- a/client/src/components/Chat/Input/TokenUsage/index.tsx+++ b/client/src/components/Chat/Input/TokenUsage/index.tsx@@ -232,7 +232,7 @@ function TokenUsageIndicator({}}}className={cn(- 'border-border-medium bg-surface-secondary text-text-primary z-[200] rounded-xl border p-3 shadow-lg focus:outline-hidden',+ 'border-border-medium bg-surface-secondary text-text-primary z-[200] max-h-[calc(100dvh-1rem)] overflow-y-auto overscroll-contain rounded-xl border p-3 shadow-lg focus:outline-hidden','origin-bottom translate-y-1 scale-95 opacity-0 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none','data-[enter]:translate-y-0 data-[enter]:scale-100 data-[enter]:opacity-100','data-[leave]:translate-y-1 data-[leave]:scale-95 data-[leave]:opacity-0',diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsxindex 4a66996cfb..c046f41ae0 100644--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx@@ -8,6 +8,7 @@ import type {TMessage,TSubmission,} from 'librechat-data-provider';+import { activeUsageResponseIdFamily, pendingUsageFamily } from '~/store/usage';import { revealedQueuedTurnFamily } from '~/store/steer';import useChatFunctions from '../useChatFunctions';import { isPasteSubmitted } from '~/utils';@@ -159,6 +160,26 @@ describe('useChatFunctions ask', () => {mockResolveCodeWorkspaceSubmission.mockReturnValue({});});+ it.each([EModelEndpoint.agents, EModelEndpoint.openAI])(+ 'binds the optimistic %s response before publishing its messages',+ (endpoint) => {+ const { result, setMessages, setSubmission } = renderAsk([], 'conversation-1', { endpoint });+ const store = getDefaultStore();+ store.set(activeUsageResponseIdFamily('conversation-1'), null);+ setMessages.mockImplementation((messages: TMessage[]) => {+ expect(store.get(activeUsageResponseIdFamily('conversation-1'))).toBe(+ messages.at(-1)?.messageId,+ );+ });+ act(() => result.current.ask({ text: 'Hello', conversationId: 'conversation-1' }));+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;+ expect(store.get(activeUsageResponseIdFamily('conversation-1'))).toBe(+ submission.initialResponse?.messageId,+ );+ expect(store.get(pendingUsageFamily('conversation-1')).eventCount).toBe(0);+ },+ );+it('reads an approval-mode selection made immediately before send', () => {mockGetLatestConversation.mockReturnValue({...conversation('conversation-1'),diff --git a/client/src/hooks/Chat/__tests__/useTokenUsage.spec.tsx b/client/src/hooks/Chat/__tests__/useTokenUsage.spec.tsxindex 442ca2872a..0abc3464c6 100644--- a/client/src/hooks/Chat/__tests__/useTokenUsage.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useTokenUsage.spec.tsx@@ -1,14 +1,25 @@import { getDefaultStore } from 'jotai';-import { renderHook } from '@testing-library/react';-import { QueryKeys } from 'librechat-data-provider';+import { act, renderHook } from '@testing-library/react';+import { Constants, QueryKeys } from 'librechat-data-provider';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { TMessage, TConversation } from 'librechat-data-provider';import type { ContextSnapshot } from '~/store/usage';-import { contextSnapshotFamily, snapshotsByAnchorFamily } from '~/store/usage';+import {+ contextSnapshotFamily,+ pendingUsageFamily,+ totalUsageFamily,+ activeUsageResponseIdFamily,+ liveTokensFamily,+ removeUsageAtoms,+ snapshotsByAnchorFamily,+} from '~/store/usage';+import { getRegenerateSubmissionMessages } from '~/hooks/Chat/useChatFunctions';+import { useLatestMessageId } from '~/hooks/Messages/useLatestMessage';+import useUsageHandler from '~/hooks/SSE/useUsageHandler';import useTokenUsage from '~/hooks/Chat/useTokenUsage';jest.mock('~/hooks/Messages/useLatestMessage', () => ({- useLatestMessageId: () => 'a2',+ useLatestMessageId: jest.fn(() => 'a2'),}));jest.mock('~/hooks/Chat/useTokenLimits', () => ({@@ -87,7 +98,7 @@ const renderTokenUsage = (['a1', anchorSnapshot(196000)],['a2', anchorSnapshot(195000)],]),- overrides: { messages?: TMessage[]; snapshot?: ContextSnapshot } = {},+ overrides: { messages?: TMessage[]; snapshot?: ContextSnapshot; isSubmitting?: boolean } = {},) => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -97,22 +108,450 @@ const renderTokenUsage = (store.set(contextSnapshotFamily(convo), overrides.snapshot ?? tailSnapshot);store.set(snapshotsByAnchorFamily(convo), anchors);- return renderHook(- () =>+ const hook = renderHook(+ (+ { isSubmitting }: { isSubmitting: boolean } = {+ isSubmitting: overrides.isSubmitting ?? false,+ },+ ) =>useTokenUsage({index: 0,conversation: { conversationId: convo, endpoint: 'agents' } as TConversation,- isSubmitting: false,+ isSubmitting,}),{+ initialProps: { isSubmitting: overrides.isSubmitting ?? false },wrapper: ({ children }) => (<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>),},);+ return { ...hook, queryClient };};describe('useTokenUsage — post-snapshot output', () => {+ beforeEach(() => {+ jest.mocked(useLatestMessageId).mockReturnValue('a2');+ removeUsageAtoms(convo);+ });++ it.each(['before idle', 'after idle'])(+ 'reconciles a recovered same-ID response whose metadata arrives %s',+ (arrival) => {+ const store = getDefaultStore();+ store.set(activeUsageResponseIdFamily(convo), 'a2');+ const pendingSnapshot = {+ ...tailSnapshot,+ anchorMessageId: 'u2',+ responseMessageId: 'a2',+ completedOutputTokens: 0,+ remainingContextTokens: 10000,+ };+ const { result, rerender, queryClient } = renderTokenUsage(new Map(), {+ isSubmitting: true,+ snapshot: pendingSnapshot,+ });+ expect(result.current.lastTurnUsage).toBeUndefined();+ const recovered = messages.map((message) =>+ message.messageId === 'a2'+ ? {+ ...message,+ metadata: {+ usage: { input: 10, output: 20, cacheRead: 900, cacheWrite: 50, cost: 0.02 },+ contextUsage: {+ ...tailSnapshot,+ completedOutputTokens: 20,+ cacheRead: 900,+ cacheWrite: 50,+ },+ },+ }+ : message,+ );+ const replaceCache = () =>+ act(() => queryClient.setQueryData([QueryKeys.messages, convo], recovered));+ if (arrival === 'before idle') {+ replaceCache();+ expect(result.current.lastTurnUsage).toBeUndefined();+ }+ // Terminal recovery clears live accounting, fetches messages, then idles.+ act(() => store.set(activeUsageResponseIdFamily(convo), null));+ rerender({ isSubmitting: false });+ if (arrival === 'after idle') {+ replaceCache();+ }+ expect(result.current.lastTurnUsage).toMatchObject({+ input: 10,+ output: 20,+ cacheRead: 900,+ cost: 0.02,+ costKnown: true,+ });+ expect(result.current.branchUsage.cacheRead).toBe(900);+ expect(result.current.totalUsage.cacheRead).toBe(900);+ expect(result.current.usedTokens).toBe(195020);+ expect(result.current.cacheRead).toBe(900);+ // A later refetch updates metadata without changing the selected tail.+ act(() =>+ queryClient.setQueryData(+ [QueryKeys.messages, convo],+ recovered.map((message) =>+ message.messageId === 'a2'+ ? {+ ...message,+ metadata: {+ ...message.metadata,+ usage: { input: 10, output: 30, cacheRead: 950, cacheWrite: 50, cost: 0.03 },+ },+ }+ : message,+ ),+ ),+ );+ expect(result.current.lastTurnUsage?.cacheRead).toBe(950);+ expect(result.current.branchCost).toBe(0.03);+ expect(result.current.totalCost).toBe(0.03);+ },+ );++ it('preserves all-branch history through a reduced regeneration cache, then honors an idle deletion', () => {+ const usage = (input: number) => ({+ input,+ output: 10,+ cacheRead: input,+ cacheWrite: 0,+ cost: input / 1000,+ });+ const saved = messages.map((message) =>+ message.messageId === 'a1' || message.messageId === 'a2'+ ? {+ ...message,+ metadata: { usage: usage(message.messageId === 'a1' ? 100 : 200) },+ }+ : message,+ );+ const descendantUser = { ...messages[2], messageId: 'u3', parentMessageId: 'a2' };+ const descendant = {+ ...messages[3],+ messageId: 'a3',+ parentMessageId: 'u3',+ metadata: { usage: usage(300) },+ };+ const history = [...saved, descendantUser, descendant];+ const { result, rerender, queryClient } = renderTokenUsage(undefined, {+ messages: history as TMessage[],+ });+ expect(result.current.totalUsage.input).toBe(600);+ const replacement = { ...messages[3], messageId: 'replacement', tokenCount: 0 };+ const reduced = [+ ...getRegenerateSubmissionMessages({+ messages: history as TMessage[],+ targetResponseMessage: history[3],+ initialResponseId: replacement.messageId,+ }),+ replacement,+ ];+ const submission = {+ conversation: { conversationId: convo },+ userMessage: messages[2],+ initialResponse: replacement,+ };+ const { result: writer } = renderHook(() => useUsageHandler());+ // Same order as ask(): ownership, reduced cache, then React's next render.+ act(() => {+ writer.current.bindResponse(submission);+ queryClient.setQueryData([QueryKeys.messages, convo], reduced);+ });+ jest.mocked(useLatestMessageId).mockReturnValue('replacement');+ rerender({ isSubmitting: true });+ expect(result.current.totalUsage.input).toBe(600);+ expect(result.current.branchUsage.input).toBe(100);+ expect(result.current.turnInProgress).toBe(true);+ act(() =>+ writer.current.backfillUsage(+ [{ input_tokens: 50, output_tokens: 10, cost: 0.05, runId: 'regen-history', seq: 1 }],+ submission,+ ),+ );+ expect(result.current.totalUsage.input).toBe(650);+ expect(result.current.branchUsage.input).toBe(150);+ const final = { ...replacement, metadata: { usage: usage(50) } };+ act(() => {+ queryClient.setQueryData([QueryKeys.messages, convo], [...history, final]);+ writer.current.finalizeUsage(+ { responseMessage: final, conversation: { conversationId: convo } },+ submission,+ );+ });+ rerender({ isSubmitting: false });+ expect(result.current.totalUsage.input).toBe(650);+ expect(result.current.totalCost).toBeCloseTo(0.65);+ jest.mocked(useLatestMessageId).mockReturnValue('a3');+ rerender({ isSubmitting: false });+ expect(result.current.branchUsage.input).toBe(600);+ expect(result.current.lastTurnUsage?.input).toBe(300);+ jest.mocked(useLatestMessageId).mockReturnValue('replacement');+ rerender({ isSubmitting: false });+ act(() =>+ queryClient.setQueryData([QueryKeys.messages, convo], [...reduced.slice(0, -1), final]),+ );+ expect(result.current.totalUsage.input).toBe(150);+ expect(result.current.totalCost).toBeCloseTo(0.15);+ });++ it('preserves unsaved usage across view unmount until the server assigns the conversation id', () => {+ const store = getDefaultStore();+ const key = String(Constants.NEW_CONVO);+ removeUsageAtoms(key);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const { result: writer } = renderHook(() => useUsageHandler());+ const submission = {+ userMessage: { messageId: 'u-new', conversationId: key },+ conversation: { conversationId: key },+ initialResponse: { messageId: 'a-new', parentMessageId: 'u-new' },+ };+ writer.current.backfillUsage(+ [{ input_tokens: 10, output_tokens: 5, cost: 0.01, runId: 'new-run', seq: 1 }],+ submission,+ );+ const { unmount } = renderHook(+ () =>+ useTokenUsage({+ index: 0,+ conversation: { conversationId: key } as TConversation,+ isSubmitting: true,+ }),+ {+ wrapper: ({ children }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ ),+ },+ );+ unmount();+ expect(store.get(pendingUsageFamily(key)).eventCount).toBe(1);+ writer.current.finalizeUsage(+ {+ conversation: { conversationId: 'newly-saved' },+ responseMessage: { messageId: 'a-new', parentMessageId: 'u-new', isCreatedByUser: false },+ },+ submission,+ );+ expect(store.get(totalUsageFamily('newly-saved')).input).toBe(10);+ expect(store.get(totalUsageFamily('newly-saved')).cost).toBe(0.01);+ removeUsageAtoms(key);+ removeUsageAtoms('newly-saved');+ });++ it('keeps the granular context gauge after a local stop and branch revisit', () => {+ const { result: writer } = renderHook(() => useUsageHandler());+ const submission = {+ conversation: { conversationId: convo },+ userMessage: { messageId: 'u2', conversationId: convo },+ initialResponse: { messageId: 'a2', parentMessageId: 'u2' },+ };+ writer.current.contextHandler(tailSnapshot, submission);+ writer.current.tapContent('x'.repeat(168), submission);+ const live = getDefaultStore().get(contextSnapshotFamily(convo))!;+ const { result, rerender } = renderTokenUsage(new Map(), {+ snapshot: live,+ isSubmitting: true,+ });+ expect(result.current.isEstimate).toBe(false);+ act(() => writer.current.attributePending('a2', submission));+ rerender({ isSubmitting: false });+ expect(result.current.isEstimate).toBe(false);+ expect(result.current.usedTokens).toBe(195042);+ expect(result.current.liveTokens).toBe(0);+ jest.mocked(useLatestMessageId).mockReturnValue('a1');+ rerender({ isSubmitting: false });+ jest.mocked(useLatestMessageId).mockReturnValue('a2');+ rerender({ isSubmitting: false });+ expect(result.current.isEstimate).toBe(false);+ expect(result.current.usedTokens).toBe(195042);+ });++ it('keeps a viewed sibling isolated while another response streams and finalizes', () => {+ const saved = messages.map((message) =>+ message.messageId === 'a2'+ ? {+ ...message,+ metadata: {+ usage: { input: 25, output: 10, cacheRead: 100, cacheWrite: 0, cost: 0.01 },+ },+ }+ : message,+ );+ const generating = { ...messages[3], messageId: 'a2-alt', tokenCount: 0, text: '' };+ const { result: writer } = renderHook(() => useUsageHandler());+ const submission = {+ userMessage: { messageId: 'u2', conversationId: convo },+ initialResponse: { messageId: 'a2-alt', parentMessageId: 'u2' },+ conversation: { conversationId: convo },+ isRegenerate: true,+ };+ const store = getDefaultStore();+ const liveSnapshot = {+ ...tailSnapshot,+ anchorMessageId: 'u2',+ responseMessageId: 'a2-alt',+ completedOutputTokens: 0,+ remainingContextTokens: 8000,+ };+ const usage = {+ input_tokens: 40,+ output_tokens: 4,+ input_token_details: { cache_read: 300 },+ cost: 0.02,+ runId: 'sibling-run',+ seq: 1,+ };+ writer.current.backfillUsage([usage], submission);+ store.set(liveTokensFamily(convo), 100);+ const { result, rerender } = renderTokenUsage(new Map([['a2', tailSnapshot]]), {+ messages: [...saved, generating] as TMessage[],+ isSubmitting: true,+ snapshot: liveSnapshot,+ });++ expect(result.current.turnInProgress).toBe(false);+ expect(result.current.lastTurnUsage?.cacheRead).toBe(100);+ expect(result.current.branchUsage.cacheRead).toBe(100);+ expect(result.current.totalUsage.cacheRead).toBe(400);+ expect(result.current.liveTokens).toBe(0);+ expect(result.current.usedTokens).toBe(197000);++ jest.mocked(useLatestMessageId).mockReturnValue('a2-alt');+ rerender();+ expect(result.current.turnInProgress).toBe(true);+ expect(result.current.lastTurnUsage?.cacheRead).toBe(300);+ expect(result.current.branchUsage.cacheRead).toBe(300);+ expect(result.current.usedTokens).toBe(192100);++ jest.mocked(useLatestMessageId).mockReturnValue('a2');+ rerender();+ act(() =>+ writer.current.finalizeUsage(+ { responseMessage: generating, conversation: { conversationId: convo } },+ submission,+ ),+ );+ expect(result.current.branchTotals.tailId).toBe('a2');+ expect(result.current.lastTurnUsage?.cacheRead).toBe(100);+ expect(result.current.branchUsage.cacheRead).toBe(100);+ expect(result.current.totalUsage.cacheRead).toBe(400);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBeNull();+ });++ it('uses the selected branch estimate when only a sibling has live context', () => {+ const store = getDefaultStore();+ store.set(activeUsageResponseIdFamily(convo), 'a2-alt');+ store.set(liveTokensFamily(convo), 9000);+ const { result } = renderTokenUsage(new Map(), {+ isSubmitting: true,+ snapshot: { ...tailSnapshot, responseMessageId: 'a2-alt' },+ });+ expect(result.current.isEstimate).toBe(true);+ expect(result.current.liveTokens).toBe(0);+ expect(result.current.usedTokens).toBe(4400);+ });++ it('keeps ancestor context cache distinct from a newer response with usage but no snapshot', () => {+ const ancestor = { ...tailSnapshot, anchorMessageId: 'a1', cacheRead: 1234, cacheWrite: 50 };+ const saved = messages.map((message) =>+ message.messageId === 'a2'+ ? {+ ...message,+ metadata: { usage: { input: 10, output: 5, cacheRead: 888, cacheWrite: 20 } },+ }+ : message,+ );+ const { result } = renderTokenUsage(new Map([['a1', ancestor]]), {+ messages: saved as TMessage[],+ snapshot: { ...tailSnapshot, anchorMessageId: 'another-branch' },+ });+ expect(result.current.cacheRead).toBe(1234);+ expect(result.current.cacheWrite).toBe(50);+ expect(result.current.lastTurnUsage?.cacheRead).toBe(888);+ expect(result.current.turnInProgress).toBe(false);+ });++ it('uses the selected response rollup, not the cumulative branch usage', () => {+ const saved = messages.map((message) => {+ if (message.messageId === 'a1') {+ return {+ ...message,+ metadata: { usage: { input: 100, output: 20, cacheRead: 500, cacheWrite: 0 } },+ };+ }+ if (message.messageId === 'a2') {+ return {+ ...message,+ metadata: { usage: { input: 30, output: 15, cacheRead: 700, cacheWrite: 50, cost: 0 } },+ };+ }+ return message;+ }) as TMessage[];+ const { result, unmount } = renderTokenUsage(undefined, { messages: saved });++ expect(result.current.lastTurnUsage).toEqual({+ input: 30,+ output: 15,+ cacheRead: 700,+ cacheWrite: 50,+ cost: 0,+ costKnown: true,+ });+ expect(result.current.branchUsage.input).toBe(130);+ expect(result.current.branchUsage.cacheRead).toBe(1200);+ expect(result.current.branchUsage.costKnown).toBe(false);+ unmount();+ });++ it('reports only confirmed calls in an in-progress turn, never the previous tail', () => {+ const pendingAtom = pendingUsageFamily(convo);+ const store = getDefaultStore();+ store.set(activeUsageResponseIdFamily(convo), 'a2');+ const saved = messages.map((message) =>+ message.messageId === 'a2'+ ? ({+ ...message,+ metadata: { usage: { input: 100, output: 10, cacheRead: 50, cacheWrite: 0 } },+ } as TMessage)+ : message,+ );+ store.set(pendingAtom, {+ input: 40,+ output: 4,+ cacheRead: 300,+ cacheWrite: 20,+ eventCount: 2,+ costUSD: 0.01,+ costKnown: true,+ });+ const { result, unmount } = renderTokenUsage(undefined, {+ messages: saved,+ isSubmitting: true,+ });+ expect(result.current.turnInProgress).toBe(true);+ expect(result.current.lastTurnUsage?.input).toBe(40);+ expect(result.current.lastTurnUsage?.cacheRead).toBe(300);+ expect(result.current.branchUsage.cacheRead).toBe(350);+ unmount();+ store.set(pendingAtom, {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ eventCount: 0,+ costUSD: 0,+ costKnown: true,+ });+ store.set(activeUsageResponseIdFamily(convo), 'a2');+ const waiting = renderTokenUsage(undefined, { messages: saved, isSubmitting: true });+ expect(waiting.result.current.lastTurnUsage).toBeUndefined();+ waiting.unmount();+ });+it('charges the finalized output against the runway projection', () => {const { result } = renderTokenUsage();diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.tsindex 18bb4fa29f..d14a978ce0 100644--- a/client/src/hooks/Chat/useChatFunctions.ts+++ b/client/src/hooks/Chat/useChatFunctions.ts@@ -44,6 +44,7 @@ import useCodeApprovalMode from '~/hooks/Agents/useCodeApprovalMode';import useSetFilesToDelete from '~/hooks/Files/useSetFilesToDelete';import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';import useGetSender from '~/hooks/Conversations/useGetSender';+import { activeUsageResponseIdFamily } from '~/store/usage';import { revealedQueuedTurnFamily } from '~/store/steer';import store, { useGetEphemeralAgent } from '~/store';import { startupConfigKey } from '~/data-provider';@@ -782,6 +783,13 @@ export default function useChatFunctions({queuedMessageOrigin: overrideQueuedMessageOrigin,};+ /** Bind before publishing the optimistic tail, not after the first provider+ * event: a waiting request already owns a turn even when no usage exists. */+ jotaiStore.set(+ activeUsageResponseIdFamily(conversationId ?? Constants.NEW_CONVO),+ initialResponse.messageId,+ );+if (regenerateShaped) {setMessages([...submissionMessages, initialResponse]);focusRegeneratedResponse(initialResponse.parentMessageId);diff --git a/client/src/hooks/Chat/useTokenUsage.ts b/client/src/hooks/Chat/useTokenUsage.tsindex 2af292eb14..578ab8684f 100644--- a/client/src/hooks/Chat/useTokenUsage.ts+++ b/client/src/hooks/Chat/useTokenUsage.ts@@ -1,6 +1,6 @@import { useEffect, useMemo, useRef } from 'react';-import { useAtomValue, useSetAtom } from 'jotai';import { useQueryClient } from '@tanstack/react-query';+import { useStore, useAtomValue, useSetAtom } from 'jotai';import { Constants, QueryKeys } from 'librechat-data-provider';import type { TMessage, TConversation, TModelTokenomics } from 'librechat-data-provider';import type { BranchTotals, BranchUsage } from '~/utils/tokens';@@ -13,6 +13,7 @@ import {removeUsageAtoms,hydrateSnapshots,pendingUsageFamily,+ activeUsageResponseIdFamily,subagentUsageFamily,pendingSubagentUsageFamily,branchTotalsFamily,@@ -21,6 +22,7 @@ import {} from '~/store/usage';import {buildIndex,+ upsertEntries,sumBranch,clearIndex,mergeUsage,@@ -55,6 +57,10 @@ export interface TokenUsageView {branchUsage: BranchUsage;/** Provider usage across all branches of the conversation */totalUsage: BranchUsage;+ /** Usage of the selected response, or completed calls in the in-flight turn. */+ lastTurnUsage?: BranchUsage;+ /** Distinguishes incomplete in-flight usage from a completed saved turn. */+ turnInProgress: boolean;/** Whether any usage is available to display (branch has token usage) */hasUsage: boolean;/** Authoritative branch cost; the cost row is gated on `interface.contextCost` at render */@@ -105,14 +111,27 @@ export default function useTokenUsage({isSubmitting,}: TokenUsageParams): TokenUsageView {const queryClient = useQueryClient();+ const usageStore = useStore();const conversationKey = conversation?.conversationId ?? Constants.NEW_CONVO;const tailId = useLatestMessageId(index);const snapshot = useAtomValue(contextSnapshotFamily(conversationKey));const snapshotsByAnchor = useAtomValue(snapshotsByAnchorFamily(conversationKey));const pendingUsage = useAtomValue(pendingUsageFamily(conversationKey));+ const activeResponseId = useAtomValue(activeUsageResponseIdFamily(conversationKey));+ const turnInProgress = isSubmitting && activeResponseId != null && activeResponseId === tailId;const totalUsageBase = useAtomValue(totalUsageFamily(conversationKey));- const branchTotals = useAtomValue(branchTotalsFamily(conversationKey));+ const storedBranchTotals = useAtomValue(branchTotalsFamily(conversationKey));+ /** A terminal stream writer updates the shared rollup for its own response.+ * Project a different viewed tail locally, without writing it back and making+ * two views of the same conversation compete over the shared atom. */+ const branchTotals = useMemo(+ () =>+ storedBranchTotals.tailId === tailId+ ? storedBranchTotals+ : sumBranch(conversationKey, tailId, snapshot?.anchorMessageId),+ [storedBranchTotals, conversationKey, tailId, snapshot?.anchorMessageId],+ );const liveTokens = useAtomValue(liveTokensFamily(conversationKey));const committedSubagentUsage = useAtomValue(subagentUsageFamily(conversationKey));const pendingSubagentUsage = useAtomValue(pendingSubagentUsageFamily(conversationKey));@@ -156,8 +175,8 @@ export default function useTokenUsage({[pendingUsage],);const branchUsage = useMemo(- () => mergeUsage(branchTotals.usage, pendingAsUsage),- [branchTotals.usage, pendingAsUsage],+ () => (turnInProgress ? mergeUsage(branchTotals.usage, pendingAsUsage) : branchTotals.usage),+ [branchTotals.usage, pendingAsUsage, turnInProgress],);const totalUsage = useMemo(() => mergeUsage(totalUsageBase, pendingAsUsage),@@ -170,80 +189,90 @@ export default function useTokenUsage({() => mergeUsage(committedSubagentUsage, pendingSubagentUsage),[committedSubagentUsage, pendingSubagentUsage],);+ /** Do not show the previous response as the current turn during a submission.+ * Pending contains only provider-confirmed completed calls, not text estimates. */+ let lastTurnUsage = branchTotals.lastTurnUsage;+ if (turnInProgress) {+ lastTurnUsage = pendingUsage.eventCount > 0 ? pendingAsUsage : undefined;+ }const hasUsage =branchUsage.input + branchUsage.output + branchUsage.cacheRead + branchUsage.cacheWrite > 0;- const isSubmittingRef = useRef(isSubmitting);- isSubmittingRef.current = isSubmitting;- const tailIdRef = useRef(tailId);- tailIdRef.current = tailId;- const anchorId = snapshot?.anchorMessageId ?? null;- const anchorIdRef = useRef(anchorId);- anchorIdRef.current = anchorId;+ const indexedCache = useRef<{ conversationKey: string; messages: TMessage[] | undefined }>();+ /** The messages cache is authoritative once a run settles. Stream deltas do+ * not rebuild the index, but idle transitions MUST catch up even when the+ * recovered message has the same id (404/retry-ceiling recovery has no FINAL).+ * All refresh triggers use this one projection, not separate writer paths. */useEffect(() => {- /** Cache `updated` events fire on every state transition — rebuild the- * O(n) index only when the data snapshot reference actually changed */- let lastIndexed: TMessage[] | undefined;- const rebuild = (messages?: TMessage[]) => {- if (messages === lastIndexed && messages !== undefined) {- return;+ const queryKey = [QueryKeys.messages, conversationKey];+ const reconcile = () => {+ const messages = queryClient.getQueryData<TMessage[]>(queryKey);+ if (+ indexedCache.current?.conversationKey !== conversationKey ||+ messages !== indexedCache.current.messages+ ) {+ /** Regeneration temporarily removes the old response and descendants+ * from the cache. A streaming projection is not a history deletion. */+ if (isSubmitting || usageStore.get(activeUsageResponseIdFamily(conversationKey)) != null) {+ upsertEntries(conversationKey, messages ?? []);+ } else {+ buildIndex(conversationKey, messages);+ }+ hydrateSnapshots(conversationKey, messages);+ indexedCache.current = { conversationKey, messages };}- lastIndexed = messages;- buildIndex(conversationKey, messages);- /** Restore each branch's persisted breakdown (Part A) without clobbering- * a live finalized snapshot for the same response id. */- hydrateSnapshots(conversationKey, messages);- setBranchTotals(sumBranch(conversationKey, tailIdRef.current, anchorIdRef.current));+ setBranchTotals(sumBranch(conversationKey, tailId, snapshot?.anchorMessageId));setTotalUsage(sumTotalUsage(conversationKey));};-- rebuild(queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationKey]));-+ reconcile();const unsubscribe = queryClient.getQueryCache().subscribe((event) => {- if (isSubmittingRef.current || event.type !== 'updated') {- return;- }- const queryKey = event.query.queryKey;+ /** ask() binds before changing the cache. Read that atom synchronously:+ * this callback can run before React renders isSubmitting=true. */if (- !Array.isArray(queryKey) ||- queryKey[0] !== QueryKeys.messages ||- queryKey[1] !== conversationKey+ isSubmitting ||+ usageStore.get(activeUsageResponseIdFamily(conversationKey)) != null ||+ event.type !== 'updated') {return;}- rebuild(event.query.state.data as TMessage[] | undefined);+ const key = event.query.queryKey;+ if (key[0] !== QueryKeys.messages || key[1] !== conversationKey) {+ return;+ }+ const messages = event.query.state.data as TMessage[] | undefined;+ if (messages !== indexedCache.current?.messages) {+ reconcile();+ }});- return () => {- unsubscribe();- /** Bound memory to open conversations — drop this one's token index and- * usage atoms on switch/unmount; both rebuild from the query cache on- * return. NEW_CONVO is migrated to its real id by finalizeUsage, so- * leave it alone to avoid racing that handoff. */+ return unsubscribe;+ }, [+ conversationKey,+ tailId,+ snapshot?.anchorMessageId,+ isSubmitting,+ queryClient,+ usageStore,+ setBranchTotals,+ setTotalUsage,+ ]);++ /** Lifetime cleanup is independent of projection refreshes. A branch change+ * or stream completion must not discard sticky usage or replay dedup keys. */+ useEffect(+ () => () => {+ if (indexedCache.current?.conversationKey === conversationKey) {+ indexedCache.current = undefined;+ }+ /** The unsaved conversation is migrated by finalizeUsage. Route changes+ * can unmount this view before that handoff, so leave its state intact. */if (conversationKey !== Constants.NEW_CONVO) {clearIndex(conversationKey);removeUsageAtoms(conversationKey);}- };- }, [conversationKey, queryClient, setBranchTotals, setTotalUsage]);-- useEffect(() => {- /** Re-index from the cache on every tail change (created/finalize during a- * stream AND branch switches). Branch switches don't fire a cache `updated`- * event, so the subscriber below can't catch them; without rebuilding here- * the index stays on whatever the last stream left it — which may have- * dropped the now-viewed branch's response, so sumBranch would find no- * tokens/usage and the gauge + branch cost would blank out. Bounded: tailId- * only shifts on created/finalize/branch-switch, never per chunk. Usage for- * responses whose cache message lacks `metadata.usage` is restored from the- * sticky history inside buildIndex. */- buildIndex(- conversationKey,- queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationKey]),- );- setBranchTotals(sumBranch(conversationKey, tailId, anchorId));- setTotalUsage(sumTotalUsage(conversationKey));- }, [conversationKey, tailId, anchorId, setBranchTotals, setTotalUsage, queryClient]);+ },+ [conversationKey],+ );return useMemo(() => {/** The granular snapshot is for one specific generation. Show the live one@@ -252,7 +281,12 @@ export default function useTokenUsage({* one branch's breakdown onto its siblings. */const currentActive =snapshot != null &&- (isSubmitting || (snapshot.anchorMessageId != null && branchTotals.containsAnchor));+ (isSubmitting+ ? turnInProgress && snapshot.responseMessageId === activeResponseId+ : snapshot.anchorMessageId != null &&+ branchTotals.containsAnchor &&+ (snapshot.responseMessageId == null ||+ snapshot.anchorMessageId === snapshot.responseMessageId));/** Precedence: live/active snapshot → persisted branch snapshot →* per-message estimate. The first two are authoritative (real runs with the@@ -272,7 +306,7 @@ export default function useTokenUsage({* projection must too. */const completedOutput = normalizeTokenCount(effective?.completedOutputTokens);const retainedToolTokens = normalizeTokenCount(effective?.retainedToolTokens);- const liveOutput = normalizeTokenCount(liveTokens);+ const liveOutput = turnInProgress ? normalizeTokenCount(liveTokens) : 0;const remainingForRunway =effective?.remainingContextTokens != null? Math.max(@@ -341,6 +375,8 @@ export default function useTokenUsage({branchTotals,branchUsage,totalUsage,+ lastTurnUsage,+ turnInProgress,hasUsage,branchCost: branchUsage.cost,totalCost: totalUsage.cost,@@ -383,7 +419,7 @@ export default function useTokenUsage({latestExchangeTokens(conversationKey,tailId,- liveTokens > 0,+ liveOutput > 0,normalizeTokenCount(breakdown.summaryTokens),),),@@ -403,7 +439,7 @@ export default function useTokenUsage({* gauge at 100% after a compaction). */const maxTokens =limits.maxContextTokens != null ? normalizeTokenCount(limits.maxContextTokens) : undefined;- const liveOnTail = normalizeTokenCount(liveTokens) > 0;+ const liveOnTail = liveOutput > 0;/** Fixed instruction + tool-schema overhead for this agent/model (the latter is* already folded into `instructionTokens`), cached from live usage events. The* client can't otherwise know it for a snapshot-less branch, so reserve it from@@ -480,7 +516,7 @@ export default function useTokenUsage({overheadTokens +normalizeTokenCount(branchTotals.summaryBaseline) +messageTokens +- normalizeTokenCount(liveTokens),+ liveOutput,);return {usedTokens,@@ -493,10 +529,12 @@ export default function useTokenUsage({branchTotals,branchUsage,totalUsage,+ lastTurnUsage,+ turnInProgress,hasUsage,branchCost: branchUsage.cost,totalCost: totalUsage.cost,- liveTokens: normalizeTokenCount(liveTokens),+ liveTokens: liveOutput,estimatedTokens,overheadTokens,messageTokens,@@ -509,9 +547,12 @@ export default function useTokenUsage({}, [snapshot,isSubmitting,+ turnInProgress,+ activeResponseId,branchTotals,branchUsage,totalUsage,+ lastTurnUsage,hasUsage,liveTokens,limits,diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.tsindex 55b3193467..735cda82a3 100644--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts@@ -12,6 +12,13 @@ import {} from 'librechat-data-provider';import type { TMessage, TSubmission } from 'librechat-data-provider';import type { Query, QueryKey } from '@tanstack/react-query';+import {+ activeUsageResponseIdFamily,+ liveTokensFamily,+ branchTotalsFamily,+ pendingUsageFamily,+ removeUsageAtoms,+} from '~/store/usage';import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';type SSEEventListener = (e: Partial<MessageEvent> & { responseCode?: number }) => void;@@ -21,6 +28,7 @@ interface MockSSEInstance {addEventListener: jest.Mock;stream: jest.Mock;close: jest.Mock;+ dispatchEvent: jest.Mock;headers: Record<string, string>;readyState: number;_listeners: Record<string, SSEEventListener>;@@ -42,6 +50,7 @@ jest.mock('sse.js', () => {listeners[event] = cb;}),stream: jest.fn(),+ dispatchEvent: jest.fn(),close: jest.fn(() => {if (instance.readyState === 2) {return;@@ -228,6 +237,8 @@ const mockFinalHandler = jest.fn();const mockCreatedHandler = jest.fn();const mockStepHandler = jest.fn();const mockTitleHandler = jest.fn();+const mockContentHandler = jest.fn();+const mockSyncHandler = jest.fn();const mockSetIsSubmitting = jest.fn();const mockClearStepMaps = jest.fn();@@ -236,6 +247,12 @@ jest.mock('~/hooks/SSE/useEventHandlers', () => {return {__esModule: true,...actual,+ // Read at call time: the hooks barrel imports useSSE during this factory.+ startedAsNewConversation: (submission: TSubmission) =>+ jest.requireActual('~/hooks/SSE/useEventHandlers').startedAsNewConversation(submission),+ buildCreatedInitialResponse: (+ submission: Pick<TSubmission, 'initialResponse' | 'userMessage' | 'isRegenerate'>,+ ) => jest.requireActual('~/hooks/SSE/useEventHandlers').buildCreatedInitialResponse(submission),default: jest.fn(() => ({errorHandler: mockErrorHandler,finalHandler: mockFinalHandler,@@ -243,12 +260,15 @@ jest.mock('~/hooks/SSE/useEventHandlers', () => {attachmentHandler: jest.fn(),stepHandler: mockStepHandler,titleHandler: mockTitleHandler,- contentHandler: jest.fn(),+ contentHandler: mockContentHandler,+ syncHandler: mockSyncHandler,resetContentHandler: jest.fn(),syncStepMessage: jest.fn(),prunePtcTraces: jest.fn(),clearStepMaps: mockClearStepMaps,flushPendingDeltas: jest.fn(),+ cancelPendingDeltaFlush: jest.fn(),+ abortConversation: jest.fn(),messageHandler: jest.fn(),setIsSubmitting: mockSetIsSubmitting,setShowStopButton: jest.fn(),@@ -282,6 +302,7 @@ jest.mock('librechat-data-provider', () => {});import useResumableSSE from '~/hooks/SSE/useResumableSSE';+import useSSE from '~/hooks/SSE/useSSE';const CONV_ID = 'conv-abc-123';@@ -458,6 +479,187 @@ describe('useResumableSSE', () => {return { sse, unmount, chatHelpers };};+ it.each([useSSE, useResumableSSE])(+ '%p binds a created response before any output or usage',+ async (useTransport) => {+ removeUsageAtoms(CONV_ID);+ const submission = buildSubmission();+ const { unmount } = renderHook(() => useTransport(submission, buildChatHelpers()));+ await flushMicrotasks();+ const sse = getLastSSE();+ await act(async () => {+ sse._emit('message', {+ data: JSON.stringify({+ created: true,+ message: { ...submission.userMessage, messageId: 'created-user-id' },+ }),+ });+ });+ expect(getDefaultStore().get(activeUsageResponseIdFamily(CONV_ID))).toBe('created-user-id_');+ expect(getDefaultStore().get(pendingUsageFamily(CONV_ID)).eventCount).toBe(0);+ sse.readyState = MOCK_SSE_CLOSED;+ unmount();+ },+ );++ it.each(['final', 'cancel', 'error'])(+ 'keeps Assistants sync identity consistent through content, usage, and %s',+ async (terminal) => {+ removeUsageAtoms(CONV_ID);+ const submission = buildSubmission({ endpointOption: { endpoint: 'assistants' } });+ const helpers = buildChatHelpers();+ const { unmount } = renderHook(() => useSSE(submission, helpers));+ const sse = getLastSSE();+ const synced = {+ messageId: 'assistant-server-id',+ parentMessageId: 'server-user',+ conversationId: CONV_ID,+ isCreatedByUser: false,+ text: '',+ };+ await act(async () => {+ sse._emit('message', {+ data: JSON.stringify({+ sync: true,+ requestMessage: { ...submission.userMessage, messageId: 'server-user' },+ responseMessage: synced,+ }),+ });+ });+ const store = getDefaultStore();+ expect(store.get(activeUsageResponseIdFamily(CONV_ID))).toBe(synced.messageId);+ expect(mockSyncHandler.mock.calls.at(-1)?.[1].initialResponse.messageId).toBe(+ synced.messageId,+ );+ await act(async () => {+ sse._emit('message', {+ data: JSON.stringify({ type: 'text', index: 0, text: { value: 'x'.repeat(400) } }),+ });+ sse._emit('message', {+ data: JSON.stringify({+ event: 'on_token_usage',+ data: {+ input_tokens: 5,+ output_tokens: 100,+ cost: 0.01,+ runId: 'assistant-usage',+ seq: 1,+ },+ }),+ });+ });+ expect(mockContentHandler.mock.calls.at(-1)?.[0].submission.initialResponse.messageId).toBe(+ synced.messageId,+ );+ expect(mockContentHandler.mock.calls.at(-1)?.[0].submission.userMessage.messageId).toBe(+ 'server-user',+ );+ expect(store.get(activeUsageResponseIdFamily(CONV_ID))).toBe(synced.messageId);+ expect(store.get(pendingUsageFamily(CONV_ID)).eventCount).toBe(1);+ // The rendered response has the same ID that the accounting owner uses.+ helpers.getMessages.mockReturnValue([synced]);+ if (terminal === 'final') {+ await act(async () =>+ sse._emit('message', {+ data: JSON.stringify({+ final: true,+ responseMessage: synced,+ conversation: { conversationId: CONV_ID },+ }),+ }),+ );+ expect(mockFinalHandler.mock.calls.at(-1)?.[1].initialResponse.messageId).toBe(+ synced.messageId,+ );+ } else {+ await act(async () =>+ sse._emit(terminal, { data: JSON.stringify({ message: 'Stream ended' }) }),+ );+ }+ expect(store.get(activeUsageResponseIdFamily(CONV_ID))).toBeNull();+ expect(store.get(pendingUsageFamily(CONV_ID)).eventCount).toBe(0);+ if (terminal !== 'error') {+ expect(store.get(branchTotalsFamily(CONV_ID)).tailId).toBe(synced.messageId);+ expect(store.get(branchTotalsFamily(CONV_ID)).lastTurnUsage?.output).toBe(100);+ }+ sse.readyState = MOCK_SSE_CLOSED;+ unmount();+ },+ );++ it('binds the waiting submission before the start request resolves', async () => {+ removeUsageAtoms(CONV_ID);+ let finishStart!: (value: unknown) => void;+ (request.post as jest.Mock).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishStart = resolve;+ }),+ );+ const submission = buildSubmission();+ const { unmount } = renderHook(() => useResumableSSE(submission, buildChatHelpers()));+ expect(getDefaultStore().get(activeUsageResponseIdFamily(CONV_ID))).toBe('resp-1');+ expect(getDefaultStore().get(pendingUsageFamily(CONV_ID)).eventCount).toBe(0);+ unmount();+ await act(async () => {+ finishStart({ streamId: 'stream-123', generationCreatedAt: 1000 });+ });+ });++ it.each([useSSE, useResumableSSE])(+ '%p retains authoritative legacy text response ownership for subsequent usage events',+ async (useTransport) => {+ removeUsageAtoms(CONV_ID);+ const submission = buildSubmission();+ const { unmount } = renderHook(() => useTransport(submission, buildChatHelpers()));+ await flushMicrotasks();+ const sse = getLastSSE();+ await act(async () => {+ sse._emit('message', {+ data: JSON.stringify({+ message: true,+ messageId: 'server-text-id',+ parentMessageId: 'msg-1',+ text: 'a'.repeat(400),+ }),+ });+ });+ const store = getDefaultStore();+ expect(store.get(activeUsageResponseIdFamily(CONV_ID))).toBe('server-text-id');+ expect(store.get(liveTokensFamily(CONV_ID))).toBe(100);+ await act(async () => {+ sse._emit('message', {+ data: JSON.stringify({+ event: 'on_token_usage',+ data: { input_tokens: 5, output_tokens: 100, runId: 'legacy-call', seq: 1 },+ }),+ });+ });+ expect(store.get(activeUsageResponseIdFamily(CONV_ID))).toBe('server-text-id');+ expect(store.get(pendingUsageFamily(CONV_ID)).eventCount).toBe(1);+ await act(async () => {+ sse._emit('message', {+ data: JSON.stringify({+ final: true,+ responseMessage: {+ messageId: 'server-text-id',+ parentMessageId: 'msg-1',+ conversationId: CONV_ID,+ isCreatedByUser: false,+ text: 'done',+ },+ conversation: { conversationId: CONV_ID },+ }),+ });+ });+ expect(store.get(activeUsageResponseIdFamily(CONV_ID))).toBeNull();+ expect(store.get(pendingUsageFamily(CONV_ID)).eventCount).toBe(0);+ // A finalized legacy stream closes without dispatching cancellation.+ sse.readyState = MOCK_SSE_CLOSED;+ unmount();+ },+ );+it('clears the text and files draft from localStorage on 404', async () => {seedDraft(CONV_ID);expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}${CONV_ID}`)).not.toBeNull();diff --git a/client/src/hooks/SSE/__tests__/useUsageHandler.spec.tsx b/client/src/hooks/SSE/__tests__/useUsageHandler.spec.tsxindex b1366db0e3..954c46f581 100644--- a/client/src/hooks/SSE/__tests__/useUsageHandler.spec.tsx+++ b/client/src/hooks/SSE/__tests__/useUsageHandler.spec.tsx@@ -1,13 +1,20 @@import { getDefaultStore } from 'jotai';import { renderHook } from '@testing-library/react';import { Constants, reconcileContextUsageFromEvent } from 'librechat-data-provider';-import type { TContextUsageEvent, TTokenUsageEvent } from 'librechat-data-provider';+import type { TMessage, TContextUsageEvent, TTokenUsageEvent } from 'librechat-data-provider';import {contextSnapshotFamily,+ snapshotsByAnchorFamily,+ removeUsageAtoms,+ branchTotalsFamily,+ totalUsageFamily,+ pendingUsageFamily,+ activeUsageResponseIdFamily,liveTokensFamily,subagentUsageFamily,pendingSubagentUsageFamily,} from '~/store/usage';+import { buildIndex, sumTotalUsage, sumBranch, clearIndex } from '~/utils/tokens';import useUsageHandler from '~/hooks/SSE/useUsageHandler';/** Mirrors a real web-search + summarization turn: calibration pinned at 5@@ -46,6 +53,232 @@ const primaryUsage = (over?: Partial<TTokenUsageEvent>): TTokenUsageEvent => ({});describe('useUsageHandler — live snapshot reconciliation', () => {+ it.each([true, false])(+ 'retains a stopped snapshot with confirmed or unflushed output (confirmed=%s)',+ (confirmed) => {+ const convo = `stop-snapshot-${confirmed}`;+ const store = getDefaultStore();+ const { result } = renderHook(() => useUsageHandler());+ const submission = {+ conversation: { conversationId: convo },+ userMessage: { messageId: 'u', conversationId: convo },+ initialResponse: { messageId: 'r', parentMessageId: 'u' },+ };+ result.current.contextHandler(inflatedSnapshot({ calibrationRatio: 1 }), submission);+ if (confirmed) {+ result.current.usageHandler(+ primaryUsage({ output_tokens: 42, total_tokens: undefined }),+ submission,+ );+ } else {+ result.current.tapContent('x'.repeat(168), submission);+ }+ result.current.attributePending('r', submission);+ const snapshot = store.get(contextSnapshotFamily(convo));+ expect(snapshot?.anchorMessageId).toBe('r');+ expect(snapshot?.responseMessageId).toBe('r');+ expect(snapshot?.completedOutputTokens).toBe(42);+ expect(store.get(snapshotsByAnchorFamily(convo)).get('r')).toEqual(snapshot);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBeNull();+ expect(store.get(liveTokensFamily(convo))).toBe(0);+ result.current.attributePending('r', submission);+ expect(store.get(contextSnapshotFamily(convo))?.completedOutputTokens).toBe(42);+ result.current.contextHandler(inflatedSnapshot(), {+ ...submission,+ initialResponse: { messageId: 'other', parentMessageId: 'u' },+ });+ result.current.attributePending('r', submission);+ expect(store.get(contextSnapshotFamily(convo))?.anchorMessageId).toBe('u');+ expect(store.get(snapshotsByAnchorFamily(convo)).get('r')).toEqual(snapshot);+ },+ );++ it.each(['created', 'context', 'final'])(+ 'migrates unsaved usage at %s without retaining earlier optimistic branches',+ (handoff) => {+ const store = getDefaultStore();+ const temp = String(Constants.NEW_CONVO);+ removeUsageAtoms(temp);+ clearIndex(temp);+ const { result } = renderHook(() => useUsageHandler());+ for (let i = 0; i < 3; i++) {+ const real = `assigned-${handoff}-${i}`;+ const responseId = `response-${i}`;+ const old = {+ conversation: { conversationId: temp },+ userMessage: { messageId: `u-${i}`, conversationId: temp },+ initialResponse: { messageId: responseId, parentMessageId: `u-${i}` },+ };+ buildIndex(temp, [+ {+ messageId: `older-${i}`,+ text: 'Prior recorded response',+ conversationId: temp,+ parentMessageId: null,+ isCreatedByUser: false,+ metadata: { usage: { input: 20, output: 5, cacheRead: 0, cacheWrite: 0, cost: 0.01 } },+ } as TMessage,+ ]);+ result.current.bindResponse(old);+ const oldOwner = activeUsageResponseIdFamily(temp);+ result.current.contextHandler(inflatedSnapshot({ calibrationRatio: 1 }), old);+ const event = primaryUsage({+ runId: `call-${i}`,+ output_tokens: 12,+ total_tokens: undefined,+ });+ result.current.usageHandler(event, old);+ const moved = {+ ...old,+ conversation: { conversationId: real },+ userMessage: { ...old.userMessage, conversationId: real },+ };+ if (handoff === 'created') result.current.bindResponse(moved);+ if (handoff === 'context')+ result.current.contextHandler(inflatedSnapshot({ calibrationRatio: 1 }), moved);+ if (handoff !== 'final') {+ expect(store.get(oldOwner)).toBeNull();+ expect(sumTotalUsage(temp).input).toBe(0);+ expect(store.get(activeUsageResponseIdFamily(temp))).toBeNull();+ expect(store.get(pendingUsageFamily(real)).eventCount).toBe(1);+ result.current.backfillUsage([event], moved);+ expect(store.get(pendingUsageFamily(real)).eventCount).toBe(1);+ }+ // Even a terminal callback holding the original submission resolves real.+ result.current.finalizeUsage(+ {+ conversation: { conversationId: real },+ responseMessage: {+ messageId: responseId,+ parentMessageId: `u-${i}`,+ isCreatedByUser: false,+ },+ },+ old,+ );+ expect(sumBranch(real, responseId).lastTurnUsage?.output).toBe(12);+ expect(sumTotalUsage(temp).input).toBe(0);+ expect(store.get(activeUsageResponseIdFamily(temp))).toBeNull();+ expect(store.get(pendingUsageFamily(temp)).eventCount).toBe(0);+ removeUsageAtoms(real);+ clearIndex(real);+ }+ },+ );++ it.each([undefined, 0, 0.05])(+ 'prefers the server rollup to partially observed events (cost=%s)',+ (cost) => {+ const convo = `final-authority-${cost}`;+ const store = getDefaultStore();+ const { result } = renderHook(() => useUsageHandler());+ const submission = {+ conversation: { conversationId: convo },+ userMessage: { messageId: 'u', conversationId: convo },+ initialResponse: { messageId: 'r', parentMessageId: 'u' },+ };+ result.current.usageHandler(+ {+ input_tokens: 10,+ output_tokens: 5,+ cost: 0.01,+ runId: 'partial',+ seq: 1,+ usage_type: 'subagent',+ },+ submission,+ );+ const final = {+ conversation: { conversationId: convo },+ responseMessage: {+ messageId: 'r',+ parentMessageId: 'u',+ conversationId: convo,+ isCreatedByUser: false,+ metadata: { usage: { input: 100, output: 50, cacheRead: 900, cacheWrite: 40, cost } },+ },+ };+ result.current.finalizeUsage(final, submission);+ expect(store.get(branchTotalsFamily(convo)).lastTurnUsage).toEqual({+ input: 100,+ output: 50,+ cacheRead: 900,+ cacheWrite: 40,+ cost: cost ?? 0,+ costKnown: cost != null,+ });+ expect(store.get(totalUsageFamily(convo)).cacheRead).toBe(900);+ expect(store.get(pendingUsageFamily(convo)).eventCount).toBe(0);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBeNull();+ expect(store.get(subagentUsageFamily(convo)).input).toBe(10);+ result.current.finalizeUsage(final, submission);+ expect(store.get(totalUsageFamily(convo)).cacheRead).toBe(900);+ expect(store.get(subagentUsageFamily(convo)).input).toBe(10);+ },+ );++ it('tracks hydrated response ownership across replay, resume, regeneration, and reset', () => {+ const convo = 'usage-response-identity';+ const store = getDefaultStore();+ const { result } = renderHook(() => useUsageHandler());+ const submission = {+ userMessage: { messageId: 'server-user', conversationId: convo },+ initialResponse: { messageId: 'server-user_', parentMessageId: 'server-user' },+ conversation: { conversationId: convo },+ };+ result.current.contextHandler(inflatedSnapshot(), submission);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBe('server-user_');+ expect(store.get(contextSnapshotFamily(convo))?.responseMessageId).toBe('server-user_');+ result.current.backfillUsage([primaryUsage(), primaryUsage()], submission);+ expect(store.get(pendingUsageFamily(convo)).eventCount).toBe(1);++ result.current.resetLive(submission);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBeNull();+ const resumed = {+ ...submission,+ initialResponse: { messageId: 'durable-response', parentMessageId: 'server-user' },+ };+ result.current.seedLive(40, resumed);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBe('durable-response');+ result.current.resetLive(submission);+ const regenerated = {+ ...submission,+ initialResponse: { messageId: 'local-user_', parentMessageId: 'server-user' },+ };+ result.current.backfillUsage([], regenerated);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBe('local-user_');+ result.current.attributePending('local-user_', regenerated);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBeNull();+ });++ it('binds a waiting response without usage and remaps its live context on an authoritative ID', () => {+ const convo = 'waiting-response-id';+ const store = getDefaultStore();+ const { result } = renderHook(() => useUsageHandler());+ const submission = {+ conversation: { conversationId: convo },+ userMessage: { messageId: 'user-id', conversationId: convo },+ initialResponse: { messageId: 'optimistic-id', parentMessageId: 'user-id' },+ };+ result.current.bindResponse(submission);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBe('optimistic-id');+ expect(store.get(pendingUsageFamily(convo)).eventCount).toBe(0);+ result.current.contextHandler(inflatedSnapshot(), submission);+ result.current.usageHandler(primaryUsage(), submission);+ const pending = store.get(pendingUsageFamily(convo));+ const authoritative = {+ ...submission,+ initialResponse: { messageId: 'server-id', parentMessageId: 'user-id' },+ };+ result.current.bindResponse(authoritative);+ expect(store.get(contextSnapshotFamily(convo))?.responseMessageId).toBe('server-id');+ expect(store.get(pendingUsageFamily(convo))).toBe(pending);+ result.current.tapContent('some text', authoritative);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBe('server-id');+ result.current.resetLive(authoritative);+ expect(store.get(activeUsageResponseIdFamily(convo))).toBeNull();+ });+it('reconciles the live snapshot to the primary call’s actual prompt tokens', () => {const convo = 'convo-recon-1';const submission = {diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.tsindex 67dc162c26..c57993b930 100644--- a/client/src/hooks/SSE/useResumableSSE.ts+++ b/client/src/hooks/SSE/useResumableSSE.ts@@ -1350,6 +1350,7 @@ export default function useResumableSSE(enabled: !!isAuthenticated && startupConfig?.balance?.enabled,});const {+ bindResponse,contextHandler,usageHandler,tapStream,@@ -1463,6 +1464,7 @@ export default function useResumableSSE(editPrefixClearedRef.current = false;editPrefixFirstPartFoldedRef.current = false;}+ bindResponse(currentSubmission);let { userMessage } = currentSubmission;let textIndex: number | null = null;let finalReceived = false;@@ -2206,6 +2208,7 @@ export default function useResumableSSE(initialResponse: createdInitialResponse,};submissionRef.current = currentSubmission;+ bindResponse(currentSubmission);createdHandler(data, currentSubmission as EventSubmission);replayPreCreatedStepEvents();return;@@ -2617,8 +2620,11 @@ export default function useResumableSSE(};/** Legacy non-agent streams send cumulative text here — feed the* live estimate like the content path above */- tapContent(text, { ...currentSubmission, userMessage });- messageHandler(text, { ...currentSubmission, userMessage, initialResponse });+ const textSubmission = { ...currentSubmission, userMessage, initialResponse };+ currentSubmission = textSubmission;+ submissionRef.current = textSubmission;+ tapContent(text, textSubmission);+ messageHandler(text, textSubmission);}} catch (error) {logger.error('ResumableSSE', 'Error processing message:', error);@@ -3931,6 +3937,7 @@ export default function useResumableSSE(balanceQuery,removeActiveJob,queryClient,+ bindResponse,contextHandler,usageHandler,tapStream,@@ -4251,6 +4258,7 @@ export default function useResumableSSE(return;}+ bindResponse(submission);setIsSubmitting(true);/** Starting a new generation is the one interval where `isSubmitting`* is true but no generation epoch exists yet. Clear any prior epoch anddiff --git a/client/src/hooks/SSE/useSSE.ts b/client/src/hooks/SSE/useSSE.tsindex cd2447e6fa..ca3eeb0f2a 100644--- a/client/src/hooks/SSE/useSSE.ts+++ b/client/src/hooks/SSE/useSSE.ts@@ -21,9 +21,9 @@ import type {import type { EventHandlerParams } from './useEventHandlers';import type { TResData } from '~/common';import { clearComposerDrafts, applyPendingAction, findPendingActionMessageIndex } from '~/utils';+import { startedAsNewConversation, buildCreatedInitialResponse } from './useEventHandlers';import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';-import { startedAsNewConversation } from './useEventHandlers';import { useAuthContext } from '~/hooks/AuthContext';import useEventHandlers from './useEventHandlers';import useUsageHandler from './useUsageHandler';@@ -82,6 +82,7 @@ export default function useSSE(enabled: !!isAuthenticated && startupConfig?.balance?.enabled,});const {+ bindResponse,contextHandler,usageHandler,tapStream,@@ -96,7 +97,21 @@ export default function useSSE(return;}- let { userMessage } = submission;+ let currentSubmission = submission as EventSubmission;+ /** Provider identity updates cross one boundary. Message rendering, usage,+ * content, and terminal handlers all consume the same resolved response. */+ const adoptResponse = (userMessage: Partial<TMessage>, responseMessage: Partial<TMessage>) => {+ currentSubmission = {+ ...currentSubmission,+ userMessage: {+ ...currentSubmission.userMessage,+ ...userMessage,+ overrideParentMessageId: currentSubmission.userMessage.overrideParentMessageId,+ },+ initialResponse: { ...currentSubmission.initialResponse, ...responseMessage },+ };+ bindResponse(currentSubmission);+ };const payloadData = createPayload(submission);let { payload } = payloadData;@@ -104,6 +119,7 @@ export default function useSSE(let textIndex = null;clearStepMaps();+ bindResponse(currentSubmission);const sse = new SSE(payloadData.server, {payload: JSON.stringify(payload),@@ -113,7 +129,7 @@ export default function useSSE(sse.addEventListener('attachment', (e: MessageEvent) => {try {const data = JSON.parse(e.data);- attachmentHandler({ data, submission: submission as EventSubmission });+ attachmentHandler({ data, submission: currentSubmission });} catch (error) {console.error(error);}@@ -130,8 +146,8 @@ export default function useSSE(includeNewChatDraft: startedAsNewConversation(submission),});try {- finalHandler(data, submission as EventSubmission);- finalizeUsage(data, { ...submission, userMessage });+ finalHandler(data, currentSubmission);+ finalizeUsage(data, currentSubmission);} catch (error) {console.error('Error in finalHandler:', error);setIsSubmitting(false);@@ -143,19 +159,21 @@ export default function useSSE(} else if (data.created != null) {const runId = v4();setActiveRunId(runId);- userMessage = {- ...userMessage,- ...data.message,- overrideParentMessageId: userMessage.overrideParentMessageId,- };-- createdHandler(data, { ...submission, userMessage } as EventSubmission);+ const userMessage = { ...currentSubmission.userMessage, ...data.message };+ adoptResponse(+ userMessage,+ buildCreatedInitialResponse({+ ...currentSubmission,+ userMessage,+ }),+ );+ createdHandler(data, currentSubmission);} else if (data.event === 'title') {titleHandler(data);} else if (data.event === UsageEvents.ON_CONTEXT_USAGE) {- contextHandler(data.data, { ...submission, userMessage });+ contextHandler(data.data, currentSubmission);} else if (data.event === UsageEvents.ON_TOKEN_USAGE) {- usageHandler(data.data, { ...submission, userMessage });+ usageHandler(data.data, currentSubmission);} else if (data.event === ApprovalEvents.ON_PENDING_ACTION) {/** The pause card must attach to the same message state the stream* produced — apply any queued delta before reading the cache. */@@ -181,37 +199,32 @@ export default function useSSE(data.event === StepEvents.ON_MESSAGE_DELTA ||data.event === StepEvents.ON_REASONING_DELTA) {- tapStream(data.data, { ...submission, userMessage });+ tapStream(data.data, currentSubmission);}- stepHandler(data, { ...submission, userMessage } as EventSubmission);+ stepHandler(data, currentSubmission);} else if (data.sync != null) {const runId = v4();setActiveRunId(runId);/* synchronize messages to Assistants API as well as with real DB ID's */- syncHandler(data, { ...submission, userMessage } as EventSubmission);+ adoptResponse(data.requestMessage, data.responseMessage);+ syncHandler(data, currentSubmission);} else if (data.type != null) {const { text, index } = data;if (text != null && index !== textIndex) {textIndex = index;}- tapContent(text, { ...submission, userMessage });- contentHandler({ data, submission: submission as EventSubmission });- } else {+ tapContent(text, currentSubmission);+ contentHandler({ data, submission: currentSubmission });+ } else if (data.message != null) {const text = data.text ?? data.response;- const initialResponse = {- ...(submission.initialResponse as TMessage),- parentMessageId: data.parentMessageId,- messageId: data.messageId,- };+ adoptResponse({}, { parentMessageId: data.parentMessageId, messageId: data.messageId });- if (data.message != null) {- /** Legacy non-agent streams (handleText) send cumulative text here,- * not via the content path — feed it to the live estimate too */- tapContent(text, { ...submission, userMessage });- messageHandler(text, { ...submission, userMessage, initialResponse });- }+ /** Legacy non-agent streams (handleText) send cumulative text here,+ * not via the content path — feed it to the live estimate too */+ tapContent(text, currentSubmission);+ messageHandler(text, currentSubmission);}});@@ -243,14 +256,14 @@ export default function useSSE(const tail = latestMessages?.[latestMessages.length - 1];const partialResponseId =tail != null && tail.isCreatedByUser === false ? tail.messageId : null;- attributePending(partialResponseId, { ...submission, userMessage });+ attributePending(partialResponseId, currentSubmission);try {await abortConversation(conversationId ??- userMessage.conversationId ??+ currentSubmission.userMessage.conversationId ??submission.conversation?.conversationId ??'',- submission as EventSubmission,+ currentSubmission,latestMessages,);} catch (error) {@@ -286,7 +299,7 @@ export default function useSSE(console.log('error in server stream.');(startupConfig?.balance?.enabled ?? false) && balanceQuery.refetch();- resetLive({ ...submission, userMessage });+ resetLive(currentSubmission);let data: TResData | undefined = undefined;try {@@ -300,7 +313,10 @@ export default function useSSE(/** FLUSH (not cancel): the error card is built from the cache tail, so* the last queued tokens must land before it is synthesized. */flushPendingDeltas();- errorHandler({ data, submission: { ...submission, userMessage } as EventSubmission });+ errorHandler({+ data,+ submission: currentSubmission,+ });});setIsSubmitting(true);diff --git a/client/src/hooks/SSE/useUsageHandler.ts b/client/src/hooks/SSE/useUsageHandler.tsindex ee54a940ec..6b5f47943a 100644--- a/client/src/hooks/SSE/useUsageHandler.ts+++ b/client/src/hooks/SSE/useUsageHandler.ts@@ -19,6 +19,7 @@ import {clearUsageFolded,calibrationFamily,pendingUsageFamily,+ activeUsageResponseIdFamily,branchTotalsFamily,subagentUsageFamily,pendingSubagentUsageFamily,@@ -42,6 +43,7 @@ const FLUSH_INTERVAL_MS = 250;interface UsageSubmissionLike {userMessage?: Pick<TMessage, 'messageId' | 'conversationId'> | null;+ initialResponse?: Pick<TMessage, 'messageId' | 'parentMessageId'> | null;conversation?: Partial<Pick<TConversation, 'conversationId' | 'endpoint' | 'model'>> | null;}@@ -52,6 +54,8 @@ interface FinalDataLike {}export interface UsageHandlers {+ /** Bind an optimistic, created, or resumed response without inventing usage. */+ bindResponse: (submission: UsageSubmissionLike) => string | null;contextHandler: (data: TContextUsageEvent, submission: UsageSubmissionLike) => void;usageHandler: (data: TTokenUsageEvent, submission: UsageSubmissionLike) => void;tapStream: (data: { delta?: { content?: unknown } }, submission: UsageSubmissionLike) => void;@@ -122,20 +126,85 @@ export default function useUsageHandler(): UsageHandlers {return useMemo<UsageHandlers>(() => {const jotai = getDefaultStore();+ let liveConversationKey: string | null = null;+ /** Some terminal callbacks retain the original unsaved submission after+ * CREATED has already moved its state. Never move an empty `new` bucket+ * back over the live conversation in those callbacks. */+ const resolveUsageKey = (submission: UsageSubmissionLike) => {+ const key = getConvoKey(submission);+ return key === Constants.NEW_CONVO && liveConversationKey != null ? liveConversationKey : key;+ };+ const moveConversation = (from: string, to: string) => {+ if (from === to) {+ return;+ }+ migrateIndex(from, to);+ migrateUsageFolded(from, to);+ jotai.set(contextSnapshotFamily(to), jotai.get(contextSnapshotFamily(from)));+ jotai.set(snapshotsByAnchorFamily(to), jotai.get(snapshotsByAnchorFamily(from)));+ jotai.set(pendingUsageFamily(to), jotai.get(pendingUsageFamily(from)));+ jotai.set(activeUsageResponseIdFamily(to), jotai.get(activeUsageResponseIdFamily(from)));+ jotai.set(liveTokensFamily(to), jotai.get(liveTokensFamily(from)));+ jotai.set(branchTotalsFamily(to), jotai.get(branchTotalsFamily(from)));+ jotai.set(totalUsageFamily(to), sumTotalUsage(to));+ jotai.set(calibrationFamily(to), jotai.get(calibrationFamily(from)));+ jotai.set(subagentUsageFamily(to), jotai.get(subagentUsageFamily(from)));+ jotai.set(pendingSubagentUsageFamily(to), jotai.get(pendingSubagentUsageFamily(from)));+ // Atom-family eviction alone does not notify a still-mounted /c/new view.+ jotai.set(activeUsageResponseIdFamily(from), null);+ jotai.set(pendingUsageFamily(from), EMPTY_USAGE_TOTALS);+ jotai.set(liveTokensFamily(from), 0);+ removeUsageAtoms(from);+ liveConversationKey = to;+ };++ /** The transport owns response-id normalization. Use the same response it+ * renders, including durable IDs assigned by legacy text and resume events. */+ const bindResponse: UsageHandlers['bindResponse'] = (submission) => {+ const convoKey = getConvoKey(submission);+ if (liveConversationKey === Constants.NEW_CONVO && convoKey !== liveConversationKey) {+ moveConversation(liveConversationKey, convoKey);+ }+ liveConversationKey = convoKey;+ const responseId = submission.initialResponse?.messageId ?? null;+ const ownerAtom = activeUsageResponseIdFamily(convoKey);+ const previousId = jotai.get(ownerAtom);+ jotai.set(ownerAtom, responseId);+ /** A server ID remap doesn't invalidate this turn's pending usage or its+ * live context. Only move a snapshot owned by the previous response. */+ const snapshotAtom = contextSnapshotFamily(convoKey);+ const snapshot = jotai.get(snapshotAtom);+ if (+ previousId != null &&+ responseId != null &&+ previousId !== responseId &&+ snapshot?.responseMessageId === previousId+ ) {+ jotai.set(snapshotAtom, { ...snapshot, responseMessageId: responseId });+ }+ return responseId;+ };+const setLive = (convoKey: string, value: number) => {jotai.set(liveTokensFamily(convoKey), value);};- /** Flush the in-flight pending usage into a response's index entry, then- * reset pending. Only flushes when events were actually folded this session- * (eventCount > 0), so a finalize that carries persisted `metadata.usage`- * but folded nothing — a late/second resumable subscriber — keeps the entry- * loaded by `upsertEntries` instead of overwriting it with an empty record. */- const flushPendingInto = (convoKey: string, responseId: string | null) => {+ /** Settle observed usage and clear live state. Pending supplies a response+ * rollup only when the server supplied none (legacy FINAL or local stop).+ * Session-only subagent usage still settles once, independently of which+ * source supplied the whole-turn rollup. */+ const flushPendingInto = (+ convoKey: string,+ responseId: string | null,+ hasPersistedUsage = false,+ ) => {const pendingAtom = pendingUsageFamily(convoKey);const pending = jotai.get(pendingAtom);const keep = responseId != null && pending.eventCount > 0;- if (keep) {+ /** FINAL's persisted rollup covers the whole run; this subscriber may+ * have observed only the last calls. Pending is a legacy/stop fallback,+ * never a replacement for the response just upserted from the server. */+ if (keep && !hasPersistedUsage) {setEntryUsage(convoKey, responseId, {input: pending.input,output: pending.output,@@ -156,14 +225,17 @@ export default function useUsageHandler(): UsageHandlers {}jotai.set(pendingSubAtom, EMPTY_USAGE);jotai.set(pendingAtom, EMPTY_USAGE_TOTALS);+ jotai.set(activeUsageResponseIdFamily(convoKey), null);};const contextHandler: UsageHandlers['contextHandler'] = (data, submission) => {- const convoKey = getConvoKey(submission);+ const responseMessageId = bindResponse(submission);+ const convoKey = resolveUsageKey(submission);jotai.set(contextSnapshotFamily(convoKey), {...data,completedOutputTokens: data.resumedOutputTokens ?? data.completedOutputTokens,anchorMessageId: submission.userMessage?.messageId ?? null,+ responseMessageId,});if (data.calibrationRatio != null && data.calibrationRatio > 0) {jotai.set(calibrationFamily(convoKey), data.calibrationRatio);@@ -191,7 +263,8 @@ export default function useUsageHandler(): UsageHandlers {* `finalizeUsage` flushes the accumulated pending into the per-message index* and resets it, so branch/total stay index-derived (no double count). */const foldUsage = (data: TTokenUsageEvent, submission: UsageSubmissionLike): boolean => {- const convoKey = getConvoKey(submission);+ bindResponse(submission);+ const convoKey = resolveUsageKey(submission);/** runId+seq is unique per model call; fall back to the payload when a* source predates the sequence tag */const usageKey =@@ -248,7 +321,7 @@ export default function useUsageHandler(): UsageHandlers {* search). Resume is handled server-side (the job-store snapshot is reconciled* when the call's usage is persisted), so no backfill reconcile is needed. */const reconcileLiveSnapshot = (data: TTokenUsageEvent, submission: UsageSubmissionLike) => {- const convoKey = getConvoKey(submission);+ const convoKey = resolveUsageKey(submission);const snapshotAtom = contextSnapshotFamily(convoKey);const snapshot = jotai.get(snapshotAtom);if (snapshot == null) {@@ -284,10 +357,11 @@ export default function useUsageHandler(): UsageHandlers {* snapshot gauge keeps the full response for under-reporting providers */confirmedRef.current += normalizeUsageUnits(data).output;streamCharsRef.current = 0;- setLive(getConvoKey(submission), confirmedRef.current);+ setLive(resolveUsageKey(submission), confirmedRef.current);};const tapStream: UsageHandlers['tapStream'] = (data, submission) => {+ bindResponse(submission);const chars = countDeltaChars(data?.delta?.content);if (chars <= 0) {return;@@ -298,12 +372,13 @@ export default function useUsageHandler(): UsageHandlers {return;}lastFlushRef.current = now;- const convoKey = getConvoKey(submission);+ const convoKey = resolveUsageKey(submission);const ratio = jotai.get(calibrationFamily(convoKey));setLive(convoKey, confirmedRef.current + estimateTokens(streamCharsRef.current, ratio));};const tapContent: UsageHandlers['tapContent'] = (text, submission) => {+ bindResponse(submission);const value = extractContentText(text);if (value.length === 0) {return;@@ -315,7 +390,7 @@ export default function useUsageHandler(): UsageHandlers {return;}lastFlushRef.current = now;- const convoKey = getConvoKey(submission);+ const convoKey = resolveUsageKey(submission);const ratio = jotai.get(calibrationFamily(convoKey));setLive(convoKey, confirmedRef.current + estimateTokens(streamCharsRef.current, ratio));};@@ -323,7 +398,7 @@ export default function useUsageHandler(): UsageHandlers {const resetLive: UsageHandlers['resetLive'] = (submission) => {streamCharsRef.current = 0;confirmedRef.current = 0;- const convoKey = getConvoKey(submission);+ const convoKey = resolveUsageKey(submission);setLive(convoKey, 0);/** Terminal path with no salvageable response (stream error / intentional* close): discard the in-flight pending usage — and the subagent share@@ -334,12 +409,59 @@ export default function useUsageHandler(): UsageHandlers {* them as already folded and the response's usage stays missing until a* full reload. */jotai.set(pendingUsageFamily(convoKey), EMPTY_USAGE_TOTALS);+ jotai.set(activeUsageResponseIdFamily(convoKey), null);jotai.set(pendingSubagentUsageFamily(convoKey), EMPTY_USAGE);clearUsageFolded(convoKey);};+ /** Both local stop and FINAL retain the same branch-owned context. Capture+ * output from refs before resetting live state, including throttled text.+ * Never promote a snapshot from a different response sharing the user. */+ const retainSnapshot = (+ convoKey: string,+ responseId: string | null,+ userMsgId: string | null,+ output: number,+ retainedToolTokens?: number,+ ) => {+ if (responseId == null) {+ return;+ }+ const snapshotAtom = contextSnapshotFamily(convoKey);+ const snapshot = jotai.get(snapshotAtom);+ if (+ snapshot == null ||+ (snapshot.responseMessageId != null+ ? snapshot.responseMessageId !== responseId+ : snapshot.anchorMessageId !== userMsgId)+ ) {+ return;+ }+ const retained: ContextSnapshot = {+ ...snapshot,+ anchorMessageId: responseId,+ responseMessageId: responseId,+ ...(output > 0 && { completedOutputTokens: output }),+ ...(retainedToolTokens != null &&+ Number.isFinite(retainedToolTokens) &&+ retainedToolTokens > 0 && { retainedToolTokens }),+ };+ jotai.set(snapshotAtom, retained);+ const historyAtom = snapshotsByAnchorFamily(convoKey);+ const next = new Map(jotai.get(historyAtom));+ next.set(responseId, retained);+ jotai.set(historyAtom, next);+ };+const attributePending: UsageHandlers['attributePending'] = (responseId, submission) => {- const convoKey = getConvoKey(submission);+ const convoKey = resolveUsageKey(submission);+ retainSnapshot(+ convoKey,+ responseId,+ submission.userMessage?.messageId ?? null,+ confirmedRef.current ++ estimateTokens(streamCharsRef.current, jotai.get(calibrationFamily(convoKey))),+ );/** Flush the billed-but-uncommitted usage onto the stopped partial reply* (when its id is known and events were folded), then reset pending and* the live estimate. Index-derived branch/total then reflect it. */@@ -354,6 +476,7 @@ export default function useUsageHandler(): UsageHandlers {};const backfillUsage: UsageHandlers['backfillUsage'] = (entries, submission) => {+ bindResponse(submission);/** Fold the resumed run's persisted events idempotently — never reset* the conversation totals, or a reconnect mid-stream would drop the* usage of prompts already completed earlier in the session */@@ -363,7 +486,8 @@ export default function useUsageHandler(): UsageHandlers {};const seedLive: UsageHandlers['seedLive'] = (chars, submission) => {- const convoKey = getConvoKey(submission);+ bindResponse(submission);+ const convoKey = resolveUsageKey(submission);/** A completed resumed call already carries exact output in its snapshot.* Trailing text is the same output, not a new streaming delta. */if (chars <= 0 || jotai.get(contextSnapshotFamily(convoKey))?.completedOutputTokens != null) {@@ -375,7 +499,7 @@ export default function useUsageHandler(): UsageHandlers {};const finalizeUsage: UsageHandlers['finalizeUsage'] = (data, submission) => {- const fromKey = getConvoKey(submission);+ const fromKey = resolveUsageKey(submission);const realId = data.conversation?.conversationId ?? fromKey;/** From the refs, not the atom — the throttle may not have flushed */const liveAtFinalize =@@ -384,20 +508,7 @@ export default function useUsageHandler(): UsageHandlers {upsertEntries(fromKey, [data.requestMessage, data.responseMessage]);- if (realId !== fromKey) {- migrateIndex(fromKey, realId);- migrateUsageFolded(fromKey, realId);- jotai.set(contextSnapshotFamily(realId), jotai.get(contextSnapshotFamily(fromKey)));- jotai.set(snapshotsByAnchorFamily(realId), jotai.get(snapshotsByAnchorFamily(fromKey)));- jotai.set(pendingUsageFamily(realId), jotai.get(pendingUsageFamily(fromKey)));- jotai.set(calibrationFamily(realId), jotai.get(calibrationFamily(fromKey)));- jotai.set(subagentUsageFamily(realId), jotai.get(subagentUsageFamily(fromKey)));- jotai.set(- pendingSubagentUsageFamily(realId),- jotai.get(pendingSubagentUsageFamily(fromKey)),- );- removeUsageAtoms(fromKey);- }+ moveConversation(fromKey, realId);const responseMeta = data.responseMessage?.contextMeta;if (responseMeta?.calibrationRatio != null && responseMeta.calibrationRatio > 0) {@@ -411,7 +522,7 @@ export default function useUsageHandler(): UsageHandlers {* reset pending. Branch/total are summed from the index, so this single* add is counted exactly once; the persisted `metadata.usage` reproduces* it on reload. */- flushPendingInto(realId, responseId);+ flushPendingInto(realId, responseId, data.responseMessage?.metadata?.usage != null);const tailId = responseId ?? data.requestMessage?.messageId ?? null;if (tailId) {@@ -419,38 +530,14 @@ export default function useUsageHandler(): UsageHandlers {}jotai.set(totalUsageFamily(realId), sumTotalUsage(realId));- const snapshotAtom = contextSnapshotFamily(realId);- const snapshot = jotai.get(snapshotAtom);- /** Re-anchor the snapshot from the user message — shared by both branches- * when a response is regenerated — to the branch-unique response message,- * so switching to a sibling branch falls back to that branch's own- * totals instead of showing this generation's snapshot. Also carry the- * output streamed since the pre-invoke snapshot, kept after live resets.- * The finalized response metadata is the authoritative source for retained- * tool results, which the live snapshot must keep after its re-anchor. */- if (snapshot != null && snapshot.anchorMessageId === userMsgId) {- const retainedToolTokens = (- data.responseMessage?.metadata?.contextUsage as TContextUsageEvent | undefined- )?.retainedToolTokens;- const finalized: ContextSnapshot = {- ...snapshot,- anchorMessageId: responseId ?? snapshot.anchorMessageId,- ...(liveAtFinalize > 0 && { completedOutputTokens: liveAtFinalize }),- ...(retainedToolTokens != null &&- Number.isFinite(retainedToolTokens) &&- retainedToolTokens > 0 && { retainedToolTokens }),- };- jotai.set(snapshotAtom, finalized);- /** Retain this generation's breakdown keyed by the branch-unique- * response id so a later run on a sibling branch (which overwrites the- * live snapshot) doesn't strip this branch's granular rows. */- if (responseId != null) {- const historyAtom = snapshotsByAnchorFamily(realId);- const next = new Map(jotai.get(historyAtom));- next.set(responseId, finalized);- jotai.set(historyAtom, next);- }- }+ retainSnapshot(+ realId,+ responseId,+ userMsgId,+ liveAtFinalize,+ (data.responseMessage?.metadata?.contextUsage as TContextUsageEvent | undefined)+ ?.retainedToolTokens,+ );streamCharsRef.current = 0;confirmedRef.current = 0;@@ -458,6 +545,7 @@ export default function useUsageHandler(): UsageHandlers {};return {+ bindResponse,contextHandler,usageHandler,tapStream,diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 59d97a3fd4..2285ff5fea 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1313,12 +1313,21 @@"com_ui_context_compacting": "Compacting context...","com_ui_context_cost": "Cost","com_ui_context_cost_branch": "Cost (this branch)",+ "com_ui_context_cost_current_turn": "Cost (current turn so far)",+ "com_ui_context_cost_last_turn": "Cost (last turn)","com_ui_context_cost_total": "All branches","com_ui_context_estimated": "Estimated","com_ui_context_filter_sort": "Filter and Sort by Context","com_ui_context_free": "Free space","com_ui_context_cached": "Cached",+ "com_ui_context_cache_last_call": "Cached input in the context snapshot","com_ui_context_cache_write": "Cache write",+ "com_ui_context_current_turn": "Current turn (so far)",+ "com_ui_context_last_turn": "Last turn",+ "com_ui_context_this_branch": "This branch",+ "com_ui_context_uncached_input": "Input (uncached)",+ "com_ui_context_waiting_usage": "Waiting for model usage...",+ "com_ui_context_unavailable_usage": "Usage not available for this turn","com_ui_context_dynamic_instructions": "Agent instructions","com_ui_context_pressure_warn": "Context window is filling up","com_ui_context_pressure_danger": "Context window is almost full",diff --git a/client/src/store/usage.ts b/client/src/store/usage.tsindex 157c9cb82a..37b996cd95 100644--- a/client/src/store/usage.ts+++ b/client/src/store/usage.ts@@ -15,6 +15,8 @@ export const contextBreakdownExpandedAtom = createStorageAtom<boolean>(/** Latest backend context snapshot, anchored to the run's user message for staleness checks */export interface ContextSnapshot extends TContextUsageEvent {anchorMessageId: string | null;+ /** Response owning a live snapshot; user-message anchors are shared by siblings. */+ responseMessageId?: string | null;/** Output tokens finalized after this pre-call snapshot (the last call's response) */completedOutputTokens?: number;}@@ -73,6 +75,11 @@ export const snapshotsByAnchorFamily = atomFamily((_conversationId: string) =>atom<Map<string, ContextSnapshot>>(new Map()),);+/** Response owning live usage, independent of the selected branch. */+export const activeUsageResponseIdFamily = atomFamily((_conversationId: string) =>+ atom<string | null>(null),+);+/** In-flight usage of the streaming response; flushed into the index at finalize. */export const pendingUsageFamily = atomFamily((_conversationId: string) =>atom<UsageTotals>(EMPTY_USAGE_TOTALS),@@ -202,6 +209,7 @@ export function removeUsageAtoms(conversationId: string): void {contextSnapshotFamily.remove(conversationId);snapshotsByAnchorFamily.remove(conversationId);pendingUsageFamily.remove(conversationId);+ activeUsageResponseIdFamily.remove(conversationId);totalUsageFamily.remove(conversationId);liveTokensFamily.remove(conversationId);subagentUsageFamily.remove(conversationId);diff --git a/client/src/utils/tokens.spec.ts b/client/src/utils/tokens.spec.tsindex ddac55b635..3b281b5cc4 100644--- a/client/src/utils/tokens.spec.ts+++ b/client/src/utils/tokens.spec.ts@@ -844,6 +844,47 @@ describe('per-message usage index (branch + total)', () => {expect(sumTotalUsage(CONVO)).toEqual(EMPTY_USAGE);});+ it('selects only the viewed response as the last turn across compaction and regeneration', () => {+ buildIndex(CONVO, [+ msg('u1', Constants.NO_PARENT, true, 10),+ responseMsg('a1', 'u1', 50, USAGE_A),+ msg('u2', 'a1', true, 20),+ {+ ...responseMsg('a2', 'u2', 80, { ...USAGE_B, cacheRead: 400, cacheWrite: 30 }),+ metadata: {+ usage: { ...USAGE_B, cacheRead: 400, cacheWrite: 30 },+ summaryUsedTokens: 500,+ },+ },+ responseMsg('a2-alt', 'u2', 60, { ...USAGE_A, cost: 0 }),+ ]);++ expect(sumBranch(CONVO, 'a2').lastTurnUsage).toEqual({+ input: 200,+ output: 80,+ cacheRead: 400,+ cacheWrite: 30,+ cost: 0.02,+ costKnown: true,+ });+ expect(sumBranch(CONVO, 'a2').usage.input).toBe(300);+ expect(sumBranch(CONVO, 'a2-alt').lastTurnUsage?.cost).toBe(0);+ expect(sumBranch(CONVO, 'u2').lastTurnUsage).toBeUndefined();+ expect(sumTotalUsage(CONVO).cacheRead).toBe(400);+ });++ it('does not borrow an ancestor response when the selected tail has no usage', () => {+ buildIndex(CONVO, [+ msg('u1', Constants.NO_PARENT, true, 10),+ responseMsg('a1', 'u1', 50, USAGE_A),+ msg('u2', 'a1', true, 10),+ msg('a2', 'u2', false, 20),+ ]);+ expect(sumBranch(CONVO, 'a2').lastTurnUsage).toBeUndefined();+ expect(sumBranch(CONVO, 'a2').usage.cost).toBe(0.01);+ expect(sumBranch(CONVO, 'u2').lastTurnUsage).toBeUndefined();+ });+it('preserves a prior entry usage when a rebuilt message lacks metadata.usage', () => {/** Live finalize flushes usage into the index before persisted metadata* reaches the cache; a mid-session rebuild from a cache message without@@ -861,6 +902,7 @@ describe('per-message usage index (branch + total)', () => {buildIndex(CONVO, [msg('u1', Constants.NO_PARENT, true, 10), msg('a1', 'u1', false, 50)]);expect(sumBranch(CONVO, 'a1').usage.cost).toBeCloseTo(0.01);expect(sumBranch(CONVO, 'a1').usage.input).toBe(100);+ expect(sumBranch(CONVO, 'a1').lastTurnUsage?.cost).toBeCloseTo(0.01);});it('restores branch cost from sticky history after regenerate drops then re-adds a sibling', () => {diff --git a/client/src/utils/tokens.ts b/client/src/utils/tokens.tsindex e3fc8d50a3..d342fcfeab 100644--- a/client/src/utils/tokens.ts+++ b/client/src/utils/tokens.ts@@ -94,6 +94,8 @@ export interface BranchTotals {containsAnchor: boolean;/** Provider usage/cost summed along the active branch */usage: BranchUsage;+ /** Recorded usage of the selected response, never an earlier ancestor's usage. */+ lastTurnUsage?: BranchUsage;/** Compacted-context baseline from the deepest summarized response on the* branch (0 if none). The branch walk stops there, so `input`/`output` cover* only the post-summary messages; the estimate adds this to avoid counting@@ -429,6 +431,7 @@ export function sumBranch(* message total holding tokens whose tool share had been removed, so both* tail figures are zero for a counted tail. */const tailEntry = index.get(tailId);+ const lastTurnUsage = tailEntry?.isCreatedByUser === false ? tailEntry.usage : undefined;const tailCounted = tailEntry != null && tailEntry.tokenCount > 0;const tailEstTokens = tailCounted ? 0 : (tailEntry?.estTokens ?? 0);const tailEstToolTokens = tailCounted@@ -485,7 +488,15 @@ export function sumBranch(currentId = entry.parentMessageId;}- return { ...totals, tailEstTokens, tailEstToolTokens, tailId, usage, summaryBaseline };+ return {+ ...totals,+ tailEstTokens,+ tailEstToolTokens,+ tailId,+ usage,+ lastTurnUsage,+ summaryBaseline,+ };}/**diff --git a/e2e/screenshots/token-usage/README.md b/e2e/screenshots/token-usage/README.mdnew file mode 100644index 0000000000..a0c8f8296a--- /dev/null+++ b/e2e/screenshots/token-usage/README.md@@ -0,0 +1,25 @@+# Token-usage panel evidence++Real app captures for PR #16230, taken on 2026-09-23 with Playwright against the+production-built client and the repository's disposable mock E2E app. MongoDB+was ephemeral; conversation data was seeded, not taken from a real user or API.++- Before client: `44703da3c62e5218caf1fb80511c038cd4c1ab85` (`dev` baseline).+- After client: `2d3e4974b70cb57049c95e33a48eb29988c23332`.+- Desktop viewport: 1440 × 1000, matching light/dark themes and seeded data.+- Panel captures: native 288px width, after the expand animation settled.+- Narrow viewport: 390 × 844, after scrolling the cost section into view.++The first response records input 305, output 109, cache read 7100, cache write+7200, cost $0.102. The selected response records input 140, output 86, cache read+14200, cache write 94, cost $0.014. This distinguishes the selected turn from+conversation totals. The snapshot budget is 128000 with 109566 remaining before+86 output tokens. No real provider request is needed for these captures.++Browser assertions checked usage values, theme, settled panel geometry, reload,+and Escape. The narrow-layout cost section remains reachable by scrolling.+These static images do not prove streaming timing or independent visual review.++The five PNGs are retained on the PR branch because GitHub's direct attachment+upload rejected the GitHub App authentication type. The PR description uses+commit-pinned image URLs. They are review evidence, not golden image-test files.diff --git a/e2e/screenshots/token-usage/after-dark.png b/e2e/screenshots/token-usage/after-dark.pngnew file mode 100644index 0000000000..bd19a12ecfBinary files /dev/null and b/e2e/screenshots/token-usage/after-dark.png differdiff --git a/e2e/screenshots/token-usage/after-light.png b/e2e/screenshots/token-usage/after-light.pngnew file mode 100644index 0000000000..cfddc7107dBinary files /dev/null and b/e2e/screenshots/token-usage/after-light.png differdiff --git a/e2e/screenshots/token-usage/after-mobile.png b/e2e/screenshots/token-usage/after-mobile.pngnew file mode 100644index 0000000000..6127dc4625Binary files /dev/null and b/e2e/screenshots/token-usage/after-mobile.png differdiff --git a/e2e/screenshots/token-usage/before-dark.png b/e2e/screenshots/token-usage/before-dark.pngnew file mode 100644index 0000000000..0a5ae5156aBinary files /dev/null and b/e2e/screenshots/token-usage/before-dark.png differdiff --git a/e2e/screenshots/token-usage/before-light.png b/e2e/screenshots/token-usage/before-light.pngnew file mode 100644index 0000000000..05ef4f9f17Binary files /dev/null and b/e2e/screenshots/token-usage/before-light.png differdiff --git a/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts b/e2e/specs/mock/scenarios/persisted-context-usage.spec.tsindex 9b81a5a9ca..73d7575b45 100644--- a/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts+++ b/e2e/specs/mock/scenarios/persisted-context-usage.spec.ts@@ -64,6 +64,93 @@ test.afterEach(async () => {});test.describe('persisted context usage', () => {+ test('separates the selected turn from cumulative cache totals after reload @scenario:last-turn-cache-vs-branch', async ({+ page,+ }) => {+ test.setTimeout(120000);+ const conversationId = randomUUID();+ cleanupConversationIds.push(conversationId);++ await insertConversation(conversationId, 'Latest-turn usage fixture', [+ {+ messageId: 'usage-user-1',+ parentMessageId: NO_PARENT,+ text: 'First request',+ isCreatedByUser: true,+ sender: 'User',+ tokenCount: 8,+ },+ {+ messageId: 'usage-assistant-1',+ parentMessageId: 'usage-user-1',+ text: 'First reply',+ isCreatedByUser: false,+ sender: 'Assistant',+ tokenCount: 5,+ metadata: { usage: { input: 30, output: 5, cacheRead: 100, cacheWrite: 0, cost: 0.01 } },+ },+ {+ messageId: 'usage-user-2',+ parentMessageId: 'usage-assistant-1',+ text: 'Second request',+ isCreatedByUser: true,+ sender: 'User',+ tokenCount: 8,+ },+ {+ messageId: 'usage-assistant-2',+ parentMessageId: 'usage-user-2',+ text: 'Second reply',+ isCreatedByUser: false,+ sender: 'Assistant',+ tokenCount: 5,+ metadata: {+ usage: { input: 20, output: 5, cacheRead: 400, cacheWrite: 50, cost: 0.02 },+ contextUsage: {+ runId: 'usage-run-2',+ contextBudget: 300,+ cacheRead: 400,+ cacheWrite: 50,+ breakdown: {+ maxContextTokens: 300,+ instructionTokens: 20,+ messageTokens: 80,+ toolCount: 0,+ messageCount: 4,+ },+ },+ },+ },+ ]);++ const assertUsage = async () => {+ await expect(page.getByTestId('token-usage')).toBeVisible({ timeout: 30000 });+ await page.getByTestId('token-usage').click();+ const popover = page.getByRole('region', { name: 'Context usage' });+ const toggle = popover.getByTestId('context-breakdown-toggle');+ if ((await toggle.getAttribute('aria-expanded')) === 'false') {+ await toggle.click();+ }+ const lastTurn = popover.getByTestId('token-usage-last-turn');+ const branch = popover.getByTestId('token-usage-totals');+ await expect(lastTurn.getByRole('heading', { name: 'Last turn' })).toBeVisible();+ await expect(lastTurn.getByText('Cache read').locator('../..')).toContainText('400');+ 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(popover.getByTestId('token-usage-all-branches')).toHaveCount(0);+ await page.keyboard.press('Escape');+ };++ await page.goto(`/c/${conversationId}`, { timeout: 30000 });+ await expect(page.getByText('Second reply')).toBeVisible({ timeout: 30000 });+ await assertUsage();+ await page.reload({ timeout: 30000 });+ await expect(page.getByText('Second reply')).toBeVisible({ timeout: 30000 });+ await assertUsage();+ });+/** A snapshot persisted before `remainingContextTokens` existed carries only a* budget and a breakdown. Reading the absent remaining count as zero scored* such a snapshot as having spent its whole window, so an old conversationdiff --git a/e2e/specs/mock/scenarios/subagent-context-total.spec.ts b/e2e/specs/mock/scenarios/subagent-context-total.spec.tsindex 1fab174ecc..578649385d 100644--- a/e2e/specs/mock/scenarios/subagent-context-total.spec.ts+++ b/e2e/specs/mock/scenarios/subagent-context-total.spec.ts@@ -97,7 +97,7 @@ test.describe('subagent context usage totals', () => {const totals = popover.getByTestId('token-usage-totals');await expect(totals).toBeVisible({ timeout: 10000 });await expect(totals.getByRole('heading', { name: 'Totals' })).toBeVisible();- await expect(totals.getByText('Input', { exact: true })).toBeVisible();+ await expect(totals.getByText('Input (uncached)', { exact: true })).toBeVisible();await expect(totals.getByText('Output', { exact: true })).toBeVisible();const subagentRow = totalsdiff --git a/e2e/specs/mock/usage.spec.ts b/e2e/specs/mock/usage.spec.tsindex e4b00881d4..0d42a3286e 100644--- a/e2e/specs/mock/usage.spec.ts+++ b/e2e/specs/mock/usage.spec.ts@@ -80,9 +80,12 @@ test.describe('context usage gauge', () => {* Input/Output rows when the lib predates on_context_usage */const popover = await openBreakdown(page);await expect(popover.getByText('Context window')).toBeVisible();+ const lastTurn = popover.getByTestId('token-usage-last-turn');+ await expect(lastTurn.getByRole('heading', { name: 'Last turn' })).toBeVisible();+ await expect(lastTurn.getByText('Input (uncached)')).toBeVisible();const usageSection = popover.getByTestId('token-usage-totals');await expect(usageSection).toBeVisible({ timeout: 10000 });- await expect(usageSection.getByText('Input', { exact: true })).toBeVisible();+ await expect(usageSection.getByText('Input (uncached)', { exact: true })).toBeVisible();await expect(usageSection.getByText('Output', { exact: true })).toBeVisible();/** Cost row: interface.contextCost is enabled in the harness yaml, the@@ -91,7 +94,7 @@ test.describe('context usage gauge', () => {* conversation shows only the branch cost, no all-branches total line. */const costSection = popover.getByTestId('token-usage-cost');await expect(costSection).toBeVisible();- await expect(costSection.getByText(/\$\d|<\$0\.01/)).toBeVisible();+ await expect(costSection.getByText(/\$\d|<\$0\.01/).first()).toBeVisible();await expect(costSection.getByText('All branches')).toHaveCount(0);await page.keyboard.press('Escape');@@ -103,9 +106,10 @@ test.describe('context usage gauge', () => {await expectGaugeAboveZero(page);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');await expect(reloadedCost).toBeVisible();- await expect(reloadedCost.getByText(/\$\d|<\$0\.01/)).toBeVisible();+ await expect(reloadedCost.getByText(/\$\d|<\$0\.01/).first()).toBeVisible();});test('renders the granular breakdown from the live context snapshot', async ({ page }) => {diff --git a/packages/api/src/agents/responses/clientTools.sdk.spec.ts b/packages/api/src/agents/responses/clientTools.sdk.spec.tsindex 7d54182503..ae58b677c7 100644--- a/packages/api/src/agents/responses/clientTools.sdk.spec.ts+++ b/packages/api/src/agents/responses/clientTools.sdk.spec.ts@@ -1,3 +1,4 @@+import { AIMessageChunk } from '@langchain/core/messages';import {ChatModelStreamHandler,HandlerRegistry,@@ -8,10 +9,9 @@ import {} from '@librechat/agents';import type { ToolExecuteBatchRequest } from '@librechat/agents';import type { Response as ServerResponse } from 'express';-import { AIMessageChunk } from '@langchain/core/messages';+import { createResponsesEventHandlers } from './service';import { createClientToolHandoff } from './clientTools';import { createResponseTracker } from './handlers';-import { createResponsesEventHandlers } from './service';jest.mock('@librechat/data-schemas', () => ({ logger: { warn: jest.fn() } }));jest.mock('../usage', () => ({ aggregateCollectedUsage: jest.fn() }));