Add Top chats to usage analytics (#45765)

## What changed

- Show local chats active in the past 30 days, ranked by estimated lifetime credits, for supported Business and Enterprise plans. Exclude archived chats and subagents.
- Add expandable model, reasoning effort, and speed breakdowns, optional zero-credit groups, and dollar estimates when supplied by the backend.
- Load estimates in bounded batches of up to 100 distinct threads, retaining available results when some estimates are unavailable. Hide chat titles without a returned estimate and distinguish missing usage from zero.

## Testing

Add coverage for batch validation, partial failures, request limits, pagination and ranking, plan eligibility, title visibility, and responsive table navigation and details.

GitOrigin-RevId: 783b960a780f4e0fd39f57e2fa78fb31b3090c44
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-09-15 19:07:03 +00:00
1 parent ca53e19c75
commit 0e7ab7c1b5
47 files changed
+2491 -356

No files matched your search

@@ -1,4 +1,4 @@
//! Authoritative estimated credit and dollar usage for an individual Codex thread.
//! Authoritative estimated credit and dollar usage for bounded batches of Codex threads.
use super::Client;
use super::PathStyle;
@@ -36,39 +36,77 @@ pub struct ThreadUsage {
#[derive(Serialize)]
struct ThreadUsageQueryRequest<'a> {
thread_ids: [&'a str; 1],
thread_ids: &'a [&'a str],
}
#[derive(Deserialize)]
struct ThreadUsageQueryResponse {
threads: Vec<ThreadUsage>,
threads: Vec<ThreadUsageEstimate>,
}
// Preserve unavailable rows until all returned IDs have been validated.
#[derive(Deserialize)]
struct ThreadUsageEstimate {
thread_id: String,
estimated_usage_credits_micros: Option<i64>,
estimated_usage_usd_micros: Option<i64>,
groups: Option<Vec<ThreadUsageBreakdownGroup>>,
}
impl Client {
/// Reads authoritative estimated totals without maintaining a second usage ledger.
pub async fn get_thread_usage(&self, thread_id: &str) -> Result<ThreadUsage, RequestError> {
self.get_threads_usage(&[thread_id])
.await?
.into_iter()
.find(|usage| usage.thread_id == thread_id)
.ok_or_else(|| {
RequestError::from(anyhow!("thread usage response omitted requested thread"))
})
}
/// Reads at most 100 distinct threads; omitted results are unavailable, not zero.
pub async fn get_threads_usage(
&self,
thread_ids: &[&str],
) -> Result<Vec<ThreadUsage>, RequestError> {
let requested: std::collections::HashSet<_> = thread_ids.iter().copied().collect();
if thread_ids.is_empty() || thread_ids.len() > 100 || requested.len() != thread_ids.len() {
return Err(RequestError::from(anyhow!(
"expected 1–100 distinct thread IDs"
)));
}
let url = self.thread_usage_url();
let request = self
.request(Method::POST, &url)
.headers(self.headers())
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.json(&ThreadUsageQueryRequest {
thread_ids: [thread_id],
});
let (body, content_type) = self.exec_request_detailed(request, "POST", &url).await?;
let response = self
.decode_json::<ThreadUsageQueryResponse>(&url, &content_type, &body)
.map_err(RequestError::from)?;
response
.json(&ThreadUsageQueryRequest { thread_ids });
let (body, _) = self.exec_request_detailed(request, "POST", &url).await?;
let response: ThreadUsageQueryResponse = serde_json::from_str(&body)
.map_err(|_| RequestError::Other(anyhow!("Invalid thread usage response.")))?;
let mut seen = std::collections::HashSet::new();
if response
.threads
.iter()
.any(|row| !requested.contains(row.thread_id.as_str()) || !seen.insert(&row.thread_id))
{
return Err(RequestError::from(anyhow!(
"thread usage returned unexpected threads"
)));
}
Ok(response
.threads
.into_iter()
.find(|usage| usage.thread_id == thread_id)
.ok_or_else(|| {
RequestError::from(anyhow!(
"thread usage response did not contain requested thread {thread_id}"
))
.filter_map(|row| {
Some(ThreadUsage {
thread_id: row.thread_id,
estimated_usage_credits_micros: row.estimated_usage_credits_micros?,
estimated_usage_usd_micros: row.estimated_usage_usd_micros,
groups: row.groups.unwrap_or_default(),
})
})
.collect())
}
fn thread_usage_url(&self) -> String {
@@ -23,7 +23,7 @@ fn thread_usage_contract_uses_expected_paths_and_payload() {
);
assert_eq!(
serde_json::to_value(ThreadUsageQueryRequest {
thread_ids: ["thread-123"],
thread_ids: &["thread-123"],
})
.expect("serialize thread usage request"),
json!({ "thread_ids": ["thread-123"] })
@@ -142,5 +142,59 @@ async fn get_thread_usage_rejects_totals_for_another_thread() {
.get_thread_usage("thread-123")
.await
.expect_err("reject usage for a different thread");
assert!(error.to_string().contains("requested thread thread-123"));
assert!(error.to_string().contains("unexpected threads"));
}
#[tokio::test]
async fn batch_usage_rejects_invalid_requests_before_http() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(/*s*/ 500))
.expect(/*r*/ 0)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let too_many = (0..101)
.map(|id| format!("thread-{id}"))
.collect::<Vec<_>>();
for ids in [
Vec::new(),
vec!["duplicate", "duplicate"],
too_many.iter().map(String::as_str).collect(),
] {
let error = client.get_threads_usage(&ids).await.unwrap_err();
assert!(error.to_string().contains("1–100 distinct thread IDs"));
}
}
#[tokio::test]
async fn batch_usage_rejects_duplicate_and_unrequested_response_rows() {
for returned in [["first", "first"], ["first", "unexpected"]] {
for second_amount in [Some(1), None] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(body_json(json!({"thread_ids": ["first", "second"]})))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"threads": returned.iter().enumerate().map(|(index, thread_id)| json!({
"thread_id": thread_id,
"estimated_usage_credits_micros": if index == 0 { Some(1) } else { second_amount }
})).collect::<Vec<_>>()
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
let error = client
.get_threads_usage(&["first", "second"])
.await
.unwrap_err();
assert!(error.to_string().contains("unexpected threads"));
}
}
}