Skip to content

stats: persist per-session usage + /v1/stats endpoint + web UI Stats tab - #202

Merged
FMXExpress merged 2 commits into
mainfrom
claude/stats-persistence-and-webui
Jun 9, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/stats-persistence-and-webui

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

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 /stats overlay 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).
  • Emitted only on the explicit-on path, so fresh configs stay clean. Default-False survives round-trip via "field missing, fall back to default" — verified in the test.
  • Onboarding asks 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)

Field Source
input_tokens / output_tokens Loop.TotalUsage
cache_read_tokens / cache_created_tokens Loop.TotalUsage
turns += 1 per turn
tool_calls new Loop.ToolCallsDispatched (sum across the loop's iterations)
truncation_bytes_saved Loop.TruncatedBytesSaved

When every counter is zero (flag-off path), WriteSessionStatsJSON skips the entire "stats" block — flag-off sessions are byte-identical to the pre-feature schema, so no migration concern.

3. Per-turn accumulator

  • AccumulateTurnStats helper in PasClaw.Session.Store (exposed in interface).
  • Wired into Cmd.Agent.RunInteractive after each RunToolLoop, and into TUI.AccumulateLoopStats next to the existing in-memory accumulator.
  • Both call sites gate on 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/stats endpoint

  • TGatewayServer.HandleStats walks ListSessions, sums every counter, bucket-sums input+output tokens by Meta.Provider and Meta.Model.
  • 5-second in-memory cache (process-wide; reads and writes are serialised through the gateway's single-threaded request handler so no locking).
  • JSON response includes stats_collection_enabled so 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

  • New tab in the nav, between Logs and Settings.
  • Cards: Sessions / Turns / Tool calls / Input / Output / Cache R / Cache W / Bytes saved.
  • Tables: Tokens by provider, Tokens by model (sorted high-to-low).
  • Auto-refresh every 10s while the tab is active. Renders a hint pointing at the config flag when the gateway reports stats_collection_enabled: false, instead of a wall of zeros.

Tests

session_stats_tests.pas (4 cases):

  • TestStatsRoundTrip — every counter survives Save → Load; Provider and Model survive too (they're what /v1/stats rolls up by).
  • TestEmptyStatsOmitted — flag-off session writes no "stats" block; byte-clean diff vs. pre-feature schema.
  • TestAccumulateTurnStatsAddsCorrectly — pins that Turns increments by exactly 1 per call regardless of other deltas (an early draft incremented by InputTokens — easy mistake worth pinning).
  • TestStatsCollectionEnabledRoundTrip — default-False stays unwritten; explicit-True round-trips through ToJSON / 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

… 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/pkg/tui/PasClaw.TUI.pas Outdated
Comment on lines +752 to +759
if Cfg.StatsCollectionEnabled then
AccumulateTurnStats(FSession.Meta,
Loop.TotalUsage.InputTokens,
Loop.TotalUsage.OutputTokens,
Loop.TotalUsage.CacheReadTokens,
Loop.TotalUsage.CacheCreatedTokens,
Loop.ToolCallsDispatched,
Loop.TruncatedBytesSaved);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@FMXExpress
FMXExpress merged commit 8a32d2a into main Jun 9, 2026
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.

2 participants