Skip to content

perf(usage): show all matched sessions in a paged overview - #169660

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-sessions-usage-aggregates-20260919
Oct 12, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-sessions-usage-aggregates-20260919

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #127245

What Problem This Solves

The Usage overview decoded complete usage histories and transferred up to 1,000 detailed rows, delaying the view and blocking the Gateway while serializing large responses. Client-side filters also stopped at that row cap.

User Impact

The overview now charts every matching session and pages 50 rows on the server. Query, creator, day, hour, and session selections share the server's accounting; sorting and paging preserve the selected totals. Detailed reports and JSON/session CSV exports retain canonical data. Model Providers and Daily CSV use the compact overview too.

Why This Change Was Made

A versioned, rebuildable projection reuses cache_entries: transcript checkpoints and UTC-date partitions of quarter-hour aggregates commit through the same worker writer. Committed transcript updates feed the existing queue, with 50-file backfill batches and visible partial progress. The former persisted per-event body is retired. No tables, indexes, database-version bump, retention change, or configuration option is added. Incognito retains its nonpersistent cache.

Transcripts remain authoritative. Exact partial-quarter boundaries and numerically unsafe regrouping use canonical replay. Legacy RPC requests keep their full response contract. The maintainer explicitly approved this cache representation and the change from the first 1,000 rows to all matched sessions before implementation.

Completed overview results are reused until their transcript, usage, metadata, profile, access, pricing, or configuration identity changes. Single-agent workers filter and aggregate before returning compact rows. Cross-agent views read summaries in workers, then use the same overview builder in global session order on the Gateway thread; independently summing agent subtotals changes ordinary decimal results, so that merge implementation was removed. The same query implementation serves UI filters and canonical exports; old client-side aggregation is removed.

Production/tooling delta is +1,326 lines (2,541 added, 1,215 removed, excluding tests, test support, and docs). Growth implements the approved stored representation and commit-driven refresh lifecycle plus the optional all-matched RPC and server paging while preserving the full canonical RPC/export and nonpersistent-session contracts. The superseded stored event body, client-side query/aggregation, and independent cross-agent subtotal merger are removed.

Evidence

Paired single-agent synthetic handler/worker benchmarks used the same AWS host (32 EPYC CPUs, Node 24), 2,000 sessions × 500 parent-linked transcript rows over 365 days, and an inclusive 30-day query. Each steady/warm cohort has 20 samples; timings include JSON serialization. These single-agent measurements precede the final rebase and are reused for the unchanged normal read path; later fixes affect cross-agent folding, background backfill, cache repair, and selected details. The cold and cross-agent measurements below use the final production code.

Measurement Previous Overview
Steady rebuild p95 7,465.79 ms 3,668.98 ms
Main-thread CPU p95 837.87 ms 99.40 ms
Maximum event-loop delay 594.02 ms 30.31 ms
Repeated view p95 135.24 ms 0.427 ms
Response 28,670,665 B 129,380 B

The 200 KB target passes. The 500 ms target passes for cached opens, but not revision rebuilds. This is a 2.03× steady latency improvement, 8.43× lower main-thread CPU, and 221.6× fewer response bytes.

Important tradeoffs: the sparse fixture's cache grows from 18.51 MB to 382.27 MB before SQLite overhead. Dense fractional-cost histories use canonical replay: their p95 rebuild is 2.05 s versus 1.15 s before, while main-thread CPU falls 3.32× and response bytes fall 52.6×. The dense cache shrinks 27.7%. Legacy detailed reads can also be slower after migration. Overview latency p95 uses compressed samples: a 512-event probe differed by 0.34%, while count, average, minimum, and maximum matched; canonical detailed reads retain their prior contract. These measurements do not claim lower whole-process RSS or production-dist cold startup.

On a four-agent, 200-session × 500-event fixture, the overview matched the retained canonical endpoint exactly on the same migrated cache: rebuild p95 1,037.01 ms vs 4,085.09 ms, main-thread p95 145.55 ms vs 155.02 ms, repeated opens 0.853 ms vs 20.523 ms, response 130,479 B vs 5,751,735 B. This comparison isolates the two current endpoint paths; it is not a pre-change multi-agent benchmark.

A separate paired empty-cache run exercised the actual report-triggered background queue on the same 8-core Linux rig with isolated state (Node 26.8.1, 2,000 × 500 rows; host CPU was shared). Time to a fully fresh view regressed from 71.46 s to 198.78 s (2.78×): initial refreshing response 19.87 → 44.33 s, queue drain 44.43 → 147.97 s, final fresh read 7.16 → 6.48 s. The candidate publishes progress across 40 bounded batches. Measured process CPU rose from 80.45 s to 199.23 s, so this is a real cold-build cost as well as a wall-time regression. Cold backfill throughput is a material cost of this representation; these are source-worker measurements, not production-dist startup timings.

Rollback proof used actual new-writer output with the unchanged old reader, which ignored the new version and rebuilt its prior cache. Focused tests cover atomic publication, backfill, deletion, rewind, pricing, rollback/re-upgrade, exact floating-point sums, inclusive ranges, DST, all-matched filters, pagination, exports, and current access at response publication. A committed turn advances the cache without a report read; stopping its lifecycle stops scheduling.

Remote evidence uses Blacksmith Testbox tbx_01m4p9j3myv88w23a2bjt7fq86 and AWS cbx_d175509fac0d. Paired benchmark and boundary proof and dense comparison. The benchmark's old-reader footer initially sent an unsupported pagination parameter after all measured samples; those samples and token checks remain valid. An earlier baseline attempt failed dependency setup before measuring, and one Testbox sync timed out before checks; no passing result is claimed for those steps.

Independent review passed through P2. Focused protocol/storage/worker/actor-memory/Gateway/shared suites, all 29 Usage E2E tests across 9 files, the full production runtime and Control UI builds, export collisions, and six closure/CI-plan suites passed. Review-driven repairs cover bounded backfill, selected-summary freshness, and complete partition replacement after cache damage.

The broad pre-PR gate passed production types, the first 15 core-test type graphs, UI/scripts types, and the architecture/security guards. It exposed stale sibling-test identity assertions, a fixture Window assertion, one test brace, and an unused encoder export; these have been corrected. Remaining broad type and dead-code verification runs in PR CI under the current proof policy. Other full-tree dead-code findings are not claimed as inherited exemptions.

Focused test cost

Each row ran pnpm test <file> --maxWorkers=1 on the rig and passed. Wall time includes wrapper/compiler setup. CI seconds are estimates from the observed workload, not measured GitHub billing.

File Wall seconds Estimated serial CI seconds
packages/gateway-protocol/src/session-usage.test.ts 9.37 ≈9
src/gateway/server-lifetime-sidecars.test.ts 130.99 ≈131
src/gateway/server-methods/usage-cache.test.ts 13.20 ≈13
src/gateway/server-methods/usage.sessions-usage-owner-attribution.integration.test.ts 256.52 ≈257
src/gateway/server-methods/usage.sessions-usage.test.ts 101.71 ≈102
src/infra/session-cost-usage-cache.sqlite.test.ts 118.11 ≈118
src/infra/session-cost-usage-cache.worker.test.ts 148.62 ≈149
src/infra/session-cost-usage-refresh.test.ts 76.49 ≈76
src/infra/session-cost-usage-worker-io.test.ts 120.33 ≈120
src/sessions/session-row-changes.test.ts 6.74 ≈7
src/shared/usage-overview.test.ts 6.17 ≈6
Total 988.24 ≈989

Rebased for GitHub merge conflicts. Earlier resolutions retained main's removal of an inert test-inventory row and direct-props Usage cleanup together with the overview and export owners. The final rebase respects main's retirement of the standalone memory backend and its test; generic storage operations for explicitly supplied actors remain part of the documented session-phase actor contract. Production patches are unchanged. The affected detail/export files passed 23/23 in an 8.56 s wrapper run. Fresh review of the complete lane diff is clean through P2. The added regression also passed independent review through P2. The active ephemeral-SQLite incognito fixture now proves overview paging keeps both sessions in totals: 1/1 selected case passed (31 skipped), test 7.07 s, wrapper 86.62 s with source/artifact verification. Current head: 8363dcca70e78c0ce987e95a0beec2be4604f90e.

CI and review repairs

The first PR CI run found a historical migration decoder following the new version number instead of its stored version 6, an incognito bounded-read cleanup publishing an unnecessary mutation, a type-only import cycle, and stale representation/access/detail test assertions. These are repaired. Genuine historical UTF-8 and UTF-16LE cache fixtures and the bounded/claimed/revoked incognito cases were exercised.

Review also found two behavioral regressions. Selected comparison rows now come from the same server-owned overview snapshot independently of the current table page; selecting and clearing them preserves that page. No UI page cache or second request is introduced. A failed canonical transcript replay omits only the unreadable session, reports partial usage, and schedules the existing rebuild path. It never publishes a partially scanned result; host-authority and task failures still propagate.

The selection regression reproduced the page jump before repair. Focused shared accounting tests passed 19/19, export tests 4/4, and the detail file 19/19, including paging, revision refresh, deletion, query changes, clearing, and off-page detail identity. The new page scenario took 8.08 s; its full file wrapper took 33.34 s on the loaded local host. The later removal of a redundant page lookup is covered by exact-head CI. Five Gateway checkpoint/lifecycle cases passed, but that wrapper exited during final source verification because another repair changed a worker input mid-run; this is recorded as passing test cases, not a clean local gate.

The corrected transcript-error file passed 2/2 tests with wrapper exit 0 and complete source verification. One fixture exercises background failure, foreground failure, and recovery using the same initialized worker: committed totals stay 17 after background failure, the foreground failure returns the readable sibling's 7 tokens, and recovery returns 17 with unchanged durable cache bytes. The combined regression took 18.19 s; its loaded-host wrapper took 136.63 s, including 63.18 s worker preparation. Changed-file format and lint and the export-name collision guard passed. Fresh independent review is clean through P2 for the final repair. Exact-head PR CI owns the remaining full gates.

The initial built-CLI concurrent-delete proof returned a terminal AbortError without its structured stop reason. That test correctly failed. The preserved log does not identify the producer that lost the metadata; the same test passed on main in run 38216343022. This remains an investigated, unclassified failure, not an inherited exemption or a claimed repair. The final head passed the built-artifact job; that passing result does not establish a repair for the earlier abort.

The benchmark samples above predate the final comparison-row metadata and error-path repairs. An empty selection adds 18 bytes to the overview response; the default no-selection aggregation path is unchanged. No new latency or whole-process memory claim is made from these final repairs. Shift-click ranges are local to the current table page.

Usage screenshots

Before/after images and all UI fixtures contain only synthetic data; validation did not access a live Gateway.

The same synthetic 1,250-session fixture: the previous overview caps its cohort at 1,000, while the new overview counts all 1,250 and pages 50 rows.

Before: 1,000-session cohort with a cap warning

After: all 1,250 sessions with server-side pagination

Comparison paging repair

The same synthetic 55-session fixture after selecting the first two rows and moving to the final page. Before, both comparison rows and the card's clear control disappear; after, both remain visible independently of the page.

Before: paging hides selected comparisons

After: paging retains selected comparisons and Clear Selection

Final exact-head CI

