Skip to content

fix(usage): retain reset history and unify accounting - #131667

Merged
steipete merged 3 commits into
mainfrom
codex/usage-owner-refactor
Aug 28, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/usage-owner-refactor

Conversation

@steipete

@steipete steipete commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #128803 (preserving agent ownership for matching session IDs).

What Problem This Solves

Fixes an issue where the Usage page loses a session's historical usage immediately after reset, before the new instance has a transcript. The same accounting flow also had drift between aggregate totals, filtered UI exports, and conversation details: fleet configuration changes could reuse old totals, filtered results dropped missing-price attribution, and detail logs could disagree with the canonical pricing rules.

Why This Change Was Made

Session selection now owns the agent-scoped current/history join and passes selected instances to batched loading. Historical discovery selects its recorded canonical family even when its current transcript is empty. Each instance is assigned once: a direct current owner takes precedence over historical references, and unresolved historical aliases remain independent instances. Discovery supplies the actual SQLite or retained JSONL source to loading; storage is not guessed from the current instance. Independent agents with identical session IDs remain independent. No lineage is inferred beyond the stored family IDs.

The Gateway and Control UI now share one pure accumulator and canonical total arithmetic. Conversation logs reuse the same token, timestamp, and price parser as summaries and charts. Calendar resolution, bounded result caching, session selection, and batched loading have separate owners; the old duplicate paths and two oversized-file exemptions are removed. Both result caches require configuration identity.

No configuration options, protocol shape, database schema, persistence semantics, dependencies, or provider runtime behavior change. Existing file-backed transcript artifacts remain readable. Equal-cost model/provider rows now use the Gateway's token-count tie-breaker consistently in filtered UI results.

User Impact

Historical lineage remains visible after reset. Fleet changes invalidate aggregate cost results. Filtering and JSON exports retain which models have missing prices. Detail logs agree with summary pricing, including tiered rates, unknown pricing, and explicitly provider-billed zero cost.

Real-state regressions retain 30 historical tokens plus 100 from another agent reusing an ID. A retained direct run owns its 10 tokens separately, leaving 20 in the reset family and 130 overall; mixed JSONL/SQLite history also retains all 130.

Evidence

Before-fix reproductions on the pinned Vitest 4.1.11 fail at the actual boundaries: stale fleet totals; three missing-price UI aggregate/export assertions; four log-pricing cases; and a real SQLite reset family omitted from the Gateway response. Candidate tests cover the same cases, sibling archive behavior, cache refresh/eviction, aliases, date/time-zone boundaries, weighted latency, and pre-limit aggregates.

Validation: 99 Gateway usage tests, 73 accounting/pricing tests, and 58 Control UI tests passed (230 total). The full build and Control UI asset/performance gates passed before the final family-source adjustments; those adjustments passed the Gateway selection tests and type checks. Exact-head CI validates the final build before merge. Independent Codex review is clean (no actionable P0–P2 findings); repository changed checks, final Gateway type checks, and formatting passed. Initial CI run33155908560 caught two type-import cycles and a test file two lines over its cap. The follow-up removes the import cycles at their type owners and deletes obsolete fixture setup, with no exemptions. Both failed checks pass locally, all50 affected tests pass, and the repair also has clean independent review. Run33156849140 then identified six unused type re-exports left in the former barrel; those are removed. Production/full-tree/script unused-export scans and core typecheck now pass, with another clean independent review of that type-only deletion.

Real Gateway + Chromium proof ran on Blacksmith Testbox tbx_01m13nb58x9hbrfedxjwnytnvb (workflow lease). The original baseline bccb649077f086a4935c8f2473b7a72656f1d5a1 fails the reset case because the named row is absent. The usage behavior candidate passes both owner/reset cases (2/2); the reset case completed in 1.85 seconds. The lease was stopped after proof. Local browser attempts stalled during startup under shared host load; the clean Testbox run used the normal timeouts, without relaxing assertions. This exercises a real Gateway and browser with synthetic stored transcripts, not a live model or Telegram account.

