mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-01 17:00:21 +08:00
feat: combine usage quota and pool stats updates
This commit is contained in:
@@ -3,12 +3,12 @@ pub(crate) use crate::handlers::admin::{
|
|||||||
build_internal_control_error_response, create_provider_oauth_catalog_key,
|
build_internal_control_error_response, create_provider_oauth_catalog_key,
|
||||||
find_duplicate_provider_oauth_key, maybe_build_local_admin_pool_response,
|
find_duplicate_provider_oauth_key, maybe_build_local_admin_pool_response,
|
||||||
maybe_build_local_admin_response, provider_oauth_runtime_endpoint_for_provider,
|
maybe_build_local_admin_response, provider_oauth_runtime_endpoint_for_provider,
|
||||||
refresh_antigravity_provider_quota_locally, refresh_codex_provider_quota_locally,
|
refresh_antigravity_provider_quota_locally, refresh_chatgpt_web_provider_quota_locally,
|
||||||
refresh_kiro_provider_quota_locally, refresh_provider_oauth_account_state_after_update,
|
refresh_codex_provider_quota_locally, refresh_kiro_provider_quota_locally,
|
||||||
update_existing_provider_oauth_catalog_key, AdminAppState,
|
refresh_provider_oauth_account_state_after_update, update_existing_provider_oauth_catalog_key,
|
||||||
AdminGatewayProviderTransportSnapshot, AdminLocalOAuthRefreshError, AdminRequestContext,
|
AdminAppState, AdminGatewayProviderTransportSnapshot, AdminLocalOAuthRefreshError,
|
||||||
AdminRouteRequest, AdminRouteResponse, AdminRouteResult, AdminStatsTimeRange,
|
AdminRequestContext, AdminRouteRequest, AdminRouteResponse, AdminRouteResult,
|
||||||
AdminStatsUsageFilter,
|
AdminStatsTimeRange, AdminStatsUsageFilter,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::handlers::admin::{
|
use crate::handlers::admin::{
|
||||||
|
|||||||
@@ -30,8 +30,9 @@ use super::{
|
|||||||
WalletLookupKey, WalletMutationOutcome,
|
WalletLookupKey, WalletMutationOutcome,
|
||||||
};
|
};
|
||||||
use aether_data_contracts::repository::usage::{
|
use aether_data_contracts::repository::usage::{
|
||||||
PendingUsageCleanupSummary, StoredUsageDailySummary, UsageAuditListQuery, UsageCleanupSummary,
|
PendingUsageCleanupSummary, ProviderApiKeyWindowUsageRequest,
|
||||||
UsageCleanupWindow, UsageDailyHeatmapQuery,
|
StoredProviderApiKeyWindowUsageSummary, StoredUsageDailySummary, UsageAuditListQuery,
|
||||||
|
UsageCleanupSummary, UsageCleanupWindow, UsageDailyHeatmapQuery,
|
||||||
};
|
};
|
||||||
use aether_video_tasks_core::read_data_backed_video_task_response;
|
use aether_video_tasks_core::read_data_backed_video_task_response;
|
||||||
|
|
||||||
@@ -1366,6 +1367,20 @@ impl GatewayDataState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<Vec<StoredProviderApiKeyWindowUsageSummary>, DataLayerError> {
|
||||||
|
match &self.usage_reader {
|
||||||
|
Some(repository) => {
|
||||||
|
repository
|
||||||
|
.summarize_usage_by_provider_api_key_windows(requests)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
None => Ok(Vec::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn list_users_by_ids(
|
pub(crate) async fn list_users_by_ids(
|
||||||
&self,
|
&self,
|
||||||
user_ids: &[String],
|
user_ids: &[String],
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ pub(crate) use self::provider::oauth::provisioning::{
|
|||||||
create_provider_oauth_catalog_key, update_existing_provider_oauth_catalog_key,
|
create_provider_oauth_catalog_key, update_existing_provider_oauth_catalog_key,
|
||||||
};
|
};
|
||||||
pub(crate) use self::provider::oauth::quota::antigravity::refresh_antigravity_provider_quota_locally;
|
pub(crate) use self::provider::oauth::quota::antigravity::refresh_antigravity_provider_quota_locally;
|
||||||
|
pub(crate) use self::provider::oauth::quota::chatgpt_web::refresh_chatgpt_web_provider_quota_locally;
|
||||||
pub(crate) use self::provider::oauth::quota::codex::refresh_codex_provider_quota_locally;
|
pub(crate) use self::provider::oauth::quota::codex::refresh_codex_provider_quota_locally;
|
||||||
pub(crate) use self::provider::oauth::quota::kiro::refresh_kiro_provider_quota_locally;
|
pub(crate) use self::provider::oauth::quota::kiro::refresh_kiro_provider_quota_locally;
|
||||||
pub(crate) use self::provider::oauth::runtime::{
|
pub(crate) use self::provider::oauth::runtime::{
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ use serde_json::json;
|
|||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
use super::super::oauth::quota::antigravity::refresh_antigravity_provider_quota_locally;
|
use super::super::oauth::quota::antigravity::refresh_antigravity_provider_quota_locally;
|
||||||
|
use super::super::oauth::quota::chatgpt_web::refresh_chatgpt_web_provider_quota_locally;
|
||||||
use super::super::oauth::quota::codex::refresh_codex_provider_quota_locally;
|
use super::super::oauth::quota::codex::refresh_codex_provider_quota_locally;
|
||||||
use super::super::oauth::quota::kiro::refresh_kiro_provider_quota_locally;
|
use super::super::oauth::quota::kiro::refresh_kiro_provider_quota_locally;
|
||||||
use super::super::oauth::quota::shared::normalize_string_id_list;
|
use super::super::oauth::quota::shared::normalize_string_id_list;
|
||||||
@@ -110,6 +111,13 @@ pub(super) async fn maybe_handle(
|
|||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
.or_else(|| endpoints.into_iter().find(|endpoint| endpoint.is_active)),
|
.or_else(|| endpoints.into_iter().find(|endpoint| endpoint.is_active)),
|
||||||
|
"chatgpt_web" => endpoints.into_iter().find(|endpoint| {
|
||||||
|
endpoint.is_active
|
||||||
|
&& endpoint
|
||||||
|
.api_format
|
||||||
|
.trim()
|
||||||
|
.eq_ignore_ascii_case("openai:image")
|
||||||
|
}),
|
||||||
_ => return Ok(None),
|
_ => return Ok(None),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -118,6 +126,7 @@ pub(super) async fn maybe_handle(
|
|||||||
"codex" => "找不到有效的 openai:responses 端点",
|
"codex" => "找不到有效的 openai:responses 端点",
|
||||||
"antigravity" => "找不到有效的 gemini:generate_content 端点",
|
"antigravity" => "找不到有效的 gemini:generate_content 端点",
|
||||||
"kiro" => "找不到有效的 Kiro 端点",
|
"kiro" => "找不到有效的 Kiro 端点",
|
||||||
|
"chatgpt_web" => "找不到有效的 openai:image 端点",
|
||||||
_ => "找不到有效端点",
|
_ => "找不到有效端点",
|
||||||
};
|
};
|
||||||
return Ok(Some(
|
return Ok(Some(
|
||||||
@@ -198,6 +207,10 @@ pub(super) async fn maybe_handle(
|
|||||||
refresh_antigravity_provider_quota_locally(state, &provider, &endpoint, keys, None)
|
refresh_antigravity_provider_quota_locally(state, &provider, &endpoint, keys, None)
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
|
"chatgpt_web" => {
|
||||||
|
refresh_chatgpt_web_provider_quota_locally(state, &provider, &endpoint, keys, None)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
}) else {
|
}) else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
|
|||||||
@@ -0,0 +1,521 @@
|
|||||||
|
use super::shared::{
|
||||||
|
build_quota_snapshot_payload, default_provider_quota_execution_timeouts,
|
||||||
|
execute_provider_quota_plan, extract_execution_error_message,
|
||||||
|
persist_provider_quota_refresh_state, quota_refresh_success_invalid_state,
|
||||||
|
ProviderQuotaExecutionOutcome,
|
||||||
|
};
|
||||||
|
use crate::handlers::admin::provider::shared::payloads::{
|
||||||
|
OAUTH_ACCOUNT_BLOCK_PREFIX, OAUTH_EXPIRED_PREFIX,
|
||||||
|
};
|
||||||
|
use crate::handlers::admin::request::{AdminAppState, AdminGatewayProviderTransportSnapshot};
|
||||||
|
use crate::GatewayError;
|
||||||
|
use aether_admin::provider::quota::parse_chatgpt_web_conversation_init_response;
|
||||||
|
use aether_contracts::{
|
||||||
|
ExecutionPlan, ProxySnapshot, RequestBody, EXECUTION_REQUEST_ACCEPT_INVALID_CERTS_HEADER,
|
||||||
|
};
|
||||||
|
use aether_data_contracts::repository::provider_catalog::{
|
||||||
|
StoredProviderCatalogEndpoint, StoredProviderCatalogKey, StoredProviderCatalogProvider,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
const CHATGPT_WEB_DEFAULT_BASE_URL: &str = "https://chatgpt.com";
|
||||||
|
const CHATGPT_WEB_CONVERSATION_INIT_PATH: &str = "/backend-api/conversation/init";
|
||||||
|
const CHATGPT_WEB_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0";
|
||||||
|
const CHATGPT_WEB_CLIENT_VERSION: &str = "prod-be885abbfcfe7b1f511e88b3003d9ee44757fbad";
|
||||||
|
const CHATGPT_WEB_BUILD_NUMBER: &str = "5955942";
|
||||||
|
const CHATGPT_WEB_SEC_CH_UA: &str =
|
||||||
|
r#""Microsoft Edge";v="143", "Chromium";v="143", "Not A(Brand";v="24""#;
|
||||||
|
const PLACEHOLDER_API_KEY: &str = "__placeholder__";
|
||||||
|
const CHATGPT_WEB_FREE_IMAGE_QUOTA_LIMIT: f64 = 25.0;
|
||||||
|
|
||||||
|
fn chatgpt_web_base_url(endpoint: &StoredProviderCatalogEndpoint) -> String {
|
||||||
|
let base_url = endpoint.base_url.trim().trim_end_matches('/');
|
||||||
|
if base_url.is_empty() {
|
||||||
|
CHATGPT_WEB_DEFAULT_BASE_URL.to_string()
|
||||||
|
} else {
|
||||||
|
base_url.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_chatgpt_web_quota_headers(
|
||||||
|
authorization: (String, String),
|
||||||
|
base_url: &str,
|
||||||
|
) -> BTreeMap<String, String> {
|
||||||
|
let device_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let session_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let mut headers = BTreeMap::from([
|
||||||
|
("accept".to_string(), "application/json".to_string()),
|
||||||
|
("content-type".to_string(), "application/json".to_string()),
|
||||||
|
("user-agent".to_string(), CHATGPT_WEB_USER_AGENT.to_string()),
|
||||||
|
("origin".to_string(), base_url.to_string()),
|
||||||
|
("referer".to_string(), format!("{base_url}/")),
|
||||||
|
(
|
||||||
|
"accept-language".to_string(),
|
||||||
|
"zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7".to_string(),
|
||||||
|
),
|
||||||
|
("cache-control".to_string(), "no-cache".to_string()),
|
||||||
|
("pragma".to_string(), "no-cache".to_string()),
|
||||||
|
("priority".to_string(), "u=1, i".to_string()),
|
||||||
|
("sec-ch-ua".to_string(), CHATGPT_WEB_SEC_CH_UA.to_string()),
|
||||||
|
("sec-ch-ua-arch".to_string(), r#""x86""#.to_string()),
|
||||||
|
("sec-ch-ua-bitness".to_string(), r#""64""#.to_string()),
|
||||||
|
("sec-ch-ua-mobile".to_string(), "?0".to_string()),
|
||||||
|
("sec-ch-ua-model".to_string(), r#""""#.to_string()),
|
||||||
|
("sec-ch-ua-platform".to_string(), r#""Windows""#.to_string()),
|
||||||
|
(
|
||||||
|
"sec-ch-ua-platform-version".to_string(),
|
||||||
|
r#""19.0.0""#.to_string(),
|
||||||
|
),
|
||||||
|
("sec-fetch-dest".to_string(), "empty".to_string()),
|
||||||
|
("sec-fetch-mode".to_string(), "cors".to_string()),
|
||||||
|
("sec-fetch-site".to_string(), "same-origin".to_string()),
|
||||||
|
("oai-device-id".to_string(), device_id),
|
||||||
|
("oai-session-id".to_string(), session_id),
|
||||||
|
("oai-language".to_string(), "zh-CN".to_string()),
|
||||||
|
(
|
||||||
|
"oai-client-version".to_string(),
|
||||||
|
CHATGPT_WEB_CLIENT_VERSION.to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"oai-client-build-number".to_string(),
|
||||||
|
CHATGPT_WEB_BUILD_NUMBER.to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"x-openai-target-path".to_string(),
|
||||||
|
CHATGPT_WEB_CONVERSATION_INIT_PATH.to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"x-openai-target-route".to_string(),
|
||||||
|
CHATGPT_WEB_CONVERSATION_INIT_PATH.to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
EXECUTION_REQUEST_ACCEPT_INVALID_CERTS_HEADER.to_string(),
|
||||||
|
"true".to_string(),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
headers.insert(authorization.0.to_ascii_lowercase(), authorization.1);
|
||||||
|
headers
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_auth_config(
|
||||||
|
transport: &AdminGatewayProviderTransportSnapshot,
|
||||||
|
) -> Option<serde_json::Value> {
|
||||||
|
transport
|
||||||
|
.key
|
||||||
|
.decrypted_auth_config
|
||||||
|
.as_deref()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.and_then(|value| serde_json::from_str::<serde_json::Value>(value).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_auth_config_string(
|
||||||
|
auth_config: Option<&serde_json::Value>,
|
||||||
|
fields: &[&str],
|
||||||
|
) -> Option<String> {
|
||||||
|
let object = auth_config.and_then(serde_json::Value::as_object)?;
|
||||||
|
fields.iter().find_map(|field| {
|
||||||
|
object
|
||||||
|
.get(*field)
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enrich_chatgpt_web_quota_metadata(
|
||||||
|
metadata: &mut serde_json::Value,
|
||||||
|
auth_config: Option<&serde_json::Value>,
|
||||||
|
) {
|
||||||
|
let Some(object) = metadata.as_object_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for (target, fields) in [
|
||||||
|
("plan_type", &["plan_type", "tier", "plan"][..]),
|
||||||
|
("email", &["email"][..]),
|
||||||
|
("account_id", &["account_id", "accountId"][..]),
|
||||||
|
("account_user_id", &["account_user_id", "accountUserId"][..]),
|
||||||
|
("user_id", &["user_id", "userId"][..]),
|
||||||
|
] {
|
||||||
|
if object.contains_key(target) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(value) = chatgpt_web_auth_config_string(auth_config, fields) {
|
||||||
|
object.insert(target.to_string(), json!(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_json_number(value: Option<&serde_json::Value>) -> Option<f64> {
|
||||||
|
let value = value?;
|
||||||
|
if let Some(number) = value.as_f64() {
|
||||||
|
return number.is_finite().then_some(number);
|
||||||
|
}
|
||||||
|
value
|
||||||
|
.as_str()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.and_then(|value| value.parse::<f64>().ok())
|
||||||
|
.filter(|value| value.is_finite())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_json_string(value: Option<&serde_json::Value>) -> Option<&str> {
|
||||||
|
value
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn existing_chatgpt_web_image_quota_limit(
|
||||||
|
upstream_metadata: Option<&serde_json::Value>,
|
||||||
|
) -> Option<f64> {
|
||||||
|
upstream_metadata
|
||||||
|
.and_then(serde_json::Value::as_object)
|
||||||
|
.and_then(|metadata| metadata.get("chatgpt_web"))
|
||||||
|
.and_then(serde_json::Value::as_object)
|
||||||
|
.and_then(|bucket| chatgpt_web_json_number(bucket.get("image_quota_total")))
|
||||||
|
.filter(|value| *value > 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn infer_chatgpt_web_image_quota_limit(
|
||||||
|
plan_type: Option<&str>,
|
||||||
|
remaining: Option<f64>,
|
||||||
|
existing_limit: Option<f64>,
|
||||||
|
) -> Option<f64> {
|
||||||
|
let normalized_plan = plan_type.unwrap_or_default().trim().to_ascii_lowercase();
|
||||||
|
if normalized_plan == "free" {
|
||||||
|
return Some(CHATGPT_WEB_FREE_IMAGE_QUOTA_LIMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(existing_limit) = existing_limit.filter(|value| *value > 0.0) {
|
||||||
|
return Some(existing_limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
remaining.filter(|value| *value > 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_chatgpt_web_image_quota_limit(
|
||||||
|
metadata: &mut serde_json::Value,
|
||||||
|
upstream_metadata: Option<&serde_json::Value>,
|
||||||
|
) {
|
||||||
|
let existing_limit = existing_chatgpt_web_image_quota_limit(upstream_metadata);
|
||||||
|
let Some(object) = metadata.as_object_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let remaining = chatgpt_web_json_number(object.get("image_quota_remaining"));
|
||||||
|
let explicit_limit =
|
||||||
|
chatgpt_web_json_number(object.get("image_quota_total")).filter(|value| *value > 0.0);
|
||||||
|
let plan_type = chatgpt_web_json_string(object.get("plan_type"));
|
||||||
|
let is_free_plan = plan_type.is_some_and(|value| value.trim().eq_ignore_ascii_case("free"));
|
||||||
|
let limit = if is_free_plan {
|
||||||
|
Some(CHATGPT_WEB_FREE_IMAGE_QUOTA_LIMIT)
|
||||||
|
} else {
|
||||||
|
explicit_limit
|
||||||
|
.or_else(|| infer_chatgpt_web_image_quota_limit(plan_type, remaining, existing_limit))
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(limit) = limit {
|
||||||
|
object.insert("image_quota_total".to_string(), json!(limit));
|
||||||
|
|
||||||
|
if !object.contains_key("image_quota_used") {
|
||||||
|
if let Some(remaining) = remaining {
|
||||||
|
object.insert(
|
||||||
|
"image_quota_used".to_string(),
|
||||||
|
json!((limit - remaining).max(0.0)),
|
||||||
|
);
|
||||||
|
} else if object
|
||||||
|
.get("image_quota_blocked")
|
||||||
|
.and_then(serde_json::Value::as_bool)
|
||||||
|
== Some(true)
|
||||||
|
{
|
||||||
|
object.insert("image_quota_used".to_string(), json!(limit));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_chatgpt_web_quota_auth(
|
||||||
|
state: &AdminAppState<'_>,
|
||||||
|
transport: &AdminGatewayProviderTransportSnapshot,
|
||||||
|
) -> Result<Option<(String, String)>, GatewayError> {
|
||||||
|
if let Some(auth) = state.resolve_local_oauth_header_auth(transport).await? {
|
||||||
|
return Ok(Some(auth));
|
||||||
|
}
|
||||||
|
let decrypted_key = transport.key.decrypted_api_key.trim();
|
||||||
|
if decrypted_key.is_empty() || decrypted_key == PLACEHOLDER_API_KEY {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(Some((
|
||||||
|
"authorization".to_string(),
|
||||||
|
format!("Bearer {decrypted_key}"),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute_chatgpt_web_quota_plan(
|
||||||
|
state: &AdminAppState<'_>,
|
||||||
|
transport: &AdminGatewayProviderTransportSnapshot,
|
||||||
|
endpoint: &StoredProviderCatalogEndpoint,
|
||||||
|
authorization: (String, String),
|
||||||
|
proxy_override: Option<&ProxySnapshot>,
|
||||||
|
) -> Result<ProviderQuotaExecutionOutcome, GatewayError> {
|
||||||
|
let base_url = chatgpt_web_base_url(endpoint);
|
||||||
|
let proxy = match proxy_override {
|
||||||
|
Some(proxy) => Some(proxy.clone()),
|
||||||
|
None => {
|
||||||
|
state
|
||||||
|
.resolve_transport_proxy_snapshot_with_tunnel_affinity(transport)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let timeouts = state
|
||||||
|
.resolve_transport_execution_timeouts(transport)
|
||||||
|
.or(Some(default_provider_quota_execution_timeouts(
|
||||||
|
proxy.as_ref(),
|
||||||
|
)));
|
||||||
|
let plan = ExecutionPlan {
|
||||||
|
request_id: format!("chatgpt-web-quota:{}", transport.key.id),
|
||||||
|
candidate_id: None,
|
||||||
|
provider_name: Some("chatgpt_web".to_string()),
|
||||||
|
provider_id: transport.provider.id.clone(),
|
||||||
|
endpoint_id: transport.endpoint.id.clone(),
|
||||||
|
key_id: transport.key.id.clone(),
|
||||||
|
method: "POST".to_string(),
|
||||||
|
url: format!("{base_url}{CHATGPT_WEB_CONVERSATION_INIT_PATH}"),
|
||||||
|
headers: build_chatgpt_web_quota_headers(authorization, base_url.as_str()),
|
||||||
|
content_type: Some("application/json".to_string()),
|
||||||
|
content_encoding: None,
|
||||||
|
body: RequestBody::from_json(json!({
|
||||||
|
"gizmo_id": serde_json::Value::Null,
|
||||||
|
"requested_default_model": serde_json::Value::Null,
|
||||||
|
"conversation_id": serde_json::Value::Null,
|
||||||
|
"timezone_offset_min": -480,
|
||||||
|
"system_hints": ["picture_v2"],
|
||||||
|
})),
|
||||||
|
stream: false,
|
||||||
|
client_api_format: "openai:image".to_string(),
|
||||||
|
provider_api_format: "chatgpt_web:conversation_init".to_string(),
|
||||||
|
model_name: Some("chatgpt-web-conversation-init".to_string()),
|
||||||
|
proxy,
|
||||||
|
transport_profile: state.resolve_transport_profile(transport),
|
||||||
|
timeouts,
|
||||||
|
};
|
||||||
|
|
||||||
|
execute_provider_quota_plan(state, transport, plan, "chatgpt_web").await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_quota_invalid_reason(status_code: u16, upstream_message: Option<&str>) -> String {
|
||||||
|
let message = upstream_message.unwrap_or_default().trim();
|
||||||
|
let detail = if message.is_empty() {
|
||||||
|
match status_code {
|
||||||
|
401 => "ChatGPT Web Token 无效或已过期",
|
||||||
|
403 => "ChatGPT Web 账户访问受限",
|
||||||
|
_ => "ChatGPT Web 请求失败",
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message
|
||||||
|
};
|
||||||
|
match status_code {
|
||||||
|
401 => format!("{OAUTH_EXPIRED_PREFIX}{detail}"),
|
||||||
|
403 => format!("{OAUTH_ACCOUNT_BLOCK_PREFIX}{detail}"),
|
||||||
|
_ => detail.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn refresh_chatgpt_web_provider_quota_locally(
|
||||||
|
state: &AdminAppState<'_>,
|
||||||
|
provider: &StoredProviderCatalogProvider,
|
||||||
|
endpoint: &StoredProviderCatalogEndpoint,
|
||||||
|
keys: Vec<StoredProviderCatalogKey>,
|
||||||
|
proxy_override: Option<ProxySnapshot>,
|
||||||
|
) -> Result<Option<serde_json::Value>, GatewayError> {
|
||||||
|
let mut results = Vec::new();
|
||||||
|
let mut success_count = 0usize;
|
||||||
|
let mut failed_count = 0usize;
|
||||||
|
|
||||||
|
for key in keys {
|
||||||
|
let transport = match state
|
||||||
|
.read_provider_transport_snapshot(&provider.id, &endpoint.id, &key.id)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Some(transport) => transport,
|
||||||
|
None => {
|
||||||
|
failed_count += 1;
|
||||||
|
results.push(json!({
|
||||||
|
"key_id": key.id,
|
||||||
|
"key_name": key.name,
|
||||||
|
"status": "error",
|
||||||
|
"message": "Provider transport snapshot unavailable",
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let authorization = match resolve_chatgpt_web_quota_auth(state, &transport).await? {
|
||||||
|
Some(auth) => auth,
|
||||||
|
None => {
|
||||||
|
failed_count += 1;
|
||||||
|
results.push(json!({
|
||||||
|
"key_id": key.id,
|
||||||
|
"key_name": key.name,
|
||||||
|
"status": "error",
|
||||||
|
"message": "缺少 ChatGPT Web OAuth 认证信息,请先导入/刷新 Token",
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = match execute_chatgpt_web_quota_plan(
|
||||||
|
state,
|
||||||
|
&transport,
|
||||||
|
endpoint,
|
||||||
|
authorization,
|
||||||
|
proxy_override.as_ref(),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
ProviderQuotaExecutionOutcome::Response(result) => result,
|
||||||
|
ProviderQuotaExecutionOutcome::Failure(detail) => {
|
||||||
|
failed_count += 1;
|
||||||
|
results.push(json!({
|
||||||
|
"key_id": key.id,
|
||||||
|
"key_name": key.name,
|
||||||
|
"status": "error",
|
||||||
|
"message": format!("conversation/init 请求执行失败: {detail}"),
|
||||||
|
"status_code": 502,
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let now_unix_secs = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.ok()
|
||||||
|
.map(|duration| duration.as_secs())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let mut metadata_update = None::<serde_json::Value>;
|
||||||
|
let (mut oauth_invalid_at_unix_secs, mut oauth_invalid_reason) = (
|
||||||
|
key.oauth_invalid_at_unix_secs,
|
||||||
|
key.oauth_invalid_reason.clone(),
|
||||||
|
);
|
||||||
|
let mut status = "error".to_string();
|
||||||
|
let mut message = None::<String>;
|
||||||
|
|
||||||
|
if result.status_code == 200 {
|
||||||
|
if let Some(body_json) = result
|
||||||
|
.body
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|body| body.json_body.as_ref())
|
||||||
|
{
|
||||||
|
if let Some(mut metadata) =
|
||||||
|
parse_chatgpt_web_conversation_init_response(body_json, now_unix_secs)
|
||||||
|
{
|
||||||
|
let auth_config = chatgpt_web_auth_config(&transport);
|
||||||
|
enrich_chatgpt_web_quota_metadata(&mut metadata, auth_config.as_ref());
|
||||||
|
normalize_chatgpt_web_image_quota_limit(
|
||||||
|
&mut metadata,
|
||||||
|
key.upstream_metadata.as_ref(),
|
||||||
|
);
|
||||||
|
metadata_update = Some(json!({ "chatgpt_web": metadata }));
|
||||||
|
(oauth_invalid_at_unix_secs, oauth_invalid_reason) =
|
||||||
|
quota_refresh_success_invalid_state(&key);
|
||||||
|
status = "success".to_string();
|
||||||
|
} else {
|
||||||
|
status = "no_metadata".to_string();
|
||||||
|
message = Some("响应中未包含 ChatGPT Web 生图限额信息".to_string());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
status = "no_metadata".to_string();
|
||||||
|
message = Some("响应中未包含 ChatGPT Web 生图限额信息".to_string());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let err_msg = extract_execution_error_message(&result);
|
||||||
|
message = Some(match err_msg.as_deref() {
|
||||||
|
Some(detail) if !detail.is_empty() => {
|
||||||
|
format!(
|
||||||
|
"conversation/init 返回状态码 {}: {}",
|
||||||
|
result.status_code, detail
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_ => format!("conversation/init 返回状态码 {}", result.status_code),
|
||||||
|
});
|
||||||
|
|
||||||
|
if matches!(result.status_code, 401 | 403) {
|
||||||
|
oauth_invalid_at_unix_secs = Some(now_unix_secs);
|
||||||
|
oauth_invalid_reason = Some(chatgpt_web_quota_invalid_reason(
|
||||||
|
result.status_code,
|
||||||
|
err_msg.as_deref(),
|
||||||
|
));
|
||||||
|
status = if result.status_code == 401 {
|
||||||
|
"auth_invalid".to_string()
|
||||||
|
} else {
|
||||||
|
"forbidden".to_string()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !persist_provider_quota_refresh_state(
|
||||||
|
state,
|
||||||
|
&key.id,
|
||||||
|
metadata_update.as_ref(),
|
||||||
|
oauth_invalid_at_unix_secs,
|
||||||
|
oauth_invalid_reason,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
failed_count += 1;
|
||||||
|
results.push(json!({
|
||||||
|
"key_id": key.id,
|
||||||
|
"key_name": key.name,
|
||||||
|
"status": "error",
|
||||||
|
"message": "Key 状态写入失败",
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if status == "success" {
|
||||||
|
success_count += 1;
|
||||||
|
} else {
|
||||||
|
failed_count += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut payload = serde_json::Map::new();
|
||||||
|
payload.insert("key_id".to_string(), json!(key.id));
|
||||||
|
payload.insert("key_name".to_string(), json!(key.name));
|
||||||
|
payload.insert("status".to_string(), json!(status));
|
||||||
|
if let Some(message) = message {
|
||||||
|
payload.insert("message".to_string(), json!(message));
|
||||||
|
}
|
||||||
|
if result.status_code != 200 {
|
||||||
|
payload.insert("status_code".to_string(), json!(result.status_code));
|
||||||
|
}
|
||||||
|
if let Some(metadata) = metadata_update
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|value| value.get("chatgpt_web"))
|
||||||
|
.cloned()
|
||||||
|
{
|
||||||
|
payload.insert("metadata".to_string(), metadata);
|
||||||
|
}
|
||||||
|
if let Some(quota_snapshot) = build_quota_snapshot_payload(
|
||||||
|
"chatgpt_web",
|
||||||
|
key.status_snapshot.as_ref(),
|
||||||
|
metadata_update.as_ref(),
|
||||||
|
) {
|
||||||
|
payload.insert("quota_snapshot".to_string(), quota_snapshot);
|
||||||
|
}
|
||||||
|
results.push(serde_json::Value::Object(payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Some(json!({
|
||||||
|
"success": success_count,
|
||||||
|
"failed": failed_count,
|
||||||
|
"total": success_count + failed_count,
|
||||||
|
"results": results,
|
||||||
|
"message": format!("已处理 {} 个 Key", success_count + failed_count),
|
||||||
|
"auto_removed": 0,
|
||||||
|
})))
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub(crate) mod antigravity;
|
pub(crate) mod antigravity;
|
||||||
|
pub(crate) mod chatgpt_web;
|
||||||
pub(crate) mod codex;
|
pub(crate) mod codex;
|
||||||
pub(crate) mod kiro;
|
pub(crate) mod kiro;
|
||||||
pub(crate) mod shared;
|
pub(crate) mod shared;
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ pub(crate) async fn persist_provider_quota_refresh_state(
|
|||||||
metadata_update,
|
metadata_update,
|
||||||
));
|
));
|
||||||
quota_snapshot_provider_type = metadata_update.as_object().and_then(|object| {
|
quota_snapshot_provider_type = metadata_update.as_object().and_then(|object| {
|
||||||
["codex", "kiro", "antigravity", "gemini_cli"]
|
["codex", "kiro", "antigravity", "gemini_cli", "chatgpt_web"]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|provider_type| object.contains_key(*provider_type))
|
.find(|provider_type| object.contains_key(*provider_type))
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::quota::antigravity::refresh_antigravity_provider_quota_locally;
|
use super::quota::antigravity::refresh_antigravity_provider_quota_locally;
|
||||||
|
use super::quota::chatgpt_web::refresh_chatgpt_web_provider_quota_locally;
|
||||||
use super::quota::codex::refresh_codex_provider_quota_locally;
|
use super::quota::codex::refresh_codex_provider_quota_locally;
|
||||||
use super::quota::kiro::refresh_kiro_provider_quota_locally;
|
use super::quota::kiro::refresh_kiro_provider_quota_locally;
|
||||||
use crate::handlers::admin::request::AdminAppState;
|
use crate::handlers::admin::request::AdminAppState;
|
||||||
@@ -72,7 +73,10 @@ pub(crate) async fn refresh_provider_oauth_account_state_after_update(
|
|||||||
proxy_override: Option<&ProxySnapshot>,
|
proxy_override: Option<&ProxySnapshot>,
|
||||||
) -> Result<(bool, Option<String>), GatewayError> {
|
) -> Result<(bool, Option<String>), GatewayError> {
|
||||||
let provider_type = provider.provider_type.trim().to_ascii_lowercase();
|
let provider_type = provider.provider_type.trim().to_ascii_lowercase();
|
||||||
if !matches!(provider_type.as_str(), "codex" | "kiro" | "antigravity") {
|
if !matches!(
|
||||||
|
provider_type.as_str(),
|
||||||
|
"codex" | "kiro" | "antigravity" | "chatgpt_web"
|
||||||
|
) {
|
||||||
return Ok((false, None));
|
return Ok((false, None));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,6 +131,16 @@ pub(crate) async fn refresh_provider_oauth_account_state_after_update(
|
|||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
|
"chatgpt_web" => {
|
||||||
|
refresh_chatgpt_web_provider_quota_locally(
|
||||||
|
state,
|
||||||
|
provider,
|
||||||
|
&endpoint,
|
||||||
|
vec![key],
|
||||||
|
proxy_override,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
let Some(payload) = payload else {
|
let Some(payload) = payload else {
|
||||||
|
|||||||
@@ -9,7 +9,11 @@ use aether_admin::provider::quota as admin_provider_quota_pure;
|
|||||||
use aether_data_contracts::repository::provider_catalog::{
|
use aether_data_contracts::repository::provider_catalog::{
|
||||||
StoredProviderCatalogEndpoint, StoredProviderCatalogKey,
|
StoredProviderCatalogEndpoint, StoredProviderCatalogKey,
|
||||||
};
|
};
|
||||||
|
use aether_data_contracts::repository::usage::{
|
||||||
|
ProviderApiKeyWindowUsageRequest, StoredProviderApiKeyWindowUsageSummary,
|
||||||
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
fn admin_pool_string_list(value: Option<&serde_json::Value>) -> Option<Vec<String>> {
|
fn admin_pool_string_list(value: Option<&serde_json::Value>) -> Option<Vec<String>> {
|
||||||
let values = value
|
let values = value
|
||||||
@@ -289,6 +293,124 @@ fn admin_pool_quota_window<'a>(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) type AdminPoolCodexWindowUsageByKey =
|
||||||
|
BTreeMap<(String, String), StoredProviderApiKeyWindowUsageSummary>;
|
||||||
|
|
||||||
|
fn admin_pool_provider_type_is_codex(provider_type: &str) -> bool {
|
||||||
|
provider_type.trim().eq_ignore_ascii_case("codex")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admin_pool_codex_window_usage_code(
|
||||||
|
window: &serde_json::Map<String, serde_json::Value>,
|
||||||
|
) -> Option<&'static str> {
|
||||||
|
let code = window
|
||||||
|
.get("code")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.map(str::trim)?;
|
||||||
|
if code.eq_ignore_ascii_case("5h") {
|
||||||
|
Some("5h")
|
||||||
|
} else if code.eq_ignore_ascii_case("weekly") {
|
||||||
|
Some("weekly")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admin_pool_codex_window_usage_bounds(
|
||||||
|
window: &serde_json::Map<String, serde_json::Value>,
|
||||||
|
) -> Option<(u64, u64)> {
|
||||||
|
let reset_at = admin_pool_json_to_u64(window.get("reset_at"))?;
|
||||||
|
let window_minutes = admin_pool_json_to_u64(window.get("window_minutes"))?;
|
||||||
|
let window_seconds = window_minutes.checked_mul(60)?;
|
||||||
|
let start = reset_at.checked_sub(window_seconds)?;
|
||||||
|
(start < reset_at).then_some((start, reset_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn build_admin_pool_codex_window_usage_requests(
|
||||||
|
provider_type: &str,
|
||||||
|
keys: &[StoredProviderCatalogKey],
|
||||||
|
) -> Vec<ProviderApiKeyWindowUsageRequest> {
|
||||||
|
if !admin_pool_provider_type_is_codex(provider_type) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut requests = Vec::new();
|
||||||
|
for key in keys {
|
||||||
|
let status_snapshot = provider_key_status_snapshot_payload(key, provider_type);
|
||||||
|
let Some(windows) = status_snapshot
|
||||||
|
.get("quota")
|
||||||
|
.and_then(serde_json::Value::as_object)
|
||||||
|
.and_then(|quota| quota.get("windows"))
|
||||||
|
.and_then(serde_json::Value::as_array)
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
for window in windows.iter().filter_map(serde_json::Value::as_object) {
|
||||||
|
let Some(window_code) = admin_pool_codex_window_usage_code(window) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some((start_unix_secs, end_unix_secs)) =
|
||||||
|
admin_pool_codex_window_usage_bounds(window)
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
requests.push(ProviderApiKeyWindowUsageRequest {
|
||||||
|
provider_api_key_id: key.id.clone(),
|
||||||
|
window_code: window_code.to_string(),
|
||||||
|
start_unix_secs,
|
||||||
|
end_unix_secs,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requests
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admin_pool_codex_window_usage_payload(
|
||||||
|
usage: &StoredProviderApiKeyWindowUsageSummary,
|
||||||
|
) -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"request_count": usage.request_count,
|
||||||
|
"total_tokens": usage.total_tokens,
|
||||||
|
"total_cost_usd": format!("{:.8}", usage.total_cost_usd),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admin_pool_attach_codex_window_usage(
|
||||||
|
status_snapshot: &mut serde_json::Value,
|
||||||
|
key_id: &str,
|
||||||
|
usage_by_key: &AdminPoolCodexWindowUsageByKey,
|
||||||
|
) {
|
||||||
|
if usage_by_key.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(windows) = status_snapshot
|
||||||
|
.get_mut("quota")
|
||||||
|
.and_then(serde_json::Value::as_object_mut)
|
||||||
|
.and_then(|quota| quota.get_mut("windows"))
|
||||||
|
.and_then(serde_json::Value::as_array_mut)
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
for window in windows
|
||||||
|
.iter_mut()
|
||||||
|
.filter_map(serde_json::Value::as_object_mut)
|
||||||
|
{
|
||||||
|
let Some(window_code) = admin_pool_codex_window_usage_code(window) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let lookup_key = (key_id.to_string(), window_code.to_string());
|
||||||
|
if let Some(usage) = usage_by_key.get(&lookup_key) {
|
||||||
|
window.insert(
|
||||||
|
"usage".to_string(),
|
||||||
|
admin_pool_codex_window_usage_payload(usage),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn admin_pool_quota_window_used_percent(
|
fn admin_pool_quota_window_used_percent(
|
||||||
window: &serde_json::Map<String, serde_json::Value>,
|
window: &serde_json::Map<String, serde_json::Value>,
|
||||||
) -> Option<f64> {
|
) -> Option<f64> {
|
||||||
@@ -481,6 +603,43 @@ fn admin_pool_build_kiro_account_quota_from_snapshot(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn admin_pool_build_chatgpt_web_account_quota_from_snapshot(
|
||||||
|
quota_snapshot: &serde_json::Map<String, serde_json::Value>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let now_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
|
||||||
|
let window = admin_pool_quota_window(quota_snapshot, "image_gen")
|
||||||
|
.or_else(|| admin_pool_quota_windows(quota_snapshot).into_iter().next())?;
|
||||||
|
let remaining_value = admin_pool_json_to_f64(window.get("remaining_value"));
|
||||||
|
let limit_value = admin_pool_json_to_f64(window.get("limit_value"));
|
||||||
|
let remaining_percent = admin_pool_json_to_f64(window.get("remaining_ratio"))
|
||||||
|
.map(|value| (value * 100.0).clamp(0.0, 100.0))
|
||||||
|
.or_else(|| {
|
||||||
|
admin_pool_json_to_f64(window.get("used_ratio"))
|
||||||
|
.map(|value| ((1.0 - value) * 100.0).clamp(0.0, 100.0))
|
||||||
|
});
|
||||||
|
let reset_seconds =
|
||||||
|
admin_pool_quota_window_reset_seconds(quota_snapshot, window, now_unix_secs);
|
||||||
|
|
||||||
|
let mut text = match (remaining_value, limit_value, remaining_percent) {
|
||||||
|
(Some(remaining), Some(limit), _) if limit > 0.0 => Some(format!(
|
||||||
|
"生图剩余 {}/{}",
|
||||||
|
admin_pool_format_quota_value(remaining),
|
||||||
|
admin_pool_format_quota_value(limit),
|
||||||
|
)),
|
||||||
|
(Some(remaining), _, _) => Some(format!(
|
||||||
|
"生图剩余 {}",
|
||||||
|
admin_pool_format_quota_value(remaining),
|
||||||
|
)),
|
||||||
|
(_, _, Some(percent)) => Some(format!("生图剩余 {}", admin_pool_format_percent(percent))),
|
||||||
|
_ => None,
|
||||||
|
}?;
|
||||||
|
|
||||||
|
if let Some(reset_text) = reset_seconds.and_then(admin_pool_format_reset_after) {
|
||||||
|
text.push_str(&format!(" ({reset_text})"));
|
||||||
|
}
|
||||||
|
Some(text)
|
||||||
|
}
|
||||||
|
|
||||||
fn admin_pool_build_antigravity_account_quota_from_snapshot(
|
fn admin_pool_build_antigravity_account_quota_from_snapshot(
|
||||||
quota_snapshot: &serde_json::Map<String, serde_json::Value>,
|
quota_snapshot: &serde_json::Map<String, serde_json::Value>,
|
||||||
) -> Option<String> {
|
) -> Option<String> {
|
||||||
@@ -617,6 +776,13 @@ fn admin_pool_build_account_quota(
|
|||||||
return Some(account_quota);
|
return Some(account_quota);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"chatgpt_web" => {
|
||||||
|
if let Some(account_quota) =
|
||||||
|
admin_pool_build_chatgpt_web_account_quota_from_snapshot(quota_snapshot)
|
||||||
|
{
|
||||||
|
return Some(account_quota);
|
||||||
|
}
|
||||||
|
}
|
||||||
"antigravity" => {
|
"antigravity" => {
|
||||||
if let Some(account_quota) =
|
if let Some(account_quota) =
|
||||||
admin_pool_build_antigravity_account_quota_from_snapshot(quota_snapshot)
|
admin_pool_build_antigravity_account_quota_from_snapshot(quota_snapshot)
|
||||||
@@ -760,6 +926,7 @@ pub(super) fn build_admin_pool_key_payload(
|
|||||||
key: &StoredProviderCatalogKey,
|
key: &StoredProviderCatalogKey,
|
||||||
runtime: &AdminProviderPoolRuntimeState,
|
runtime: &AdminProviderPoolRuntimeState,
|
||||||
pool_config: Option<AdminProviderPoolConfig>,
|
pool_config: Option<AdminProviderPoolConfig>,
|
||||||
|
codex_window_usage_by_key: &AdminPoolCodexWindowUsageByKey,
|
||||||
) -> serde_json::Value {
|
) -> serde_json::Value {
|
||||||
let cooldown_reason = runtime.cooldown_reason_by_key.get(&key.id).cloned();
|
let cooldown_reason = runtime.cooldown_reason_by_key.get(&key.id).cloned();
|
||||||
let cooldown_ttl_seconds = cooldown_reason
|
let cooldown_ttl_seconds = cooldown_reason
|
||||||
@@ -777,7 +944,14 @@ pub(super) fn build_admin_pool_key_payload(
|
|||||||
admin_pool_derive_oauth_expires_at(provider_type, key, auth_config.as_ref());
|
admin_pool_derive_oauth_expires_at(provider_type, key, auth_config.as_ref());
|
||||||
let oauth_plan_type =
|
let oauth_plan_type =
|
||||||
admin_pool_derive_oauth_plan_type(key, provider_type, auth_config.as_ref());
|
admin_pool_derive_oauth_plan_type(key, provider_type, auth_config.as_ref());
|
||||||
let status_snapshot = provider_key_status_snapshot_payload(key, provider_type);
|
let mut status_snapshot = provider_key_status_snapshot_payload(key, provider_type);
|
||||||
|
if admin_pool_provider_type_is_codex(provider_type) {
|
||||||
|
admin_pool_attach_codex_window_usage(
|
||||||
|
&mut status_snapshot,
|
||||||
|
&key.id,
|
||||||
|
codex_window_usage_by_key,
|
||||||
|
);
|
||||||
|
}
|
||||||
let account_snapshot = status_snapshot
|
let account_snapshot = status_snapshot
|
||||||
.get("account")
|
.get("account")
|
||||||
.and_then(serde_json::Value::as_object);
|
.and_then(serde_json::Value::as_object);
|
||||||
|
|||||||
@@ -253,6 +253,26 @@ pub(super) async fn build_admin_pool_list_keys_response(
|
|||||||
}
|
}
|
||||||
_ => AdminProviderPoolRuntimeState::default(),
|
_ => AdminProviderPoolRuntimeState::default(),
|
||||||
};
|
};
|
||||||
|
let codex_window_usage_requests =
|
||||||
|
pool_payloads::build_admin_pool_codex_window_usage_requests(&provider.provider_type, &keys);
|
||||||
|
let codex_window_usage_by_key: pool_payloads::AdminPoolCodexWindowUsageByKey =
|
||||||
|
if codex_window_usage_requests.is_empty() {
|
||||||
|
pool_payloads::AdminPoolCodexWindowUsageByKey::new()
|
||||||
|
} else {
|
||||||
|
state
|
||||||
|
.app()
|
||||||
|
.summarize_usage_by_provider_api_key_windows(&codex_window_usage_requests)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|usage| {
|
||||||
|
(
|
||||||
|
(usage.provider_api_key_id.clone(), usage.window_code.clone()),
|
||||||
|
usage,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
|
||||||
let items = keys
|
let items = keys
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|key| {
|
.map(|key| {
|
||||||
@@ -263,6 +283,7 @@ pub(super) async fn build_admin_pool_list_keys_response(
|
|||||||
&key,
|
&key,
|
||||||
&runtime,
|
&runtime,
|
||||||
pool_config.clone(),
|
pool_config.clone(),
|
||||||
|
&codex_window_usage_by_key,
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|||||||
@@ -425,6 +425,31 @@ fn quota_window_reset_seconds(
|
|||||||
.map(|(observed_at, reset_at)| reset_at.saturating_sub(observed_at))
|
.map(|(observed_at, reset_at)| reset_at.saturating_sub(observed_at))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_image_quota_limit(
|
||||||
|
metadata: &Map<String, Value>,
|
||||||
|
remaining: Option<f64>,
|
||||||
|
) -> Option<f64> {
|
||||||
|
let plan_type = metadata
|
||||||
|
.get("plan_type")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(|value| value.to_ascii_lowercase());
|
||||||
|
if plan_type.as_deref() == Some("free") {
|
||||||
|
return Some(25.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let explicit_limit = metadata
|
||||||
|
.get("image_quota_total")
|
||||||
|
.and_then(admin_provider_quota_pure::coerce_json_f64)
|
||||||
|
.filter(|value| *value > 0.0);
|
||||||
|
if let Some(limit) = explicit_limit {
|
||||||
|
return Some(limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
remaining.filter(|value| *value > 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
fn model_quota_window_snapshot(
|
fn model_quota_window_snapshot(
|
||||||
model_name: &str,
|
model_name: &str,
|
||||||
item: &Map<String, Value>,
|
item: &Map<String, Value>,
|
||||||
@@ -813,6 +838,98 @@ fn build_kiro_quota_status_snapshot(
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn build_chatgpt_web_quota_status_snapshot(
|
||||||
|
upstream_metadata: Option<&Value>,
|
||||||
|
source: &str,
|
||||||
|
) -> Option<Value> {
|
||||||
|
let metadata = provider_quota_metadata_bucket(upstream_metadata, "chatgpt_web")?;
|
||||||
|
let observed_at_unix_secs = provider_quota_timestamp_unix_secs(metadata.get("updated_at"));
|
||||||
|
let remaining = metadata
|
||||||
|
.get("image_quota_remaining")
|
||||||
|
.and_then(admin_provider_quota_pure::coerce_json_f64);
|
||||||
|
let limit = chatgpt_web_image_quota_limit(metadata, remaining);
|
||||||
|
let used = metadata
|
||||||
|
.get("image_quota_used")
|
||||||
|
.and_then(admin_provider_quota_pure::coerce_json_f64)
|
||||||
|
.or_else(|| {
|
||||||
|
limit
|
||||||
|
.zip(remaining)
|
||||||
|
.map(|(limit, remaining)| (limit - remaining).max(0.0))
|
||||||
|
});
|
||||||
|
let reset_at = provider_quota_timestamp_unix_secs(metadata.get("image_quota_reset_at"));
|
||||||
|
let reset_seconds = quota_window_reset_seconds(observed_at_unix_secs, reset_at);
|
||||||
|
let plan_type = metadata
|
||||||
|
.get("plan_type")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(|value| value.to_ascii_lowercase());
|
||||||
|
let image_blocked = metadata
|
||||||
|
.get("image_quota_blocked")
|
||||||
|
.and_then(admin_provider_quota_pure::coerce_json_bool)
|
||||||
|
== Some(true);
|
||||||
|
let usage_ratio = used
|
||||||
|
.zip(limit)
|
||||||
|
.and_then(|(used, limit)| (limit > 0.0).then_some((used / limit).clamp(0.0, 1.0)));
|
||||||
|
let remaining_ratio = remaining.zip(limit).and_then(|(remaining, limit)| {
|
||||||
|
(limit > 0.0).then_some((remaining / limit).clamp(0.0, 1.0))
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut windows = Vec::new();
|
||||||
|
if remaining.is_some()
|
||||||
|
|| limit.is_some()
|
||||||
|
|| used.is_some()
|
||||||
|
|| reset_at.is_some()
|
||||||
|
|| image_blocked
|
||||||
|
{
|
||||||
|
windows.push(json!({
|
||||||
|
"code": "image_gen",
|
||||||
|
"label": "生图",
|
||||||
|
"scope": "account",
|
||||||
|
"unit": "count",
|
||||||
|
"used_ratio": usage_ratio,
|
||||||
|
"remaining_ratio": remaining_ratio,
|
||||||
|
"used_value": used,
|
||||||
|
"remaining_value": remaining,
|
||||||
|
"limit_value": limit,
|
||||||
|
"reset_at": reset_at,
|
||||||
|
"reset_seconds": reset_seconds,
|
||||||
|
"is_exhausted": image_blocked || remaining.is_some_and(|value| value <= 0.0),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if windows.is_empty() && plan_type.is_none() && observed_at_unix_secs.is_none() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let exhausted = image_blocked
|
||||||
|
|| remaining.is_some_and(|value| value <= 0.0)
|
||||||
|
|| usage_ratio.is_some_and(|value| value >= 1.0 - 1e-6);
|
||||||
|
let reason = if exhausted {
|
||||||
|
Some("生图额度已耗尽")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(json!({
|
||||||
|
"version": 2,
|
||||||
|
"provider_type": "chatgpt_web",
|
||||||
|
"code": if exhausted { "exhausted" } else { "ok" },
|
||||||
|
"label": if exhausted { Some("额度耗尽") } else { None::<&str> },
|
||||||
|
"reason": reason,
|
||||||
|
"freshness": "fresh",
|
||||||
|
"source": source,
|
||||||
|
"observed_at": observed_at_unix_secs,
|
||||||
|
"exhausted": exhausted,
|
||||||
|
"usage_ratio": usage_ratio,
|
||||||
|
"updated_at": observed_at_unix_secs,
|
||||||
|
"reset_at": reset_at,
|
||||||
|
"reset_seconds": reset_seconds,
|
||||||
|
"plan_type": plan_type,
|
||||||
|
"windows": windows,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
fn build_antigravity_quota_status_snapshot(
|
fn build_antigravity_quota_status_snapshot(
|
||||||
upstream_metadata: Option<&Value>,
|
upstream_metadata: Option<&Value>,
|
||||||
source: &str,
|
source: &str,
|
||||||
@@ -993,6 +1110,7 @@ pub(crate) fn sync_provider_key_quota_status_snapshot(
|
|||||||
let quota = match normalized_provider_type.as_str() {
|
let quota = match normalized_provider_type.as_str() {
|
||||||
"codex" => build_codex_quota_status_snapshot(upstream_metadata, source),
|
"codex" => build_codex_quota_status_snapshot(upstream_metadata, source),
|
||||||
"kiro" => build_kiro_quota_status_snapshot(upstream_metadata, source),
|
"kiro" => build_kiro_quota_status_snapshot(upstream_metadata, source),
|
||||||
|
"chatgpt_web" => build_chatgpt_web_quota_status_snapshot(upstream_metadata, source),
|
||||||
"antigravity" => build_antigravity_quota_status_snapshot(upstream_metadata, source),
|
"antigravity" => build_antigravity_quota_status_snapshot(upstream_metadata, source),
|
||||||
"gemini_cli" => build_gemini_cli_quota_status_snapshot(upstream_metadata, source),
|
"gemini_cli" => build_gemini_cli_quota_status_snapshot(upstream_metadata, source),
|
||||||
_ => None,
|
_ => None,
|
||||||
@@ -1784,6 +1902,42 @@ mod tests {
|
|||||||
assert_eq!(window.get("reset_seconds"), Some(&json!(3_600u64)));
|
assert_eq!(window.get("reset_seconds"), Some(&json!(3_600u64)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn provider_key_status_snapshot_payload_backfills_chatgpt_web_image_quota() {
|
||||||
|
let mut key = sample_catalog_key();
|
||||||
|
key.upstream_metadata = Some(json!({
|
||||||
|
"chatgpt_web": {
|
||||||
|
"updated_at": 1_778_067_246u64,
|
||||||
|
"plan_type": "free",
|
||||||
|
"image_quota_remaining": 24.0,
|
||||||
|
"image_quota_reset_at": 1_778_157_172u64
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
let payload = provider_key_status_snapshot_payload(&key, "chatgpt_web");
|
||||||
|
let quota = payload
|
||||||
|
.get("quota")
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
.expect("quota snapshot should be object");
|
||||||
|
let window = quota
|
||||||
|
.get("windows")
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.and_then(|windows| windows.first())
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
.expect("image quota window should exist");
|
||||||
|
|
||||||
|
assert_eq!(quota.get("provider_type"), Some(&json!("chatgpt_web")));
|
||||||
|
assert_eq!(quota.get("code"), Some(&json!("ok")));
|
||||||
|
assert_eq!(quota.get("plan_type"), Some(&json!("free")));
|
||||||
|
assert_eq!(quota.get("reset_at"), Some(&json!(1_778_157_172u64)));
|
||||||
|
assert_eq!(quota.get("usage_ratio"), Some(&json!(0.04)));
|
||||||
|
assert_eq!(window.get("code"), Some(&json!("image_gen")));
|
||||||
|
assert_eq!(window.get("remaining_value"), Some(&json!(24.0)));
|
||||||
|
assert_eq!(window.get("limit_value"), Some(&json!(25.0)));
|
||||||
|
assert_eq!(window.get("used_value"), Some(&json!(1.0)));
|
||||||
|
assert_eq!(window.get("remaining_ratio"), Some(&json!(0.96)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn provider_key_status_snapshot_payload_preserves_existing_materialized_quota_snapshot() {
|
fn provider_key_status_snapshot_payload_preserves_existing_materialized_quota_snapshot() {
|
||||||
let mut key = sample_catalog_key();
|
let mut key = sample_catalog_key();
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ use tracing::{debug, info, warn};
|
|||||||
|
|
||||||
use crate::admin_api::{
|
use crate::admin_api::{
|
||||||
admin_provider_pool_config, provider_oauth_runtime_endpoint_for_provider,
|
admin_provider_pool_config, provider_oauth_runtime_endpoint_for_provider,
|
||||||
refresh_antigravity_provider_quota_locally, refresh_codex_provider_quota_locally,
|
refresh_antigravity_provider_quota_locally, refresh_chatgpt_web_provider_quota_locally,
|
||||||
refresh_kiro_provider_quota_locally, AdminAppState,
|
refresh_codex_provider_quota_locally, refresh_kiro_provider_quota_locally, AdminAppState,
|
||||||
};
|
};
|
||||||
use crate::{AppState, GatewayError};
|
use crate::{AppState, GatewayError};
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ fn now_unix_secs() -> u64 {
|
|||||||
fn provider_supports_quota_probe(provider_type: &str) -> bool {
|
fn provider_supports_quota_probe(provider_type: &str) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
provider_type.trim().to_ascii_lowercase().as_str(),
|
provider_type.trim().to_ascii_lowercase().as_str(),
|
||||||
"codex" | "kiro" | "antigravity"
|
"codex" | "kiro" | "antigravity" | "chatgpt_web"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,6 +116,7 @@ fn extract_quota_updated_at(provider_type: &str, upstream_metadata: Option<&Valu
|
|||||||
"codex" => "codex",
|
"codex" => "codex",
|
||||||
"kiro" => "kiro",
|
"kiro" => "kiro",
|
||||||
"antigravity" => "antigravity",
|
"antigravity" => "antigravity",
|
||||||
|
"chatgpt_web" => "chatgpt_web",
|
||||||
_ => return None,
|
_ => return None,
|
||||||
};
|
};
|
||||||
let bucket = metadata.get(bucket_name)?.as_object()?;
|
let bucket = metadata.get(bucket_name)?.as_object()?;
|
||||||
@@ -382,6 +383,10 @@ async fn refresh_provider_probe_keys(
|
|||||||
refresh_antigravity_provider_quota_locally(admin_state, provider, endpoint, keys, None)
|
refresh_antigravity_provider_quota_locally(admin_state, provider, endpoint, keys, None)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
"chatgpt_web" => {
|
||||||
|
refresh_chatgpt_web_provider_quota_locally(admin_state, provider, endpoint, keys, None)
|
||||||
|
.await
|
||||||
|
}
|
||||||
_ => Ok(None),
|
_ => Ok(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -345,6 +345,16 @@ impl AppState {
|
|||||||
.map_err(|err| GatewayError::Internal(err.to_string()))
|
.map_err(|err| GatewayError::Internal(err.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[usage::ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<Vec<usage::StoredProviderApiKeyWindowUsageSummary>, GatewayError> {
|
||||||
|
self.data
|
||||||
|
.summarize_usage_by_provider_api_key_windows(requests)
|
||||||
|
.await
|
||||||
|
.map_err(|err| GatewayError::Internal(err.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn list_users_by_ids(
|
pub(crate) async fn list_users_by_ids(
|
||||||
&self,
|
&self,
|
||||||
user_ids: &[String],
|
user_ids: &[String],
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ use std::sync::{Arc, Mutex};
|
|||||||
|
|
||||||
use aether_crypto::{encrypt_python_fernet_plaintext, DEVELOPMENT_ENCRYPTION_KEY};
|
use aether_crypto::{encrypt_python_fernet_plaintext, DEVELOPMENT_ENCRYPTION_KEY};
|
||||||
use aether_data::repository::provider_catalog::InMemoryProviderCatalogReadRepository;
|
use aether_data::repository::provider_catalog::InMemoryProviderCatalogReadRepository;
|
||||||
|
use aether_data::repository::usage::InMemoryUsageReadRepository;
|
||||||
use aether_data_contracts::repository::provider_catalog::ProviderCatalogReadRepository;
|
use aether_data_contracts::repository::provider_catalog::ProviderCatalogReadRepository;
|
||||||
|
use aether_data_contracts::repository::usage::StoredRequestUsageAudit;
|
||||||
use axum::body::{to_bytes, Body, Bytes};
|
use axum::body::{to_bytes, Body, Bytes};
|
||||||
use axum::routing::{any, get, post};
|
use axum::routing::{any, get, post};
|
||||||
use axum::{extract::Request, Router};
|
use axum::{extract::Request, Router};
|
||||||
@@ -21,6 +23,54 @@ use crate::constants::{
|
|||||||
use crate::control::resolve_public_request_context;
|
use crate::control::resolve_public_request_context;
|
||||||
use crate::data::GatewayDataState;
|
use crate::data::GatewayDataState;
|
||||||
|
|
||||||
|
fn sample_pool_usage_row(
|
||||||
|
request_id: &str,
|
||||||
|
provider_api_key_id: &str,
|
||||||
|
created_at_unix_secs: i64,
|
||||||
|
total_tokens: i32,
|
||||||
|
total_cost_usd: f64,
|
||||||
|
) -> StoredRequestUsageAudit {
|
||||||
|
StoredRequestUsageAudit::new(
|
||||||
|
format!("usage-{request_id}"),
|
||||||
|
request_id.to_string(),
|
||||||
|
Some("user-codex".to_string()),
|
||||||
|
Some("api-key-codex".to_string()),
|
||||||
|
Some("codex-user".to_string()),
|
||||||
|
Some("codex-api-key".to_string()),
|
||||||
|
"codex".to_string(),
|
||||||
|
"gpt-5-codex".to_string(),
|
||||||
|
None,
|
||||||
|
Some("provider-codex".to_string()),
|
||||||
|
Some("endpoint-codex".to_string()),
|
||||||
|
Some(provider_api_key_id.to_string()),
|
||||||
|
Some("responses".to_string()),
|
||||||
|
Some("openai:responses".to_string()),
|
||||||
|
Some("openai".to_string()),
|
||||||
|
Some("responses".to_string()),
|
||||||
|
Some("openai:responses".to_string()),
|
||||||
|
Some("openai".to_string()),
|
||||||
|
Some("responses".to_string()),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
total_tokens,
|
||||||
|
0,
|
||||||
|
total_tokens,
|
||||||
|
total_cost_usd,
|
||||||
|
total_cost_usd,
|
||||||
|
Some(200),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
Some(240),
|
||||||
|
Some(80),
|
||||||
|
"completed".to_string(),
|
||||||
|
"settled".to_string(),
|
||||||
|
created_at_unix_secs,
|
||||||
|
created_at_unix_secs + 1,
|
||||||
|
Some(created_at_unix_secs + 2),
|
||||||
|
)
|
||||||
|
.expect("usage row should build")
|
||||||
|
}
|
||||||
|
|
||||||
fn trusted_admin_headers() -> HeaderMap {
|
fn trusted_admin_headers() -> HeaderMap {
|
||||||
let mut headers = HeaderMap::new();
|
let mut headers = HeaderMap::new();
|
||||||
headers.insert(GATEWAY_HEADER, HeaderValue::from_static("rust-phase3b"));
|
headers.insert(GATEWAY_HEADER, HeaderValue::from_static("rust-phase3b"));
|
||||||
@@ -793,6 +843,233 @@ async fn gateway_sorts_admin_pool_keys_by_imported_and_last_used_time() {
|
|||||||
assert_eq!(last_used_names, vec!["active", "old", "fresh"]);
|
assert_eq!(last_used_names, vec!["active", "old", "fresh"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn gateway_pool_list_adds_codex_cycle_usage_to_quota_windows() {
|
||||||
|
const RESET_AT: u64 = 1_711_000_000;
|
||||||
|
|
||||||
|
let mut provider = sample_provider("provider-codex", "codex", 10).with_transport_fields(
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
Some(json!({
|
||||||
|
"pool_advanced": {
|
||||||
|
"enabled": true
|
||||||
|
}
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
provider.provider_type = "codex".to_string();
|
||||||
|
|
||||||
|
let mut usage_key = sample_key(
|
||||||
|
"key-codex-cycle",
|
||||||
|
"provider-codex",
|
||||||
|
"openai:responses",
|
||||||
|
"oauth-placeholder",
|
||||||
|
);
|
||||||
|
usage_key.name = "codex cycle usage".to_string();
|
||||||
|
usage_key.auth_type = "oauth".to_string();
|
||||||
|
usage_key.request_count = Some(4);
|
||||||
|
usage_key.total_tokens = 999;
|
||||||
|
usage_key.total_cost_usd = 9.99;
|
||||||
|
usage_key.status_snapshot = Some(json!({
|
||||||
|
"quota": {
|
||||||
|
"version": 2,
|
||||||
|
"provider_type": "codex",
|
||||||
|
"code": "ok",
|
||||||
|
"label": serde_json::Value::Null,
|
||||||
|
"reason": serde_json::Value::Null,
|
||||||
|
"freshness": "fresh",
|
||||||
|
"source": "response_headers",
|
||||||
|
"observed_at": RESET_AT,
|
||||||
|
"exhausted": false,
|
||||||
|
"usage_ratio": 0.0,
|
||||||
|
"updated_at": RESET_AT,
|
||||||
|
"reset_seconds": serde_json::Value::Null,
|
||||||
|
"plan_type": "plus",
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"code": "weekly",
|
||||||
|
"label": "周",
|
||||||
|
"scope": "account",
|
||||||
|
"unit": "percent",
|
||||||
|
"used_ratio": 0.0,
|
||||||
|
"remaining_ratio": 1.0,
|
||||||
|
"reset_at": RESET_AT,
|
||||||
|
"reset_seconds": 604_800,
|
||||||
|
"window_minutes": 10_080
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "5h",
|
||||||
|
"label": "5H",
|
||||||
|
"scope": "account",
|
||||||
|
"unit": "percent",
|
||||||
|
"used_ratio": 0.0,
|
||||||
|
"remaining_ratio": 1.0,
|
||||||
|
"reset_at": RESET_AT,
|
||||||
|
"reset_seconds": 18_000,
|
||||||
|
"window_minutes": 300
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
let mut zero_key = sample_key(
|
||||||
|
"key-codex-zero",
|
||||||
|
"provider-codex",
|
||||||
|
"openai:responses",
|
||||||
|
"oauth-placeholder",
|
||||||
|
);
|
||||||
|
zero_key.name = "codex zero usage".to_string();
|
||||||
|
zero_key.auth_type = "oauth".to_string();
|
||||||
|
zero_key.status_snapshot = usage_key.status_snapshot.clone();
|
||||||
|
|
||||||
|
let mut invalid_key = sample_key(
|
||||||
|
"key-codex-invalid",
|
||||||
|
"provider-codex",
|
||||||
|
"openai:responses",
|
||||||
|
"oauth-placeholder",
|
||||||
|
);
|
||||||
|
invalid_key.name = "codex invalid window".to_string();
|
||||||
|
invalid_key.auth_type = "oauth".to_string();
|
||||||
|
invalid_key.status_snapshot = Some(json!({
|
||||||
|
"quota": {
|
||||||
|
"version": 2,
|
||||||
|
"provider_type": "codex",
|
||||||
|
"code": "ok",
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"code": "weekly",
|
||||||
|
"label": "周",
|
||||||
|
"reset_at": serde_json::Value::Null,
|
||||||
|
"window_minutes": 10_080
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "5h",
|
||||||
|
"label": "5H",
|
||||||
|
"reset_at": RESET_AT,
|
||||||
|
"window_minutes": serde_json::Value::Null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
let provider_catalog_repository = Arc::new(InMemoryProviderCatalogReadRepository::seed(
|
||||||
|
vec![provider],
|
||||||
|
Vec::new(),
|
||||||
|
vec![usage_key, zero_key, invalid_key],
|
||||||
|
));
|
||||||
|
let usage_repository = Arc::new(InMemoryUsageReadRepository::seed(vec![
|
||||||
|
sample_pool_usage_row(
|
||||||
|
"req-5h-a",
|
||||||
|
"key-codex-cycle",
|
||||||
|
RESET_AT as i64 - 60,
|
||||||
|
100,
|
||||||
|
0.10,
|
||||||
|
),
|
||||||
|
sample_pool_usage_row(
|
||||||
|
"req-5h-b",
|
||||||
|
"key-codex-cycle",
|
||||||
|
RESET_AT as i64 - 17_999,
|
||||||
|
125,
|
||||||
|
0.20,
|
||||||
|
),
|
||||||
|
sample_pool_usage_row(
|
||||||
|
"req-weekly-only",
|
||||||
|
"key-codex-cycle",
|
||||||
|
RESET_AT as i64 - 18_001,
|
||||||
|
150,
|
||||||
|
0.30,
|
||||||
|
),
|
||||||
|
sample_pool_usage_row(
|
||||||
|
"req-before-weekly",
|
||||||
|
"key-codex-cycle",
|
||||||
|
RESET_AT as i64 - 604_801,
|
||||||
|
200,
|
||||||
|
0.40,
|
||||||
|
),
|
||||||
|
]));
|
||||||
|
let state = AppState::new()
|
||||||
|
.expect("gateway should build")
|
||||||
|
.with_data_state_for_tests(
|
||||||
|
GatewayDataState::with_provider_catalog_and_usage_reader_for_tests(
|
||||||
|
provider_catalog_repository,
|
||||||
|
usage_repository,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = local_admin_pool_response(
|
||||||
|
&state,
|
||||||
|
http::Method::GET,
|
||||||
|
"/api/admin/pool/provider-codex/keys?page=1&page_size=50&status=all",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let payload: serde_json::Value = serde_json::from_slice(
|
||||||
|
&to_bytes(response.into_body(), usize::MAX)
|
||||||
|
.await
|
||||||
|
.expect("body should read"),
|
||||||
|
)
|
||||||
|
.expect("json body should parse");
|
||||||
|
let keys = payload["keys"].as_array().expect("keys should be array");
|
||||||
|
fn key_by_id<'a>(keys: &'a [serde_json::Value], key_id: &str) -> &'a serde_json::Value {
|
||||||
|
keys.iter()
|
||||||
|
.find(|key| key["key_id"] == json!(key_id))
|
||||||
|
.expect("key payload should exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_by_code<'a>(key_payload: &'a serde_json::Value, code: &str) -> &'a serde_json::Value {
|
||||||
|
key_payload["status_snapshot"]["quota"]["windows"]
|
||||||
|
.as_array()
|
||||||
|
.expect("quota windows should be array")
|
||||||
|
.iter()
|
||||||
|
.find(|window| window["code"] == json!(code))
|
||||||
|
.expect("quota window should exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
let usage_key_payload = key_by_id(keys, "key-codex-cycle");
|
||||||
|
let five_hour_window = window_by_code(usage_key_payload, "5h");
|
||||||
|
let weekly_window = window_by_code(usage_key_payload, "weekly");
|
||||||
|
assert_eq!(five_hour_window["usage"]["request_count"], json!(2));
|
||||||
|
assert_eq!(five_hour_window["usage"]["total_tokens"], json!(225));
|
||||||
|
assert_eq!(
|
||||||
|
five_hour_window["usage"]["total_cost_usd"],
|
||||||
|
json!("0.30000000")
|
||||||
|
);
|
||||||
|
assert_eq!(weekly_window["usage"]["request_count"], json!(3));
|
||||||
|
assert_eq!(weekly_window["usage"]["total_tokens"], json!(375));
|
||||||
|
assert_eq!(
|
||||||
|
weekly_window["usage"]["total_cost_usd"],
|
||||||
|
json!("0.60000000")
|
||||||
|
);
|
||||||
|
assert_eq!(usage_key_payload["request_count"], json!(4));
|
||||||
|
assert_eq!(usage_key_payload["total_tokens"], json!(999));
|
||||||
|
assert_eq!(usage_key_payload["total_cost_usd"], json!("9.99000000"));
|
||||||
|
|
||||||
|
let zero_key_payload = key_by_id(keys, "key-codex-zero");
|
||||||
|
assert_eq!(
|
||||||
|
window_by_code(zero_key_payload, "5h")["usage"]["request_count"],
|
||||||
|
json!(0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
window_by_code(zero_key_payload, "weekly")["usage"]["total_tokens"],
|
||||||
|
json!(0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let invalid_key_payload = key_by_id(keys, "key-codex-invalid");
|
||||||
|
assert!(window_by_code(invalid_key_payload, "5h")
|
||||||
|
.get("usage")
|
||||||
|
.is_none());
|
||||||
|
assert!(window_by_code(invalid_key_payload, "weekly")
|
||||||
|
.get("usage")
|
||||||
|
.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn gateway_marks_account_blocked_pool_key_in_list_keys_response() {
|
async fn gateway_marks_account_blocked_pool_key_in_list_keys_response() {
|
||||||
let mut provider = sample_provider("provider-codex", "codex", 10).with_transport_fields(
|
let mut provider = sample_provider("provider-codex", "codex", 10).with_transport_fields(
|
||||||
|
|||||||
@@ -247,6 +247,23 @@ pub fn admin_pool_key_account_quota_exhausted(
|
|||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"chatgpt_web" => {
|
||||||
|
if admin_pool_json_bool(bucket.get("image_quota_blocked")) == Some(true) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if admin_pool_json_f64(bucket.get("image_quota_remaining"))
|
||||||
|
.is_some_and(|value| value <= 0.0)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match (
|
||||||
|
admin_pool_json_f64(bucket.get("image_quota_total")),
|
||||||
|
admin_pool_json_f64(bucket.get("image_quota_used")),
|
||||||
|
) {
|
||||||
|
(Some(limit), Some(used)) if limit > 0.0 => used >= limit,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -655,9 +655,227 @@ pub fn parse_kiro_usage_response(
|
|||||||
Some(serde_json::Value::Object(result))
|
Some(serde_json::Value::Object(result))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_quota_feature_name(value: &serde_json::Value) -> Option<String> {
|
||||||
|
coerce_json_string(
|
||||||
|
value
|
||||||
|
.get("feature_name")
|
||||||
|
.or_else(|| value.get("featureName"))
|
||||||
|
.or_else(|| value.get("feature"))
|
||||||
|
.or_else(|| value.get("name")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_is_image_quota_feature(value: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
value.trim().to_ascii_lowercase().as_str(),
|
||||||
|
"image_gen" | "image_generation" | "image_edit" | "img_gen"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_feature_number(feature: &serde_json::Value, fields: &[&str]) -> Option<f64> {
|
||||||
|
fields
|
||||||
|
.iter()
|
||||||
|
.find_map(|field| feature.get(*field).and_then(coerce_json_f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_chatgpt_web_reset_timestamp(
|
||||||
|
value: Option<&serde_json::Value>,
|
||||||
|
observed_at: u64,
|
||||||
|
) -> Option<u64> {
|
||||||
|
let value = value?;
|
||||||
|
if let Some(text) = value
|
||||||
|
.as_str()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
{
|
||||||
|
if let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(text) {
|
||||||
|
return u64::try_from(parsed.timestamp()).ok();
|
||||||
|
}
|
||||||
|
if let Ok(parsed) = text.parse::<f64>() {
|
||||||
|
return normalize_chatgpt_web_numeric_reset(parsed, observed_at);
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
value
|
||||||
|
.as_f64()
|
||||||
|
.and_then(|parsed| normalize_chatgpt_web_numeric_reset(parsed, observed_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_chatgpt_web_numeric_reset(value: f64, observed_at: u64) -> Option<u64> {
|
||||||
|
if !value.is_finite() || value <= 0.0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if value > 1_000_000_000_000.0 {
|
||||||
|
return Some((value / 1000.0).floor() as u64);
|
||||||
|
}
|
||||||
|
if value > 1_000_000_000.0 {
|
||||||
|
return Some(value.floor() as u64);
|
||||||
|
}
|
||||||
|
Some(observed_at.saturating_add(value.floor() as u64))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chatgpt_web_blocked_features(value: &serde_json::Value) -> Vec<String> {
|
||||||
|
value
|
||||||
|
.get("blocked_features")
|
||||||
|
.or_else(|| value.get("blockedFeatures"))
|
||||||
|
.and_then(serde_json::Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(serde_json::Value::as_str)
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_chatgpt_web_conversation_init_response(
|
||||||
|
value: &serde_json::Value,
|
||||||
|
updated_at_unix_secs: u64,
|
||||||
|
) -> Option<serde_json::Value> {
|
||||||
|
let root = value.as_object()?;
|
||||||
|
let limits_progress = root
|
||||||
|
.get("limits_progress")
|
||||||
|
.or_else(|| root.get("limitsProgress"))
|
||||||
|
.and_then(serde_json::Value::as_array)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default();
|
||||||
|
let image_limit = limits_progress
|
||||||
|
.iter()
|
||||||
|
.find(|item| {
|
||||||
|
chatgpt_web_quota_feature_name(item)
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(chatgpt_web_is_image_quota_feature)
|
||||||
|
})
|
||||||
|
.cloned();
|
||||||
|
let blocked_features = chatgpt_web_blocked_features(value);
|
||||||
|
let image_blocked = blocked_features
|
||||||
|
.iter()
|
||||||
|
.any(|feature| chatgpt_web_is_image_quota_feature(feature));
|
||||||
|
|
||||||
|
if image_limit.is_none() && !image_blocked {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut result = serde_json::Map::new();
|
||||||
|
result.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||||
|
|
||||||
|
if let Some(default_model_slug) = coerce_json_string(
|
||||||
|
root.get("default_model_slug")
|
||||||
|
.or_else(|| root.get("defaultModelSlug")),
|
||||||
|
) {
|
||||||
|
result.insert("default_model_slug".to_string(), json!(default_model_slug));
|
||||||
|
}
|
||||||
|
if let Some(plan_type) = coerce_json_string(
|
||||||
|
root.get("plan_type")
|
||||||
|
.or_else(|| root.get("planType"))
|
||||||
|
.or_else(|| root.get("subscription_plan")),
|
||||||
|
) {
|
||||||
|
result.insert(
|
||||||
|
"plan_type".to_string(),
|
||||||
|
json!(plan_type.to_ascii_lowercase()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
result.insert("blocked_features".to_string(), json!(blocked_features));
|
||||||
|
result.insert(
|
||||||
|
"limits_progress".to_string(),
|
||||||
|
serde_json::Value::Array(limits_progress),
|
||||||
|
);
|
||||||
|
|
||||||
|
if image_blocked {
|
||||||
|
result.insert("image_quota_blocked".to_string(), json!(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(image_limit) = image_limit.as_ref() {
|
||||||
|
if let Some(feature_name) = chatgpt_web_quota_feature_name(image_limit) {
|
||||||
|
result.insert("image_quota_feature_name".to_string(), json!(feature_name));
|
||||||
|
}
|
||||||
|
|
||||||
|
let remaining = chatgpt_web_feature_number(
|
||||||
|
image_limit,
|
||||||
|
&[
|
||||||
|
"remaining",
|
||||||
|
"remaining_value",
|
||||||
|
"remainingValue",
|
||||||
|
"remaining_count",
|
||||||
|
"remainingCount",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let total = chatgpt_web_feature_number(
|
||||||
|
image_limit,
|
||||||
|
&[
|
||||||
|
"max_value",
|
||||||
|
"maxValue",
|
||||||
|
"cap",
|
||||||
|
"total",
|
||||||
|
"limit",
|
||||||
|
"quota",
|
||||||
|
"usage_limit",
|
||||||
|
"usageLimit",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let used = chatgpt_web_feature_number(
|
||||||
|
image_limit,
|
||||||
|
&[
|
||||||
|
"used",
|
||||||
|
"used_value",
|
||||||
|
"usedValue",
|
||||||
|
"consumed",
|
||||||
|
"current_usage",
|
||||||
|
"currentUsage",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.or_else(|| {
|
||||||
|
total
|
||||||
|
.zip(remaining)
|
||||||
|
.map(|(total, remaining)| (total - remaining).max(0.0))
|
||||||
|
});
|
||||||
|
let reset_source = image_limit
|
||||||
|
.get("reset_at")
|
||||||
|
.or_else(|| image_limit.get("resetAt"))
|
||||||
|
.or_else(|| image_limit.get("next_reset_at"))
|
||||||
|
.or_else(|| image_limit.get("nextResetAt"))
|
||||||
|
.or_else(|| image_limit.get("reset_after"))
|
||||||
|
.or_else(|| image_limit.get("resetAfter"));
|
||||||
|
let reset_at = parse_chatgpt_web_reset_timestamp(reset_source, updated_at_unix_secs);
|
||||||
|
|
||||||
|
if let Some(remaining) = remaining {
|
||||||
|
result.insert("image_quota_remaining".to_string(), json!(remaining));
|
||||||
|
} else if image_blocked {
|
||||||
|
result.insert("image_quota_remaining".to_string(), json!(0.0));
|
||||||
|
}
|
||||||
|
if let Some(total) = total {
|
||||||
|
result.insert("image_quota_total".to_string(), json!(total));
|
||||||
|
}
|
||||||
|
if let Some(used) = used {
|
||||||
|
result.insert("image_quota_used".to_string(), json!(used));
|
||||||
|
}
|
||||||
|
if let Some(reset_at) = reset_at {
|
||||||
|
result.insert("image_quota_reset_at".to_string(), json!(reset_at));
|
||||||
|
}
|
||||||
|
if let Some(reset_after) = coerce_json_string(
|
||||||
|
image_limit
|
||||||
|
.get("reset_after")
|
||||||
|
.or_else(|| image_limit.get("resetAfter")),
|
||||||
|
) {
|
||||||
|
result.insert("image_quota_reset_after".to_string(), json!(reset_after));
|
||||||
|
}
|
||||||
|
} else if image_blocked {
|
||||||
|
result.insert("image_quota_remaining".to_string(), json!(0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(serde_json::Value::Object(result))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{codex_runtime_invalid_reason, OAUTH_ACCOUNT_BLOCK_PREFIX, OAUTH_EXPIRED_PREFIX};
|
use super::{
|
||||||
|
codex_runtime_invalid_reason, parse_chatgpt_web_conversation_init_response,
|
||||||
|
OAUTH_ACCOUNT_BLOCK_PREFIX, OAUTH_EXPIRED_PREFIX,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn codex_runtime_invalid_reason_marks_401_as_expired() {
|
fn codex_runtime_invalid_reason_marks_401_as_expired() {
|
||||||
@@ -681,4 +899,45 @@ mod tests {
|
|||||||
fn codex_runtime_invalid_reason_ignores_generic_403() {
|
fn codex_runtime_invalid_reason_ignores_generic_403() {
|
||||||
assert_eq!(codex_runtime_invalid_reason(403, Some("forbidden")), None);
|
assert_eq!(codex_runtime_invalid_reason(403, Some("forbidden")), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_chatgpt_web_image_quota_from_conversation_init() {
|
||||||
|
let parsed = parse_chatgpt_web_conversation_init_response(
|
||||||
|
&json!({
|
||||||
|
"default_model_slug": "auto",
|
||||||
|
"blocked_features": [],
|
||||||
|
"limits_progress": [
|
||||||
|
{
|
||||||
|
"feature_name": "image_gen",
|
||||||
|
"remaining": 24,
|
||||||
|
"reset_after": "2026-05-07T12:32:52.826482+00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
1_778_067_246,
|
||||||
|
)
|
||||||
|
.expect("chatgpt web quota should parse");
|
||||||
|
|
||||||
|
assert_eq!(parsed.get("default_model_slug"), Some(&json!("auto")));
|
||||||
|
assert_eq!(parsed.get("image_quota_remaining"), Some(&json!(24.0)));
|
||||||
|
assert_eq!(
|
||||||
|
parsed.get("image_quota_reset_at"),
|
||||||
|
Some(&json!(1_778_157_172u64))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_chatgpt_web_blocked_image_feature_as_zero_remaining() {
|
||||||
|
let parsed = parse_chatgpt_web_conversation_init_response(
|
||||||
|
&json!({
|
||||||
|
"blocked_features": ["image_generation"],
|
||||||
|
"limits_progress": []
|
||||||
|
}),
|
||||||
|
1_778_067_246,
|
||||||
|
)
|
||||||
|
.expect("blocked image feature should produce metadata");
|
||||||
|
|
||||||
|
assert_eq!(parsed.get("image_quota_blocked"), Some(&json!(true)));
|
||||||
|
assert_eq!(parsed.get("image_quota_remaining"), Some(&json!(0.0)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ mod types;
|
|||||||
|
|
||||||
pub use types::{
|
pub use types::{
|
||||||
parse_usage_body_ref, usage_body_ref, PendingUsageCleanupSummary,
|
parse_usage_body_ref, usage_body_ref, PendingUsageCleanupSummary,
|
||||||
StoredProviderApiKeyUsageSummary, StoredProviderUsageSummary, StoredProviderUsageWindow,
|
ProviderApiKeyWindowUsageRequest, StoredProviderApiKeyUsageSummary,
|
||||||
|
StoredProviderApiKeyWindowUsageSummary, StoredProviderUsageSummary, StoredProviderUsageWindow,
|
||||||
StoredRequestUsageAudit, StoredUsageAuditAggregation, StoredUsageAuditSummary,
|
StoredRequestUsageAudit, StoredUsageAuditAggregation, StoredUsageAuditSummary,
|
||||||
StoredUsageBreakdownSummaryRow, StoredUsageCacheAffinityHitSummary,
|
StoredUsageBreakdownSummaryRow, StoredUsageCacheAffinityHitSummary,
|
||||||
StoredUsageCacheAffinityIntervalRow, StoredUsageCacheHitSummary, StoredUsageCostSavingsSummary,
|
StoredUsageCacheAffinityIntervalRow, StoredUsageCacheHitSummary, StoredUsageCostSavingsSummary,
|
||||||
|
|||||||
@@ -619,6 +619,23 @@ pub struct StoredProviderApiKeyUsageSummary {
|
|||||||
pub last_used_at_unix_secs: Option<u64>,
|
pub last_used_at_unix_secs: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct ProviderApiKeyWindowUsageRequest {
|
||||||
|
pub provider_api_key_id: String,
|
||||||
|
pub window_code: String,
|
||||||
|
pub start_unix_secs: u64,
|
||||||
|
pub end_unix_secs: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct StoredProviderApiKeyWindowUsageSummary {
|
||||||
|
pub provider_api_key_id: String,
|
||||||
|
pub window_code: String,
|
||||||
|
pub request_count: u64,
|
||||||
|
pub total_tokens: u64,
|
||||||
|
pub total_cost_usd: f64,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct UsageAuditListQuery {
|
pub struct UsageAuditListQuery {
|
||||||
pub created_from_unix_secs: Option<u64>,
|
pub created_from_unix_secs: Option<u64>,
|
||||||
@@ -1479,6 +1496,11 @@ pub trait UsageReadRepository: Send + Sync {
|
|||||||
crate::DataLayerError,
|
crate::DataLayerError,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<Vec<StoredProviderApiKeyWindowUsageSummary>, crate::DataLayerError>;
|
||||||
|
|
||||||
async fn summarize_provider_usage_since(
|
async fn summarize_provider_usage_since(
|
||||||
&self,
|
&self,
|
||||||
provider_id: &str,
|
provider_id: &str,
|
||||||
|
|||||||
@@ -30,9 +30,10 @@ use super::{
|
|||||||
api_key_usage_contribution, provider_api_key_usage_contribution,
|
api_key_usage_contribution, provider_api_key_usage_contribution,
|
||||||
strip_deprecated_usage_display_fields, usage_can_recover_terminal_failure,
|
strip_deprecated_usage_display_fields, usage_can_recover_terminal_failure,
|
||||||
ApiKeyUsageContribution, ApiKeyUsageDelta, ProviderApiKeyUsageContribution,
|
ApiKeyUsageContribution, ApiKeyUsageDelta, ProviderApiKeyUsageContribution,
|
||||||
ProviderApiKeyUsageDelta, StoredProviderApiKeyUsageSummary, StoredProviderUsageSummary,
|
ProviderApiKeyUsageDelta, ProviderApiKeyWindowUsageRequest, StoredProviderApiKeyUsageSummary,
|
||||||
StoredProviderUsageWindow, StoredRequestUsageAudit, StoredUsageDailySummary, UpsertUsageRecord,
|
StoredProviderApiKeyWindowUsageSummary, StoredProviderUsageSummary, StoredProviderUsageWindow,
|
||||||
UsageAuditListQuery, UsageDailyHeatmapQuery, UsageReadRepository, UsageWriteRepository,
|
StoredRequestUsageAudit, StoredUsageDailySummary, UpsertUsageRecord, UsageAuditListQuery,
|
||||||
|
UsageDailyHeatmapQuery, UsageReadRepository, UsageWriteRepository,
|
||||||
};
|
};
|
||||||
use crate::repository::auth::InMemoryAuthApiKeySnapshotRepository;
|
use crate::repository::auth::InMemoryAuthApiKeySnapshotRepository;
|
||||||
use crate::repository::provider_catalog::InMemoryProviderCatalogReadRepository;
|
use crate::repository::provider_catalog::InMemoryProviderCatalogReadRepository;
|
||||||
@@ -2327,6 +2328,59 @@ impl UsageReadRepository for InMemoryUsageReadRepository {
|
|||||||
Ok(summaries)
|
Ok(summaries)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<Vec<StoredProviderApiKeyWindowUsageSummary>, DataLayerError> {
|
||||||
|
let usage = self.by_request_id.read().expect("usage repository lock");
|
||||||
|
let mut summaries = Vec::with_capacity(requests.len());
|
||||||
|
|
||||||
|
for request in requests {
|
||||||
|
let provider_api_key_id = request.provider_api_key_id.trim();
|
||||||
|
if provider_api_key_id.is_empty() {
|
||||||
|
return Err(DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage provider_api_key_id cannot be empty".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let window_code = request.window_code.trim();
|
||||||
|
if window_code.is_empty() {
|
||||||
|
return Err(DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage window_code cannot be empty".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if request.start_unix_secs >= request.end_unix_secs {
|
||||||
|
return Err(DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage range must be non-empty".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut summary = StoredProviderApiKeyWindowUsageSummary {
|
||||||
|
provider_api_key_id: provider_api_key_id.to_string(),
|
||||||
|
window_code: window_code.to_string(),
|
||||||
|
..StoredProviderApiKeyWindowUsageSummary::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
for item in usage.values() {
|
||||||
|
if item.provider_api_key_id.as_deref() != Some(provider_api_key_id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if item.created_at_unix_ms < request.start_unix_secs
|
||||||
|
|| item.created_at_unix_ms >= request.end_unix_secs
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
summary.request_count = summary.request_count.saturating_add(1);
|
||||||
|
summary.total_tokens = summary.total_tokens.saturating_add(item.total_tokens);
|
||||||
|
summary.total_cost_usd += item.total_cost_usd;
|
||||||
|
}
|
||||||
|
|
||||||
|
summaries.push(summary);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(summaries)
|
||||||
|
}
|
||||||
|
|
||||||
async fn summarize_provider_usage_since(
|
async fn summarize_provider_usage_since(
|
||||||
&self,
|
&self,
|
||||||
provider_id: &str,
|
provider_id: &str,
|
||||||
@@ -2934,8 +2988,9 @@ mod tests {
|
|||||||
UsageWriteRepository,
|
UsageWriteRepository,
|
||||||
};
|
};
|
||||||
use aether_data_contracts::repository::usage::{
|
use aether_data_contracts::repository::usage::{
|
||||||
usage_body_ref, UsageAuditAggregationGroupBy, UsageAuditAggregationQuery, UsageBodyField,
|
usage_body_ref, ProviderApiKeyWindowUsageRequest, UsageAuditAggregationGroupBy,
|
||||||
UsageProviderPerformanceQuery, UsageTimeSeriesGranularity,
|
UsageAuditAggregationQuery, UsageBodyField, UsageProviderPerformanceQuery,
|
||||||
|
UsageTimeSeriesGranularity,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
@@ -4533,6 +4588,44 @@ mod tests {
|
|||||||
assert_eq!(item.last_used_at_unix_secs, Some(1_711_000_250));
|
assert_eq!(item.last_used_at_unix_secs, Some(1_711_000_250));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn summarizes_provider_api_key_window_usage_with_zero_rows() {
|
||||||
|
let repository = InMemoryUsageReadRepository::seed(vec![
|
||||||
|
sample_usage("req-1", 1_711_000_000),
|
||||||
|
sample_usage("req-2", 1_711_000_250),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let usage = repository
|
||||||
|
.summarize_usage_by_provider_api_key_windows(&[
|
||||||
|
ProviderApiKeyWindowUsageRequest {
|
||||||
|
provider_api_key_id: "provider-key-1".to_string(),
|
||||||
|
window_code: "5h".to_string(),
|
||||||
|
start_unix_secs: 1_711_000_000,
|
||||||
|
end_unix_secs: 1_711_000_300,
|
||||||
|
},
|
||||||
|
ProviderApiKeyWindowUsageRequest {
|
||||||
|
provider_api_key_id: "provider-key-empty".to_string(),
|
||||||
|
window_code: "weekly".to_string(),
|
||||||
|
start_unix_secs: 1_711_000_000,
|
||||||
|
end_unix_secs: 1_711_000_300,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.await
|
||||||
|
.expect("window summary should succeed");
|
||||||
|
|
||||||
|
assert_eq!(usage.len(), 2);
|
||||||
|
assert_eq!(usage[0].provider_api_key_id, "provider-key-1");
|
||||||
|
assert_eq!(usage[0].window_code, "5h");
|
||||||
|
assert_eq!(usage[0].request_count, 2);
|
||||||
|
assert_eq!(usage[0].total_tokens, 300);
|
||||||
|
assert_eq!(usage[0].total_cost_usd, 0.24);
|
||||||
|
assert_eq!(usage[1].provider_api_key_id, "provider-key-empty");
|
||||||
|
assert_eq!(usage[1].window_code, "weekly");
|
||||||
|
assert_eq!(usage[1].request_count, 0);
|
||||||
|
assert_eq!(usage[1].total_tokens, 0);
|
||||||
|
assert_eq!(usage[1].total_cost_usd, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn list_usage_audits_applies_second_based_time_filters() {
|
async fn list_usage_audits_applies_second_based_time_filters() {
|
||||||
let repository = InMemoryUsageReadRepository::seed(vec![
|
let repository = InMemoryUsageReadRepository::seed(vec![
|
||||||
|
|||||||
@@ -319,6 +319,17 @@ macro_rules! impl_materialized_usage_read_repository {
|
|||||||
<$crate::repository::usage::InMemoryUsageReadRepository as $crate::repository::usage::UsageReadRepository>::summarize_usage_by_provider_api_key_ids(&repository, provider_api_key_ids).await
|
<$crate::repository::usage::InMemoryUsageReadRepository as $crate::repository::usage::UsageReadRepository>::summarize_usage_by_provider_api_key_ids(&repository, provider_api_key_ids).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[$crate::repository::usage::ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<
|
||||||
|
Vec<$crate::repository::usage::StoredProviderApiKeyWindowUsageSummary>,
|
||||||
|
$crate::DataLayerError,
|
||||||
|
> {
|
||||||
|
let repository = self.materialize_read_model().await?;
|
||||||
|
<$crate::repository::usage::InMemoryUsageReadRepository as $crate::repository::usage::UsageReadRepository>::summarize_usage_by_provider_api_key_windows(&repository, requests).await
|
||||||
|
}
|
||||||
|
|
||||||
async fn summarize_provider_usage_since(
|
async fn summarize_provider_usage_since(
|
||||||
&self,
|
&self,
|
||||||
provider_id: &str,
|
provider_id: &str,
|
||||||
@@ -352,9 +363,10 @@ mod sqlite;
|
|||||||
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
pub(crate) use aether_data_contracts::repository::usage::{
|
pub(crate) use aether_data_contracts::repository::usage::{
|
||||||
PendingUsageCleanupSummary, StoredProviderApiKeyUsageSummary, StoredProviderUsageSummary,
|
PendingUsageCleanupSummary, ProviderApiKeyWindowUsageRequest, StoredProviderApiKeyUsageSummary,
|
||||||
StoredProviderUsageWindow, StoredRequestUsageAudit, StoredUsageAuditAggregation,
|
StoredProviderApiKeyWindowUsageSummary, StoredProviderUsageSummary, StoredProviderUsageWindow,
|
||||||
StoredUsageAuditSummary, StoredUsageBreakdownSummaryRow, StoredUsageCacheAffinityHitSummary,
|
StoredRequestUsageAudit, StoredUsageAuditAggregation, StoredUsageAuditSummary,
|
||||||
|
StoredUsageBreakdownSummaryRow, StoredUsageCacheAffinityHitSummary,
|
||||||
StoredUsageCacheAffinityIntervalRow, StoredUsageCacheHitSummary, StoredUsageCostSavingsSummary,
|
StoredUsageCacheAffinityIntervalRow, StoredUsageCacheHitSummary, StoredUsageCostSavingsSummary,
|
||||||
StoredUsageDailySummary, StoredUsageDashboardDailyBreakdownRow,
|
StoredUsageDailySummary, StoredUsageDashboardDailyBreakdownRow,
|
||||||
StoredUsageDashboardProviderCount, StoredUsageDashboardSummary,
|
StoredUsageDashboardProviderCount, StoredUsageDashboardSummary,
|
||||||
|
|||||||
@@ -38,7 +38,8 @@ use super::{
|
|||||||
api_key_usage_contribution, incoming_usage_can_recover_terminal_failure,
|
api_key_usage_contribution, incoming_usage_can_recover_terminal_failure,
|
||||||
model_usage_contribution, provider_api_key_usage_contribution,
|
model_usage_contribution, provider_api_key_usage_contribution,
|
||||||
strip_deprecated_usage_display_fields, ApiKeyUsageDelta, ModelUsageDelta,
|
strip_deprecated_usage_display_fields, ApiKeyUsageDelta, ModelUsageDelta,
|
||||||
PendingUsageCleanupSummary, ProviderApiKeyUsageDelta, StoredProviderApiKeyUsageSummary,
|
PendingUsageCleanupSummary, ProviderApiKeyUsageDelta, ProviderApiKeyWindowUsageRequest,
|
||||||
|
StoredProviderApiKeyUsageSummary, StoredProviderApiKeyWindowUsageSummary,
|
||||||
StoredProviderUsageSummary, StoredRequestUsageAudit, StoredUsageDailySummary,
|
StoredProviderUsageSummary, StoredRequestUsageAudit, StoredUsageDailySummary,
|
||||||
UpsertUsageRecord, UsageAuditListQuery, UsageDailyHeatmapQuery, UsageReadRepository,
|
UpsertUsageRecord, UsageAuditListQuery, UsageDailyHeatmapQuery, UsageReadRepository,
|
||||||
UsageWriteRepository,
|
UsageWriteRepository,
|
||||||
@@ -1314,6 +1315,9 @@ const SUMMARIZE_USAGE_TOTALS_BY_USER_IDS_SQL: &str =
|
|||||||
const SUMMARIZE_USAGE_BY_PROVIDER_API_KEY_IDS_SQL: &str =
|
const SUMMARIZE_USAGE_BY_PROVIDER_API_KEY_IDS_SQL: &str =
|
||||||
include_str!("queries/summarize_usage_by_provider_api_key_ids_sql.sql");
|
include_str!("queries/summarize_usage_by_provider_api_key_ids_sql.sql");
|
||||||
|
|
||||||
|
const SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL: &str =
|
||||||
|
include_str!("queries/summarize_provider_api_key_window_usage_sql.sql");
|
||||||
|
|
||||||
const APPLY_API_KEY_USAGE_DELTA_SQL: &str =
|
const APPLY_API_KEY_USAGE_DELTA_SQL: &str =
|
||||||
include_str!("queries/apply_api_key_usage_delta_sql.sql");
|
include_str!("queries/apply_api_key_usage_delta_sql.sql");
|
||||||
|
|
||||||
@@ -7225,6 +7229,98 @@ ORDER BY "usage".user_id ASC
|
|||||||
Ok(summaries)
|
Ok(summaries)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<Vec<StoredProviderApiKeyWindowUsageSummary>, DataLayerError> {
|
||||||
|
if requests.is_empty() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut provider_api_key_ids = Vec::with_capacity(requests.len());
|
||||||
|
let mut window_codes = Vec::with_capacity(requests.len());
|
||||||
|
let mut start_unix_secs = Vec::with_capacity(requests.len());
|
||||||
|
let mut end_unix_secs = Vec::with_capacity(requests.len());
|
||||||
|
|
||||||
|
for request in requests {
|
||||||
|
let provider_api_key_id = request.provider_api_key_id.trim();
|
||||||
|
if provider_api_key_id.is_empty() {
|
||||||
|
return Err(DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage provider_api_key_id cannot be empty".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let window_code = request.window_code.trim();
|
||||||
|
if window_code.is_empty() {
|
||||||
|
return Err(DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage window_code cannot be empty".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if request.start_unix_secs >= request.end_unix_secs {
|
||||||
|
return Err(DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage range must be non-empty".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
provider_api_key_ids.push(provider_api_key_id.to_string());
|
||||||
|
window_codes.push(window_code.to_string());
|
||||||
|
start_unix_secs.push(i64::try_from(request.start_unix_secs).map_err(|_| {
|
||||||
|
DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage start_unix_secs is out of range".to_string(),
|
||||||
|
)
|
||||||
|
})?);
|
||||||
|
end_unix_secs.push(i64::try_from(request.end_unix_secs).map_err(|_| {
|
||||||
|
DataLayerError::InvalidInput(
|
||||||
|
"provider api key window usage end_unix_secs is out of range".to_string(),
|
||||||
|
)
|
||||||
|
})?);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rows = sqlx::query(SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL)
|
||||||
|
.bind(&provider_api_key_ids)
|
||||||
|
.bind(&window_codes)
|
||||||
|
.bind(&start_unix_secs)
|
||||||
|
.bind(&end_unix_secs)
|
||||||
|
.fetch(&self.pool);
|
||||||
|
|
||||||
|
let mut summaries = Vec::new();
|
||||||
|
while let Some(row) = rows.try_next().await.map_postgres_err()? {
|
||||||
|
let total_cost_usd = row.try_get::<f64, _>("total_cost_usd").map_postgres_err()?;
|
||||||
|
if !total_cost_usd.is_finite() {
|
||||||
|
return Err(DataLayerError::UnexpectedValue(
|
||||||
|
"usage.total_cost_usd window aggregate is not finite".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
summaries.push(StoredProviderApiKeyWindowUsageSummary {
|
||||||
|
provider_api_key_id: row
|
||||||
|
.try_get::<String, _>("provider_api_key_id")
|
||||||
|
.map_postgres_err()?,
|
||||||
|
window_code: row.try_get::<String, _>("window_code").map_postgres_err()?,
|
||||||
|
request_count: row
|
||||||
|
.try_get::<i64, _>("request_count")
|
||||||
|
.map_postgres_err()?
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| {
|
||||||
|
DataLayerError::UnexpectedValue(
|
||||||
|
"usage.request_count window aggregate is negative".to_string(),
|
||||||
|
)
|
||||||
|
})?,
|
||||||
|
total_tokens: row
|
||||||
|
.try_get::<i64, _>("total_tokens")
|
||||||
|
.map_postgres_err()?
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| {
|
||||||
|
DataLayerError::UnexpectedValue(
|
||||||
|
"usage.total_tokens window aggregate is negative".to_string(),
|
||||||
|
)
|
||||||
|
})?,
|
||||||
|
total_cost_usd,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(summaries)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn upsert(
|
pub async fn upsert(
|
||||||
&self,
|
&self,
|
||||||
usage: UpsertUsageRecord,
|
usage: UpsertUsageRecord,
|
||||||
@@ -8044,6 +8140,13 @@ impl UsageReadRepository for SqlxUsageReadRepository {
|
|||||||
Self::summarize_usage_by_provider_api_key_ids(self, provider_api_key_ids).await
|
Self::summarize_usage_by_provider_api_key_ids(self, provider_api_key_ids).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn summarize_usage_by_provider_api_key_windows(
|
||||||
|
&self,
|
||||||
|
requests: &[ProviderApiKeyWindowUsageRequest],
|
||||||
|
) -> Result<Vec<StoredProviderApiKeyWindowUsageSummary>, DataLayerError> {
|
||||||
|
Self::summarize_usage_by_provider_api_key_windows(self, requests).await
|
||||||
|
}
|
||||||
|
|
||||||
async fn summarize_provider_usage_since(
|
async fn summarize_provider_usage_since(
|
||||||
&self,
|
&self,
|
||||||
provider_id: &str,
|
provider_id: &str,
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
WITH requested AS (
|
||||||
|
SELECT
|
||||||
|
request_row.provider_api_key_id,
|
||||||
|
request_row.window_code,
|
||||||
|
request_row.start_unix_secs,
|
||||||
|
request_row.end_unix_secs,
|
||||||
|
request_row.ordinality
|
||||||
|
FROM UNNEST(
|
||||||
|
$1::TEXT[],
|
||||||
|
$2::TEXT[],
|
||||||
|
$3::BIGINT[],
|
||||||
|
$4::BIGINT[]
|
||||||
|
) WITH ORDINALITY AS request_row(
|
||||||
|
provider_api_key_id,
|
||||||
|
window_code,
|
||||||
|
start_unix_secs,
|
||||||
|
end_unix_secs,
|
||||||
|
ordinality
|
||||||
|
)
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
requested.provider_api_key_id,
|
||||||
|
requested.window_code,
|
||||||
|
COUNT("usage".id)::BIGINT AS request_count,
|
||||||
|
COALESCE(SUM("usage".total_tokens), 0)::BIGINT AS total_tokens,
|
||||||
|
CAST(COALESCE(SUM("usage".total_cost_usd), 0) AS DOUBLE PRECISION) AS total_cost_usd
|
||||||
|
FROM requested
|
||||||
|
LEFT JOIN usage_billing_facts AS "usage"
|
||||||
|
ON "usage".provider_api_key_id = requested.provider_api_key_id
|
||||||
|
AND "usage".created_at >= to_timestamp(requested.start_unix_secs::DOUBLE PRECISION)
|
||||||
|
AND "usage".created_at < to_timestamp(requested.end_unix_secs::DOUBLE PRECISION)
|
||||||
|
GROUP BY
|
||||||
|
requested.provider_api_key_id,
|
||||||
|
requested.window_code,
|
||||||
|
requested.ordinality
|
||||||
|
ORDER BY requested.ordinality ASC
|
||||||
@@ -234,6 +234,21 @@ fn usage_sql_summarizes_usage_by_provider_api_key_ids_in_database() {
|
|||||||
assert!(super::SUMMARIZE_USAGE_BY_PROVIDER_API_KEY_IDS_SQL.contains("ANY($1::TEXT[])"));
|
assert!(super::SUMMARIZE_USAGE_BY_PROVIDER_API_KEY_IDS_SQL.contains("ANY($1::TEXT[])"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn usage_sql_summarizes_provider_key_window_usage_from_billing_facts() {
|
||||||
|
assert!(super::SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL.contains("UNNEST"));
|
||||||
|
assert!(super::SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL
|
||||||
|
.contains("LEFT JOIN usage_billing_facts AS \"usage\""));
|
||||||
|
assert!(
|
||||||
|
super::SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL.contains("created_at >= to_timestamp")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
super::SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL.contains("created_at < to_timestamp")
|
||||||
|
);
|
||||||
|
assert!(super::SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL
|
||||||
|
.contains("COUNT(\"usage\".id)::BIGINT AS request_count"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn usage_sql_serializes_request_id_upserts_before_reading_previous_usage() {
|
fn usage_sql_serializes_request_id_upserts_before_reading_previous_usage() {
|
||||||
assert!(super::LOCK_USAGE_REQUEST_ID_SQL.contains("pg_advisory_xact_lock"));
|
assert!(super::LOCK_USAGE_REQUEST_ID_SQL.contains("pg_advisory_xact_lock"));
|
||||||
@@ -455,6 +470,8 @@ fn usage_sql_raw_aggregates_use_canonical_billing_facts() {
|
|||||||
.contains("FROM usage_billing_facts AS \"usage\""));
|
.contains("FROM usage_billing_facts AS \"usage\""));
|
||||||
assert!(super::SUMMARIZE_USAGE_TOTALS_BY_USER_IDS_SQL
|
assert!(super::SUMMARIZE_USAGE_TOTALS_BY_USER_IDS_SQL
|
||||||
.contains("FROM usage_billing_facts AS \"usage\""));
|
.contains("FROM usage_billing_facts AS \"usage\""));
|
||||||
|
assert!(super::SUMMARIZE_PROVIDER_API_KEY_WINDOW_USAGE_SQL
|
||||||
|
.contains("usage_billing_facts AS \"usage\""));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -348,10 +348,30 @@ export interface KiroUpstreamMetadata {
|
|||||||
banned_at?: number // 封禁时间(Unix 时间戳,秒)
|
banned_at?: number // 封禁时间(Unix 时间戳,秒)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ChatGPTWebUpstreamMetadata {
|
||||||
|
updated_at?: number // Unix 时间戳(秒)
|
||||||
|
plan_type?: string | null
|
||||||
|
default_model_slug?: string | null
|
||||||
|
blocked_features?: string[] | null
|
||||||
|
image_quota_feature_name?: string | null
|
||||||
|
image_quota_remaining?: number | null
|
||||||
|
image_quota_total?: number | null
|
||||||
|
image_quota_used?: number | null
|
||||||
|
image_quota_reset_at?: number | null
|
||||||
|
image_quota_reset_after?: string | null
|
||||||
|
image_quota_blocked?: boolean | null
|
||||||
|
limits_progress?: Array<Record<string, unknown>> | null
|
||||||
|
email?: string | null
|
||||||
|
account_id?: string | null
|
||||||
|
account_user_id?: string | null
|
||||||
|
user_id?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
export interface UpstreamMetadata {
|
export interface UpstreamMetadata {
|
||||||
codex?: CodexUpstreamMetadata
|
codex?: CodexUpstreamMetadata
|
||||||
antigravity?: AntigravityUpstreamMetadata
|
antigravity?: AntigravityUpstreamMetadata
|
||||||
kiro?: KiroUpstreamMetadata
|
kiro?: KiroUpstreamMetadata
|
||||||
|
chatgpt_web?: ChatGPTWebUpstreamMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按格式的健康度数据
|
// 按格式的健康度数据
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ export interface AccountStatusSnapshot {
|
|||||||
recoverable?: boolean
|
recoverable?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface QuotaWindowUsageSnapshot {
|
||||||
|
request_count?: number | null
|
||||||
|
total_tokens?: number | null
|
||||||
|
total_cost_usd?: number | string | null
|
||||||
|
}
|
||||||
|
|
||||||
export interface QuotaWindowSnapshot {
|
export interface QuotaWindowSnapshot {
|
||||||
code: string
|
code: string
|
||||||
label?: string | null
|
label?: string | null
|
||||||
@@ -33,6 +39,7 @@ export interface QuotaWindowSnapshot {
|
|||||||
reset_seconds?: number | null
|
reset_seconds?: number | null
|
||||||
window_minutes?: number | null
|
window_minutes?: number | null
|
||||||
is_exhausted?: boolean | null
|
is_exhausted?: boolean | null
|
||||||
|
usage?: QuotaWindowUsageSnapshot | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QuotaCreditsSnapshot {
|
export interface QuotaCreditsSnapshot {
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: 20,
|
pageSize: 20,
|
||||||
sortBy: 'last_used_at',
|
sortBy: 'last_used_at',
|
||||||
sortOrder: 'asc',
|
sortOrder: 'asc',
|
||||||
|
statsMode: 'account_total',
|
||||||
},
|
},
|
||||||
storage,
|
storage,
|
||||||
)
|
)
|
||||||
@@ -52,6 +53,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: '100',
|
pageSize: '100',
|
||||||
sortBy: 'imported_at',
|
sortBy: 'imported_at',
|
||||||
sortOrder: 'desc',
|
sortOrder: 'desc',
|
||||||
|
statsMode: 'current_cycle',
|
||||||
},
|
},
|
||||||
storage,
|
storage,
|
||||||
)
|
)
|
||||||
@@ -64,6 +66,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: 100,
|
pageSize: 100,
|
||||||
sortBy: 'imported_at',
|
sortBy: 'imported_at',
|
||||||
sortOrder: 'desc',
|
sortOrder: 'desc',
|
||||||
|
statsMode: 'current_cycle',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -77,6 +80,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
sortBy: 'last_used_at',
|
sortBy: 'last_used_at',
|
||||||
sortOrder: 'asc',
|
sortOrder: 'asc',
|
||||||
|
statsMode: 'account_total',
|
||||||
},
|
},
|
||||||
storage,
|
storage,
|
||||||
)
|
)
|
||||||
@@ -91,6 +95,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
sortBy: 'last_used_at',
|
sortBy: 'last_used_at',
|
||||||
sortOrder: 'asc',
|
sortOrder: 'asc',
|
||||||
|
statsMode: 'account_total',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -104,6 +109,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
sortBy: null,
|
sortBy: null,
|
||||||
sortOrder: 'desc',
|
sortOrder: 'desc',
|
||||||
|
statsMode: 'current_cycle',
|
||||||
}),
|
}),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
providerId: 'provider-d',
|
providerId: 'provider-d',
|
||||||
@@ -113,6 +119,7 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: undefined,
|
pageSize: undefined,
|
||||||
sortBy: undefined,
|
sortBy: undefined,
|
||||||
sortOrder: undefined,
|
sortOrder: undefined,
|
||||||
|
statsMode: undefined,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -126,13 +133,36 @@ describe('poolManagementState', () => {
|
|||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
sortBy: 'last_used_at',
|
sortBy: 'last_used_at',
|
||||||
sortOrder: 'asc',
|
sortOrder: 'asc',
|
||||||
|
statsMode: 'account_total',
|
||||||
}),
|
}),
|
||||||
).toMatchObject({
|
).toMatchObject({
|
||||||
sortBy: 'last_used_at',
|
sortBy: 'last_used_at',
|
||||||
sortOrder: 'asc',
|
sortOrder: 'asc',
|
||||||
|
statsMode: 'account_total',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('restores stats mode from storage and lets query override it', () => {
|
||||||
|
writePoolManagementViewState(
|
||||||
|
{
|
||||||
|
providerId: 'provider-f',
|
||||||
|
search: '',
|
||||||
|
status: 'all',
|
||||||
|
page: 1,
|
||||||
|
pageSize: 50,
|
||||||
|
sortBy: null,
|
||||||
|
sortOrder: 'desc',
|
||||||
|
statsMode: 'account_total',
|
||||||
|
},
|
||||||
|
storage,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(readPoolManagementViewState({}, storage).statsMode).toBe('account_total')
|
||||||
|
expect(
|
||||||
|
readPoolManagementViewState({ statsMode: 'current_cycle' }, storage).statsMode,
|
||||||
|
).toBe('current_cycle')
|
||||||
|
})
|
||||||
|
|
||||||
it('clamps a restored page to the last available page after load', () => {
|
it('clamps a restored page to the last available page after load', () => {
|
||||||
expect(
|
expect(
|
||||||
resolvePoolManagementPageAfterLoad({
|
resolvePoolManagementPageAfterLoad({
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
buildPoolStatsDisplay,
|
||||||
|
type PoolStatsKeyInput,
|
||||||
|
} from '@/features/pool/utils/poolStatsDisplay'
|
||||||
|
|
||||||
|
function metricValues(metrics: Array<{ key: string, value: string }>) {
|
||||||
|
return Object.fromEntries(metrics.map(metric => [metric.key, metric.value]))
|
||||||
|
}
|
||||||
|
|
||||||
|
function createCodexKey(overrides: Partial<PoolStatsKeyInput> = {}): PoolStatsKeyInput {
|
||||||
|
return {
|
||||||
|
request_count: 1234,
|
||||||
|
total_tokens: 5678000,
|
||||||
|
total_cost_usd: '12.3456',
|
||||||
|
status_snapshot: {
|
||||||
|
quota: {
|
||||||
|
windows: [
|
||||||
|
{
|
||||||
|
code: '5h',
|
||||||
|
usage: {
|
||||||
|
request_count: 5,
|
||||||
|
total_tokens: 2500,
|
||||||
|
total_cost_usd: '0.0045',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: 'weekly',
|
||||||
|
usage: {
|
||||||
|
request_count: 0,
|
||||||
|
total_tokens: 0,
|
||||||
|
total_cost_usd: '0.00000000',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('poolStatsDisplay', () => {
|
||||||
|
it('builds Codex current-cycle groups in 5H and weekly order', () => {
|
||||||
|
const display = buildPoolStatsDisplay(createCodexKey(), 'codex', 'current_cycle')
|
||||||
|
|
||||||
|
expect(display.kind).toBe('codex_cycle')
|
||||||
|
if (display.kind !== 'codex_cycle') throw new Error('expected codex cycle display')
|
||||||
|
|
||||||
|
expect(display.groups.map(group => group.label)).toEqual(['5H', '周'])
|
||||||
|
expect(metricValues(display.groups[0].metrics)).toEqual({
|
||||||
|
request_count: '5',
|
||||||
|
total_tokens: '2.5K',
|
||||||
|
total_cost_usd: '$0.0045',
|
||||||
|
})
|
||||||
|
expect(metricValues(display.groups[1].metrics)).toEqual({
|
||||||
|
request_count: '0',
|
||||||
|
total_tokens: '0',
|
||||||
|
total_cost_usd: '0',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders missing cycle usage as dashes instead of account-total fallback', () => {
|
||||||
|
const display = buildPoolStatsDisplay(
|
||||||
|
createCodexKey({
|
||||||
|
status_snapshot: {
|
||||||
|
quota: {
|
||||||
|
windows: [{ code: '5h', usage: null }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
'codex',
|
||||||
|
'current_cycle',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(display.kind).toBe('codex_cycle')
|
||||||
|
if (display.kind !== 'codex_cycle') throw new Error('expected codex cycle display')
|
||||||
|
|
||||||
|
expect(metricValues(display.groups[0].metrics)).toEqual({
|
||||||
|
request_count: '—',
|
||||||
|
total_tokens: '—',
|
||||||
|
total_cost_usd: '—',
|
||||||
|
})
|
||||||
|
expect(metricValues(display.groups[1].metrics)).toEqual({
|
||||||
|
request_count: '—',
|
||||||
|
total_tokens: '—',
|
||||||
|
total_cost_usd: '—',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('preserves account-total formatting when toggled away from current cycle', () => {
|
||||||
|
const display = buildPoolStatsDisplay(createCodexKey(), 'codex', 'account_total')
|
||||||
|
|
||||||
|
expect(display.kind).toBe('account_total')
|
||||||
|
if (display.kind !== 'account_total') throw new Error('expected account total display')
|
||||||
|
|
||||||
|
expect(metricValues(display.metrics)).toEqual({
|
||||||
|
request_count: '1,234',
|
||||||
|
total_tokens: '5.7M',
|
||||||
|
total_cost_usd: '$12.35',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps non-Codex providers on account totals even in current-cycle mode', () => {
|
||||||
|
const display = buildPoolStatsDisplay(createCodexKey(), 'openai', 'current_cycle')
|
||||||
|
|
||||||
|
expect(display.kind).toBe('account_total')
|
||||||
|
if (display.kind !== 'account_total') throw new Error('expected account total display')
|
||||||
|
expect(metricValues(display.metrics)).toMatchObject({
|
||||||
|
request_count: '1,234',
|
||||||
|
total_tokens: '5.7M',
|
||||||
|
total_cost_usd: '$12.35',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
export type PoolManagementStatus = 'all' | 'active' | 'cooldown' | 'inactive'
|
export type PoolManagementStatus = 'all' | 'active' | 'cooldown' | 'inactive'
|
||||||
export type PoolManagementSortBy = 'imported_at' | 'last_used_at'
|
export type PoolManagementSortBy = 'imported_at' | 'last_used_at'
|
||||||
export type PoolManagementSortOrder = 'asc' | 'desc'
|
export type PoolManagementSortOrder = 'asc' | 'desc'
|
||||||
|
export type PoolManagementStatsMode = 'current_cycle' | 'account_total'
|
||||||
|
|
||||||
export interface PoolManagementViewState {
|
export interface PoolManagementViewState {
|
||||||
providerId: string | null
|
providerId: string | null
|
||||||
@@ -10,6 +11,7 @@ export interface PoolManagementViewState {
|
|||||||
pageSize: number
|
pageSize: number
|
||||||
sortBy: PoolManagementSortBy | null
|
sortBy: PoolManagementSortBy | null
|
||||||
sortOrder: PoolManagementSortOrder
|
sortOrder: PoolManagementSortOrder
|
||||||
|
statsMode: PoolManagementStatsMode
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PoolManagementStateSource {
|
export interface PoolManagementStateSource {
|
||||||
@@ -20,6 +22,7 @@ export interface PoolManagementStateSource {
|
|||||||
pageSize?: string
|
pageSize?: string
|
||||||
sortBy?: string
|
sortBy?: string
|
||||||
sortOrder?: string
|
sortOrder?: string
|
||||||
|
statsMode?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StorageLike {
|
export interface StorageLike {
|
||||||
@@ -28,6 +31,10 @@ export interface StorageLike {
|
|||||||
removeItem(key: string): void
|
removeItem(key: string): void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type PoolManagementViewStateInput = Partial<{
|
||||||
|
[Key in keyof PoolManagementViewState]: unknown
|
||||||
|
}>
|
||||||
|
|
||||||
export const POOL_MANAGEMENT_VIEW_STORAGE_KEY = 'aether:pool-management:view-state'
|
export const POOL_MANAGEMENT_VIEW_STORAGE_KEY = 'aether:pool-management:view-state'
|
||||||
|
|
||||||
export const DEFAULT_POOL_MANAGEMENT_VIEW_STATE: PoolManagementViewState = {
|
export const DEFAULT_POOL_MANAGEMENT_VIEW_STATE: PoolManagementViewState = {
|
||||||
@@ -38,6 +45,7 @@ export const DEFAULT_POOL_MANAGEMENT_VIEW_STATE: PoolManagementViewState = {
|
|||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
sortBy: null,
|
sortBy: null,
|
||||||
sortOrder: 'desc',
|
sortOrder: 'desc',
|
||||||
|
statsMode: 'current_cycle',
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeProviderId(value: unknown): string | null {
|
function normalizeProviderId(value: unknown): string | null {
|
||||||
@@ -75,7 +83,11 @@ function normalizeSortOrder(value: unknown): PoolManagementSortOrder {
|
|||||||
return value === 'asc' ? 'asc' : 'desc'
|
return value === 'asc' ? 'asc' : 'desc'
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeViewState(input: Partial<PoolManagementViewState>): PoolManagementViewState {
|
function normalizeStatsMode(value: unknown): PoolManagementStatsMode {
|
||||||
|
return value === 'account_total' ? 'account_total' : 'current_cycle'
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeViewState(input: PoolManagementViewStateInput): PoolManagementViewState {
|
||||||
return {
|
return {
|
||||||
providerId: normalizeProviderId(input.providerId),
|
providerId: normalizeProviderId(input.providerId),
|
||||||
search: normalizeSearch(input.search),
|
search: normalizeSearch(input.search),
|
||||||
@@ -84,6 +96,7 @@ function normalizeViewState(input: Partial<PoolManagementViewState>): PoolManage
|
|||||||
pageSize: normalizePositiveInteger(input.pageSize, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.pageSize),
|
pageSize: normalizePositiveInteger(input.pageSize, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.pageSize),
|
||||||
sortBy: normalizeSortBy(input.sortBy),
|
sortBy: normalizeSortBy(input.sortBy),
|
||||||
sortOrder: normalizeSortOrder(input.sortOrder),
|
sortOrder: normalizeSortOrder(input.sortOrder),
|
||||||
|
statsMode: normalizeStatsMode(input.statsMode),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,15 +119,20 @@ export function readPoolManagementViewState(
|
|||||||
): PoolManagementViewState {
|
): PoolManagementViewState {
|
||||||
const stored = normalizeViewState(readStoredState(storage))
|
const stored = normalizeViewState(readStoredState(storage))
|
||||||
|
|
||||||
return normalizeViewState({
|
return {
|
||||||
providerId: source.providerId ?? stored.providerId,
|
providerId: source.providerId !== undefined ? normalizeProviderId(source.providerId) : stored.providerId,
|
||||||
search: source.search ?? stored.search,
|
search: source.search !== undefined ? normalizeSearch(source.search) : stored.search,
|
||||||
status: source.status ?? stored.status,
|
status: source.status !== undefined ? normalizeStatus(source.status) : stored.status,
|
||||||
page: source.page ?? stored.page,
|
page: source.page !== undefined
|
||||||
pageSize: source.pageSize ?? stored.pageSize,
|
? normalizePositiveInteger(source.page, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.page)
|
||||||
sortBy: source.sortBy ?? stored.sortBy,
|
: stored.page,
|
||||||
sortOrder: source.sortOrder ?? stored.sortOrder,
|
pageSize: source.pageSize !== undefined
|
||||||
})
|
? normalizePositiveInteger(source.pageSize, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.pageSize)
|
||||||
|
: stored.pageSize,
|
||||||
|
sortBy: source.sortBy !== undefined ? normalizeSortBy(source.sortBy) : stored.sortBy,
|
||||||
|
sortOrder: source.sortOrder !== undefined ? normalizeSortOrder(source.sortOrder) : stored.sortOrder,
|
||||||
|
statsMode: source.statsMode !== undefined ? normalizeStatsMode(source.statsMode) : stored.statsMode,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writePoolManagementViewState(
|
export function writePoolManagementViewState(
|
||||||
@@ -150,6 +168,7 @@ export function buildPoolManagementQueryPatch(
|
|||||||
: String(normalized.pageSize),
|
: String(normalized.pageSize),
|
||||||
sortBy: normalized.sortBy || undefined,
|
sortBy: normalized.sortBy || undefined,
|
||||||
sortOrder: normalized.sortBy ? normalized.sortOrder : undefined,
|
sortOrder: normalized.sortBy ? normalized.sortOrder : undefined,
|
||||||
|
statsMode: normalized.statsMode === 'account_total' ? 'account_total' : undefined,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
178
frontend/src/features/pool/utils/poolStatsDisplay.ts
Normal file
178
frontend/src/features/pool/utils/poolStatsDisplay.ts
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
import type { QuotaWindowUsageSnapshot } from '@/api/endpoints/types/statusSnapshot'
|
||||||
|
import type { PoolManagementStatsMode } from '@/features/pool/utils/poolManagementState'
|
||||||
|
|
||||||
|
export type PoolStatsMetricKey = 'request_count' | 'total_tokens' | 'total_cost_usd'
|
||||||
|
export type PoolStatsDisplayKind = 'account_total' | 'codex_cycle'
|
||||||
|
export type PoolCodexCycleWindowCode = '5h' | 'weekly'
|
||||||
|
|
||||||
|
export interface PoolStatsKeyInput {
|
||||||
|
request_count?: number | null
|
||||||
|
total_tokens?: number | null
|
||||||
|
total_cost_usd?: number | string | null
|
||||||
|
status_snapshot?: {
|
||||||
|
quota?: {
|
||||||
|
windows?: Array<{
|
||||||
|
code?: string | null
|
||||||
|
usage?: QuotaWindowUsageSnapshot | null
|
||||||
|
} | null> | null
|
||||||
|
} | null
|
||||||
|
} | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PoolStatsMetric {
|
||||||
|
key: PoolStatsMetricKey
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
missing: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PoolAccountTotalStatsDisplay {
|
||||||
|
kind: 'account_total'
|
||||||
|
metrics: PoolStatsMetric[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PoolCodexCycleStatsGroup {
|
||||||
|
code: PoolCodexCycleWindowCode
|
||||||
|
label: string
|
||||||
|
metrics: PoolStatsMetric[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PoolCodexCycleStatsDisplay {
|
||||||
|
kind: 'codex_cycle'
|
||||||
|
groups: PoolCodexCycleStatsGroup[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PoolStatsDisplay = PoolAccountTotalStatsDisplay | PoolCodexCycleStatsDisplay
|
||||||
|
|
||||||
|
const MISSING_STAT_VALUE = '—'
|
||||||
|
const CODEX_CYCLE_WINDOWS: Array<{ code: PoolCodexCycleWindowCode, label: string }> = [
|
||||||
|
{ code: '5h', label: '5H' },
|
||||||
|
{ code: 'weekly', label: '周' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function isCodexProviderType(providerType: string | null | undefined): boolean {
|
||||||
|
return String(providerType || '').trim().toLowerCase() === 'codex'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatPoolStatInteger(value: number | null | undefined): string {
|
||||||
|
const n = Number(value ?? 0)
|
||||||
|
if (!Number.isFinite(n) || n <= 0) return '0'
|
||||||
|
return Math.round(n).toLocaleString('en-US')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatPoolTokenCount(value: number | null | undefined): string {
|
||||||
|
const n = Number(value ?? 0)
|
||||||
|
if (!Number.isFinite(n) || n <= 0) return '0'
|
||||||
|
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
|
||||||
|
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
|
||||||
|
return String(Math.round(n))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatPoolStatUsd(value: number | string | null | undefined): string {
|
||||||
|
const n = Number(value ?? 0)
|
||||||
|
if (!Number.isFinite(n) || n <= 0) return '$0.00'
|
||||||
|
if (n < 0.01) return `$${n.toFixed(4)}`
|
||||||
|
if (n < 1) return `$${n.toFixed(3)}`
|
||||||
|
if (n < 1000) return `$${n.toFixed(2)}`
|
||||||
|
return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCycleInteger(value: number | null | undefined): string | null {
|
||||||
|
if (value == null) return null
|
||||||
|
const n = Number(value)
|
||||||
|
if (!Number.isFinite(n)) return null
|
||||||
|
if (n <= 0) return '0'
|
||||||
|
return Math.round(n).toLocaleString('en-US')
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCycleTokenCount(value: number | null | undefined): string | null {
|
||||||
|
if (value == null) return null
|
||||||
|
const n = Number(value)
|
||||||
|
if (!Number.isFinite(n)) return null
|
||||||
|
return formatPoolTokenCount(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCycleUsd(value: number | string | null | undefined): string | null {
|
||||||
|
if (value == null) return null
|
||||||
|
const n = Number(value)
|
||||||
|
if (!Number.isFinite(n)) return null
|
||||||
|
if (n <= 0) return '0'
|
||||||
|
return formatPoolStatUsd(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMetric(
|
||||||
|
key: PoolStatsMetricKey,
|
||||||
|
label: string,
|
||||||
|
value: string | null,
|
||||||
|
): PoolStatsMetric {
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
label,
|
||||||
|
value: value ?? MISSING_STAT_VALUE,
|
||||||
|
missing: value == null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeWindowCode(value: unknown): string {
|
||||||
|
return String(value || '').trim().toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
function getQuotaWindowUsage(
|
||||||
|
key: PoolStatsKeyInput,
|
||||||
|
code: PoolCodexCycleWindowCode,
|
||||||
|
): QuotaWindowUsageSnapshot | null {
|
||||||
|
const windows = key.status_snapshot?.quota?.windows
|
||||||
|
if (!Array.isArray(windows)) return null
|
||||||
|
|
||||||
|
const window = windows.find(item => normalizeWindowCode(item?.code) === code)
|
||||||
|
return window?.usage ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAccountTotalMetrics(key: PoolStatsKeyInput): PoolStatsMetric[] {
|
||||||
|
return [
|
||||||
|
createMetric('request_count', '请求', formatPoolStatInteger(key.request_count)),
|
||||||
|
createMetric('total_tokens', 'Token', formatPoolTokenCount(key.total_tokens)),
|
||||||
|
createMetric('total_cost_usd', '费用', formatPoolStatUsd(key.total_cost_usd)),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCycleMetrics(usage: QuotaWindowUsageSnapshot | null): PoolStatsMetric[] {
|
||||||
|
return [
|
||||||
|
createMetric('request_count', '请求', formatCycleInteger(usage?.request_count)),
|
||||||
|
createMetric('total_tokens', 'Token', formatCycleTokenCount(usage?.total_tokens)),
|
||||||
|
createMetric('total_cost_usd', '费用', formatCycleUsd(usage?.total_cost_usd)),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildAccountTotalStatsDisplay(
|
||||||
|
key: PoolStatsKeyInput,
|
||||||
|
): PoolAccountTotalStatsDisplay {
|
||||||
|
return {
|
||||||
|
kind: 'account_total',
|
||||||
|
metrics: buildAccountTotalMetrics(key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCodexCycleStatsDisplay(
|
||||||
|
key: PoolStatsKeyInput,
|
||||||
|
): PoolCodexCycleStatsDisplay {
|
||||||
|
return {
|
||||||
|
kind: 'codex_cycle',
|
||||||
|
groups: CODEX_CYCLE_WINDOWS.map(window => ({
|
||||||
|
...window,
|
||||||
|
metrics: buildCycleMetrics(getQuotaWindowUsage(key, window.code)),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPoolStatsDisplay(
|
||||||
|
key: PoolStatsKeyInput,
|
||||||
|
providerType: string | null | undefined,
|
||||||
|
mode: PoolManagementStatsMode,
|
||||||
|
): PoolStatsDisplay {
|
||||||
|
if (isCodexProviderType(providerType) && mode === 'current_cycle') {
|
||||||
|
return buildCodexCycleStatsDisplay(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildAccountTotalStatsDisplay(key)
|
||||||
|
}
|
||||||
@@ -818,6 +818,51 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- ChatGPT Web 上游额度信息(生图配额) -->
|
||||||
|
<div
|
||||||
|
v-if="provider.provider_type === 'chatgpt_web' && hasChatGPTWebQuotaDisplayData(key)"
|
||||||
|
class="mt-2 p-2 rounded-md bg-muted/30"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between mb-1">
|
||||||
|
<span class="text-[10px] text-muted-foreground">账号配额</span>
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<RefreshCw
|
||||||
|
v-if="refreshingQuota"
|
||||||
|
class="w-3 h-3 text-muted-foreground/70 animate-spin"
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
v-if="getChatGPTWebQuotaDisplay(key)?.updated_at"
|
||||||
|
class="text-[9px] text-muted-foreground/70"
|
||||||
|
>
|
||||||
|
{{ formatKiroUpdatedAt(getChatGPTWebQuotaDisplay(key)?.updated_at || 0) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center justify-between text-[10px] mb-0.5">
|
||||||
|
<span class="text-muted-foreground">使用额度</span>
|
||||||
|
<span :class="getQuotaRemainingClass(getChatGPTWebQuotaUsedPercent(key))">
|
||||||
|
{{ getChatGPTWebQuotaRemainingPercent(key).toFixed(1) }}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="relative w-full h-1.5 bg-border rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
class="absolute left-0 top-0 h-full transition-all duration-300"
|
||||||
|
:class="getQuotaRemainingBarColor(getChatGPTWebQuotaUsedPercent(key))"
|
||||||
|
:style="{ width: `${Math.max(getChatGPTWebQuotaRemainingPercent(key), 0)}%` }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between text-[9px] text-muted-foreground/70 mt-0.5">
|
||||||
|
<span>
|
||||||
|
{{ formatChatGPTWebUsage(getChatGPTWebQuotaDisplay(key)?.image_quota_used) }} /
|
||||||
|
{{ formatChatGPTWebUsage(getChatGPTWebQuotaDisplay(key)?.image_quota_total) }}
|
||||||
|
</span>
|
||||||
|
<span v-if="getChatGPTWebQuotaDisplay(key)?.image_quota_reset_at">
|
||||||
|
{{ formatKiroResetTime(getChatGPTWebQuotaDisplay(key)?.image_quota_reset_at) }}重置
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<!-- 第二行:优先级 + API 格式(展开显示) + 统计信息 -->
|
<!-- 第二行:优先级 + API 格式(展开显示) + 统计信息 -->
|
||||||
<div class="flex items-center gap-1.5 mt-1 text-[11px] text-muted-foreground">
|
<div class="flex items-center gap-1.5 mt-1 text-[11px] text-muted-foreground">
|
||||||
<!-- 优先级放最前面,支持点击编辑 -->
|
<!-- 优先级放最前面,支持点击编辑 -->
|
||||||
@@ -1165,6 +1210,7 @@ import type {
|
|||||||
AntigravityModelQuota,
|
AntigravityModelQuota,
|
||||||
AntigravityUpstreamMetadata,
|
AntigravityUpstreamMetadata,
|
||||||
CodexUpstreamMetadata,
|
CodexUpstreamMetadata,
|
||||||
|
ChatGPTWebUpstreamMetadata,
|
||||||
KiroUpstreamMetadata,
|
KiroUpstreamMetadata,
|
||||||
QuotaStatusSnapshot,
|
QuotaStatusSnapshot,
|
||||||
QuotaWindowSnapshot,
|
QuotaWindowSnapshot,
|
||||||
@@ -1815,7 +1861,7 @@ async function handleClearOAuthInvalid(key: EndpointAPIKey) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Codex / Antigravity / Kiro:打开抽屉后自动后台刷新(配额缓存缺失/过期,或 Token 即将过期时触发)
|
// Codex / Antigravity / Kiro / ChatGPT Web:打开抽屉后自动后台刷新(配额缓存缺失/过期,或 Token 即将过期时触发)
|
||||||
const AUTO_QUOTA_REFRESH_STALE_SECONDS = 5 * 60
|
const AUTO_QUOTA_REFRESH_STALE_SECONDS = 5 * 60
|
||||||
// 与后端 OAuth 懒刷新阈值对齐:到期前 2 分钟内视为需要刷新
|
// 与后端 OAuth 懒刷新阈值对齐:到期前 2 分钟内视为需要刷新
|
||||||
const AUTO_TOKEN_REFRESH_SKEW_SECONDS = 2 * 60
|
const AUTO_TOKEN_REFRESH_SKEW_SECONDS = 2 * 60
|
||||||
@@ -1834,7 +1880,7 @@ function quotaSnapshotHasDisplayData(quota: QuotaStatusSnapshot | null | undefin
|
|||||||
|
|
||||||
function getQuotaSnapshotForProvider(
|
function getQuotaSnapshotForProvider(
|
||||||
key: EndpointAPIKey,
|
key: EndpointAPIKey,
|
||||||
providerType: 'codex' | 'kiro' | 'antigravity' | 'gemini_cli',
|
providerType: 'codex' | 'kiro' | 'antigravity' | 'chatgpt_web' | 'gemini_cli',
|
||||||
): QuotaStatusSnapshot | null {
|
): QuotaStatusSnapshot | null {
|
||||||
const quota = key.status_snapshot?.quota
|
const quota = key.status_snapshot?.quota
|
||||||
if (!quota) return null
|
if (!quota) return null
|
||||||
@@ -2006,6 +2052,86 @@ function hasKiroQuotaDisplayData(key: EndpointAPIKey): boolean {
|
|||||||
return !!kiro && (kiro.usage_percentage !== undefined || kiro.usage_limit !== undefined)
|
return !!kiro && (kiro.usage_percentage !== undefined || kiro.usage_limit !== undefined)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ChatGPTWebQuotaDisplay = ChatGPTWebUpstreamMetadata & {
|
||||||
|
image_quota_remaining_percent?: number
|
||||||
|
image_quota_used_percent?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function getChatGPTWebQuotaDisplay(key: EndpointAPIKey): ChatGPTWebQuotaDisplay | null {
|
||||||
|
const quota = getQuotaSnapshotForProvider(key, 'chatgpt_web')
|
||||||
|
if (!quota) return null
|
||||||
|
|
||||||
|
const display: ChatGPTWebQuotaDisplay = {}
|
||||||
|
const updatedAt = getQuotaSnapshotUpdatedAt(quota)
|
||||||
|
if (updatedAt !== undefined) display.updated_at = updatedAt
|
||||||
|
if (quota.plan_type) display.plan_type = quota.plan_type
|
||||||
|
if (quota.code === 'exhausted' || quota.code === 'banned') display.image_quota_blocked = true
|
||||||
|
|
||||||
|
const imageWindow =
|
||||||
|
getQuotaWindow(quota, 'image_gen')
|
||||||
|
?? getQuotaWindowByScope(quota, 'account')[0]
|
||||||
|
?? null
|
||||||
|
if (imageWindow) {
|
||||||
|
const remainingValue = typeof imageWindow.remaining_value === 'number' ? imageWindow.remaining_value : undefined
|
||||||
|
const limitValue = typeof imageWindow.limit_value === 'number' ? imageWindow.limit_value : undefined
|
||||||
|
const usedValue = typeof imageWindow.used_value === 'number' ? imageWindow.used_value : undefined
|
||||||
|
const remainingPercent = getQuotaWindowRemainingPercent(imageWindow)
|
||||||
|
const usedPercent = getQuotaWindowUsedPercent(imageWindow)
|
||||||
|
|
||||||
|
if (remainingValue !== undefined) display.image_quota_remaining = remainingValue
|
||||||
|
if (limitValue !== undefined) display.image_quota_total = limitValue
|
||||||
|
if (usedValue !== undefined) display.image_quota_used = usedValue
|
||||||
|
if (remainingPercent !== undefined) display.image_quota_remaining_percent = remainingPercent
|
||||||
|
if (usedPercent !== undefined) display.image_quota_used_percent = usedPercent
|
||||||
|
if (typeof imageWindow.reset_at === 'number') display.image_quota_reset_at = imageWindow.reset_at
|
||||||
|
if (typeof imageWindow.reset_seconds === 'number') {
|
||||||
|
const resetAt = updatedAt === undefined ? undefined : updatedAt + imageWindow.reset_seconds
|
||||||
|
if (resetAt !== undefined && display.image_quota_reset_at === undefined) {
|
||||||
|
display.image_quota_reset_at = resetAt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.keys(display).length > 0 ? display : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasChatGPTWebQuotaDisplayData(key: EndpointAPIKey): boolean {
|
||||||
|
const display = getChatGPTWebQuotaDisplay(key)
|
||||||
|
return !!display && (
|
||||||
|
display.image_quota_remaining_percent !== undefined
|
||||||
|
|| display.image_quota_total !== undefined
|
||||||
|
|| display.image_quota_used !== undefined
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function getChatGPTWebQuotaUsedPercent(key: EndpointAPIKey): number {
|
||||||
|
const display = getChatGPTWebQuotaDisplay(key)
|
||||||
|
if (!display) return 0
|
||||||
|
if (typeof display.image_quota_used_percent === 'number') return display.image_quota_used_percent
|
||||||
|
if (typeof display.image_quota_remaining_percent === 'number') {
|
||||||
|
return Math.max(100 - display.image_quota_remaining_percent, 0)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function getChatGPTWebQuotaRemainingPercent(key: EndpointAPIKey): number {
|
||||||
|
const display = getChatGPTWebQuotaDisplay(key)
|
||||||
|
if (!display) return 0
|
||||||
|
if (typeof display.image_quota_remaining_percent === 'number') return display.image_quota_remaining_percent
|
||||||
|
if (typeof display.image_quota_used_percent === 'number') {
|
||||||
|
return Math.max(100 - display.image_quota_used_percent, 0)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatChatGPTWebUsage(value: number | null | undefined): string {
|
||||||
|
if (value === undefined || value === null) return '-'
|
||||||
|
if (Math.abs(value - Math.round(value)) < 1e-6) {
|
||||||
|
return String(Math.round(value))
|
||||||
|
}
|
||||||
|
return value.toFixed(1)
|
||||||
|
}
|
||||||
|
|
||||||
function isKiroBannedKey(key: EndpointAPIKey): boolean {
|
function isKiroBannedKey(key: EndpointAPIKey): boolean {
|
||||||
const quota = getQuotaSnapshotForProvider(key, 'kiro')
|
const quota = getQuotaSnapshotForProvider(key, 'kiro')
|
||||||
return String(quota?.code || '').trim().toLowerCase() === 'banned'
|
return String(quota?.code || '').trim().toLowerCase() === 'banned'
|
||||||
@@ -2138,7 +2264,7 @@ function shouldAutoRefreshCodexQuota(): boolean {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查 OAuth Token 是否即将过期(Codex / Antigravity / Kiro)
|
// 检查 OAuth Token 是否即将过期(Codex / Antigravity / Kiro / ChatGPT Web)
|
||||||
function isTokenExpiringSoon(key: EndpointAPIKey, now: number): boolean {
|
function isTokenExpiringSoon(key: EndpointAPIKey, now: number): boolean {
|
||||||
const oauthCode = String(key.status_snapshot?.oauth?.code || '').trim().toLowerCase()
|
const oauthCode = String(key.status_snapshot?.oauth?.code || '').trim().toLowerCase()
|
||||||
if (oauthCode && oauthCode !== 'valid' && oauthCode !== 'expiring') {
|
if (oauthCode && oauthCode !== 'valid' && oauthCode !== 'expiring') {
|
||||||
@@ -2193,6 +2319,28 @@ function shouldAutoRefreshKiroQuota(): boolean {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function shouldAutoRefreshChatGPTWebQuota(): boolean {
|
||||||
|
if (provider.value?.provider_type !== 'chatgpt_web') return false
|
||||||
|
const now = Math.floor(Date.now() / 1000)
|
||||||
|
|
||||||
|
for (const { key } of allKeys.value) {
|
||||||
|
if (!key.is_active) continue
|
||||||
|
|
||||||
|
if (isTokenExpiringSoon(key, now)) return true
|
||||||
|
|
||||||
|
if (!hasChatGPTWebQuotaDisplayData(key)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedAt = getChatGPTWebQuotaDisplay(key)?.updated_at
|
||||||
|
if (typeof updatedAt !== 'number' || (now - updatedAt) > AUTO_QUOTA_REFRESH_STALE_SECONDS) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
function defaultQuotaSnapshot(): QuotaStatusSnapshot {
|
function defaultQuotaSnapshot(): QuotaStatusSnapshot {
|
||||||
return {
|
return {
|
||||||
code: 'unknown',
|
code: 'unknown',
|
||||||
@@ -2270,14 +2418,14 @@ function applyQuotaResults(
|
|||||||
return applied
|
return applied
|
||||||
}
|
}
|
||||||
|
|
||||||
// 通用的自动刷新配额函数(支持 Codex、Antigravity 和 Kiro)
|
// 通用的自动刷新配额函数(支持 Codex、Antigravity、Kiro 和 ChatGPT Web)
|
||||||
async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean } = {}) {
|
async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean } = {}) {
|
||||||
const providerId = props.providerId
|
const providerId = props.providerId
|
||||||
if (!providerId) return
|
if (!providerId) return
|
||||||
if (refreshingQuota.value) return
|
if (refreshingQuota.value) return
|
||||||
|
|
||||||
const providerType = provider.value?.provider_type
|
const providerType = provider.value?.provider_type
|
||||||
if (providerType !== 'codex' && providerType !== 'antigravity' && providerType !== 'kiro') return
|
if (providerType !== 'codex' && providerType !== 'antigravity' && providerType !== 'kiro' && providerType !== 'chatgpt_web') return
|
||||||
|
|
||||||
// 检查是否需要刷新
|
// 检查是否需要刷新
|
||||||
let shouldRefresh = false
|
let shouldRefresh = false
|
||||||
@@ -2287,6 +2435,8 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
|
|||||||
shouldRefresh = shouldAutoRefreshAntigravityQuota()
|
shouldRefresh = shouldAutoRefreshAntigravityQuota()
|
||||||
} else if (providerType === 'kiro') {
|
} else if (providerType === 'kiro') {
|
||||||
shouldRefresh = shouldAutoRefreshKiroQuota()
|
shouldRefresh = shouldAutoRefreshKiroQuota()
|
||||||
|
} else if (providerType === 'chatgpt_web') {
|
||||||
|
shouldRefresh = shouldAutoRefreshChatGPTWebQuota()
|
||||||
}
|
}
|
||||||
if (!shouldRefresh) return
|
if (!shouldRefresh) return
|
||||||
if (!options.ignoreCooldown && isProviderQuotaAutoRefreshCoolingDown(providerId)) return
|
if (!options.ignoreCooldown && isProviderQuotaAutoRefreshCoolingDown(providerId)) return
|
||||||
@@ -2298,6 +2448,8 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
|
|||||||
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasAntigravityQuotaDisplayData(key))
|
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasAntigravityQuotaDisplayData(key))
|
||||||
} else if (providerType === 'kiro') {
|
} else if (providerType === 'kiro') {
|
||||||
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasKiroQuotaDisplayData(key))
|
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasKiroQuotaDisplayData(key))
|
||||||
|
} else if (providerType === 'chatgpt_web') {
|
||||||
|
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasChatGPTWebQuotaDisplayData(key))
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshingQuota.value = true
|
refreshingQuota.value = true
|
||||||
|
|||||||
@@ -272,16 +272,28 @@
|
|||||||
<!-- 耗时 -->
|
<!-- 耗时 -->
|
||||||
<span
|
<span
|
||||||
v-if="getDisplayStatus(record) === 'pending' || getDisplayStatus(record) === 'streaming'"
|
v-if="getDisplayStatus(record) === 'pending' || getDisplayStatus(record) === 'streaming'"
|
||||||
class="text-primary tabular-nums"
|
class="tabular-nums whitespace-nowrap"
|
||||||
><ElapsedTimeText
|
>
|
||||||
:created-at="record.created_at"
|
<span>{{ formatRecordDurationSeconds(record.first_byte_time_ms) }}</span>
|
||||||
:status="getDisplayStatus(record)"
|
<span class="text-muted-foreground"> / </span>
|
||||||
:response-time-ms="record.response_time_ms ?? null"
|
<ElapsedTimeText
|
||||||
/></span>
|
class="text-primary"
|
||||||
|
:created-at="record.created_at"
|
||||||
|
:status="getDisplayStatus(record)"
|
||||||
|
:response-time-ms="record.response_time_ms ?? null"
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
<span
|
<span
|
||||||
v-else-if="record.response_time_ms != null || record.first_byte_time_ms != null"
|
v-else-if="record.response_time_ms != null || record.first_byte_time_ms != null"
|
||||||
class="tabular-nums"
|
class="flex flex-col items-end tabular-nums leading-3 shrink-0"
|
||||||
>{{ record.first_byte_time_ms != null ? (record.first_byte_time_ms / 1000).toFixed(1) + '/' : '' }}{{ record.response_time_ms != null ? (record.response_time_ms / 1000).toFixed(1) : '-' }}{{ record.response_time_ms != null ? 's' : '' }}</span>
|
:title="getRecordPerformanceTitle(record)"
|
||||||
|
>
|
||||||
|
<span class="whitespace-nowrap">{{ formatRecordLatencyPair(record) }}</span>
|
||||||
|
<span
|
||||||
|
v-if="getRecordDisplayOutputRate(record) != null"
|
||||||
|
class="text-muted-foreground tabular-nums whitespace-nowrap"
|
||||||
|
>{{ formatOutputRate(getRecordDisplayOutputRate(record)) }}</span>
|
||||||
|
</span>
|
||||||
<span
|
<span
|
||||||
v-else
|
v-else
|
||||||
class="tabular-nums"
|
class="tabular-nums"
|
||||||
@@ -310,12 +322,12 @@
|
|||||||
<colgroup v-else>
|
<colgroup v-else>
|
||||||
<col class="w-[9%]">
|
<col class="w-[9%]">
|
||||||
<col class="w-[17%]">
|
<col class="w-[17%]">
|
||||||
<col class="w-[26%]">
|
<col class="w-[24%]">
|
||||||
<col class="w-[15%]">
|
<col class="w-[15%]">
|
||||||
<col class="w-[7%]">
|
<col class="w-[7%]">
|
||||||
<col class="w-[11%]">
|
<col class="w-[11%]">
|
||||||
<col class="w-[7%]">
|
<col class="w-[7%]">
|
||||||
<col class="w-[8%]">
|
<col class="w-[10%]">
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow class="border-b border-border/60 hover:bg-transparent">
|
<TableRow class="border-b border-border/60 hover:bg-transparent">
|
||||||
@@ -429,8 +441,8 @@
|
|||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead class="h-12 font-semibold w-[9%] text-right">
|
<TableHead class="h-12 font-semibold w-[9%] text-right">
|
||||||
<div class="flex flex-col items-end text-xs gap-0.5">
|
<div class="flex flex-col items-end text-xs gap-0.5">
|
||||||
<span>首字</span>
|
<span class="whitespace-nowrap">首字/总耗时</span>
|
||||||
<span class="text-muted-foreground font-normal">总耗时</span>
|
<span class="text-muted-foreground font-normal">输出速度</span>
|
||||||
</div>
|
</div>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
@@ -716,58 +728,33 @@
|
|||||||
</div>
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell class="text-right py-4 w-[9%]">
|
<TableCell class="text-right py-4 w-[9%]">
|
||||||
<!-- pending 状态:只显示增长的总时间 -->
|
<!-- pending/streaming 状态:首字与动态总耗时保留在同一行 -->
|
||||||
<div
|
<div
|
||||||
v-if="getDisplayStatus(record) === 'pending'"
|
v-if="getDisplayStatus(record) === 'pending' || getDisplayStatus(record) === 'streaming'"
|
||||||
class="flex flex-col items-end text-xs gap-0.5"
|
class="flex flex-col items-end text-xs gap-0.5"
|
||||||
>
|
>
|
||||||
<span class="text-muted-foreground">-</span>
|
<span class="tabular-nums whitespace-nowrap">
|
||||||
<span class="text-primary tabular-nums"><ElapsedTimeText
|
<span>{{ formatRecordDurationSeconds(record.first_byte_time_ms) }}</span>
|
||||||
:created-at="record.created_at"
|
<span class="text-muted-foreground"> / </span>
|
||||||
:status="getDisplayStatus(record)"
|
<ElapsedTimeText
|
||||||
:response-time-ms="record.response_time_ms ?? null"
|
class="text-primary"
|
||||||
/></span>
|
:created-at="record.created_at"
|
||||||
</div>
|
:status="getDisplayStatus(record)"
|
||||||
<!-- streaming 状态:首字固定 + 总时间增长 -->
|
:response-time-ms="record.response_time_ms ?? null"
|
||||||
<div
|
/>
|
||||||
v-else-if="getDisplayStatus(record) === 'streaming'"
|
</span>
|
||||||
class="flex flex-col items-end text-xs gap-0.5"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
v-if="record.first_byte_time_ms != null"
|
|
||||||
class="tabular-nums"
|
|
||||||
>{{ (record.first_byte_time_ms / 1000).toFixed(2) }}s</span>
|
|
||||||
<span
|
|
||||||
v-else
|
|
||||||
class="text-muted-foreground"
|
|
||||||
>-</span>
|
|
||||||
<span class="text-primary tabular-nums"><ElapsedTimeText
|
|
||||||
:created-at="record.created_at"
|
|
||||||
:status="getDisplayStatus(record)"
|
|
||||||
:response-time-ms="record.response_time_ms ?? null"
|
|
||||||
/></span>
|
|
||||||
</div>
|
</div>
|
||||||
<!-- 已完成状态:首字 + 总耗时 -->
|
<!-- 已完成状态:首字 + 总耗时 -->
|
||||||
<div
|
<div
|
||||||
v-else-if="record.response_time_ms != null || record.first_byte_time_ms != null"
|
v-else-if="record.response_time_ms != null || record.first_byte_time_ms != null"
|
||||||
class="flex flex-col items-end text-xs gap-0.5"
|
class="flex flex-col items-end text-xs gap-0.5"
|
||||||
|
:title="getRecordPerformanceTitle(record)"
|
||||||
>
|
>
|
||||||
|
<span class="tabular-nums whitespace-nowrap">{{ formatRecordLatencyPair(record) }}</span>
|
||||||
<span
|
<span
|
||||||
v-if="record.first_byte_time_ms != null"
|
v-if="getRecordDisplayOutputRate(record) != null"
|
||||||
class="tabular-nums"
|
class="text-muted-foreground tabular-nums whitespace-nowrap"
|
||||||
>{{ (record.first_byte_time_ms / 1000).toFixed(2) }}s</span>
|
>{{ formatOutputRate(getRecordDisplayOutputRate(record)) }}</span>
|
||||||
<span
|
|
||||||
v-else
|
|
||||||
class="text-muted-foreground"
|
|
||||||
>-</span>
|
|
||||||
<span
|
|
||||||
v-if="record.response_time_ms != null"
|
|
||||||
class="text-muted-foreground tabular-nums"
|
|
||||||
>{{ (record.response_time_ms / 1000).toFixed(2) }}s</span>
|
|
||||||
<span
|
|
||||||
v-else
|
|
||||||
class="text-muted-foreground"
|
|
||||||
>-</span>
|
|
||||||
</div>
|
</div>
|
||||||
<span
|
<span
|
||||||
v-else
|
v-else
|
||||||
@@ -820,6 +807,12 @@ import {
|
|||||||
import { RefreshCcw, Search } from 'lucide-vue-next'
|
import { RefreshCcw, Search } from 'lucide-vue-next'
|
||||||
import { formatTokens, formatCurrency } from '@/utils/format'
|
import { formatTokens, formatCurrency } from '@/utils/format'
|
||||||
import { getCacheCreationTokens, getCacheReadTokens, getEffectiveInputTokens } from '../token-normalization'
|
import { getCacheCreationTokens, getCacheReadTokens, getEffectiveInputTokens } from '../token-normalization'
|
||||||
|
import {
|
||||||
|
formatOutputRate,
|
||||||
|
formatOutputRateValue,
|
||||||
|
getDisplayOutputRate,
|
||||||
|
getGenerationTimeMs,
|
||||||
|
} from '../performance'
|
||||||
import {
|
import {
|
||||||
formatUsageStreamLabel,
|
formatUsageStreamLabel,
|
||||||
isUsageRecordFailed,
|
isUsageRecordFailed,
|
||||||
@@ -1040,6 +1033,43 @@ function formatOptionalTokens(value: number | null | undefined): string {
|
|||||||
return hasPositiveTokens(value) ? formatTokens(value) : '-'
|
return hasPositiveTokens(value) ? formatTokens(value) : '-'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatRecordLatencyPair(record: UsageRecord): string {
|
||||||
|
const firstByte = formatRecordDurationSeconds(record.first_byte_time_ms)
|
||||||
|
const total = formatRecordDurationSeconds(record.response_time_ms)
|
||||||
|
return `${firstByte} / ${total}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRecordDurationSeconds(ms: number | null | undefined): string {
|
||||||
|
if (ms == null || !Number.isFinite(ms)) return '-'
|
||||||
|
return `${(ms / 1000).toFixed(2)}s`
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRecordDisplayOutputRate(record: UsageRecord): number | null {
|
||||||
|
return getDisplayOutputRate({
|
||||||
|
output_tokens: record.output_tokens,
|
||||||
|
response_time_ms: record.response_time_ms,
|
||||||
|
first_byte_time_ms: record.first_byte_time_ms,
|
||||||
|
is_stream: record.is_stream,
|
||||||
|
upstream_is_stream: record.upstream_is_stream,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRecordPerformanceTitle(record: UsageRecord): string {
|
||||||
|
const outputRate = getRecordDisplayOutputRate(record)
|
||||||
|
return [
|
||||||
|
`首字: ${formatRecordDurationSeconds(record.first_byte_time_ms)}`,
|
||||||
|
`总耗时: ${formatRecordDurationSeconds(record.response_time_ms)}`,
|
||||||
|
`生成耗时: ${formatRecordDurationSeconds(getGenerationTimeMs(record))}`,
|
||||||
|
`输出速度: ${formatOutputRateTokensPerSecond(outputRate)}`,
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatOutputRateTokensPerSecond(outputRate: number | null | undefined): string {
|
||||||
|
const value = formatOutputRateValue(outputRate)
|
||||||
|
if (value === '-') return value
|
||||||
|
return `${value} tokens/s`
|
||||||
|
}
|
||||||
|
|
||||||
// useDebounceFn 自动处理清理,无需 onUnmounted
|
// useDebounceFn 自动处理清理,无需 onUnmounted
|
||||||
|
|
||||||
// 判断是否应该显示格式转换信息
|
// 判断是否应该显示格式转换信息
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { createApp, defineComponent, h, type App } from 'vue'
|
||||||
|
import UsageRecordsTable from '../UsageRecordsTable.vue'
|
||||||
|
import type { UsageRecord } from '../../types'
|
||||||
|
|
||||||
|
vi.mock('@/components/ui', async () => {
|
||||||
|
const { defineComponent, h } = await import('vue')
|
||||||
|
|
||||||
|
const passthrough = (name: string, tag = 'div') => defineComponent({
|
||||||
|
name,
|
||||||
|
setup(_, { slots }) {
|
||||||
|
return () => h(tag, [
|
||||||
|
slots.default?.(),
|
||||||
|
slots.actions?.(),
|
||||||
|
slots.pagination?.(),
|
||||||
|
slots.filter?.({ close: () => undefined }),
|
||||||
|
])
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
TableCard: passthrough('TableCardStub', 'section'),
|
||||||
|
Badge: passthrough('BadgeStub', 'span'),
|
||||||
|
Button: passthrough('ButtonStub', 'button'),
|
||||||
|
Input: defineComponent({
|
||||||
|
name: 'InputStub',
|
||||||
|
props: { modelValue: String },
|
||||||
|
emits: ['update:modelValue'],
|
||||||
|
setup(props, { attrs, emit }) {
|
||||||
|
return () => h('input', {
|
||||||
|
...attrs,
|
||||||
|
value: props.modelValue ?? '',
|
||||||
|
onInput: (event: Event) => emit('update:modelValue', (event.target as HTMLInputElement).value),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
Select: passthrough('SelectStub'),
|
||||||
|
SelectTrigger: passthrough('SelectTriggerStub'),
|
||||||
|
SelectValue: passthrough('SelectValueStub', 'span'),
|
||||||
|
SelectContent: passthrough('SelectContentStub'),
|
||||||
|
SelectItem: passthrough('SelectItemStub'),
|
||||||
|
Table: passthrough('TableStub', 'table'),
|
||||||
|
TableHeader: passthrough('TableHeaderStub', 'thead'),
|
||||||
|
TableBody: passthrough('TableBodyStub', 'tbody'),
|
||||||
|
TableRow: passthrough('TableRowStub', 'tr'),
|
||||||
|
TableHead: passthrough('TableHeadStub', 'th'),
|
||||||
|
TableCell: passthrough('TableCellStub', 'td'),
|
||||||
|
Pagination: passthrough('PaginationStub'),
|
||||||
|
SortableTableHead: passthrough('SortableTableHeadStub', 'th'),
|
||||||
|
TableFilterMenu: passthrough('TableFilterMenuStub'),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/components/common', async () => {
|
||||||
|
const { defineComponent, h } = await import('vue')
|
||||||
|
|
||||||
|
return {
|
||||||
|
TimeRangePicker: defineComponent({
|
||||||
|
name: 'TimeRangePickerStub',
|
||||||
|
setup() {
|
||||||
|
return () => h('div')
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('lucide-vue-next', async () => {
|
||||||
|
const { defineComponent, h } = await import('vue')
|
||||||
|
const Icon = defineComponent({
|
||||||
|
name: 'IconStub',
|
||||||
|
setup() {
|
||||||
|
return () => h('span')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
RefreshCcw: Icon,
|
||||||
|
Search: Icon,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('../ElapsedTimeText.vue', () => ({
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'ElapsedTimeTextStub',
|
||||||
|
setup() {
|
||||||
|
return () => h('span', 'elapsed')
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
|
||||||
|
|
||||||
|
function buildRecord(overrides: Partial<UsageRecord> = {}): UsageRecord {
|
||||||
|
return {
|
||||||
|
id: 'usage-1',
|
||||||
|
model: 'gpt-5',
|
||||||
|
input_tokens: 100,
|
||||||
|
output_tokens: 50,
|
||||||
|
total_tokens: 150,
|
||||||
|
cost: 0.01,
|
||||||
|
response_time_ms: 1000,
|
||||||
|
first_byte_time_ms: 500,
|
||||||
|
is_stream: true,
|
||||||
|
upstream_is_stream: true,
|
||||||
|
status: 'completed',
|
||||||
|
created_at: '2026-05-06T12:00:00Z',
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountUsageRecordsTable(records: UsageRecord[], overrides: Record<string, unknown> = {}) {
|
||||||
|
const root = document.createElement('div')
|
||||||
|
document.body.appendChild(root)
|
||||||
|
|
||||||
|
const app = createApp(UsageRecordsTable, {
|
||||||
|
records,
|
||||||
|
isAdmin: true,
|
||||||
|
showActualCost: false,
|
||||||
|
loading: false,
|
||||||
|
timeRange: { preset: 'today', tz_offset_minutes: 0 },
|
||||||
|
filterSearch: '',
|
||||||
|
filterUser: '__all__',
|
||||||
|
filterModel: '__all__',
|
||||||
|
filterProvider: '__all__',
|
||||||
|
filterApiFormat: '__all__',
|
||||||
|
filterStatus: '__all__',
|
||||||
|
availableUsers: [],
|
||||||
|
availableModels: [],
|
||||||
|
availableProviders: [],
|
||||||
|
currentPage: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
totalRecords: records.length,
|
||||||
|
pageSizeOptions: [20, 50],
|
||||||
|
autoRefresh: false,
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
|
||||||
|
app.mount(root)
|
||||||
|
mountedApps.push({ app, root })
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const { app, root } of mountedApps.splice(0)) {
|
||||||
|
app.unmount()
|
||||||
|
root.remove()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('UsageRecordsTable', () => {
|
||||||
|
it('shows output TPS after the request completes', () => {
|
||||||
|
const root = mountUsageRecordsTable([buildRecord()])
|
||||||
|
|
||||||
|
expect(root.textContent).toContain('输出速度')
|
||||||
|
expect(root.textContent).toContain('0.50s / 1.00s')
|
||||||
|
expect(root.textContent).not.toContain('500ms')
|
||||||
|
expect(root.textContent).toContain('100 tps')
|
||||||
|
expect([...root.querySelectorAll<HTMLElement>('.text-muted-foreground')]
|
||||||
|
.some((element) => element.textContent?.includes('100 tps'))).toBe(true)
|
||||||
|
const tpsElements = [...root.querySelectorAll<HTMLElement>('.text-muted-foreground')]
|
||||||
|
.filter((element) => element.textContent?.trim() === '100 tps')
|
||||||
|
expect(tpsElements.some((element) => element.classList.contains('text-[11px]'))).toBe(false)
|
||||||
|
|
||||||
|
const titles = [...root.querySelectorAll<HTMLElement>('[title]')].map((element) => element.title)
|
||||||
|
expect(titles).toContain([
|
||||||
|
'首字: 0.50s',
|
||||||
|
'总耗时: 1.00s',
|
||||||
|
'生成耗时: 0.50s',
|
||||||
|
'输出速度: 100 tokens/s',
|
||||||
|
].join('\n'))
|
||||||
|
expect(titles.join('\n')).not.toContain('500ms')
|
||||||
|
expect(titles.join('\n')).not.toContain('首字后生成耗时')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps active request latency in one first-byte / live-total line without TPS', () => {
|
||||||
|
const root = mountUsageRecordsTable([buildRecord({
|
||||||
|
status: 'streaming',
|
||||||
|
response_time_ms: null,
|
||||||
|
first_byte_time_ms: 500,
|
||||||
|
})])
|
||||||
|
|
||||||
|
expect(root.textContent).toContain('0.50s')
|
||||||
|
expect(root.textContent).toContain('elapsed')
|
||||||
|
expect(root.textContent).toContain('0.50s / elapsed')
|
||||||
|
expect(root.textContent).not.toContain('100 tps')
|
||||||
|
expect(root.textContent).not.toContain('生成中')
|
||||||
|
expect(root.textContent).not.toContain('等待首字')
|
||||||
|
expect(root.querySelector('[data-active-latency-state="streaming"]')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses a first-byte placeholder and live total before the first byte arrives', () => {
|
||||||
|
const root = mountUsageRecordsTable([buildRecord({
|
||||||
|
status: 'pending',
|
||||||
|
response_time_ms: null,
|
||||||
|
first_byte_time_ms: null,
|
||||||
|
})])
|
||||||
|
|
||||||
|
expect(root.textContent).toContain('- / elapsed')
|
||||||
|
expect(root.textContent).toContain('elapsed')
|
||||||
|
expect(root.textContent).not.toContain('等待首字')
|
||||||
|
expect(root.querySelector('[data-active-latency-state="waiting-first-byte"]')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders output TPS in the non-admin usage table', () => {
|
||||||
|
const root = mountUsageRecordsTable([buildRecord()], { isAdmin: false })
|
||||||
|
|
||||||
|
expect(root.textContent).toContain('100 tps')
|
||||||
|
expect(root.textContent).toContain('0.50s / 1.00s')
|
||||||
|
expect(root.textContent).toContain('gpt-5')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -189,6 +189,31 @@ function getGeminiCliQuotaText(quota: QuotaStatusSnapshot): string | null {
|
|||||||
return `最低剩余 ${formatPercent(minimumRemaining)} (${remainingList.length} 模型)`
|
return `最低剩余 ${formatPercent(minimumRemaining)} (${remainingList.length} 模型)`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getChatGPTWebQuotaText(quota: QuotaStatusSnapshot): string | null {
|
||||||
|
const window = getQuotaWindow(quota, 'image_gen') ?? getQuotaWindowsByScope(quota, 'account')[0] ?? null
|
||||||
|
if (!window) return normalizeText(quota.label)
|
||||||
|
|
||||||
|
const remainingPercent = getQuotaWindowRemainingPercent(window)
|
||||||
|
if (typeof window.remaining_value === 'number' && typeof window.limit_value === 'number' && window.limit_value > 0 && window.remaining_value <= 0) {
|
||||||
|
return `生图剩余 ${formatQuotaValue(window.remaining_value)}/${formatQuotaValue(window.limit_value)}`
|
||||||
|
}
|
||||||
|
if (remainingPercent != null) {
|
||||||
|
if (typeof window.used_value === 'number' && typeof window.limit_value === 'number' && window.limit_value > 0) {
|
||||||
|
return `生图剩余 ${formatPercent(remainingPercent)} (${formatQuotaValue(window.used_value)}/${formatQuotaValue(window.limit_value)})`
|
||||||
|
}
|
||||||
|
return `生图剩余 ${formatPercent(remainingPercent)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window.remaining_value === 'number' && typeof window.limit_value === 'number' && window.limit_value > 0) {
|
||||||
|
return `生图剩余 ${formatQuotaValue(window.remaining_value)}/${formatQuotaValue(window.limit_value)}`
|
||||||
|
}
|
||||||
|
if (typeof window.remaining_value === 'number') {
|
||||||
|
return `生图剩余 ${formatQuotaValue(window.remaining_value)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizeText(quota.label)
|
||||||
|
}
|
||||||
|
|
||||||
export function getLegacyAccountQuotaText(
|
export function getLegacyAccountQuotaText(
|
||||||
input: ProviderKeyQuotaCarrier,
|
input: ProviderKeyQuotaCarrier,
|
||||||
): string | null {
|
): string | null {
|
||||||
@@ -212,6 +237,8 @@ export function getQuotaSnapshotFallbackText(
|
|||||||
return getAntigravityQuotaText(quota)
|
return getAntigravityQuotaText(quota)
|
||||||
case 'gemini_cli':
|
case 'gemini_cli':
|
||||||
return getGeminiCliQuotaText(quota)
|
return getGeminiCliQuotaText(quota)
|
||||||
|
case 'chatgpt_web':
|
||||||
|
return getChatGPTWebQuotaText(quota)
|
||||||
default:
|
default:
|
||||||
return normalizeText(quota.label)
|
return normalizeText(quota.label)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,6 +76,34 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="showCodexStatsModeSwitch"
|
||||||
|
class="flex items-center"
|
||||||
|
data-testid="pool-mobile-header-actions"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="group inline-flex min-h-12 flex-col items-center justify-center gap-1 rounded-md border border-border/50 bg-muted/20 px-2.5 py-1.5 text-xs transition-all duration-200 hover:border-primary/40 hover:bg-muted/40"
|
||||||
|
data-testid="pool-stats-mode-control"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-1 leading-none">
|
||||||
|
<span
|
||||||
|
class="font-medium transition-colors"
|
||||||
|
:class="!codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||||
|
>累计</span>
|
||||||
|
<span class="text-muted-foreground/50 transition-colors group-hover:text-muted-foreground/80">/</span>
|
||||||
|
<span
|
||||||
|
class="font-medium transition-colors"
|
||||||
|
:class="codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||||
|
>周期</span>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
v-model="codexCurrentCycleStatsEnabled"
|
||||||
|
class="shrink-0"
|
||||||
|
aria-label="Codex 统计模式"
|
||||||
|
data-testid="pool-stats-mode-switch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="selectedProviderId"
|
v-if="selectedProviderId"
|
||||||
class="flex items-center gap-1"
|
class="flex items-center gap-1"
|
||||||
@@ -171,7 +199,10 @@
|
|||||||
</span>
|
</span>
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2">
|
<div
|
||||||
|
class="flex items-center gap-2"
|
||||||
|
data-testid="pool-header-actions"
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
v-model="selectedProviderIdProxy"
|
v-model="selectedProviderIdProxy"
|
||||||
:disabled="providerSelectDisabled"
|
:disabled="providerSelectDisabled"
|
||||||
@@ -228,6 +259,33 @@
|
|||||||
v-if="selectedProviderId"
|
v-if="selectedProviderId"
|
||||||
class="h-4 w-px bg-border"
|
class="h-4 w-px bg-border"
|
||||||
/>
|
/>
|
||||||
|
<div
|
||||||
|
v-if="showCodexStatsModeSwitch"
|
||||||
|
class="group inline-flex min-h-12 flex-col items-center justify-center gap-1 rounded-md border border-border/50 bg-muted/20 px-2.5 py-1.5 text-xs transition-all duration-200 hover:border-primary/40 hover:bg-muted/40"
|
||||||
|
data-testid="pool-stats-mode-control"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-1 leading-none">
|
||||||
|
<span
|
||||||
|
class="font-medium transition-colors"
|
||||||
|
:class="!codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||||
|
>累计</span>
|
||||||
|
<span class="text-muted-foreground/50 transition-colors group-hover:text-muted-foreground/80">/</span>
|
||||||
|
<span
|
||||||
|
class="font-medium transition-colors"
|
||||||
|
:class="codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||||
|
>周期</span>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
v-model="codexCurrentCycleStatsEnabled"
|
||||||
|
class="shrink-0"
|
||||||
|
aria-label="Codex 统计模式"
|
||||||
|
data-testid="pool-stats-mode-switch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="showCodexStatsModeSwitch"
|
||||||
|
class="h-4 w-px bg-border"
|
||||||
|
/>
|
||||||
<Button
|
<Button
|
||||||
v-if="selectedProviderId"
|
v-if="selectedProviderId"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -571,23 +629,44 @@
|
|||||||
>-</span>
|
>-</span>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell class="py-3 px-2 align-middle">
|
<TableCell class="py-3 px-2 align-middle">
|
||||||
<div class="grid grid-rows-3 gap-0.5 w-[136px] mx-auto text-[10px] leading-4">
|
<div
|
||||||
<div class="flex items-center justify-between gap-2">
|
v-if="isPoolKeyCycleStatsDisplay(key)"
|
||||||
<span class="text-muted-foreground">请求</span>
|
class="mx-auto w-[136px] space-y-1.5 text-[10px] leading-4"
|
||||||
<span class="tabular-nums text-foreground/90">
|
data-testid="pool-stats-cycle-groups"
|
||||||
{{ formatStatInteger(key.request_count) }}
|
>
|
||||||
</span>
|
<div
|
||||||
|
v-for="group in getPoolKeyCycleStatsGroups(key)"
|
||||||
|
:key="`${key.key_id}-${group.code}-desktop-stats`"
|
||||||
|
:data-testid="`pool-stats-cycle-group-${group.code}`"
|
||||||
|
>
|
||||||
|
<div class="text-[9px] text-muted-foreground/70 font-medium mb-0.5">{{ group.label }}</div>
|
||||||
|
<div
|
||||||
|
v-for="metric in group.metrics"
|
||||||
|
:key="`${group.code}-${metric.key}`"
|
||||||
|
class="flex items-center justify-between gap-2"
|
||||||
|
>
|
||||||
|
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||||
|
<span
|
||||||
|
class="tabular-nums text-foreground/90"
|
||||||
|
:class="metric.missing ? 'text-muted-foreground/80' : ''"
|
||||||
|
:data-testid="`pool-stats-${group.code}-${metric.key}`"
|
||||||
|
>{{ metric.value }}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center justify-between gap-2">
|
</div>
|
||||||
<span class="text-muted-foreground">Token</span>
|
<div
|
||||||
|
v-else
|
||||||
|
class="grid grid-rows-3 gap-0.5 w-[136px] mx-auto text-[10px] leading-4"
|
||||||
|
data-testid="pool-stats-account-total"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-for="metric in getPoolKeyAccountStatsMetrics(key)"
|
||||||
|
:key="`${key.key_id}-${metric.key}-account-total`"
|
||||||
|
class="flex items-center justify-between gap-2"
|
||||||
|
>
|
||||||
|
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||||
<span class="tabular-nums text-foreground/90">
|
<span class="tabular-nums text-foreground/90">
|
||||||
{{ formatTokenCount(key.total_tokens) }}
|
{{ metric.value }}
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center justify-between gap-2">
|
|
||||||
<span class="text-muted-foreground">费用</span>
|
|
||||||
<span class="tabular-nums text-foreground/90">
|
|
||||||
{{ formatStatUsd(key.total_cost_usd) }}
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -787,16 +866,48 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="overflow-x-auto rounded-xl border border-border/50 bg-muted/30 px-3 py-2 text-[11px] text-muted-foreground">
|
<div class="overflow-x-auto rounded-xl border border-border/50 bg-muted/30 px-3 py-2 text-[11px] text-muted-foreground">
|
||||||
<div class="flex min-w-max items-center justify-center whitespace-nowrap text-center">
|
<div class="space-y-1 text-center">
|
||||||
<span class="font-medium text-foreground/90">请求:{{ formatStatInteger(key.request_count) }}</span>
|
<template v-if="isPoolKeyCycleStatsDisplay(key)">
|
||||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
<div
|
||||||
<span class="font-medium text-foreground/90">Token:{{ formatTokenCount(key.total_tokens) }}</span>
|
v-for="group in getPoolKeyCycleStatsGroups(key)"
|
||||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
:key="`${key.key_id}-${group.code}-mobile-stats`"
|
||||||
<span class="font-medium text-foreground/90">费用:{{ formatStatUsd(key.total_cost_usd) }}</span>
|
class="flex items-start gap-3 text-left"
|
||||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
:data-testid="`pool-mobile-stats-cycle-group-${group.code}`"
|
||||||
<span class="font-medium text-foreground/90">导入:{{ keyUiStateMap[key.key_id]?.importedAtRelative || '-' }}</span>
|
>
|
||||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
<span class="w-10 shrink-0 pt-0.5 text-[10px] font-semibold text-foreground">{{ group.label }}</span>
|
||||||
<span class="font-medium text-foreground/90">最后使用:{{ keyUiStateMap[key.key_id]?.lastUsedRelative || '-' }}</span>
|
<div class="min-w-0 flex-1 space-y-0.5">
|
||||||
|
<div
|
||||||
|
v-for="metric in group.metrics"
|
||||||
|
:key="`${group.code}-${metric.key}-mobile`"
|
||||||
|
class="flex items-center justify-between gap-2"
|
||||||
|
>
|
||||||
|
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||||
|
<span
|
||||||
|
class="font-medium text-foreground/90 tabular-nums"
|
||||||
|
:class="metric.missing ? 'text-muted-foreground/80' : ''"
|
||||||
|
>{{ metric.value }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<div
|
||||||
|
v-for="metric in getPoolKeyAccountStatsMetrics(key)"
|
||||||
|
:key="`${key.key_id}-${metric.key}-mobile-account-total`"
|
||||||
|
class="flex items-center justify-between gap-2"
|
||||||
|
>
|
||||||
|
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||||
|
<span class="font-medium text-foreground/90">{{ metric.value }}</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div class="flex items-center justify-between gap-2 border-t border-border/40 pt-1 mt-1">
|
||||||
|
<span class="text-muted-foreground">导入</span>
|
||||||
|
<span class="font-medium text-foreground/90">{{ keyUiStateMap[key.key_id]?.importedAtRelative || '-' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<span class="text-muted-foreground">最后使用</span>
|
||||||
|
<span class="font-medium text-foreground/90">{{ keyUiStateMap[key.key_id]?.lastUsedRelative || '-' }}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1146,6 +1257,7 @@ import {
|
|||||||
SortableTableHead,
|
SortableTableHead,
|
||||||
TableFilterMenu,
|
TableFilterMenu,
|
||||||
TableCell,
|
TableCell,
|
||||||
|
Switch,
|
||||||
Pagination,
|
Pagination,
|
||||||
Popover,
|
Popover,
|
||||||
PopoverTrigger,
|
PopoverTrigger,
|
||||||
@@ -1209,9 +1321,16 @@ import {
|
|||||||
resolvePoolManagementPageAfterLoad,
|
resolvePoolManagementPageAfterLoad,
|
||||||
type PoolManagementSortBy,
|
type PoolManagementSortBy,
|
||||||
type PoolManagementSortOrder,
|
type PoolManagementSortOrder,
|
||||||
|
type PoolManagementStatsMode,
|
||||||
type PoolManagementViewState,
|
type PoolManagementViewState,
|
||||||
writePoolManagementViewState,
|
writePoolManagementViewState,
|
||||||
} from '@/features/pool/utils/poolManagementState'
|
} from '@/features/pool/utils/poolManagementState'
|
||||||
|
import {
|
||||||
|
buildPoolStatsDisplay,
|
||||||
|
type PoolCodexCycleStatsGroup,
|
||||||
|
type PoolStatsDisplay,
|
||||||
|
type PoolStatsMetric,
|
||||||
|
} from '@/features/pool/utils/poolStatsDisplay'
|
||||||
import { getOAuthOrgBadge } from '@/utils/oauthIdentity'
|
import { getOAuthOrgBadge } from '@/utils/oauthIdentity'
|
||||||
import { getOAuthRefreshFeedback } from '@/utils/oauthRefreshFeedback'
|
import { getOAuthRefreshFeedback } from '@/utils/oauthRefreshFeedback'
|
||||||
import {
|
import {
|
||||||
@@ -1253,6 +1372,7 @@ const restoredViewState = readPoolManagementViewState(
|
|||||||
pageSize: getQueryValue('pageSize'),
|
pageSize: getQueryValue('pageSize'),
|
||||||
sortBy: getQueryValue('sortBy'),
|
sortBy: getQueryValue('sortBy'),
|
||||||
sortOrder: getQueryValue('sortOrder'),
|
sortOrder: getQueryValue('sortOrder'),
|
||||||
|
statsMode: getQueryValue('statsMode'),
|
||||||
},
|
},
|
||||||
poolManagementViewStorage,
|
poolManagementViewStorage,
|
||||||
)
|
)
|
||||||
@@ -1476,6 +1596,14 @@ const selectedProviderType = computed(() => {
|
|||||||
return String(fromOverview || '').trim().toLowerCase()
|
return String(fromOverview || '').trim().toLowerCase()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const showCodexStatsModeSwitch = computed(() => selectedProviderType.value === 'codex')
|
||||||
|
const codexCurrentCycleStatsEnabled = computed({
|
||||||
|
get: () => poolStatsMode.value === 'current_cycle',
|
||||||
|
set: (enabled: boolean) => {
|
||||||
|
poolStatsMode.value = enabled ? 'current_cycle' : 'account_total'
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const selectedProviderStatusText = computed(() => {
|
const selectedProviderStatusText = computed(() => {
|
||||||
if (!selectedProviderId.value) return ''
|
if (!selectedProviderId.value) return ''
|
||||||
const providerActive = selectedProviderData.value?.is_active
|
const providerActive = selectedProviderData.value?.is_active
|
||||||
@@ -1498,6 +1626,7 @@ const showAccountQuotaColumn = computed(() => {
|
|||||||
|| selectedProviderType.value === 'gemini_cli'
|
|| selectedProviderType.value === 'gemini_cli'
|
||||||
|| selectedProviderType.value === 'kiro'
|
|| selectedProviderType.value === 'kiro'
|
||||||
|| selectedProviderType.value === 'antigravity'
|
|| selectedProviderType.value === 'antigravity'
|
||||||
|
|| selectedProviderType.value === 'chatgpt_web'
|
||||||
})
|
})
|
||||||
|
|
||||||
const desktopColumnWidths = computed(() => {
|
const desktopColumnWidths = computed(() => {
|
||||||
@@ -1599,6 +1728,7 @@ const currentPage = ref(restoredViewState.page)
|
|||||||
const pageSize = ref(restoredViewState.pageSize)
|
const pageSize = ref(restoredViewState.pageSize)
|
||||||
const sortBy = ref<PoolManagementSortBy | null>(restoredViewState.sortBy)
|
const sortBy = ref<PoolManagementSortBy | null>(restoredViewState.sortBy)
|
||||||
const sortOrder = ref<PoolManagementSortOrder>(restoredViewState.sortOrder)
|
const sortOrder = ref<PoolManagementSortOrder>(restoredViewState.sortOrder)
|
||||||
|
const poolStatsMode = ref<PoolManagementStatsMode>(restoredViewState.statsMode)
|
||||||
const hasPoolKeyFilters = computed(() => searchQuery.value.trim().length > 0 || statusFilter.value !== 'all')
|
const hasPoolKeyFilters = computed(() => searchQuery.value.trim().length > 0 || statusFilter.value !== 'all')
|
||||||
const MANUAL_QUOTA_REFRESH_COOLDOWN_SECONDS = 5 * 60
|
const MANUAL_QUOTA_REFRESH_COOLDOWN_SECONDS = 5 * 60
|
||||||
const refreshingOAuthKeyId = ref<string | null>(null)
|
const refreshingOAuthKeyId = ref<string | null>(null)
|
||||||
@@ -1680,6 +1810,18 @@ watch(
|
|||||||
{ immediate: true },
|
{ immediate: true },
|
||||||
)
|
)
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => readPoolManagementViewState(
|
||||||
|
{ statsMode: getQueryValue('statsMode') },
|
||||||
|
poolManagementViewStorage,
|
||||||
|
).statsMode,
|
||||||
|
(value) => {
|
||||||
|
if (poolStatsMode.value === value) return
|
||||||
|
poolStatsMode.value = value
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
)
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => getQueryValue('providerId'),
|
() => getQueryValue('providerId'),
|
||||||
(value) => {
|
(value) => {
|
||||||
@@ -1696,8 +1838,8 @@ watch(
|
|||||||
)
|
)
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
[selectedProviderId, searchQuery, statusFilter, currentPage, pageSize, sortBy, sortOrder],
|
[selectedProviderId, searchQuery, statusFilter, currentPage, pageSize, sortBy, sortOrder, poolStatsMode],
|
||||||
([providerId, search, status, page, pageSizeValue, sortByValue, sortOrderValue]) => {
|
([providerId, search, status, page, pageSizeValue, sortByValue, sortOrderValue, statsMode]) => {
|
||||||
const nextState: PoolManagementViewState = {
|
const nextState: PoolManagementViewState = {
|
||||||
providerId,
|
providerId,
|
||||||
search,
|
search,
|
||||||
@@ -1706,6 +1848,7 @@ watch(
|
|||||||
pageSize: pageSizeValue,
|
pageSize: pageSizeValue,
|
||||||
sortBy: sortByValue,
|
sortBy: sortByValue,
|
||||||
sortOrder: sortOrderValue,
|
sortOrder: sortOrderValue,
|
||||||
|
statsMode: statsMode as PoolManagementStatsMode,
|
||||||
}
|
}
|
||||||
patchQuery(buildPoolManagementQueryPatch(nextState))
|
patchQuery(buildPoolManagementQueryPatch(nextState))
|
||||||
writePoolManagementViewState(nextState, poolManagementViewStorage)
|
writePoolManagementViewState(nextState, poolManagementViewStorage)
|
||||||
@@ -1738,6 +1881,7 @@ type PoolKeyUiState = {
|
|||||||
quotaTextClass: string
|
quotaTextClass: string
|
||||||
importedAtRelative: string
|
importedAtRelative: string
|
||||||
lastUsedRelative: string
|
lastUsedRelative: string
|
||||||
|
statsDisplay: PoolStatsDisplay
|
||||||
mobileTagItems: PoolMobileTagItem[]
|
mobileTagItems: PoolMobileTagItem[]
|
||||||
mobileActionIds: PoolMobileActionId[]
|
mobileActionIds: PoolMobileActionId[]
|
||||||
}
|
}
|
||||||
@@ -1777,6 +1921,7 @@ const keyUiStateMap = computed<Record<string, PoolKeyUiState>>(() => {
|
|||||||
quotaTextClass: quotaFallbackText ? getQuotaTextClass(quotaFallbackText) : '',
|
quotaTextClass: quotaFallbackText ? getQuotaTextClass(quotaFallbackText) : '',
|
||||||
importedAtRelative: formatPoolKeyImportedAt(key),
|
importedAtRelative: formatPoolKeyImportedAt(key),
|
||||||
lastUsedRelative: key.last_used_at ? formatRelativeTime(key.last_used_at) : '-',
|
lastUsedRelative: key.last_used_at ? formatRelativeTime(key.last_used_at) : '-',
|
||||||
|
statsDisplay: buildPoolStatsDisplay(key, selectedProviderType.value, poolStatsMode.value),
|
||||||
mobileTagItems: getMobileTagItems(key),
|
mobileTagItems: getMobileTagItems(key),
|
||||||
mobileActionIds: splitPoolMobileActions({
|
mobileActionIds: splitPoolMobileActions({
|
||||||
canDownloadOrCopy: true,
|
canDownloadOrCopy: true,
|
||||||
@@ -1790,10 +1935,32 @@ const keyUiStateMap = computed<Record<string, PoolKeyUiState>>(() => {
|
|||||||
return map
|
return map
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function getPoolKeyStatsDisplay(key: PoolKeyDetail): PoolStatsDisplay {
|
||||||
|
return keyUiStateMap.value[key.key_id]?.statsDisplay
|
||||||
|
?? buildPoolStatsDisplay(key, selectedProviderType.value, poolStatsMode.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPoolKeyCycleStatsDisplay(key: PoolKeyDetail): boolean {
|
||||||
|
return getPoolKeyStatsDisplay(key).kind === 'codex_cycle'
|
||||||
|
}
|
||||||
|
|
||||||
|
function getPoolKeyCycleStatsGroups(key: PoolKeyDetail): PoolCodexCycleStatsGroup[] {
|
||||||
|
const display = getPoolKeyStatsDisplay(key)
|
||||||
|
return display.kind === 'codex_cycle' ? display.groups : []
|
||||||
|
}
|
||||||
|
|
||||||
|
function getPoolKeyAccountStatsMetrics(key: PoolKeyDetail): PoolStatsMetric[] {
|
||||||
|
const display = getPoolKeyStatsDisplay(key)
|
||||||
|
return display.kind === 'account_total'
|
||||||
|
? display.metrics
|
||||||
|
: buildPoolStatsDisplay(key, selectedProviderType.value, 'account_total').metrics
|
||||||
|
}
|
||||||
|
|
||||||
const quotaRefreshSupported = computed(() => {
|
const quotaRefreshSupported = computed(() => {
|
||||||
return selectedProviderType.value === 'codex'
|
return selectedProviderType.value === 'codex'
|
||||||
|| selectedProviderType.value === 'kiro'
|
|| selectedProviderType.value === 'kiro'
|
||||||
|| selectedProviderType.value === 'antigravity'
|
|| selectedProviderType.value === 'antigravity'
|
||||||
|
|| selectedProviderType.value === 'chatgpt_web'
|
||||||
})
|
})
|
||||||
|
|
||||||
const refreshCurrentPageLoading = computed(() => {
|
const refreshCurrentPageLoading = computed(() => {
|
||||||
@@ -2875,6 +3042,7 @@ function getQuotaLabelOrder(label: string): number {
|
|||||||
if (label === '周') return 1
|
if (label === '周') return 1
|
||||||
if (label === '剩余') return 2
|
if (label === '剩余') return 2
|
||||||
if (label === '最低') return 3
|
if (label === '最低') return 3
|
||||||
|
if (label === '生图') return 4
|
||||||
return 10
|
return 10
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3062,6 +3230,34 @@ function buildQuotaProgressItemsFromSnapshot(key: PoolKeyDetail): QuotaProgressI
|
|||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (providerType === 'chatgpt_web') {
|
||||||
|
const window = getQuotaSnapshotWindow(quota, 'image_gen')
|
||||||
|
?? getQuotaSnapshotWindowsByScope(quota, 'account')[0]
|
||||||
|
?? null
|
||||||
|
const remainingPercent = getQuotaWindowRemainingPercent(window)
|
||||||
|
if (remainingPercent == null) return []
|
||||||
|
|
||||||
|
const remainingValue = typeof window?.remaining_value === 'number' ? window.remaining_value : null
|
||||||
|
const limitValue = typeof window?.limit_value === 'number' ? window.limit_value : null
|
||||||
|
const usedValue = typeof window?.used_value === 'number' ? window.used_value : null
|
||||||
|
const detail = usedValue != null && limitValue != null
|
||||||
|
? `${formatQuotaValue(usedValue)}/${formatQuotaValue(limitValue)}`
|
||||||
|
: remainingValue != null && limitValue != null
|
||||||
|
? `${formatQuotaValue(Math.max(limitValue - remainingValue, 0))}/${formatQuotaValue(limitValue)}`
|
||||||
|
: remainingValue != null
|
||||||
|
? `剩余 ${formatQuotaValue(remainingValue)}`
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
return [{
|
||||||
|
label: '生图',
|
||||||
|
remainingPercent,
|
||||||
|
detail,
|
||||||
|
resetAtSeconds: normalizeUnixSeconds(window?.reset_at ?? null),
|
||||||
|
resetSeconds: normalizeRemainingSeconds(window?.reset_seconds ?? null),
|
||||||
|
updatedAtSeconds: getQuotaSnapshotUpdatedAtSeconds(quota),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,599 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { createApp, nextTick, type App } from 'vue'
|
||||||
|
|
||||||
|
import PoolManagement from '@/views/admin/PoolManagement.vue'
|
||||||
|
import type { PoolKeyDetail, PoolOverviewItem, PoolKeysPageResponse } from '@/api/endpoints/pool'
|
||||||
|
import { POOL_MANAGEMENT_VIEW_STORAGE_KEY } from '@/features/pool/utils/poolManagementState'
|
||||||
|
|
||||||
|
const endpointMocks = vi.hoisted(() => ({
|
||||||
|
getPoolOverview: vi.fn(),
|
||||||
|
getPoolSchedulingPresets: vi.fn(),
|
||||||
|
listPoolKeys: vi.fn(),
|
||||||
|
clearPoolCooldown: vi.fn(),
|
||||||
|
getProvider: vi.fn(),
|
||||||
|
updateProvider: vi.fn(),
|
||||||
|
revealEndpointKey: vi.fn(),
|
||||||
|
exportKey: vi.fn(),
|
||||||
|
deleteEndpointKey: vi.fn(),
|
||||||
|
updateProviderKey: vi.fn(),
|
||||||
|
refreshProviderQuota: vi.fn(),
|
||||||
|
refreshProviderOAuth: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const routeMocks = vi.hoisted(() => ({
|
||||||
|
query: {} as Record<string, string>,
|
||||||
|
patchQuery: vi.fn((patch: Record<string, string | undefined | null>) => {
|
||||||
|
for (const [key, value] of Object.entries(patch)) {
|
||||||
|
if (value == null || String(value).trim() === '') {
|
||||||
|
delete routeMocks.query[key]
|
||||||
|
} else {
|
||||||
|
routeMocks.query[key] = String(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const proxyStoreMocks = vi.hoisted(() => ({
|
||||||
|
ensureLoaded: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/api/endpoints/pool', () => ({
|
||||||
|
getPoolOverview: endpointMocks.getPoolOverview,
|
||||||
|
getPoolSchedulingPresets: endpointMocks.getPoolSchedulingPresets,
|
||||||
|
listPoolKeys: endpointMocks.listPoolKeys,
|
||||||
|
clearPoolCooldown: endpointMocks.clearPoolCooldown,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/api/endpoints/keys', () => ({
|
||||||
|
revealEndpointKey: endpointMocks.revealEndpointKey,
|
||||||
|
exportKey: endpointMocks.exportKey,
|
||||||
|
deleteEndpointKey: endpointMocks.deleteEndpointKey,
|
||||||
|
updateProviderKey: endpointMocks.updateProviderKey,
|
||||||
|
refreshProviderQuota: endpointMocks.refreshProviderQuota,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/api/endpoints/provider_oauth', () => ({
|
||||||
|
refreshProviderOAuth: endpointMocks.refreshProviderOAuth,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/api/endpoints', () => ({
|
||||||
|
getProvider: endpointMocks.getProvider,
|
||||||
|
updateProvider: endpointMocks.updateProvider,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/composables/useRouteQuery', () => ({
|
||||||
|
useRouteQuery: () => ({
|
||||||
|
getQueryValue: (key: string) => routeMocks.query[key],
|
||||||
|
patchQuery: routeMocks.patchQuery,
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/stores/proxy-nodes', () => ({
|
||||||
|
useProxyNodesStore: () => ({
|
||||||
|
nodes: [],
|
||||||
|
ensureLoaded: proxyStoreMocks.ensureLoaded,
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/composables/useToast', () => ({
|
||||||
|
useToast: () => ({
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
warning: vi.fn(),
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/composables/useConfirm', () => ({
|
||||||
|
useConfirm: () => ({
|
||||||
|
confirm: vi.fn().mockResolvedValue(true),
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/composables/useClipboard', () => ({
|
||||||
|
useClipboard: () => ({
|
||||||
|
copyToClipboard: vi.fn().mockResolvedValue(undefined),
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/composables/useCountdownTimer', async () => {
|
||||||
|
const { ref } = await import('vue')
|
||||||
|
return {
|
||||||
|
useCountdownTimer: () => ({
|
||||||
|
tick: ref(0),
|
||||||
|
start: vi.fn(),
|
||||||
|
}),
|
||||||
|
getCodexResetCountdown: () => ({
|
||||||
|
isExpired: false,
|
||||||
|
text: '1h',
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('lucide-vue-next', async () => {
|
||||||
|
const { defineComponent, h } = await import('vue')
|
||||||
|
const Icon = defineComponent({
|
||||||
|
name: 'IconStub',
|
||||||
|
setup() {
|
||||||
|
return () => h('span')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
Search: Icon,
|
||||||
|
Upload: Icon,
|
||||||
|
ChevronDown: Icon,
|
||||||
|
RefreshCw: Icon,
|
||||||
|
Power: Icon,
|
||||||
|
Database: Icon,
|
||||||
|
KeyRound: Icon,
|
||||||
|
Download: Icon,
|
||||||
|
Copy: Icon,
|
||||||
|
Shield: Icon,
|
||||||
|
Globe: Icon,
|
||||||
|
SquarePen: Icon,
|
||||||
|
Trash2: Icon,
|
||||||
|
Users: Icon,
|
||||||
|
Settings2: Icon,
|
||||||
|
SlidersHorizontal: Icon,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/components/ui', async () => {
|
||||||
|
const { defineComponent, h } = await import('vue')
|
||||||
|
const passthrough = (name: string, tag = 'div') => defineComponent({
|
||||||
|
name,
|
||||||
|
inheritAttrs: false,
|
||||||
|
setup(_, { attrs, slots }) {
|
||||||
|
return () => h(tag, attrs, slots.default?.())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const Button = defineComponent({
|
||||||
|
name: 'ButtonStub',
|
||||||
|
inheritAttrs: false,
|
||||||
|
props: {
|
||||||
|
disabled: Boolean,
|
||||||
|
},
|
||||||
|
setup(props, { attrs, slots }) {
|
||||||
|
return () => h('button', { ...attrs, disabled: props.disabled, type: attrs.type ?? 'button' }, slots.default?.())
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const Input = defineComponent({
|
||||||
|
name: 'InputStub',
|
||||||
|
inheritAttrs: false,
|
||||||
|
props: {
|
||||||
|
modelValue: { type: [String, Number], default: '' },
|
||||||
|
},
|
||||||
|
emits: ['update:modelValue'],
|
||||||
|
setup(props, { attrs, emit }) {
|
||||||
|
return () => h('input', {
|
||||||
|
...attrs,
|
||||||
|
value: props.modelValue ?? '',
|
||||||
|
onInput: (event: Event) => emit('update:modelValue', (event.target as HTMLInputElement).value),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const Switch = defineComponent({
|
||||||
|
name: 'SwitchStub',
|
||||||
|
inheritAttrs: false,
|
||||||
|
props: {
|
||||||
|
modelValue: Boolean,
|
||||||
|
},
|
||||||
|
emits: ['update:modelValue'],
|
||||||
|
setup(props, { attrs, emit }) {
|
||||||
|
return () => h('input', {
|
||||||
|
...attrs,
|
||||||
|
type: 'checkbox',
|
||||||
|
role: 'switch',
|
||||||
|
checked: props.modelValue,
|
||||||
|
onChange: (event: Event) => emit('update:modelValue', (event.target as HTMLInputElement).checked),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const Pagination = defineComponent({
|
||||||
|
name: 'PaginationStub',
|
||||||
|
setup() {
|
||||||
|
return () => h('nav')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
Card: passthrough('CardStub'),
|
||||||
|
Badge: passthrough('BadgeStub', 'span'),
|
||||||
|
Button,
|
||||||
|
Input,
|
||||||
|
Select: passthrough('SelectStub'),
|
||||||
|
SelectTrigger: passthrough('SelectTriggerStub', 'button'),
|
||||||
|
SelectValue: passthrough('SelectValueStub', 'span'),
|
||||||
|
SelectContent: passthrough('SelectContentStub'),
|
||||||
|
SelectItem: passthrough('SelectItemStub'),
|
||||||
|
Table: passthrough('TableStub', 'table'),
|
||||||
|
TableHeader: passthrough('TableHeaderStub', 'thead'),
|
||||||
|
TableBody: passthrough('TableBodyStub', 'tbody'),
|
||||||
|
TableRow: passthrough('TableRowStub', 'tr'),
|
||||||
|
TableHead: passthrough('TableHeadStub', 'th'),
|
||||||
|
SortableTableHead: passthrough('SortableTableHeadStub', 'th'),
|
||||||
|
TableFilterMenu: passthrough('TableFilterMenuStub'),
|
||||||
|
TableCell: passthrough('TableCellStub', 'td'),
|
||||||
|
Switch,
|
||||||
|
Pagination,
|
||||||
|
Popover: passthrough('PopoverStub'),
|
||||||
|
PopoverTrigger: passthrough('PopoverTriggerStub'),
|
||||||
|
PopoverContent: passthrough('PopoverContentStub'),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/components/ui/refresh-button.vue', async () => {
|
||||||
|
const { defineComponent, h } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'RefreshButtonStub',
|
||||||
|
setup(_, { attrs }) {
|
||||||
|
return () => h('button', attrs, '刷新')
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/features/pool/components/PoolSchedulingDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'PoolSchedulingDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/pool/components/PoolAdvancedDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'PoolAdvancedDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/pool/components/PoolAccountBatchDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'PoolAccountBatchDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/pool/components/ProviderProxyPopover.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'ProviderProxyPopoverStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/providers/components/KeyAllowedModelsEditDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'KeyAllowedModelsEditDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/providers/components/KeyFormDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'KeyFormDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/providers/components/OAuthKeyEditDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'OAuthKeyEditDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/providers/components/OAuthAccountDialog.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'OAuthAccountDialogStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
vi.mock('@/features/providers/components/ProxyNodeSelect.vue', async () => {
|
||||||
|
const { defineComponent } = await import('vue')
|
||||||
|
return {
|
||||||
|
default: defineComponent({
|
||||||
|
name: 'ProxyNodeSelectStub',
|
||||||
|
setup() {
|
||||||
|
return () => null
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
|
||||||
|
|
||||||
|
function createOverview(providerType: string): PoolOverviewItem {
|
||||||
|
return {
|
||||||
|
provider_id: `${providerType}-provider`,
|
||||||
|
provider_name: `${providerType} Provider`,
|
||||||
|
provider_type: providerType,
|
||||||
|
total_keys: 1,
|
||||||
|
active_keys: 1,
|
||||||
|
cooldown_count: 0,
|
||||||
|
pool_enabled: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createProvider(providerType: string) {
|
||||||
|
return {
|
||||||
|
id: `${providerType}-provider`,
|
||||||
|
name: `${providerType} Provider`,
|
||||||
|
provider_type: providerType,
|
||||||
|
is_active: true,
|
||||||
|
api_formats: ['openai:chat'],
|
||||||
|
proxy: null,
|
||||||
|
pool_advanced: null,
|
||||||
|
claude_code_advanced: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPoolKey(providerType = 'codex', overrides: Partial<PoolKeyDetail> = {}): PoolKeyDetail {
|
||||||
|
return {
|
||||||
|
key_id: `${providerType}-key-1`,
|
||||||
|
key_name: `${providerType} key`,
|
||||||
|
is_active: true,
|
||||||
|
auth_type: 'api_key',
|
||||||
|
api_formats: ['openai:chat'],
|
||||||
|
internal_priority: 50,
|
||||||
|
account_quota: null,
|
||||||
|
cooldown_reason: null,
|
||||||
|
cooldown_ttl_seconds: null,
|
||||||
|
cost_window_usage: 0,
|
||||||
|
cost_limit: null,
|
||||||
|
request_count: 9876,
|
||||||
|
total_tokens: 4321000,
|
||||||
|
total_cost_usd: '8.7654',
|
||||||
|
sticky_sessions: 0,
|
||||||
|
lru_score: null,
|
||||||
|
created_at: '2026-05-05T00:00:00Z',
|
||||||
|
imported_at: '2026-05-05T00:00:00Z',
|
||||||
|
last_used_at: '2026-05-05T01:00:00Z',
|
||||||
|
status_snapshot: {
|
||||||
|
oauth: { code: 'none' },
|
||||||
|
account: { code: 'ok', blocked: false },
|
||||||
|
quota: {
|
||||||
|
code: 'ok',
|
||||||
|
exhausted: false,
|
||||||
|
provider_type: providerType,
|
||||||
|
windows: providerType === 'codex'
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
code: '5h',
|
||||||
|
remaining_ratio: 0.8,
|
||||||
|
usage: { request_count: 7, total_tokens: 2500, total_cost_usd: '0.0045' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: 'weekly',
|
||||||
|
remaining_ratio: 0.5,
|
||||||
|
usage: { request_count: 0, total_tokens: 0, total_cost_usd: '0.00000000' },
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createKeyPage(key: PoolKeyDetail): PoolKeysPageResponse {
|
||||||
|
return {
|
||||||
|
total: 1,
|
||||||
|
page: 1,
|
||||||
|
page_size: 50,
|
||||||
|
keys: [key],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetQuery() {
|
||||||
|
for (const key of Object.keys(routeMocks.query)) {
|
||||||
|
delete routeMocks.query[key]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountPoolManagement() {
|
||||||
|
const root = document.createElement('div')
|
||||||
|
document.body.appendChild(root)
|
||||||
|
const app = createApp(PoolManagement)
|
||||||
|
app.mount(root)
|
||||||
|
mountedApps.push({ app, root })
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
async function settle() {
|
||||||
|
for (let index = 0; index < 8; index += 1) {
|
||||||
|
await Promise.resolve()
|
||||||
|
await nextTick()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedStoredStatsMode(statsMode: 'current_cycle' | 'account_total') {
|
||||||
|
window.sessionStorage.setItem(
|
||||||
|
POOL_MANAGEMENT_VIEW_STORAGE_KEY,
|
||||||
|
JSON.stringify({ statsMode }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetQuery()
|
||||||
|
window.sessionStorage.clear()
|
||||||
|
routeMocks.patchQuery.mockClear()
|
||||||
|
proxyStoreMocks.ensureLoaded.mockClear()
|
||||||
|
|
||||||
|
endpointMocks.getPoolOverview.mockReset()
|
||||||
|
endpointMocks.getPoolSchedulingPresets.mockReset()
|
||||||
|
endpointMocks.listPoolKeys.mockReset()
|
||||||
|
endpointMocks.clearPoolCooldown.mockReset()
|
||||||
|
endpointMocks.getProvider.mockReset()
|
||||||
|
endpointMocks.updateProvider.mockReset()
|
||||||
|
endpointMocks.revealEndpointKey.mockReset()
|
||||||
|
endpointMocks.exportKey.mockReset()
|
||||||
|
endpointMocks.deleteEndpointKey.mockReset()
|
||||||
|
endpointMocks.updateProviderKey.mockReset()
|
||||||
|
endpointMocks.refreshProviderQuota.mockReset()
|
||||||
|
endpointMocks.refreshProviderOAuth.mockReset()
|
||||||
|
|
||||||
|
endpointMocks.getPoolSchedulingPresets.mockResolvedValue([])
|
||||||
|
endpointMocks.clearPoolCooldown.mockResolvedValue({ message: 'ok' })
|
||||||
|
endpointMocks.refreshProviderQuota.mockResolvedValue({ success: 0, failed: 0 })
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const { app, root } of mountedApps.splice(0)) {
|
||||||
|
app.unmount()
|
||||||
|
root.remove()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('PoolManagement Codex cycle stats mode', () => {
|
||||||
|
it('defaults Codex providers to current-cycle groups and toggles back to account totals', async () => {
|
||||||
|
const codexKey = createPoolKey('codex')
|
||||||
|
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||||
|
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||||
|
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||||
|
|
||||||
|
const root = mountPoolManagement()
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
const modeSwitch = root.querySelector<HTMLInputElement>('[data-testid="pool-stats-mode-switch"]')
|
||||||
|
expect(modeSwitch).not.toBeNull()
|
||||||
|
expect(modeSwitch?.checked).toBe(true)
|
||||||
|
expect(root.querySelectorAll('[data-testid="pool-stats-cycle-group-5h"]').length).toBeGreaterThan(0)
|
||||||
|
expect(root.querySelectorAll('[data-testid="pool-stats-cycle-group-weekly"]').length).toBeGreaterThan(0)
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-5h-request_count"]')?.textContent?.trim()).toBe('7')
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-weekly-total_tokens"]')?.textContent?.trim()).toBe('0')
|
||||||
|
|
||||||
|
if (!modeSwitch) throw new Error('expected stats switch')
|
||||||
|
modeSwitch.checked = false
|
||||||
|
modeSwitch.dispatchEvent(new Event('change', { bubbles: true }))
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
expect(routeMocks.query.statsMode).toBe('account_total')
|
||||||
|
expect(window.sessionStorage.getItem(POOL_MANAGEMENT_VIEW_STORAGE_KEY)).toContain('"statsMode":"account_total"')
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).not.toBeNull()
|
||||||
|
expect(root.textContent).toContain('9,876')
|
||||||
|
expect(root.textContent).toContain('4.3M')
|
||||||
|
expect(root.textContent).toContain('$8.77')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders the Codex stats switch in header actions instead of a standalone mode bar', async () => {
|
||||||
|
const codexKey = createPoolKey('codex')
|
||||||
|
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||||
|
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||||
|
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||||
|
|
||||||
|
const root = mountPoolManagement()
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
const desktopHeaderActions = root.querySelector('[data-testid="pool-header-actions"]')
|
||||||
|
const mobileHeaderActions = root.querySelector('[data-testid="pool-mobile-header-actions"]')
|
||||||
|
const modeControls = Array.from(root.querySelectorAll('[data-testid="pool-stats-mode-control"]'))
|
||||||
|
|
||||||
|
expect(desktopHeaderActions?.querySelector('[data-testid="pool-stats-mode-control"]')).not.toBeNull()
|
||||||
|
expect(mobileHeaderActions?.querySelector('[data-testid="pool-stats-mode-control"]')).not.toBeNull()
|
||||||
|
expect(modeControls).toHaveLength(2)
|
||||||
|
expect(modeControls.every(control => control.closest('[data-testid="pool-header-actions"], [data-testid="pool-mobile-header-actions"]'))).toBe(true)
|
||||||
|
expect(desktopHeaderActions?.textContent).toContain('累计')
|
||||||
|
expect(desktopHeaderActions?.textContent).toContain('周期')
|
||||||
|
expect(root.textContent).not.toContain('Codex 统计模式')
|
||||||
|
expect(root.textContent).not.toContain('当前周期显示 5H 与周窗口')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restores stored Codex account-total mode when the query omits statsMode', async () => {
|
||||||
|
seedStoredStatsMode('account_total')
|
||||||
|
const codexKey = createPoolKey('codex')
|
||||||
|
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||||
|
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||||
|
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||||
|
|
||||||
|
const root = mountPoolManagement()
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
const modeSwitch = root.querySelector<HTMLInputElement>('[data-testid="pool-stats-mode-switch"]')
|
||||||
|
expect(modeSwitch).not.toBeNull()
|
||||||
|
expect(modeSwitch?.checked).toBe(false)
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).not.toBeNull()
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-cycle-group-5h"]')).toBeNull()
|
||||||
|
expect(routeMocks.query.statsMode).toBe('account_total')
|
||||||
|
expect(window.sessionStorage.getItem(POOL_MANAGEMENT_VIEW_STORAGE_KEY)).toContain('"statsMode":"account_total"')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lets a current-cycle statsMode query override stored Codex account-total mode', async () => {
|
||||||
|
seedStoredStatsMode('account_total')
|
||||||
|
routeMocks.query.statsMode = 'current_cycle'
|
||||||
|
const codexKey = createPoolKey('codex')
|
||||||
|
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||||
|
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||||
|
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||||
|
|
||||||
|
const root = mountPoolManagement()
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
const modeSwitch = root.querySelector<HTMLInputElement>('[data-testid="pool-stats-mode-switch"]')
|
||||||
|
expect(modeSwitch).not.toBeNull()
|
||||||
|
expect(modeSwitch?.checked).toBe(true)
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-cycle-group-5h"]')).not.toBeNull()
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).toBeNull()
|
||||||
|
expect(routeMocks.query.statsMode).toBeUndefined()
|
||||||
|
expect(window.sessionStorage.getItem(POOL_MANAGEMENT_VIEW_STORAGE_KEY)).toContain('"statsMode":"current_cycle"')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides the stats mode switch for non-Codex providers and keeps account totals', async () => {
|
||||||
|
const openaiKey = createPoolKey('openai', {
|
||||||
|
request_count: 12,
|
||||||
|
total_tokens: 3456,
|
||||||
|
total_cost_usd: '1.25',
|
||||||
|
})
|
||||||
|
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('openai')] })
|
||||||
|
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(openaiKey))
|
||||||
|
endpointMocks.getProvider.mockResolvedValue(createProvider('openai'))
|
||||||
|
|
||||||
|
const root = mountPoolManagement()
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-mode-switch"]')).toBeNull()
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-mode-control"]')).toBeNull()
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-cycle-group-5h"]')).toBeNull()
|
||||||
|
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).not.toBeNull()
|
||||||
|
expect(root.textContent).toContain('12')
|
||||||
|
expect(root.textContent).toContain('3.5K')
|
||||||
|
expect(root.textContent).toContain('$1.25')
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user