Add gated plan usage history to TUI analytics (#45766)

## What changed

- Add consumer plan usage history behind `analytics_plan_history`, disabled by default, fetching seven days of five-hour and weekly allowance periods.
- Show period usage percentages with expandable breakdowns by feature, model, surface, or turn start, plus snapshot freshness and incomplete coverage indicators.
- Preserve unknown usage separately from zero and handle an unavailable history endpoint without blocking other analytics reports.

## Testing

Add backend and TUI tests for unavailable endpoints, response validation, feature and account gating, account changes during requests, period navigation, snapshot resets, and narrow and wide layouts.

GitOrigin-RevId: 7bea87a3407730b18040d7dda7e7dd0afe67fb2e
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-09-15 19:12:18 +00:00
1 parent 0e7ab7c1b5
commit 0d0979f457
23 files changed
+1062 -18

No files matched your search

+1
View File
@@ -36,6 +36,7 @@ use std::fmt;
pub(crate) mod analytics;
mod chatgpt_turn_cost;
pub(crate) mod plan_history;
mod rate_limit_resets;
mod thread_usage;
pub(crate) mod turn_usage;
@@ -0,0 +1,85 @@
//! Seven-day allowance snapshots, preserving historical limits and unknown accounting.
use super::Client;
use super::PathStyle;
use super::RequestError;
use http::Method;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitHistory {
pub data_as_of: Option<String>,
pub coverage_start: Option<String>,
pub coverage_complete: bool,
#[serde(default = "approximate_by_default")]
pub approximate: bool,
pub boundary_tolerance_seconds: Option<u32>,
pub periods: Vec<PlanLimitPeriod>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitPeriod {
pub id: String,
pub window_minutes: u32,
pub plan_type: String,
pub starts_at: String,
pub ends_at: String,
pub accounting_complete: bool,
/// Hundredths of a percent of this period's historical allowance; null is unknown.
pub used_basis_points: Option<f64>,
pub breakdowns: Option<Vec<PlanLimitBreakdown>>,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PlanLimitDimension {
ThreadSource,
TurnTrigger,
Model,
Surface,
/// Additive server dimensions must not discard the supported breakdowns.
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitBreakdown {
pub dimension: PlanLimitDimension,
pub rows: Vec<PlanLimitValue>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PlanLimitValue {
pub key: String,
pub basis_points: f64,
}
fn approximate_by_default() -> bool {
true
}
impl Client {
/// Fetches seven days of snapshot history. An undeployed route has no report.
pub async fn get_plan_limit_history(&self) -> Result<Option<PlanLimitHistory>, RequestError> {
let prefix = match self.path_style {
PathStyle::CodexApi => "api/codex",
PathStyle::ChatGptApi => "wham",
};
let url = format!("{}/{prefix}/usage/plan_limit_history?days=7", self.base_url);
let request = self.request(Method::GET, &url).headers(self.headers());
let (body, _) = match self.exec_request_detailed(request, "GET", &url).await {
Ok(response) => response,
Err(error) if error.status().is_some_and(|status| status.as_u16() == 404) => {
return Ok(None);
}
Err(error) => return Err(error),
};
serde_json::from_str(&body)
.map(Some)
.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid plan history response.")))
}
}
#[cfg(test)]
#[path = "plan_history_tests.rs"]
mod tests;
@@ -0,0 +1,51 @@
//! Plan history's undeployed route and wire defaults remain distinct from failures.
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
#[tokio::test]
async fn plan_history_handles_unavailable_errors_and_approximation_default() {
let server = MockServer::start().await;
let client = Client::new(
server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
);
for status in [404, 503, 200] {
server.reset().await;
Mock::given(method("GET"))
.and(path("/api/codex/usage/plan_limit_history"))
.and(query_param("days", "7"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"data_as_of": null, "coverage_start": null, "coverage_complete": false,
"boundary_tolerance_seconds": null, "periods": []
})))
.expect(/*r*/ 1)
.mount(&server)
.await;
let response = client.get_plan_limit_history().await;
match status {
404 => assert_eq!(response.unwrap(), None),
503 => assert_eq!(response.unwrap_err().status().unwrap().as_u16(), status),
200 => assert_eq!(
response.unwrap(),
Some(PlanLimitHistory {
data_as_of: None,
coverage_start: None,
coverage_complete: false,
approximate: true,
boundary_tolerance_seconds: None,
periods: vec![],
})
),
_ => unreachable!(),
}
}
}
+5
View File
@@ -42,4 +42,9 @@ pub use types::TokenUsageProfileDailyBucket;
pub use types::TokenUsageProfileStats;
pub use types::TurnAttemptsSiblingTurnsResponse;
pub use client::plan_history::PlanLimitBreakdown;
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 codex_backend_openapi_models::models::analytics as analytics_models;