Files
roboco/tests/unit/agent_sdk/test_usage_sync.py
T
547fe444f2 [4865ff8b] Add WebSocket support to the usage dashboard (#115)
* [e7349d84] feat(dashboard): WS usage store, hook extension, status badge, and smooth animations (#111) (#113)

- Add src/store/usage-store.ts with typed UsageData interface, useUsageStore
  Zustand store, setUsageData, clearUsageData, and setWsState actions
- Export useUsageStore and UsageData from store/index.ts
- Extend use-rate-limit-websocket.ts: rename msg type to SystemWsMessage,
  add key_metrics field; add useEffect syncing wsState into useUsageStore;
  add USAGE_UPDATE/USAGE_SNAPSHOT handler dispatching to useUsageStore
  (RATE_LIMIT_HIT/LIFTED handling and onReconnect unchanged)
- Update CommandCenter to read key_metrics from useUsageStore when
  wsState === 'connected' and usageData non-null; falls back to
  useCeoOverview() (refetchInterval: 60000) when WS disconnected
- Update KeyMetricsPanel: add wsState prop, render connection status Badge
  matching AgentStreamViewer pattern (bg-green-500+Wifi / bg-yellow-500+
  Loader2 spin / bg-gray-500+WifiOff); add transition-all duration-300
  ease-in-out to metric value spans for smooth animated updates

Co-authored-by: Frontend Developer 1 <fe-dev-1@agents.roboco.dev>

* [c9745ee8] feat(events): add USAGE_UPDATE/SNAPSHOT event types, throttled publisher, /ws/system usage bridge (#112) (#114)

- Add EventType.USAGE_UPDATE='usage.update' and EventType.USAGE_SNAPSHOT='usage.snapshot'
  to the EventType StrEnum in roboco/models/events.py

- Create roboco/services/usage_events.py with _UsageThrottle class (5-second per-agent
  window using time.monotonic()) and publish_usage_update() / publish_usage_snapshot()
  helpers; lazy imports prevent circular dependency with roboco.events

- Extend orchestrator._sweep_token_snapshots() to publish USAGE_UPDATE per active agent
  (throttled) and a USAGE_SNAPSHOT aggregate after each sweep cycle; wrapped in
  contextlib.suppress so event errors never abort DB snapshot operations

- Add _handle_usage_event() to websocket_bridge.py following _handle_rate_limit_event
  pattern; register USAGE_UPDATE and USAGE_SNAPSHOT subscriptions in
  register_websocket_bridge_handlers() forwarding both to /ws/system via broadcast_system()

- Add unit tests: test_usage_events.py (throttle suppression, publish helpers) and
  test_websocket_bridge.py extended with _handle_usage_event coverage and updated
  registration assertion to include USAGE_UPDATE/USAGE_SNAPSHOT

Co-authored-by: Backend Developer 1 <be-dev-1@agents.roboco.dev>

* fix(usage-ws): reconcile the realtime token/cost contract end-to-end

The backend and frontend halves shipped mismatched contracts, so the usage
dashboard never received live data:

- The bridge forwarded the dotted event value ("usage.update") while the panel
  switched on "USAGE_UPDATE"; map both to the UPPER_SNAKE type string the same
  way the rate-limit handler does.
- The backend emitted token/cost telemetry but the frontend read a key_metrics
  field and fed the org-metrics panel. Rewire the frontend to consume the
  USAGE_SNAPSHOT token/cost payload into the "Token Usage & Cost" panel —
  WS-first with polling fallback and a connection-status badge — and revert the
  unrelated KeyMetricsPanel / CommandCenter wiring.

Backend cleanups in the same path:

- Replace the multi-argument publish helpers with typed UsageUpdate /
  UsageSnapshot payloads, removing the too-many-arguments lint suppressions.
- Extract _fetch_agent_tokens and _persist_token_snapshot from the token sweep,
  removing the too-many-statements suppression; label the live snapshot "live".

Hardening uncovered while fixing the above:

- _finalize_spawn_session pulled the full RAG stack into the
  session-finalization path through a transcript-parse import; move the pure
  parser into a dependency-light roboco.agent_sdk.transcript_usage module so
  finalization never imports the agent SDK server.
- Reduce _finalize_spawn_session complexity by extracting
  _resolve_final_token_usage, and widen the transcript-fallback guard so a read
  error can never abort finalization.

Also align KeyMetricsPanel with the metrics /dashboard/ceo actually returns: it
read velocity_24h / avg_time_to_done / active_agents, none of which
get_key_metrics() emits, so four of five rows rendered "—". Render
velocity_weekly, completion_rate, documentation_coverage and active_blockers.

* docs: note live usage push over /ws/system on the usage dashboard

* fix(usage): finalize on self-exit and de-duplicate transcript token counts

Two bugs left token capture broken even after the transcript-read fallback
landed — surfaced by a live agent run:

- Agents that self-exit (the normal i_am_idle -> container shutdown, exit 0)
  were never finalized. _finalize_spawn_session is only called from
  stop_agent(), but a graceful self-exit goes through _handle_stopped_container,
  which set the instance OFFLINE and returned without finalizing — leaving the
  spawn-session row open with zero tokens. Finalize there for both graceful
  (exit_reason="completed") and crash (exit_reason="crashed") exits.

- sum_transcript_usage double-counted. Claude Code logs one assistant message
  as several JSONL lines (one per content block — thinking / text / tool_use),
  each repeating the same message.usage, so summing every line roughly doubled
  the totals. De-duplicate by message.id.

Verified against a live agent transcript: the raw sum (12, 1068, 62502, 115828)
vs the de-duped (6, 516, 62502, 63336), which matches the session's
authoritative result.usage exactly.

* feat(usage): fall back to the transcript in the live token sweep

The 60s token sweep read only the agent SDK's /usage/status, which races
container teardown and reports zero mid-run — so live usage (and the
USAGE_SNAPSHOT pushed to /ws/system) stayed at zero for active agents.
Extract _resolve_active_tokens: try the SDK, then fall back to the durable
transcript (the same source finalize uses) so running agents report live.

* feat(usage): add GET /usage/sessions for the dashboard's Recent Sessions

The panel's Recent Sessions table was mock-only — the backend had no sessions
endpoint, so production always showed 'No sessions recorded yet'. Add
UsageService.get_recent_sessions + a /usage/sessions route returning the most
recent spawn-session rows (token totals + cost), and point the panel client
at it.

---------

Co-authored-by: Frontend Developer 1 <fe-dev-1@agents.roboco.dev>
Co-authored-by: Backend Developer 1 <be-dev-1@agents.roboco.dev>
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-06-11 23:19:50 +02:00

219 lines
7.5 KiB
Python

"""Token-usage capture — /usage/sync parses the transcript and sets totals.
The agent SDK exposes /usage/report (additive) and /usage/status (read),
but nothing ever fed token counts in, so every session reported zero and the
cost dashboard rendered all-zeros. The fix: the usage-report hook hands the
SDK the Claude Code transcript path; /usage/sync parses the per-message
``usage`` blocks and *sets* the cumulative totals absolutely. These tests pin
that contract — correct summation, idempotency (no double-count on re-sync),
graceful handling of a missing/partial transcript, and growth on re-sync.
Expected totals are derived from the input rows (no magic literals), so the
assertions track whatever the fixtures declare.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
import roboco.agent_sdk.server as srv
from fastapi.testclient import TestClient
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
from pathlib import Path
_OK = 200
# Each row is (input, output, cache_read, cache_write).
_UsageRow = tuple[int, int, int, int]
@pytest.fixture(autouse=True)
def _reset_state() -> Iterator[None]:
srv._state.reset()
yield
srv._state.reset()
@pytest.fixture
def client() -> TestClient:
return TestClient(srv.app)
def _assistant_line(row: _UsageRow) -> str:
inp, out, cread, cwrite = row
return json.dumps(
{
"type": "assistant",
"message": {
"role": "assistant",
"usage": {
"input_tokens": inp,
"output_tokens": out,
"cache_read_input_tokens": cread,
"cache_creation_input_tokens": cwrite,
},
},
}
)
def _write(path: Path, *lines: str) -> None:
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def _expected(rows: Sequence[_UsageRow]) -> dict[str, int]:
return {
"tokens_input": sum(r[0] for r in rows),
"tokens_output": sum(r[1] for r in rows),
"tokens_cache_read": sum(r[2] for r in rows),
"tokens_cache_write": sum(r[3] for r in rows),
}
def test_sums_usage_across_assistant_messages(
client: TestClient, tmp_path: Path
) -> None:
rows: list[_UsageRow] = [(100, 20, 5, 3), (50, 10, 2, 1)]
transcript = tmp_path / "session.jsonl"
_write(transcript, *(_assistant_line(r) for r in rows))
resp = client.post("/usage/sync", json={"transcript_path": str(transcript)})
assert resp.status_code == _OK
body = resp.json()
for key, value in _expected(rows).items():
assert body[key] == value
def test_status_reflects_synced_totals(client: TestClient, tmp_path: Path) -> None:
rows: list[_UsageRow] = [(200, 40, 0, 0)]
transcript = tmp_path / "session.jsonl"
_write(transcript, *(_assistant_line(r) for r in rows))
client.post("/usage/sync", json={"transcript_path": str(transcript)})
status = client.get("/usage/status").json()
for key, value in _expected(rows).items():
assert status[key] == value
def test_resync_is_idempotent_not_additive(client: TestClient, tmp_path: Path) -> None:
"""The set is absolute — syncing the same transcript twice must not double."""
rows: list[_UsageRow] = [(100, 20, 0, 0)]
transcript = tmp_path / "session.jsonl"
_write(transcript, *(_assistant_line(r) for r in rows))
client.post("/usage/sync", json={"transcript_path": str(transcript)})
client.post("/usage/sync", json={"transcript_path": str(transcript)})
status = client.get("/usage/status").json()
for key, value in _expected(rows).items():
assert status[key] == value
def test_resync_after_growth_overwrites_with_new_total(
client: TestClient, tmp_path: Path
) -> None:
first: list[_UsageRow] = [(100, 20, 0, 0)]
grown: list[_UsageRow] = [(100, 20, 0, 0), (80, 15, 0, 0)]
transcript = tmp_path / "session.jsonl"
_write(transcript, *(_assistant_line(r) for r in first))
client.post("/usage/sync", json={"transcript_path": str(transcript)})
# The transcript grows as the turn continues.
_write(transcript, *(_assistant_line(r) for r in grown))
client.post("/usage/sync", json={"transcript_path": str(transcript)})
status = client.get("/usage/status").json()
for key, value in _expected(grown).items():
assert status[key] == value
def test_missing_transcript_returns_zero_without_error(
client: TestClient, tmp_path: Path
) -> None:
resp = client.post(
"/usage/sync", json={"transcript_path": str(tmp_path / "nope.jsonl")}
)
assert resp.status_code == _OK
assert resp.json() == _expected([])
def test_malformed_lines_are_skipped(client: TestClient, tmp_path: Path) -> None:
rows: list[_UsageRow] = [(100, 20, 0, 0), (50, 10, 0, 0)]
transcript = tmp_path / "session.jsonl"
_write(
transcript,
"not json at all",
_assistant_line(rows[0]),
json.dumps({"type": "user", "message": {"role": "user"}}), # no usage
"{ broken",
_assistant_line(rows[1]),
)
body = client.post("/usage/sync", json={"transcript_path": str(transcript)}).json()
exp = _expected(rows)
assert body["tokens_input"] == exp["tokens_input"]
assert body["tokens_output"] == exp["tokens_output"]
def test_parser_handles_entries_without_message(tmp_path: Path) -> None:
rows: list[_UsageRow] = [(10, 5, 0, 0)]
transcript = tmp_path / "session.jsonl"
_write(
transcript,
json.dumps({"type": "system", "subtype": "init"}),
_assistant_line(rows[0]),
)
tin, tout, cread, cwrite = srv._sum_transcript_usage(transcript)
exp = _expected(rows)
assert (tin, tout, cread, cwrite) == (
exp["tokens_input"],
exp["tokens_output"],
exp["tokens_cache_read"],
exp["tokens_cache_write"],
)
def _assistant_line_with_id(row: _UsageRow, message_id: str) -> str:
"""An assistant line carrying a message id (for de-duplication tests)."""
inp, out, cread, cwrite = row
return json.dumps(
{
"type": "assistant",
"message": {
"id": message_id,
"role": "assistant",
"usage": {
"input_tokens": inp,
"output_tokens": out,
"cache_read_input_tokens": cread,
"cache_creation_input_tokens": cwrite,
},
},
}
)
def test_parser_dedupes_repeated_message_id(tmp_path: Path) -> None:
"""One message logged across several lines (same id) is counted once.
Claude Code emits one transcript line per content block (thinking, text,
tool_use), each repeating the message's ``usage``. Summing every line would
roughly double the totals, so the parser must de-duplicate by message id.
"""
msg = (100, 20, 5, 3)
other = (7, 2, 1, 0)
transcript = tmp_path / "session.jsonl"
_write(
transcript,
_assistant_line_with_id(msg, "msg_aaa"), # thinking block
_assistant_line_with_id(msg, "msg_aaa"), # text block (same id)
_assistant_line_with_id(msg, "msg_aaa"), # tool_use block (same id)
_assistant_line_with_id(other, "msg_bbb"),
)
tin, tout, cread, cwrite = srv._sum_transcript_usage(transcript)
# Counted once per id: msg + other, NOT msg * 3 + other.
exp = _expected([msg, other])
assert (tin, tout, cread, cwrite) == (
exp["tokens_input"],
exp["tokens_output"],
exp["tokens_cache_read"],
exp["tokens_cache_write"],
)