nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Bug] TUI leaves auto-compacted and malformed-retry model calls out of /usage and /stats

Open harpreetkbadhan opened this issue 1 week ago • 0 comments

Description

In the TUI, a model call that the provider billed is left out of the session's apiCallHistory (so /usage Cumulative Session) and out of the lifetime /stats ledger in two cases:

  • Auto-compaction. When maybeAutoCompact runs after a reply, onTurnRecorded gets compacted: true and the onApiCallComplete gate (!compacted &&) skips the record. That call is usually the largest one in the session, since it is what pushed the context over the limit.
  • Malformed tool-call retry. The turn engine continues to the retry before onTurnRecorded runs, so the failed attempt is never recorded.

The TUI emits onApiCallComplete from onTurnRecorded. The other frontends record each call in onModelResponse, which the engine calls for every model response: plain (plain/conversation.ts), ACP (acp-conversation.ts) and subagents (subagent-executor.ts). The engine's own header comment also puts "per-call bookkeeping: usage, stats" in onModelResponse.

Environment

  • OS: macOS
  • Node version: v22.23.4
  • Nanocoder version: 1.32.0 (main at 2f2d5f10)
  • Provider / model: any; the repro uses the mock client from conversation-loop.spec.ts

Steps to Reproduce

In source/hooks/chat-handler/conversation/conversation-loop.spec.ts, with a mock client that reports {inputTokens: 1000, outputTokens: 100, totalTokens: 1100} on every call and onApiCallComplete collecting records:

  1. Malformed retry: the first reply is '[tool_use: read_file]' with toolsDisabled, the second is 'Recovered answer'. Two calls are billed.
  2. Compaction: setSessionContextLimit(100), history with an old message of 'old context sentence. '.repeat(120), reply 'Done.'. One call is billed.

Expected Behavior

One ApiCallRecord per billed call: 2 records in case 1, 1 record in case 2.

Actual Behavior

Case 1 records 1 call, case 2 records 0. /usage and /stats under-report tokens and cost for those turns.

Suggested fix

Emit onApiCallComplete from onModelResponse using response.usage (same hasReportedUsage check, without !compacted), and keep the setLastApiUsage snapshot logic, including its clear on compaction, in onTurnRecorded. Roughly 15 lines plus the two specs above.

Happy to send a PR if you'd like to assign it to me.

Additional Context

  • [x] I have searched existing issues to ensure this is not a duplicate (#1855 is about hidden SDK retries inside one call; open PR #2184 counts spend in onModelResponse but leaves this gate unchanged)
  • [x] I can reproduce this issue consistently
  • [x] This issue occurs with the latest version of nanocoder

harpreetkbadhan avatar Nov 24 '26 13:11 harpreetkbadhan