Before: reset hides the named family After: both owners remain visible
Baseline missing the named session Candidate retaining the named session

Usage behavior candidate browser recording: the reset case passed on Testbox tbx_01m13qm07s8bqv13qmyk4vydxv (workflow lease). Recording adds only Playwright recordVideo to the existing test context; assertions and product source are unchanged. The first recording attempt lacked Playwright FFmpeg; installing that recorder dependency on the disposable box fixed the setup failure. The video was inspected before upload, and the lease was stopped.

usage-refactor-proof.mp4

Production: 266 fewer lines after accounting for the extracted modules; tests: +571 lines; tooling/docs: -2 lines. The 1,640-line handler is now 388 lines. No oversized-file baseline is increased; two exemptions are removed.

Focused proof commands
OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/gateway/server-methods/usage.sessions-usage-owner-attribution.integration.test.ts src/gateway/server-methods/usage.sessions-usage.test.ts src/gateway/server-methods/usage.sessions-usage-owner-attribution.test.ts src/gateway/server-methods/usage.sessions-usage-cache.test.ts src/gateway/server-methods/usage.cost-usage-cache.test.ts src/gateway/server-methods/usage.test.ts
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts
pnpm build

The browser command ran through the repository Crabbox wrapper on the Testbox above. Regression tests were demonstrated failing before each owner-boundary repair, not only added after the fix.

The separate conflicting-scope request validation issue #125268 already has PR #125269; this follow-up does not duplicate that RPC contract change.

CI run 33157421585 passed every lane except the unchanged Chat disclosure scrolling test, which timed out on both attempts. Current main had already fixed that same test race in #131622 by binding deferred recovery to a still-mounted row. This branch was rebased onto 4ec40f190d4580dad0c5d4dc5d111400ef12a60c to reuse that landed fix; git range-diff confirms all three usage commits are patch-identical. Final head 878b2f0a036ed1579f5c0989977e818523ea5706 receives fresh CI. The screenshots/video above precede the mechanical type cleanup and rebase; final-head CI supplies the refreshed build and browser gates.

Refreshed real-flow proof on head 878b2f0a036ed1579f5c0989977e818523ea5706: the hosted Gateway/Chromium job passed both owner/reset cases, 2/2, in 25.96 seconds total; the empty-current reset case itself took 2.04 seconds. This addresses the latest ClawSweeper Rank-up request for after-fix proof. Its attempt expired while waiting 30 seconds for terminal output and showed only Vitest startup, without a failing product assertion. The completed hosted run and inspected Testbox recording provide the missing terminal and browser evidence. The inherited Chat disclosure shard also passes on this head.

The latest ClawSweeper re-review on this exact head failed before either case ran: /usr/bin/chromium-browser aborted during browserType.launch (SIGABRT; both cases skipped). That is browser setup failure, not a failed usage assertion. The final-head hosted Gateway/Chromium job linked above completed both cases successfully, and the inspected recording remains attached. This supplies the requested real-flow evidence without weakening the product tests or treating the failed sandbox run as a pass.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete steipete self-assigned this Aug 28, 2026
@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 maintainer Maintainer-authored PR labels Aug 28, 2026
@steipete
steipete marked this pull request as ready for review August 28, 2026 08:34
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 28, 2026
@clawsweeper

clawsweeper Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 28, 2026, 5:44 AM ET / 09:44 UTC.

ClawSweeper review

What this changes

The PR restructures Gateway and Control UI usage reporting so reset-session history remains visible and cost/token totals share one accounting path.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 2 items remain

The patch appears correct and remains necessary: current main can suppress discovered reset history when the new current session is empty, while the branch retains that history through ownership-aware selection and loading.

Priority: P2
Reviewed head: 878b2f0a036ed1579f5c0989977e818523ea5706

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main defect: Family-mode discovery suppresses a discovered historic transcript whenever the same agent-qualified identity is in stored family IDs, assuming a current row will load it; an empty reset current transcript leaves no row to display the history.
Selection repair: The branch resolves family ownership by agent-qualified identity, preserves discovered concrete sources, and selects a recorded family once even when its current transcript is absent.
Reset lineage producer: Reset lineage records family keys and IDs during session-entry transitions and preserves them in the reset service, giving selection an authoritative family relationship.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts --reporter=verbose

Result: FAIL (failed) — step 1 expect_output keeps same-id owners separate with an empty current session: terminal command failed with exit status 1: "node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts --reporter=verbose"

[failure]
terminal command failed with exit status 1: "node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts --reporter=verbose"

[command 1 combined output]
RUN  v4.1.11 /tmp/clawsweeper-live-proof-131667-jnWMVi/target

[vitest] still running with no output for 30000ms.
 ↓  ui-e2e  ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts › Control UI usage sessions owner attribution › keeps same-id owners separate with an empty
current session: false
 ↓  ui-e2e  ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts › Control UI usage sessions owner attribution › keeps same-id owners separate with an empty
current session: true

⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL   ui-e2e  ui/src/e2e/usage-sessions-owner-attribution.e2e.test.ts › Control UI usage sessions owner attribution
Error: browserType.launch: Target page, context or browser has been closed
Browser logs:

‹launching› /usr/bin/chromium-browser --disable-field-trial-config --disable-background-networking --disable-background-timer-throttling --disable-backgrounding
-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages
--disable-component-update --no-default-browser-check --disable-default-apps --disable-dev-shm-usage --disable-edgeupdater --disable-extensions --disable-featur
es=AvoidUnnecessaryBeforeUnloadCheckSync,BoundaryEventDispatchTracksNodeRemoval,DestroyProfileOnBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpg
rades,LensOverlay,MediaRouter,PaintHolding,ThirdPartyStoragePartitioning,BlockOriginHeaderModificationOnRedirect,Translate,AutoDeElevate,OptimizationHints,msFor
ceBrowserSignIn,msEdgeUpdateLaunchServicesPreferredVersion --enable-features=CDPScreenshotNewSurface --allow-pre-commit-input --disable-hang-monitor --disable-i
pc-flooding-protection --disable-popup-blocki
… output truncated …
6b56b97 ChromeProcessSingleton::NotifyOtherProcessOrCreate()', '  - [pid=9237][err] #16 0x560962084f4f ChromeMainDelegate::PostEarlyInitializ
ation()', '  - [pid=9237][err] #17 0x5609678a7c79 content::ContentMainRunnerImpl::RunBrowser()', '  - [pid=9237][err] #18 0x5609678a7943 content::ContentMainRun
nerImpl::Run()', '  - [pid=9237][err] #19 0x5609678a4f25 content::RunContentProcess()', '  - [pid=9237][err] #20 0x5609678a5157 content::ContentMain()', '  - [p
id=9237][err] #21 0x5609620845da ChromeMain', '  - [pid=9237][err] #22 0x7ffa2ae2a1ca (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9)', '  - [pid=9237][err] #23 0
x7ffa2ae2a28b __libc_start_main', '  - [pid=9237][err] #24 0x56096208402a _start', '  - [pid=9237][err]   r8: 000019c8000794d9  r9: 000000000000108e r10: 000000
0000000008 r11: 0000000000000246', '  - [pid=9237][err]  r12: 0000000000000006 r13: 0000000000001167 r14: 0000000000000016 r15: 00007ffece321930', '  - [pid=923
7][err]   di: 0000000000002415  si: 0000000000002415  bp: 00007ffece3217e0  bx: 0000000000002415', '  - [pid=9237][err]   dx: 0000000000000006  ax: 000000000000
0000  cx: 00007ffa2ae9ec0c  sp: 00007ffece3217a0', '  - [pid=9237][err]   ip: 00007ffa2ae9ec0c efl: 0000000000000246 cgf: 002b000000000033 erf: 0000000000000000
', '  - [pid=9237][err]  trp: 0000000000000000 msk: 0000000000000000 cr2: 0000000000000000', '  - [pid=9237][err] [end of stack trace]', '  - [pid=9237] ‹gracef
ully close start›', '  - [pid=9237] ‹kill›', '  - [pid=9237] ‹will force kill›', '  - [pid=9237] ‹process did exit: exitCode=null, signal=SIGABRT›', '  - [pid=9
237] starting temporary directories cleanup', '  - [pid=9237] finished temporary directories cleanup', '  - [pid=9237] ‹gracefully close end›' ] }
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


 Test Files  1 failed (1)
      Tests  2 skipped (2)
   Start at  09:44:52
   Duration  33.16s (transform 7.41s, setup 139ms, import 9.61s, tests 9.17s, environment 0ms)

