Repository navigation
feat: show per-response token usage and estimated cost indicator - #796
will-lamerton merged 2 commits into
Conversation
There was a problem hiding this comment.
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
hasReportedUsagetreats0as a usable token count (becauseNumber.isFinite(0)is true). If a provider returns{totalTokens: 0}(or zeroes for all fields) to mean “usage unavailable”, this will produce aResponseUsageand can suppress the UI fallback estimate, regressing to showingTokens: 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.
| * 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. |
| 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); | ||
| } |
| 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; | ||
| }; |
| 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(); | ||
| } |
|
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 1. ACP zero-fills input/output, silently zeroing cost for lump-sum providers. Cost 2. The CLI now awaits a possibly-networked pricing lookup inside the streaming-to-static swap. The cold path is worse. With no cache or one older than 7 days, Smaller things, not blocking:
|
# Conflicts: # plugins/vscode/media/chat-panel.js # plugins/vscode/src/acp-client.ts # plugins/vscode/src/chat-webview-provider.ts
…t lookup per review
4664158 to
6a08cb3
Compare
|
@will-lamerton please review |
|
Looks good @lakshay-2411 :) Thanks for this PR - feel free to add yourself as a contributor to our website via a PR which I will approve :) https://nanocollective.org/contributors |
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:
~120 tokens) now shows the provider-reported usage plus estimated cost,e.g.
Tokens: 4.2k | ~$0.01.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.source/usage/format.ts(compact token/cost formatters) andsource/usage/response-usage.ts(usage + cost payload builder, with injectable pricing lookup for tests).VS Code extension:
PromptResponsevia the ACP SDK's experimentalusagefield, with the estimated cost in_meta['nanocoder/usage'].prompt_responsewebview update, and the chat panel renders the same subtle gray indicator under each finished response.assets/nanocoder-vscode.vsixaccordingly.Design decisions (from the approach discussed in #756 — happy to adjust):
Type of Change
Changeset
pnpm changeset) describing this change for the changelogTesting
Automated Tests
.spec.ts/tsxfilespnpm test:allcompletes successfully)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 thePromptResponse(and its absence when the provider reports none).Manual Testing
Checklist