CI run 38227273100 completed on 8363dcca70e78c0ce987e95a0beec2be4604f90e: all other selected build, type, UI, architecture, and security jobs passed (inapplicable jobs skipped); three Node jobs contain five pre-existing failing cases. The rewind query-count case also fails on scheduled main run 38220958692. The mismatched-window resolution case, committed-preview case, and both pricing-cancellation cases reproduce on the verified unchanged main parent used by CI, 044f8ea2c39c93bbe01cf55578758ec027235f38. The failing tests and their relevant fork/read/pricing implementations are unchanged by this PR. Full test-level attribution is recorded in the landing comment. CI reported unknown from job names because changed-shard names differ from scheduled main; no CI rerun or expectation weakening was used. Landing uses the documented pre-existing-failure exception.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR adds server-side Usage filtering and 50-row pagination backed by incrementally maintained transcript projections.

Example: Open Usage with 1,250 matching sessions.

  • Before: The overview analyzes the first 1,000 sessions and displays at most 50 rows without pagination.
  • After: The overview analyzes all 1,250 sessions and pages through 50 rows while preserving totals and selected comparisons.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful implementation with strong visible behavior evidence and no identified production defect; helper-only tests retain obsolete policy.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (screenshot): Inspected browser screenshots exercise the real Usage rendering path with a synthetic Gateway, showing all 1,250 sessions, pagination, and retained off-page comparisons; the body also records production-worker boundary measurements and new-writer/old-reader rollback behavior.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large Usage histories produce expensive detailed responses, and client-side analysis excludes sessions beyond the loaded cap.
Reason: The maintainer-directed change provides complete filtered analysis and substantially smaller overview responses, with its performance tradeoffs disclosed.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-directed improvement addresses capped Usage analysis still present on main. No new production defect was identified, but GitHub confirms a merge conflict on the reviewed head.

Priority: P2
Reviewed head: 753bfc9adc8781ffef2eedbc0b8cb51eb6392747

Before merge

  • Complete next step - Resolve GitHub's reported merge conflict while preserving both the overview changes and main's Usage changes, then validate the paths affected by the resolution.

Findings

None.

Tests

  • Low-value test ui/src/pages/usage/view.test.ts: Remove the bounded source-order inventory test and its copied test-support builder: it now tests a retired implementation rather than the production server inventory.
  • Low-value test ui/src/pages/usage/query.test.ts: Use explicit server-option fixtures for suggestion tests and remove assertions against the retired buildUsageFilterOptions copy.
Agent review details

How this fits together

The Usage RPC reads session metadata and transcript-derived SQLite caches, aggregates the matching population, and returns compact overview rows to Control UI while retaining canonical detailed reports and exports.

flowchart LR
  A[Committed transcripts] --> B[Usage refresh queue]
  B --> C[Worker owned SQLite projection]
  D[Session metadata and access] --> E[Usage RPC]
  C --> E
  E --> F[Control UI overview]
  E --> G[Canonical details and exports]
Loading

Technical review

Best possible solution:

Land the conflict-resolved overview while preserving canonical exports, exact accounting, and current access checks.

Do we have a high-confidence way to reproduce the issue?

Current main's 1,000-row request and client-side filtering establish the capped-analysis path; the inspected synthetic browser evidence shows the corresponding before/after behavior.

Is this the best way to solve the issue?

A shared server overview owner coherently handles filtering, accounting, and paging while retaining canonical detail paths, with the storage and cold-build costs explicitly recorded.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d77d04aacc99.

Provenance checked

  • Usage filtering and capped session presentation changes intended behavior with a stated reason (8a352c8: The original dashboard supplied session analytics and filters; subsequent display-count work explicitly documented the 50-row presentation cap.)
  • Worker-owned usage reporting keeps the original intent (ad74de5: Move expensive cache decoding, aggregation, and refresh work away from the Gateway thread while retaining existing accounting and ownership.)
  • Precise hourly accounting and calendar traversal keeps the original intent (fix(ui): prevent Usage hour filters from freezing during DST #146919: Preserve elapsed allocation and forward progress across daylight-saving transitions; the shared overview retains these contracts with named-zone coverage.)
  • Full-history cache representation changes intended behavior with a stated reason (a64b307: Serve usage from a durable transcript aggregate cache; this PR explains replacing its per-event body with rebuildable date partitions and canonical replay.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
RPC contract expansion 9 optional request fields The existing sessions.usage endpoint gains overview, filtering, sorting, and paging parameters while omitted parameters preserve the legacy response path.
Persisted cache transition Cache version 6 → 7; no database schema-version bump The changed representation remains reconstructible from authoritative transcripts and reuses cache_entries.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #127245
Summary: This PR addresses oversized usage responses and aggregation costs; a narrower open candidate trims only Model Providers detail rows.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Improves large-history analytics completeness and responsiveness without establishing an urgent core-runtime regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Remove the retired filter-inventory implementation from test support and retain suggestion coverage using explicit server-option fixtures.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-12T06:17:56.232Z sha 6961144ca7570b50f05d4c99d7c8cb142898d2c0 :: needs changes before merge. :: [P2] Preserve selected comparison rows when changing pages
  • reviewed 2026-10-12T06:43:45.788Z sha 9b245f7 :: blocked before merge. :: [P2] Preserve selected comparison rows across page changes | [P2] Keep the historical migration reader pinned to version 6 | [P2] Handle transcript replay failures at the report boundary | [P2] Update the existing revocation regression for report rejection
  • reviewed 2026-10-12T08:32:45.100Z sha 562b531d30a4ece91746d1d0504f5bcfb78d65e5 :: needs changes before merge. :: none

Reviewed October 12, 2026, 5:00 AM ET / 09:00 UTC (Revision 4).

@steipete
steipete force-pushed the steipete/perf-micro-sessions-usage-aggregates-20260919 branch from 6961144 to 9b245f7 Compare October 12, 2026 06:29
@steipete
steipete marked this pull request as ready for review October 12, 2026 06:34
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 12, 2026
@steipete
steipete force-pushed the steipete/perf-micro-sessions-usage-aggregates-20260919 branch from 562b531 to 753bfc9 Compare October 12, 2026 08:48
Keep the Usage overview's filtering and aggregation in workers, report all
matched sessions, and send only the visible 50-row page. Advance rebuildable
UTC date partitions from committed transcript publication while retaining
canonical replay for exact boundaries and legacy RPC responses.

Preserve full exports, shared-store attribution, creator filters, timezone
semantics, and current access checks. Reuse completed overview results until
an owning revision changes.

Related: #127245
Fold cross-agent summaries in global session order and keep final paging in
one overview owner. Bound queued refresh inputs and targeted inventory reads,
retain pending rebuild identities, and support actor-memory overview progress.

Replace all date partitions after an incomplete projection forces a rebuild.
Refresh selected session details when the overview revision advances while
retaining existing timeline and log refresh behavior.

Related: #127245
@steipete
steipete force-pushed the steipete/perf-micro-sessions-usage-aggregates-20260919 branch from 753bfc9 to 8363dcc Compare October 12, 2026 09:01
@steipete

Copy link
Copy Markdown
Contributor Author

Current reviewed head: 8363dcca70e78c0ce987e95a0beec2be4604f90e. CI run: https://github.com/openclaw/openclaw/actions/runs/38227273100. Its tested merge is 5bf711531fc11f3ae945d0f31d464399172f7820, with main parent 044f8ea2c39c93bbe01cf55578758ec027235f38.

The failing cases are pre-existing:

  • sessions-rewind.test.ts — “returns editor text for rewind and a new key for fork” observes two session_upstream_links reads where its assertion expects one. The same case and signature fail on main in run 38220958692. The focused local case also reproduces it. The PR's failing job is 114738346982.

  • sessions-resolve-projection.test.ts — “preserves warm and cold storage-reader outcomes for mismatched-window rows” receives undefined instead of target-id. A focused local run against the verified, unchanged CI main parent 044f8ea2c39c93bbe01cf55578758ec027235f38 fails identically (1 failed, 14 skipped; test 0.36 s, wrapper 52.76 s). The candidate tree was restored and verified clean afterward. The PR's failing job is 114738347025.

  • sessions-read-cache.test.ts — “refreshes row previews after a committed transcript update” receives undefined instead of the committed preview. The selected case reproduces identically on unchanged CI main 044f8ea2c39c93bbe01cf55578758ec027235f38 (1 failed, 25 skipped; test 4.57 s, wrapper 27.35 s). Its failing job is 114738347263.

  • session-cost-usage-metadata.test.ts — both “pricing loses its database admission” and “pricing loses its plugin cache” cases reproduce on unchanged CI main 044f8ea2c39c93bbe01cf55578758ec027235f38: each times out at 120 s and reports that the log promise resolved instead of rejecting. The fixture waits for a mocked metadata operation which the configured-pricing path does not reach. Baseline result: 2 failed, 1 skipped, the same 2 unhandled assertion errors; wrapper 255.75 s. These cases share failing job 114738347263.

The failing test files and their relevant fork/read/pricing implementations are byte-identical between the CI main parent and tested merge. No expectations were weakened and no CI rerun was requested. Independent review is clean through P2; the scoped Usage proof and inspected synthetic screenshots remain in the body.

The earlier built-CLI abort without stop metadata did not recur: build-artifacts passed on this head. Its earlier cause remains unclassified; this passing result is not claimed as a repair.

The completed run passed all other selected test/build/type/security jobs; inapplicable jobs were skipped. The automatic failure classifier reported unknown because the changed-shard names have no matching scheduled-main job; the attribution above uses exact test signatures and unchanged-main execution. Landing uses the documented pre-existing-failure exception; no passing CI result is claimed for these cases.

@steipete
steipete merged commit 7aae49e into main Oct 12, 2026
170 of 177 checks passed
@steipete
steipete deleted the steipete/perf-micro-sessions-usage-aggregates-20260919 branch October 12, 2026 09:31
steipete added a commit that referenced this pull request Oct 12, 2026
Proactive Usage projections were rescanning transcript pages and acquiring durable refresh locks on every publication, adding 122 SQL statements and 18 worker requests per warmed turn after #169660.

Coalesce usage-bearing publications, resume scans from the existing transcript rewrite watermark, decode each page once, and use the Gateway-owned refresh reservation with atomic rollup/partition writes. Overview reads flush pending work for immediate completed-turn freshness. Remove obsolete lock discovery and resolver paths; preserve incognito locking and session-fact residency.

One live baseline/candidate pair reduced Usage work to 10 SQL statements and 2 requests per warmed turn. All-thread warmed medians fell from 390 to 254 statements and 87 to 62 requests; warmed MAIN and area T1 remain zero. All five shared read families decreased.

Regression coverage includes append/rewrite/rewind/compaction totals, immediate overview freshness, write exclusion, deletion drainage, and actor residency. Two Codex review rounds and Knip pass. Full evidence, CI results, and accepted derived-cache concurrency edges are recorded in the PR. No schema, configuration, retention, or update migration changes.

Final-head typechecks, lint, source contracts, Madge, and database ratchets pass. Land with the authorized exception for the unchanged pending-inputs savepoint test: its identical SQLite lock failure was reproduced independently on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…169660)

* perf(usage): serve paged overview from transcript projections

Keep the Usage overview's filtering and aggregation in workers, report all
matched sessions, and send only the visible 50-row page. Advance rebuildable
UTC date partitions from committed transcript publication while retaining
canonical replay for exact boundaries and legacy RPC responses.

Preserve full exports, shared-store attribution, creator filters, timezone
semantics, and current access checks. Reuse completed overview results until
an owning revision changes.

Related: openclaw#127245

* fix(usage): preserve ordered totals and complete projection rebuilds

Fold cross-agent summaries in global session order and keep final paging in
one overview owner. Bound queued refresh inputs and targeted inventory reads,
retain pending rebuild identities, and support actor-memory overview progress.

Replace all date partitions after an incomplete projection forces a rebuild.
Refresh selected session details when the overview revision advances while
retaining existing timeline and log refresh behavior.

Related: openclaw#127245

* fix(usage): preserve incognito reads and historical cache migration

* fix(usage): retain paged comparisons and partial reports

* style(usage): format comparison selection after rebase

* test(usage): cover overview through active incognito storage
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Proactive Usage projections were rescanning transcript pages and acquiring durable refresh locks on every publication, adding 122 SQL statements and 18 worker requests per warmed turn after openclaw#169660.

Coalesce usage-bearing publications, resume scans from the existing transcript rewrite watermark, decode each page once, and use the Gateway-owned refresh reservation with atomic rollup/partition writes. Overview reads flush pending work for immediate completed-turn freshness. Remove obsolete lock discovery and resolver paths; preserve incognito locking and session-fact residency.

One live baseline/candidate pair reduced Usage work to 10 SQL statements and 2 requests per warmed turn. All-thread warmed medians fell from 390 to 254 statements and 87 to 62 requests; warmed MAIN and area T1 remain zero. All five shared read families decreased.

Regression coverage includes append/rewrite/rewind/compaction totals, immediate overview freshness, write exclusion, deletion drainage, and actor residency. Two Codex review rounds and Knip pass. Full evidence, CI results, and accepted derived-cache concurrency edges are recorded in the PR. No schema, configuration, retention, or update migration changes.

Final-head typechecks, lint, source contracts, Madge, and database ratchets pass. Land with the authorized exception for the unchanged pending-inputs savepoint test: its identical SQLite lock failure was reproduced independently on main.
steipete added a commit that referenced this pull request Oct 15, 2026
Remove a test-only config cache-reset wrapper, duplicate internal selection
and channel-support checks, an unused session-file metadata fallback, and
duplicate usage target shapes. Carry transcript delivery facts from their
first parsing pass. Keep all network validation, effect authority, transcript
durability, current update policy and standalone session memory machinery.

Best-effort tradeoffs accepted:
- Internal agent updates trust the selection-shape check at their sole
  production caller, agents.update. The duplicate originated in the Models
  agent-selection feature #150224; the same boundary check still rejects
  invalid user input. Live runtime choice validation stays at the effect.
- Channel start support is checked once at the synchronous request boundary.
  The inner check from #67815 / #167159 cannot observe a different plugin
  without unsupported synchronous mutation; the boundary guard remains.
- Workspace-root readers require caller-prepared metadata: both production
  consumers already provide it. The unused fallback from #161747 is deleted,
  not the Phase E backend or any factory. A future invalid internal caller
  gets a clear error instead of starting another metadata read.
- Update handlers trust the required getRuntimeConfig contract instead of
  falling back to a global schedule for an invalid context. Keep #158301's
  real scheduler-policy incident fix and its post-await current-config read.
- Usage summaries trust the canonical required target identity from #169660;
  the first-instance fallback served no production caller. The integration
  fixture now supplies that identity with all original assertions retained.

No public schema/config/SDK/protocol or persisted shape changes. The config
tests call the same canonical invalidators directly; no coverage is removed.

Follow-up removes 54 net production lines; branch total removes 154. Targeted
types (including MCP consumers), retained-file type-aware lint, formatting,
zero runtime import cycles, suppression audit and independent P2 review pass.
Gateway behavioral suites remain incomplete after a loaded-host startup run
was stopped at about ten minutes (exit 143). The prior full static-graph gap
remains pending for the coordinator bundle; no new production edge is added.
steipete added a commit that referenced this pull request Oct 15, 2026
…-5 bundle A) (#172989)

* refactor(ui): remove unused page plumbing and duplicate presentation work

Fold sole-caller Config and Cron adapters into their existing owners, reuse
canonical controller types, and remove unused request arguments and login
selection options. Adopt the complete background mutation receipt instead of
rereading the write; keep authoritative preflight and live ownership checks.

Best-effort tradeoffs accepted: a later background edit in another browser is
reflected by normal preference events or refresh, not an unconditional read of
our own successful write. The introducing feature PR #168301 does not identify
a human incident requiring that reread. Settled rendering and public contracts
are unchanged; both shipping renderer paths remain intact.

* refactor(ui): consolidate presentation helpers and cached preview inputs

Share point-menu trigger attributes and deletion-first LCS traversal. Remove
an obsolete empty-badge predicate, a one-caller loading facade, and redundant
whole-map translation fallback. Preserve both active Lit and Solid paths,
positioning formulas, diff work budgets, visible text, and rendering.

Best-effort tradeoffs accepted:
- Trust successful synchronous Web Storage writes instead of reading them back.
  Introducing PR #162428 supplied synthetic storage failures, not a human
  incident where successful setItem silently failed. Nonconforming Storage
  replacements may miss a cache publication until the next refresh.
- Trust immutable message/tool-card identities for cached source previews.
  PR #148431's in-place mutation assertions were synthetic; production owners
  publish replacement snapshots. Unsupported in-place mutation may leave a
  decoration stale until replacement. Run/frame/origin and external source
  validation remain unchanged.

Net production reduction: 76 lines; tests: 20 lines removed, only synthetic
same-object mutation assertions. Kept config coercion tied to human Safari
report #13348, along with security, durability, ordinary navigation ownership,
and all active migration paths.

Focused proof: 73 boot/cache/diff tests, 82 menu tests, 46 badge/assistant tests,
20 i18n tests, 8 browser details tests, 3 lint-suppression tests; UI typecheck,
formatting, stylesheet lint and CSS declaration parity passed.

Known inherited local check failure: environment-variable count is 455 against
budget 454, independently reproduced against clean HEAD/index. Its counted
source roots exclude UI. No budget or unrelated source changes made.

* refactor(ui): remove obsolete presentation compatibility and styling

Use the native Popover capability required by the Control UI bootstrap
instead of retaining old-engine in-flow fallbacks. Keep native overlay
occlusion and all real connection/navigation ownership.

Remove retired sidebar style hooks and share identical question-panel
declarations. Supported browsers render identically; no user-visible
copy, feature, renderer selection, config, protocol, or storage change.

Best-effort tradeoffs accepted

- Old engines without Popover support, or invalid direct popover mounts,
  no longer receive an in-flow menu fallback. The fallback came from
  #105598 as generic compatibility, not a human incident; #168595 made
  native Popover support a required bootstrap capability. Invalid direct
  mounts now fail clearly rather than silently changing layering.

Deeper coverage and retained candidates are recorded in the requested
task-local y03 ledger for coordinator bundling.

Branch total: 123 net production LOC removed (+114/-237), excluding tests,
fixtures, generated files and declarations. Below the 500-line campaign
floor after the deeper components/app/lib/styles and lead-owned owner pass;
push branch-only for bundling.

* refactor(gateway): reuse server method owners

Consolidate duplicate catalog response handling,
optional catalog reads, pairing resolution, requester assertions and system
agent transcript persistence. Carry prepared pairing and actor facts instead
of probing or re-reading them. Remove redundant cache-generation and internal
receipt checks; retain security, durability, pagination and resource bounds.

Best-effort tradeoffs accepted:
- Pairing captures its selected adapter once. Repeated internal checks added
  by #112401 guarded hypothetical in-place plugin mutation, not a reported
  incident. Such a mutation now leaves this request on its selected adapter;
  later requests discover the current registration.
- Channel identity RPCs trust the canonical mutation result instead of
  repeating the action/kind assertion introduced in #161284. No human incident
  justified the redundant adapter assertion; live mutation authority remains
  with the state owner.

No user-facing feature, protocol/config/persistence shape, schema, dependency,
test coverage or standalone session memory backend changes.

Net production reduction: 100 lines (179 added / 279 deleted).
Type-aware lint, targeted production types, formatting, runtime cycles (zero),
SDK surface, suppression audit and independent P2 review pass. Gateway focused
suites and the full static import graph remain incomplete on the loaded host;
retain these proof gaps for the coordinator bundle rather than claiming green.

* refactor(gateway): trust prepared server method inputs

Remove a test-only config cache-reset wrapper, duplicate internal selection
and channel-support checks, an unused session-file metadata fallback, and
duplicate usage target shapes. Carry transcript delivery facts from their
first parsing pass. Keep all network validation, effect authority, transcript
durability, current update policy and standalone session memory machinery.

Best-effort tradeoffs accepted:
- Internal agent updates trust the selection-shape check at their sole
  production caller, agents.update. The duplicate originated in the Models
  agent-selection feature #150224; the same boundary check still rejects
  invalid user input. Live runtime choice validation stays at the effect.
- Channel start support is checked once at the synchronous request boundary.
  The inner check from #67815 / #167159 cannot observe a different plugin
  without unsupported synchronous mutation; the boundary guard remains.
- Workspace-root readers require caller-prepared metadata: both production
  consumers already provide it. The unused fallback from #161747 is deleted,
  not the Phase E backend or any factory. A future invalid internal caller
  gets a clear error instead of starting another metadata read.
- Update handlers trust the required getRuntimeConfig contract instead of
  falling back to a global schedule for an invalid context. Keep #158301's
  real scheduler-policy incident fix and its post-await current-config read.
- Usage summaries trust the canonical required target identity from #169660;
  the first-instance fallback served no production caller. The integration
  fixture now supplies that identity with all original assertions retained.

No public schema/config/SDK/protocol or persisted shape changes. The config
tests call the same canonical invalidators directly; no coverage is removed.

Follow-up removes 54 net production lines; branch total removes 154. Targeted
types (including MCP consumers), retained-file type-aware lint, formatting,
zero runtime import cycles, suppression audit and independent P2 review pass.
Gateway behavioral suites remain incomplete after a loaded-host startup run
was stopped at about ten minutes (exit 143). The prior full static-graph gap
remains pending for the coordinator bundle; no new production edge is added.

* refactor(ui): consolidate page lifecycle and config plumbing

Reuse the existing controller host, subscription and plugin-icon owners;
share cloud-worker config edit wiring and Usage query comparisons. Remove
the unused Usage detail predicate and duplicate model loading flag.

Retire the Web Awesome-era picker hiding fence now that native Popover
owns generation-bound close completion. Keep both rendering paths,
draft recovery, user-intent checks and dispatch-time write authority.
Settled rendering is unchanged. Net production reduction: 210 lines.

Best-effort tradeoffs accepted:
- Failed channel artwork retries on the next channel refresh rather than
  a queued trailing ensure. #131511 was a synthetic ordering regression;
  the human-reported owning-plugin bug #144152 remains covered.
- Picker triggers may reopen during closing. #126032's fence came from
  CI/synthetic overlap, not a human incident; #171441 transferred lifecycle
  ownership to native Popover, which ignores superseded completions.

Focused proof: 281 tests passed, including Chromium/WebKit overlay lifecycle
and responsive placement controls. Independent P0-P2 review: scoped-clean.
Final UI production and UI-pages test typechecks passed; suppression tests 3/3.
Scoped lint passed after a mechanical no-lonely-if fix.
Runtime and static import cycles: zero. No visual or locale changes.
The global environment-name budget is inherited at 455/454 on both the
untouched base and origin/main; none of its counted source roots changed.

* refactor(ui): remove unused new-session hiding selector

* refactor(gateway): retain legacy catalog and update handler contracts

Withdraw two wave-5 cleanups after focused CI failures and bounded isolated replay. Preserve the existing scalar-read concurrency and update-status handler contract. Tighten task-suggestions assertion allowance to match the cleaned source.
obviyus added a commit that referenced this pull request Oct 15, 2026
…#148682)

Related: #148603 (this PR fixes the whole-turn accounting; the issue's final per-call output count is listed under Not in scope below)

## What Problem This Solves

Fixes: session usage, `usage.cost`, and the Usage page count only the last model call (with its stream-start output count) for Claude CLI turns. Turns that make several model calls, such as tool-using turns, are therefore heavily undercounted.

## User Impact

User impact: Claude CLI turns now record the whole turn's tokens in the session transcript, so usage reports and anything built on them (cost estimates, budget alerts) match what Claude Code reports.

- Context-window sizing, preflight compaction, and memory-flush gating keep using the latest model call.
- Chat context displays (Control UI message footer, iOS/macOS chat) keep showing the latest call's context size.
- Turns recorded before this change keep their existing counts.
- No config, schema, or migration change (see compatibility below).

## Why This Change Was Made

Claude Code's terminal `result` event already carries whole-turn usage, and the stream parser keeps it as `diagnosticUsage` (#120100). Both CLI transcript writers still persisted the last call.

- **Both writers:** they now persist the turn total as the usage counters. `contextUsage` is derived from the last call through one shared helper (`resolveCliTranscriptUsage`), so every context reader still sizes the window from the latest call.
- **Reply-path writer:** it adds that context marker only when the backend reports a turn total separately. Other CLI backends keep their unmarked records, which context readers already refuse to treat as a fresh context size (#120497).
- **Memory flush and preflight:** their transcript snapshot now takes the last completion's output from the context marker instead of the turn counters.

- **Chat context displays:** chat history now forwards an available, coherent `contextUsage` marker with assistant usage. The Control UI message footer and the native context control and footer size context from it. Rows without an available marker keep sizing from the counters, as before.
- **Tiered pricing:** summed tokens cannot recover each request's tier. `usage.cost` now leaves a turn unpriced when its counters exceed the marker's prompt and their sum reaches past the lowest tier.
  - A sum inside the lowest tier keeps every call there, so it is still estimated. Flat pricing is unchanged.
  - The rule reads the usage shape, so it also applies to Codex harness rows whose summed prompt crosses a tier boundary.
  - `USAGE_COST_ROLLUP_VERSION` moves to 8 so cached usage summaries rebuild with the new rule. `main` is at 7 since #169660, which also carries version-6 summaries forward; both were priced under the old rule, so this PR accepts only version 8. The schema cutover still moves version-6 rows, and readers rebuild them.

Live `agentMeta.usage` / `lastCallUsage` and the context-engine hook message are unchanged.

## Evidence

### Real behavior proof (after the fix, live OpenClaw)

Setup:
- A production OpenClaw 2026.9.2 gateway with Claude Code 2.1.263 on a Claude subscription.
- This PR's three production edits applied as a local backport, with identical logic, because the host runs the published build.
- Output is redacted to usage counters; the session id is replaced.

Two non-delivering `openclaw agent` turns ran on one dedicated session:
- Turn 1 makes two model calls: a Read tool call, then the reply.
- Turn 2 reuses the existing session.

```text
$ openclaw agent --agent main --session-key agent:main:<proof> --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."

# live run metadata (unchanged by this PR)
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# persisted assistant transcript records, read back from the session's SQLite transcript
turn 1  usage {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
               contextUsage {state available, promptTokens 74920, totalTokens 74921}}
turn 2  usage {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
               contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# Claude Code's own transcript for the bound CLI session (deduplicated by message id)
turn 1  model calls 2  sum input 4 / output 89 / cacheRead 74593 / cacheWrite 74918  last-call prompt 74920
turn 2  model calls 1  sum input 2 / output 3  / cacheRead 74918 / cacheWrite 102    last-call prompt 75022

# usage.cost for the agent's day, read back before and after the two proof turns (rollup refresh)
before  totalTokens 404634  output 13   cacheWrite 45337   totalCost 0.3800  missingCostEntries 0
after   totalTokens 629263  output 105  cacheWrite 120357  totalCost 0.8764  missingCostEntries 0
delta   totalTokens +224629 (= 149604 + 75025)  output +92 (= 89 + 3)  cacheWrite +75020 (= 74918 + 102)
```

What this shows:
- The persisted counters equal Claude Code's per-turn totals exactly.
- The usage report's delta equals the two persisted records. The dollar figure comes from a locally configured `claude-cli` price entry; this PR does not change pricing.
- `contextUsage.promptTokens` equals the last call's prompt.
- Without this change, turn 1 would have been persisted as output 1 / cacheWrite 325.
- A scheduled heartbeat turn on the same gateway also persisted its final output count (9) and not the stream-start value (1): `usage {input 2, output 9, cacheRead 69062, cacheWrite 10885, totalTokens 79958, contextUsage {state available, promptTokens 79949, totalTokens 79950}}`.

### Real behavior proof for the chat display and pricing follow-ups

Setup:
- OpenClaw built from this branch at 4f6d8a8, run as an isolated local gateway (own state directory, loopback only, channels off).
- Both turns ran with `openclaw agent` through the real `claude-cli` backend. The `claude` binary on `PATH` was a stand-in that emits the usage of the live turns above as Claude Code stream records: one `assistant` record per model call and the terminal `result`. No model call was made.
  - The first call's record is derived: turn total minus the last call.
  - `qa/scenarios/channels/telegram-claude-cli-compaction-final-priority.yaml` uses the same stand-in technique.
- The runner, transcript writer, chat history, `usage.cost` and the Control UI are the built product with no proof-only changes. The only stand-in is the `claude` binary.
- **Before** is this branch with the source changes of fa8ed7c and db6439b reverted and rebuilt. That is the state reviewed at 9366812: whole-turn counters stored, displays and pricing not yet following the marker. **After** is the head.
- The turns ran once, on the before build. The after build read the same session from the same state directory. The transcript writer is identical in both builds.
- Proof configuration: a 200,000-token context window, and a `claude-cli/claude-sonnet-4-5` price entry with a tier boundary at 100,000 prompt tokens (`$3 / $15 / $0.30 / $3.75` per million tokens below it, `$6 / $22.50 / $0.60 / $7.50` above). Each call of turn 1 stays below the boundary (74,595 and 74,920 prompt tokens). Their sum (149,515) crosses it.

```text
$ openclaw agent --agent main --session-key agent:main:proof --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."
$ openclaw agent --agent main --session-key agent:main:proof --json --message "Reply with only the word ok."

# run metadata from the stand-in, equal to the live run above
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# openclaw gateway call chat.history: assistant usage as the Control UI and the apps receive it
before  turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025}
after   turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
                 contextUsage {state available, promptTokens 74920, totalTokens 74921}}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
                 contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# openclaw gateway call usage.cost --params '{"days":1}': totals
before  totalTokens 224629  totalCost 0.6315762  missingCostEntries 0
after   totalTokens 224629  totalCost 0.0229089  missingCostEntries 1
        missingCostByModel {"claude-cli/claude-sonnet-4-5": 1}
```

What this shows:
- **`usage.cost`, before:** turn 1 is priced from its summed prompt at the upper tier. That is `$0.6086673` of the total; the rest is turn 2. Both of its calls sit in the lower tier, where the same tokens cost about `$0.3047`.
- **`usage.cost`, after:** turn 1 is left unpriced and counted in `missingCostEntries`. Turn 2 is a single call and keeps its estimate, `$0.0229089`.
- Token totals are the same in both builds (224,629 = 149,604 + 75,025).
- The before build stored its usage rollup under version 6. On the head, the first `usage.cost` read reported it stale and refreshing. The next read, 3 s later, was fresh with the new totals, and the stored rollup carries version 7. No manual step was needed.

**Control UI** (web): the usage details of turn 1's reply in the chat view. They show when the message footer is hovered.

Before: `75% ctx`

![Control UI message footer before: 75% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-before.png)

After: `37% ctx`

![Control UI message footer after: 37% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-after.png)

**Native** (iOS): the message footer (top) and the context control's menu (bottom).

Before: `75% ctx` with a warning, and "149.6k of 200.0k tokens used"

![iOS chat before: 75% ctx, 149.6k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-before.png)

After: `37% ctx`, and "74.9k of 200.0k tokens used"

![iOS chat after: 37% ctx, 74.9k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-after.png)

- The iOS app target is a Debug build of `apps/ios` on an iPhone 17 simulator (iOS 26.4.1), from a reduced project without the watch app, in the app's screenshot fixture mode (`--openclaw-screenshot-mode`).
- A local, uncommitted patch to the fixture transport seeds the chat history with turn 1's usage row and a 200,000-token window. The chat text and the model label (`claude-sonnet-4-6`) are the fixture's own.
- Both runs receive the same history payload, marker included. Before reverts the Swift changes of fa8ed7c, so only the app code differs.
- The macOS app renders the same shared `OpenClawChatUI` views from `apps/shared/OpenClawKit`. It was not captured separately.
- The screenshots hold proof-session and fixture content only: no endpoints, addresses, keys or personal data.

### Tests and checks

Regression tests. Each one fails on `main` and passes with this change:
- `cli-runner.turn-usage.test.ts` › "persists the terminal Claude turn usage for a multi-call turn"
  - Runs a turn whose parsed output carries the last call and a separate turn total through `runPreparedCliAgent`, then reads the persisted transcript back.
  - Before: input 2 / output 1 / cacheRead 27,376.
  - After: 6 / 77 / 54,631, with `contextUsage` at the last call's 27,378 prompt tokens.
- `transcript-persistence.test.ts` › "persists the terminal CLI turn usage while keeping last-call context"
- `session-transcript-readers.test.ts` › "sizes CLI output from the context marker when counters cover the whole turn"
  - Before: 30,000 output tokens.
  - After: 2,000 output tokens.

- `chat-display-projection.test.ts` › "forwards an available context marker with assistant usage"
- `chat-message-timestamp.test.ts` (new file) › "sizes context from the marker when usage counters cover a whole turn"
  - Before: 75% ctx for a two-call turn in a 200k window.
  - After: 37% ctx.
- `ChatContextUsageTests.swift` › "whole-turn counters report the latest call's context marker" and "usage footer sizes context from the marker and keeps whole-turn counters"
  - Before: 149,000 tokens and "98% ctx".
  - After: 75,000 tokens and "49% ctx".
- `session-cost-usage-pricing.test.ts` (new file) › "leaves a multi-call turn unpriced when its sum crosses a tier" and "prices a multi-call turn whose sum stays in the lowest tier"

Guard test:
- `cli-run-transcript.test.ts` › "keeps CLI usage unmarked when the backend reports no separate turn total"

Suites and checks (branch merged with `main` at 035bf89):
- Merge history: the merge at efa6458 had three conflicts, all code `main` had moved: the transcript accounting reader now lives in `session-transcript-accounting-policy.ts`, and the chat footer's `extractGroupMeta` in the Solid `chat-message-timestamp-view.tsx`; this PR's two edits were re-applied there unchanged. The merge at 432d890 was clean. The merge at 035bf89 had one import conflict in `chat-message-timestamp-view.tsx`; both helpers are kept.
- #120008 (usage reports marked unavailable) landed in three files this PR also changes: the chat history projection, the usage pricing estimate and the Control UI footer. Both changes are kept side by side: an unavailable usage report is skipped before this PR's context marker and tier guard are read.
- On the merged head, `pnpm test <files> --maxWorkers=4` passed 2,239 tests across 171 files:
  - every test file in `src/agents/cli-runner/` and `src/agents/command/` (live and e2e files excluded);
  - the `cli-runner.*`, `cli-output*`, `usage*`, `agent-runner-memory*`, `session-transcript-readers*`, `chat-display-projection*`, `session-cost-usage*` and `usage-format*` suites;
  - the Control UI `chat-message*` suites, including the six chat browser tests;
  - the usage cache suites (`session-cost-usage-cache.*`), `doctor-usage-cost-cache.test.ts` and the schema cutover test `openclaw-agent-db.storage-migration.test.ts`.
- The version 8 move updates two cutover tests from #169660: a migrated version-6 report is still moved (the cache test checks it arrives byte for byte), but no longer decodes as current (`session-cost-usage-cache.sqlite.test.ts`, `openclaw-agent-db.storage-migration.test.ts`). Our earlier fixture change in the cutover test (4f6d8a8) is replaced by `main`'s stored version 6.
- CI on the first merge failed two of this PR's new tests and one existing e2e test:
  - `cli-runner.turn-usage.test.ts` and the guard test in `cli-run-transcript.test.ts` relied on runtime config being loaded on demand, which #169714 removed. Without config the persistence wrapper wrote no row, so both saw an empty transcript. Both now pass `config: {}`, as #169714 did for the neighbouring tests. Both fail on the new merge without that change and pass with it.
  - `cli-runner.fault-sequences.e2e.test.ts` › "dispatches bridge mode through one fresh CLI child and bypasses the native run budget" fails with "Runtime config is not prepared" on this head, and identically with all of this PR's source changes reverted (tests kept). It comes from `main`, not from this PR.
  - Left out of the local run: `session-cost-usage-cache.creation-race.test.ts`, new on `main`, fails on this Mac with "state … is undergoing offline maintenance", identically with this PR's source changes reverted.
- Test cost of the four added tests, from `pnpm test <file> --maxWorkers=1` on an M-series laptop:
  - `cli-runner.turn-usage.test.ts` (new file): 2.2 s for the test, 11 s for the file. It runs the real runner and transcript store, because that is the only layer that proves the turn total is wired from the runner into the writer.
  - `transcript-persistence.test.ts`: 63 ms for the added test.
  - `session-transcript-readers.test.ts`: 144 ms for the added test.
  - `cli-run-transcript.test.ts`: 201 ms for the added test.
- Gates re-run on the merged head: `oxfmt --check` and oxlint on the changed files, `tsgo:core`, `tsgo:ui`, `tsgo:core:test`, and the line-cap, assertion-safety and mock-export ratchets. `git diff --check` is clean.
- Gates last run before the merge of `main`: import cycles (0 runtime, 0 madge), dead-code exports, deprecated API usage, `lint:ui:i18n`, stylelint on the changed UI files, and the max-lines and test-timeout-race ratchets. The SQLite-worker ratchet last ran before the chat-display and pricing commits, which add no database code.
- The three regression tests moved out of `cli-runner.reliability.test.ts`, `attempt-execution.cli.test.ts` and `agent-runner-memory.test.ts`, which are over the line cap and may not grow.
- Chat display and pricing follow-up:
  - `swift test --package-path apps/shared/OpenClawKit --filter ChatContextUsageTests` passed 14 tests on the merged head; SwiftFormat and SwiftLint at the pinned versions report nothing on the changed files.
  - The added TypeScript tests take 0 to 2 ms each. Each new regression test fails with its source change reverted.
  - The iOS app target was built (Debug, simulator, reduced project without the watch app) for the screenshots above. Not run locally: the full OpenClawKit suite, the full iOS project and the macOS app build.

Live Claude Code semantics (stream-json, `--include-partial-messages`):
- A tool-using turn's `result` reported 77 output tokens, while its two `assistant` events carried 15 and 1.
- In one warm stdio process, each turn's `result.usage` covered only that turn (78 output tokens each time). Only `total_cost_usd` accumulates, so persisting `result` usage does not double count warm sessions.
  - Rechecked on Claude Code 2.1.293: two turns in one process reported cache writes of 28,094 and then 5,619, while `total_cost_usd` rose from 0.0057 to 0.0072.

## Upgrade and data compatibility

- **No schema, migration, or config change.** The persisted assistant `usage` keeps its existing shape. `contextUsage` is an existing optional field that the agent-command writer has persisted since #120497.
- **Existing records are untouched.** Older unmarked CLI records still hit the existing provenance barrier, so readers treat them exactly as before.
- **Old and new records mix safely in one session.** Accounting sums the counters, and context readers use the newest record's marker (proof turn 2 above ran in an existing session).
- **Upgrade.** Only turns recorded after the update carry turn totals, and nothing needs to run. Rolling back leaves new records readable, because their counters are ordinary usage fields.

## Related

- #148676 targets the same issue. Its current revision uses the same projection for both writers and the same reader change.
  - It also switches live `agentMeta.usage` to the turn total in `cli-run-settlement.ts`.
  - This PR leaves live `agentMeta.usage` on the last call.

Not in scope (possible follow-ups):
- `lastCallUsage` still takes its output count from the stream-start `assistant` event, because `readCliUsage` does not read `message_delta`. This only affects the small output side of the context marker.
- A run with several interim `result` events persists the last segment's total. That undercounts rather than double counts, and the behavior predates this change.
- Live `agentMeta.usage` for CLI runs (reply footer, session store counters, cron run records) still reflects the last call.
- Subscription dollar pricing (#102771).
- Turns whose reply goes out through the message tool, and room-event turns, write no CLI assistant row, so they still add nothing to `usage.cost`.
- Rows whose marker is `unavailable` (for example an aborted Codex turn) keep sizing context and choosing a tier from their counters, as on `main`.

AI-assisted (Claude Code).

## Maintainer simplification

Reviewed the complete diff and the contributing commits at `443a1722ce` before executing the branch. The changes stay within usage accounting, its existing consumers, and regression tests: no new network calls, credential/environment reads, package or lockfile changes, install hooks, or build-configuration changes.

The smallest complete fix is to persist the terminal whole-turn counters, preserve the latest call in `contextUsage`, and keep every context consumer on that marker. The pass preserves mcaldas's commits and implementation:

- Reused the shared `CliTranscriptUsage` contract instead of maintaining an identical local type in the command writer.
- Removed the new Control UI no-marker fallback test: the existing rendered-chat test, “uses the largest prompt for context and aggregates usage, cache, and nested cost,” already exercises that behavior more thoroughly. The distinct whole-turn marker regression remains.
- Kept chat-history forwarding and both web/native consumers: without them, the accounting correction inflates the displayed context size.
- Kept the tiered-pricing guard: a summed prompt cannot reconstruct each request's tier, and applying a higher tier to a sum would introduce incorrect dollar estimates. Flat pricing and sums below the first boundary remain estimated. The same shape-based protection applies to existing Codex rows; no separate backend policy was added.
- Kept rollup version 8 and the adjusted storage-cutover tests: cached versions 6/7 were priced under the old rule and must rebuild. The existing migration still preserves the old cache bytes; the reader correctly declines to treat them as current.
- Kept the small shared `cli-transcript-usage.ts` leaf: both transcript writers need the same projection; importing it from the command writer previously pulled its runtime dependency graph into the runner. There is no competing usage owner to remove.

No additional feature or split-out is needed for these retained pieces; all prevent regressions introduced by persisting totals. The existing “Not in scope” items above remain out of scope.

Line deltas against merge base `035bf8903442` (production includes the native and web consumers):

| | Before pass | After pass |
| --- | ---: | ---: |
| Production | +164 / −44 (net +120) | +165 / −51 (net +114) |
| Tests | +375 / −4 (net +371) | +371 / −4 (net +367) |
| Total | +539 / −48 (net +491) | +536 / −55 (net +481) |

The pass removes 6 net production lines and 4 test lines without removing any distinct regression boundary. GitHub reported the branch mergeable, so no extra merge or rebase was performed.

## Maintainer real-CLI verification

Verified the simplified code at `c8a5bb223bb0130863f2159640faa2adf674ecd6` using a full production build (pueue task 7067), real Claude Code **2.1.300**, and an isolated loopback Gateway launched in the GUI session so the CLI could use its existing login keychain. No stand-in binary was used. The setup and prompts match the main-branch reproduction: one Read-tool turn followed by a plain reply on the same fresh session. The test Gateway was stopped afterward.

These are separate live runs, so model token counts vary between main and PR. The invariant is equality between the CLI's own per-turn sum and the canonical persisted counters within each run.

| Revision / turn | Claude transcript output | Persisted output | Claude transcript cache write | Persisted cache write |
| --- | ---: | ---: | ---: | ---: |
| Main `3f1011275f`, Read (2 calls) | 104 | 1 | 61,090 | 216 |
| Main `3f1011275f`, plain reply (1 call) | 4 | 1 | 425 | 425 |
| PR simplified head, Read (2 calls) | 106 | **106** | 60,587 | **60,587** |
| PR simplified head, plain reply (1 call) | 4 | **4** | 427 | **427** |

PR-head details (Claude transcript assistant records deduplicated by `message.id`):

| Turn | Source | Input | Output | Cache read | Cache write | Total |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| Read | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 4 | 106 | 60,369 | 60,587 | 121,066 |
| Read | Live lastCallUsage | 1 | 1 | 60,369 | 218 | — |
| Plain reply | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 3 | 4 | 60,587 | 427 | 61,021 |
| Plain reply | Live lastCallUsage | 3 | 1 | 60,587 | 427 | — |

- `contextUsage` persisted and returned by **chat.history** is `{state: available, promptTokens: 60588, totalTokens: 60589}` for the Read turn and `{state: available, promptTokens: 61017, totalTokens: 61018}` for the reply. Both prompts equal the native transcript's last-call prompt exactly.
- The Control UI receives the last-call marker, corresponding to **30%** and **31%** of the configured 200,000-token window, rather than sizing the first turn from its 120,960-token aggregate prompt. This was checked through the actual `chat.history` payload; no new browser/native screenshot is claimed.
- Combined `usage.cost` delta: input **7**, output **110**, cache read **120,956**, cache write **61,014**, total **182,087**. All equal the two canonical records and the deduplicated CLI sums.
- The exact reproduction config has no CLI dollar-price entry: dollar totals remain zero and `missingCostEntries` increases by two. This run proves token accounting, not subscription billing or a dollar estimate. The focused tier-pricing tests cover the guard separately.
- The last-call stream-start output count remains 1, as expected for the explicitly out-of-scope `message_delta` issue; it no longer replaces whole-turn output in stored usage.

Validation on the simplified code:
- **208 tests passed across 10 files**, including both transcript writers, real runner wiring, accounting reader, chat projection and rendering, tier pricing, SQLite usage-cache migration, and storage cutover.
- Passed `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`, `pnpm tsgo:ui`, and the matching `test/tsconfig` lanes: agents-root, agents-other, commands, gateway-root, infra, state-logging, ui-chat.
- Passed scoped oxlint and oxfmt, `git diff --check`, `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`.
- The full install/build passed. An initial test invocation before installation found no Vitest; the post-install invocation above passed. The combined validation command reached its overall deadline during the final assertion scan; that scan was rerun alone and passed.
- **Local Swift limitation:** after generating the required Mermaid resources, `swift test --filter ChatContextUsageTests` could not compile because this host's CommandLineTools toolchain lacks the `SwiftUIMacros.StateMacro` plugin. The OpenClawKit package-test CI lane remains responsible for native verification; no local Swift pass is claimed.

Only redacted counters are published here; session identifiers, credentials and raw transcripts are omitted. A fresh ClawSweeper review is requested for this new head; the prior ready review was for `4daf2fecd4`.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…-5 bundle A) (openclaw#172989)

* refactor(ui): remove unused page plumbing and duplicate presentation work

Fold sole-caller Config and Cron adapters into their existing owners, reuse
canonical controller types, and remove unused request arguments and login
selection options. Adopt the complete background mutation receipt instead of
rereading the write; keep authoritative preflight and live ownership checks.

Best-effort tradeoffs accepted: a later background edit in another browser is
reflected by normal preference events or refresh, not an unconditional read of
our own successful write. The introducing feature PR openclaw#168301 does not identify
a human incident requiring that reread. Settled rendering and public contracts
are unchanged; both shipping renderer paths remain intact.

* refactor(ui): consolidate presentation helpers and cached preview inputs

Share point-menu trigger attributes and deletion-first LCS traversal. Remove
an obsolete empty-badge predicate, a one-caller loading facade, and redundant
whole-map translation fallback. Preserve both active Lit and Solid paths,
positioning formulas, diff work budgets, visible text, and rendering.

Best-effort tradeoffs accepted:
- Trust successful synchronous Web Storage writes instead of reading them back.
  Introducing PR openclaw#162428 supplied synthetic storage failures, not a human
  incident where successful setItem silently failed. Nonconforming Storage
  replacements may miss a cache publication until the next refresh.
- Trust immutable message/tool-card identities for cached source previews.
  PR openclaw#148431's in-place mutation assertions were synthetic; production owners
  publish replacement snapshots. Unsupported in-place mutation may leave a
  decoration stale until replacement. Run/frame/origin and external source
  validation remain unchanged.

Net production reduction: 76 lines; tests: 20 lines removed, only synthetic
same-object mutation assertions. Kept config coercion tied to human Safari
report openclaw#13348, along with security, durability, ordinary navigation ownership,
and all active migration paths.

Focused proof: 73 boot/cache/diff tests, 82 menu tests, 46 badge/assistant tests,
20 i18n tests, 8 browser details tests, 3 lint-suppression tests; UI typecheck,
formatting, stylesheet lint and CSS declaration parity passed.

Known inherited local check failure: environment-variable count is 455 against
budget 454, independently reproduced against clean HEAD/index. Its counted
source roots exclude UI. No budget or unrelated source changes made.

* refactor(ui): remove obsolete presentation compatibility and styling

Use the native Popover capability required by the Control UI bootstrap
instead of retaining old-engine in-flow fallbacks. Keep native overlay
occlusion and all real connection/navigation ownership.

Remove retired sidebar style hooks and share identical question-panel
declarations. Supported browsers render identically; no user-visible
copy, feature, renderer selection, config, protocol, or storage change.

Best-effort tradeoffs accepted

- Old engines without Popover support, or invalid direct popover mounts,
  no longer receive an in-flow menu fallback. The fallback came from
  openclaw#105598 as generic compatibility, not a human incident; openclaw#168595 made
  native Popover support a required bootstrap capability. Invalid direct
  mounts now fail clearly rather than silently changing layering.

Deeper coverage and retained candidates are recorded in the requested
task-local y03 ledger for coordinator bundling.

Branch total: 123 net production LOC removed (+114/-237), excluding tests,
fixtures, generated files and declarations. Below the 500-line campaign
floor after the deeper components/app/lib/styles and lead-owned owner pass;
push branch-only for bundling.

* refactor(gateway): reuse server method owners

Consolidate duplicate catalog response handling,
optional catalog reads, pairing resolution, requester assertions and system
agent transcript persistence. Carry prepared pairing and actor facts instead
of probing or re-reading them. Remove redundant cache-generation and internal
receipt checks; retain security, durability, pagination and resource bounds.

Best-effort tradeoffs accepted:
- Pairing captures its selected adapter once. Repeated internal checks added
  by openclaw#112401 guarded hypothetical in-place plugin mutation, not a reported
  incident. Such a mutation now leaves this request on its selected adapter;
  later requests discover the current registration.
- Channel identity RPCs trust the canonical mutation result instead of
  repeating the action/kind assertion introduced in openclaw#161284. No human incident
  justified the redundant adapter assertion; live mutation authority remains
  with the state owner.

No user-facing feature, protocol/config/persistence shape, schema, dependency,
test coverage or standalone session memory backend changes.

Net production reduction: 100 lines (179 added / 279 deleted).
Type-aware lint, targeted production types, formatting, runtime cycles (zero),
SDK surface, suppression audit and independent P2 review pass. Gateway focused
suites and the full static import graph remain incomplete on the loaded host;
retain these proof gaps for the coordinator bundle rather than claiming green.

* refactor(gateway): trust prepared server method inputs

Remove a test-only config cache-reset wrapper, duplicate internal selection
and channel-support checks, an unused session-file metadata fallback, and
duplicate usage target shapes. Carry transcript delivery facts from their
first parsing pass. Keep all network validation, effect authority, transcript
durability, current update policy and standalone session memory machinery.

Best-effort tradeoffs accepted:
- Internal agent updates trust the selection-shape check at their sole
  production caller, agents.update. The duplicate originated in the Models
  agent-selection feature openclaw#150224; the same boundary check still rejects
  invalid user input. Live runtime choice validation stays at the effect.
- Channel start support is checked once at the synchronous request boundary.
  The inner check from openclaw#67815 / openclaw#167159 cannot observe a different plugin
  without unsupported synchronous mutation; the boundary guard remains.
- Workspace-root readers require caller-prepared metadata: both production
  consumers already provide it. The unused fallback from openclaw#161747 is deleted,
  not the Phase E backend or any factory. A future invalid internal caller
  gets a clear error instead of starting another metadata read.
- Update handlers trust the required getRuntimeConfig contract instead of
  falling back to a global schedule for an invalid context. Keep openclaw#158301's
  real scheduler-policy incident fix and its post-await current-config read.
- Usage summaries trust the canonical required target identity from openclaw#169660;
  the first-instance fallback served no production caller. The integration
  fixture now supplies that identity with all original assertions retained.

No public schema/config/SDK/protocol or persisted shape changes. The config
tests call the same canonical invalidators directly; no coverage is removed.

Follow-up removes 54 net production lines; branch total removes 154. Targeted
types (including MCP consumers), retained-file type-aware lint, formatting,
zero runtime import cycles, suppression audit and independent P2 review pass.
Gateway behavioral suites remain incomplete after a loaded-host startup run
was stopped at about ten minutes (exit 143). The prior full static-graph gap
remains pending for the coordinator bundle; no new production edge is added.

* refactor(ui): consolidate page lifecycle and config plumbing

Reuse the existing controller host, subscription and plugin-icon owners;
share cloud-worker config edit wiring and Usage query comparisons. Remove
the unused Usage detail predicate and duplicate model loading flag.

Retire the Web Awesome-era picker hiding fence now that native Popover
owns generation-bound close completion. Keep both rendering paths,
draft recovery, user-intent checks and dispatch-time write authority.
Settled rendering is unchanged. Net production reduction: 210 lines.

Best-effort tradeoffs accepted:
- Failed channel artwork retries on the next channel refresh rather than
  a queued trailing ensure. openclaw#131511 was a synthetic ordering regression;
  the human-reported owning-plugin bug openclaw#144152 remains covered.
- Picker triggers may reopen during closing. openclaw#126032's fence came from
  CI/synthetic overlap, not a human incident; openclaw#171441 transferred lifecycle
  ownership to native Popover, which ignores superseded completions.

Focused proof: 281 tests passed, including Chromium/WebKit overlay lifecycle
and responsive placement controls. Independent P0-P2 review: scoped-clean.
Final UI production and UI-pages test typechecks passed; suppression tests 3/3.
Scoped lint passed after a mechanical no-lonely-if fix.
Runtime and static import cycles: zero. No visual or locale changes.
The global environment-name budget is inherited at 455/454 on both the
untouched base and origin/main; none of its counted source roots changed.

* refactor(ui): remove unused new-session hiding selector

* refactor(gateway): retain legacy catalog and update handler contracts

Withdraw two wave-5 cleanups after focused CI failures and bounded isolated replay. Preserve the existing scalar-read concurrency and update-status handler contract. Tighten task-suggestions assertion allowance to match the cleaned source.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…openclaw#148682)

Related: openclaw#148603 (this PR fixes the whole-turn accounting; the issue's final per-call output count is listed under Not in scope below)

## What Problem This Solves

Fixes: session usage, `usage.cost`, and the Usage page count only the last model call (with its stream-start output count) for Claude CLI turns. Turns that make several model calls, such as tool-using turns, are therefore heavily undercounted.

## User Impact

User impact: Claude CLI turns now record the whole turn's tokens in the session transcript, so usage reports and anything built on them (cost estimates, budget alerts) match what Claude Code reports.

- Context-window sizing, preflight compaction, and memory-flush gating keep using the latest model call.
- Chat context displays (Control UI message footer, iOS/macOS chat) keep showing the latest call's context size.
- Turns recorded before this change keep their existing counts.
- No config, schema, or migration change (see compatibility below).

## Why This Change Was Made

Claude Code's terminal `result` event already carries whole-turn usage, and the stream parser keeps it as `diagnosticUsage` (openclaw#120100). Both CLI transcript writers still persisted the last call.

- **Both writers:** they now persist the turn total as the usage counters. `contextUsage` is derived from the last call through one shared helper (`resolveCliTranscriptUsage`), so every context reader still sizes the window from the latest call.
- **Reply-path writer:** it adds that context marker only when the backend reports a turn total separately. Other CLI backends keep their unmarked records, which context readers already refuse to treat as a fresh context size (openclaw#120497).
- **Memory flush and preflight:** their transcript snapshot now takes the last completion's output from the context marker instead of the turn counters.

- **Chat context displays:** chat history now forwards an available, coherent `contextUsage` marker with assistant usage. The Control UI message footer and the native context control and footer size context from it. Rows without an available marker keep sizing from the counters, as before.
- **Tiered pricing:** summed tokens cannot recover each request's tier. `usage.cost` now leaves a turn unpriced when its counters exceed the marker's prompt and their sum reaches past the lowest tier.
  - A sum inside the lowest tier keeps every call there, so it is still estimated. Flat pricing is unchanged.
  - The rule reads the usage shape, so it also applies to Codex harness rows whose summed prompt crosses a tier boundary.
  - `USAGE_COST_ROLLUP_VERSION` moves to 8 so cached usage summaries rebuild with the new rule. `main` is at 7 since openclaw#169660, which also carries version-6 summaries forward; both were priced under the old rule, so this PR accepts only version 8. The schema cutover still moves version-6 rows, and readers rebuild them.

Live `agentMeta.usage` / `lastCallUsage` and the context-engine hook message are unchanged.

## Evidence

### Real behavior proof (after the fix, live OpenClaw)

Setup:
- A production OpenClaw 2026.9.2 gateway with Claude Code 2.1.263 on a Claude subscription.
- This PR's three production edits applied as a local backport, with identical logic, because the host runs the published build.
- Output is redacted to usage counters; the session id is replaced.

Two non-delivering `openclaw agent` turns ran on one dedicated session:
- Turn 1 makes two model calls: a Read tool call, then the reply.
- Turn 2 reuses the existing session.

```text
$ openclaw agent --agent main --session-key agent:main:<proof> --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."

# live run metadata (unchanged by this PR)
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# persisted assistant transcript records, read back from the session's SQLite transcript
turn 1  usage {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
               contextUsage {state available, promptTokens 74920, totalTokens 74921}}
turn 2  usage {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
               contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# Claude Code's own transcript for the bound CLI session (deduplicated by message id)
turn 1  model calls 2  sum input 4 / output 89 / cacheRead 74593 / cacheWrite 74918  last-call prompt 74920
turn 2  model calls 1  sum input 2 / output 3  / cacheRead 74918 / cacheWrite 102    last-call prompt 75022

# usage.cost for the agent's day, read back before and after the two proof turns (rollup refresh)
before  totalTokens 404634  output 13   cacheWrite 45337   totalCost 0.3800  missingCostEntries 0
after   totalTokens 629263  output 105  cacheWrite 120357  totalCost 0.8764  missingCostEntries 0
delta   totalTokens +224629 (= 149604 + 75025)  output +92 (= 89 + 3)  cacheWrite +75020 (= 74918 + 102)
```

What this shows:
- The persisted counters equal Claude Code's per-turn totals exactly.
- The usage report's delta equals the two persisted records. The dollar figure comes from a locally configured `claude-cli` price entry; this PR does not change pricing.
- `contextUsage.promptTokens` equals the last call's prompt.
- Without this change, turn 1 would have been persisted as output 1 / cacheWrite 325.
- A scheduled heartbeat turn on the same gateway also persisted its final output count (9) and not the stream-start value (1): `usage {input 2, output 9, cacheRead 69062, cacheWrite 10885, totalTokens 79958, contextUsage {state available, promptTokens 79949, totalTokens 79950}}`.

### Real behavior proof for the chat display and pricing follow-ups

Setup:
- OpenClaw built from this branch at 4f6d8a8, run as an isolated local gateway (own state directory, loopback only, channels off).
- Both turns ran with `openclaw agent` through the real `claude-cli` backend. The `claude` binary on `PATH` was a stand-in that emits the usage of the live turns above as Claude Code stream records: one `assistant` record per model call and the terminal `result`. No model call was made.
  - The first call's record is derived: turn total minus the last call.
  - `qa/scenarios/channels/telegram-claude-cli-compaction-final-priority.yaml` uses the same stand-in technique.
- The runner, transcript writer, chat history, `usage.cost` and the Control UI are the built product with no proof-only changes. The only stand-in is the `claude` binary.
- **Before** is this branch with the source changes of fa8ed7c and db6439b reverted and rebuilt. That is the state reviewed at 9366812: whole-turn counters stored, displays and pricing not yet following the marker. **After** is the head.
- The turns ran once, on the before build. The after build read the same session from the same state directory. The transcript writer is identical in both builds.
- Proof configuration: a 200,000-token context window, and a `claude-cli/claude-sonnet-4-5` price entry with a tier boundary at 100,000 prompt tokens (`$3 / $15 / $0.30 / $3.75` per million tokens below it, `$6 / $22.50 / $0.60 / $7.50` above). Each call of turn 1 stays below the boundary (74,595 and 74,920 prompt tokens). Their sum (149,515) crosses it.

```text
$ openclaw agent --agent main --session-key agent:main:proof --json \
    --message "Use the Read tool to read IDENTITY.md in your workspace, then reply with only the number of lines in that file."
$ openclaw agent --agent main --session-key agent:main:proof --json --message "Reply with only the word ok."

# run metadata from the stand-in, equal to the live run above
turn 1  lastCallUsage    {input 2, output 1, cacheRead 74593, cacheWrite 325}
        diagnosticUsage  {input 4, output 89, cacheRead 74593, cacheWrite 74918}
turn 2  lastCallUsage    {input 2, output 1, cacheRead 74918, cacheWrite 102}
        diagnosticUsage  {input 2, output 3, cacheRead 74918, cacheWrite 102}

# openclaw gateway call chat.history: assistant usage as the Control UI and the apps receive it
before  turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025}
after   turn 1  {input 4, output 89, cacheRead 74593, cacheWrite 74918, totalTokens 149604,
                 contextUsage {state available, promptTokens 74920, totalTokens 74921}}
        turn 2  {input 2, output 3, cacheRead 74918, cacheWrite 102, totalTokens 75025,
                 contextUsage {state available, promptTokens 75022, totalTokens 75023}}

# openclaw gateway call usage.cost --params '{"days":1}': totals
before  totalTokens 224629  totalCost 0.6315762  missingCostEntries 0
after   totalTokens 224629  totalCost 0.0229089  missingCostEntries 1
        missingCostByModel {"claude-cli/claude-sonnet-4-5": 1}
```

What this shows:
- **`usage.cost`, before:** turn 1 is priced from its summed prompt at the upper tier. That is `$0.6086673` of the total; the rest is turn 2. Both of its calls sit in the lower tier, where the same tokens cost about `$0.3047`.
- **`usage.cost`, after:** turn 1 is left unpriced and counted in `missingCostEntries`. Turn 2 is a single call and keeps its estimate, `$0.0229089`.
- Token totals are the same in both builds (224,629 = 149,604 + 75,025).
- The before build stored its usage rollup under version 6. On the head, the first `usage.cost` read reported it stale and refreshing. The next read, 3 s later, was fresh with the new totals, and the stored rollup carries version 7. No manual step was needed.

**Control UI** (web): the usage details of turn 1's reply in the chat view. They show when the message footer is hovered.

Before: `75% ctx`

![Control UI message footer before: 75% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-before.png)

After: `37% ctx`

![Control UI message footer after: 37% ctx](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/web-after.png)

**Native** (iOS): the message footer (top) and the context control's menu (bottom).

Before: `75% ctx` with a warning, and "149.6k of 200.0k tokens used"

![iOS chat before: 75% ctx, 149.6k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-before.png)

After: `37% ctx`, and "74.9k of 200.0k tokens used"

![iOS chat after: 37% ctx, 74.9k of 200.0k tokens used](https://raw.githubusercontent.com/mcaldas/openclaw/3dfa8d6f0e5f2621859385790d6ed887ea566fbd/native-after.png)

- The iOS app target is a Debug build of `apps/ios` on an iPhone 17 simulator (iOS 26.4.1), from a reduced project without the watch app, in the app's screenshot fixture mode (`--openclaw-screenshot-mode`).
- A local, uncommitted patch to the fixture transport seeds the chat history with turn 1's usage row and a 200,000-token window. The chat text and the model label (`claude-sonnet-4-6`) are the fixture's own.
- Both runs receive the same history payload, marker included. Before reverts the Swift changes of fa8ed7c, so only the app code differs.
- The macOS app renders the same shared `OpenClawChatUI` views from `apps/shared/OpenClawKit`. It was not captured separately.
- The screenshots hold proof-session and fixture content only: no endpoints, addresses, keys or personal data.

### Tests and checks

Regression tests. Each one fails on `main` and passes with this change:
- `cli-runner.turn-usage.test.ts` › "persists the terminal Claude turn usage for a multi-call turn"
  - Runs a turn whose parsed output carries the last call and a separate turn total through `runPreparedCliAgent`, then reads the persisted transcript back.
  - Before: input 2 / output 1 / cacheRead 27,376.
  - After: 6 / 77 / 54,631, with `contextUsage` at the last call's 27,378 prompt tokens.
- `transcript-persistence.test.ts` › "persists the terminal CLI turn usage while keeping last-call context"
- `session-transcript-readers.test.ts` › "sizes CLI output from the context marker when counters cover the whole turn"
  - Before: 30,000 output tokens.
  - After: 2,000 output tokens.

- `chat-display-projection.test.ts` › "forwards an available context marker with assistant usage"
- `chat-message-timestamp.test.ts` (new file) › "sizes context from the marker when usage counters cover a whole turn"
  - Before: 75% ctx for a two-call turn in a 200k window.
  - After: 37% ctx.
- `ChatContextUsageTests.swift` › "whole-turn counters report the latest call's context marker" and "usage footer sizes context from the marker and keeps whole-turn counters"
  - Before: 149,000 tokens and "98% ctx".
  - After: 75,000 tokens and "49% ctx".
- `session-cost-usage-pricing.test.ts` (new file) › "leaves a multi-call turn unpriced when its sum crosses a tier" and "prices a multi-call turn whose sum stays in the lowest tier"

Guard test:
- `cli-run-transcript.test.ts` › "keeps CLI usage unmarked when the backend reports no separate turn total"

Suites and checks (branch merged with `main` at 05af73b):
- Merge history: the merge at a944978 had three conflicts, all code `main` had moved: the transcript accounting reader now lives in `session-transcript-accounting-policy.ts`, and the chat footer's `extractGroupMeta` in the Solid `chat-message-timestamp-view.tsx`; this PR's two edits were re-applied there unchanged. The merge at 6923fd4 was clean. The merge at 05af73b had one import conflict in `chat-message-timestamp-view.tsx`; both helpers are kept.
- openclaw#120008 (usage reports marked unavailable) landed in three files this PR also changes: the chat history projection, the usage pricing estimate and the Control UI footer. Both changes are kept side by side: an unavailable usage report is skipped before this PR's context marker and tier guard are read.
- On the merged head, `pnpm test <files> --maxWorkers=4` passed 2,239 tests across 171 files:
  - every test file in `src/agents/cli-runner/` and `src/agents/command/` (live and e2e files excluded);
  - the `cli-runner.*`, `cli-output*`, `usage*`, `agent-runner-memory*`, `session-transcript-readers*`, `chat-display-projection*`, `session-cost-usage*` and `usage-format*` suites;
  - the Control UI `chat-message*` suites, including the six chat browser tests;
  - the usage cache suites (`session-cost-usage-cache.*`), `doctor-usage-cost-cache.test.ts` and the schema cutover test `openclaw-agent-db.storage-migration.test.ts`.
- The version 8 move updates two cutover tests from openclaw#169660: a migrated version-6 report is still moved (the cache test checks it arrives byte for byte), but no longer decodes as current (`session-cost-usage-cache.sqlite.test.ts`, `openclaw-agent-db.storage-migration.test.ts`). Our earlier fixture change in the cutover test (4f6d8a8) is replaced by `main`'s stored version 6.
- CI on the first merge failed two of this PR's new tests and one existing e2e test:
  - `cli-runner.turn-usage.test.ts` and the guard test in `cli-run-transcript.test.ts` relied on runtime config being loaded on demand, which openclaw#169714 removed. Without config the persistence wrapper wrote no row, so both saw an empty transcript. Both now pass `config: {}`, as openclaw#169714 did for the neighbouring tests. Both fail on the new merge without that change and pass with it.
  - `cli-runner.fault-sequences.e2e.test.ts` › "dispatches bridge mode through one fresh CLI child and bypasses the native run budget" fails with "Runtime config is not prepared" on this head, and identically with all of this PR's source changes reverted (tests kept). It comes from `main`, not from this PR.
  - Left out of the local run: `session-cost-usage-cache.creation-race.test.ts`, new on `main`, fails on this Mac with "state … is undergoing offline maintenance", identically with this PR's source changes reverted.
- Test cost of the four added tests, from `pnpm test <file> --maxWorkers=1` on an M-series laptop:
  - `cli-runner.turn-usage.test.ts` (new file): 2.2 s for the test, 11 s for the file. It runs the real runner and transcript store, because that is the only layer that proves the turn total is wired from the runner into the writer.
  - `transcript-persistence.test.ts`: 63 ms for the added test.
  - `session-transcript-readers.test.ts`: 144 ms for the added test.
  - `cli-run-transcript.test.ts`: 201 ms for the added test.
- Gates re-run on the merged head: `oxfmt --check` and oxlint on the changed files, `tsgo:core`, `tsgo:ui`, `tsgo:core:test`, and the line-cap, assertion-safety and mock-export ratchets. `git diff --check` is clean.
- Gates last run before the merge of `main`: import cycles (0 runtime, 0 madge), dead-code exports, deprecated API usage, `lint:ui:i18n`, stylelint on the changed UI files, and the max-lines and test-timeout-race ratchets. The SQLite-worker ratchet last ran before the chat-display and pricing commits, which add no database code.
- The three regression tests moved out of `cli-runner.reliability.test.ts`, `attempt-execution.cli.test.ts` and `agent-runner-memory.test.ts`, which are over the line cap and may not grow.
- Chat display and pricing follow-up:
  - `swift test --package-path apps/shared/OpenClawKit --filter ChatContextUsageTests` passed 14 tests on the merged head; SwiftFormat and SwiftLint at the pinned versions report nothing on the changed files.
  - The added TypeScript tests take 0 to 2 ms each. Each new regression test fails with its source change reverted.
  - The iOS app target was built (Debug, simulator, reduced project without the watch app) for the screenshots above. Not run locally: the full OpenClawKit suite, the full iOS project and the macOS app build.

Live Claude Code semantics (stream-json, `--include-partial-messages`):
- A tool-using turn's `result` reported 77 output tokens, while its two `assistant` events carried 15 and 1.
- In one warm stdio process, each turn's `result.usage` covered only that turn (78 output tokens each time). Only `total_cost_usd` accumulates, so persisting `result` usage does not double count warm sessions.
  - Rechecked on Claude Code 2.1.293: two turns in one process reported cache writes of 28,094 and then 5,619, while `total_cost_usd` rose from 0.0057 to 0.0072.

## Upgrade and data compatibility

- **No schema, migration, or config change.** The persisted assistant `usage` keeps its existing shape. `contextUsage` is an existing optional field that the agent-command writer has persisted since openclaw#120497.
- **Existing records are untouched.** Older unmarked CLI records still hit the existing provenance barrier, so readers treat them exactly as before.
- **Old and new records mix safely in one session.** Accounting sums the counters, and context readers use the newest record's marker (proof turn 2 above ran in an existing session).
- **Upgrade.** Only turns recorded after the update carry turn totals, and nothing needs to run. Rolling back leaves new records readable, because their counters are ordinary usage fields.

## Related

- openclaw#148676 targets the same issue. Its current revision uses the same projection for both writers and the same reader change.
  - It also switches live `agentMeta.usage` to the turn total in `cli-run-settlement.ts`.
  - This PR leaves live `agentMeta.usage` on the last call.

Not in scope (possible follow-ups):
- `lastCallUsage` still takes its output count from the stream-start `assistant` event, because `readCliUsage` does not read `message_delta`. This only affects the small output side of the context marker.
- A run with several interim `result` events persists the last segment's total. That undercounts rather than double counts, and the behavior predates this change.
- Live `agentMeta.usage` for CLI runs (reply footer, session store counters, cron run records) still reflects the last call.
- Subscription dollar pricing (openclaw#102771).
- Turns whose reply goes out through the message tool, and room-event turns, write no CLI assistant row, so they still add nothing to `usage.cost`.
- Rows whose marker is `unavailable` (for example an aborted Codex turn) keep sizing context and choosing a tier from their counters, as on `main`.

AI-assisted (Claude Code).

## Maintainer simplification

Reviewed the complete diff and the contributing commits at `443a1722ce` before executing the branch. The changes stay within usage accounting, its existing consumers, and regression tests: no new network calls, credential/environment reads, package or lockfile changes, install hooks, or build-configuration changes.

The smallest complete fix is to persist the terminal whole-turn counters, preserve the latest call in `contextUsage`, and keep every context consumer on that marker. The pass preserves mcaldas's commits and implementation:

- Reused the shared `CliTranscriptUsage` contract instead of maintaining an identical local type in the command writer.
- Removed the new Control UI no-marker fallback test: the existing rendered-chat test, “uses the largest prompt for context and aggregates usage, cache, and nested cost,” already exercises that behavior more thoroughly. The distinct whole-turn marker regression remains.
- Kept chat-history forwarding and both web/native consumers: without them, the accounting correction inflates the displayed context size.
- Kept the tiered-pricing guard: a summed prompt cannot reconstruct each request's tier, and applying a higher tier to a sum would introduce incorrect dollar estimates. Flat pricing and sums below the first boundary remain estimated. The same shape-based protection applies to existing Codex rows; no separate backend policy was added.
- Kept rollup version 8 and the adjusted storage-cutover tests: cached versions 6/7 were priced under the old rule and must rebuild. The existing migration still preserves the old cache bytes; the reader correctly declines to treat them as current.
- Kept the small shared `cli-transcript-usage.ts` leaf: both transcript writers need the same projection; importing it from the command writer previously pulled its runtime dependency graph into the runner. There is no competing usage owner to remove.

No additional feature or split-out is needed for these retained pieces; all prevent regressions introduced by persisting totals. The existing “Not in scope” items above remain out of scope.

Line deltas against merge base `05af73b39e6f` (production includes the native and web consumers):

| | Before pass | After pass |
| --- | ---: | ---: |
| Production | +164 / −44 (net +120) | +165 / −51 (net +114) |
| Tests | +375 / −4 (net +371) | +371 / −4 (net +367) |
| Total | +539 / −48 (net +491) | +536 / −55 (net +481) |

The pass removes 6 net production lines and 4 test lines without removing any distinct regression boundary. GitHub reported the branch mergeable, so no extra merge or rebase was performed.

## Maintainer real-CLI verification

Verified the simplified code at `c8a5bb223bb0130863f2159640faa2adf674ecd6` using a full production build (pueue task 7067), real Claude Code **2.1.300**, and an isolated loopback Gateway launched in the GUI session so the CLI could use its existing login keychain. No stand-in binary was used. The setup and prompts match the main-branch reproduction: one Read-tool turn followed by a plain reply on the same fresh session. The test Gateway was stopped afterward.

These are separate live runs, so model token counts vary between main and PR. The invariant is equality between the CLI's own per-turn sum and the canonical persisted counters within each run.

| Revision / turn | Claude transcript output | Persisted output | Claude transcript cache write | Persisted cache write |
| --- | ---: | ---: | ---: | ---: |
| Main `05d13dc7da`, Read (2 calls) | 104 | 1 | 61,090 | 216 |
| Main `05d13dc7da`, plain reply (1 call) | 4 | 1 | 425 | 425 |
| PR simplified head, Read (2 calls) | 106 | **106** | 60,587 | **60,587** |
| PR simplified head, plain reply (1 call) | 4 | **4** | 427 | **427** |

PR-head details (Claude transcript assistant records deduplicated by `message.id`):

| Turn | Source | Input | Output | Cache read | Cache write | Total |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| Read | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 4 | 106 | 60,369 | 60,587 | 121,066 |
| Read | Live lastCallUsage | 1 | 1 | 60,369 | 218 | — |
| Plain reply | CLI sum = live diagnosticUsage = SQLite usage = usage.cost delta | 3 | 4 | 60,587 | 427 | 61,021 |
| Plain reply | Live lastCallUsage | 3 | 1 | 60,587 | 427 | — |

- `contextUsage` persisted and returned by **chat.history** is `{state: available, promptTokens: 60588, totalTokens: 60589}` for the Read turn and `{state: available, promptTokens: 61017, totalTokens: 61018}` for the reply. Both prompts equal the native transcript's last-call prompt exactly.
- The Control UI receives the last-call marker, corresponding to **30%** and **31%** of the configured 200,000-token window, rather than sizing the first turn from its 120,960-token aggregate prompt. This was checked through the actual `chat.history` payload; no new browser/native screenshot is claimed.
- Combined `usage.cost` delta: input **7**, output **110**, cache read **120,956**, cache write **61,014**, total **182,087**. All equal the two canonical records and the deduplicated CLI sums.
- The exact reproduction config has no CLI dollar-price entry: dollar totals remain zero and `missingCostEntries` increases by two. This run proves token accounting, not subscription billing or a dollar estimate. The focused tier-pricing tests cover the guard separately.
- The last-call stream-start output count remains 1, as expected for the explicitly out-of-scope `message_delta` issue; it no longer replaces whole-turn output in stored usage.

Validation on the simplified code:
- **208 tests passed across 10 files**, including both transcript writers, real runner wiring, accounting reader, chat projection and rendering, tier pricing, SQLite usage-cache migration, and storage cutover.
- Passed `node scripts/run-tsgo.mjs -p tsconfig.core.json --noEmit`, `pnpm tsgo:ui`, and the matching `test/tsconfig` lanes: agents-root, agents-other, commands, gateway-root, infra, state-logging, ui-chat.
- Passed scoped oxlint and oxfmt, `git diff --check`, `check:test-timeout-race-ratchet --base origin/main`, `check:test-mock-exports`, and `check:assertion-safety`.
- The full install/build passed. An initial test invocation before installation found no Vitest; the post-install invocation above passed. The combined validation command reached its overall deadline during the final assertion scan; that scan was rerun alone and passed.
- **Local Swift limitation:** after generating the required Mermaid resources, `swift test --filter ChatContextUsageTests` could not compile because this host's CommandLineTools toolchain lacks the `SwiftUIMacros.StateMacro` plugin. The OpenClawKit package-test CI lane remains responsible for native verification; no local Swift pass is claimed.

Only redacted counters are published here; session identifiers, credentials and raw transcripts are omitted. A fresh ClawSweeper review is requested for this new head; the prior ready review was for `4daf2fecd4`.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant