Skip to content

Show Claude subscription usage without metered cost - #2170

Closed
erichroepke wants to merge 1 commit into
Abilityai:devfrom
erichroepke:contrib/claude-subscription-usage
Closed

erichroepke wants to merge 1 commit into
Abilityai:devfrom
erichroepke:contrib/claude-subscription-usage

Conversation

@erichroepke

Copy link
Copy Markdown

Summary

  • add a discriminated subscription / api / unconfigured usage contract to agent auth, agent list/detail, and subscription responses
  • show each Claude subscription-backed agent's named subscription and provider-backed allowance percentage/window/reset metadata when available
  • return an explicit provider_signal_unavailable state today because Trinity has no reliable Claude allowance counter; never substitute token totals or Claude Code dollar estimates
  • keep Anthropic API usage explicitly labelled API · metered with USD cost semantics
  • update the agent header, Tasks summary, Dashboard grid/list/timeline, and Settings subscriptions table
  • suppress Anthropic presentation entirely for non-Claude runtimes

Provider data limitation

Claude setup-token authentication currently exposes no reliable allowance percentage/window/reset signal to Trinity. The new model supports an available state, but production responses remain honest and explicit until an authenticated provider signal can supply percent consumed, window identity, observation time, and reset time when defined.

Verification

  • pytest tests/unit/test_subscription_usage_presentation.py -q — 6 passed
  • frontend unit suite — 311 passed
  • focused Ruff — passed
  • focused mypy — passed
  • Python compileall — passed
  • design-token check — passed
  • production Vite build — passed
  • staged Gitleaks scan — no leaks
  • headed local Playwright review verified subscription, API-metered, and Settings presentation states

Notes

  • No credentials, subscriptions, or provider authentication were changed.
  • No deployment or merge was performed.

@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

@vybe

vybe commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Thanks for this — the diagnosis underneath it is correct and worth acting on. A bare dollar figure on a subscription-backed agent implies metered spend that doesn't exist, and that's a real defect. I'm going to fix it, but not this way, so I'm closing the PR.

The disagreement is about the cure. This PR removes the measurement: cost_usd comes out of the SubscriptionUsage aggregation SQL for both windows, and AgentHeader.vue loses the 7-day sparkline, today's cost, and the trend-vs-average for subscription agents. What replaces them is usage unavailable, and that state is permanent rather than transitional — the available arm needs an allowance percent/window/reset that Anthropic doesn't expose, as the PR body itself notes, so the progress bar behind v-if="utilization?.status === 'available'" can never render. The net effect across five surfaces is trading a real-but-mislabeled number for no number at all.

The number is worth keeping because of what it actually is. For Claude Code, cost isn't our estimate — it's the runtime's own total_cost_usd, real token counts at API prices. On a subscription that's counterfactual spend: what this work would have cost on the API. That's a legitimate and useful figure — it's the value being extracted from the flat-rate plan, it tracks load, and enterprise per-agent spend caps need it. So the fix is to label it honestly (≈$3.12 API-equivalent, plus a billing-mode badge) rather than suppress it.

Separately, the honest allowance signal already exists and is dark: GET /api/subscriptions/{id}/usage computes real 5h/7d token windows, and subscription_rate_limit_events is populated on every 429. Neither reaches the UI. That's the work, and it's tracked in #471 (P1, ready) — which concluded back in April that no provider-side allowance counter exists, so a contract built around one shouldn't ship ahead of it.

Two smaller notes for future PRs: requirements/security.md was edited to narrow SUB-004 to match the code, and per our Rules of Engagement requirements lead implementation rather than follow it; and the subscription_credentials join added to get_all_agent_metadata puts subscription names on the fleet roster, which also serves shared non-owner users.

I've written the approach up on #471. Genuinely useful contribution — you found the bug, and the labeling fix lands because of it.

@vybe vybe closed this Aug 17, 2026
vybe pushed a commit that referenced this pull request Aug 19, 2026
…s, per-agent breakdown, pressure badges (#471) (#2316)

* feat(subscriptions): usage observability + live headroom — data layer, Settings panel, pressure badges (#471)

Data layer: failure events recorded BEFORE the auto-switch enabled gate
(opted-out operators previously got a permanently-zero count); failure_kind
persisted (dual-track migration — the table conflated auth failures with
429s); iso_cutoff() in SUB-004's window queries (Invariant #16).

Headroom: services/subscription_headroom_service.py reads real 5h/7d
utilization + reset times from the anthropic-ratelimit-unified-* headers of
a minimal probe (verified against a stored setup token 2026-08-19; the
/api/oauth/usage endpoint is 403-scope-dead for setup tokens — the #2170
mechanism). Click-to-refresh + default-ON ambient refresh behind a Settings
toggle; 15-min floor; single-flighted; fail-closed to observed-only when
Redis is down. Every reading carries source: anthropic|observed + age; the
DB-derived block is always populated (the #2170 inversion).

Surfaces: Settings subscriptions section extracted to SubscriptionsPanel.vue
(partial #717/#1030 paydown) with usage windows, per-agent breakdown (ranked
by cost — model-weighted by construction), failure-event warnings, headroom
gauge + refresh; GET /api/agents/subscription-pressure batch endpoint
(pure-DB visible set via the shared ent#384 helper; AgentAuthStatus
vocabulary) feeding tile chips + list badges; Tier 0 ≈ API-equivalent cost
relabel on AgentHeader + fleet surfaces.

OSS-core by decision; Tier 4 auto-assign cut (SUB-003 covers the reactive
case; bulk migration filed separately); MCP tools stay in ent#351.

Fixes #471

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(471): review fixes — true fail-closed ambient probing, stale-while-revalidate on the batch path, zeros-fork, snapshot TTL

- _read_snapshot returns (redis_ok, snapshot): an unreachable Redis no longer
  reads as 'no snapshot' (client object != reachable server), so ambient
  probing stays off during a Redis outage — the storm is closed for real
- pressure_states uses get_headroom(wait=False): ambient refreshes spawn as
  strong-ref background tasks; the 60s dashboard poll never blocks behind
  N x probe-timeout; probe timeout 30s -> 15s
- AgentHeader zeros-fork: subscription-funded agents whose lifetime cost is
  never reported render an honest dash, not a meaningless approx-USD 0.00
- headroom snapshots get a 7d TTL (self-clean after subscription delete)
- regression pins for both fail-closed behaviors; learnings entry added

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(security): cso --diff report for #471 — zero findings at gate

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(471): snapshot age parses microsecond timestamps (caught on first live probe)

utc_now_iso() emits microseconds; the seconds-only strptime made every
snapshot age None — read as 'refresh due' on every poll (only the 60s
in-process floor held) and 'never fresh' for the gauge and the provider
limited-verdict. fromisoformat with Z-normalization; regression-pinned.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(471): SUB-004 dedup — executions are the sole cost source (caught live in the demo)

A modern turn writes BOTH a schedule_executions row and (for /chat +
persisted /task, chat_persistence_service:104) a cost-bearing chat_messages
row; SUB-004's chat+exec SUM counted that turn's cost twice — verified live:
one sync-chat turn reported $0.137 for a $0.0687 run. Executions are the
canonical run record (status-as-projection #1082), so windows and the
per-agent breakdown now take cost/context/turn-count from executions only;
chat_messages contributes only output_tokens (which executions don't carry).
Pre-#1483 chat rows without paired executions fall outside any rolling
window. Realistic paired-row seeds + explicit counted-once pins.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(471): architecture + feature flows — headroom service, pressure endpoint, SUB-004 dedup, Tier 0 relabel

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(471): sys.modules re-import via monkeypatch.delitem — satisfies the pollution linter

The tmp_db fixture popped db.connection/db.subscriptions bare to force a
re-import against the tmp DB path; the lint gate requires monkeypatch.delitem
(raising=False) so the original modules are restored at teardown. Verified:
tests/lint_sys_modules.py OK (no new violations), suite 26 passed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(384): guard follows the helper's ONE home — pin the property, not the module edge

#471 extracted the pure-DB visible_agent_names into
services/agent_service/helpers.py (second consumer: the subscription-pressure
batch endpoint), so the guard's module-import ban on the skills router became
stale — it was a proxy written when the helper lived in the router and a
sentinel could not fire. The guard now pins what actually protects the
endpoint: the router's alias IS the shared helper (identity assert, so a local
re-implementation cannot dodge the source asserts), the helper reads
db.get_all_agent_metadata, and neither helper nor router references the
Docker-derived accessible_agent_names. Behavioural asserts unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(384): pin the shared helper by origin, not object identity

The #471 guard added in 059b0ab asserted `router_mod._visible_agent_names
is helpers.visible_agent_names`. That passes in isolation and failed on all
three full-suite seed orders (head 12345/67890/99999), while base stayed
green — a deterministic new failure, not a flake.

Cause: `router_mod` is the module object bound at ITS import, but the
`from services.agent_service import helpers` inside the test resolves at call
time. The suite contains tests that purge `sys.modules` (the reason CI
carries a dedicated sys.modules-pollution lint), after which `helpers` is
re-imported from the same path under the same key — so `is` compares two
distinct function objects. The CI failure shows exactly that: two
`visible_agent_names` at different addresses, both from
`src/backend/services/agent_service/helpers.py`.

Pin the ORIGIN instead (`__module__` + `__qualname__`). That is stable across
re-import and still defeats what identity was there to defeat: a router-local
`def _visible_agent_names` reads `routers.skills` and fails the assert
(verified by negative control — "got routers.skills._visible_agent_names").

Test-only; no product change.

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants