aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
@@ -1,182 +0,0 @@
|
||||
//! Local analytics authentication, server plan discovery, and account/user identity checks.
|
||||
//! Each new session fetches its plan once; token plan claims do not select reports.
|
||||
|
||||
use crate::Client;
|
||||
use crate::RequestError;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthManagerConfig;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::account::PlanType;
|
||||
use codex_runtime_agent_instance::RegistrationError;
|
||||
use codex_runtime_agent_instance::RuntimeAuthError;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::resolve_installation_id;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Non-secret account metadata associated with an analytics session.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnalyticsAccount {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub plan_type: Option<PlanType>,
|
||||
}
|
||||
|
||||
/// A backend client bound to its initial ChatGPT account and user, with a server plan snapshot.
|
||||
pub struct AnalyticsSession {
|
||||
client: Client,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
auth: CodexAuth,
|
||||
account: AnalyticsAccount,
|
||||
}
|
||||
|
||||
impl AnalyticsSession {
|
||||
/// Load local ChatGPT credentials and the current server plan using the configured HTTP policy.
|
||||
pub async fn from_config(
|
||||
config: &impl AuthManagerConfig,
|
||||
http_client_factory: HttpClientFactory,
|
||||
runtime_auth_mode: Option<RuntimeAuthMode>,
|
||||
) -> Result<Self, String> {
|
||||
let auth_manager =
|
||||
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
"Couldn't load local sign-in. Sign in with ChatGPT and retry.".to_string()
|
||||
})?;
|
||||
let auth = auth_manager
|
||||
.auth()
|
||||
.await
|
||||
.filter(CodexAuth::is_chatgpt_auth)
|
||||
.ok_or("Sign in locally with ChatGPT to view Analytics.")?;
|
||||
let (Some(id), Some(_)) = (auth.get_account_id(), auth.get_chatgpt_user_id()) else {
|
||||
return Err("Analytics requires a ChatGPT account and user identity.".into());
|
||||
};
|
||||
let account = AnalyticsAccount {
|
||||
id,
|
||||
email: auth.get_account_email(),
|
||||
plan_type: None,
|
||||
};
|
||||
let base_url = config.chatgpt_base_url();
|
||||
let runtime_auth_mode = runtime_auth_mode
|
||||
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(&base_url));
|
||||
let client = match runtime_auth_mode {
|
||||
Some(mode) => {
|
||||
let home = AbsolutePathBuf::from_absolute_path(config.codex_home())
|
||||
.map_err(|_| "Couldn't initialize local Analytics authentication.")?;
|
||||
let installation_id = resolve_installation_id(&home)
|
||||
.await
|
||||
.map_err(|_| "Couldn't initialize local Analytics authentication.")?;
|
||||
let runtime = (
|
||||
Arc::new(RuntimeAuthManager::for_codex(
|
||||
Arc::clone(&auth_manager),
|
||||
&base_url,
|
||||
&installation_id,
|
||||
)),
|
||||
mode,
|
||||
);
|
||||
Client::from_auth_with_runtime_without_redirects(
|
||||
&base_url,
|
||||
&auth,
|
||||
http_client_factory,
|
||||
Some(&runtime),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
match error.downcast_ref::<RuntimeAuthError>() {
|
||||
Some(
|
||||
RuntimeAuthError::RefreshFailed
|
||||
| RuntimeAuthError::RefreshTokenFailed(_)
|
||||
| RuntimeAuthError::Registration(RegistrationError::Rejected {
|
||||
status: http::StatusCode::UNAUTHORIZED,
|
||||
..
|
||||
}),
|
||||
) => "Sign in again to load Analytics.",
|
||||
_ => "Couldn't authenticate the Analytics request.",
|
||||
}
|
||||
})?
|
||||
}
|
||||
None => Client::new_without_redirects(base_url, http_client_factory)
|
||||
.with_auth_provider(codex_model_provider::auth_provider_from_auth_manager(
|
||||
Arc::clone(&auth_manager),
|
||||
&auth,
|
||||
))
|
||||
.map_err(|_| "Couldn't initialize local Analytics authentication.")?,
|
||||
};
|
||||
let mut session = Self {
|
||||
client,
|
||||
auth_manager,
|
||||
auth,
|
||||
account,
|
||||
};
|
||||
let accounts = session
|
||||
.request(|client| async move { client.get_accounts_check().await })
|
||||
.await;
|
||||
// Preserve account-switch guidance even when it interrupts account discovery.
|
||||
session.ensure_identity().await?;
|
||||
let accounts = accounts.map_err(|error| {
|
||||
if error.is_unauthorized() {
|
||||
"Sign in again to load Analytics."
|
||||
} else {
|
||||
"Couldn't load account plan. Press R to retry Analytics."
|
||||
}
|
||||
})?;
|
||||
session.account.plan_type = Some(
|
||||
accounts
|
||||
.accounts
|
||||
.into_iter()
|
||||
.find(|account| account.id == session.account.id)
|
||||
.and_then(|account| account.plan_type)
|
||||
.ok_or("Couldn't load account plan. Press R to retry Analytics.")?,
|
||||
);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Return the account metadata captured when this session was opened.
|
||||
pub fn account(&self) -> &AnalyticsAccount {
|
||||
&self.account
|
||||
}
|
||||
/// Reject responses or cached data after a local account or user change.
|
||||
pub async fn ensure_identity(&self) -> Result<(), String> {
|
||||
self.auth_manager.reload().await;
|
||||
let current = self.auth_manager.auth().await;
|
||||
if current.is_none_or(|auth| {
|
||||
auth.get_account_id() != self.auth.get_account_id()
|
||||
|| auth.get_chatgpt_user_id() != self.auth.get_chatgpt_user_id()
|
||||
}) {
|
||||
return Err("Account changed. Press R to refresh Analytics.".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run an account-scoped request with bounded unauthorized recovery.
|
||||
pub async fn request<T, F>(&self, request: impl Fn(Client) -> F) -> Result<T, RequestError>
|
||||
where
|
||||
F: std::future::Future<Output = Result<T, RequestError>>,
|
||||
{
|
||||
let mut recovery = self.auth_manager.unauthorized_recovery();
|
||||
loop {
|
||||
self.ensure_identity()
|
||||
.await
|
||||
.map_err(|error| RequestError::Other(anyhow::anyhow!(error)))?;
|
||||
let result = request(self.client.clone()).await;
|
||||
// Keep the original 401 when recovery fails so callers retain sign-in guidance.
|
||||
if result.as_ref().is_err_and(RequestError::is_unauthorized)
|
||||
&& recovery.has_next()
|
||||
&& recovery.next().await.is_ok()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
self.ensure_identity()
|
||||
.await
|
||||
.map_err(|error| RequestError::Other(anyhow::anyhow!(error)))?;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "analytics_session_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,114 +0,0 @@
|
||||
//! Authentication recovery preserves actionable status without changing the account scope.
|
||||
|
||||
use super::*;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_protocol::auth::RefreshTokenFailedError;
|
||||
use codex_protocol::auth::RefreshTokenFailedReason;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
|
||||
enum RefreshOutcome {
|
||||
Accepted,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
struct ExternalCredentials {
|
||||
auth: CodexAuth,
|
||||
outcome: RefreshOutcome,
|
||||
refreshes: AtomicUsize,
|
||||
}
|
||||
|
||||
impl ExternalAuth for ExternalCredentials {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.auth.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
self.refreshes.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
match self.outcome {
|
||||
RefreshOutcome::Accepted => Ok(self.auth.clone()),
|
||||
RefreshOutcome::Rejected => Err(std::io::Error::other("refresh rejected")),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn classify_error(&self, error: std::io::Error) -> RefreshTokenError {
|
||||
RefreshTokenError::Permanent(RefreshTokenFailedError::new(
|
||||
RefreshTokenFailedReason::Other,
|
||||
error.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_recovery_preserves_unauthorized_status() {
|
||||
assert_unauthorized_after_recovery(RefreshOutcome::Rejected, /*expected_requests*/ 1).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persistent_unauthorized_stops_after_successful_recovery() {
|
||||
assert_unauthorized_after_recovery(RefreshOutcome::Accepted, /*expected_requests*/ 2).await;
|
||||
}
|
||||
|
||||
async fn assert_unauthorized_after_recovery(outcome: RefreshOutcome, expected_requests: u64) {
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
"e30.eyJleHAiOjQxMDI0NDQ4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X3VzZXJfaWQiOiJ1c2VyLWEifX0.test", "account-a", Some("plus"),
|
||||
).unwrap();
|
||||
let auth_manager = AuthManager::from_auth_for_testing(auth.clone());
|
||||
let credentials = Arc::new(ExternalCredentials {
|
||||
auth: auth.clone(),
|
||||
outcome,
|
||||
refreshes: AtomicUsize::new(/*v*/ 0),
|
||||
});
|
||||
auth_manager
|
||||
.set_external_auth(credentials.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 401))
|
||||
.expect(expected_requests)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = Client::new_without_redirects(
|
||||
server.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.with_auth_provider(codex_model_provider::auth_provider_from_auth_manager(
|
||||
Arc::clone(&auth_manager),
|
||||
&auth,
|
||||
))
|
||||
.unwrap();
|
||||
let session = AnalyticsSession {
|
||||
account: AnalyticsAccount {
|
||||
id: "account-a".into(),
|
||||
email: None,
|
||||
plan_type: auth.account_plan_type(),
|
||||
},
|
||||
client,
|
||||
auth_manager,
|
||||
auth,
|
||||
};
|
||||
let error = session
|
||||
.request(|client| async move {
|
||||
client
|
||||
.get_account_analytics(crate::AnalyticsReport::Usage, "2026-09-01", "2026-09-07")
|
||||
.await
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.status().map(|status| status.as_u16()), Some(401));
|
||||
session.ensure_identity().await.unwrap();
|
||||
assert_eq!(credentials.refreshes.load(Ordering::SeqCst), 1);
|
||||
server.verify().await;
|
||||
}
|
||||
@@ -43,7 +43,6 @@ use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) mod analytics;
|
||||
mod chatgpt_turn_cost;
|
||||
pub(crate) mod plan_history;
|
||||
pub(crate) mod profile;
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
//! Authenticated account analytics reads. Attribution and missing amounts remain unmodified.
|
||||
|
||||
use super::Client;
|
||||
use super::PathStyle;
|
||||
use super::RequestError;
|
||||
use codex_backend_openapi_models::models::analytics as models;
|
||||
use http::Method;
|
||||
|
||||
/// The bounded set of reports used by consumer and workspace Analytics views.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum AnalyticsReport {
|
||||
Usage,
|
||||
EnterpriseTokens,
|
||||
Credits,
|
||||
WorkspaceCredits,
|
||||
EnterpriseCredits { breakdown: &'static str },
|
||||
Messages,
|
||||
Plugins { limit: u8 },
|
||||
Skills { limit: u8 },
|
||||
}
|
||||
|
||||
/// Endpoint-specific backend contracts; normalization belongs to the consumer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AnalyticsResponse {
|
||||
Usage(models::DailyProductSurfaceUsageResponse),
|
||||
Credits(models::CreditUsageEventsResponse),
|
||||
EnterpriseCredits(models::CurrentUserCreditUsageResponse),
|
||||
Messages(models::DailyWorkspaceUsageCountResponse),
|
||||
Plugins(models::PluginUsageMetricsResponse),
|
||||
Skills(models::DailySkillUsageMetricsResponse),
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Fetches one report for an inclusive UTC date range supplied by the caller.
|
||||
pub async fn get_account_analytics(
|
||||
&self,
|
||||
report: AnalyticsReport,
|
||||
start_date: &str,
|
||||
end_date: &str,
|
||||
) -> Result<AnalyticsResponse, RequestError> {
|
||||
let route = match report {
|
||||
AnalyticsReport::Usage => "usage/daily-token-usage-breakdown",
|
||||
AnalyticsReport::Credits => "usage/credit-usage-events",
|
||||
AnalyticsReport::WorkspaceCredits | AnalyticsReport::EnterpriseTokens => {
|
||||
"usage/daily-workspace-user-token-usage-breakdown"
|
||||
}
|
||||
AnalyticsReport::EnterpriseCredits { .. } => "usage/daily-workspace-user-credit-usage",
|
||||
AnalyticsReport::Messages => "analytics/daily-workspace-usage-counts",
|
||||
AnalyticsReport::Plugins { .. } => "analytics/daily-plugin-usage-metrics",
|
||||
AnalyticsReport::Skills { .. } => "analytics/daily-skill-usage-metrics",
|
||||
};
|
||||
let prefix = match self.path_style {
|
||||
PathStyle::CodexApi => "api/codex",
|
||||
PathStyle::ChatGptApi => "wham",
|
||||
};
|
||||
let mut url = url::Url::parse(&format!("{}/{prefix}/{route}", self.base_url))
|
||||
.map_err(anyhow::Error::from)?;
|
||||
if report != AnalyticsReport::Credits {
|
||||
url.query_pairs_mut()
|
||||
.append_pair("start_date", start_date)
|
||||
.append_pair("end_date", end_date);
|
||||
if let AnalyticsReport::EnterpriseCredits { breakdown } = report {
|
||||
url.query_pairs_mut().append_pair("breakdown", breakdown);
|
||||
} else {
|
||||
url.query_pairs_mut().append_pair("group_by", "day");
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
report,
|
||||
AnalyticsReport::Messages
|
||||
| AnalyticsReport::Plugins { .. }
|
||||
| AnalyticsReport::Skills { .. }
|
||||
) {
|
||||
url.query_pairs_mut().append_pair("workspace_user", "true");
|
||||
}
|
||||
match report {
|
||||
AnalyticsReport::EnterpriseTokens => {
|
||||
url.query_pairs_mut()
|
||||
.append_pair("breakdown_by", "model")
|
||||
.append_pair("modes", "codex")
|
||||
.append_pair("modes", "work");
|
||||
}
|
||||
AnalyticsReport::Plugins { limit } => {
|
||||
url.query_pairs_mut()
|
||||
.append_pair("top_plugin_limit", &limit.to_string());
|
||||
}
|
||||
AnalyticsReport::Skills { limit } => {
|
||||
url.query_pairs_mut()
|
||||
.append_pair("top_skill_limit", &limit.to_string());
|
||||
}
|
||||
AnalyticsReport::Usage
|
||||
| AnalyticsReport::Credits
|
||||
| AnalyticsReport::WorkspaceCredits
|
||||
| AnalyticsReport::EnterpriseCredits { .. }
|
||||
| AnalyticsReport::Messages => {}
|
||||
}
|
||||
let request = self
|
||||
.request(Method::GET, url.as_str())
|
||||
.headers(self.headers().await?);
|
||||
let (body, _) = self
|
||||
.exec_request_detailed(request, "GET", url.as_str())
|
||||
.await?;
|
||||
// Do not include an untyped billing response in errors or diagnostics.
|
||||
let response = match report {
|
||||
AnalyticsReport::Usage
|
||||
| AnalyticsReport::EnterpriseTokens
|
||||
| AnalyticsReport::WorkspaceCredits => {
|
||||
serde_json::from_str(&body).map(AnalyticsResponse::Usage)
|
||||
}
|
||||
AnalyticsReport::Credits => serde_json::from_str(&body).map(AnalyticsResponse::Credits),
|
||||
AnalyticsReport::EnterpriseCredits { .. } => {
|
||||
serde_json::from_str(&body).map(AnalyticsResponse::EnterpriseCredits)
|
||||
}
|
||||
AnalyticsReport::Messages => {
|
||||
serde_json::from_str(&body).map(AnalyticsResponse::Messages)
|
||||
}
|
||||
AnalyticsReport::Plugins { .. } => {
|
||||
serde_json::from_str(&body).map(AnalyticsResponse::Plugins)
|
||||
}
|
||||
AnalyticsReport::Skills { .. } => {
|
||||
serde_json::from_str(&body).map(AnalyticsResponse::Skills)
|
||||
}
|
||||
};
|
||||
response.map_err(|_| RequestError::Other(anyhow::anyhow!("Invalid analytics response.")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "analytics_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,190 +0,0 @@
|
||||
//! HTTP contract coverage for account analytics report reads.
|
||||
|
||||
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 account_analytics_uses_personal_daily_scope_and_plugin_contract() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/analytics/daily-plugin-usage-metrics"))
|
||||
.and(query_param("start_date", "2026-01-03"))
|
||||
.and(query_param("end_date", "2026-01-09"))
|
||||
.and(query_param("group_by", "day"))
|
||||
.and(query_param("workspace_user", "true"))
|
||||
.and(query_param("top_plugin_limit", "10"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"data": [{"date": "2026-01-03", "plugin_usage_overviews": [{
|
||||
"plugin_id": null, "plugin_name": "example", "marketplace": null,
|
||||
"display_name": "Example plugin", "invocation_counts": 12
|
||||
}]}]
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = Client::new(
|
||||
server.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
);
|
||||
let response = client
|
||||
.get_account_analytics(
|
||||
AnalyticsReport::Plugins { limit: 10 },
|
||||
"2026-01-03",
|
||||
"2026-01-09",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response,
|
||||
AnalyticsResponse::Plugins(models::PluginUsageMetricsResponse {
|
||||
data: vec![models::PluginUsageBucket {
|
||||
date: "2026-01-03".into(),
|
||||
plugin_usage_overviews: vec![models::PluginUsageOverview {
|
||||
plugin_id: None,
|
||||
plugin_name: "example".into(),
|
||||
display_name: "Example plugin".into(),
|
||||
marketplace: None,
|
||||
invocation_counts: 12,
|
||||
}],
|
||||
}],
|
||||
data_freshness_ts: None,
|
||||
group_by: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_analytics_preserves_signed_credit_events() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/wham/usage/credit-usage-events"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"data": [{"date": "2026-01-03", "product_surface": "cli", "credit_amount": -0.004}]
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = Client::new(
|
||||
server.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
)
|
||||
.with_path_style(PathStyle::ChatGptApi);
|
||||
let response = client
|
||||
.get_account_analytics(AnalyticsReport::Credits, "2026-01-03", "2026-01-09")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response,
|
||||
AnalyticsResponse::Credits(models::CreditUsageEventsResponse {
|
||||
data: vec![models::CreditUsageEventBySurface {
|
||||
date: "2026-01-03".into(),
|
||||
product_surface: "cli".into(),
|
||||
credit_amount: -0.004,
|
||||
usage_id: None,
|
||||
}],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_analytics_rejects_another_reports_shape_without_logging_the_body() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/analytics/daily-workspace-usage-counts"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"data": [{"date": "2026-01-03", "product_surface": "sensitive-value", "credit_amount": 10}]
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = Client::new(
|
||||
server.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
);
|
||||
let error = client
|
||||
.get_account_analytics(AnalyticsReport::Messages, "2026-01-03", "2026-01-09")
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.to_string(), "Invalid analytics response.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_analytics_decodes_each_endpoint_and_accepts_new_string_values() {
|
||||
for (report, route, body, expected) in [
|
||||
(
|
||||
AnalyticsReport::Usage,
|
||||
"usage/daily-token-usage-breakdown",
|
||||
json!({"data": [{"date": "2026-01-03", "product_surface_usage_values": {"future_surface": 1.0}}], "units": "future_unit"}),
|
||||
AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse {
|
||||
data: vec![models::DailyProductSurfaceUsage {
|
||||
date: "2026-01-03".into(),
|
||||
product_surface_usage_values: [("future_surface".into(), 1.0)].into(),
|
||||
..Default::default()
|
||||
}],
|
||||
units: Some("future_unit".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
(
|
||||
AnalyticsReport::EnterpriseCredits { breakdown: "model" },
|
||||
"usage/daily-workspace-user-credit-usage",
|
||||
json!({"data": [], "series": [], "breakdown": "model"}),
|
||||
AnalyticsResponse::EnterpriseCredits(models::CurrentUserCreditUsageResponse {
|
||||
breakdown: "model".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
(
|
||||
AnalyticsReport::Messages,
|
||||
"analytics/daily-workspace-usage-counts",
|
||||
json!({"data": []}),
|
||||
AnalyticsResponse::Messages(models::DailyWorkspaceUsageCountResponse::default()),
|
||||
),
|
||||
(
|
||||
AnalyticsReport::Skills { limit: 10 },
|
||||
"analytics/daily-skill-usage-metrics",
|
||||
json!({"data": []}),
|
||||
AnalyticsResponse::Skills(models::DailySkillUsageMetricsResponse::default()),
|
||||
),
|
||||
(
|
||||
AnalyticsReport::WorkspaceCredits,
|
||||
"usage/daily-workspace-user-token-usage-breakdown",
|
||||
json!({"data": []}),
|
||||
AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse::default()),
|
||||
),
|
||||
(
|
||||
AnalyticsReport::EnterpriseTokens,
|
||||
"usage/daily-workspace-user-token-usage-breakdown",
|
||||
json!({"data": []}),
|
||||
AnalyticsResponse::Usage(models::DailyProductSurfaceUsageResponse::default()),
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/api/codex/{route}")))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(body))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = Client::new(
|
||||
server.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
);
|
||||
assert_eq!(
|
||||
client
|
||||
.get_account_analytics(report, "2026-01-03", "2026-01-09")
|
||||
.await
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
mod analytics_session;
|
||||
mod client;
|
||||
pub(crate) mod types;
|
||||
|
||||
pub use analytics_session::AnalyticsAccount;
|
||||
pub use analytics_session::AnalyticsSession;
|
||||
pub use client::AddCreditsNudgeCreditType;
|
||||
pub use client::ChatgptThreadTurnCosts;
|
||||
pub use client::ChatgptTurnCost;
|
||||
@@ -11,8 +8,6 @@ pub use client::Client;
|
||||
pub use client::RequestError;
|
||||
pub use client::ThreadUsage;
|
||||
pub use client::ThreadUsageBreakdownGroup;
|
||||
pub use client::analytics::AnalyticsReport;
|
||||
pub use client::analytics::AnalyticsResponse;
|
||||
pub use client::profile::AccountProfile;
|
||||
pub use client::profile::ProfileIdentity;
|
||||
pub use client::profile::ProfileInvocation;
|
||||
@@ -61,4 +56,3 @@ 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