[vitest] FAILED (exit 1)
[test] FAILED (exit 1)

Assertions:

  • FAIL expect_output: keeps same-id owners separate with an empty current session

How this fits together

Gateway usage reporting combines stored session metadata with discovered JSONL and SQLite history, then returns rows and totals to the Control UI. Reset lineage and per-agent ownership must remain intact through selection, loading, and aggregation.

flowchart LR
  A[Stored sessions] --> C[Usage session selection]
  B[Discovered JSONL and SQLite history] --> C
  D[Reset lineage] --> C
  C --> E[Per-agent source loading]
  E --> F[Shared usage aggregation]
  F --> G[Gateway usage response]
  F --> H[Control UI usage view]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Complete next step (P2) - The contributor patch is a bounded, evidence-backed repair that remains necessary on current main; no separate repair job is needed.
Agent review details

Security

None.

PR surface

Source -266, Tests +571, Docs +1, Other -3. Total +303 across 25 files.

View PR surface stats
Area Files Added Removed Net
Source 12 1449 1715 -266
Tests 9 836 265 +571
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 3 2 5 -3
Total 25 2288 1985 +303

Review metrics

Metric Value Why it matters
Production versus test delta production -266, tests +571, docs/tooling -2 The refactor removes duplicated production accounting while adding focused reset-history and cross-agent ownership coverage.

Stored data model

Persistent data-model change detected: persistent cache schema: src/gateway/server-methods/usage-result-cache.ts, serialized state: src/infra/session-cost-usage-pricing.ts, serialized state: src/infra/session-cost-usage-reporting.ts, unknown-data-model-change: src/infra/session-cost-usage-reporting.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #131667
Summary: This PR is the canonical repair for reset history disappearing after agent-qualified ownership selection; #128803 is a preceding partial repair and #125269 is adjacent validation work.

Members:

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

Technical review

Best possible solution:

Merge the focused ownership-aware selection and shared aggregation repair after normal maintainer validation.

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

Yes—current-main selection suppresses a discovered historical member whenever its family identity is stored, even when the reset current transcript is empty and no replacement row is emitted.

Is this the best way to solve the issue?

Yes—the repair makes selection retain the discovered concrete source and centralizes aggregation, matching the owner boundary instead of compensating in the UI.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a1782855a25a.

Labels

Label justifications:

  • P2: Current main can omit reset-session usage history, while the repair is scoped to reporting selection and aggregation.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦞 diamond lobster.
  • status: needs maintainer proof decision: A ClawSweeper-authored PR needs a maintainer proof capture or override decision. Needs stronger real behavior proof before merge: ClawSweeper live verification failed on the reviewed terminal surface. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the current usage repair and follow-up accounting refactors in the checked-out branch. (role: recent area contributor; confidence: high; commits: 1560c7a153df, 605d2c9b7b70, 878b2f0a036e; files: src/gateway/server-methods/usage.ts, src/gateway/server-methods/usage-session-selection.ts, src/shared/usage-aggregates.ts)
  • weiqinl: Merged ownership repair 0fef631 established the agent-qualified usage ownership path extended here. (role: prior feature contributor; confidence: medium; commits: 0fef6319fa84; files: src/gateway/server-methods/usage.ts)

Rank-up moves

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

  • Add after-fix proof from a real setup, such as a short recording, terminal output, linked artifact, or redacted logs.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-28T08:46:12.078Z sha 068618b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T08:55:59.908Z sha 14c6f79 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T09:06:41.423Z sha 9ed1b40 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added proof: 🎥 video Contributor real behavior proof includes video or recording evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: needs maintainer proof decision A ClawSweeper-authored PR needs a maintainer proof capture or override decision. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. proof: 🎥 video Contributor real behavior proof includes video or recording evidence. labels Aug 28, 2026
