Skip to content

feat: show per-response token usage and estimated cost indicator - #796

Merged
will-lamerton merged 2 commits into
Nano-Collective:mainfrom
lakshay-2411:feat/per-response-usage-indicator
Aug 11, 2026
Merged

will-lamerton merged 2 commits into
Nano-Collective:mainfrom
lakshay-2411:feat/per-response-usage-indicator

Conversation

@lakshay-2411

Copy link
Copy Markdown
Contributor

Description

This PR adds a per-response token usage and estimated cost indicator to both the CLI and the VS Code extension. Closes #756

When using paid APIs (OpenRouter, OpenAI, etc.), developers want immediate feedback on how many tokens each response consumed and roughly what it cost, so they can build an intuition for context size and know when to clear their session.

CLI:

  • The gray footer under each assistant message (previously a client-side estimate like ~120 tokens) now shows the provider-reported usage plus estimated cost,
    e.g. Tokens: 4.2k | ~$0.01.
  • Cost is computed from models.dev pricing via the existing getModelPricing() helper (cache-backed, best-effort). The cost segment is omitted for local/free models (e.g. Ollama), and sub-cent costs render as <$0.01.
  • When a provider reports no usage at all, the footer falls back to the previous client-side estimate — behavior never regresses.
  • New source/usage/format.ts (compact token/cost formatters) and source/usage/response-usage.ts (usage + cost payload builder, with injectable pricing lookup for tests).

VS Code extension:

  • The ACP conversation loop now accumulates provider-reported usage across all model calls in a turn and returns it on the PromptResponse via the ACP SDK's experimental usage field, with the estimated cost in _meta['nanocoder/usage'].
  • The extension forwards both through the existing prompt_response webview update, and the chat panel renders the same subtle gray indicator under each finished response.
  • Rebuilt assets/nanocoder-vscode.vsix accordingly.

Design decisions (from the approach discussed in #756 — happy to adjust):

  • CLI shows the indicator per API call (each rendered assistant message); the extension shows it per turn (ACP's usage field is turn-scoped).
  • Always-on, no config toggle — the footer already existed; this upgrades its accuracy.

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Changeset

  • Added a changeset (pnpm changeset) describing this change for the changelog

Testing

Automated Tests

  • New features include passing tests in .spec.ts/tsx files
  • All existing tests pass (pnpm test:all completes successfully)
  • Tests cover both success and error scenarios

New tests: source/usage/format.spec.ts (compact token/cost formatting, invalid inputs), source/usage/response-usage.spec.ts (cost computation, lump-sum totals, unavailable/failing pricing), component tests for the footer (real usage, no pricing, fallback to estimate), and two ACP tests verifying usage accumulation onto the PromptResponse (and its absence when the provider reports none).

Manual Testing

  • Tested with Ollama
  • Tested with OpenRouter
  • Tested with OpenAI-compatible API
  • Tested MCP integration (if applicable)

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No breaking changes (or clearly documented)
  • Appropriate logging added using structured logging (see CONTRIBUTING.md)

Copilot AI lite review requested due to automatic review settings August 5, 2026 10:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds first-class, provider-reported per-response/per-turn token usage with a best-effort USD cost estimate, surfaced in both the CLI assistant message footer and the VS Code extension chat panel (closing #756).

Changes:

  • Introduces new usage utilities to build a per-response usage payload (tokens + optional cost) and to format compact token/cost indicators.
  • Updates the CLI conversation loop + assistant message component to prefer provider-reported usage, falling back to the existing client-side estimate when unavailable.
  • Extends ACP prompt responses to accumulate usage across model calls in a turn and forwards that data through the VS Code extension into the webview for rendering.

Reviewed changes

Copilot reviewed 15 out of 16 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
source/usage/response-usage.ts Builds per-response usage payload and estimates cost via model pricing lookup.
source/usage/response-usage.spec.ts Tests for usage payload construction and cost estimation behavior.
source/usage/format.ts Compact formatting helpers for tokens/cost and indicator string building.
source/usage/format.spec.ts Tests for compact token formatting, cost formatting, and indicator output.
source/types/usage.ts Adds ResponseUsage type for per-response token/cost payloads.
source/types/components.ts Extends assistant message props to optionally carry ResponseUsage.
source/hooks/chat-handler/conversation/conversation-loop.tsx Attaches per-response usage payload to rendered assistant messages.
source/components/assistant-message.tsx Renders provider-reported usage indicator (or falls back to estimated tokens).
source/components/assistant-message.spec.tsx Adds component tests covering real usage, no pricing, and fallback behavior.
source/acp/acp-conversation.ts Accumulates per-turn usage across model calls and attaches usage/cost to ACP PromptResponse.
source/acp/acp-conversation.spec.ts Tests for usage accumulation onto PromptResponse and omission when none is reported.
plugins/vscode/src/chat-webview-provider.ts Forwards ACP usage + cost metadata to the webview on turn completion.
plugins/vscode/src/acp-client.ts Updates ACP client to return the PromptResponse payload from prompt().
plugins/vscode/media/chat-panel.js Renders compact token usage/cost indicator under finished responses in the webview.
.changeset/per-response-usage-indicator.md Changeset entry documenting the new usage/cost indicator feature.
Suppressed comments (1)

source/usage/response-usage.ts:30

  • hasReportedUsage treats 0 as a usable token count (because Number.isFinite(0) is true). If a provider returns {totalTokens: 0} (or zeroes for all fields) to mean “usage unavailable”, this will produce a ResponseUsage and can suppress the UI fallback estimate, regressing to showing Tokens: 0. Consider requiring a positive token count before considering usage “reported”.
	const hasReportedUsage =
		!!usage &&
		(Number.isFinite(usage.inputTokens) ||
			Number.isFinite(usage.outputTokens) ||
			Number.isFinite(usage.totalTokens));

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread source/usage/response-usage.ts Outdated
* best-effort cost estimate. Returns undefined when the provider reported
* no usable token counts (the indicator then falls back to the client-side
* estimate). Cost is omitted when pricing is unavailable (local models) or
* the lookup fails — never blocks or throws.
Comment thread source/usage/format.ts
Comment on lines +54 to +68
export function getTotalTokens(usage: ResponseUsage): number | null {
if (Number.isFinite(usage.totalTokens)) {
return usage.totalTokens as number;
}
const input = Number.isFinite(usage.inputTokens)
? (usage.inputTokens as number)
: null;
const output = Number.isFinite(usage.outputTokens)
? (usage.outputTokens as number)
: null;
if (input == null && output == null) {
return null;
}
return (input ?? 0) + (output ?? 0);
}
Comment on lines +63 to +79
const recordUsage = (usage: ApiUsage | undefined) => {
if (!usage) return;
const input = Number.isFinite(usage.inputTokens)
? (usage.inputTokens as number)
: 0;
const output = Number.isFinite(usage.outputTokens)
? (usage.outputTokens as number)
: 0;
const total = Number.isFinite(usage.totalTokens)
? (usage.totalTokens as number)
: input + output;
if (input === 0 && output === 0 && total === 0) return;
turnUsage.inputTokens += input;
turnUsage.outputTokens += output;
turnUsage.totalTokens += total;
usageReported = true;
};
Comment on lines +322 to +341
function appendUsageIndicator(usage, cost) {
if (!usage) return;
const total = Number.isFinite(usage.totalTokens)
? usage.totalTokens
: (Number.isFinite(usage.inputTokens) ? usage.inputTokens : 0) +
(Number.isFinite(usage.outputTokens) ? usage.outputTokens : 0);
if (!total) return;

let text = 'Tokens: ' + formatCompactTokens(total);
if (Number.isFinite(cost) && cost > 0) {
text += cost < 0.01 ? ' | <$0.01' : ' | ~$' + cost.toFixed(2);
}

endCurrentTextBlock();
const el = document.createElement('div');
el.className = 'self-start text-[0.8em] opacity-50 shrink-0 mb-1';
el.textContent = text;
messagesContainer.appendChild(el);
scrollToBottom();
}
@will-lamerton

Copy link
Copy Markdown
Member

Hey @lakshay-2411 - thanks for this, the feature is well-scoped and for the most part looking great! Requesting changes on two things, plus the merge conflicts.

Merge conflicts. The branch is currently conflicting with main in plugins/vscode/src/acp-client.ts and plugins/vscode/src/chat-webview-provider.ts. Could you rebase onto latest main and rebuild the vsix afterwards so the committed artifact matches the resolved source?

1. ACP zero-fills input/output, silently zeroing cost for lump-sum providers. recordUsage (source/acp/acp-conversation.ts:63) coerces missing inputTokens/outputTokens to 0 while still accumulating totalTokens. buildResponseUsage then sees both as finite and takes the input/output branch (source/usage/response-usage.ts:43) instead of the lump-sum averaging branch at line 50, so cost comes out 0. I verified against the real code:

turnUsage {inputTokens: 0, outputTokens: 0, totalTokens: 1_000_000} -> cost = 0
direct     {totalTokens: 1_000_000}                                 -> cost = 9

Cost 0 then fails the cost > 0 check in the webview, so any provider reporting only total_tokens gets no cost segment in the GUI with no signal that pricing was skipped. The same coercion undercounts when a provider reports input but not output. Suggest keeping the accumulators as number | undefined and only filling a field once a finite value arrives, so a total-only turn reaches buildResponseUsage as {totalTokens: n}. Worth a third ACP test with a total-only mock.

2. The CLI now awaits a possibly-networked pricing lookup inside the streaming-to-static swap. conversation-loop.tsx:496 awaits buildResponseUsage after setStreamingContent('') at line 460 has already wiped the live message off screen, but before addToChatQueue appends the static one. getModelPricing has no in-process memo: getModelsData does a disk read plus JSON.parse every call, and findModelById falling through to findModelByName does it twice. The models.dev payload is 3.46MB, ~13ms per read+parse, so roughly 26ms of blocking parse per assistant message on the warm path.

The cold path is worse. With no cache or one older than 7 days, fetchModelsData runs with a 10s headers timeout and its failure path reads the cache again. Offline, that's a blank screen where the reply used to be, up to ten seconds, on every response, including for Ollama users whose models aren't on models.dev anyway. Suggest memoizing the parsed database (and the negative lookup) at module level in models-dev-client.ts, which also speeds up /usage, and not blocking the queue push on cost.

Smaller things, not blocking:

  • Cost ignores cache-read/write tokens. ModelInfo['cost'] only carries input/output, so with prompt caching the estimate is materially over-stated, and this footer is far more visible than /usage. A note in the changeset would help.
  • Resumed sessions regress to the old estimate. session-history-renderer.tsx:186 and subagent-view.tsx:61,91 render AssistantMessage without usage, and usage isn't persisted, so /resume shows ~120 tokens where the live session showed Tokens: 4.2k | ~$0.01. Fine as a follow-up.
  • acp-conversation.ts:150 returns a bare {stopReason: 'end_turn'} while the other eight returns go through withTurnUsage. Harmless today since it precedes any model call, but it reads as an oversight.
  • Widening prompt() to Promise<unknown> forces the cast in chat-webview-provider.ts:230. Returning PromptResponse | undefined gets usage typed for free and drops the any.
  • source/usage/ isn't in the CLAUDE.md key-directories list.
  • The manual testing boxes are all unchecked. Given this touches the render path on every response, at least one Ollama run and one paid-API run would be reassuring, especially for item 2.

# Conflicts:
#	plugins/vscode/media/chat-panel.js
#	plugins/vscode/src/acp-client.ts
#	plugins/vscode/src/chat-webview-provider.ts
@lakshay-2411
lakshay-2411 force-pushed the feat/per-response-usage-indicator branch from 4664158 to 6a08cb3 Compare August 10, 2026 10:01
@lakshay-2411

Copy link
Copy Markdown
Contributor Author

@will-lamerton please review

@will-lamerton

Copy link
Copy Markdown
Member

@will-lamerton
will-lamerton merged commit af63efa into Nano-Collective:main Aug 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Token Usage & Cost Indicator per Response

3 participants