Repository navigation
stats: persist per-session usage + /v1/stats endpoint + web UI Stats tab - #202
Conversation
… tab Opt-in via stats_collection_enabled (default off, onboarding asks). When on, each turn's token / tool-call / truncation-savings counters accumulate into the session JSON's meta.stats block; the gateway exposes a 5-second-cached aggregate at GET /v1/stats with by_provider and by_model rollups; the web UI gains a Stats tab that auto-refreshes every 10s. The TUI /stats overlay is unchanged -- it uses an in-process accumulator and works regardless of the flag. Schema (TSessionMeta.Stats): - input_tokens, output_tokens - cache_read_tokens, cache_created_tokens - turns, tool_calls - truncation_bytes_saved When every counter is zero (flag-off path) the JSON omits the "stats" block entirely so flag-off sessions are byte-identical to the pre-feature schema. No migration required. Pieces: - TSessionMeta gains Stats: TSessionStats. - WriteSessionStatsJSON / ReadSessionStatsJSON in PasClaw.Session.Store; wired into TSession.Save / Load. - AccumulateTurnStats helper -- called from Cmd.Agent's RunInteractive after each RunToolLoop, and from TUI's AccumulateLoopStats. Both gate on the config flag, which they re-read per turn (cheap; the JSON parse is over a tiny file). - TConfig.StatsCollectionEnabled with JSON round-trip; emits only on the explicit-on path so fresh configs stay clean. Default- False survives round-trip via "field missing, fall back". - PromptStatsCollection added to onboarding (default N). - TToolLoopResult gains ToolCallsDispatched (sum across the loop's iterations) so callers don't have to walk FinalMessages to count tool invocations. - TGatewayServer.HandleStats: walks ListSessions, sums counters, bucket-sums tokens by provider + model. 5-second in-memory cache hides the walk cost from the web UI's auto-refresh. - webui.html: new Stats tab with cards (sessions / turns / tool calls / token totals / bytes saved) + by-provider + by-model tables. Polls /v1/stats every 10s; renders a "stats collection off" hint pointing at the config flag when the gateway reports flag-off. Tests (session_stats_tests, 4 cases): - TestStatsRoundTrip: every counter survives Save/Load. - TestEmptyStatsOmitted: flag-off session writes no "stats" block. - TestAccumulateTurnStatsAddsCorrectly: Turns increments by 1 per call regardless of other deltas; doubling produces double counters. - TestStatsCollectionEnabledRoundTrip: default-False stays unwritten; explicit-True round-trips. Verified end-to-end by hand-crafting two synthetic sessions with distinct providers / models, running the gateway against them, and confirming /v1/stats returns the right totals + rollups.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e57b4eb14f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if Cfg.StatsCollectionEnabled then | ||
| AccumulateTurnStats(FSession.Meta, | ||
| Loop.TotalUsage.InputTokens, | ||
| Loop.TotalUsage.OutputTokens, | ||
| Loop.TotalUsage.CacheReadTokens, | ||
| Loop.TotalUsage.CacheCreatedTokens, | ||
| Loop.ToolCallsDispatched, | ||
| Loop.TruncatedBytesSaved); |
There was a problem hiding this comment.
Persist TUI stats before saving the session
When stats collection is enabled in the TUI, this increments FSession.Meta after ApplyLoopResultTo has already saved the completed turn, and there is no subsequent save on the normal path before quitting. As a result, successful TUI turns still write no meta.stats to disk, so /v1/stats stays missing/zero for TUI sessions; if the user switched sessions while the loop was running, this also mutates the currently selected session rather than the originating one.
Useful? React with 👍 / 👎.
Two bugs in one wiring on the TUI side, both flagged by Codex: 1. Order of operations. AccumulateLoopStats ran AFTER ApplyLoopResultTo's Save. The Meta.Stats increment had nothing to flush it to disk on the normal path -- TUI sessions kept reporting zero counters at /v1/stats with the flag turned on. 2. Cross-session race. AccumulateLoopStats mutated FSession.Meta, but a worker can complete after the operator has already switched to a different session. Pre-fix: the new session silently absorbed the originating session's stats. Fix: move the persistent half of the accumulation INSIDE ApplyLoopResultTo, between the Working-state update and the Save. ApplyLoopResultTo already opens the originating session by id (via the FLoopSessionId mechanism PR #122 added for messages), so: - The Save that immediately follows picks up the new counters. - The right session gets credited regardless of where FSession points by the time the worker completes. TTUI.AccumulateLoopStats is reduced to the in-memory FStats* updates that drive the /stats overlay -- those still need to run regardless of Cfg.StatsCollectionEnabled. Tests (session_stats_tests): - TestAccumulateThenSavePersistsCounters pins the order: accumulate first, save second, reload, counters survive. A future refactor that reverses the order fails this test instead of silently dropping data. - TestAccumulateRoutesToOriginatingSession simulates the cross-session race by creating two sessions, accumulating into the first, saving, and asserting the sibling stays clean. Pins the by-id routing contract.
Opt-in flag to persist per-turn usage counters into each session JSON, plus a server-wide aggregator endpoint and a web UI tab that consumes it. The TUI
/statsoverlay is unchanged — it keeps its own in-process accumulator and works regardless of the flag.What ships
1. Config flag — opt-in, default off
TConfig.StatsCollectionEnabled(JSON:stats_collection_enabled).Enable stats collection [y/N]:(default N) with a one-line explanation of what it persists and where to flip it back.2. Per-session schema (
TSessionMeta.Stats)input_tokens/output_tokensLoop.TotalUsagecache_read_tokens/cache_created_tokensLoop.TotalUsageturns+= 1per turntool_callsLoop.ToolCallsDispatched(sum across the loop's iterations)truncation_bytes_savedLoop.TruncatedBytesSavedWhen every counter is zero (flag-off path),
WriteSessionStatsJSONskips the entire"stats"block — flag-off sessions are byte-identical to the pre-feature schema, so no migration concern.3. Per-turn accumulator
AccumulateTurnStatshelper inPasClaw.Session.Store(exposed in interface).Cmd.Agent.RunInteractiveafter eachRunToolLoop, and intoTUI.AccumulateLoopStatsnext to the existing in-memory accumulator.Cfg.StatsCollectionEnabled(re-read per turn — JSON parse over a small file, fine for v1; cache on the instance if it shows in a profile).4.
GET /v1/statsendpointTGatewayServer.HandleStatswalksListSessions, sums every counter, bucket-sumsinput+outputtokens byMeta.ProviderandMeta.Model.stats_collection_enabledso the web UI can render an "off" hint instead of zeros.{ "stats_collection_enabled": true, "sessions": 2, "input_tokens": 4000, "output_tokens": 2000, "cache_read_tokens": 200, "cache_created_tokens": 100, "turns": 13, "tool_calls": 16, "truncation_bytes_saved": 4096, "by_provider": [ { "provider": "openai", "tokens": 4500 }, { "provider": "anthropic", "tokens": 1500 } ], "by_model": [ { "model": "gpt-5", "tokens": 4500 }, { "model": "claude-opus-4-8", "tokens": 1500 } ] }End-to-end verified by hand-crafting two synthetic sessions and querying the live gateway — output above is the actual response.
5. Web UI Stats tab
stats_collection_enabled: false, instead of a wall of zeros.Tests
session_stats_tests.pas(4 cases):TestStatsRoundTrip— every counter survivesSave → Load;ProviderandModelsurvive too (they're what/v1/statsrolls up by).TestEmptyStatsOmitted— flag-off session writes no"stats"block; byte-clean diff vs. pre-feature schema.TestAccumulateTurnStatsAddsCorrectly— pins thatTurnsincrements by exactly 1 per call regardless of other deltas (an early draft incremented byInputTokens— easy mistake worth pinning).TestStatsCollectionEnabledRoundTrip— default-False stays unwritten; explicit-True round-trips throughToJSON / FromJSON.All 16 test programs pass on clean FPC 3.2.2 build.
Why aggregate-at-request-time instead of a process-wide counter
Cheaper to ship (zero new persistence layer), one source of truth (session JSONs), and the 5-second cache hides the walk cost. Trade-off: O(sessions) per refresh — fine for a personal gateway, painful at thousands. Documented in the handler comment so a future operator with that problem knows the lever.
Generated by Claude Code