Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Record each API model call's tokens per bot (item 6)

Lin (kwant bot)2235e5243542
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index 7a4470ea..651cc90a 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -323,7 +323,7 @@ impl Database {
}
/// Deletes a bot the person chose to remove, with its direct chat, threads, memories,
- /// skills, routines, questions, approvals, suggestions, proposals, cached API prompts and memberships, in one
+ /// skills, routines, questions, approvals, suggestions, proposals, cached API prompts, model usage and memberships, in one
/// transaction. Channels and teams it led get another lead (`new_lead`, which must be in
/// the same space). What it wrote in shared channels stays, as the room's history; so does
/// the space's log of bot actions.
@@ -348,6 +348,7 @@ impl Database {
"DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?1",
"DELETE FROM kwant_mcp_servers WHERE kwant_id = ?1",
"DELETE FROM api_contexts WHERE kwant_id = ?1",
+ "DELETE FROM model_usage WHERE kwant_id = ?1",
] {
sqlx::query(sql).bind(id).execute(&mut *tx).await?;
}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index c3368336..f97fa469 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -18,6 +18,7 @@ pub mod hires;
pub mod imports;
pub mod approval_modes;
pub mod api_context;
+pub mod usage;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -142,6 +143,7 @@ impl Database {
db.migrate_parallel().await?;
db.migrate_documents().await?;
db.migrate_api_context().await?;
+ db.migrate_usage().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/db/usage.rs b/src/db/usage.rs
new file mode 100644
index 00000000..d73cbb4a
--- /dev/null
+++ b/src/db/usage.rs
@@ -0,0 +1,205 @@
+//! One row per model API call an API-key bot makes: what it was for and the tokens it used, so
+//! the person can see per bot what caching, summaries and tools save (see `crate::drivers::api`).
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+
+/// Why a call was made.
+pub const PURPOSE_REPLY: &str = "reply";
+/// A follow-up call that hands the model its tool results.
+pub const PURPOSE_TOOL_ROUND: &str = "tool_round";
+/// Summarising older messages (see `crate::drivers::api`).
+pub const PURPOSE_SUMMARY: &str = "summary";
+
+/// A call to record. Token fields are 0 when the provider sent no counts (`reported` false).
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct NewUsage {
+ pub kwant_id: String,
+ pub context_id: String,
+ pub purpose: &'static str,
+ pub model: String,
+ /// Input tokens not read from or written to the cache.
+ pub fresh_input: i64,
+ pub cache_read: i64,
+ pub cache_write: i64,
+ pub output: i64,
+ pub reported: bool,
+ /// Size of the request's tool schemas, system prompt and messages, in characters of JSON.
+ pub tools_chars: i64,
+ pub system_chars: i64,
+ pub messages_chars: i64,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow)]
+pub struct UsageRow {
+ pub id: i64,
+ pub context_id: String,
+ pub purpose: String,
+ pub model: String,
+ pub fresh_input_tokens: i64,
+ pub cache_read_tokens: i64,
+ pub cache_write_tokens: i64,
+ pub output_tokens: i64,
+ pub reported: bool,
+ pub tools_chars: i64,
+ pub system_chars: i64,
+ pub messages_chars: i64,
+ pub created_at: DateTime<Utc>,
+}
+
+/// Sums over a set of calls.
+#[derive(Debug, Clone, Default, Serialize, FromRow, PartialEq, Eq)]
+pub struct UsageTotals {
+ pub calls: i64,
+ pub fresh_input_tokens: i64,
+ pub cache_read_tokens: i64,
+ pub cache_write_tokens: i64,
+ pub output_tokens: i64,
+ pub tools_chars: i64,
+ pub system_chars: i64,
+ pub messages_chars: i64,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow)]
+pub struct PurposeTotals {
+ pub purpose: String,
+ #[sqlx(flatten)]
+ #[serde(flatten)]
+ pub totals: UsageTotals,
+}
+
+const SUMS: &str = "COUNT(*) AS calls, COALESCE(SUM(fresh_input), 0) AS fresh_input_tokens, \
+ COALESCE(SUM(cache_read), 0) AS cache_read_tokens, COALESCE(SUM(cache_write), 0) AS cache_write_tokens, \
+ COALESCE(SUM(output), 0) AS output_tokens, COALESCE(SUM(tools_chars), 0) AS tools_chars, \
+ COALESCE(SUM(system_chars), 0) AS system_chars, COALESCE(SUM(messages_chars), 0) AS messages_chars";
+
+impl Database {
+ pub(super) async fn migrate_usage(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS model_usage (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ kwant_id TEXT NOT NULL,
+ context_id TEXT NOT NULL,
+ purpose TEXT NOT NULL,
+ model TEXT NOT NULL,
+ fresh_input INTEGER NOT NULL DEFAULT 0,
+ cache_read INTEGER NOT NULL DEFAULT 0,
+ cache_write INTEGER NOT NULL DEFAULT 0,
+ output INTEGER NOT NULL DEFAULT 0,
+ reported INTEGER NOT NULL DEFAULT 0,
+ tools_chars INTEGER NOT NULL DEFAULT 0,
+ system_chars INTEGER NOT NULL DEFAULT 0,
+ messages_chars INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS model_usage_kwant ON model_usage (kwant_id, created_at)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ pub async fn record_usage(&self, u: &NewUsage) -> Result<(), DbError> {
+ sqlx::query(
+ "INSERT INTO model_usage (kwant_id, context_id, purpose, model, fresh_input, cache_read, cache_write, output, \
+ reported, tools_chars, system_chars, messages_chars, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(&u.kwant_id)
+ .bind(&u.context_id)
+ .bind(u.purpose)
+ .bind(&u.model)
+ .bind(u.fresh_input)
+ .bind(u.cache_read)
+ .bind(u.cache_write)
+ .bind(u.output)
+ .bind(u.reported)
+ .bind(u.tools_chars)
+ .bind(u.system_chars)
+ .bind(u.messages_chars)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// A bot's newest calls first, at most `limit`.
+ pub async fn recent_usage(&self, kwant_id: &str, limit: i64) -> Result<Vec<UsageRow>, DbError> {
+ Ok(sqlx::query_as(
+ "SELECT id, context_id, purpose, model, fresh_input AS fresh_input_tokens, cache_read AS cache_read_tokens, \
+ cache_write AS cache_write_tokens, output AS output_tokens, reported, tools_chars, system_chars, messages_chars, created_at \
+ FROM model_usage WHERE kwant_id = ? ORDER BY id DESC LIMIT ?",
+ )
+ .bind(kwant_id)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// A bot's totals since `since` (all time when `None`), overall and per purpose.
+ pub async fn usage_totals(
+ &self,
+ kwant_id: &str,
+ since: Option<DateTime<Utc>>,
+ ) -> Result<(UsageTotals, Vec<PurposeTotals>), DbError> {
+ let since = since.unwrap_or(DateTime::<Utc>::MIN_UTC);
+ let all = sqlx::query_as(&format!("SELECT {SUMS} FROM model_usage WHERE kwant_id = ? AND created_at >= ?"))
+ .bind(kwant_id)
+ .bind(since)
+ .fetch_one(&self.pool)
+ .await?;
+ let by_purpose = sqlx::query_as(&format!(
+ "SELECT purpose, {SUMS} FROM model_usage WHERE kwant_id = ? AND created_at >= ? GROUP BY purpose ORDER BY purpose"
+ ))
+ .bind(kwant_id)
+ .bind(since)
+ .fetch_all(&self.pool)
+ .await?;
+ Ok((all, by_purpose))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn usage_is_summed_per_bot_and_purpose() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let call = |kwant: &str, purpose, fresh, read| NewUsage {
+ kwant_id: kwant.into(),
+ context_id: "c".into(),
+ purpose,
+ model: "claude-opus-5-5".into(),
+ fresh_input: fresh,
+ cache_read: read,
+ cache_write: 10,
+ output: 5,
+ reported: true,
+ tools_chars: 100,
+ system_chars: 200,
+ messages_chars: 300,
+ };
+ db.record_usage(&call("k1", PURPOSE_REPLY, 50, 1000)).await.unwrap();
+ db.record_usage(&call("k1", PURPOSE_TOOL_ROUND, 20, 1200)).await.unwrap();
+ db.record_usage(&call("k1", PURPOSE_REPLY, 30, 0)).await.unwrap();
+ db.record_usage(&call("k2", PURPOSE_REPLY, 999, 999)).await.unwrap();
+
+ let (all, by) = db.usage_totals("k1", None).await.unwrap();
+ assert_eq!((all.calls, all.fresh_input_tokens, all.cache_read_tokens, all.cache_write_tokens, all.output_tokens), (3, 100, 2200, 30, 15));
+ assert_eq!(all.tools_chars, 300);
+ let reply = by.iter().find(|p| p.purpose == PURPOSE_REPLY).unwrap();
+ assert_eq!((reply.totals.calls, reply.totals.fresh_input_tokens), (2, 80));
+ assert_eq!(by.len(), 2);
+
+ let recent = db.recent_usage("k1", 2).await.unwrap();
+ assert_eq!(recent.len(), 2);
+ assert_eq!((recent[0].fresh_input_tokens, recent[1].purpose.as_str()), (30, PURPOSE_TOOL_ROUND), "newest first");
+
+ let later = Utc::now() + chrono::Duration::minutes(1);
+ assert_eq!(db.usage_totals("k1", Some(later)).await.unwrap().0, UsageTotals::default());
+ assert_eq!(db.usage_totals("nobody", None).await.unwrap().0.calls, 0);
+ }
+}
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 1e96af4f..4aa76a18 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -339,11 +339,15 @@ impl Usage {
/// Reads an OpenAI or Anthropic `usage` object; `None` when it has no token counts.
fn parse(usage: &Value) -> Option<Self> {
let n = |k: &str| usage[k].as_u64();
+ // OpenAI counts cached tokens inside `prompt_tokens`; Anthropic counts them apart
+ let openai_cached = usage["prompt_tokens_details"]["cached_tokens"].as_u64().unwrap_or(0);
let found = Self {
- input: n("input_tokens").or_else(|| n("prompt_tokens")).unwrap_or(0),
+ input: n("input_tokens")
+ .or_else(|| n("prompt_tokens").map(|p| p.saturating_sub(openai_cached)))
+ .unwrap_or(0),
output: n("output_tokens").or_else(|| n("completion_tokens")).unwrap_or(0),
cache_creation: n("cache_creation_input_tokens").unwrap_or(0),
- cache_read: n("cache_read_input_tokens").unwrap_or(0),
+ cache_read: n("cache_read_input_tokens").unwrap_or(openai_cached),
total: n("total_tokens"),
};
(found.total.is_some() || n("input_tokens").is_some()).then_some(found)
@@ -473,6 +477,55 @@ struct ChatRequest<'a> {
max_calls: usize,
/// Stream the reply as it is written (rounds without tools only).
stream: bool,
+ /// Where each call is recorded; `None` records nothing.
+ record: Option<UsageSink<'a>>,
+}
+
+/// The bot and conversation a turn's calls are recorded for (see `crate::db::usage`).
+#[derive(Clone, Copy)]
+struct UsageSink<'a> {
+ db: &'a crate::db::Database,
+ kwant_id: &'a str,
+ context_id: &'a str,
+}
+
+/// Characters of JSON a request spends on tool schemas, the system prompt and the messages, so a
+/// bot's usage shows which part of the prompt is worth shrinking.
+fn prompt_chars(body: &Value) -> (usize, usize, usize) {
+ let len = |v: &Value| if v.is_null() { 0 } else { v.to_string().len() };
+ let tools = len(&body["tools"]);
+ let messages = body["messages"].as_array().map(Vec::as_slice).unwrap_or_default();
+ // OpenAI-style bodies keep the system prompt in `messages`
+ let (system, rest): (Vec<&Value>, Vec<&Value>) = messages.iter().partition(|m| m["role"] == "system");
+ let system = len(&body["system"]) + system.iter().map(|m| len(m)).sum::<usize>();
+ let messages = rest.iter().map(|m| len(m)).sum();
+ (tools, system, messages)
+}
+
+/// Records one model call, if the request has somewhere to record it. Never fails the turn.
+async fn record_call(request: &ChatRequest<'_>, purpose: &'static str, usage: Option<Usage>, body: &Value) {
+ let Some(sink) = request.record else {
+ return;
+ };
+ let (tools, system, messages) = prompt_chars(body);
+ let u = usage.unwrap_or_default();
+ let row = crate::db::usage::NewUsage {
+ kwant_id: sink.kwant_id.to_string(),
+ context_id: sink.context_id.to_string(),
+ purpose,
+ model: body["model"].as_str().unwrap_or(request.model).to_string(),
+ fresh_input: u.input as i64,
+ cache_read: u.cache_read as i64,
+ cache_write: u.cache_creation as i64,
+ output: u.output as i64,
+ reported: usage.is_some(),
+ tools_chars: tools as i64,
+ system_chars: system as i64,
+ messages_chars: messages as i64,
+ };
+ if let Err(e) = sink.db.record_usage(&row).await {
+ tracing::warn!(error = %e, "could not record model usage");
+ }
}
#[derive(Clone, Debug)]
@@ -665,6 +718,7 @@ impl ApiDriver {
if let Some(u) = usage {
u.log(request.model);
}
+ record_call(request, crate::db::usage::PURPOSE_REPLY, usage, &body).await;
return Ok((text, usage.map_or(45, |u| u.tokens() as usize), true));
}
for round in 0..max_calls {
@@ -694,13 +748,16 @@ impl ApiDriver {
))
}
};
- match Usage::parse(&reply["usage"]) {
+ let usage = Usage::parse(&reply["usage"]);
+ match usage {
Some(u) => {
u.log(request.model);
tokens += u.tokens() as usize;
}
None => tokens += 45,
}
+ let purpose = if round == 0 { crate::db::usage::PURPOSE_REPLY } else { crate::db::usage::PURPOSE_TOOL_ROUND };
+ record_call(request, purpose, usage, &body).await;
let message = &reply["choices"][0]["message"];
let content = reply_text(&reply);
let calls = message["tool_calls"].as_array().filter(|c| !c.is_empty());
@@ -895,6 +952,11 @@ impl Driver for ApiDriver {
max_tokens,
max_calls: mcp.map(|c| c.max_tool_iterations).unwrap_or(1),
stream: custom,
+ record: input.store.as_ref().filter(|_| !input.thread_id.is_empty()).map(|db| UsageSink {
+ db,
+ kwant_id: &input.kwant.id,
+ context_id: &input.thread_id,
+ }),
};
let caller = Caller {
kwant_id: input.kwant.id.clone(),
@@ -1031,6 +1093,7 @@ mod tests {
max_tokens: 100,
max_calls: 1,
stream: false,
+ record: None,
}
}
@@ -1170,6 +1233,42 @@ mod tests {
assert_eq!((streamed.cache_read, streamed.output, streamed.tokens()), (900, 30, 934));
}
+ #[tokio::test]
+ async fn each_call_is_recorded_with_its_tokens_and_prompt_sizes() {
+ let reply = json!({"content": [{"type": "text", "text": "ok"}], "usage": {"input_tokens": 20, "output_tokens": 7, "cache_creation_input_tokens": 1500, "cache_read_input_tokens": 3000}});
+ let (url, _seen) = mock(200, reply).await;
+ let driver = ApiDriver::new(Some("sk-ant-test-key".into()), Some(url));
+ let (tx, mut rx) = mpsc::channel(64);
+ tokio::spawn(async move { while rx.recv().await.is_some() {} });
+ let tmp = tempfile::tempdir().unwrap();
+ let db = crate::db::Database::init(tmp.path()).await.unwrap();
+ let mut input = turn("hi", vec![message("m1", "user", "Oleks", "hi")]);
+ input.store = Some(db.clone());
+ driver.stream_turn(input, tx).await.unwrap();
+
+ let rows = db.recent_usage("k1", 10).await.unwrap();
+ assert_eq!(rows.len(), 1);
+ let r = &rows[0];
+ assert_eq!((r.purpose.as_str(), r.context_id.as_str(), r.model.as_str()), ("reply", "t1", "claude-opus-5-5"));
+ assert_eq!((r.fresh_input_tokens, r.cache_read_tokens, r.cache_write_tokens, r.output_tokens), (20, 3000, 1500, 7));
+ assert!(r.reported);
+ assert!(r.system_chars > 1000 && r.messages_chars > 0, "{r:?}");
+ assert_eq!(r.tools_chars, 0, "no tools this turn");
+ }
+
+ #[test]
+ fn openai_cached_tokens_count_as_cache_reads_not_fresh_input() {
+ let u = Usage::parse(&json!({"prompt_tokens": 1200, "completion_tokens": 9, "total_tokens": 1209, "prompt_tokens_details": {"cached_tokens": 1024}})).unwrap();
+ assert_eq!((u.input, u.cache_read, u.output, u.tokens()), (176, 1024, 9, 1209));
+ let (tools, system, messages) = prompt_chars(&json!({
+ "messages": [{"role": "system", "content": "sys"}, {"role": "user", "content": "hi"}],
+ "tools": [{"type": "function"}],
+ }));
+ assert_eq!(tools, json!([{"type": "function"}]).to_string().len());
+ assert_eq!(system, json!({"role": "system", "content": "sys"}).to_string().len());
+ assert_eq!(messages, json!({"role": "user", "content": "hi"}).to_string().len());
+ }
+
#[tokio::test]
async fn streamed_anthropic_usage_includes_cache_reads() {
let sse = concat!(
diff --git a/src/server/mod.rs b/src/server/mod.rs
index bb773acd..2a3fd622 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -11,6 +11,7 @@ pub mod engine_routes;
pub mod engine_login;
pub mod auth;
pub mod continuity;
+pub mod model_usage;
pub mod scheduler;
pub mod turns;
pub mod delegation;
@@ -272,6 +273,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/channels/:id", get(continuity::get_channel).patch(continuity::patch_channel))
.route("/api/search", get(continuity::search))
.route("/api/kwants/:id/memories", get(continuity::list_memories).post(continuity::add_memory))
+ .route("/api/kwants/:id/model-usage", get(model_usage::get_usage))
.route(
"/api/kwants/:id/memories/:mid",
axum::routing::patch(continuity::update_memory).delete(continuity::delete_memory),
diff --git a/src/server/model_usage.rs b/src/server/model_usage.rs
new file mode 100644
index 00000000..570827ef
--- /dev/null
+++ b/src/server/model_usage.rs
@@ -0,0 +1,48 @@
+//! `GET /api/kwants/:id/model-usage`: an API-key bot's model calls and tokens (see `crate::db::usage`).
+
+use super::AppState;
+use axum::{
+ extract::{Path, Query, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Utc};
+use serde::Deserialize;
+use serde_json::json;
+
+/// Most rows `recent` returns.
+const MAX_RECENT: i64 = 500;
+
+#[derive(Debug, Deserialize)]
+pub struct UsageQuery {
+ /// How many of the newest calls to list (default 50, at most 500).
+ pub limit: Option<i64>,
+ /// Only totals for calls at or after this time (RFC 3339); all time when missing.
+ pub since: Option<DateTime<Utc>>,
+}
+
+pub async fn get_usage(
+ State(state): State<AppState>,
+ Path(kwant_id): Path<String>,
+ Query(q): Query<UsageQuery>,
+) -> Response {
+ match state.db.get_kwant(&kwant_id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return StatusCode::NOT_FOUND.into_response(),
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+ let limit = q.limit.unwrap_or(50).clamp(1, MAX_RECENT);
+ let (totals, recent) = tokio::join!(state.db.usage_totals(&kwant_id, q.since), state.db.recent_usage(&kwant_id, limit));
+ match (totals, recent) {
+ (Ok((totals, by_purpose)), Ok(recent)) => Json(json!({
+ "kwant_id": kwant_id,
+ "since": q.since,
+ "totals": totals,
+ "by_purpose": by_purpose,
+ "recent": recent,
+ }))
+ .into_response(),
+ _ => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+}
diff --git a/tests/model_usage_test.rs b/tests/model_usage_test.rs
new file mode 100644
index 00000000..03978ad9
--- /dev/null
+++ b/tests/model_usage_test.rs
@@ -0,0 +1,58 @@
+//! `GET /api/kwants/:id/model-usage`: per-bot model calls and tokens, as the bot's usage view shows them.
+
+mod common;
+
+use axum::http::StatusCode;
+use common::*;
+use kwnt::db::usage::{NewUsage, PURPOSE_REPLY, PURPOSE_SUMMARY};
+
+fn call_row(kwant: &str, purpose: &'static str, fresh: i64) -> NewUsage {
+ NewUsage {
+ kwant_id: kwant.into(),
+ context_id: "ctx".into(),
+ purpose,
+ model: "claude-opus-5-5".into(),
+ fresh_input: fresh,
+ cache_read: 4000,
+ cache_write: 0,
+ output: 12,
+ reported: true,
+ tools_chars: 900,
+ system_chars: 5000,
+ messages_chars: 700,
+ }
+}
+
+#[tokio::test]
+async fn a_bots_usage_lists_its_calls_and_totals() {
+ let env = setup().await;
+ for (purpose, fresh) in [(PURPOSE_REPLY, 30), (PURPOSE_REPLY, 40), (PURPOSE_SUMMARY, 300)] {
+ env.state.db.record_usage(&call_row(&env.a, purpose, fresh)).await.unwrap();
+ }
+ env.state.db.record_usage(&call_row(&env.b, PURPOSE_REPLY, 1)).await.unwrap();
+
+ let (s, body) = call(&env.app, "GET", &format!("/api/kwants/{}/model-usage?limit=2", env.a), None).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ assert_eq!(body["kwant_id"], env.a.as_str());
+ assert_eq!(body["totals"]["calls"], 3);
+ assert_eq!(body["totals"]["fresh_input_tokens"], 370);
+ assert_eq!(body["totals"]["cache_read_tokens"], 12000);
+ let reply = body["by_purpose"].as_array().unwrap().iter().find(|p| p["purpose"] == "reply").unwrap().clone();
+ assert_eq!((reply["calls"].as_i64(), reply["fresh_input_tokens"].as_i64()), (Some(2), Some(70)));
+ let recent = body["recent"].as_array().unwrap();
+ assert_eq!(recent.len(), 2, "limit applies to the list, not the totals");
+ assert_eq!(recent[0]["purpose"], "summary", "newest first");
+ for key in ["context_id", "model", "cache_write_tokens", "output_tokens", "reported", "tools_chars", "system_chars", "messages_chars", "created_at"] {
+ assert!(recent[0].get(key).is_some(), "row has {key}");
+ }
+
+ // The delete dialog's counts stay at the old path
+ let (s, counts) = call(&env.app, "GET", &format!("/api/kwants/{}/usage", env.a), None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert!(counts.get("totals").is_none(), "{counts}");
+
+ let (s, _) = call(&env.app, "GET", "/api/kwants/no-such-bot/model-usage", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ let (s, body) = call(&env.app, "GET", &format!("/api/kwants/{}/model-usage?since=2999-01-01T00:00:00Z", env.a), None).await;
+ assert_eq!((s, body["totals"]["calls"].as_i64()), (StatusCode::OK, Some(0)));
+}