Compare commits

...
10 Commits
Author SHA1 Message Date
ZyyandCodex 914c4c24d3 chore: bump version to 3.60.5
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:52:44 +08:00
ZyyandCodex 7251546c75 fix(gateway): preserve upstream retry headers across capacity rotation
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:52:24 +08:00
ZyyandCodex 3c38925716 docs(skills): clarify frontend tooltip and list loading guidance
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:33:02 +08:00
ZyyandCodex 43ca35b027 fix(antigravity): explain Google account connection test failures
Refs #805

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:18:47 +08:00
ZyyandCodex 95d545a7d8 perf(admin): show request error popovers without fetching details
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 12:17:35 +08:00
ZyyandCodex db3324f90a fix(admin): show upstream errors and retry waits in request popovers
Localize interrupted requests, align quota badges, and update the icon picker to the responsive UI revision.

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:56:13 +08:00
ZyyandCodex 30bcff3419 test(store): verify display names for accounts sharing an email
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:56:13 +08:00
329503d967 fix(admin): use account display names in sorting and usage (#815)
* fix(admin): use account display names in sorting and usage

Co-authored-by: Codex <noreply@openai.com>

* fix(ui): remove native tooltips from usage identity cells

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 11:10:24 +08:00
eae19e211e fix(openai): start weekly bucket warmup after reset-credit consume (#813)
* fix(openai): start weekly bucket warmup after reset-credit consume

After a successful reset or already_redeemed consume, refresh quota and
advance an already-enabled bucket warmup to the actual reset time. Pull
an early reset's registered future boundary back so due() is not blocked
until the original window ends. Keep the five-minute recheck and skip
warmup when the new round already has usage.

* fix(openai): make credit-triggered weekly warmup idempotent

Register confirmed redemptions with bucket progress and recheck usage in the warmup worker. Preserve precise usage evidence and keep rolling quota deadlines separate from confirmed resets.

Co-authored-by: Codex <noreply@openai.com>

* refactor(openai): keep only the latest warmup redemption

Reuse account warmup progress to recognize retries of the latest credit. Remove the receipt table and keep the existing storage contract.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-01 10:56:06 +08:00
github-actions[bot] 294e9c8bd8 chore(release): update release channels to 3.60.4 2026-11-30 16:44:00 +00:00
73 changed files with 1159 additions and 251 deletions
@@ -21,6 +21,9 @@
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
## 验收范围与收尾
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
@@ -55,7 +55,7 @@ pub struct AccountImportSettings {
/// 账号列表排序字段
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountSortField {
Email,
Name,
Status,
PlanType,
Usage,
@@ -889,12 +889,14 @@ impl UsageErrorOrigin {
}
/// 使用记录表格的窄读模型
#[derive(Debug, Clone, PartialEq)]
#[derive(Clone, PartialEq)]
pub struct UsageListRecord {
pub platform_icon: Option<String>,
pub outcome: RequestOutcome,
/// 已保存的上游错误对象含非空字符串 code、type 或 message
pub has_upstream_error: bool,
pub upstream_error_message: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub error_kind: Option<String>,
@@ -961,6 +963,17 @@ pub struct UsageListRecord {
pub started_at: DateTime<Utc>,
}
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
impl std::fmt::Debug for UsageListRecord {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("UsageListRecord")
.field("id", &self.id)
.field("outcome", &self.outcome)
.finish_non_exhaustive()
}
}
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
#[derive(Clone, PartialEq)]
pub struct UsageUpstreamError {
@@ -1169,6 +1182,7 @@ pub struct DiagnosticsObservation {
pub struct DiagnosticObservation {
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub account_authentication_kind: Option<String>,
@@ -1647,6 +1661,7 @@ pub struct DiagnosticsItem {
pub platform_icon: Option<String>,
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub account_authentication_kind: Option<String>,
pub account_plan_type: Option<String>,
/// 仅账号维度补充当前互联识别结果
@@ -1342,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
.map(ToOwned::to_owned);
let upstream_body = error
.upstream_response()
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
.map(|body| String::from_utf8_lossy(body).into_owned());
let message = error.client_message().to_owned();
vec![AccountConnectionTestEvent::Failed {
source: error.source(),
@@ -379,6 +379,7 @@ impl ObservabilityService for DefaultObservabilityService {
account_upstream_peer: peers.get(&item.key).copied(),
key: item.key,
name: item.name,
account_email: item.account_email,
account_authentication_kind: item.account_authentication_kind,
account_plan_type_display: self.historical_plan_display(
item.account_plan_type_display,
@@ -454,6 +454,8 @@ fn total_record(
platform_icon: None,
provider_account_upstream_peer: None,
has_upstream_error: false,
upstream_error_message: None,
retry_after_ms: None,
error_code: None,
error_message: None,
error_kind: None,
@@ -550,6 +552,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
account_plan_type_display: None,
key: name.to_owned(),
name: name.to_owned(),
account_email: None,
request_count,
success_count: request_count,
failure_count: 0,
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
match value.trim() {
"email" => Some(AccountSortField::Email),
"name" => Some(AccountSortField::Name),
"status" => Some(AccountSortField::Status),
"planType" => Some(AccountSortField::PlanType),
"usage" => Some(AccountSortField::Usage),
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
upstream_status_code: record.upstream_status_code,
error_code: record.error_code,
error_message: record.error_message,
upstream_error_message: record.upstream_error_message,
retry_after_ms: record.retry_after_ms,
error_kind: record.error_kind,
websocket_close_code: record.websocket_close_code,
continuation_unavailable_reason: record.continuation_unavailable_reason,
@@ -1354,13 +1356,14 @@ pub(crate) fn diagnostics_view(
.map(|item| DiagnosticItemView {
providers: item.providers,
platform_icon: item.platform_icon,
key: item.key,
account_email: item.account_email,
authentication_kind: item.account_authentication_kind,
name: if item.name == "__none__" {
name: if item.key == "__none__" {
"未知".to_owned()
} else {
item.name
},
key: item.key,
request_count: item.request_count,
account_plan_type: item.account_plan_type,
account_plan_type_display: item.account_plan_type_display,
@@ -92,6 +92,8 @@ pub struct UsageListRecordView {
pub upstream_status_code: Option<u16>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub upstream_error_message: Option<String>,
pub retry_after_ms: Option<u64>,
pub error_kind: Option<String>,
pub websocket_close_code: Option<u16>,
pub continuation_unavailable_reason: Option<String>,
@@ -878,6 +880,7 @@ pub struct DiagnosticItemView {
pub platform_icon: Option<String>,
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub authentication_kind: Option<String>,
pub account_plan_type: Option<String>,
pub account_plan_type_display: Option<String>,
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
}
}
pub(crate) fn is_retry_after_header(name: &str) -> bool {
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
}
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
return None;
}
let mut projected = data.clone();
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
for path in ["/headers", "/error/headers", "/response/error/headers"] {
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
headers.retain(|name, _| !is_retry_after_header(name));
}
}
for path in CODE_PATHS {
if let Some(code) = projected.pointer_mut(path)
&& capacity_code(code)
@@ -15,7 +15,7 @@ use serde_json::{Value, json};
pub use gateway_core::engine::execution::gateway_error_from_engine;
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client, is_retry_after_header};
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client};
pub use crate::client_error::{
gateway_error_contract, gateway_error_response, openai_error_response,
@@ -109,6 +109,29 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
)
}
/// 已提交的 Responses 流通过终止事件交付容量错误的等待头
pub(crate) fn capacity_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
let mut headers = serde_json::Map::new();
if let EngineError::Provider(provider) = error
&& provider.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
&& let Some(response) = provider.client_visible_upstream_response()
{
for header in response.headers() {
if (header.name().eq_ignore_ascii_case("retry-after")
|| header.name().eq_ignore_ascii_case("retry-after-ms"))
&& let Ok(value) = HeaderValue::from_bytes(header.value())
&& let Ok(value) = value.to_str()
{
headers.insert(
header.name().to_ascii_lowercase(),
Value::String(value.to_owned()),
);
}
}
}
headers
}
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
pub fn engine_error_response(error: &EngineError) -> Response {
let capacity_unavailable = matches!(error, EngineError::Provider(error)
@@ -122,7 +145,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
let projected = serde_json::from_slice::<Value>(upstream.body())
.ok()
.and_then(|body| capacity_error_for_client(&body));
let suppress_retry_after = capacity_unavailable || projected.is_some();
let mut response = match projected {
Some(body) => {
let mut response = Response::new(Body::from(body.to_string()));
@@ -145,9 +167,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
response.headers_mut().insert(CONTENT_TYPE, content_type);
}
for header in upstream.headers() {
if suppress_retry_after && is_retry_after_header(header.name()) {
continue;
}
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
continue;
};
@@ -830,7 +830,10 @@ impl StreamingExecutionBody {
}
Ok(None) => return Err(invalid_execution_stream()),
Err(error) if self.committed => {
self.push_stream_error(gateway_error_from_engine(&error));
self.push_stream_error(
gateway_error_from_engine(&error),
crate::data_plane::error::capacity_retry_headers(&error),
);
continue;
}
Err(error) => return Err(MiddlewareError::Engine(error)),
@@ -893,9 +896,13 @@ impl StreamingExecutionBody {
}
}
fn push_stream_error(&mut self, error: GatewayError) {
fn push_stream_error(
&mut self,
error: GatewayError,
headers: serde_json::Map<String, serde_json::Value>,
) {
self.pending.push_back(MiddlewareFrame::new(
self.encoder.error_frame(&error),
self.encoder.error_frame(&error, headers),
MiddlewareFraming::SseEvent,
false,
));
@@ -935,7 +942,7 @@ impl MiddlewareBody for StreamingExecutionBody {
"Gateway response stream could not be delivered.",
),
};
self.push_stream_error(error);
self.push_stream_error(error, Default::default());
}
Ok(self.pending.pop_front())
})
@@ -972,7 +979,7 @@ impl MiddlewareBody for StreamingExecutionBody {
"The Chat response could not be finalized.",
),
};
self.push_stream_error(error);
self.push_stream_error(error, Default::default());
}
}
}
@@ -6,7 +6,8 @@ use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
use gateway_protocol::{
anthropic::MessagesAccumulator,
openai::sse::{
DONE_SSE_FRAME, encode_sse_event_with_metadata, response_failed_sse_event_with_id,
DONE_SSE_FRAME, encode_sse_event, encode_sse_event_with_metadata,
response_failed_sse_data_with_id,
},
};
use serde_json::{Value, json};
@@ -159,7 +160,11 @@ impl GenerationEncoder {
}
}
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
pub(super) fn error_frame(
&self,
error: &GatewayError,
headers: serde_json::Map<String, Value>,
) -> Bytes {
let (status, error_type, code) = gateway_error_contract(error.kind());
match self {
Self::Chat(_) => {
@@ -169,12 +174,21 @@ impl GenerationEncoder {
"message": error.client_message(),
}}))
}
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
encoder.response_id(),
error.client_error_type().unwrap_or(error_type),
crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)),
error.client_message(),
)),
Self::Responses(encoder) => {
let mut data = response_failed_sse_data_with_id(
encoder.response_id(),
error.client_error_type().unwrap_or(error_type),
crate::client_error::client_error_code(
error.client_error_code().unwrap_or(code),
),
error.client_message(),
);
if !headers.is_empty() {
data["response"]["error"]["headers"] = json!(headers);
data["error"]["headers"] = Value::Object(headers);
}
Bytes::from(encode_sse_event("response.failed", &data.to_string()))
}
Self::GenAi { .. } => {
crate::data_plane::genai::error_frame(status, error.client_message())
}
@@ -575,7 +575,10 @@ impl WebSocketExecutionBody {
Ok(Some(delivery)) => delivery,
Ok(None) => return Err(MiddlewareError::InvalidState),
Err(error) if self.committed => {
self.push_gateway_error(gateway_error_from_engine(&error));
self.push_gateway_error(
gateway_error_from_engine(&error),
crate::data_plane::error::capacity_retry_headers(&error),
);
continue;
}
Err(error) => return Err(MiddlewareError::Engine(error)),
@@ -635,7 +638,11 @@ impl WebSocketExecutionBody {
Ok(())
}
fn push_gateway_error(&mut self, error: GatewayError) {
fn push_gateway_error(
&mut self,
error: GatewayError,
headers: serde_json::Map<String, serde_json::Value>,
) {
let (status, default_type, default_code) = gateway_error_contract(error.kind());
self.pending.push_back(MiddlewareFrame::new(
Bytes::from(
@@ -646,7 +653,7 @@ impl WebSocketExecutionBody {
error.client_message(),
None,
Some(&self.request_id),
serde_json::Map::new(),
headers,
)
.to_string(),
),
@@ -126,7 +126,7 @@ mod query {
"provider": "xai",
"search": " operator ",
"status": "normal",
"sortBy": "lastUsedAt",
"sortBy": "name",
"sortDirection": "desc"
}))
.expect("deserialize account query");
@@ -139,10 +139,7 @@ mod query {
));
assert_eq!(query.search.as_deref(), Some("operator"));
assert_eq!(query.status, Some(AccountStatus::Normal));
assert_eq!(
query.sort.expect("sort").field,
AccountSortField::LastUsedAt
);
assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
assert_eq!(
query.sort.expect("copy sort").direction,
SortDirection::Desc
@@ -753,7 +753,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
account_authentication_kind: authentication_kind.map(str::to_owned),
account_plan_type: plan_type.map(str::to_owned),
account_plan_type_display: None,
name: "diag@example.invalid".to_owned(),
account_email: Some("diag@example.invalid".to_owned()),
name: "__none__".to_owned(),
request_count: 2,
success_count: 2,
failure_count: 0,
@@ -813,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
(
&value["data"]["items"][0]["key"],
&value["data"]["items"][0]["name"],
&value["data"]["items"][0]["accountEmail"],
&value["data"]["items"][0]["latencyP95Ms"],
&value["data"]["dimension"],
),
(
&serde_json::json!("acct_diag"),
&serde_json::json!("__none__"),
&serde_json::json!("diag@example.invalid"),
&serde_json::json!(3800),
&serde_json::json!("account"),
@@ -987,6 +990,8 @@ async fn usage_route_projects_request_facts_and_billing() {
platform_icon: None,
provider_account_upstream_peer: None,
has_upstream_error: false,
upstream_error_message: None,
retry_after_ms: None,
error_code: None,
error_message: None,
error_kind: None,
@@ -1089,6 +1094,8 @@ async fn usage_route_projects_request_facts_and_billing() {
failed.upstream_status_code = Some(429);
failed.error_code = Some("server_error".to_owned());
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
failed.upstream_error_message = Some("Retry once capacity is available.".to_owned());
failed.retry_after_ms = Some(30_000);
records.push(failed);
let mut closed = records[0].clone();
closed.id = "request_ws_closed".to_owned();
@@ -1131,6 +1138,11 @@ async fn usage_route_projects_request_facts_and_billing() {
assert!(value["data"]["items"][0]["errorCode"].is_null());
assert!(value["data"]["items"][0]["errorMessage"].is_null());
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
assert_eq!(
value["data"]["items"][3]["upstreamErrorMessage"],
"Retry once capacity is available."
);
assert_eq!(value["data"]["items"][3]["retryAfterMs"], 30_000);
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
@@ -101,8 +101,8 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
if raw_response {
assert_eq!(response.headers()["x-request-id"], "req_capacity");
assert!(!response.headers().contains_key("retry-after"));
assert!(!response.headers().contains_key("retry-after-ms"));
assert_eq!(response.headers()["retry-after"], "7");
assert_eq!(response.headers()["retry-after-ms"], "7000");
}
let body: Value = serde_json::from_slice(
&to_bytes(response.into_body(), 4096)
@@ -116,7 +116,6 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
if raw_response {
let mut expected = original.clone();
expected["error"]["code"] = json!("server_error");
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
assert_eq!(body, expected);
}
let EngineError::Provider(provider) = error else {
@@ -2214,14 +2214,13 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
#[tokio::test]
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
for (error_type, code, client_code, kind, client_status, keeps_retry_after) in [
for (error_type, code, client_code, kind, client_status) in [
(
"service_unavailable_error",
"server_is_overloaded",
"server_error",
ProviderErrorKind::UpstreamCapacityUnavailable,
503,
false,
),
(
"rate_limit_error",
@@ -2229,7 +2228,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
"turn_rate_limit_exceeded",
ProviderErrorKind::RateLimited,
429,
true,
),
] {
let trace = Arc::new(Trace::default());
@@ -2306,16 +2304,17 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
.find(|event| event.event.as_deref() == Some("response.failed"))
.expect("translated response.failed event");
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
let mut expected = json!({
let expected = json!({
"type": "response.failed",
"status": client_status,
"headers": {"x-request-id": "req_test"},
"headers": {"Retry-After": "24", "retry-after-ms": "24000", "x-request-id": "req_test"},
"response": {
"id": "resp_test",
"model": "public-model",
"status": "failed",
"error": {
"type": error_type,
"headers": {"retry-after": "24", "retry-after-ms": "24000"},
"code": client_code,
"message": "Our servers are currently overloaded. Please try again later.",
"param": null,
@@ -2326,11 +2325,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
"sequence_number": 2,
"future_event_field": {"keep": true}
});
if keeps_retry_after {
expected["headers"]["Retry-After"] = json!("24");
expected["headers"]["retry-after-ms"] = json!("24000");
expected["response"]["error"]["headers"] = json!({"retry-after": "24"});
}
assert_eq!(
(
@@ -2347,12 +2341,23 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
#[tokio::test]
async fn streaming_capacity_error_after_commit_offers_client_retry() {
for code in ["server_is_overloaded", "slow_down"] {
for (code, expected) in [
("server_is_overloaded", "server_error"),
("slow_down", "server_error"),
("previous_response_not_found", "previous_response_not_found"),
] {
let trace = Arc::new(Trace::default());
let error = ProviderError::new(
ProviderErrorKind::UpstreamCapacityUnavailable,
UpstreamSendState::Sent,
)
.with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
]),
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"busy",
Some(code.to_owned()),
@@ -2377,7 +2382,11 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
.find(|event| event.event.as_deref() == Some("response.failed"))
.expect("failed event");
let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
assert_eq!(failed["response"]["error"]["code"], "server_error");
assert_eq!(failed["response"]["error"]["code"], expected);
assert_eq!(
failed["response"]["error"]["headers"],
json!({"retry-after": "309", "retry-after-ms": "309001"})
);
assert_eq!(failed["response"]["error"]["message"], "busy");
assert_eq!(text.matches("event: response.failed").count(), 1);
assert!(text.ends_with("data: [DONE]\n\n"));
@@ -1256,16 +1256,12 @@ fn capacity_failure_projection_preserves_wire_metadata_and_original_events() {
assert_eq!(sse_data["response"]["error"]["code"], "server_error");
assert_eq!(sse_data["response"]["error"]["message"], "busy");
assert_eq!(sse_data["response"]["error"]["future"], 42);
assert_eq!(
sse_data["response"]["error"]["headers"],
json!({"x-request-id":"req_capacity"})
);
assert_eq!(sse_data["response"]["error"]["headers"], error["headers"]);
let messages = ws.push_websocket(&event);
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
if event_type == "error" && status.is_some() {
let mut expected = original.clone();
expected["error"]["code"] = json!("server_error");
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
expected["status_code"] = json!(503);
assert_eq!(ws_data, expected);
} else {
@@ -340,8 +340,8 @@ async fn initial_capacity_failure_offers_client_retry_with_upstream_correlation(
assert_eq!(error["error"]["code"], "server_error");
assert_eq!(error["error"]["message"], "busy");
assert_eq!(error["headers"]["x-request-id"], "req_capacity");
assert!(error["headers"].get("retry-after").is_none());
assert!(error["headers"].get("retry-after-ms").is_none());
assert_eq!(error["headers"]["retry-after"], "7");
assert_eq!(error["headers"]["retry-after-ms"], "7000");
}
}
}
@@ -104,6 +104,8 @@ fn usage_record() -> UsageListRecord {
platform_icon: None,
provider_account_upstream_peer: None,
has_upstream_error: false,
upstream_error_message: Some("private-sentinel-upstream".into()),
retry_after_ms: Some(30_000),
error_code: None,
error_message: None,
error_kind: None,
@@ -1480,7 +1480,7 @@ where
&& let Some(original) = self.last_retryable_failure.take()
{
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
error = original.with_client_recovery_from(error);
error = original.with_client_recovery_from(error, &self.last_retryable_failure_events);
self.last_retryable_failure_events.clear();
}
let kind = error.kind();
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
) -> AccountProbeError {
let (source, send_state, upstream_response) = match error {
EngineError::Provider(provider_error) => {
let upstream_response = provider_error
.client_visible_upstream_response()
.map(AccountProbeUpstreamResponse::from_client_response);
let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|| provider_error.upstream_status().is_some()
|| provider_error.upstream_code().is_some()
|| provider_error.client_visible_upstream_error().is_some()
|| upstream_response.is_some();
+13 -13
View File
@@ -5,9 +5,7 @@ use std::fmt;
use bytes::Bytes;
use futures::future::BoxFuture;
use crate::error::{
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
};
use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
use crate::identity::ProviderKind;
use crate::routing::UpstreamModelId;
use crate::{
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
pub struct AccountProbeUpstreamResponse {
status: u16,
content_type: Option<Vec<u8>>,
body: Bytes,
body: Option<Bytes>,
}
impl AccountProbeUpstreamResponse {
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self {
Self {
status: response.status(),
content_type: response.content_type().map(<[u8]>::to_vec),
body: response.body().clone(),
}
pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
let response = error.client_visible_upstream_response();
// 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
Some(Self {
status: response.map(|r| r.status()).or(error.upstream_status())?,
content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
body: response.map(|r| r.body().clone()),
})
}
#[must_use]
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
}
#[must_use]
pub const fn body(&self) -> &Bytes {
&self.body
pub const fn body(&self) -> Option<&Bytes> {
self.body.as_ref()
}
}
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
"content_type",
&self.content_type.as_ref().map(|_| "<present>"),
)
.field("body", &"<redacted>")
.field("body", &self.body.as_ref().map(|_| "<redacted>"))
.finish()
}
}
+37 -1
View File
@@ -1094,7 +1094,43 @@ impl ProviderError {
}
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
pub(crate) fn with_client_recovery_from(mut self, recovery: Self) -> Self {
pub(crate) fn with_client_recovery_from(
mut self,
mut recovery: Self,
events: &[ProviderEvent],
) -> Self {
if self.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
&& let Some(response) = recovery.client_visible_upstream_response.as_deref_mut()
{
// 迁移响应继承原失败的等待头;其余旧账号头和错误正文不属于新响应
let original = self.client_visible_upstream_response();
let body = original.and_then(|original| serde_json::from_slice(original.body()).ok());
let event = events
.iter()
.rev()
.find_map(ProviderEvent::wire_event)
.map(|wire| wire.data());
for name in ["retry-after", "retry-after-ms"] {
if let Some(header) = original.and_then(|original| {
original
.headers()
.iter()
.rev()
.find(|h| h.name().eq_ignore_ascii_case(name))
}) {
response.headers.push(header.clone());
} else if let Some(value) =
event.into_iter().chain(body.as_ref()).find_map(|value| {
gateway_protocol::openai::events::error_event_header(value, name)
})
{
response.headers.push(ProviderResponseHeader::new(
name,
Bytes::copy_from_slice(value.as_bytes()),
));
}
}
}
if let Some(reason) = recovery.continuation_unavailable_reason() {
self = self.with_continuation_unavailable_reason(reason);
}
@@ -2525,11 +2525,33 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
.with_continuation_recovery_disposition(
ContinuationRecoveryDisposition::ClientReplayRequired,
);
let original = if committed_prelude {
let event = json!({"type":"response.failed", "response":{"error":{
"headers":{"Retry-After":seconds.to_string(), "Retry-After-Ms":"317001", "x-private":"omit"}
}}});
original.with_atomic_client_events(vec![ProviderEvent::wire(
ProtocolWireEvent::json("openai", Some("response.failed".to_owned()), event)
.unwrap(),
)])
} else {
original.with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new(503, None, Bytes::from(original_body.clone()))
.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
"Retry-After-Ms",
Bytes::from_static(b"309001"),
)]),
)
};
let recovery = if replacement {
ProviderError::new(
ProviderErrorKind::ContinuationRecoveryRequired,
UpstreamSendState::NotSent,
)
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
400,
None,
Bytes::from_static(b"{}"),
))
.with_continuation_unavailable_reason("account_rotated")
.with_continuation_recovery_disposition(
ContinuationRecoveryDisposition::ClientReplayRequired,
@@ -2602,6 +2624,29 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
error.continuation_unavailable_reason(),
(replacement && expected_attempts == 2).then_some("account_rotated")
);
if replacement && expected_attempts == 2 {
let response = error.client_visible_upstream_response().unwrap();
assert_eq!(response.status(), 400);
let headers: Vec<_> = response
.headers()
.iter()
.map(|header| (header.name().to_ascii_lowercase(), header.value().as_ref()))
.collect();
assert_eq!(
headers,
vec![
("retry-after".to_owned(), seconds.to_string().as_bytes()),
(
"retry-after-ms".to_owned(),
if committed_prelude {
b"317001"
} else {
b"309001"
}
),
]
);
}
let contexts = provider.contexts.lock().unwrap();
assert_eq!(contexts.len(), expected_attempts);
if contexts.len() == 2 {
@@ -3509,8 +3509,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
#[test]
fn probe_failures_should_be_observable_without_a_model_request_row() {
let store = Arc::new(TrackingExecutionStore::default());
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
.expect("provider registry");
let providers = ProviderRegistry::new([
Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
])
.expect("provider registry");
let service = DefaultExecutionService::new(
RuntimeSnapshotHandle::new(probe_snapshot()),
store.clone(),
@@ -3547,7 +3549,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
);
assert_eq!(
upstream.body(),
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#),
Some(&Bytes::from_static(
br#"{"error":{"message":"source upstream failure"}}"#
)),
);
assert!(!format!("{error:?}").contains("source upstream failure"));
assert!(!store.touched.load(Ordering::SeqCst));
@@ -3687,8 +3691,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
fail_probe_observation: AtomicBool::new(true),
..TrackingExecutionStore::default()
});
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
.expect("provider registry");
let providers = ProviderRegistry::new([Arc::new(FailingProvider {
include_body: false,
}) as Arc<dyn Provider>])
.expect("provider registry");
let service = DefaultExecutionService::new(
RuntimeSnapshotHandle::new(probe_snapshot()),
store.clone(),
@@ -3715,9 +3721,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
assert!(!store.touched.load(Ordering::SeqCst));
assert!(store.probe_failures().is_empty());
let upstream = error.upstream_response().unwrap();
assert_eq!(upstream.status(), 403);
assert!(upstream.body().is_none());
assert!(upstream.content_type().is_none());
}
struct FailingProvider;
struct FailingProvider {
include_body: bool,
}
#[derive(Clone, Copy)]
enum CatalogProvider {
@@ -4055,6 +4067,13 @@ impl Provider for FailingProvider {
_request: ProviderRequest,
_context: AttemptContext,
) -> Result<ProviderStream, ProviderError> {
if !self.include_body {
return Err(ProviderError::new(
ProviderErrorKind::PermissionDenied,
UpstreamSendState::Sent,
)
.with_status(403));
}
Err(
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
@@ -228,12 +228,32 @@ fn retry_after_seconds_field(value: &Value) -> Option<u64> {
/// 同时保留原始头值与解析秒数,供事件转换和重试观测共用官方头部规则
pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
let (value, header) = event_header(value, "retry-after")?;
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
Some((value, seconds))
}
/// 从客户端可见的错误事件读取指定头,嵌套错误优先于事件头
pub fn error_event_header(event: &Value, name: &str) -> Option<http::HeaderValue> {
let error = event
.pointer("/response/error")
.or_else(|| event.get("error"));
error
.and_then(|error| event_header(error, name))
.or_else(|| event_header(event, name))
.map(|(_, header)| header)
}
pub(super) fn event_header<'a>(
value: &'a Value,
wanted: &str,
) -> Option<(&'a Value, http::HeaderValue)> {
let headers = value.get("headers")?.as_object()?;
// 官方先按 HTTP 头值校验,再覆盖大小写不同的同名头;最后才解释重试时间
// 合法但无法解析为时间的末项也会覆盖前值,非法头值和数组不参与覆盖
let (value, header) = headers
headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
.filter(|(name, _)| name.eq_ignore_ascii_case(wanted))
.filter_map(|(_, value)| {
let header = match value {
Value::String(value) => http::HeaderValue::from_str(value).ok(),
@@ -244,9 +264,7 @@ pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
}?;
Some((value, header))
})
.next_back()?;
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
Some((value, seconds))
.next_back()
}
/// 判断上游错误是否携带 `x-retry-metadata: NO_MORE_RETRY`
@@ -322,9 +322,18 @@ pub fn response_failed_sse_data_from_error_event(
let mut error = event.remove("error").filter(Value::is_object)?;
// 官方 WS 先读错误头、再读事件头,SSE 只读 response.error.headers
// 仅补充有效的等待建议,保留原始日期或秒数,不复制其他事件级响应头
if super::events::retry_after_header(&error).is_none()
&& let Some((retry_after, _)) = super::events::retry_after_header(error_event)
{
let seconds = super::events::retry_after_header(&error)
.is_none()
.then(|| super::events::retry_after_header(error_event))
.flatten()
.map(|(value, _)| value);
let millis = super::events::event_header(&error, "retry-after-ms")
.is_none()
.then(|| super::events::event_header(error_event, "retry-after-ms"))
.flatten()
.map(|(value, _)| value);
for (name, value) in [("retry-after", seconds), ("retry-after-ms", millis)] {
let Some(value) = value else { continue };
let headers = error
.as_object_mut()?
.entry("headers")
@@ -333,8 +342,8 @@ pub fn response_failed_sse_data_from_error_event(
*headers = json!({});
}
let headers = headers.as_object_mut()?;
headers.retain(|name, _| !name.eq_ignore_ascii_case("retry-after"));
headers.insert("retry-after".to_owned(), retry_after.clone());
headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
headers.insert(name.to_owned(), value.clone());
}
let mut response = response
.and_then(Value::as_object)
@@ -634,6 +634,7 @@ impl<'a> AnalyticsSnapshot<'a> {
observations.push(DiagnosticObservation {
key: key.clone(),
name: key,
account_email: None,
providers: state.providers.iter().cloned().collect(),
platform_icon: None,
account_authentication_kind: None,
@@ -672,9 +673,29 @@ impl<'a> AnalyticsSnapshot<'a> {
.map(|item| item.key.clone())
.collect::<Vec<_>>();
let statement = if dimension == DiagnosticDimension::Account {
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
"select requested.id, coalesce(h.provider_kind, a.provider_kind) as provider_kind,
a.platform_icon, h.authentication_kind, h.plan_type, h.plan_type_display,
coalesce(h.account_name, h.account_email, requested.id) as name, h.account_email
from unnest($1::text[]) requested(id)
left join provider_accounts a on a.id = requested.id
left join lateral (
select provider_kind, provider_account_authentication_kind_snapshot as authentication_kind,
provider_account_plan_type_snapshot as plan_type,
provider_account_plan_type_display_snapshot as plan_type_display,
nullif(btrim(provider_account_name_snapshot), '') as account_name,
nullif(btrim(provider_account_email_snapshot), '') as account_email
from model_request_observations where provider_account_ref = requested.id
order by started_at desc, id desc limit 1
) h on true"
} else {
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
"select requested.id, null::text as provider_kind, null::text as platform_icon,
null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display,
coalesce(h.client_api_key_name_snapshot, requested.id) as name, null::text as account_email
from unnest($1::text[]) requested(id)
left join lateral (
select client_api_key_name_snapshot from model_request_observations
where client_api_key_ref = requested.id order by started_at desc, id desc limit 1
) h on true"
};
let labels = sqlx::query(statement)
.bind(ids)
@@ -685,6 +706,7 @@ impl<'a> AnalyticsSnapshot<'a> {
let id: String = get(&row, "id")?;
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
item.name = get(&row, "name")?;
item.account_email = get(&row, "account_email")?;
item.providers = get::<Option<String>>(&row, "provider_kind")?
.into_iter()
.collect();
@@ -280,6 +280,7 @@ fn admin_diagnostic_observation(
admin_observability::DiagnosticObservation {
key: observation.key,
name: observation.name,
account_email: observation.account_email,
providers: observation.providers,
platform_icon: observation.platform_icon,
account_authentication_kind: observation.account_authentication_kind,
@@ -369,6 +370,8 @@ pub(crate) fn usage_list_record_from_row(
)?;
Ok(UsageListRecord {
has_upstream_error: get(row, "has_upstream_error")?,
upstream_error_message: get(row, "upstream_error_message")?,
retry_after_ms: optional_unsigned(row, "retry_after_ms")?,
error_code: get(row, "error_code")?,
error_message: get(row, "error_message")?,
error_kind: get(row, "error_kind")?,
@@ -384,6 +384,7 @@ pub struct DiagnosticsObservation {
pub struct DiagnosticObservation {
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub account_authentication_kind: Option<String>,
@@ -130,7 +130,7 @@ pub(crate) fn push_usage_filter(
pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
"select mr.id, mr.outcome, mr.provider_error_code as error_code, mr.error_message, mr.client_status_code, mr.client_api_key_name_snapshot as client_api_key_name, mr.endpoint, mr.client_transport, mr.requested_model_id,
mr.error_kind, mr.upstream_status_code,
facts.has_upstream_error, facts.websocket_close_code,
facts.has_upstream_error, facts.websocket_close_code, facts.upstream_error_message, mr.retry_after_ms,
mr.continuation_unavailable_reason, mr.upstream_connection_exit_reason,
(mr.recovery_request_id is not null and mr.recovered_at is not null) as recovered,
mr.provider_kind, mr.provider_account_ref,
@@ -166,6 +166,13 @@ const SAVED_ERROR_FACTS: &str = "(select exists (
) as field(value)
where jsonb_typeof(field.value) = 'string' and field.value <> '\"\"'::jsonb
) as has_upstream_error,
coalesce(
case when jsonb_typeof(saved_error.body -> 'message') = 'string'
then nullif(saved_error.body ->> 'message', '') end,
case when saved_upstream.body ->> 'type' = 'websocket.close'
and jsonb_typeof(saved_upstream.body -> 'reason') = 'string'
then nullif(saved_upstream.body ->> 'reason', '') end
) as upstream_error_message,
case when saved_upstream.body ->> 'type' = 'websocket.close'
and jsonb_typeof(saved_upstream.body -> 'code') = 'number'
and (saved_upstream.body ->> 'code') ~ '^[0-9]{1,5}$'
@@ -253,7 +253,9 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
return "a.id asc".to_owned();
};
let expression = match sort.field {
AdminAccountSortField::Email => "a.email",
AdminAccountSortField::Name => {
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
}
AdminAccountSortField::Status => {
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
}
@@ -125,7 +125,7 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
"update model_requests
set client_status_code = 200, upstream_status_code = 200, error_kind = 'unavailable',
request_observation_json = jsonb_set(request_observation_json, '{error}',
'{\"message\":\"Upstream error summary\"}'::jsonb)
'{\"message\":\"Upstream error summary\",\"retryAfterMs\":30000}'::jsonb)
where id = 'req_observe_failed'",
)
.execute(&database.pool)
@@ -191,6 +191,13 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
assert_eq!(detail.request.provider_error_code, None);
assert_eq!(list.client_status_code, Some(200));
assert_eq!(list.upstream_status_code, Some(200));
let expected_message = error
.get("message")
.and_then(serde_json::Value::as_str)
.filter(|value| !value.is_empty());
assert_eq!(list.upstream_error_message.as_deref(), expected_message);
assert_eq!(list.retry_after_ms, Some(30_000));
assert_eq!(list.retry_after_ms, detail.request.retry_after_ms);
assert_eq!(list.error_origin(), origin, "list: {body}");
assert_eq!(detail.request.error_origin(), origin, "detail: {body}");
}
@@ -437,6 +444,12 @@ async fn usage_error_facts_preserve_recovery_and_validate_saved_close_frames() {
.await
.expect("detail with saved error facts");
assert_eq!(detail.request.websocket_close_code, close_code);
let close_reason = detail
.request
.upstream_error
.as_ref()
.and_then(|error| error.close_reason.as_deref());
assert_eq!(record.upstream_error_message.as_deref(), close_reason);
assert!(detail.request.recovered);
assert_eq!(
detail.request.continuation_unavailable_reason,
@@ -2386,7 +2399,11 @@ async fn admin_observability_adapter_preserves_utc_queries_metrics_costs_and_det
.expect("admin diagnostics")
.items;
assert_eq!(diagnostics[0].key, "acct_observe");
assert_eq!(diagnostics[0].name, "account@example.invalid");
assert_eq!(diagnostics[0].name, "primary");
assert_eq!(
diagnostics[0].account_email.as_deref(),
Some("account@example.invalid")
);
assert_eq!(diagnostics[0].cost_coverage.provider_reported_count, 1);
assert_eq!(diagnostics[0].costs[0].amount.as_str(), "1.25");
@@ -2914,7 +2931,11 @@ async fn observability_queries_preserve_request_account_cost_and_diagnostic_fact
.expect("usage diagnostics")
.items;
assert_eq!(diagnostics[0].key, "acct_observe");
assert_eq!(diagnostics[0].name, "account@example.invalid");
assert_eq!(diagnostics[0].name, "primary");
assert_eq!(
diagnostics[0].account_email.as_deref(),
Some("account@example.invalid")
);
assert_eq!(diagnostics[0].request_count, 3);
assert_eq!(diagnostics[0].success_count, 2);
assert_eq!(diagnostics[0].failure_count, 1);
@@ -715,14 +715,18 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
let now = Utc::now();
let mut alpha = account("acct_alpha", "user-alpha");
alpha.name = "Zulu".to_owned();
alpha.email = Some("alpha@example.invalid".to_owned());
let mut beta = account("acct_beta", "user-beta");
beta.provider_kind = "xai".to_owned();
beta.name = "Team".to_owned();
beta.email = Some("beta@example.invalid".to_owned());
beta.credential_state = CredentialState::Banned;
let mut charlie = account("acct_charlie", "user-charlie");
charlie.name = "Team".to_owned();
charlie.email = Some("charlie@example.invalid".to_owned());
let mut invalid = account("acct_invalid", "user-invalid");
invalid.name = " ".to_owned();
invalid.email = Some("invalid@example.invalid".to_owned());
invalid.credential_state = CredentialState::Invalid;
let mut disabled = account("acct_disabled", "user-disabled");
@@ -850,6 +854,33 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
["acct_charlie", "acct_beta"]
);
let name_page = store
.list_accounts(
AccountListQuery {
page: 1,
page_size: PageSize::new(4).expect("page size"),
provider_kind: None,
group_filter: None,
search: None,
status: None,
sort: Some(AccountSort {
field: AccountSortField::Name,
direction: SortDirection::Desc,
}),
},
Default::default(),
)
.await
.expect("sort accounts by display name");
assert_eq!(
name_page
.items
.iter()
.map(|item| item.account.id.as_str())
.collect::<Vec<_>>(),
["acct_alpha", "acct_charlie", "acct_beta", "acct_invalid"]
);
let last_used_page = store
.list_accounts(
AccountListQuery {
@@ -572,18 +572,17 @@ async fn diagnostics_should_group_same_email_accounts_by_stable_ref() {
.await
.expect("account diagnostics")
.items;
assert_eq!(diagnostics.len(), 2);
assert_eq!(
diagnostics
.iter()
.map(|item| item.key.as_str())
.map(|item| (item.key.as_str(), item.name.as_str()))
.collect::<Vec<_>>(),
vec!["acct_snap_a", "acct_snap_b"]
[("acct_snap_a", "Alpha"), ("acct_snap_b", "Beta")]
);
assert!(
diagnostics
.iter()
.all(|item| item.name == "same@example.invalid")
.all(|item| item.account_email.as_deref() == Some("same@example.invalid"))
);
assert!(diagnostics.iter().all(|item| item.request_count == 1));
@@ -4,6 +4,7 @@ use super::{AntigravityProvider, candidates::Project};
use crate::transport::unsent;
use futures::StreamExt;
use gateway_core::{
account::AccountEligibilityPolicy,
engine::{
AttemptContext,
provider::{
@@ -122,7 +123,13 @@ impl AntigravityProvider {
if deadline.is_elapsed() {
Err(unsent(Kind::Timeout))?;
}
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
.then(|| selected.material.access_token.clone());
let record_failure = async |error| {
let error = match &probe_token {
Some(token) => crate::transport::connection_test_error(error, token),
None => error,
};
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
};
let response = tokio::select! {
@@ -1,10 +1,14 @@
//! 保留上游错误事实与本地来源,敏感凭据不得进入运维正文
use gateway_core::{
error::{ProviderError, ProviderErrorKind as Kind, RawUpstreamError},
error::{
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind,
RawUpstreamError,
},
upstream::UpstreamSendState,
};
use reqwest::{Response, StatusCode};
use serde_json::Value;
use std::time::{Duration, SystemTime};
const MAX_ERROR_BYTES: usize = 64 * 1024;
@@ -73,15 +77,66 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
error.with_raw_upstream_error(RawUpstreamError::new(text))
}
fn retry_info(body: &str) -> Option<Duration> {
let document: serde_json::Value = serde_json::from_str(body).ok()?;
let error = document
/// 连接测试只取 Google 的错误字段,验证链接和其他 metadata 留在受控详情中
pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> ProviderError {
let Some(document) = error
.raw_upstream_error()
.and_then(|raw| serde_json::from_str::<Value>(raw.as_str()).ok())
else {
return error;
};
let Some(failure) = google_error(&document) else {
return error;
};
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo");
let safe_text = |value: &Value| {
value
.as_str()
.filter(|s| {
!s.trim().is_empty()
&& !s.contains("://")
&& (token.is_empty() || !s.contains(token))
})
.map(str::to_owned)
};
let code = info.and_then(|detail| safe_text(&detail["reason"]));
let error_type = safe_text(&failure["status"]);
let message = info
.and_then(|detail| safe_text(&detail["metadata"]["validation_error_message"]))
.or_else(|| safe_text(&failure["message"]));
if code.is_none() && error_type.is_none() && message.is_none() {
return error;
}
let message = message.unwrap_or_else(|| {
GatewayError::from_provider(&error)
.safe_message()
.to_owned()
});
error.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
message, code, error_type,
))
}
fn google_error(document: &Value) -> Option<&Value> {
document
.get("error")
.or_else(|| document.pointer("/response/error"))?;
let detail = error.get("details")?.as_array()?.iter().find(|detail| {
detail.get("@type").and_then(serde_json::Value::as_str)
== Some("type.googleapis.com/google.rpc.RetryInfo")
})?;
.or_else(|| document.pointer("/response/error"))
}
fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
error
.get("details")?
.as_array()?
.iter()
.find(|detail| detail["@type"] == kind)
}
fn retry_info(body: &str) -> Option<Duration> {
let document: Value = serde_json::from_str(body).ok()?;
let detail = google_error_detail(
google_error(&document)?,
"type.googleapis.com/google.rpc.RetryInfo",
)?;
let delay = detail.get("retryDelay")?.as_str()?.strip_suffix('s')?;
let (seconds, fraction) = delay.split_once('.').unwrap_or((delay, ""));
if seconds.is_empty()
@@ -12,7 +12,7 @@ mod signatures;
mod tool_ids;
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
pub(crate) use count::count_events;
pub(crate) use failure::{sent, unsent};
pub(crate) use failure::{connection_test_error, sent, unsent};
pub(crate) use headers::request_headers;
pub(crate) use pool::ClientPool;
pub(crate) use response::{ResponseContext, events};
@@ -455,6 +455,75 @@ async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
released(&fixture).await;
}
#[tokio::test]
async fn connection_probe_reports_google_rejection_without_verification_links() {
let details = json!([{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "VALIDATION_REQUIRED",
"metadata": {"validation_error_message": "Complete SMS verification.", "validation_url": "https://accounts.example.test/verify?nonce=private"}
}]);
for (status, body, reason, message) in [
(401, json!({}), None, None),
(
403,
json!({"error":{"status":"PERMISSION_DENIED","message":"Access denied."}}),
None,
Some("Access denied."),
),
(
403,
json!({"error":{"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":details}}),
Some("VALIDATION_REQUIRED"),
Some("Complete SMS verification."),
),
(
403,
json!({"error":{"message":"fixture-access","details":details}}),
None,
None,
),
] {
let upstream = MockServer::start().await;
Mock::given(path("/v1internal:loadCodeAssist"))
.respond_with(ResponseTemplate::new(status).set_body_json(body))
.expect(1)
.mount(&upstream)
.await;
let fixture = Fixture::new(&upstream.uri());
let account = fixture
.store
.primary()
.loaded
.lock()
.unwrap()
.account
.id()
.clone();
let error = fixture
.provider
.clone()
.execute(
request(false),
diagnostic_context(AccountProbeTarget::ConnectionTest(account)),
)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.expect_err("Google rejected the project lookup");
assert_eq!(error.upstream_status(), Some(status));
let visible = error.client_visible_upstream_error();
assert_eq!(visible.and_then(|e| e.code()), reason);
assert_eq!(visible.map(|e| e.message()), message);
assert_eq!(
visible.and_then(|e| e.error_type()),
message.map(|_| "PERMISSION_DENIED")
);
assert!(error.client_visible_upstream_response().is_none());
released(&fixture).await;
}
}
#[tokio::test]
async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() {
for (status, kind) in [
@@ -1,5 +1,6 @@
//! 额度桶重置后的延迟预热、使用证据复核和持久化领取
use super::snapshot::BucketUseTime;
use super::*;
use chrono::{DateTime, Utc};
use gateway_core::account::QuotaWarmupStateUpdate;
@@ -11,30 +12,49 @@ const RESET_WARMUP_DELAY_SECONDS: i64 = 5 * 60;
struct BucketProgress {
reset_at: Option<i64>,
completed_reset_at: Option<i64>,
last_warmup_at: Option<i64>,
last_warmup_at: Option<BucketUseTime>,
#[serde(skip_serializing_if = "Option::is_none")]
credit_reset: Option<CreditReset>,
retry_at: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct CreditReset {
started_at: DateTime<Utc>,
previous_window_end: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct LastRedemption {
request_id: String,
credit_id: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
struct WarmupProgress {
#[serde(skip_serializing_if = "Option::is_none")]
last_redemption: Option<LastRedemption>,
#[serde(default)]
buckets: BTreeMap<String, BucketProgress>,
}
fn enabled_windows<'a>(
account: &'a ProviderAccount,
snapshot: &'a CodexAccountQuotaSnapshot,
) -> impl Iterator<Item = &'a CodexQuotaWindow> {
snapshot.windows().iter().filter(|window| {
window.is_account_wide()
&& account
.quota_settings()
.iter()
.any(|(key, settings)| key == window.key() && settings.warmup.is_some())
})
}
impl WarmupProgress {
fn reconcile(&mut self, account: &ProviderAccount, snapshot: &CodexAccountQuotaSnapshot) {
for (key, settings) in account.quota_settings().iter() {
if settings.warmup.is_none() {
continue;
}
let Some(window) = snapshot
.windows()
.iter()
.find(|window| window.is_account_wide() && window.key() == key)
else {
continue;
};
let progress = self.buckets.entry(key.to_owned()).or_default();
for window in enabled_windows(account, snapshot) {
let progress = self.buckets.entry(window.key().to_owned()).or_default();
let observed_reset = window.reset_at().map(|at| at.timestamp());
if let Some(reset) = progress.reset_at {
let last_use = snapshot
@@ -44,9 +64,19 @@ impl WarmupProgress {
.into_iter()
.chain(progress.last_warmup_at)
.max();
let newly_used = last_use.is_some_and(|used| used >= reset)
|| (observed_reset.is_some_and(|next| next > reset)
&& DateTime::<Utc>::from(snapshot.observed_at()).timestamp() >= reset
let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
let used_after_reset = last_use.is_some_and(|used| match &progress.credit_reset {
Some(credit) => used.0 >= credit.started_at,
None => used.0.timestamp() >= reset,
});
let previous_end = progress
.credit_reset
.as_ref()
.and_then(|credit| credit.previous_window_end)
.unwrap_or(reset);
let newly_used = used_after_reset
|| (observed_reset.is_some_and(|next| next > previous_end)
&& observed_at.timestamp() >= reset
&& window.used_percent().is_some_and(|used| used > 0.0));
if newly_used {
progress.complete(reset);
@@ -65,6 +95,29 @@ impl WarmupProgress {
}
}
fn register_weekly_reset(
&mut self,
account: &ProviderAccount,
snapshot: &CodexAccountQuotaSnapshot,
started_at: DateTime<Utc>,
confirmed_at: i64,
) -> bool {
let mut registered = false;
for window in
enabled_windows(account, snapshot).filter(|w| w.kind() == CodexQuotaWindowKind::Weekly)
{
let bucket = self.buckets.entry(window.key().to_owned()).or_default();
bucket.reset_at = Some(confirmed_at);
bucket.retry_at = None;
bucket.credit_reset = Some(CreditReset {
started_at,
previous_window_end: window.reset_at().map(|at| at.timestamp()),
});
registered = true;
}
registered
}
fn due(&self, account: &ProviderAccount, now: DateTime<Utc>) -> Vec<(String, String, i64)> {
account
.quota_settings()
@@ -88,6 +141,7 @@ impl BucketProgress {
fn complete(&mut self, reset: i64) {
self.completed_reset_at = Some(self.completed_reset_at.map_or(reset, |old| old.max(reset)));
self.reset_at = None;
self.credit_reset = None;
self.retry_at = None;
}
}
@@ -131,6 +185,56 @@ impl CodexCredentialQuotaService {
.await?)
}
pub(super) async fn register_weekly_reset(
&self,
original: &ProviderAccount,
started_at: DateTime<Utc>,
request_id: Uuid,
credit_id: Option<&str>,
) -> Result<(), CodexCredentialQuotaError> {
if !original.quota_settings().has_warmup() {
return Ok(());
}
let request_id = request_id.to_string();
let confirmed_at = Utc::now().timestamp();
for _ in 0..QUOTA_MERGE_ATTEMPTS {
let Some(account) = self.store.get_account(original.id()).await? else {
return Ok(());
};
if account.revision() != original.revision()
|| !warmup::warmup_account_is_available(&account)
{
return Ok(());
}
let Some(snapshot) = self.read_snapshot_for(&account).await? else {
return Ok(());
};
let Some((version, mut progress)) = self.read_warmup_progress(&account).await? else {
return Ok(());
};
if progress.last_redemption.as_ref().is_some_and(|last| {
last.request_id == request_id
|| (credit_id.is_some() && last.credit_id.as_deref() == credit_id)
}) {
return Ok(());
}
if !progress.register_weekly_reset(&account, &snapshot, started_at, confirmed_at) {
return Ok(());
}
progress.last_redemption = Some(LastRedemption {
request_id: request_id.clone(),
credit_id: credit_id.map(str::to_owned),
});
if self
.write_warmup_progress(&account, &snapshot, version, &progress)
.await?
{
return Ok(());
}
}
Err(CodexCredentialQuotaError::RevisionConflict)
}
/// 与 Cron 共用同一受租约保护的 worker,每次周期独立于全局 Cron 开关
pub async fn execute_bucket_warmup_at(
&self,
@@ -192,7 +296,8 @@ impl CodexCredentialQuotaService {
let Some(current) = self.store.get_account(account.id()).await? else {
return Ok(None);
};
if !warmup::warmup_account_is_available(&current)
if account.revision() != current.revision()
|| !warmup::warmup_account_is_available(&current)
|| current.quota().is_exhausted()
|| current.quota_paused()
|| !access_token_is_current(&current, SystemTime::now())
@@ -217,12 +322,16 @@ impl CodexCredentialQuotaService {
.as_ref()
.is_some_and(|warmup| warmup.model == *model)
})
&& progress
.buckets
.get(key)
.is_some_and(|bucket| bucket.reset_at == Some(*reset))
&& snapshot.windows().iter().any(|window| {
window.is_account_wide() && window.key() == key && !window.limit_reached()
&& progress.buckets.get(key).is_some_and(|bucket| {
bucket.reset_at == Some(*reset)
&& snapshot.windows().iter().any(|window| {
window.is_account_wide()
&& window.key() == key
&& !window.limit_reached()
&& (bucket.credit_reset.is_none()
|| (window.reset_at().is_some()
&& window.used_percent() == Some(0.0)))
})
})
&& current.model_access().allows(model)
});
@@ -272,19 +381,12 @@ impl CodexCredentialQuotaService {
return Ok(());
};
progress.reconcile(account, &snapshot);
for (key, settings) in account.quota_settings().iter() {
if settings.warmup.is_some()
&& snapshot
.windows()
.iter()
.any(|window| window.is_account_wide() && window.key() == key)
{
progress
.buckets
.entry(key.to_owned())
.or_default()
.last_warmup_at = Some(now.timestamp());
}
for window in enabled_windows(account, &snapshot) {
progress
.buckets
.entry(window.key().to_owned())
.or_default()
.last_warmup_at = Some(BucketUseTime(now));
}
progress.reconcile(account, &snapshot);
if self
@@ -208,9 +208,7 @@ fn merge_passive_quota(
if let Some(usage) = usage.as_object_mut() {
usage.insert(
active_limit.clone(),
serde_json::json!(
chrono::DateTime::<chrono::Utc>::from(used_at).timestamp()
),
serde_json::json!(chrono::DateTime::<chrono::Utc>::from(used_at)),
);
}
}
@@ -170,7 +170,8 @@ impl CodexCredentialQuotaService {
credential,
};
let request_id = format!("reset_credit_consume_{}", Uuid::now_v7().simple());
consume_reset_credit_once(
let started_at = chrono::Utc::now();
let result = consume_reset_credit_once(
&client,
&prepared,
&request_id,
@@ -178,7 +179,28 @@ impl CodexCredentialQuotaService {
redeem_request_id,
)
.await
.map_err(|error| map_reset_credit_attempt_error(error, true))
.map_err(|error| map_reset_credit_attempt_error(error, true))?;
if matches!(result.code.as_str(), "reset" | "already_redeemed")
&& let Err(error) = self
.register_weekly_reset(
&prepared.account,
started_at,
redeem_request_id,
result
.credit
.as_ref()
.map(|card| card.id.as_str())
.or(credit_id),
)
.await
{
tracing::warn!(
account_id = %account_id,
error = %error,
"OpenAI quota bucket warmup after reset-credit consume failed"
);
}
Ok(result)
}
async fn reset_credit_account(
@@ -12,6 +12,7 @@ use gateway_core::account::{
QuotaEvidence, QuotaObservation, QuotaResetPeriod, QuotaState,
};
use gateway_protocol::openai::events::{CreditsSnapshot, parse_credits_from_object};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::document::{
@@ -110,6 +111,27 @@ impl CodexQuotaWindow {
}
}
/// 自然窗口按整秒划界,用卡操作还需区分同一秒内先后的使用
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub(super) struct BucketUseTime(pub(super) DateTime<Utc>);
impl<'de> Deserialize<'de> for BucketUseTime {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Stored {
Precise(DateTime<Utc>),
Seconds(i64),
}
match Stored::deserialize(deserializer)? {
Stored::Precise(at) => Ok(Self(at)),
Stored::Seconds(at) => DateTime::from_timestamp(at, 0)
.map(Self)
.ok_or_else(|| serde::de::Error::custom("invalid bucket use timestamp")),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CodexAccountQuotaSnapshot {
account_id: ProviderAccountId,
@@ -122,7 +144,7 @@ pub struct CodexAccountQuotaSnapshot {
quota: QuotaState,
windows: Vec<CodexQuotaWindow>,
unconfirmed_limits: BTreeMap<String, f64>,
pub(super) last_used_at: BTreeMap<String, i64>,
pub(super) last_used_at: BTreeMap<String, BucketUseTime>,
pub(super) recovery: Option<QuotaRecovery>,
}
@@ -449,7 +471,9 @@ pub(crate) fn parse_account_quota_snapshot(
.map(|usage| {
usage
.iter()
.filter_map(|(source, at)| Some((source.clone(), at.as_i64()?)))
.filter_map(|(source, at)| {
Some((source.clone(), BucketUseTime::deserialize(at).ok()?))
})
.collect()
})
.unwrap_or_default(),
@@ -8,6 +8,18 @@ async fn setup() -> (
MockServer,
chrono::DateTime<Utc>,
i64,
) {
setup_window(-300, 0).await
}
async fn setup_window(
seconds_until_reset: i64,
used: u64,
) -> (
Arc<MemoryAccountStore>,
MockServer,
chrono::DateTime<Utc>,
i64,
) {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_bucket_warmup").await;
@@ -19,9 +31,12 @@ async fn setup() -> (
.unwrap(),
);
let now = Utc::now();
let reset = now.timestamp() - 300;
let reset = now.timestamp() + seconds_until_reset;
let account = store.account("acct_bucket_warmup").unwrap();
let observed_at = SystemTime::from(Utc.timestamp_opt(reset - 60, 0).unwrap());
let observed_at = SystemTime::from(
Utc.timestamp_opt(reset.min(now.timestamp()) - 60, 0)
.unwrap(),
);
store
.compare_and_swap_quota(QuotaObservation {
quota_pause: None,
@@ -29,7 +44,7 @@ async fn setup() -> (
plan_type: None,
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(usage(reset, 0).as_object().unwrap().clone()),
quota: OpaqueProviderData::new(usage(reset, used).as_object().unwrap().clone()),
observed_at,
state: QuotaState::allowed(observed_at),
})
@@ -267,3 +282,243 @@ async fn pre_reset_usage_and_arbitrary_general_window_still_warm_up() {
1
);
}
async fn mount_consume(server: &MockServer, code: &str, card: Option<&str>) {
Mock::given(method("POST"))
.and(path("/api/codex/rate-limit-reset-credits/consume"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"code": code,
"credit": card.map(|id| json!({"id": id, "reset_type": "codex_rate_limits"}))
})))
.expect(1)
.mount(server)
.await;
}
#[tokio::test]
async fn rounded_request_in_idle_window_keeps_the_registered_boundary() {
let (store, server, now, _) = setup_window(3 * 86400, 0).await;
let quota = service(&store, &server);
quota.execute_bucket_warmup_at(now).await.unwrap();
observe_request(&quota, &store, now.timestamp() + 604800, false).await;
assert_eq!(
quota
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
.await
.unwrap()
.warmed_up,
0
);
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn rounded_request_in_the_natural_reset_second_skips_warmup() {
let (store, server, now, reset) = setup().await;
let quota = service(&store, &server);
quota
.execute_bucket_warmup_at(Utc.timestamp_opt(reset - 1, 0).unwrap())
.await
.unwrap();
let account = store.account("acct_bucket_warmup").unwrap();
let mut document = usage(reset + 604800, 0);
document["_cpr_bucket_last_used_at"] = json!({"codex": reset});
let observed_at = SystemTime::from(Utc.timestamp_opt(reset, 500_000_000).unwrap());
store
.compare_and_swap_quota(QuotaObservation {
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(document.as_object().unwrap().clone()),
observed_at,
state: QuotaState::allowed(observed_at),
quota_pause: None,
expected_connection: None,
plan_type: None,
})
.await
.unwrap();
assert_eq!(
quota.execute_bucket_warmup_at(now).await.unwrap().warmed_up,
0
);
assert!(server.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn confirmed_credit_retries_the_quota_check_after_restart() {
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
let quota = service(&store, &server);
quota.execute_bucket_warmup_at(now).await.unwrap();
let account = store.account("acct_bucket_warmup").unwrap();
let key = uuid::Uuid::new_v4();
mount_consume(&server, "reset", None).await;
quota
.consume_reset_credit(account.id(), Some("credit_1"), key)
.await
.unwrap();
let confirmed = Utc::now();
quota
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(4))
.await
.unwrap();
assert_eq!(server.received_requests().await.unwrap().len(), 1);
server.reset().await;
let outage = Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(ResponseTemplate::new(400))
.expect(1)
.mount_as_scoped(&server)
.await;
let first = quota
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(5))
.await
.unwrap();
assert_eq!(first.failed, 1);
drop(outage);
let restarted = service(&store, &server);
mount_usage(&server, now.timestamp() + 604800, 0, 1).await;
mount_warmup(&server, 1).await;
assert_eq!(
restarted
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(9))
.await
.unwrap()
.warmed_up,
0
);
assert_eq!(
restarted
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(10))
.await
.unwrap()
.warmed_up,
1
);
}
#[tokio::test]
async fn latest_credit_retries_keep_the_claim_and_new_credits_can_warm_up() {
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
let account = store.account("acct_bucket_warmup").unwrap();
let first_key = uuid::Uuid::new_v4();
for (code, key, requested_card, returned_card, expected) in [
("reset", first_key, None, Some("first"), 1),
("already_redeemed", first_key, None, None, 0),
(
"already_redeemed",
uuid::Uuid::new_v4(),
Some("first"),
None,
0,
),
("reset", uuid::Uuid::new_v4(), None, None, 1),
("reset", uuid::Uuid::new_v4(), None, None, 1),
] {
let quota = service(&store, &server);
mount_consume(&server, code, returned_card).await;
mount_usage(&server, now.timestamp() + 604800, 0, expected).await;
mount_warmup(&server, expected).await;
quota
.consume_reset_credit(account.id(), requested_card, key)
.await
.unwrap();
let summary = quota
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
.await
.unwrap();
assert_eq!(summary.warmed_up, expected);
server.verify().await;
server.reset().await;
}
}
#[tokio::test]
async fn rounded_request_after_credit_consume_skips_warmup() {
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
let quota = service(&store, &server);
let account = store.account("acct_bucket_warmup").unwrap();
mount_consume(&server, "reset", None).await;
quota
.consume_reset_credit(account.id(), None, uuid::Uuid::new_v4())
.await
.unwrap();
observe_request(&quota, &store, now.timestamp() + 604800, false).await;
assert_eq!(
quota
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
.await
.unwrap()
.warmed_up,
0
);
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
#[tokio::test]
async fn reset_credit_consume_skips_warmup_when_new_cycle_already_has_usage() {
let (store, server, now, _) = setup_window(3 * 86400, 80).await;
let quota = service(&store, &server);
assert_eq!(
quota.execute_bucket_warmup_at(now).await.unwrap().warmed_up,
0
);
mount_consume(&server, "reset", None).await;
mount_usage(&server, now.timestamp() + 7 * 24 * 60 * 60, 1, 1).await;
mount_warmup(&server, 0).await;
quota
.consume_reset_credit(
&store.account("acct_bucket_warmup").unwrap().id().clone(),
None,
uuid::Uuid::new_v4(),
)
.await
.unwrap();
assert_eq!(
quota
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
.await
.unwrap()
.warmed_up,
0
);
}
#[tokio::test]
async fn reset_credit_consume_starts_warmup_after_previous_cycle_was_completed() {
let (store, server, _, reset) = setup().await;
let quota = service(&store, &server);
// 先登记并完成本轮(窗口已到期且已有使用证据时跳过预热),再消费重置卡开启新窗口
quota
.execute_bucket_warmup_at(Utc.timestamp_opt(reset - 1, 0).unwrap())
.await
.unwrap();
observe_request(&quota, &store, reset + 604800, false).await;
mount_consume(&server, "already_redeemed", None).await;
mount_usage(&server, Utc::now().timestamp() + 7 * 24 * 60 * 60, 0, 1).await;
mount_warmup(&server, 1).await;
quota
.consume_reset_credit(
&store.account("acct_bucket_warmup").unwrap().id().clone(),
None,
uuid::Uuid::new_v4(),
)
.await
.unwrap();
assert_eq!(
quota
.execute_bucket_warmup_at(Utc::now())
.await
.unwrap()
.warmed_up,
0
);
assert_eq!(
quota
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
.await
.unwrap()
.warmed_up,
1
);
}
+10 -6
View File
@@ -918,8 +918,8 @@ OpenAI 仅在允许安全重放且尚未交付不可重放输出时执行下表
投影为 `server_error`,HTTP 错误状态及 WS 包装错误的数字状态投影为 `503`,让客户端执行自己的
有界重试。Provider 已确认容量不足的初始失败,即使没有这两个错误码,也返回 `503`。
SSE/WS 的 `response.failed` 保留原消息、响应 ID 与其他业务字段;客户端无法消费的裸 `error`
继续按现有规则投影为 `response.failed`。容量错误的 `Retry-After`、`retry-after-ms` 从响应头及错误事件的
headers 中移除,避免客户端再次等待旧账号;关联 ID 等其他响应头保留,其他错误码不受影响。
继续按现有规则投影为 `response.failed`。最终返回容量错误或因容量不足换号后要求客户端重放时,
HTTP 响应头与 SSE/WS 错误事件保留上游提供的 `Retry-After` 和 `retry-after-ms`。
内部上游状态、等待提示、错误码、原始事件及计量事实保持不变;已开始输出的请求由
客户端决定如何恢复,代理不因此重放已提交的请求。
`flex_unavailable` 是当前请求的终止拒绝,保留原始错误,不自动重试、切换传输或冷却账号
@@ -1323,7 +1323,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
- `provider`: `openai` 或 `xai`,省略或空值表示不过滤
- `groupId`: 分组 ID、`ungrouped`,或省略以不过滤
- `status`: `normal`、`quota_paused`、`quota_exhausted`、`rate_limited`、`disabled`、`error`
- `sortBy`: `email`、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
- `sortBy`: `name`(显示名称,缺失时依次使用邮箱、上游账号 ID、本地 ID)、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
- `sortDirection`: `asc`、`desc`
账号列表的 `search` 仅按字面量包含匹配名称和邮箱,不区分大小写;`%`、`_` 和 `\` 按普通字符处理
@@ -1366,6 +1366,7 @@ OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `PO
该轮存在对应通用桶的请求使用证据或新窗口非零用量时跳过,不把重置前的使用或具名桶用量算入本轮。
正常请求的额度反馈即使用量取整为 0% 也保留使用证据,主动额度刷新不会清除;成功的账号预热同样计入。
无重置时间时等待后续观测,不通过空闲窗口滚动的倒计时推迟已登记的边界。
手动或自动用卡确认成功后,已开启预热的通用周桶从确认时间起满 5 分钟复查。额度恢复且本轮空闲时才发送,重试最近一次用卡时沿用原预热进度。
同批到期的通用窗口合并一次请求,领取进度跨重启保留;已领取请求发生超时或取消时不自动重放。
账号停用、凭据不可用、额度耗尽或达到调度上限时不执行;复查失败最多每 5 分钟重查
@@ -1647,8 +1648,9 @@ OAuth 等待回调期间允许修改代理。提交时若代理已删除、停
`unreachable` 表示无法连接代理端点,`tunnel_failed` 表示代理隧道协商失败。
`check_proxy` 表示本次使用代理且建连失败,不能据此判定故障在代理;无提示时为 `null`
- `sendState` 为 `not_sent`、`sent`、`ambiguous`,非 Provider 错误为 `null`
- `error`、`providerErrorCode`、`providerErrorType`、`upstreamStatus`、`upstreamContentType` 和
`upstreamBody` 是实际捕获的原始诊断字段;缺失时为 `null`,不会由本地猜测或翻译
- `upstreamStatus` 可单独返回;`upstreamContentType` 和 `upstreamBody` 仅在有可展示的原始响应时返回
- Antigravity 的 `providerErrorCode` 取 Google ErrorInfo 的 `reason`,`providerErrorType` 取 Google 的 `status`。
`error` 优先展示可安全返回的上游消息,缺失时使用网关提示。验证链接不随连接测试返回
### 后台导入任务
@@ -3147,7 +3149,8 @@ Client Key 的频率、并发和费用预算限制分别为 `key_rate_limited`
或 WS 关闭帧的 `closeReason`、`lastEventType`;不重新分类错误,也不包含原始请求、任意响应头或本地原因链。
缺失、非 JSON 或未识别的结构返回 `null`,完整受控诊断通过诊断包获取。
详情的 `message` 是网关摘要,不等同于上游 `upstreamError.message`;
`retryAfterMs` 是已记录的重试等待毫秒数,未记录时为 `null`
列表的 `upstreamErrorMessage` 优先取上游消息,其次取 WS 关闭原因,两者缺失时为 `null`。
列表与详情的 `retryAfterMs` 是已记录的重试等待毫秒数,未记录时为 `null`
详情 `attempts[].downstreamCommitted` 为 `true` 时表示已开始客户端响应,为 `false` 时表示未开始。
中间尝试的运维事件未保存交付边界,返回 `null`;不能据此推断客户端尚未收到响应
@@ -3161,6 +3164,7 @@ Client Key 的频率、并发和费用预算限制分别为 `key_rate_limited`
使用记录列表和错误排查列表的 `accountPlanType` / `accountPlanTypeDisplay` 来自记录保存的账号订阅快照。
Antigravity 的展示名取自请求时已观测到的 Google 套餐描述,快照缺少描述时为 `null`
账号维度诊断按账号 ID 分组,`name` 依次取最近请求快照的账号名称、邮箱和账号 ID,`accountEmail` 返回快照邮箱,其他维度为 `null`。
账号维度诊断使用该账号最近请求的订阅快照,并通过 `authenticationKind` 返回同一请求的认证类型快照;未保存的字段为 `null`,非账号维度的认证类型为 `null`
管理端请求列表及 Dashboard 最近请求中的 `accountNotes` 来自请求保存的账号备注快照,未保存时为 `null`
+2 -1
View File
@@ -811,7 +811,7 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交
正常 native 续接仍由连接池核对原连接及 response ID 是否可用
- 原生续接的安全容量拒绝超过服务器建议等待上限时,Core 在换号预算内发起 `RotateForClientReplay`。
OpenAI 仅通过既有选号器迁移会话绑定并释放租约,不发送当前增量输入;客户端收到完整历史重放指令后开启新链。
无替代账号时保留原失败;API 移除容量错误的客户端等待提示,诊断仍保留原始错误与建议等待
无替代账号时返回容量错误。两种客户端响应均保留上游的重试等待头
- xAI 的续接状态只携带账号与 session ID;原生续接失效或进入重放阶段时返回 `ClientReplayRequired`,由客户端携带完整历史重发
- scope 外账号与跨 Key 复用均拒绝;发送结果不明时,仅接受 Provider 明确给出的有界传输恢复意图
@@ -1150,6 +1150,7 @@ OpenAI 响应头的额度窗口按头名前缀归属,普通 Responses 的 `x-c
按桶预热由 OpenAI Provider 解释重置时间、五分钟延迟和本轮使用证据,与 Cron 共用已有预热 worker 和单账号发送逻辑。
请求使用时间按额度来源保留在 Provider 额度正文,未产生实际输出的失败响应只更新额度事实;刷新 `/usage` 保留本地使用证据。
Store 在账号行独立保存不透明预热进度,通过凭据版本、配置、额度快照版本及账号状态原子领取,不推进配置版本。
用卡确认后,OpenAI Provider 将最近一次消费的请求 ID 和可用的卡片 ID 随周桶预热进度一起保存,用于识别本次消费的重试。
已领取的请求不因超时、取消或重启重放;普通凭据续期保留进度,身份替换或额度事实失效时同步失效进度
OpenAI Provider 统一解释点数可用性,主动查询、耗尽恢复与失败回读复用同一规则。
+1 -1
View File
@@ -16,7 +16,7 @@
"build:source": "vue-tsc -p tsconfig.source.json --noEmit && vite build --mode source"
},
"dependencies": {
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#5f38c8bacd53e4669c0cfa57b961c8d97085ff9f",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#09de193d1f1ff785b07713e0ccea98d35ebb0222",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lobehub/icons-vue": "1.2.0",
+5 -5
View File
@@ -192,8 +192,8 @@ importers:
.:
dependencies:
'@codex-proxy/ui':
specifier: github:zyycn/codex-proxy-ui#5f38c8bacd53e4669c0cfa57b961c8d97085ff9f
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5f38c8bacd53e4669c0cfa57b961c8d97085ff9f(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
specifier: github:zyycn/codex-proxy-ui#09de193d1f1ff785b07713e0ccea98d35ebb0222
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
'@fontsource-variable/inter':
specifier: ^5.3.0
version: 5.3.0
@@ -451,8 +451,8 @@ packages:
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
engines: {node: '>= 20.12.0'}
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5f38c8bacd53e4669c0cfa57b961c8d97085ff9f':
resolution: {gitHosted: true, integrity: sha512-mwiaZaxYlA2MeAErOGCr5MlsLmxJSTySEA9fUErfaAFl0AZoaIsfTo+Bd6L+x8/kTL5xRIK8VVfju2MQXqNPrA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5f38c8bacd53e4669c0cfa57b961c8d97085ff9f}
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222':
resolution: {gitHosted: true, integrity: sha512-LQmVPnJgE6dHwQcKRpcJ3lS5uzyEVvugcfr4+kwbBU2VnoMcMII27oi/ukYXMUil73gvjX42OFwwCA16Y1HMyg==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222}
version: 0.14.0
engines: {node: '>=24'}
peerDependencies:
@@ -3559,7 +3559,7 @@ snapshots:
fast-wrap-ansi: 0.2.2
sisteransi: 1.0.5
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5f38c8bacd53e4669c0cfa57b961c8d97085ff9f(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
dependencies:
'@ant-design/colors': 8.0.1
'@ant-design/fast-color': 3.0.1
+3 -1
View File
@@ -87,6 +87,7 @@ export interface UsageErrorFacts {
errorCode: string | null
errorKind: string | null
websocketCloseCode: number | null
retryAfterMs: number | null
continuationUnavailableReason: string | null
upstreamConnectionExitReason: string | null
recovered: boolean
@@ -98,6 +99,7 @@ export interface UsageListRecord extends UsageErrorFacts {
clientStatusCode: number | null
upstreamStatusCode: number | null
errorMessage: string | null
upstreamErrorMessage: string | null
clientApiKeyName: string | null
id: string
provider: string | null
@@ -140,7 +142,6 @@ export interface UsageRecord extends UsageErrorFacts {
closeReason: string | null
lastEventType: string | null
} | null
retryAfterMs: number | null
id: string
requestId: string
clientApiKeyId: string | null
@@ -387,6 +388,7 @@ export interface UsageDiagnosticItem {
platformIcon: string | null
key: string
name: string
accountEmail: string | null
authenticationKind: string | null
accountPlanType: string | null
accountPlanTypeDisplay: string | null
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { UsageAccountIdentity } from './presenter'
import { computed } from 'vue'
import { usageAccountDisplay } from './presenter'
const props = defineProps<{ record: UsageAccountIdentity }>()
const display = computed(() => usageAccountDisplay(props.record))
</script>
<template>
<span class="block max-w-full truncate text-z-sm leading-none font-bold text-z-text">
{{ display.primary }}
</span>
<span v-if="display.secondary" class="mt-1 block max-w-full truncate font-mono text-z-xs text-z-text-secondary">
{{ display.secondary }}
</span>
</template>
@@ -4,7 +4,8 @@ import { ZPopover, ZScrollbar } from '@codex-proxy/ui'
import { CheckCheck, CircleHelp, Network, Server, Unplug } from '@lucide/vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { usageErrorOrigin, usageErrorSummary, usageErrorTitle } from './errors'
import { formatDuration } from '@/utils/format'
import { usageErrorMessage, usageErrorOrigin, usageErrorSummary, usageErrorTitle } from './errors'
const props = defineProps<{ record: UsageListRecord }>()
@@ -16,11 +17,12 @@ const originIcons = {
}
const { t } = useI18n({ useScope: 'global' })
const code = computed(() => props.record.errorCode || props.record.errorKind)
const errorType = computed(() => props.record.errorKind || props.record.errorCode)
const origin = computed(() => usageErrorOrigin(props.record))
const outcome = computed(() => usageErrorTitle(props.record))
const summary = computed(() => usageErrorSummary(props.record))
const message = computed(() => usageErrorMessage(props.record, props.record.errorMessage, props.record.upstreamErrorMessage))
</script>
<template>
@@ -65,14 +67,19 @@ const summary = computed(() => usageErrorSummary(props.record))
</template>
<ZScrollbar class="w-max max-w-[min(26rem,calc(100vw-2rem))]" max-height="min(18rem, 60dvh)">
<div class="grid gap-1 px-3 py-2 text-z-sm leading-relaxed whitespace-pre-wrap select-text wrap-anywhere" translate="no">
<code v-if="code" class="font-mono font-emphasis">{{ code }}</code>
<span v-if="record.errorKind && record.errorKind !== code">
{{ t('usage.error.failureClassification') }} · <code>{{ record.errorKind }}</code>
<span v-if="record.errorKind">
{{ t('usage.error.failureClassification') }} · <code class="font-emphasis">{{ record.errorKind }}</code>
</span>
<span v-if="record.errorCode && record.errorCode !== record.errorKind">
{{ t('usage.error.errorCode') }} · <code>{{ record.errorCode }}</code>
</span>
<span v-if="record.websocketCloseCode != null">
{{ t('usage.error.websocketCloseCode') }} · <code>{{ record.websocketCloseCode }}</code>
</span>
<span>{{ record.errorMessage || t('usage.error.noDetails') }}</span>
<span v-if="record.retryAfterMs != null">
{{ t('usage.error.retryAfter') }} · <code>{{ formatDuration(record.retryAfterMs) }}</code>
</span>
<span>{{ t('usage.error.errorMessage') }} · {{ message }}</span>
</div>
</ZScrollbar>
</ZPopover>
@@ -1,4 +1,4 @@
import type { UsageErrorFacts, UsageListRecord } from '@/api'
import type { UsageErrorFacts, UsageListRecord, UsageRecord } from '@/api'
import { t } from '@/i18n'
export type UsageErrorRecord = UsageErrorFacts & {
@@ -56,6 +56,29 @@ export function usageSendStateText(state: string) {
}
}
function gatewayErrorMessage(kind: string | null, message: string | null) {
if (kind === 'process_interrupted') {
if (message === 'request did not reach a terminal state')
return t('usage.error.processInterrupted')
if (message === 'request recovery lease is missing')
return t('usage.error.requestTrackingLost')
}
return message
}
export function usageErrorMessage(
record: Pick<UsageRecord, 'errorKind' | 'logicalOutcome'>,
message: string | null,
upstreamMessage: string | null | undefined,
) {
if (upstreamMessage)
return upstreamMessage
const saved = message?.trim()
return saved && saved !== record.logicalOutcome
? gatewayErrorMessage(record.errorKind, saved.replace(/^OpenAI upstream failure: /, ''))
: t('usage.error.noDetails')
}
export function usageErrorSummary(record: UsageListRecord): string {
const reason = usageErrorReason(record.errorKind) || usageErrorReason(record.errorCode)
if (reason)
@@ -71,7 +94,7 @@ export function usageErrorSummary(record: UsageListRecord): string {
if (record.errorKind === 'upstream_unavailable' && upstreamClosed)
return t('usage.error.upstreamConnectionClosed')
return record.errorMessage || record.errorCode || record.errorKind
return gatewayErrorMessage(record.errorKind, record.errorMessage) || record.errorCode || record.errorKind
|| (record.websocketCloseCode != null
? `WS ${record.websocketCloseCode}`
: t('usage.error.noDetails'))
@@ -7,10 +7,8 @@ import { ZTable } from '@codex-proxy/ui'
import { useI18n } from 'vue-i18n'
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
import {
usageAccountText,
usageUserAgent,
} from './presenter'
import { usageUserAgent } from './presenter'
import UsageAccountCell from './UsageAccountCell.vue'
import UsageBillingCell from './UsageBillingCell.vue'
import UsageClientIpCell from './UsageClientIpCell.vue'
import UsageErrorCell from './UsageErrorCell.vue'
@@ -63,11 +61,7 @@ const { t } = useI18n({ useScope: 'global' })
</template>
<template #accountEmail="{ row }">
<span
class="block max-w-full truncate font-mono text-z-sm leading-none font-bold text-z-text"
>
{{ usageAccountText(row) }}
</span>
<UsageAccountCell :record="row" />
<span
v-if="row.accountNotes?.trim()"
class="mt-1 block max-w-full truncate text-z-xs font-emphasis text-z-text-quaternary"
@@ -64,8 +64,24 @@ export function usageTransportTypeClass(transport?: string | null) {
return 'bg-z-fill-tertiary text-z-text-secondary'
}
export function usageAccountText(record: Pick<UsageCommonRecord, 'accountEmail' | 'accountName' | 'accountId'>) {
return record.accountEmail || record.accountName || record.accountId || '—'
export type UsageAccountIdentity = Pick<UsageCommonRecord, 'accountName' | 'accountEmail' | 'accountId'>
export function usageAccountDisplay(record: UsageAccountIdentity) {
const email = record.accountEmail?.trim()
const primary = record.accountName?.trim() || email || record.accountId || '—'
return {
primary,
secondary: email && email !== primary
? email
: '',
}
}
export function usageAccountText(record: UsageAccountIdentity) {
const { primary, secondary } = usageAccountDisplay(record)
return secondary
? `${primary} (${secondary})`
: primary
}
export function usageClientIp(record: { clientIp?: string | null }) {
@@ -111,6 +111,9 @@
"proxyUnreachable": "Could not connect to the account proxy — test it in Proxies",
"proxyTunnelFailed": "Could not establish a tunnel through the account proxy — check its settings",
"checkProxy": "The request could not be sent upstream — test the account proxy in Proxies",
"googleCredentials": "Google rejected the credentials for this account (401)",
"googleAccessDenied": "Google denied this account access to Antigravity (403)",
"googleVerification": "Sign in to Google and verify this account, then test again (403)",
"upstreamUnavailable": "Upstream service temporarily unavailable",
"timeout": "Upstream request timed out",
"canceled": "Test canceled",
+3
View File
@@ -257,6 +257,8 @@
"error": {
"noDetails": "No detailed error message was recorded",
"noAvailableProvider": "No upstream provider is available for this request.",
"processInterrupted": "The gateway did not record how the request ended",
"requestTrackingLost": "The gateway lost track of the request before its outcome was recorded",
"requestLimited": "Request limited",
"upstreamCapacityUnavailable": "Upstream model is at capacity",
"upstreamConnectionClosed": "Upstream connection closed",
@@ -273,6 +275,7 @@
"responseId": "Response ID",
"clientKeyId": "Client key ID",
"errorCode": "Error code",
"errorMessage": "Error message",
"failureClassification": "Failure classification",
"duration": "Duration",
"triggerMode": "Trigger mode",
@@ -111,6 +111,9 @@
"proxyUnreachable": "无法连接账号代理,请在「代理管理」中测试该代理",
"proxyTunnelFailed": "未能通过账号代理建立隧道,请检查代理设置",
"checkProxy": "请求未能发往上游,可在「代理管理」中测试账号代理",
"googleCredentials": "Google 未接受此账号的登录凭据(401)",
"googleAccessDenied": "Google 拒绝此账号访问 Antigravity(403)",
"googleVerification": "请登录 Google 完成账号验证后再测试(403)",
"upstreamUnavailable": "上游服务暂不可用",
"timeout": "上游请求超时",
"canceled": "测试请求已取消",
@@ -257,6 +257,8 @@
"error": {
"noDetails": "未记录具体错误消息",
"noAvailableProvider": "此请求没有可用的上游服务",
"processInterrupted": "网关未记录到请求结束",
"requestTrackingLost": "网关已失去对这次请求的跟踪,最终结果未知",
"requestLimited": "请求受限",
"upstreamCapacityUnavailable": "上游模型容量不足",
"upstreamConnectionClosed": "上游连接已关闭",
@@ -273,6 +275,7 @@
"responseId": "响应 ID",
"clientKeyId": "API密钥 ID",
"errorCode": "错误码",
"errorMessage": "错误信息",
"failureClassification": "失败分类",
"duration": "耗时",
"triggerMode": "触发方式",
@@ -111,6 +111,9 @@
"proxyUnreachable": "無法連線至帳號代理,請在「代理管理」中測試該代理",
"proxyTunnelFailed": "無法透過帳號代理建立通道,請檢查代理設定",
"checkProxy": "請求未能送往上游,可在「代理管理」中測試帳號代理",
"googleCredentials": "Google 未接受此帳號的登入憑證(401)",
"googleAccessDenied": "Google 拒絕此帳號存取 Antigravity(403)",
"googleVerification": "請登入 Google 完成帳號驗證後再測試(403)",
"upstreamUnavailable": "上游服務暫不可用",
"timeout": "上游請求超時",
"canceled": "測試請求已取消",
@@ -257,6 +257,8 @@
"error": {
"noDetails": "未記錄具體錯誤消息",
"noAvailableProvider": "此請求沒有可用的上游服務",
"processInterrupted": "閘道未記錄到請求結束",
"requestTrackingLost": "閘道已失去對這次請求的追蹤,最終結果未知",
"requestLimited": "請求受限",
"upstreamCapacityUnavailable": "上游模型容量不足",
"upstreamConnectionClosed": "上游連線已關閉",
@@ -273,6 +275,7 @@
"responseId": "響應 ID",
"clientKeyId": "API密鑰 ID",
"errorCode": "錯誤碼",
"errorMessage": "錯誤訊息",
"failureClassification": "失敗分類",
"duration": "耗時",
"triggerMode": "觸發方式",
@@ -85,7 +85,7 @@ watch(hasPersonalInfo, (available) => {
v-if="(account.capabilities.quota || quotaEntries.length > 0 || account.upstream?.discovered) && (hasPlanBadge || lastRefreshed)"
class="col-span-2 row-start-2 m-0 flex min-w-0 items-center gap-1.5 text-z-xs font-emphasis text-z-text-secondary"
>
<AccountPlanBadge v-if="hasPlanBadge" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" class="shrink-0" />
<AccountPlanBadge v-if="hasPlanBadge" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" class="shrink-0 rounded-md!" />
<span v-if="lastRefreshed" class="min-w-0 truncate">{{ lastRefreshed }}</span>
</p>
<div v-if="hasActions" class="col-start-2 row-start-1 flex items-center gap-0.5 [&_svg]:size-3.5 [&_svg]:stroke-2">
@@ -123,7 +123,16 @@ function parseConnectionTestEvent(raw: string): ConnectionTestEvent | null {
return value as ConnectionTestEvent
}
function connectionTestFailureText(event: ConnectionTestFailureEvent) {
function connectionTestFailureText(event: ConnectionTestFailureEvent, provider?: string) {
if (provider === 'antigravity' && event.source === 'upstream') {
if (event.upstreamStatus === 401)
return t('accounts.connectionTest.errors.googleCredentials')
if (event.upstreamStatus === 403) {
return event.providerErrorCode === 'VALIDATION_REQUIRED'
? t('accounts.connectionTest.errors.googleVerification')
: t('accounts.connectionTest.errors.googleAccessDenied')
}
}
if (event.source === 'provider' && event.sendState === 'not_sent') {
switch (event.proxyHint) {
case 'invalid_configuration': return t('accounts.connectionTest.errors.proxyInvalid')
@@ -394,7 +403,7 @@ export function useAccountConnectionTest(options: { reload: () => Promise<unknow
recordConnectionTestFailure(
`failure-${event.source || 'unknown'}`,
connectionTestFailureLabel(event),
connectionTestFailureText(event),
connectionTestFailureText(event, testingAccount.value?.provider),
connectionTestFailureDiagnostics(event),
event,
)
+1 -1
View File
@@ -35,7 +35,7 @@ export const accountColumns = computed(() => (defineTableColumns<Account>([
label: t('accounts.account'),
kind: 'identity',
size: '2xl',
sortable: 'email',
sortable: 'name',
},
{
key: 'provider',
@@ -118,6 +118,8 @@ function previewUsageRecord(options: PreviewUsageRecordOptions): UsageListRecord
upstreamConnectionExitReason: null,
recovered: false,
errorMessage: null,
upstreamErrorMessage: null,
retryAfterMs: null,
clientApiKeyName: t('appearance.preview.dashboard.demoKey'),
provider: options.provider,
authenticationKind: options.authenticationKind,
@@ -7,6 +7,7 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
import { usageAccountDisplay } from '@/components/usage-records-table/presenter'
import { formatLocalizedCompactNumber as formatCompactNumber, formatDuration, formatPercent, formatUsd } from '@/utils/format'
const props = withDefaults(
@@ -123,26 +124,28 @@ type DiagnosticDisplayItem = Diagnostics['items'][number] & {
const displayItems = computed<DiagnosticDisplayItem[]>(() =>
(props.diagnostics?.items ?? []).map(item => ({
...item,
nameDisplay: diagnosticNameDisplay(item.name),
nameDisplay: diagnosticNameDisplay(item),
})),
)
const hasData = computed(() => !props.loading && displayItems.value.length > 0)
function diagnosticNameDisplay(name: string) {
const raw = name.trim() || t('common.values.unknown')
function diagnosticNameDisplay(item: Diagnostics['items'][number]) {
if (resultDimension.value === 'account')
return usageAccountDisplay({ accountName: item.name, accountEmail: item.accountEmail, accountId: item.key })
const raw = item.name.trim() || t('common.values.unknown')
const full
= resultDimension.value === 'transport'
? ({ websocket: 'WS', http_sse: 'SSE' }[raw] ?? raw)
: raw
if (resultDimension.value !== 'model' && resultDimension.value !== 'account') {
return { primary: full, secondary: '', full }
if (resultDimension.value !== 'model') {
return { primary: full, secondary: '' }
}
const [primary, secondary = ''] = full.split(/\s+(?:→|->)\s+/, 2)
return {
primary: primary || full,
secondary,
full,
}
}
</script>
@@ -139,6 +139,7 @@ const attempts = computed(() => (props.record?.attempts ?? []).map(attempt => ({
label: t('accounts.account'),
value: usageAccountText(attempt),
mono: true,
wrap: true,
},
{
label: t('usage.error.platform'),
@@ -2,7 +2,7 @@
import type { UsageRecordDetail } from '@/api'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { usageErrorOrigin, usageErrorTitle } from '@/components/usage-records-table/errors'
import { usageErrorMessage, usageErrorOrigin, usageErrorTitle } from '@/components/usage-records-table/errors'
import { usageTransportType } from '@/components/usage-records-table/presenter'
import { formatDuration } from '@/utils/format'
import UsageDetailFieldGrid from './UsageDetailFieldGrid.vue'
@@ -12,15 +12,7 @@ const props = defineProps<{ record: UsageRecordDetail }>()
const { t } = useI18n({ useScope: 'global' })
const origin = computed(() => usageErrorOrigin(props.record))
const title = computed(() => usageErrorTitle(props.record))
const errorMessage = computed(() => {
const upstream = props.record.upstreamError
if (upstream?.message || upstream?.closeReason)
return upstream.message || upstream.closeReason
const message = props.record.message.trim()
return message && message !== props.record.logicalOutcome
? message.replace(/^OpenAI upstream failure: /, '')
: t('usage.error.noDetails')
})
const errorMessage = computed(() => usageErrorMessage(props.record, props.record.message, props.record.upstreamError?.message || props.record.upstreamError?.closeReason))
const errorItems = computed(() => [
{ label: 'Code', value: props.record.upstreamError?.code ?? props.record.errorCode },
{ label: 'Type', value: props.record.upstreamError?.errorType },
@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { EChartsOption } from 'echarts'
import type { UsageRecordDetail } from '@/api'
import type { UsageAttempt, UsageRecordDetail } from '@/api'
import { defineTableColumns, ZButton, ZDialog, ZTable } from '@codex-proxy/ui'
import { computed } from 'vue'
@@ -19,6 +19,7 @@ import {
usageTransportType,
usageUserAgent,
} from '@/components/usage-records-table/presenter'
import UsageAccountCell from '@/components/usage-records-table/UsageAccountCell.vue'
import { useChartPalette } from '@/composables/useChartPalette'
import { formatDuration, formatInteger } from '@/utils/format'
@@ -74,6 +75,7 @@ const requestItems = computed(() => [
label: t('accounts.account'),
value: accountDisplay.value,
mono: true,
wrap: true,
fullWidth: true,
},
{
@@ -240,8 +242,7 @@ interface AttemptRow {
model: string | null
transport: string
statusCode: number | null
accountLabel: string
accountId: string | null
account: UsageAttempt
latencyMs: number | null
}
@@ -282,7 +283,7 @@ const attemptColumns = computed(() => (defineTableColumns<AttemptRow>([
size: 'sm',
},
{
key: 'accountLabel',
key: 'account',
label: t('accounts.account'),
kind: 'mono',
size: '2xl',
@@ -304,8 +305,7 @@ const attemptRows = computed<AttemptRow[]>(() =>
model: attempt.model,
transport: attempt.transport,
statusCode: attempt.statusCode,
accountLabel: attempt.accountEmail || attempt.accountName || attempt.accountId || '—',
accountId: attempt.accountId,
account: attempt,
latencyMs: attempt.latencyMs,
})),
)
@@ -685,12 +685,8 @@ const tokenDonutOption = computed<EChartsOption>(() => {
:status-code="typeof row.statusCode === 'number' ? row.statusCode : null"
/>
</template>
<template #accountLabel="{ row }">
<span
class="block max-w-full truncate font-mono text-z-sm font-bold text-z-text"
>
{{ row.accountLabel }}
</span>
<template #account="{ row }">
<UsageAccountCell :record="row.account" />
</template>
<template #latencyMs="{ row }">
<span class="font-mono font-bold tabular-nums text-z-text">
+13 -13
View File
@@ -1,17 +1,17 @@
# v3.60.4
# v3.60.5
> [!IMPORTANT]
> **OpenAI 请求默认值与数据库升级**
>
> - 请求国家:默认由“跟随位置”改为“空值”(`request_country: null`)
> - 数据驻留:默认由 `us` 改为留空,不再发送驻留请求头
> - 账号路由覆盖:默认仍为留空,已有配置保持不变
>
> 升级会一次性将数据库中的“跟随位置”改为“空值”,并清空驻留值 `us`,包括手动保存的同值设置;自定义国家、透传模式和其他驻留值保持不变
>
> 仍需原值的部署,请在升级后进入“系统设置 → 平台设置 → OpenAI”重新保存
## 优化改进
- 请求错误浮层直接展示上游错误信息和重试等待时间,无需额外加载完整详情,并补充请求中断的本地化提示
- Antigravity 连接测试区分 Google 登录凭据无效、访问被拒和需要账号验证,展示可安全返回的上游错误原因
## 问题修复
- 修复 Antigravity 在 Claude 与 Gemini 之间切换时的已知思考签名冲突,保留同家族及无法识别的原生签名
- 修复系统设置帮助按钮的背景与尺寸不一致,统一请求设置和自动审批的提示交互
- 上游容量不足时,客户端收到的错误会保留上游建议的重试等待时间,换号后要求重发完整历史时也能看到
- 修复手动或自动用卡后周额度桶仍等待原重置时间的问题,已启用预热的周桶在确认用卡 5 分钟后复查,本轮已有使用或重试同次消费时避免重复预热
- 修复账号列表按邮箱而非显示名称排序的问题,请求记录、尝试明细和账号诊断统一优先展示名称并附邮箱
- 修复图标选择器异步加载时的图标稳定性和网格响应式布局
## 升级须知
- 直接调用管理 API 的账号列表排序时,需将 `sortBy=email` 改为 `sortBy=name`
+5 -5
View File
@@ -1,7 +1,7 @@
version: 3.60.4
version: 3.60.5
published:
'3':
stable: 3.60.3
rc: 3.60.3
beta: 3.60.3
alpha: 3.60.3
stable: 3.60.4
rc: 3.60.4
beta: 3.60.4
alpha: 3.60.4