use std::ffi::OsString;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, MutexGuard};
use blyte_cli::http::Request;
use blyte_cli::serve::{
authenticated_api_get_routes, generate_token, route, OpenCodes, Surface, TOKEN_HEADER,
};
use blyte_cli::session::{EntryBody, PromptRunner, Session};
use blyte_cli::usage_log::{self, Entry};
use blyte_cli::usage_report::{
build, kind_of, utc_day, DayRow, Group, KindRow, ModelRow, RepoRow, Report, SurfaceRow,
};
static ENV_MUTEX: Mutex<()> = Mutex::new(());
struct UsageLogEnvGuard {
_lock: MutexGuard<'static, ()>,
prev: Option<OsString>,
}
impl UsageLogEnvGuard {
fn set(value: &str) -> Self {
let lock = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
let prev = std::env::var_os("BLYTE_USAGE_LOG");
std::env::set_var("BLYTE_USAGE_LOG", value);
Self { _lock: lock, prev }
}
}
impl Drop for UsageLogEnvGuard {
fn drop(&mut self) {
match &self.prev {
Some(v) => std::env::set_var("BLYTE_USAGE_LOG", v),
None => std::env::remove_var("BLYTE_USAGE_LOG"),
}
}
}
struct NoopRunner;
impl PromptRunner for NoopRunner {
fn run(
&mut self,
_prompt: &str,
_model: &str,
_emit: &(dyn Fn(EntryBody) + Sync),
) -> Result<(), String> {
Ok(())
}
}
fn make_surface(root: PathBuf) -> Surface {
let session = Session::start(Box::new(NoopRunner), "m1".to_string());
let mcp = Arc::new(blyte_cli::mcp::McpManager::empty_in(&root));
Surface {
surface_id: "s00000000000000aa".to_string(),
surface_name: "alpha".to_string(),
root,
repo: "alpha".to_string(),
session,
session_id: "sess-usage-test".to_string(),
started_at: 1_795_990_000,
runtime: blyte_cli::surface_version::SurfaceRuntimeInfo::current().unwrap(),
days: 14,
token: generate_token().unwrap(),
message_credential: generate_token().unwrap(),
open_codes: OpenCodes::new(),
requests: Arc::new(blyte_cli::requests::RequestsState::new()),
publisher: Arc::new(blyte_cli::requests::RealPublisher),
mcp,
reconcile_lock: Mutex::new(()),
reconcile_requested: AtomicBool::new(false),
}
}
fn make_request(
method: &str,
path: &str,
query: Vec<(&str, &str)>,
token: Option<&str>,
) -> Request {
let headers = match token {
Some(t) => vec![(TOKEN_HEADER.to_string(), t.to_string())],
None => Vec::new(),
};
Request {
method: method.to_string(),
path: path.to_string(),
query: query
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
headers,
body: Vec::new(),
}
}
struct EntrySpec<'a> {
ts: u64,
repo: &'a str,
surface: Option<&'a str>,
surface_name: Option<&'a str>,
dispatch: Option<&'a str>,
research: bool,
model: &'a str,
outcome: &'a str,
tokens: (u64, u64, u64, u64),
cost_usd: Option<f64>,
}
fn entry(spec: EntrySpec<'_>) -> Entry {
Entry {
ts: spec.ts,
repo: spec.repo.to_string(),
session: None,
surface: spec.surface.map(str::to_string),
surface_name: spec.surface_name.map(str::to_string),
dispatch: spec.dispatch.map(str::to_string),
research: spec.research,
model: spec.model.to_string(),
outcome: spec.outcome.to_string(),
turns: 1,
input: spec.tokens.0,
cached: spec.tokens.1,
output: spec.tokens.2,
thinking: spec.tokens.3,
cost_usd: spec.cost_usd,
}
}
#[test]
fn kind_of_classifies_all_four_kinds_and_review_beats_research() {
let review = entry(EntrySpec {
ts: 1,
repo: "/r",
surface: None,
surface_name: None,
dispatch: Some("T1"),
research: false,
model: "m1",
outcome: "model_review",
tokens: (1, 0, 1, 0),
cost_usd: Some(0.1),
});
let research_review = entry(EntrySpec {
ts: 2,
repo: "/r",
surface: None,
surface_name: None,
dispatch: Some("Q1"),
research: true,
model: "m1",
outcome: "model_review",
tokens: (1, 0, 1, 0),
cost_usd: Some(0.1),
});
let research = entry(EntrySpec {
ts: 3,
repo: "/r",
surface: None,
surface_name: None,
dispatch: Some("Q1"),
research: true,
model: "m1",
outcome: "verified",
tokens: (1, 0, 1, 0),
cost_usd: Some(0.1),
});
let implementer = entry(EntrySpec {
ts: 4,
repo: "/r",
surface: None,
surface_name: None,
dispatch: Some("T2"),
research: false,
model: "m1",
outcome: "verified",
tokens: (1, 0, 1, 0),
cost_usd: Some(0.1),
});
let conversation = entry(EntrySpec {
ts: 5,
repo: "/r",
surface: None,
surface_name: None,
dispatch: None,
research: false,
model: "m1",
outcome: "turn",
tokens: (1, 0, 1, 0),
cost_usd: Some(0.1),
});
assert_eq!(kind_of(&review), "review");
assert_eq!(kind_of(&research_review), "review");
assert_eq!(kind_of(&research), "research");
assert_eq!(kind_of(&implementer), "implementer");
assert_eq!(kind_of(&conversation), "conversation");
}
#[test]
fn utc_day_formats_boundaries_and_known_timestamp() {
assert_eq!(utc_day(0), "1970-01-01");
assert_eq!(utc_day(86_399), "1970-01-01");
assert_eq!(utc_day(86_400), "1970-01-02");
assert_eq!(utc_day(1_795_996_800), "2026-11-30");
}
#[test]
fn build_aggregates_six_line_log_with_exact_groups_and_ordering() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("usage.jsonl");
let entries = [
entry(EntrySpec {
ts: 1_795_910_500,
repo: "/work/alpha",
surface: Some("s_alpha"),
surface_name: Some("alpha"),
dispatch: None,
research: false,
model: "m1",
outcome: "turn",
tokens: (100, 40, 20, 10),
cost_usd: Some(0.5),
}),
entry(EntrySpec {
ts: 1_795_910_600,
repo: "/work/alpha",
surface: Some("s_alpha"),
surface_name: Some("alpha"),
dispatch: Some("T1"),
research: false,
model: "m2",
outcome: "verified",
tokens: (200, 50, 30, 5),
cost_usd: Some(1.5),
}),
entry(EntrySpec {
ts: 1_795_910_700,
repo: "/work/alpha",
surface: Some("s_alpha"),
surface_name: Some("alpha"),
dispatch: Some("T1"),
research: false,
model: "m1",
outcome: "model_review",
tokens: (80, 10, 15, 0),
cost_usd: Some(0.25),
}),
entry(EntrySpec {
ts: 1_795_996_900,
repo: "/work/notes",
surface: Some("s_notes"),
surface_name: Some("notes"),
dispatch: Some("Q1"),
research: true,
model: "m2",
outcome: "verified",
tokens: (300, 100, 40, 20),
cost_usd: Some(1.0),
}),
entry(EntrySpec {
ts: 1_795_997_000,
repo: "/work/notes",
surface: Some("s_notes"),
surface_name: Some("notes"),
dispatch: None,
research: false,
model: "m1",
outcome: "stopped",
tokens: (50, 0, 10, 0),
cost_usd: None,
}),
entry(EntrySpec {
ts: 1_795_997_100,
repo: "/work/alpha",
surface: None,
surface_name: None,
dispatch: Some("T2"),
research: false,
model: "m1",
outcome: "gate_failed",
tokens: (400, 200, 60, 15),
cost_usd: Some(1.0),
}),
];
for item in &entries {
usage_log::append(&log, item).unwrap();
}
let report = build(&log, None, 1_796_000_000).unwrap();
assert_eq!(report.generated_at, 1_796_000_000);
assert_eq!(report.since, None);
assert_eq!(report.log, log.to_string_lossy().as_ref());
assert!(report.log_exists);
assert_eq!(report.unreadable_lines, 0);
assert_eq!(
report.totals,
Group {
cost_usd: 4.25,
unpriced: 1,
lines: 6,
runs: 3,
input: 1130,
cached: 400,
output: 175,
thinking: 50,
}
);
assert_eq!(
report.by_day,
vec![
DayRow {
day: "2026-11-29".to_string(),
group: Group {
cost_usd: 2.25,
unpriced: 0,
lines: 3,
runs: 1,
input: 380,
cached: 100,
output: 65,
thinking: 15,
},
},
DayRow {
day: "2026-11-30".to_string(),
group: Group {
cost_usd: 2.0,
unpriced: 1,
lines: 3,
runs: 2,
input: 750,
cached: 300,
output: 110,
thinking: 35,
},
},
]
);
assert_eq!(
report.by_kind,
vec![
KindRow {
kind: "implementer".to_string(),
group: Group {
cost_usd: 2.5,
unpriced: 0,
lines: 2,
runs: 2,
input: 600,
cached: 250,
output: 90,
thinking: 20,
},
},
KindRow {
kind: "research".to_string(),
group: Group {
cost_usd: 1.0,
unpriced: 0,
lines: 1,
runs: 1,
input: 300,
cached: 100,
output: 40,
thinking: 20,
},
},
KindRow {
kind: "conversation".to_string(),
group: Group {
cost_usd: 0.5,
unpriced: 1,
lines: 2,
runs: 0,
input: 150,
cached: 40,
output: 30,
thinking: 10,
},
},
KindRow {
kind: "review".to_string(),
group: Group {
cost_usd: 0.25,
unpriced: 0,
lines: 1,
runs: 0,
input: 80,
cached: 10,
output: 15,
thinking: 0,
},
},
]
);
assert_eq!(
report.by_surface,
vec![
SurfaceRow {
surface: Some("s_alpha".to_string()),
name: Some("alpha".to_string()),
last_ts: 1_795_910_700,
group: Group {
cost_usd: 2.25,
unpriced: 0,
lines: 3,
runs: 1,
input: 380,
cached: 100,
output: 65,
thinking: 15,
},
},
SurfaceRow {
surface: Some("s_notes".to_string()),
name: Some("notes".to_string()),
last_ts: 1_795_997_000,
group: Group {
cost_usd: 1.0,
unpriced: 1,
lines: 2,
runs: 1,
input: 350,
cached: 100,
output: 50,
thinking: 20,
},
},
SurfaceRow {
surface: None,
name: None,
last_ts: 1_795_997_100,
group: Group {
cost_usd: 1.0,
unpriced: 0,
lines: 1,
runs: 1,
input: 400,
cached: 200,
output: 60,
thinking: 15,
},
},
]
);
assert_eq!(
report.by_repo,
vec![
RepoRow {
repo: "/work/alpha".to_string(),
group: Group {
cost_usd: 3.25,
unpriced: 0,
lines: 4,
runs: 2,
input: 780,
cached: 300,
output: 125,
thinking: 30,
},
},
RepoRow {
repo: "/work/notes".to_string(),
group: Group {
cost_usd: 1.0,
unpriced: 1,
lines: 2,
runs: 1,
input: 350,
cached: 100,
output: 50,
thinking: 20,
},
},
]
);
assert_eq!(
report.by_model,
vec![
ModelRow {
model: "m2".to_string(),
group: Group {
cost_usd: 2.5,
unpriced: 0,
lines: 2,
runs: 2,
input: 500,
cached: 150,
output: 70,
thinking: 25,
},
},
ModelRow {
model: "m1".to_string(),
group: Group {
cost_usd: 1.75,
unpriced: 1,
lines: 4,
runs: 1,
input: 630,
cached: 250,
output: 105,
thinking: 25,
},
},
]
);
}
#[test]
fn dispatched_turn_is_not_counted_as_a_run() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("usage.jsonl");
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_996_800,
repo: "/work/alpha",
surface: Some("s_alpha"),
surface_name: Some("alpha"),
dispatch: Some("T1"),
research: false,
model: "m1",
outcome: "turn",
tokens: (100, 10, 20, 0),
cost_usd: Some(0.5),
}),
)
.unwrap();
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_996_900,
repo: "/work/alpha",
surface: Some("s_alpha"),
surface_name: Some("alpha"),
dispatch: Some("T1"),
research: false,
model: "m1",
outcome: "verified",
tokens: (100, 10, 20, 0),
cost_usd: Some(0.5),
}),
)
.unwrap();
let report = build(&log, None, 1_796_000_000).unwrap();
assert_eq!(report.totals.lines, 2);
assert_eq!(report.totals.runs, 1);
assert_eq!(report.by_kind.len(), 1);
assert_eq!(report.by_kind[0].kind, "implementer");
assert_eq!(report.by_kind[0].group.lines, 2);
assert_eq!(report.by_kind[0].group.runs, 1);
}
#[test]
fn renamed_surface_uses_name_from_latest_ts_with_a_name() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("usage.jsonl");
usage_log::append(
&log,
&entry(EntrySpec {
ts: 200,
repo: "/work/a",
surface: Some("s1"),
surface_name: Some("new-name"),
dispatch: None,
research: false,
model: "m1",
outcome: "turn",
tokens: (10, 0, 5, 0),
cost_usd: Some(0.25),
}),
)
.unwrap();
usage_log::append(
&log,
&entry(EntrySpec {
ts: 100,
repo: "/work/a",
surface: Some("s1"),
surface_name: Some("old-name"),
dispatch: None,
research: false,
model: "m1",
outcome: "turn",
tokens: (10, 0, 5, 0),
cost_usd: Some(0.25),
}),
)
.unwrap();
usage_log::append(
&log,
&entry(EntrySpec {
ts: 300,
repo: "/work/a",
surface: Some("s1"),
surface_name: None,
dispatch: None,
research: false,
model: "m1",
outcome: "turn",
tokens: (10, 0, 5, 0),
cost_usd: Some(0.25),
}),
)
.unwrap();
let report = build(&log, None, 400).unwrap();
assert_eq!(report.by_surface.len(), 1);
assert_eq!(report.by_surface[0].surface.as_deref(), Some("s1"));
assert_eq!(report.by_surface[0].name.as_deref(), Some("new-name"));
assert_eq!(report.by_surface[0].last_ts, 300);
}
#[test]
fn since_drops_earlier_lines_and_keeps_equal_ts() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("usage.jsonl");
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_910_500,
repo: "/work/early",
surface: Some("s_early"),
surface_name: Some("early"),
dispatch: Some("T1"),
research: false,
model: "m_early",
outcome: "verified",
tokens: (100, 10, 20, 5),
cost_usd: Some(2.0),
}),
)
.unwrap();
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_996_800,
repo: "/work/exact",
surface: Some("s_exact"),
surface_name: Some("exact"),
dispatch: Some("T2"),
research: false,
model: "m_exact",
outcome: "verified",
tokens: (200, 20, 30, 10),
cost_usd: Some(1.0),
}),
)
.unwrap();
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_997_000,
repo: "/work/later",
surface: Some("s_later"),
surface_name: Some("later"),
dispatch: None,
research: false,
model: "m_later",
outcome: "turn",
tokens: (50, 5, 10, 0),
cost_usd: Some(0.5),
}),
)
.unwrap();
let report = build(&log, Some(1_795_996_800), 1_796_000_000).unwrap();
assert_eq!(report.since, Some(1_795_996_800));
assert_eq!(report.totals.lines, 2);
assert_eq!(report.totals.runs, 1);
assert_eq!(report.totals.cost_usd, 1.5);
assert_eq!(report.totals.input, 250);
assert_eq!(report.by_day.len(), 1);
assert_eq!(report.by_day[0].day, "2026-11-30");
assert_eq!(report.by_kind.len(), 2);
assert_eq!(report.by_surface.len(), 2);
assert_eq!(report.by_repo.len(), 2);
assert_eq!(report.by_model.len(), 2);
assert!(!report.by_repo.iter().any(|r| r.repo == "/work/early"));
assert!(report.by_repo.iter().any(|r| r.repo == "/work/exact"));
}
#[test]
fn unreadable_and_blank_lines_are_counted_and_ignored() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("usage.jsonl");
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_996_800,
repo: "/work/a",
surface: Some("s1"),
surface_name: Some("alpha"),
dispatch: None,
research: false,
model: "m1",
outcome: "turn",
tokens: (10, 0, 5, 0),
cost_usd: Some(0.5),
}),
)
.unwrap();
{
let mut f = OpenOptions::new().append(true).open(&log).unwrap();
f.write_all(b"\n \t \nnot json\n{\"ts\": \"bad\"}\n")
.unwrap();
}
let report = build(&log, None, 1_796_000_000).unwrap();
assert!(report.log_exists);
assert_eq!(report.unreadable_lines, 2);
assert_eq!(report.totals.lines, 1);
let filtered = build(&log, Some(1_796_000_000), 1_796_000_000).unwrap();
assert_eq!(filtered.unreadable_lines, 2);
assert_eq!(filtered.totals.lines, 0);
}
#[test]
fn missing_log_file_is_empty_report_with_log_exists_false() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("does-not-exist.jsonl");
let report = build(&missing, Some(100), 200).unwrap();
assert!(!report.log_exists);
assert_eq!(report.generated_at, 200);
assert_eq!(report.since, Some(100));
assert_eq!(report.log, missing.to_string_lossy().as_ref());
assert_eq!(report.unreadable_lines, 0);
assert_eq!(report.totals, Group::default());
assert!(report.by_day.is_empty());
assert!(report.by_kind.is_empty());
assert!(report.by_surface.is_empty());
assert!(report.by_repo.is_empty());
assert!(report.by_model.is_empty());
}
#[test]
fn directory_path_returns_error_containing_path() {
let dir = tempfile::tempdir().unwrap();
let err = build(dir.path(), None, 200).unwrap_err();
assert!(
err.contains(dir.path().to_string_lossy().as_ref()),
"error should name the path: {err}"
);
}
#[test]
fn api_usage_route_auth_contract_errors_and_method_checks() {
assert!(authenticated_api_get_routes().contains(&"/api/usage"));
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("usage.jsonl");
usage_log::append(
&log,
&entry(EntrySpec {
ts: 1_795_996_800,
repo: "/work/alpha",
surface: Some("s_alpha"),
surface_name: Some("alpha"),
dispatch: Some("T1"),
research: false,
model: "m1",
outcome: "verified",
tokens: (100, 20, 30, 5),
cost_usd: Some(1.25),
}),
)
.unwrap();
let surface = make_surface(dir.path().to_path_buf());
let _guard = UsageLogEnvGuard::set(log.to_str().unwrap());
let no_token = route(
&surface,
&make_request("GET", "/api/usage", vec![], None),
1_796_000_000,
);
assert_eq!(no_token.status, 403);
let ok = route(
&surface,
&make_request("GET", "/api/usage", vec![], Some(&surface.token)),
1_796_000_000,
);
assert_eq!(ok.status, 200);
let raw: serde_json::Value = serde_json::from_slice(&ok.body).unwrap();
let obj = raw.as_object().unwrap();
for key in [
"generated_at",
"since",
"log",
"log_exists",
"unreadable_lines",
"totals",
"by_day",
"by_kind",
"by_surface",
"by_repo",
"by_model",
] {
assert!(obj.contains_key(key), "missing key {key} in {raw}");
}
let parsed: Report = serde_json::from_value(raw).unwrap();
assert_eq!(parsed.generated_at, 1_796_000_000);
assert_eq!(parsed.since, None);
assert!(parsed.log_exists);
assert_eq!(parsed.totals.lines, 1);
assert_eq!(parsed.totals.runs, 1);
assert_eq!(parsed.totals.cost_usd, 1.25);
let with_since = route(
&surface,
&make_request(
"GET",
"/api/usage",
vec![("since", "1795996801")],
Some(&surface.token),
),
1_796_000_000,
);
assert_eq!(with_since.status, 200);
let filtered: Report = serde_json::from_slice(&with_since.body).unwrap();
assert_eq!(filtered.since, Some(1_795_996_801));
assert_eq!(filtered.totals.lines, 0);
let bad_since = route(
&surface,
&make_request(
"GET",
"/api/usage",
vec![("since", "abc")],
Some(&surface.token),
),
1_796_000_000,
);
assert_eq!(bad_since.status, 400);
let bad_body: serde_json::Value = serde_json::from_slice(&bad_since.body).unwrap();
assert_eq!(bad_body["error"], "since must be unix seconds, got abc");
let post = route(
&surface,
&make_request("POST", "/api/usage", vec![], Some(&surface.token)),
1_796_000_000,
);
assert_eq!(post.status, 405);
std::env::set_var("BLYTE_USAGE_LOG", "off");
let off = route(
&surface,
&make_request("GET", "/api/usage", vec![], Some(&surface.token)),
1_796_000_000,
);
assert_eq!(off.status, 404);
let off_body: serde_json::Value = serde_json::from_slice(&off.body).unwrap();
assert_eq!(
off_body["error"],
"the usage log is switched off (BLYTE_USAGE_LOG=off)"
);
std::env::set_var("BLYTE_USAGE_LOG", dir.path());
let dir_err = route(
&surface,
&make_request("GET", "/api/usage", vec![], Some(&surface.token)),
1_796_000_000,
);
assert_eq!(dir_err.status, 500);
let dir_err_body: serde_json::Value = serde_json::from_slice(&dir_err.body).unwrap();
assert!(dir_err_body["error"]
.as_str()
.unwrap()
.contains(dir.path().to_string_lossy().as_ref()));
}