Keep family selection within the recorded agent and assign each instance once.
Carry discovered SQLite or JSONL sources into batched loading, including empty
current sessions and history encountered before a current artifact.

Share Gateway and Control UI aggregation and total arithmetic, use canonical
pricing for detail logs, and invalidate both result caches on config changes.
Split calendar, cache, selection, and loading owners out of the usage handler.

Add failing-before regressions for reset history, overlapping families, mixed
sources, config replacement, missing-price exports, and log pricing.
Make batched loading own its minimal input contract and import shared accounting
types from the leaf definition instead of the runtime barrel. Remove obsolete
current-JSONL fixture setup to keep the existing usage test within its line cap.

Verified both CI failures locally: zero Madge cycles and passing core lint with
the CI tsconfig. No runtime behavior or public protocol changes.
The shared usage contracts now import their canonical leaf definitions. Remove
the six obsolete internal-barrel type re-exports left by that ownership repair.
@steipete
steipete force-pushed the codex/usage-owner-refactor branch from 9ed1b40 to 878b2f0 Compare August 28, 2026 09:28
@steipete

Copy link
Copy Markdown
Contributor Author

Maintainer follow-up completed. The canonical selection owner assigns each (agentId, sessionId) once and carries discovered SQLite/JSONL locators into batched loading. This keeps reset families visible, prevents overlap double-counting, and removes discovery-order dependence. Gateway and UI totals now share one accumulator; detail logs share the canonical pricing parser; both result caches require config identity. Production is net -266 lines, tests +571, tooling/docs -2.

The initial CI run 33155908560 caught type-import cycles and a two-line test-cap overrun. Commit 14c6f79a30a5e169dc8a60efb76428f7f7a4d182 repairs the type ownership and removes obsolete fixture setup without exemptions. Run 33156849140 then caught six obsolete type re-exports. Commit 9ed1b4090fdbccfee56a1ac5f18f529188d60af6 removes them; production, full-tree, and script unused-export scans now pass. Independent Codex review is clean for the full change and both CI repairs.

Validation: 230 focused tests passed; 50 affected tests passed again after the CI repair. Exact commands included:

OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/gateway/server-methods/usage.sessions-usage-owner-attribution.integration.test.ts src/gateway/server-methods/usage.sessions-usage.test.ts src/gateway/server-methods/usage.sessions-usage-owner-attribution.test.ts src/shared/usage-aggregates.test.ts
node --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.ts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/gateway/server-methods/usage.sessions-usage.test.ts src/gateway/server-methods/usage-session-selection.ts src/gateway/server-methods/usage-session-loading.ts src/shared/usage-types.ts
pnpm build

The full local build preceded the final family-source adjustments; final-head hosted CI provides the final build gate. Testbox 33152724369 proved baseline failure and candidate 2/2 real Gateway/Chromium behavior; Testbox 33155330886 recorded the final reset flow, 1/1 passing after installing its missing Playwright FFmpeg recorder. Inspected before/after images and video are in the PR body. These are real Gateway/browser runs with synthetic transcript state, not a live provider or Telegram-account send.

ClawSweeper's completed review has no actionable correctness/security findings. Its latest Rank-up request asks for after-fix real behavior proof; the successful final-head hosted browser job below supplies it. Its sandbox could not run docs listing or independent autoreview; pnpm docs:list passed here, and all three independent Codex reviews completed cleanly. The automated persistent-data flag does not require a migration: usage-result-cache.ts contains process-local Maps moved from the handler, pricing helper exports became private, and log reporting reuses an existing read-only parser. No SQLite schema, durable cache format, or persisted state semantics change.

CI run 33157421585 passed every lane except an unchanged Chat disclosure fixture, which timed out on both attempts. Main had already fixed the same race in #131622: choose a still-mounted pending message after native pointer cancellation, deliver that exact request, and retain the reader-anchor, row-growth, adjacency, and unmount/remount checks. Rebasing onto 4ec40f190d4580dad0c5d4dc5d111400ef12a60c reuses that canonical repair. git range-diff confirms all three usage patches are identical; no timeouts or assertions were weakened. The earlier behavior recording precedes this mechanical rebase and type cleanup.

Refreshed real-flow proof on head 878b2f0a036ed1579f5c0989977e818523ea5706: the hosted Gateway/Chromium job passed both owner/reset cases, 2/2, in 25.96 seconds total; the empty-current reset case itself took 2.04 seconds. This addresses the latest ClawSweeper Rank-up request for after-fix proof. Its attempt expired while waiting 30 seconds for terminal output and showed only Vitest startup, without a failing product assertion. The completed hosted run and inspected Testbox recording provide the missing terminal and browser evidence. The inherited Chat disclosure shard also passes on this head.

Final-head CI attempt 1 also hit an unrelated startup timeout in board-fixture.e2e.test.ts: its standalone mock server produced no output before its existing startup deadline. The other 82 tests in that shard passed; six board cases did not run. Only that failed shard was retried on the unchanged head. The fixture and its deadlines are unmodified.

Final CI: run 33159536134, attempt 2 is completed / success on 878b2f0a036ed1579f5c0989977e818523ea5706. The retried browser shard passed all 23 files and 88 tests, including all six board-fixture cases, with no source or timeout changes. All 50 affected focused tests also passed after the rebase. The native review artifacts are bound to this exact head and validate cleanly.

The latest ClawSweeper re-review on this exact head failed before either case ran: /usr/bin/chromium-browser aborted during browserType.launch (SIGABRT; both cases skipped). That is browser setup failure, not a failed usage assertion. The final-head hosted Gateway/Chromium job linked above completed both cases successfully, and the inspected recording remains attached. This supplies the requested real-flow evidence without weakening the product tests or treating the failed sandbox run as a pass.

@steipete
steipete merged commit b576bb4 into main Aug 28, 2026
458 of 460 checks passed
@steipete
steipete deleted the codex/usage-owner-refactor branch August 28, 2026 10:00
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Rorqualx pushed a commit to Rorqualx/cortex that referenced this pull request Aug 28, 2026
…ream openclaw#131667

Upstream b576bb4 (openclaw#131667) removed mergeUsageLatency / mergeUsageDailyLatency /
buildUsageAggregateTail from src/shared/usage-aggregates.ts. The fork-owned
ui/src/ui usage-metrics view still consumes them, so keep the bodies verbatim in
ui/src/ui/views/usage-aggregate-helpers.ts instead of re-grafting exports into
src/shared (which would recreate merge=ours drift). Fixes the ui:build
MISSING_EXPORT break and the 3 tsgo:test:ui errors from proof ea34c00.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 29, 2026
* fix(usage): retain reset history and unify accounting

Keep family selection within the recorded agent and assign each instance once.
Carry discovered SQLite or JSONL sources into batched loading, including empty
current sessions and history encountered before a current artifact.

Share Gateway and Control UI aggregation and total arithmetic, use canonical
pricing for detail logs, and invalidate both result caches on config changes.
Split calendar, cache, selection, and loading owners out of the usage handler.

Add failing-before regressions for reset history, overlapping families, mixed
sources, config replacement, missing-price exports, and log pricing.

* refactor(usage): keep accounting type imports acyclic

Make batched loading own its minimal input contract and import shared accounting
types from the leaf definition instead of the runtime barrel. Remove obsolete
current-JSONL fixture setup to keep the existing usage test within its line cap.

Verified both CI failures locally: zero Madge cycles and passing core lint with
the CI tsconfig. No runtime behavior or public protocol changes.

* refactor(usage): remove unused accounting type re-exports

The shared usage contracts now import their canonical leaf definitions. Remove
the six obsolete internal-barrel type re-exports left by that ownership repair.
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 maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: needs maintainer proof decision A ClawSweeper-authored PR needs a maintainer proof capture or override decision.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant