mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Add consumer Top chats usage analytics (#45768)
## Why Consumer analytics lacked a per-chat view of allowance usage and balance credit debits. ## What changed - Add a Top chats panel for up to 100 local chats active in the past 30 days, including discovered descendants and excluding archived roots. - Show weekly and five-hour usage as percentages of current full limits, plus balance credits including adjustments. Preserve exact credit decimals and distinguish missing values from zero. - Support cycling sort metrics with `s`, a top-five dashboard summary, and expandable model, reasoning effort, and speed breakdowns. - Query task usage through `query_v2` with bounded, disjoint descendant groups. Retain partial and unavailable rows, hide titles when usage is unavailable, and report ranking coverage and freshness. ## Testing Add backend and TUI tests covering decimal precision, request and response validation, paginated archived descendants, unavailable responses, metric selection, title hiding, and top-five rendering. GitOrigin-RevId: b8f233166576389c8212bb97eceb7c6be7f5f51d
This commit is contained in:
1 parent
0d0979f457
commit
8f0d2459ac
41 files changed
+1825
-194
No files matched your search
@@ -38,6 +38,7 @@ pub(crate) mod analytics;
|
||||
mod chatgpt_turn_cost;
|
||||
pub(crate) mod plan_history;
|
||||
mod rate_limit_resets;
|
||||
pub(crate) mod task_usage;
|
||||
mod thread_usage;
|
||||
pub(crate) mod turn_usage;
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Consumer task accounting: current allowance percentages and actual balance debits.
|
||||
//! This contract is deliberately separate from enterprise estimated lifetime credits.
|
||||
|
||||
use super::Client;
|
||||
use super::PathStyle;
|
||||
use super::RequestError;
|
||||
use http::Method;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct TaskUsageThread {
|
||||
pub thread_id: String,
|
||||
pub created_at: Option<String>,
|
||||
pub descendant_thread_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct TaskUsageResponse {
|
||||
pub data_as_of: Option<String>,
|
||||
pub threads: Vec<TaskUsage>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TaskUsageStatus {
|
||||
Available,
|
||||
Partial,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct TaskUsage {
|
||||
pub thread_id: String,
|
||||
pub data_status: TaskUsageStatus,
|
||||
pub usage_source: String,
|
||||
#[serde(flatten)]
|
||||
pub amounts: TaskUsageAmounts,
|
||||
pub groups: Vec<TaskUsageGroup>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct TaskUsageAmounts {
|
||||
#[serde(default, deserialize_with = "percentage")]
|
||||
pub five_hour_limit_percent: Option<f64>,
|
||||
#[serde(default, deserialize_with = "percentage")]
|
||||
pub weekly_limit_percent: Option<f64>,
|
||||
pub balance_usage_credits: Option<TaskCredits>,
|
||||
}
|
||||
|
||||
// Flattened Serde fields buffer arbitrary-precision JSON numbers as maps.
|
||||
// Decode through Number so decimal percentages work with either serde_json configuration.
|
||||
fn percentage<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<f64>, D::Error> {
|
||||
Option::<serde_json::Number>::deserialize(deserializer)?
|
||||
.map(|value| {
|
||||
value
|
||||
.as_f64()
|
||||
.filter(|value| value.is_finite())
|
||||
.ok_or_else(|| serde::de::Error::custom("Invalid task percentage."))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct TaskUsageGroup {
|
||||
pub product_experience: Option<String>,
|
||||
pub model: Option<String>,
|
||||
pub reasoning_effort: Option<String>,
|
||||
pub speed: Option<String>,
|
||||
#[serde(flatten)]
|
||||
pub amounts: TaskUsageAmounts,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Queries disjoint tasks, including legacy descendants, without selecting a comparison plan.
|
||||
pub async fn get_task_usage(
|
||||
&self,
|
||||
threads: &[TaskUsageThread],
|
||||
) -> Result<TaskUsageResponse, RequestError> {
|
||||
let mut ids = HashSet::new();
|
||||
if threads.is_empty()
|
||||
|| threads.len() > 100
|
||||
|| threads.iter().any(|thread| {
|
||||
std::iter::once(&thread.thread_id)
|
||||
.chain(&thread.descendant_thread_ids)
|
||||
.any(|id| id.trim().is_empty() || id.len() > 512 || !ids.insert(id.as_str()))
|
||||
})
|
||||
|| ids.len() > 1_000
|
||||
{
|
||||
return Err(RequestError::Other(anyhow::anyhow!(
|
||||
"Expected at most 100 disjoint tasks and 1,000 thread IDs."
|
||||
)));
|
||||
}
|
||||
let prefix = match self.path_style {
|
||||
PathStyle::CodexApi => "api/codex",
|
||||
PathStyle::ChatGptApi => "wham",
|
||||
};
|
||||
let url = format!("{}/{prefix}/usage/thread_usage/query_v2", self.base_url);
|
||||
#[derive(Serialize)]
|
||||
struct Query<'a> {
|
||||
threads: &'a [TaskUsageThread],
|
||||
}
|
||||
let request = self
|
||||
.request(Method::POST, &url)
|
||||
.headers(self.headers())
|
||||
.json(&Query { threads });
|
||||
let (body, _) = self.exec_request_detailed(request, "POST", &url).await?;
|
||||
let response: TaskUsageResponse = serde_json::from_str(&body)
|
||||
.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid task usage response.")))?;
|
||||
let roots: HashSet<_> = threads
|
||||
.iter()
|
||||
.map(|thread| thread.thread_id.as_str())
|
||||
.collect();
|
||||
let mut seen = HashSet::new();
|
||||
if response.threads.iter().any(|thread| {
|
||||
!roots.contains(thread.thread_id.as_str())
|
||||
|| !seen.insert(&thread.thread_id)
|
||||
|| std::iter::once(&thread.amounts)
|
||||
.chain(thread.groups.iter().map(|group| &group.amounts))
|
||||
.any(|amounts| {
|
||||
[
|
||||
amounts.five_hour_limit_percent,
|
||||
amounts.weekly_limit_percent,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| !value.is_finite())
|
||||
})
|
||||
}) {
|
||||
return Err(RequestError::Other(anyhow::anyhow!(
|
||||
"Invalid task usage response."
|
||||
)));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decimal strings retain all backend digits for both rendering and sorting.
|
||||
#[derive(Clone, Debug, Eq)]
|
||||
pub struct TaskCredits(String);
|
||||
|
||||
impl TaskCredits {
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn parts(&self) -> (bool, i64, String) {
|
||||
let (mantissa, exponent) = self.0.split_once(['e', 'E']).unwrap_or((&self.0, "0"));
|
||||
let negative = mantissa.starts_with('-');
|
||||
let unsigned = mantissa.trim_start_matches(['-', '+']);
|
||||
let fraction = unsigned
|
||||
.split_once('.')
|
||||
.map_or(/*default*/ 0, |(_, fraction)| fraction.len());
|
||||
let digits = unsigned.replace('.', "");
|
||||
let digits = digits.trim_start_matches('0');
|
||||
let power =
|
||||
exponent.parse::<i64>().unwrap_or_default() - fraction as i64 + digits.len() as i64;
|
||||
(negative && !digits.is_empty(), power, digits.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for TaskCredits {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let value = String::deserialize(deserializer)?;
|
||||
let mantissa = value
|
||||
.split(['e', 'E'])
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim_start_matches(['-', '+']);
|
||||
let exponent = value
|
||||
.split_once(['e', 'E'])
|
||||
.map_or("0", |(_, exponent)| exponent);
|
||||
if value.len() > 128
|
||||
|| mantissa.is_empty()
|
||||
|| !mantissa.chars().any(|ch| ch.is_ascii_digit())
|
||||
|| !mantissa.chars().all(|ch| ch.is_ascii_digit() || ch == '.')
|
||||
|| value.parse::<f64>().is_err()
|
||||
|| exponent.parse::<i32>().is_err()
|
||||
{
|
||||
return Err(serde::de::Error::custom("Invalid decimal credits."));
|
||||
}
|
||||
Ok(Self(value))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for TaskCredits {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
let (negative, power, digits) = self.parts();
|
||||
let (other_negative, other_power, other_digits) = other.parts();
|
||||
let magnitude = match (digits.is_empty(), other_digits.is_empty()) {
|
||||
(true, true) => std::cmp::Ordering::Equal,
|
||||
(true, false) => std::cmp::Ordering::Less,
|
||||
(false, true) => std::cmp::Ordering::Greater,
|
||||
(false, false) => power.cmp(&other_power).then_with(|| {
|
||||
let width = digits.len().max(other_digits.len());
|
||||
digits
|
||||
.bytes()
|
||||
.chain(std::iter::repeat(b'0'))
|
||||
.take(width)
|
||||
.cmp(
|
||||
other_digits
|
||||
.bytes()
|
||||
.chain(std::iter::repeat(b'0'))
|
||||
.take(width),
|
||||
)
|
||||
}),
|
||||
};
|
||||
other_negative.cmp(&negative).then(if negative {
|
||||
magnitude.reverse()
|
||||
} else {
|
||||
magnitude
|
||||
})
|
||||
}
|
||||
}
|
||||
impl PartialOrd for TaskCredits {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
impl PartialEq for TaskCredits {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cmp(other).is_eq()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "task_usage_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Exact decimal preservation and sorting for consumer task credits.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn credits_preserve_precision_and_order_signed_decimal_strings() {
|
||||
let mut amounts: Vec<TaskCredits> = serde_json::from_value(json!([
|
||||
"1.000000000000000002",
|
||||
"-0.00025",
|
||||
"0",
|
||||
"1.000000000000000001",
|
||||
"1e-20",
|
||||
"-1E+3"
|
||||
]))
|
||||
.unwrap();
|
||||
amounts.sort();
|
||||
assert_eq!(
|
||||
amounts.iter().map(TaskCredits::as_str).collect::<Vec<_>>(),
|
||||
vec![
|
||||
"-1E+3",
|
||||
"-0.00025",
|
||||
"0",
|
||||
"1e-20",
|
||||
"1.000000000000000001",
|
||||
"1.000000000000000002"
|
||||
]
|
||||
);
|
||||
for invalid in ["NaN", "inf", "1..0", "", "1e999999999999"] {
|
||||
assert!(serde_json::from_value::<TaskCredits>(json!(invalid)).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn task_queries_validate_request_groups_and_response_ownership() {
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
let server = MockServer::start().await;
|
||||
let client = Client::new(
|
||||
server.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
);
|
||||
let query = TaskUsageThread {
|
||||
thread_id: "root".into(),
|
||||
created_at: None,
|
||||
descendant_thread_ids: vec!["child".into()],
|
||||
};
|
||||
let task = json!({"thread_id":"root", "data_status":"available", "usage_source":"plan_and_credits",
|
||||
"five_hour_limit_percent":150.0, "weekly_limit_percent":0.0,
|
||||
"balance_usage_credits":"-0.000000000000000001", "groups":[{
|
||||
"product_experience":"codex", "model":"gpt-5.5", "reasoning_effort":"high", "speed":"standard",
|
||||
"five_hour_limit_percent":150.25, "weekly_limit_percent":0.125, "balance_usage_credits":"0"
|
||||
}]});
|
||||
for ids in [vec!["root"], vec!["other"], vec!["root", "root"]] {
|
||||
server.reset().await;
|
||||
let response = json!({"data_as_of":null, "threads":ids.iter().map(|id| {
|
||||
let mut task=task.clone();task["thread_id"]=json!(id);task
|
||||
}).collect::<Vec<_>>()});
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/codex/usage/thread_usage/query_v2"))
|
||||
.respond_with(move |request: &wiremock::Request| {
|
||||
assert_eq!(
|
||||
request.body_json::<serde_json::Value>().unwrap(),
|
||||
json!({"threads":[{
|
||||
"thread_id":"root", "created_at":null, "descendant_thread_ids":["child"]
|
||||
}]})
|
||||
);
|
||||
ResponseTemplate::new(/*s*/ 200).set_body_json(&response)
|
||||
})
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let result = client.get_task_usage(std::slice::from_ref(&query)).await;
|
||||
if ids == ["root"] {
|
||||
let response = result.unwrap();
|
||||
assert_eq!((response.data_as_of, response.threads.len()), (None, 1));
|
||||
let row = &response.threads[0];
|
||||
assert_eq!(
|
||||
(
|
||||
row.thread_id.as_str(),
|
||||
row.data_status,
|
||||
row.amounts.five_hour_limit_percent,
|
||||
row.amounts.weekly_limit_percent,
|
||||
row.amounts
|
||||
.balance_usage_credits
|
||||
.as_ref()
|
||||
.map(TaskCredits::as_str)
|
||||
),
|
||||
(
|
||||
"root",
|
||||
TaskUsageStatus::Available,
|
||||
Some(150.0),
|
||||
Some(0.0),
|
||||
Some("-0.000000000000000001")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
row.groups[0].amounts.five_hour_limit_percent,
|
||||
row.groups[0].amounts.weekly_limit_percent
|
||||
),
|
||||
(Some(150.25), Some(0.125))
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Invalid task usage response.")
|
||||
);
|
||||
}
|
||||
}
|
||||
server.reset().await;
|
||||
for queries in [
|
||||
vec![],
|
||||
vec![query.clone(), query.clone()],
|
||||
vec![TaskUsageThread {
|
||||
thread_id: "root".into(),
|
||||
created_at: None,
|
||||
descendant_thread_ids: (0..1_000).map(|n| format!("child-{n}")).collect(),
|
||||
}],
|
||||
] {
|
||||
assert!(client.get_task_usage(&queries).await.is_err());
|
||||
}
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
@@ -47,4 +47,12 @@ pub use client::plan_history::PlanLimitDimension;
|
||||
pub use client::plan_history::PlanLimitHistory;
|
||||
pub use client::plan_history::PlanLimitPeriod;
|
||||
pub use client::plan_history::PlanLimitValue;
|
||||
|
||||
pub use client::task_usage::TaskCredits;
|
||||
pub use client::task_usage::TaskUsage;
|
||||
pub use client::task_usage::TaskUsageAmounts;
|
||||
pub use client::task_usage::TaskUsageGroup;
|
||||
pub use client::task_usage::TaskUsageResponse;
|
||||
pub use client::task_usage::TaskUsageStatus;
|
||||
pub use client::task_usage::TaskUsageThread;
|
||||
pub use codex_backend_openapi_models::models::analytics as analytics_models;
|
||||
Reference in new issue
Block a user