Compare commits

..
14 Commits
Author SHA1 Message Date
Wei HUandCodex d1be306f03 test(api): isolate virtual time from idle WebSocket I/O (#761)
The idle expiry test reads a real TCP socket with a Tokio timeout while
the clock is paused. Auto-advance can reach the read deadline while the
socket is still waiting for readiness.

Follow the adjacent connection lifecycle test and pause only for the
60-minute jump. Use a running clock for the handshake and frame read.
Keep the exact limit error and zero-execution assertions.

Co-authored-by: Codex <noreply@openai.com>
2026-11-21 22:51:47 +08:00
aa34d5291d fix(accounts): preserve quota forecast totals through reset time jitter (#760)
* fix(accounts): preserve quota forecast totals through reset time jitter

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

* fix(accounts): confirm quota cycle changes before trimming usage

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

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 21:52:12 +08:00
github-actions[bot] 56d3078ee8 chore(release): update release channels to 3.54.2 2026-11-21 12:52:38 +00:00
ZyyandCodex 8b69fa4882 chore: bump version to 3.54.2
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 20:35:59 +08:00
ZyyandCodex d05d38718e feat(frontend): show CPR wordmark and repository link in the browser console
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 19:23:03 +08:00
Zyy a1954c4746 fix(openai): limit request country overrides to Codex OAuth
Preserve the incoming request country on API key routes. Show quota refresh only for supported accounts and keep peer discovery in the account menu.

Clarify the policy scope in settings and tighten shared help icon spacing.

Refs #758
2026-11-21 18:37:59 +08:00
github-actions[bot] 636a3d2a26 chore(release): update release channels to 3.54.1 2026-11-21 04:18:44 +00:00
ZyyandCodex e9627168a7 chore: bump version to 3.54.1
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 12:02:26 +08:00
Zyy 5a4f49036b feat(frontend): share model access controls and separate request country settings
Let accounts and groups manage model lists with the same editor, including custom IDs and common image models. Tighten spacing in the group form and give the request country policy its own settings card.
2026-11-21 11:52:45 +08:00
ZyyandCodex 8041ddab65 refactor(frontend): consolidate chart, form, icon and proxy display rules
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 10:55:06 +08:00
ZyyandCodex e645d6d4c9 fix(usage): unify timestamp columns across record tables
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 10:55:01 +08:00
ZyyandCodex 5079700190 fix(ui): update shared UI to v0.13.1 for WebKit tables
Co-authored-by: Codex <noreply@openai.com>
2026-11-21 10:38:38 +08:00
ZyyandCodex 4db65d8e12 chore(deploy): update PostgreSQL to 18.7 and Redis to 8.10.3
Co-authored-by: Codex <noreply@openai.com>
2026-11-20 23:25:43 +08:00
github-actions[bot] da866de2c7 chore(release): update release channels to 3.54.0 2026-11-20 14:45:41 +00:00
57 changed files with 748 additions and 581 deletions
+2 -2
View File
@@ -35,7 +35,7 @@ jobs:
CPR_TEST_REDIS_URL: redis://127.0.0.1:6379
services:
postgres:
image: postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
image: postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
env:
POSTGRES_DB: codex_proxy
POSTGRES_USER: codex_proxy
@@ -49,7 +49,7 @@ jobs:
--health-timeout 5s
--health-retries 10
redis:
image: redis:8-alpine@sha256:0bf6577d7774e592b29d093e3ac9390eb91e13d72c21e506afce736de5e0eeb0
image: redis:8-alpine@sha256:7958cfbb9d152f87dadfbc89f1b0b15938f0b81ff8982feb327476f4911935c3
ports:
- 6379:6379
options: >-
@@ -8,6 +8,7 @@ use super::provider_credentials::ProviderDocument;
pub const MAX_FORECAST_HISTORY_POINTS: usize = 128;
const MIN_BLOCK_PERCENT: f64 = 5.0;
const RECENT_BLOCKS: usize = 3;
const MAX_PERCENT_REVERSAL: f64 = 1.0;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct QuotaForecastUsage {
@@ -80,11 +81,55 @@ pub struct QuotaForecastObservation {
#[derive(Debug, Clone)]
pub struct QuotaForecastPoint {
pub started_at: DateTime<Utc>,
pub observed_at: DateTime<Utc>,
pub reset_at: DateTime<Utc>,
pub used_percent: f64,
pub usage: QuotaForecastUsage,
}
impl QuotaForecastPoint {
fn follows(&self, previous: &Self) -> bool {
previous.observed_at <= self.started_at && previous.observed_at < self.observed_at
}
}
/// 当前窗口内仍有旧周期记录时,只在旧读数已到期、用量回落且新读数得到印证后重设累计
fn cycle_boundary(
history: &[QuotaForecastPoint],
current: &QuotaForecastPoint,
) -> (Option<usize>, bool) {
let mut boundary = None;
let mut awaiting_confirmation = false;
for (index, pair) in history.windows(2).enumerate() {
let (older, previous) = (&pair[0], &pair[1]);
let first_index = index + 2;
let first = history.get(first_index).unwrap_or(current);
let before_reset = older.used_percent.min(previous.used_percent);
if !previous.follows(older)
|| !first.follows(previous)
|| older.reset_at <= previous.observed_at
|| older.reset_at > first.started_at
|| previous.reset_at > first.started_at
|| before_reset - first.used_percent <= MAX_PERCENT_REVERSAL
{
continue;
}
// 快照可能复用请求读数;只有另一条在新窗口内独立完成的请求能确认换段
let confirmation = history
.get(first_index + 1..)
.and_then(|later| later.iter().find(|next| next.follows(first)));
awaiting_confirmation = confirmation.is_none();
if confirmation.is_some_and(|next| {
next.observed_at < first.reset_at
&& before_reset - next.used_percent > MAX_PERCENT_REVERSAL
}) {
boundary = Some(first_index);
}
}
(boundary, awaiting_confirmation)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuotaForecastMethod {
Cumulative,
@@ -117,7 +162,7 @@ pub fn select_forecast_sample(
current: QuotaForecastPoint,
mut history: Vec<QuotaForecastPoint>,
pending_request_count: u64,
interrupted: bool,
plan_changed: bool,
) -> QuotaForecastSample {
history.retain(|point| {
start_at <= point.observed_at
@@ -126,6 +171,9 @@ pub fn select_forecast_sample(
&& (0.0..=100.0).contains(&point.used_percent)
});
history.sort_by_key(|point| point.observed_at);
let (boundary, awaiting_confirmation) = cycle_boundary(&history, &current);
let history = &history[boundary.unwrap_or(0)..];
let interrupted = plan_changed || boundary.is_some();
let mut sample = QuotaForecastSample {
key,
method: QuotaForecastMethod::Cumulative,
@@ -136,23 +184,35 @@ pub fn select_forecast_sample(
block_count: 0,
observation_count: history.len(),
pending_request_count,
discontinuous: interrupted,
discontinuous: interrupted || awaiting_confirmation,
cycle_usage: current.usage.clone(),
usage: current.usage.clone(),
};
history.push(current);
// 重置边界不在查询起点时,从首个新观测重新计数,避免把旧周期累计带入总量
let cycle_baseline = interrupted.then(|| &history[0]);
if interrupted {
let baseline = history.first().unwrap_or(&current);
let Some(usage) = current.usage.difference(&baseline.usage) else {
return sample;
};
sample.cycle_usage = usage;
}
if awaiting_confirmation {
return sample;
}
let mut anchors: Vec<&QuotaForecastPoint> = Vec::new();
let mut high_water: Option<&QuotaForecastPoint> = None;
for point in &history {
for point in history.iter().chain(std::iter::once(&current)) {
// 截至快照已过期的读数不能用于预测剩余量,窗口累计仍由上面的周期证据决定
if point.reset_at <= current.observed_at {
sample.discontinuous = true;
continue;
}
if let Some(previous) = high_water {
if point.observed_at <= previous.observed_at {
continue;
}
if point.used_percent < previous.used_percent {
// 一个百分点内的回落可能是量化/并发乱序;更大的回落不能跨越
if previous.used_percent - point.used_percent <= 1.0 {
if previous.used_percent - point.used_percent <= MAX_PERCENT_REVERSAL {
continue;
}
// 同窗口回落不能证明周期重置,只重建采样并保留已记录累计
@@ -168,16 +228,6 @@ pub fn select_forecast_sample(
anchors.push(point);
}
}
let Some(current) = history.last() else {
return sample;
};
if let Some(baseline) = cycle_baseline {
let Some(usage) = current.usage.difference(&baseline.usage) else {
sample.discontinuous = true;
return sample;
};
sample.cycle_usage = usage;
}
if anchors.len() < 2 {
return sample;
}
@@ -1057,6 +1057,8 @@ impl AccountsService for DefaultAccountsService {
) else {
continue;
};
let reset_at = query.range.end;
let window_duration = reset_at - query.range.start;
query.range.start = query.range.start.max(stored.account.created_at);
if query.range.start >= observed
|| observed > now
@@ -1066,7 +1068,6 @@ impl AccountsService for DefaultAccountsService {
{
continue;
}
let reset_at = query.range.end;
query.range.end = observed;
let history = self
.accounts
@@ -1074,27 +1075,37 @@ impl AccountsService for DefaultAccountsService {
.await
.map_err(|error| map_store_error(error, "forecast paired usage"))?;
let mut points = Vec::new();
let mut interrupted = false;
let mut plan_changed = false;
for point in history.points {
let Some(fact) =
provider.quota_forecast_observation(&point.provider_observation, window)
else {
continue;
};
let same_plan = quota
.plan_type
.as_deref()
.zip(fact.plan_type.as_deref())
.is_some_and(|(current, previous)| current.eq_ignore_ascii_case(previous));
// 仅容纳已观测到的秒级量化抖动,不用宽时间容差合并实际重置
// 不匹配的段截断基线;之后的有效观测可以重新积累
if !same_plan || (fact.reset_at - reset_at).abs() > Duration::seconds(2) {
let (Some(current_plan), Some(previous_plan)) =
(quota.plan_type.as_deref(), fact.plan_type.as_deref())
else {
continue;
};
let Some(start) = fact.reset_at.checked_sub_signed(window_duration) else {
continue;
};
if point.completed_at >= observed
|| point.started_at < query.range.start
|| point.completed_at < start
|| point.completed_at >= fact.reset_at
{
continue;
}
if !current_plan.eq_ignore_ascii_case(previous_plan) {
points.clear();
interrupted = true;
plan_changed = true;
continue;
}
points.push(QuotaForecastPoint {
started_at: point.started_at,
observed_at: point.completed_at,
reset_at: fact.reset_at,
used_percent: fact.used_percent,
usage: point.usage,
});
@@ -1103,13 +1114,15 @@ impl AccountsService for DefaultAccountsService {
window.key.clone(),
query.range.start,
QuotaForecastPoint {
started_at: observed,
observed_at: observed,
reset_at,
used_percent: percent,
usage: history.usage,
},
points,
history.pending_request_count,
interrupted,
plan_changed,
);
samples.push(sample);
}
@@ -12,7 +12,9 @@ fn time(minutes: i64) -> DateTime<Utc> {
fn point(minute: i64, percent: f64, tokens: u64) -> QuotaForecastPoint {
QuotaForecastPoint {
started_at: time(minute) - Duration::seconds(1),
observed_at: time(minute),
reset_at: time(7 * 24 * 60),
used_percent: percent,
usage: QuotaForecastUsage {
request_count: minute as u64,
@@ -188,7 +190,41 @@ fn repeated_same_window_recoveries_preserve_recorded_cycle_usage() {
}
#[test]
fn changed_window_restarts_cycle_totals_at_first_matching_observation() {
fn an_expired_deadline_alone_cannot_cut_totals_or_anchor_remaining_usage() {
let mut older = point(1, 15.0, 100);
older.reset_at = time(3);
let mut previous = point(2, 20.0, 200);
previous.reset_at = time(3) + Duration::seconds(4);
let first = point(4, 25.0, 700);
let sample = select(vec![older, previous, first], point(6, 35.0, 900));
assert_eq!(sample.cycle_usage.tokens, 900);
assert_eq!(sample.baseline_percent, 25.0);
assert_eq!(sample.usage.tokens, 200);
}
#[test]
fn copied_concurrent_or_contradictory_readings_cannot_confirm_a_recovery() {
let mut older = point(1, 75.0, 100);
older.reset_at = time(3);
let mut previous = point(2, 85.0, 200);
previous.reset_at = time(3);
let first = point(4, 5.0, 300);
let current = point(6, 40.0, 900);
let mut overlapping = point(5, 20.0, 400);
overlapping.started_at = first.started_at;
for extra in [None, Some(overlapping), Some(current.clone())] {
let mut points = vec![older.clone(), previous.clone(), first.clone()];
points.extend(extra);
let sample = select(points, current.clone());
assert_eq!(sample.cycle_usage.tokens, 900);
assert!(sample.discontinuous);
}
let sample = select(vec![older, previous, first, point(5, 86.0, 400)], current);
assert_eq!(sample.cycle_usage.tokens, 900);
}
#[test]
fn changed_plan_restarts_cycle_totals_at_first_matching_observation() {
let sample = select_forecast_sample(
"week".to_owned(),
time(0),
@@ -2576,7 +2576,9 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report(
usage: usage(index as u64 + 1, tokens),
provider_observation: ProviderDocument::new(OpaqueProviderData::new(
serde_json::json!({
"percent": percent, "reset": reset.to_rfc3339(), "plan": "pro",
"percent": percent,
"reset": (reset + TimeDelta::seconds(17 * index as i64)).to_rfc3339(),
"plan": "pro",
})
.as_object()
.unwrap()
@@ -2605,14 +2607,14 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report(
}
#[tokio::test]
async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_changed_bucket() {
async fn quota_forecast_keeps_cycle_totals_through_reset_jitter_and_restarts_after_a_reset() {
use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistoryPoint;
let now = Utc::now();
let observed = now - TimeDelta::minutes(1);
let reset = now + TimeDelta::days(1);
let added = now - TimeDelta::hours(5);
let provider = FakeProviderAdmin::new("openai", events());
provider.set_quota(ProviderQuota {
let mut quota = ProviderQuota {
upstream: None,
credits: None,
plan_type: Some("pro".to_owned()),
@@ -2627,67 +2629,102 @@ async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_
role: None,
local_usage_attribution: QuotaLocalUsageAttribution::AccountWide,
window_seconds: Some(604_800),
used_percent: Some(40.0),
used_percent: Some(65.0),
reset_at: Some(reset),
limit_reached: false,
local_usage: None,
provider_data: None,
}],
..empty_quota()
});
};
let mut account = account_record("openai");
account.created_at = added;
let store = FakeAccountStore::with_account(account, events());
let make_point = |hours, percent, tokens, delta| {
QuotaForecastHistoryPoint {
started_at: now - TimeDelta::hours(hours) - TimeDelta::seconds(10),
completed_at: now - TimeDelta::hours(hours),
usage: QuotaForecastUsage { request_count: tokens / 100, tokens, ..Default::default() },
provider_observation: ProviderDocument::new(OpaqueProviderData::new(serde_json::json!({
"percent": percent, "reset": (reset + TimeDelta::seconds(delta)).to_rfc3339(), "plan": "pro",
}).as_object().unwrap().clone())),
}
let usage = |tokens| QuotaForecastUsage {
request_count: tokens / 100,
tokens,
known_cost_count: tokens / 100,
usd: tokens as f64 / 100.0,
..Default::default()
};
let point_with_plan = |hours, percent, tokens, delta, plan: Option<&str>| {
let observation = serde_json::json!({
"percent": percent,
"reset": (reset + TimeDelta::seconds(delta)).to_rfc3339(),
"plan": plan,
});
QuotaForecastHistoryPoint {
started_at: now - TimeDelta::hours(hours) - TimeDelta::seconds(10),
completed_at: now - TimeDelta::hours(hours),
usage: usage(tokens),
provider_observation: ProviderDocument::new(OpaqueProviderData::new(
observation.as_object().unwrap().clone(),
)),
}
};
let make_point =
|hours, percent, tokens, delta| point_with_plan(hours, percent, tokens, delta, Some("pro"));
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
points: vec![
make_point(3, 20.0, 1_000, 1),
make_point(2, 30.0, 1_500, -1),
make_point(4, 20.0, 20_000, 0),
make_point(3, 58.0, 62_000, 17),
make_point(2, 58.0, 62_500, 0),
],
usage: QuotaForecastUsage {
request_count: 20,
tokens: 2_000,
..Default::default()
},
usage: usage(70_600),
pending_request_count: 1,
};
let services = accounts_service(provider, store.clone()).await;
let result = services
.accounts()
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
.await
.unwrap();
assert!(result.forecasts[0].unavailable_reason.is_none());
assert_eq!(result.forecasts[0].estimated_tokens, Some(5_000));
let services = accounts_service(provider.clone(), store.clone()).await;
let account_id = ProviderAccountId::new("acct_test").unwrap();
let read_report = async || {
services
.accounts()
.quota_forecast(&account_id)
.await
.unwrap()
};
// 回放 #759 的金额和百分比,历史与快照各自报告的到期时间偏移时仍应保留整段累计
for offset in [0, 3, 6, 7, 17, -23] {
quota.windows[0].reset_at = Some(reset + TimeDelta::seconds(offset));
provider.set_quota(quota.clone());
let report = read_report().await;
let week = &report.forecasts[0];
let source = week.source.as_ref().unwrap();
assert_eq!(source.tokens, Some(70_600));
assert_eq!(source.usd, Some(706.0));
assert_eq!(week.estimated_tokens, Some(109_956));
assert!((week.estimated_usd.unwrap() - (706.0 + 506.0 * 35.0 / 45.0)).abs() < 1e-9);
assert!(week.unavailable_reason.is_none());
}
assert_eq!(store.quota_window_queries()[0].range.start, added);
store
.quota_forecast_history
.lock()
.unwrap()
.points
.push(make_point(1, 35.0, 1_700, 3_600));
let result = services
.accounts()
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
.await
.unwrap();
assert!(result.forecasts[0].estimated_tokens.is_none());
assert!(
result.forecasts[0]
.unavailable_reason
.unwrap()
.contains("不连续")
.push(make_point(1, 62.0, 66_000, 3_600));
let result = read_report().await;
assert_eq!(
result.forecasts[0].source.as_ref().unwrap().tokens,
Some(70_600)
);
// 新额度段已有足够观测后恢复预测,但总量不能带回重置前的累计用量
assert!(result.forecasts[0].estimated_tokens.is_some());
// 两份旧读数的截止时刻均已过去,新请求开始于旧窗口结束后
quota.windows[0].used_percent = Some(40.0);
provider.set_quota(quota.clone());
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
points: vec![
make_point(4, 75.0, 1_000, -90_000),
make_point(2, 85.0, 1_500, -90_021),
],
usage: usage(2_000),
..Default::default()
};
let waiting = read_report().await;
assert_eq!(
waiting.forecasts[0].source.as_ref().unwrap().tokens,
Some(2_000)
);
assert!(waiting.forecasts[0].estimated_tokens.is_none());
let mut first = make_point(1, 5.0, 1_750, 0);
first.completed_at = now - TimeDelta::minutes(45);
first.started_at = first.completed_at - TimeDelta::seconds(10);
@@ -2700,15 +2737,42 @@ async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_
.unwrap()
.points
.extend([first, next]);
let result = services
.accounts()
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
.await
.unwrap();
let result = read_report().await;
let cycle = &result.forecasts[0];
assert!(cycle.unavailable_reason.is_none());
assert_eq!(cycle.source.as_ref().unwrap().tokens, Some(250));
assert_eq!(cycle.estimated_tokens, Some(679));
for (plan, expected_tokens) in [(None, 2_000), (Some("plus"), 500)] {
store.quota_forecast_history.lock().unwrap().points = vec![
make_point(4, 20.0, 1_000, 0),
point_with_plan(3, 25.0, 1_200, 0, plan),
make_point(2, 30.0, 1_500, 0),
];
let report = read_report().await;
assert_eq!(
report.forecasts[0].source.as_ref().unwrap().tokens,
Some(expected_tokens)
);
}
// 上游提前给出新的七天窗口时,直接从新起点查询,首条配对样本前的用量也留在累计中
let new_start = now - TimeDelta::hours(1);
quota.windows[0].reset_at = Some(new_start + TimeDelta::days(7));
provider.set_quota(quota);
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
usage: usage(400),
..Default::default()
};
let report = read_report().await;
assert_eq!(
store.quota_window_queries().last().unwrap().range.start,
new_start
);
assert_eq!(
report.forecasts[0].source.as_ref().unwrap().tokens,
Some(400)
);
}
#[tokio::test]
@@ -643,7 +643,7 @@ async fn dropping_the_connection_aborts_and_drops_the_socket_owner() {
assert!(cancellation.is_cancelled());
}
#[tokio::test(start_paused = true)]
#[tokio::test]
async fn idle_connection_reaches_the_official_limit_without_starting_an_execution() {
let trace = Arc::new(AtomicFailureTrace::default());
let execution = Arc::new(AtomicFailureExecution {
@@ -672,8 +672,11 @@ async fn idle_connection_reaches_the_official_limit_without_starting_an_executio
let (mut socket, response) = connect_async(request).await.expect("upgrade WebSocket");
assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
// 真实 socket 读写期间使用实时时钟,避免 I/O 等待自动耗尽虚拟期限
tokio::time::pause();
tokio::time::advance(Duration::from_secs(60 * 60)).await;
tokio::task::yield_now().await;
tokio::time::resume();
let text = loop {
let message = tokio::time::timeout(Duration::from_secs(1), socket.next())
.await
@@ -87,7 +87,7 @@ use crate::transport::protocol::responses::{
};
use crate::transport::request::{
CodexRequestEncodeError, RequestAccountScope, align_structured_location_fields,
encode_generate_payload, scope_request_to_account,
apply_codex_request_country, encode_generate_payload, scope_request_to_account,
};
use crate::transport::session::CodexSessionIdentity;
use crate::transport::usage::normalize_service_tier;
@@ -1090,6 +1090,10 @@ impl CodexProvider {
"after": crate::transport::diagnostics::evidence::request_state(&upstream_request),
}));
}
let location = lease
.account()
.request_location()
.or(context.request_location());
if codex_oauth {
if matches!(
guardian_role,
@@ -1104,16 +1108,13 @@ impl CodexProvider {
&middleware_headers,
context.request_id().as_str(),
);
apply_codex_request_country(
upstream_request.body_mut(),
location,
context.openai_request_country(),
);
}
let location = lease
.account()
.request_location()
.or(context.request_location());
align_structured_location_fields(
upstream_request.body_mut(),
location,
context.openai_request_country(),
);
align_structured_location_fields(upstream_request.body_mut(), location);
let requirement = transport_requirement(&upstream_request);
let http_only = lease.transport() == crate::credential::ResponsesTransport::Http;
if http_only && requirement.requires_websocket() {
@@ -108,11 +108,12 @@ pub fn encode_generate_request(
location: Option<&CodexRequestLocation>,
) -> Result<CodexResponsesRequest, CodexRequestEncodeError> {
let mut encoded = encode_generate_payload(request, upstream_model)?;
align_structured_location_fields(
apply_codex_request_country(
encoded.body_mut(),
location,
&OpenAiRequestCountry::default(),
);
align_structured_location_fields(encoded.body_mut(), location);
Ok(encoded)
}
@@ -135,7 +136,7 @@ pub(crate) fn encode_generate_payload(
Ok(encoded)
}
pub(crate) fn align_structured_location_fields(
pub(crate) fn apply_codex_request_country(
body: &mut Map<String, Value>,
location: Option<&CodexRequestLocation>,
country: &OpenAiRequestCountry,
@@ -155,6 +156,12 @@ pub(crate) fn align_structured_location_fields(
body.insert("request_country".into(), Value::from(country.as_str()));
}
}
}
pub(crate) fn align_structured_location_fields(
body: &mut Map<String, Value>,
location: Option<&CodexRequestLocation>,
) {
let Some(location) = location else { return };
if let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) {
for item in input {
@@ -13463,10 +13463,12 @@ async fn downstream_client_markers_preserve_instruction_content() {
)]);
let sent = capture_client_request(body.clone(), context, api_key).await;
let mut expected = body;
expected.insert(
"request_country".to_owned(),
json!(global_request_location().country),
);
if !api_key {
expected.insert(
"request_country".to_owned(),
json!(global_request_location().country),
);
}
assert_eq!(sent, expected);
}
}
@@ -53,8 +53,7 @@ async fn responses_options_follow_the_selected_upstream_on_both_transports() {
"model": "gpt-5.4", "input": "hello",
"max_output_tokens": 1, "max_completion_tokens": 32, "max_tokens": 64,
"stream_options": {"include_usage": true, "reasoning_summary_delivery": "sequential_cutoff"},
"request_country": "US",
"client_metadata": {"user": "keep", "request_country": "US"},
"client_metadata": {"user": "keep"},
"tools": [{"type": "function", "name": "sample", "parameters": {
"type": "object", "properties": {"top_p": {"type": "number"}}
}}]
@@ -86,102 +85,86 @@ async fn responses_options_follow_the_selected_upstream_on_both_transports() {
);
}
assert_eq!(sent["client_metadata"]["user"], "keep");
assert_eq!(sent.get("request_country"), Some(&Value::Null));
assert_eq!(sent["client_metadata"]["request_country"], "US");
assert_eq!(sent["tools"], body["tools"]);
}
}
}
#[tokio::test]
async fn request_country_modes_only_change_the_top_level_across_transports() {
async fn request_country_follows_the_selected_account_across_transports() {
use OpenAiRequestCountry::{Custom, Default, FollowLocation, Passthrough};
for (api_key, websocket, policy, input, expected) in [
let location = global_request_location();
for (policy, location, input, oauth_country) in [
(FollowLocation {}, None, None, Some(Value::Null)),
(FollowLocation {}, Some(&location), None, Some(json!("NZ"))),
(
false,
false,
Default {},
Some(&location),
Some(json!("CA")),
Some(Value::Null),
),
(true, true, Default {}, None, Some(Value::Null)),
(false, true, Passthrough {}, None, None),
(Passthrough {}, Some(&location), None, None),
(
true,
false,
Passthrough {},
Some(Value::Null),
Some(Value::Null),
),
(
false,
false,
Passthrough {},
Some(&location),
Some(json!("CA")),
Some(json!("CA")),
),
(
true,
true,
FollowLocation {},
Some(json!("CA")),
Some(json!("NZ")),
),
(
true,
false,
Custom {
country: "JP".into(),
},
None,
Some(json!("JP")),
),
(
false,
true,
Custom {
country: "JP".into(),
},
Some(&location),
Some(Value::Null),
Some(json!("JP")),
),
] {
let location = global_request_location();
let mut body = json!({
"model": "gpt-5.4",
"input": "hello",
"client_metadata": {"request_country":"business"},
"tools": [{"type":"web_search"}],
"model": "gpt-5.4", "input": "hello",
"client_metadata": {"request_country": "business"},
"tools": [{"type": "web_search"}],
});
if let Some(input) = input {
body["request_country"] = input;
if let Some(country) = &input {
body["request_country"] = country.clone();
}
for api_key in [false, true] {
let expected = if api_key { &input } else { &oauth_country };
for websocket in [false, true] {
let sent = capture_downstream_with_country(
body.clone(),
api_key,
websocket,
false,
location.cloned(),
policy.clone(),
)
.await;
assert_eq!(
sent.get("request_country"),
expected.as_ref(),
"{policy:?}, api_key={api_key}, websocket={websocket}",
);
assert_eq!(
sent.pointer("/client_metadata/request_country"),
body.pointer("/client_metadata/request_country"),
);
assert_eq!(
sent.pointer("/tools/0/user_location/country")
.and_then(Value::as_str),
location.map(|location| location.country.as_str()),
);
assert_eq!(
sent.pointer("/tools/0/user_location/city")
.and_then(Value::as_str),
location.map(|location| location.city.as_str()),
);
assert_eq!(
sent.pointer("/tools/0/user_location/timezone")
.and_then(Value::as_str),
location.map(|location| location.timezone.name()),
);
}
}
let sent = capture_downstream_with_country(
body,
api_key,
websocket,
false,
Some(location.clone()),
policy,
)
.await;
assert_eq!(sent.get("request_country"), expected.as_ref());
assert_eq!(
sent.pointer("/client_metadata/request_country"),
Some(&json!("business"))
);
assert_eq!(
sent.pointer("/tools/0/user_location/country"),
Some(&json!(location.country))
);
assert_eq!(
sent.pointer("/tools/0/user_location/city"),
Some(&json!(location.city))
);
assert_eq!(
sent.pointer("/tools/0/user_location/timezone"),
Some(&json!(location.timezone.name()))
);
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
# PostgreSQL 服务端镜像:备份客户端(pg_dump/pg_restore)从这里取,与 compose 同源、
# 版本严格一致。升级数据库版本时只需同步修改这里与 deploy/compose.yaml。
ARG POSTGRES_IMAGE=postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
ARG POSTGRES_IMAGE=postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
FROM node:26.13.1-bookworm-slim@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 AS frontend-builder
+2 -2
View File
@@ -418,7 +418,7 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
| 并发与排队 | “系统设置 → 运行设置”;Key 与账号分别设置排队容量和超时,可选择账号排队失败后换号,见[排队规则](../docs/api.md#并发与排队) |
| 账号错误保护 | “系统设置 → 运行设置 → 错误保护”;默认关闭,按[自定义规则](../docs/api.md#账号错误保护)暂停账号调度 |
| 全局请求位置 | “系统设置 → 上游配置 → 请求位置覆盖”,默认关闭 |
| OpenAI 请求国家 | “系统设置 → 上游配置 → 请求位置覆盖”中默认选中“跟随位置”,可选择“空值”“透传”或“自定义” |
| Codex OAuth 请求国家 | “系统设置 → 上游配置 → 请求国家”,默认跟随位置,也可选择“空值”“透传”或“自定义” |
| OpenAI OAuth 同步审核模型 | “系统设置 → 上游配置 → 模型映射”中的“专用审核模型”默认开启,关闭后沿用客户端模型。[适用条件](../docs/api.md#正文兼容) |
| 代理位置 | “代理管理”;优先于全局位置,全局关闭时仍可独立生效 |
@@ -438,7 +438,7 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
在下游导入或编辑 OpenAI API Key 账号,填写上游 API 地址和该 Key,后台自动发现 CPR 互联能力。
地址包含自定义前缀时保留完整前缀,后台在该地址下请求 `cpr/link`。
列表与详情显示已保存的观测。展开账号可查看上游密钥限制,普通账号并发留空时跟随上游有效的正数上限。启用的 OpenAI API Key 账号可点击「刷新额度」重新识别。上游明确关闭共享或不支持互联时,账号显示为 API,重新识别成功后显示 CPR
可在账号行的「更多操作」中选择「检测 CPR 互联」手动识别。识别成功后账号显示为 CPR,展开可查看上游密钥限制和刷新额度。普通账号并发留空时跟随上游有效的正数上限。上游明确关闭共享或不支持互联时,账号显示为 API
第三方网关通过插件实现相同协议也可被识别,不按软件名称判定兼容。
上游明确返回 Key 预算耗尽时,下游暂停该账号;后续同步确认允许使用后自动恢复,普通限流冷却独立保留。
+2 -2
View File
@@ -11,7 +11,7 @@ services:
extends:
file: config.yaml
service: postgres-credentials
image: postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
image: postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
restart: unless-stopped
# 小内存部署可在此调整数据库预算,保留 UTC 参数,详见 README.md#小内存优化
command:
@@ -46,7 +46,7 @@ services:
extends:
file: config.yaml
service: redis-credentials
image: redis:8-alpine@sha256:0bf6577d7774e592b29d093e3ac9390eb91e13d72c21e506afce736de5e0eeb0
image: redis:8-alpine@sha256:7958cfbb9d152f87dadfbc89f1b0b15938f0b81ff8982feb327476f4911935c3
restart: unless-stopped
volumes:
- type: bind
+6 -6
View File
@@ -1386,7 +1386,7 @@ Key 消费窗口的 `localUsage` 按各自 `[resetAt - windowSeconds, resetAt)`
- 收到有效快照时显示 CPR 互联。明确返回不支持协议(HTTP 404、405、501),或返回 `403 peer_sharing_disabled` 时,清除互联身份和共享数据,显示普通 API Key
- 普通 401/403 保留原识别结果并清除已撤销的共享内容。超时、限流、服务异常或无效响应保留原识别结果和已有观测。无观测时 `observedAt` 与 `pool` 为 `null`,额度窗口为空
- 展开可探测的 API Key 后,点击「刷新额度」可重新识别互联。卡片显示已有更新时间,手动刷新结果通过通知反馈。明确不支持协议的连接停止周期探测,共享关闭的连接按授权退避周期复查
- 可探测但尚未识别为互联的 API Key,可在账号行的「更多操作」中选择「检测 CPR 互联」。识别成功后可在额度卡点击「刷新额度」。明确不支持协议的连接停止周期探测,共享关闭的连接按授权退避周期复查
账号地址、密钥或出口变更使旧观测与识别身份失效,重新识别当前连接。
账号停用后停止同步,重新启用后按当前连接的识别结果恢复后台任务
@@ -1410,7 +1410,7 @@ Key 预算及其访问状态随互联默认公开,不要求开启 `shareQuota`
最多 256 项,每个 ID 最多 256 字节;重复 ID 去重,不接受空白、控制字符、`__` 前缀或 `*` 通配符。
允许保存当前上游目录尚未返回的 ID。限制按全局模型映射后的上游 ID 判断,不扩大账号本身的上游权限。
管理端刷新目录只更新目录,不修改模型限制。全选与取消全选只作用于上游目录中符合当前搜索条件的模型。
账号白名单中,“添加模型”旁的图片按钮可勾选 `gpt-image-2` 和 `gpt-image-1.5`。
账号和分组白名单均可一键勾选 `gpt-image-2` 和 `gpt-image-1.5`。
自定义模型取消勾选后在本次编辑期间保留,可再次勾选。保存时以最终选中项更新限制,关闭或取消编辑会丢弃草稿。
白名单的清理按钮列出当前目录未返回的已选 ID,默认不选中任何项,
由管理员确认后从当前表单移除,保存账号后生效。目录未就绪、刷新失败或返回空目录时不能清理,清理也不能将白名单置空。
@@ -1508,7 +1508,7 @@ API 的 `autoLocation` 默认为 `false`;开启时使用已检测位置,测
只改位置不清空连通性测试结果,也不更改账号凭据版本
关联账号的 OpenAI/Codex Responses 请求(HTTP/SSE、WebSocket)优先使用代理位置,否则使用全局
运行设置中已开启的 `requestLocation`。出站正文的顶层 `request_country` 默认跟随位置,也可在[请求位置](#请求位置)选择“空值”“透传”或“自定义”。
运行设置中已开启的 `requestLocation`。Codex OAuth 请求的顶层国家字段由[请求国家策略](#请求位置)控制。
位置覆盖同时更新客户端时间上下文的时区和 Web Search 的结构化位置,未启用覆盖时这两项保留客户端原值。
全局覆盖按请求冻结,保存后对新请求生效。代理覆盖按每次执行选定的账号解析,包括换号和换出口。
位置覆盖不改变 epoch 时间戳、真实出口 IP、服务或管理端时区、数据驻留约束及 xAI 请求
@@ -1855,7 +1855,7 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
样本仅使用当前额度窗口内、账号加入后开始且截至观测时间已完整交付的请求,缓存命中不重复计入输入
重置或套餐变化后重新积累有效进度,中途加入的账号可在新基线后采样,无需等待下一次重置,职责与断点处理见[额度预测架构](architecture.md#额度预测)
重置或套餐变化后重新积累有效进度,中途加入的账号可在新基线后采样。单条历史读数的重置时间偏移不会截断已记录用量。疑似跨周期且仍待确认时,接口保留来源用量并暂停估算,详见[额度预测架构](architecture.md#额度预测)
预测不参与调度或账单结算,站外消耗、日志清理、异步延迟、未成功交付的上游消耗和模型组合变化均可能造成误差
@@ -1994,7 +1994,7 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercen
分组详情和完整列表返回 `modelAccess`、`fastMode`、`allowImageGeneration` 和 `allowSubagents`。创建时省略这些字段使用默认值,更新时省略或传 `null` 保留现值。
`modelAccess` 复用账号的模型规则。默认 `{"mode":"all","models":[]}` 允许成员账号原本可以使用的模型。
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。编辑器候选取自该组成员账号,账号自身的限制继续生效。
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。分组与账号共用[模型限制编辑器](#账号模型限制)。可从成员账号的目录勾选模型,也可在创建或编辑分组时手动添加目录外的 ID。分组和账号分别保存规则,账号自身的限制继续生效。
Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。
`fastMode` 默认跟随客户端。策略合并包括 Key 绑定的禁用分组,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端
@@ -2272,7 +2272,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
关联代理配置了自定义位置时优先使用代理值。保存后通过现有配置发布机制对新请求生效,
已开始请求及其重试保持同一份全局值;普通文本、绝对时间戳和数据驻留要求不受影响
`openaiRequestCountry` 单独控制 OpenAI Responses 出站正文顶层的 `request_country`。保存后对新请求生效。
`openaiRequestCountry` 仅控制发往 Codex OAuth 上游的 Responses 请求顶层字段 `request_country`。API Key 上游保留客户端原值,包括显式 `null`,客户端省略时也省略。保存后对新请求生效
| 管理端选项 | 设置值 | 发往上游的字段 |
| --- | --- | --- |
+4 -2
View File
@@ -361,7 +361,7 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结
| `views/<页面>/index.vue`、`views/<页面>/components/` | 页面组合与局部交互;复杂组件按职责拆成目录入口和相邻模块 |
| `views/<页面>/composables/` | 页面查询、轮询、表单及操作生命周期 |
| `presenter.ts`、页面 `utils/` | 纯展示投影或该页面拥有的业务转换,不启动请求 |
| `components/usage/`、`components/account/` | 跨页面复用的用量、健康时间线、套餐和额度窗口展示 |
| `components/usage/`、`components/account/` | 跨页面复用的用量、健康时间线、套餐和额度窗口展示,以及账号与分组共用的模型限制编辑器 |
| `composables/` | 请求取消与过期结果隔离、分页、选择、异步动作、目录加载等共享机制 |
| `i18n/` | Vue I18n 实例、三语资源和应用语言策略;从全局 Composer 派生 UI 库语言,不翻译用户数据或远端自由文本 |
| `utils/` | 按用途分开的数据解析、数字与时长格式化、位置校验、客户端配置、插件导航及颜色工具 |
@@ -1165,7 +1165,9 @@ Admin 按卡片与所选指标向 Store 请求计数、金额或分布,缓存
- 同一额度窗口内,每累计至少 5 个百分点形成一段,使用最近 3 个完整段及尾部计算合并比值,不平均逐请求的小分母比值
- 重复读数不增加段数,大于 1 个百分点的额度回落、累计计数倒退或窗口身份变化会中断采样
- 同窗口回落保留已记录累计;触顶后恢复可用不代表新周期,不能据此重设累计基线
- OpenAI 的窗口匹配复用限流解析器,核对桶、槽位、时长和明确套餐,只容许最多 2 秒的重置时间抖动
- 本周期累计从当前快照的窗口起点查询。OpenAI 历史读数须匹配额度桶、槽位、时长和明确套餐。重置时间的偏移本身不触发换段,已过期的读数不参与剩余量估算
- 当前窗口覆盖旧读数时,要有两次独立请求报告的到期时刻均已过去,且随后两次独立请求都显示已用比例回落超过 1 个百分点,才从新段首条读数重新累计。等待第二条读数期间保留累计并暂停估算
- 跳过缺少套餐的历史读数,确认套餐变化后从新段重新累计
- 重置后从新段重新累计,无法精确归属的用量不补算;只有账号在窗口开始前加入且无已知断点时,才允许以窗口累计量替代增量采样
- 历史点抽样不缩减区间累计用量,同一完成时间共用同一累计值
+27
View File
@@ -0,0 +1,27 @@
import type { Plugin } from 'vite'
const banner = `
██████╗ ██████╗ ██████╗
██╔════╝ ██╔══██╗ ██╔══██╗
██║ ██████╔╝ ██████╔╝
██║ ██╔═══╝ ██╔═██╗
╚██████╗ ██║ ██║ ██╗
╚═════╝ ╚═╝ ╚═╝ ╚═╝
https://github.com/zyycn/codex-proxy-rs`
export function consoleBanner(): Plugin {
return {
name: 'cpr-console-banner',
transformIndexHtml: {
order: 'pre',
handler: () => [
{
tag: 'script',
attrs: { type: 'module' },
children: `console.info(${JSON.stringify(banner)})`,
},
],
},
}
}
+1 -1
View File
@@ -17,7 +17,7 @@
},
"dependencies": {
"@boxicons/vue": "1.0.1",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.0",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.1",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lucide/vue": "^1.73.0",
+6 -6
View File
@@ -195,8 +195,8 @@ importers:
specifier: 1.0.1
version: 1.0.1(vue@3.5.45(typescript@6.0.3))
'@codex-proxy/ui':
specifier: github:zyycn/codex-proxy-ui#v0.13.0
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/498a491ea97dbb8c5cedbffd97064edab6969341(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))(yaml@2.9.0)
specifier: github:zyycn/codex-proxy-ui#v0.13.1
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))(yaml@2.9.0)
'@fontsource-variable/inter':
specifier: ^5.3.0
version: 5.3.0
@@ -456,9 +456,9 @@ 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/498a491ea97dbb8c5cedbffd97064edab6969341':
resolution: {gitHosted: true, integrity: sha512-/3G0XsMSCcijhwvwHL7HNLLaI9sEL03m0DDX/aVVGvqu13qsqn6rrsoBvSMgxjYgsvfd5ZnzvbI+ZCva8n/rhQ==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/498a491ea97dbb8c5cedbffd97064edab6969341}
version: 0.13.0
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee':
resolution: {gitHosted: true, integrity: sha512-pPner6XWo+saTWErInK+LLSUxbSmTtd274hrWorFnOfLqDNN2cTwl1UwDsPvaRShl7jy4dVxPC5vDWAgszwdZQ==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee}
version: 0.13.1
engines: {node: '>=24'}
peerDependencies:
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
@@ -3571,7 +3571,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/498a491ea97dbb8c5cedbffd97064edab6969341(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))(yaml@2.9.0)':
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))(yaml@2.9.0)':
dependencies:
'@ant-design/colors': 8.0.1
'@ant-design/fast-color': 3.0.1
+1 -1
View File
@@ -9,7 +9,7 @@ const canHover = useMediaQuery('(hover: hover)')
</script>
<template>
<ZPopover class="h-4 items-center" :trigger="canHover ? 'hover-click' : 'click'" placement="top-start" :hover-delay="240">
<ZPopover class="-ms-1.5 h-4 items-center" :trigger="canHover ? 'hover-click' : 'click'" placement="top-start" :hover-delay="240">
<template #reference="{ open }">
<ZIconButton variant="link" size="small" :aria-label="label" :aria-expanded="open" aria-haspopup="dialog">
<CircleAlert class="size-3.5" aria-hidden="true" />
+11 -26
View File
@@ -23,27 +23,12 @@ const providerIconComponent = computed(() => normalizedProvider.value
: undefined)
const authenticationIconComponent = computed(() => authenticationIcon(props.authenticationKind))
const showAuthenticationKind = computed(() => props.authenticationKind !== undefined)
const groupGapClass = computed(() => {
if (props.size === 'xs')
return 'gap-0.75'
return props.size === 'sm'
? 'gap-1'
: 'gap-2'
})
const iconContainerClass = computed(() => {
if (props.size === 'xs')
return 'size-4.5 rounded-md'
return props.size === 'sm'
? 'size-5 rounded-md'
: 'size-7 rounded-lg'
})
const iconClass = computed(() => {
if (props.size === 'xs')
return 'size-2.5'
return props.size === 'sm'
? 'size-3'
: 'size-4'
})
const sizeClasses = {
xs: { gap: 'gap-0.75', container: 'size-4.5 rounded-md', icon: 'size-2.5' },
sm: { gap: 'gap-1', container: 'size-5 rounded-md', icon: 'size-3' },
md: { gap: 'gap-2', container: 'size-7 rounded-lg', icon: 'size-4' },
}
const classes = computed(() => sizeClasses[props.size])
const providerLabel = computed(() => formatProviderLabel(props.provider, t('common.providers.unknown')))
@@ -51,23 +36,23 @@ const authenticationLabel = computed(() => formatAuthenticationLabel(props.authe
</script>
<template>
<span class="inline-flex items-center whitespace-nowrap" :class="groupGapClass">
<span class="inline-flex items-center whitespace-nowrap" :class="classes.gap">
<span
class="inline-flex shrink-0 items-center justify-center bg-z-fill-secondary/80 text-z-text"
:class="iconContainerClass"
:class="classes.container"
:title="providerLabel"
>
<component :is="providerIconComponent" v-if="providerIconComponent" :class="iconClass" />
<component :is="providerIconComponent" v-if="providerIconComponent" :class="classes.icon" />
<span v-else class="text-[10px] font-heavy text-z-text-quaternary">?</span>
</span>
<span
v-if="showAuthenticationKind"
class="inline-flex shrink-0 items-center justify-center bg-z-fill-secondary/80 text-z-text"
:class="iconContainerClass"
:class="classes.container"
:title="authenticationLabel"
>
<component :is="authenticationIconComponent" v-if="authenticationIconComponent" :class="iconClass" />
<component :is="authenticationIconComponent" v-if="authenticationIconComponent" :class="classes.icon" />
<span v-else class="text-[10px] font-heavy text-z-text-quaternary">?</span>
</span>
@@ -8,9 +8,9 @@ import { computed, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getAccountGroupModels, getAccountModels, refreshAccountModels } from '@/api'
import { useRequestState } from '@/composables/useRequestState'
import { accountModelAccessError, accountModelIdError, commonImageModels } from '../utils/modelAccess'
import AccountModelCleanupPopover from './AccountModelCleanupPopover.vue'
import AccountModelOption from './AccountModelOption.vue'
import { accountModelAccessError, accountModelIdError, commonImageModels } from './modelAccess'
const props = withDefaults(defineProps<{
accountId?: string
@@ -53,12 +53,10 @@ const modes = computed(() => [
},
{
value: 'allowlist',
disabled: props.groupId === null,
label: t('accounts.modelAccess.allowlist'),
},
{
value: 'denylist',
disabled: props.groupId === null,
label: t('accounts.modelAccess.blocklist'),
},
])
@@ -115,7 +113,7 @@ const groups = computed(() => [
ids: catalogResults.value,
},
].filter(group => group.ids.length))
const newModelId = computed(() => groupCatalog.value || groups.value.length
const newModelId = computed(() => groups.value.length
? ''
: search.value.trim())
const inputError = computed(() => selectionError.value || (newModelId.value && accountModelIdError(newModelId.value)))
@@ -301,17 +299,17 @@ watch(search, () => {
</ZFormItem>
<template v-if="restricted">
<div class="flex min-w-0 items-center gap-2">
<ZInput ref="searchInput" v-model="search" class="min-w-0 flex-1" :aria-label="groupCatalog ? t('groups.editor.searchModels') : t('accounts.modelAccess.searchOrAddModels')" :placeholder="groupCatalog ? t('groups.editor.searchModels') : t('accounts.modelAccess.searchOrEnterId')" :disabled="disabled" :aria-invalid="Boolean(inputError)" @keydown.enter="handleSearchEnter">
<ZInput ref="searchInput" v-model="search" class="min-w-0 flex-1" :aria-label="t('accounts.modelAccess.searchOrAddModels')" :placeholder="t('accounts.modelAccess.searchOrEnterId')" :disabled="disabled" :aria-invalid="Boolean(inputError)" @keydown.enter="handleSearchEnter">
<template #prefix>
<Search class="size-4" aria-hidden="true" />
</template>
</ZInput>
<ZButton v-if="!groupCatalog" class="shrink-0" :disabled="disabled || !canAdd" @click="addModels([newModelId])">
<ZButton class="shrink-0" :disabled="disabled || !canAdd" @click="addModels([newModelId])">
<Plus class="size-4" aria-hidden="true" />
{{ t('accounts.modelAccess.addModel') }}
</ZButton>
<ZIconButton
v-if="!groupCatalog && mode === 'allowlist'"
v-if="mode === 'allowlist'"
variant="plain"
:aria-label="t('accounts.modelAccess.addImageModels')"
:title="t('accounts.modelAccess.addImageModels')"
@@ -360,7 +358,7 @@ watch(search, () => {
<p v-else-if="mode === 'denylist' && canAdd" class="m-0 text-z-xs text-z-text-secondary">
{{ t('accounts.modelAccess.addToDenylistHint') }}
</p>
<ZEmpty v-else-if="!error && !search" :title="groupCatalog ? t('groups.editor.emptyCatalog') : t('accounts.modelAccess.noModels')" size="small" surface="none" />
<ZEmpty v-else-if="!error && !search" :title="t('accounts.modelAccess.noModels')" size="small" surface="none" />
</template>
</div>
</template>
+20 -16
View File
@@ -24,20 +24,24 @@ const parsed = computed(() => parseJsonObject(text.value, props.maximumBytes))
const error = computed(() => parsed.value.error)
const value = computed(() => parsed.value.value)
const fields = computed(() => inputFields(props.schema))
const hasExtra = computed(() => Object.keys(value.value ?? {}).some(key => !fields.value?.some(field => field.key === key)))
const incompatibleValue = computed(() => fields.value?.some((field) => {
const item = inputValue(field.key)
if (item === undefined)
const fieldsByKey = computed(() => new Map(fields.value?.map(field => [field.key, field])))
const canUseForm = computed(() => {
if (fields.value === null || error.value)
return false
if (field.values)
return !field.values.some(option => option === item)
if (field.type === 'number' || field.type === 'integer')
return typeof item !== 'number' && typeof item !== 'string'
return field.type === 'boolean'
? typeof item !== 'boolean'
: typeof item !== 'string'
}) ?? false)
const showJson = computed(() => jsonMode.value || fields.value === null || hasExtra.value || incompatibleValue.value || Boolean(error.value))
return Object.entries(value.value ?? {}).every(([key, item]) => {
const field = fieldsByKey.value.get(key)
if (!field)
return false
if (field.values)
return field.values.some(option => option === item)
if (field.type === 'number' || field.type === 'integer')
return typeof item === 'number' || typeof item === 'string'
return field.type === 'boolean'
? typeof item === 'boolean'
: typeof item === 'string'
})
})
const showJson = computed(() => jsonMode.value || !canUseForm.value)
const empty = computed(() => fields.value?.length === 0 && props.schema.additionalProperties === false && !showJson.value)
function fieldValue(field: InputField) {
@@ -105,8 +109,8 @@ function update(field: InputField, input: string) {
}
async function focusField(key?: string) {
const editableField = key && fields.value?.some(field => field.key === key)
if (editableField && jsonMode.value && !error.value && !hasExtra.value && !incompatibleValue.value)
const editableField = key && fieldsByKey.value.has(key)
if (editableField && canUseForm.value)
jsonMode.value = false
await nextTick()
@@ -128,7 +132,7 @@ defineExpose({ focusField })
<ZForm v-if="showJson">
<ZFormItem :label="t('common.form.inputPlaceholder')" :error="error">
<template #extra>
<ZIconButton v-if="fields !== null" :aria-label="t('common.form.useForm')" class="size-4!" variant="link" :disabled="disabled || Boolean(error) || hasExtra || incompatibleValue" @click="jsonMode = false">
<ZIconButton v-if="fields !== null" :aria-label="t('common.form.useForm')" class="size-4!" variant="link" :disabled="disabled || !canUseForm" @click="jsonMode = false">
<List class="size-3.5" />
</ZIconButton>
</template>
@@ -28,7 +28,6 @@ withDefaults(
defineProps<{
columns: TableColumn<UsageListRecord>[]
rows: UsageListRecord[]
requestDetails?: boolean
loading?: boolean
emptyText?: string
}>(),
@@ -97,7 +96,7 @@ const { t } = useI18n({ useScope: 'global' })
</template>
<template #createdAtDisplay="{ row }">
<UsageTimeCell :value="row.createdAtDisplay" :datetime="requestDetails ? row.createdAt : undefined" />
<UsageTimeCell :value="row.createdAtDisplay" :datetime="row.createdAt" />
</template>
<template #clientIp="{ row }">
@@ -1,12 +1,12 @@
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ value: string, datetime?: string }>()
const props = defineProps<{ value: string, datetime: string }>()
const parts = computed(() => props.value?.split(' '))
</script>
<template>
<time v-if="datetime && parts?.length === 2" :datetime="datetime" :title="value" class="grid gap-1 font-mono tabular-nums">
<time v-if="parts?.length === 2" :datetime="datetime" :title="value" class="grid gap-1 font-mono tabular-nums">
<span class="text-z-sm font-bold text-z-text">{{ parts[1] }}</span>
<span class="text-z-xs text-z-text-tertiary">{{ parts[0] }}</span>
</time>
@@ -58,6 +58,7 @@ export const usageDataColumns = computed(() => ([
key: 'createdAtDisplay',
label: t('usage.fields.time'),
kind: 'datetime',
width: 128,
},
{
key: 'clientIp',
+2 -1
View File
@@ -224,7 +224,7 @@
"upstreamCatalog": "Upstream catalog",
"selectAll": "Select all",
"deselectAll": "Deselect all",
"addToDenylistHint": "Saving blocks this ID on the account",
"addToDenylistHint": "Add and save to block this model",
"loadingModel": "Loading model",
"noModels": "No models",
"selectOrAddAtLeastOneModel": "Please select or add at least one model",
@@ -283,6 +283,7 @@
"actions": {
"deleteAccount": "Delete account",
"moreActions": "More actions",
"discoverPeer": "Detect CPR Link",
"disableScheduling": "Disable",
"enableScheduling": "Enable",
"refreshToken": "Refresh token",
-2
View File
@@ -43,8 +43,6 @@
"forceUltrafast": "Force Ultrafast",
"subagents": "Collaborative subagents",
"memberModels": "Member account models",
"searchModels": "Search member models",
"emptyCatalog": "Add an account with available models to this group first",
"fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.",
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent."
},
@@ -315,7 +315,10 @@
"day": "d",
"location": {
"requestCountry": "Request country",
"requestCountryDescription": "Choose how Codex requests send the country code",
"requestCountryScope": "Applies only to Codex OAuth accounts",
"countryHelp": "Request country mode help",
"countryMode": "Policy",
"countryModes": {
"default": "Null",
"passthrough": "Pass through",
@@ -224,7 +224,7 @@
"upstreamCatalog": "上游目录",
"selectAll": "全选",
"deselectAll": "取消全选",
"addToDenylistHint": "保存后,此账号将拒绝该模型",
"addToDenylistHint": "添加并保存后将拒绝该模型",
"loadingModel": "加载模型中",
"noModels": "暂无模型",
"selectOrAddAtLeastOneModel": "请至少选择或添加一个模型",
@@ -283,6 +283,7 @@
"actions": {
"deleteAccount": "删除账号",
"moreActions": "更多操作",
"discoverPeer": "检测 CPR 互联",
"disableScheduling": "停用",
"enableScheduling": "启用",
"refreshToken": "刷新令牌",
@@ -43,8 +43,6 @@
"forceUltrafast": "超快速",
"subagents": "协作子代理",
"memberModels": "成员账号模型",
"searchModels": "搜索成员账号模型",
"emptyCatalog": "暂无成员模型,请先将有模型的账号加入分组",
"fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择",
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求"
},
@@ -315,7 +315,10 @@
"day": "天",
"location": {
"requestCountry": "请求国家",
"requestCountryDescription": "设置 Codex 请求如何发送国家代码",
"requestCountryScope": "仅用于 Codex OAuth 账号",
"countryHelp": "请求国家模式说明",
"countryMode": "策略",
"countryModes": {
"default": "空值",
"passthrough": "透传",
@@ -224,7 +224,7 @@
"upstreamCatalog": "上游目錄",
"selectAll": "全選",
"deselectAll": "取消全選",
"addToDenylistHint": "保存後,此賬號將拒絕該模型",
"addToDenylistHint": "加入並儲存後將拒絕此模型",
"loadingModel": "加載模型中",
"noModels": "暫無模型",
"selectOrAddAtLeastOneModel": "請至少選擇或添加一個模型",
@@ -283,6 +283,7 @@
"actions": {
"deleteAccount": "刪除賬號",
"moreActions": "更多操作",
"discoverPeer": "偵測 CPR 互聯",
"disableScheduling": "停用",
"enableScheduling": "啓用",
"refreshToken": "刷新令牌",
@@ -43,8 +43,6 @@
"forceUltrafast": "超快速",
"subagents": "協作子代理",
"memberModels": "成員帳號模型",
"searchModels": "搜尋成員帳號模型",
"emptyCatalog": "暫無成員模型,請先將有模型的帳號加入分組",
"fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇",
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求"
},
@@ -315,7 +315,10 @@
"day": "天",
"location": {
"requestCountry": "請求國家",
"requestCountryDescription": "設定 Codex 請求如何傳送國家代碼",
"requestCountryScope": "僅用於 Codex OAuth 帳號",
"countryHelp": "請求國家模式說明",
"countryMode": "策略",
"countryModes": {
"default": "空值",
"passthrough": "透傳",
@@ -3,8 +3,8 @@ import type { AccountGroupRef, AccountModelAccess } from '@/api'
import { ZFormItem, ZInput, ZSwitch, ZTextarea } from '@codex-proxy/ui'
import { useI18n } from 'vue-i18n'
import AccountModelAccessField from '@/components/account/model-access/index.vue'
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
import AccountModelAccessField from './AccountModelAccessField.vue'
import AccountNameField from './AccountNameField.vue'
import AccountProxyField from './AccountProxyField.vue'
@@ -3,7 +3,7 @@ import type { Account } from '@/api'
import { ZIconButton, ZMenuItem } from '@codex-proxy/ui'
import { Download, KeyRound, Pencil, Power, RefreshCw, RotateCcw, Trash2, Wifi } from '@lucide/vue'
import { Download, KeyRound, Link2, Pencil, Power, RefreshCw, RotateCcw, Trash2, Wifi } from '@lucide/vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -15,6 +15,7 @@ const props = defineProps<{
downloadingCatalog: boolean
recovering: boolean
refreshing: boolean
refreshingQuota: boolean
testing: boolean
togglingScheduling: boolean
}>()
@@ -25,6 +26,7 @@ const emit = defineEmits<{
recover: [accountId: string]
test: [account: Account]
refresh: [accountId: string]
discoverPeer: [accountId: string]
reauthorize: [account: Account]
downloadModelCatalog: [account: Account]
toggleScheduling: [account: Account]
@@ -65,6 +67,17 @@ const credentialEligible = computed(() => props.account.authenticationKind === '
</template>
{{ t('accounts.connectionTest.title') }}
</ZMenuItem>
<ZMenuItem
v-if="account.upstream && !account.upstream.discovered"
:loading="refreshingQuota"
:disabled="refreshingQuota"
@click.stop="emit('discoverPeer', account.id)"
>
<template #icon>
<Link2 class="size-3.5 text-z-text-quaternary" />
</template>
{{ t('accounts.actions.discoverPeer') }}
</ZMenuItem>
<ZMenuItem
:loading="togglingScheduling"
:disabled="togglingScheduling"
@@ -47,7 +47,7 @@ const forecastOpen = shallowRef(false)
const hasPlanBadge = computed(() => Boolean(props.account.planType) || props.account.authenticationKind === 'api_key')
const hasForecast = computed(() => props.account.authenticationKind !== 'api_key')
const hasPersonalInfo = computed(() => props.account.capabilities.profile || props.account.capabilities.subscription)
const canRefresh = computed(() => props.account.capabilities.quotaRefresh || props.account.upstream != null)
const canRefresh = computed(() => props.account.capabilities.quotaRefresh || props.account.upstream?.discovered)
const hasActions = computed(() => hasPersonalInfo.value || hasForecast.value || canRefresh.value || props.account.capabilities.resetCredits)
const lastRefreshed = computed(() => {
const { upstream, quota } = props.account
@@ -2,8 +2,8 @@ import type { FormRules } from '@codex-proxy/ui'
import type { AccountModelAccess } from '@/api'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { accountModelAccessError } from '@/components/account/model-access/modelAccess'
import { accountNameValid } from '../utils/accountName'
import { accountModelAccessError } from '../utils/modelAccess'
interface AccountSettingsFormValue {
name?: string
+2
View File
@@ -353,11 +353,13 @@ const {
:downloading-catalog="downloadingCatalogAccountIds.has(row.id)"
:recovering="recoveringAccountIds.has(row.id)"
:refreshing="refreshingAccountIds.has(row.id)"
:refreshing-quota="refreshingQuotaAccountIds.has(row.id)"
:testing="testingAccountId === row.id"
:toggling-scheduling="togglingSchedulingAccountIds.has(row.id)"
@edit="openAccountEdit"
@delete="requestDeleteAccount"
@download-model-catalog="handleDownloadModelCatalog"
@discover-peer="handleRefreshQuota"
@recover="handleRecover"
@refresh="handleRefresh"
@reauthorize="openReauthorizeAccount"
@@ -7,9 +7,9 @@ import { normalizeRgbaHexColor, ZButton, ZColorPicker, ZDialog, ZForm, ZFormItem
import { computed, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import AccountModelAccessField from '@/components/account/model-access/index.vue'
import { accountModelAccessError } from '@/components/account/model-access/modelAccess'
import HelpPopover from '@/components/HelpPopover.vue'
import AccountModelAccessField from '@/views/accounts/components/AccountModelAccessField.vue'
import { accountModelAccessError } from '@/views/accounts/utils/modelAccess'
import { ACCOUNT_GROUP_COLOR_PRESETS } from '../constants'
const props = defineProps<{
@@ -81,7 +81,7 @@ const description = computed(() => props.group
width="42rem"
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
>
<ZForm ref="formElement" :model="form" :rules="rules" class="sm:grid-cols-[minmax(0,1fr)_fit-content(10rem)] sm:gap-x-6" scroll-to-error focus-on-error novalidate @submit="requestSave">
<ZForm ref="formElement" :model="form" :rules="rules" class="sm:grid-cols-[minmax(0,1fr)_fit-content(10rem)] sm:gap-x-6 md:grid-cols-[minmax(0,1fr)_fit-content(11rem)]" scroll-to-error focus-on-error novalidate @submit="requestSave">
<ZFormItem prop="name" :show-message="false" :label="t('groups.editor.groupName')" required>
<ZInput
v-model="form.name"
@@ -99,7 +99,7 @@ const description = computed(() => props.group
:disabled="saving"
/>
</ZFormItem>
<div class="col-span-full grid grid-cols-2 items-start gap-x-6 gap-y-4.5 sm:grid-cols-subgrid **:[[role=radio]]:px-3.5">
<div class="col-span-full grid grid-cols-2 items-start gap-x-6 gap-y-4.5 sm:grid-cols-subgrid **:[[role=radio]]:px-3.5 md:**:[[role=radio]]:px-4.5">
<div class="contents sm:flex sm:min-w-0 sm:flex-wrap sm:items-start sm:gap-x-6 sm:gap-y-4.5">
<ZFormItem :label="t('groups.editor.fastMode')" class="col-span-full sm:flex-auto">
<template #label-extra>
@@ -65,7 +65,7 @@ const { visibleColumns, columnOptions, setColumnVisible, setColumnOrder, resetCo
<UsagePerformanceCell :record="row" />
</template>
<template #createdAtDisplay="{ row }">
<UsageTimeCell :value="row.createdAtDisplay" />
<UsageTimeCell :value="row.createdAtDisplay" :datetime="row.createdAt" />
</template>
<template #clientIp="{ row }">
<UsageClientIpCell :record="row" />
@@ -4,7 +4,7 @@ import type { ProxyBatchItem } from '../utils/batch'
import { ZScrollbar } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { proxyBatchStates } from '../utils/batch'
import { proxyBatchStates, summarizeProxyBatch, summarizeProxyTests } from '../utils/batch'
import ProxyRegion from './ProxyRegion.vue'
const props = defineProps<{ items: ProxyBatchItem[], tests?: ProxyBatchItem[] }>()
@@ -12,51 +12,61 @@ const props = defineProps<{ items: ProxyBatchItem[], tests?: ProxyBatchItem[] }>
const { t } = useI18n({ useScope: 'global' })
const testItems = computed(() => props.tests ?? [])
function resultMessage(item: ProxyBatchItem, test?: ProxyBatchItem) {
if (test && test.status !== 'succeeded')
return test.message
const detection = test?.record?.lastTest?.location
if (detection?.status === 'failed')
return detection.message
return item.status === 'succeeded'
? ''
: item.message
}
const rows = computed(() => {
const tests = new Map(testItems.value.map(item => [item.key, item]))
return props.items.map((item) => {
const test = item.record
? tests.get(item.record.id)
: undefined
const detection = test?.record?.lastTest?.location
const status = (test ?? item).status
const state = proxyBatchStates.value[status]
let label = state.label
if (status === 'succeeded') {
label = test
? t('proxies.batchTest.connectionIsNormal')
: t('proxies.batchTest.addedStatus')
}
return {
item,
test,
result: test ?? item,
message: test && test.status !== 'succeeded'
? test.message
: detection?.status === 'failed'
? detection.message
: item.status !== 'succeeded'
? item.message
: '',
label,
tone: state.tone,
message: resultMessage(item, test),
messageTone: status === 'succeeded'
? 'text-z-warning-text'
: state.tone,
}
})
})
const completed = computed(() => props.items.filter(item => !['pending', 'running', 'skipped'].includes(item.status)).length)
const created = computed(() => props.items.filter(item => item.status === 'succeeded').length)
const invalid = computed(() => props.items.filter(item => item.status === 'failed').length)
const succeeded = computed(() => testItems.value.filter(item => item.status === 'succeeded').length)
const failed = computed(() => testItems.value.filter(item => item.status === 'failed').length)
const allOperations = computed(() => [
...props.items,
...testItems.value,
])
const attention = computed(() => allOperations.value.filter(item => ['error', 'conflict', 'busy', 'unknown'].includes(item.status)).length)
const skipped = computed(() => allOperations.value.filter(item => item.status === 'skipped').length)
const locationPending = computed(() => testItems.value.filter(item => item.status === 'succeeded' && item.record?.lastTest?.location.status !== 'detected').length)
const additions = computed(() => summarizeProxyBatch(props.items))
const connections = computed(() => summarizeProxyTests(testItems.value))
const attention = computed(() => additions.value.attention + connections.value.attention)
const skipped = computed(() => additions.value.skipped + connections.value.skipped)
</script>
<template>
<section class="min-w-0 space-y-3" :aria-label="t('proxies.batchTest.resultsTitle')">
<div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-z-xs text-z-text-secondary" role="status" aria-live="polite">
<span>{{ t('proxies.batchTest.processed') }} <strong class="font-mono font-medium text-z-text">{{ completed }} / {{ items.length }}</strong></span>
<span>{{ t('proxies.batchTest.added', { created }) }}</span>
<span v-if="invalid">{{ t('proxies.batchTest.invalidFormat', { invalid }) }}</span>
<span>{{ t('proxies.batchTest.processed') }} <strong class="font-mono font-medium text-z-text">{{ additions.completed }} / {{ items.length }}</strong></span>
<span>{{ t('proxies.batchTest.added', { created: additions.succeeded }) }}</span>
<span v-if="additions.failed">{{ t('proxies.batchTest.invalidFormat', { invalid: additions.failed }) }}</span>
<template v-if="testItems.length">
<span>{{ t('proxies.batchTest.connected', { succeeded }) }}</span>
<span>{{ t('proxies.batchTest.connectionFailed', { failed }) }}</span>
<span v-if="locationPending">{{ t('proxies.batchTest.locationPending', { locationPending }) }}</span>
<span>{{ t('proxies.batchTest.connected', { succeeded: connections.succeeded }) }}</span>
<span>{{ t('proxies.batchTest.connectionFailed', { failed: connections.failed }) }}</span>
<span v-if="connections.locationPending">{{ t('proxies.batchTest.locationPending', { locationPending: connections.locationPending }) }}</span>
</template>
<span v-if="attention">{{ t('proxies.batchTest.needsAttention', { attention }) }}</span>
<span v-if="skipped">{{ t('proxies.batchTest.skipped', { skipped }) }}</span>
@@ -65,9 +75,9 @@ const locationPending = computed(() => testItems.value.filter(item => item.statu
<ol class="m-0 list-none space-y-1 p-0">
<li v-for="row in rows" :key="row.item.key" class="grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1 rounded-z-sm px-3 py-2.5 odd:bg-z-fill-quaternary">
<span class="min-w-0 truncate font-mono text-z-xs text-z-text" :title="row.item.endpoint">{{ row.item.endpoint || t('proxies.batchTest.lineNumber', { key: row.item.key }) }}</span>
<span class="flex flex-wrap justify-end gap-x-2 text-z-xs" :class="proxyBatchStates[row.result.status].tone">
<span class="flex flex-wrap justify-end gap-x-2 text-z-xs" :class="row.tone">
<span v-if="row.test" class="text-z-text-secondary">{{ t('proxies.batchTest.addedStatus') }}</span>
<span>{{ row.result.status === 'succeeded' ? row.test ? t('proxies.batchTest.connectionIsNormal') : t('proxies.batchTest.addedStatus') : proxyBatchStates[row.result.status].label }}</span>
<span>{{ row.label }}</span>
</span>
<div class="col-span-2 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-z-xs text-z-text-secondary">
<span class="max-w-full truncate" :title="row.item.name">{{ row.item.name }}</span>
@@ -76,7 +86,7 @@ const locationPending = computed(() => testItems.value.filter(item => item.statu
<span class="whitespace-nowrap">{{ row.test.record.lastTest.latencyMs }} ms</span><span v-if="row.test.record.lastTest.exitIpv4"> · IPv4 {{ row.test.record.lastTest.exitIpv4 }}</span><span v-if="row.test.record.lastTest.exitIpv6"> · IPv6 {{ row.test.record.lastTest.exitIpv6 }}</span>
</span>
</div>
<span v-if="row.message" class="col-span-2 text-z-xs leading-relaxed wrap-anywhere" :class="row.result.status === 'succeeded' ? 'text-z-warning-text' : proxyBatchStates[row.result.status].tone">{{ row.message }}</span>
<span v-if="row.message" class="col-span-2 text-z-xs leading-relaxed wrap-anywhere" :class="row.messageTone">{{ row.message }}</span>
</li>
</ol>
</ZScrollbar>
@@ -4,6 +4,7 @@ import { getProxies } from '@/api'
import { useRequestState } from '@/composables/useRequestState'
import { t } from '@/i18n'
import { notification as ZNotification } from '@/utils/notification'
import { summarizeProxyTests } from '../utils/batch'
import { useProxyBatchTest } from './useProxyBatchTest'
export function useProxyBatchTesting(options: { test: ProxyTestExecutor, reload: () => Promise<unknown> }) {
@@ -48,23 +49,22 @@ export function useProxyBatchTesting(options: { test: ProxyTestExecutor, reload:
await options.reload()
if (!request.isCurrent(requestId))
return
const succeeded = tests.items.value.filter(item => item.status === 'succeeded').length
const incomplete = tests.items.value.filter(item => item.status !== 'succeeded')
const locationPending = tests.items.value.filter(item => item.status === 'succeeded' && item.record?.lastTest?.location.status !== 'detected').length
const { succeeded, locationPending } = summarizeProxyTests(tests.items.value)
const incomplete = tests.items.value.length - succeeded
const missing = wanted.size - collected.size
const summary = [
t('proxies.batchTest.batchTestCompletedConnected', { succeeded }),
]
if (incomplete.length)
summary.push(t('proxies.batchTest.unsuccessful', { count: incomplete.length }))
if (incomplete)
summary.push(t('proxies.batchTest.unsuccessful', { count: incomplete }))
if (locationPending)
summary.push(t('proxies.batchTest.locationsPending', { locationPending }))
if (missing)
summary.push(t('proxies.batchTest.proxiesNoLongerAvailable', { missing }))
const firstFailure = incomplete.find(item => item.status !== 'skipped')
const firstFailure = tests.items.value.find(item => item.status !== 'succeeded' && item.status !== 'skipped')
if (firstFailure)
summary.push(`${firstFailure.name}:${firstFailure.message}`)
const notify = incomplete.length || locationPending || missing
const notify = incomplete || locationPending || missing
? ZNotification.warning
: ZNotification.success
notify({
+20
View File
@@ -1,4 +1,5 @@
import type { OutboundProxyRecord, ProxyBatchResult } from '@/api'
import { countBy } from 'es-toolkit'
import { computed } from 'vue'
import { ApiError } from '@/api/request'
import { t } from '@/i18n'
@@ -23,6 +24,25 @@ export interface ProxyBatchItem {
record?: OutboundProxyRecord
}
export function summarizeProxyBatch(items: ProxyBatchItem[]) {
const counts = countBy(items, item => item.status)
const skipped = counts.skipped ?? 0
return {
completed: items.length - (counts.pending ?? 0) - (counts.running ?? 0) - skipped,
succeeded: counts.succeeded ?? 0,
failed: counts.failed ?? 0,
attention: (counts.error ?? 0) + (counts.conflict ?? 0) + (counts.busy ?? 0) + (counts.unknown ?? 0),
skipped,
}
}
export function summarizeProxyTests(items: ProxyBatchItem[]) {
return {
...summarizeProxyBatch(items),
locationPending: items.filter(item => item.status === 'succeeded' && item.record?.lastTest?.location.status !== 'detected').length,
}
}
export interface ProxyBatchInput {
line: number
raw: string
@@ -0,0 +1,80 @@
<script setup lang="ts">
import type { SelectOption } from '@codex-proxy/ui/select'
import type { OpenAiRequestCountry } from '@/api'
import { ZCard, ZFormItem, ZSelect } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import CountryCodeField from '@/components/CountryCodeField.vue'
import HelpPopover from '@/components/HelpPopover.vue'
defineProps<{ disabled: boolean }>()
const { t } = useI18n({ useScope: 'global' })
const requestCountry = defineModel<OpenAiRequestCountry>({ required: true })
const modes = computed<Array<SelectOption<OpenAiRequestCountry['mode']> & { help: string }>>(() => [
{
value: 'follow_location',
label: t('settings.location.countryModes.follow_location'),
help: t('settings.location.countryHints.follow_location'),
},
{
value: 'default',
label: t('settings.location.countryModes.default'),
help: t('settings.location.countryHints.default'),
},
{
value: 'passthrough',
label: t('settings.location.countryModes.passthrough'),
help: t('settings.location.countryHints.passthrough'),
},
{
value: 'custom',
label: t('settings.location.countryModes.custom'),
help: t('settings.location.countryHints.custom'),
},
])
function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
if (mode && mode !== requestCountry.value.mode) {
requestCountry.value = mode === 'custom'
? { mode, country: '' }
: { mode }
}
}
</script>
<template>
<ZCard :description="t('settings.location.requestCountryDescription')">
<template #title>
<span class="inline-flex items-center gap-1.5">
{{ t('settings.location.requestCountry') }}
<HelpPopover :label="t('settings.location.countryHelp')">
<p class="mb-2 font-emphasis text-z-text">
{{ t('settings.location.requestCountryScope') }}
</p>
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
<template v-for="mode in modes" :key="mode.value">
<dt class="font-emphasis text-z-text">
{{ mode.label }}
</dt>
<dd>{{ mode.help }}</dd>
</template>
</dl>
</HelpPopover>
</span>
</template>
<div class="grid min-w-0 max-w-6xl items-start gap-4.5 sm:grid-cols-2">
<ZFormItem :label="t('settings.location.countryMode')">
<ZSelect :model-value="requestCountry.mode" :options="modes" :aria-label="t('settings.location.countryMode')" :disabled="disabled" @update:model-value="setMode" />
</ZFormItem>
<CountryCodeField
v-if="requestCountry.mode === 'custom'"
:model-value="requestCountry.country"
form-prop="openaiRequestCountry.country"
:label="t('settings.location.customCountryCode')"
:disabled="disabled"
@update:model-value="requestCountry = { mode: 'custom', country: $event }"
/>
</div>
</ZCard>
</template>
@@ -1,12 +1,8 @@
<script setup lang="ts">
import type { SelectOption } from '@codex-proxy/ui/select'
import type { OpenAiRequestCountry, RequestLocation } from '@/api'
import type { RequestLocation } from '@/api'
import { ZCard, ZFormItem, ZSelect, ZSwitch } from '@codex-proxy/ui'
import { computed } from 'vue'
import { ZCard, ZSwitch } from '@codex-proxy/ui'
import { useI18n } from 'vue-i18n'
import CountryCodeField from '@/components/CountryCodeField.vue'
import HelpPopover from '@/components/HelpPopover.vue'
import RequestLocationDetectButton from '@/components/RequestLocationDetectButton.vue'
import RequestLocationFields from '@/components/RequestLocationFields.vue'
@@ -18,37 +14,6 @@ const { t } = useI18n({ useScope: 'global' })
const location = defineModel<RequestLocation>({ required: true })
const enabled = defineModel<boolean>('enabled', { required: true })
const requestCountry = defineModel<OpenAiRequestCountry>('requestCountry', { required: true })
const modes = computed<Array<SelectOption<OpenAiRequestCountry['mode']> & { help: string }>>(() => [
{
value: 'follow_location',
label: t('settings.location.countryModes.follow_location'),
help: t('settings.location.countryHints.follow_location'),
},
{
value: 'default',
label: t('settings.location.countryModes.default'),
help: t('settings.location.countryHints.default'),
},
{
value: 'passthrough',
label: t('settings.location.countryModes.passthrough'),
help: t('settings.location.countryHints.passthrough'),
},
{
value: 'custom',
label: t('settings.location.countryModes.custom'),
help: t('settings.location.countryHints.custom'),
},
])
function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
if (mode && mode !== requestCountry.value.mode) {
requestCountry.value = mode === 'custom'
? { mode, country: '' }
: { mode }
}
}
</script>
<template>
@@ -58,34 +23,7 @@ function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
<ZSwitch v-model="enabled" :label="t('settings.location.enableLocationOverlay')" :disabled="disabled" />
<RequestLocationDetectButton :loading="detectingLocation" :disabled="disabled" @detect="emit('detectLocation')" />
</div>
<div class="grid min-w-0 gap-4.5 mt-4 max-w-6xl">
<RequestLocationFields v-model="location" :form-prop="enabled ? 'requestLocation' : undefined" :disabled="disabled || !enabled" />
<div class="grid gap-4.5 sm:grid-cols-2">
<ZFormItem :label="t('settings.location.requestCountry')">
<template #label-extra>
<HelpPopover :label="t('settings.location.countryHelp')">
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
<template v-for="mode in modes" :key="mode.value">
<dt class="font-emphasis text-z-text">
{{ mode.label }}
</dt>
<dd>{{ mode.help }}</dd>
</template>
</dl>
</HelpPopover>
</template>
<ZSelect :model-value="requestCountry.mode" :options="modes" :aria-label="t('settings.location.requestCountry')" :disabled="disabled" @update:model-value="setMode" />
</ZFormItem>
<CountryCodeField
v-if="requestCountry.mode === 'custom'"
:model-value="requestCountry.country"
form-prop="openaiRequestCountry.country"
:label="t('settings.location.customCountryCode')"
:disabled="disabled"
@update:model-value="requestCountry = { mode: 'custom', country: $event }"
/>
</div>
</div>
<RequestLocationFields v-model="location" class="mt-4 max-w-6xl" :form-prop="enabled ? 'requestLocation' : undefined" :disabled="disabled || !enabled" />
</template>
</ZCard>
</template>
+2 -1
View File
@@ -17,6 +17,7 @@ import ConcurrencyPolicyCard from './components/ConcurrencyPolicyCard.vue'
import AccountErrorProtectionCard from './components/error-protection/AccountErrorProtectionCard.vue'
import ModelAliasesCard from './components/ModelAliasesCard.vue'
import PrivacyPolicyCard from './components/privacy/PrivacyPolicyCard.vue'
import RequestCountryCard from './components/RequestCountryCard.vue'
import RequestHistoryCard from './components/RequestHistoryCard.vue'
import RequestLocationCard from './components/RequestLocationCard.vue'
import ResetCreditCard from './components/ResetCreditCard.vue'
@@ -246,11 +247,11 @@ watch(section, (value) => {
<RequestLocationCard
v-model="form.requestLocation"
v-model:enabled="form.requestLocationEnabled"
v-model:request-country="form.openaiRequestCountry"
:disabled="disabled"
:detecting-location="detectingLocation"
@detect-location="detectLocation"
/>
<RequestCountryCard v-model="form.openaiRequestCountry" :disabled="disabled" />
<PrivacyPolicyCard v-model="form.codexPrivacyPolicy" :disabled="disabled" />
<ModelAliasesCard
:mappings="mappings"
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { EChartsOption, LineSeriesOption } from 'echarts'
import type { EChartsOption } from 'echarts'
import type { UsageCostMetric, UsageMetricResponse } from '@/api'
import { ZCard, ZEmpty, ZSegmented } from '@codex-proxy/ui'
@@ -7,12 +7,10 @@ import { ZCard, ZEmpty, ZSegmented } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import BaseChart from '@/components/charts/BaseChart.vue'
import {
zeroInactiveValues,
} from '@/components/charts/timeSeriesGap'
import { zeroInactiveValues } from '@/components/charts/timeSeriesGap'
import { chartTooltipContent, tooltipIndex, tooltipRows } from '@/components/charts/tooltip'
import { useChartPalette } from '@/composables/useChartPalette'
import { decimalDisplayNumber, formatLocalizedCompactNumber as formatCompactNumber, formatPercent, formatUsd } from '@/utils/format'
import { decimalDisplayNumber, formatPercent, formatUsd } from '@/utils/format'
import {
formatUsdAxis,
@@ -37,23 +35,19 @@ const props = withDefaults(
const { t } = useI18n({ useScope: 'global' })
type UsageChartPalette = ReturnType<typeof useChartPalette>['palette']['value']
interface CostSeries {
label: string
color: string
values: (number | null)[]
area?: 'strong'
tooltipValue: (index: number) => string | null
}
const activeView = defineModel<UsageCostMetric>({ required: true })
const { palette } = useChartPalette()
const cost = computed(() => props.result?.data.summary ?? null)
const points = computed(() => props.result?.data.points ?? [])
const costPoints = computed(() => props.result?.metric === 'cost'
? props.result.data.points
: [])
const savingsPoints = computed(() => props.result?.metric === 'savings'
? props.result.data.points
: [])
const cachePoints = computed(() => props.result?.metric === 'cache'
? props.result.data.points
: [])
const requestActivity = computed(() => points.value.map(point => point.requestCount > 0))
const hasNoCacheCost = computed(() => costPoints.value.some(point => point.value.noCacheCost != null))
const coverageRate = computed(() => {
if (!cost.value)
return null
@@ -79,21 +73,79 @@ const viewOptions = computed(() => ([
},
]))
const hasData = computed(() => {
if (props.loading || props.result?.metric !== activeView.value)
return false
if (activeView.value === 'cost')
return costPoints.value.some(point => point.value.estimatedCost != null || point.value.noCacheCost != null)
if (activeView.value === 'savings')
return savingsPoints.value.some(point => point.value != null)
return cachePoints.value.some(({ value }) => value.inputTokens > 0 || value.cachedTokenRate > 0 || (value.cacheHitRequestRate ?? 0) > 0)
function amountValues(amounts: (string | null)[]) {
return zeroInactiveValues(amounts.map(amount => decimalDisplayNumber(amount)), requestActivity.value)
}
function primaryAmountSeries(label: string, amounts: (string | null)[]): CostSeries {
return {
label,
color: palette.value.success,
area: 'strong',
values: amountValues(amounts),
tooltipValue: index => formatUsd(amounts[index] ?? (requestActivity.value[index] === false
? '0'
: null)),
}
}
function rateSeries(label: string, color: string, values: (number | null)[]): CostSeries {
return {
label,
color,
values,
tooltipValue: index => formatPercent(values[index] ?? null),
}
}
const chart = computed<{ hasData: boolean, series: CostSeries[] }>(() => {
const response = props.result
if (props.loading || !response || response.metric !== activeView.value)
return { hasData: false, series: [] }
if (response.metric === 'cost') {
const actual = response.data.points.map(({ value }) => value.estimatedCost)
const comparison = response.data.points.map(({ value }) => value.noCacheCost)
const hasComparison = comparison.some(amount => amount != null)
const series = [
primaryAmountSeries(t('usage.cost.actualCost'), actual),
]
if (hasComparison) {
series.push({
label: t('usage.cost.withoutCacheEstimate'),
color: palette.value.textMuted,
values: amountValues(comparison),
// 对比曲线允许补零,提示只展示该时间桶实际提供的估算
tooltipValue: index => comparison[index] == null
? null
: formatUsd(comparison[index]),
})
}
return { hasData: hasComparison || actual.some(amount => amount != null), series }
}
if (response.metric === 'savings') {
const savings = response.data.points.map(point => point.value)
return {
hasData: savings.some(amount => amount != null),
series: [
primaryAmountSeries(t('usage.cost.cacheSavings'), savings),
],
}
}
const { points } = response.data
return {
hasData: points.some(({ value }) => value.inputTokens > 0 || value.cachedTokenRate > 0 || (value.cacheHitRequestRate ?? 0) > 0),
series: [
rateSeries(t('usage.cost.cacheTokenProportion'), palette.value.normal, points.map(({ value }) => value.cachedTokenRate)),
rateSeries(t('usage.cost.hitRequestRate'), palette.value.success, points.map(({ value }) => value.cacheHitRequestRate)),
],
}
})
const chartOption = computed<EChartsOption>(() => {
const theme = palette.value
const legend = legendNames()
const series = chartSeries(theme)
const series = chart.value.series
return {
animationDuration: 240,
grid: {
@@ -104,157 +156,34 @@ const chartOption = computed<EChartsOption>(() => {
outerBoundsMode: 'same',
outerBoundsContain: 'axisLabel',
},
legend: usageLegend(theme, legend),
legend: usageLegend(theme, series.map(item => item.label)),
tooltip: usageTooltip(theme, formatTooltip),
xAxis: usageCategoryAxis(
points.value.map(point => point.label),
theme,
),
yAxis: usageValueAxis(theme, axisFormatter(), {
min: activeView.value === 'cache'
? 0
: undefined,
max: activeView.value === 'cache'
? 1
: undefined,
}),
series,
yAxis: activeView.value === 'cache'
? usageValueAxis(theme, formatPercent, { min: 0, max: 1 })
: usageValueAxis(theme, formatUsdAxis),
series: series.flatMap(item => usageGapAwareLineSeries(item.label, item.values, item.color, { area: item.area })),
}
})
function legendNames() {
if (activeView.value === 'savings') {
return [
t('usage.cost.cacheSavings'),
]
}
if (activeView.value === 'cache') {
return [
t('usage.cost.cacheTokenProportion'),
t('usage.cost.hitRequestRate'),
]
}
return hasNoCacheCost.value
? [
t('usage.cost.actualCost'),
t('usage.cost.withoutCacheEstimate'),
]
: [
t('usage.cost.actualCost'),
]
}
function axisFormatter() {
if (activeView.value === 'cost' || activeView.value === 'savings')
return formatUsdAxis
if (activeView.value === 'cache')
return (value: number) => formatPercent(value)
return (value: number) => formatCompactNumber(value)
}
function chartSeries(theme: UsageChartPalette): LineSeriesOption[] {
if (activeView.value === 'savings') {
return [
...usageGapAwareLineSeries(
t('usage.cost.cacheSavings'),
zeroInactiveValues(
savingsPoints.value.map(point => decimalDisplayNumber(point.value)),
requestActivity.value,
),
theme.success,
{ area: 'strong' },
),
]
}
if (activeView.value === 'cache') {
return [
...usageGapAwareLineSeries(
t('usage.cost.cacheTokenProportion'),
cachePoints.value.map(point => point.value.cachedTokenRate),
theme.normal,
),
...usageGapAwareLineSeries(
t('usage.cost.hitRequestRate'),
cachePoints.value.map(point => point.value.cacheHitRequestRate),
theme.success,
),
]
}
const series = [
...usageGapAwareLineSeries(
t('usage.cost.actualCost'),
zeroInactiveValues(
costPoints.value.map(point => decimalDisplayNumber(point.value.estimatedCost)),
requestActivity.value,
),
theme.success,
{ area: 'strong' },
),
]
if (hasNoCacheCost.value) {
series.push(
...usageGapAwareLineSeries(
t('usage.cost.withoutCacheEstimate'),
zeroInactiveValues(
costPoints.value.map(point => decimalDisplayNumber(point.value.noCacheCost)),
requestActivity.value,
),
theme.textMuted,
),
)
}
return series
}
function formatTooltip(params: unknown) {
const rows = tooltipRows(params)
const pointIndex = tooltipIndex(rows[0])
const point = points.value[pointIndex]
const index = tooltipIndex(tooltipRows(params)[0])
const point = points.value[index]
if (!point)
return ''
const theme = palette.value
if (activeView.value === 'savings') {
return chartTooltipContent(point.label, [
usageTooltipItem(
t('usage.cost.cacheSavings'),
formatUsd(costAmount(savingsPoints.value[pointIndex]?.value ?? null, pointIndex)),
theme.success,
),
])
}
if (activeView.value === 'cache') {
return chartTooltipContent(point.label, [
usageTooltipItem(t('usage.cost.cacheTokenProportion'), formatPercent(cachePoints.value[pointIndex]?.value.cachedTokenRate ?? null), theme.normal),
usageTooltipItem(t('usage.cost.hitRequestRate'), formatPercent(cachePoints.value[pointIndex]?.value.cacheHitRequestRate ?? null), theme.success),
])
}
const lines = [
usageTooltipItem(
t('usage.cost.actualCost'),
formatUsd(costAmount(costPoints.value[pointIndex]?.value.estimatedCost ?? null, pointIndex)),
theme.success,
),
]
if (costPoints.value[pointIndex]?.value.noCacheCost != null) {
lines.push(usageTooltipItem(
t('usage.cost.withoutCacheEstimate'),
formatUsd(costAmount(costPoints.value[pointIndex]?.value.noCacheCost ?? null, pointIndex)),
theme.textMuted,
))
}
const lines = chart.value.series.flatMap((series) => {
const value = series.tooltipValue(index)
return value == null
? []
: [
usageTooltipItem(series.label, value, series.color),
]
})
return chartTooltipContent(point.label, lines)
}
function costAmount(value: string | null, pointIndex: number) {
return value ?? (requestActivity.value[pointIndex] === false
? '0'
: null)
}
</script>
<template>
@@ -271,8 +200,8 @@ function costAmount(value: string | null, pointIndex: number) {
</template>
<template #body>
<div class="grid min-h-66" :class="hasData ? 'gap-3' : 'flex-1'">
<div v-if="hasData && cost" class="grid grid-cols-2 gap-x-1 gap-y-3 rounded-xl bg-z-fill-quaternary/45 p-2 @min-[24rem]/cost:grid-cols-3 @min-[40rem]/cost:grid-cols-5">
<div class="grid min-h-66" :class="chart.hasData ? 'gap-3' : 'flex-1'">
<div v-if="chart.hasData && cost" class="grid grid-cols-2 gap-x-1 gap-y-3 rounded-xl bg-z-fill-quaternary/45 p-2 @min-[24rem]/cost:grid-cols-3 @min-[40rem]/cost:grid-cols-5">
<div class="grid min-w-0 gap-1 px-1.5">
<span class="text-[10px] font-bold text-z-text-quaternary" :title="t('usage.billing.totalCost')">{{ t('usage.cost.actualCost') }}</span>
<strong class="wrap-anywhere font-mono text-z-sm font-heavy tabular-nums text-z-text">
@@ -304,7 +233,7 @@ function costAmount(value: string | null, pointIndex: number) {
</strong>
</div>
</div>
<BaseChart v-if="hasData" :option="chartOption" :height="210" />
<BaseChart v-if="chart.hasData" :option="chartOption" :height="210" />
<ZEmpty
v-else
size="small"
@@ -2,25 +2,39 @@ import type { TableColumn } from '@codex-proxy/ui'
import type { Ref } from 'vue'
import type { UsageListRecord, UsageRecordStatus } from '@/api'
import { useTableColumns } from '@codex-proxy/ui'
import { clamp, partition } from 'es-toolkit'
import { computed } from 'vue'
import { usageRecordColumns } from '@/components/usage/shared/columns'
import { t } from '@/i18n'
export function useUsageRecordColumns(status: Ref<UsageRecordStatus>, tableWidth: Readonly<Ref<number>>) {
const columns = computed(() => usageRecordColumns.value.map((column) => {
if (column.key === 'createdAtDisplay')
return { ...column, width: 128 }
if (column.key === 'accountEmail')
return { ...column, width: 280, hideable: true }
return ['clientApiKeyName', 'model', 'reasoningEffort'].includes(column.key)
? { ...column, fixedWidth: true }
: column
type ColumnLayout = Record<string, Pick<TableColumn, 'width' | 'fixedWidth' | 'hideable'>>
const requestLayout: ColumnLayout = {
clientApiKeyName: { fixedWidth: true },
accountEmail: { width: 280, hideable: true },
model: { fixedWidth: true },
reasoningEffort: { fixedWidth: true },
}
const errorActionWidth = 72
const maxErrorWidth = 370
const errorLayout: ColumnLayout = {
...requestLayout,
transport: { width: 112 },
actions: { width: errorActionWidth },
}
function columnsWithLayout(layout: ColumnLayout) {
return usageRecordColumns.value.map(column => ({
...column,
...layout[column.key],
}))
const usage = useTableColumns(columns, 'usage-records')
}
export function useUsageRecordColumns(status: Ref<UsageRecordStatus>, tableWidth: Readonly<Ref<number>>) {
const usage = useTableColumns(() => columnsWithLayout(requestLayout), 'usage-records')
const errors = useTableColumns(() => {
const time = columns.value.find(column => column.key === 'createdAtDisplay')!
const actionWidth = 72
const errorWidth = 370
const [time, details] = partition(columnsWithLayout(errorLayout), column => column.key === 'createdAtDisplay')
return [
{
key: 'errorMessage',
@@ -28,18 +42,12 @@ export function useUsageRecordColumns(status: Ref<UsageRecordStatus>, tableWidth
kind: 'custom',
fixed: 'left',
minWidth: tableWidth.value
? Math.min(errorWidth, Math.max(96, (tableWidth.value - actionWidth) / 2))
: errorWidth,
? clamp((tableWidth.value - errorActionWidth) / 2, 96, maxErrorWidth)
: maxErrorWidth,
hideable: false,
},
time,
...columns.value.filter(column => column.key !== time.key).map((column) => {
if (column.key === 'transport')
return { ...column, width: 112 }
if (column.key === 'actions')
return { ...column, width: actionWidth }
return column
}),
...time,
...details,
] satisfies TableColumn<UsageListRecord>[]
}, 'usage-error-records')
return computed(() => status.value === 'error'
-1
View File
@@ -171,7 +171,6 @@ watch(timeRange, () => {
<UsageRecordsTable
class="min-h-0 flex-1"
:columns="columns.visibleColumns.value"
request-details
:rows="records"
:loading="loading"
:empty-text="t('usage.page.noRequestsMatchTheseFilters')"
+2
View File
@@ -4,6 +4,7 @@ import VueI18n from '@intlify/unplugin-vue-i18n/vite'
import tailwindcss from '@tailwindcss/vite'
import vue from '@vitejs/plugin-vue'
import { defineConfig, loadEnv } from 'vite'
import { consoleBanner } from './build/console-banner.ts'
import { pluginBridge } from './build/plugin-bridge.ts'
export default defineConfig(({ mode }) => {
@@ -23,6 +24,7 @@ export default defineConfig(({ mode }) => {
source: sourceUi ? uiRoot : undefined,
}),
pluginBridge(),
consoleBanner(),
],
resolve: {
alias: {
+4 -20
View File
@@ -1,25 +1,9 @@
# v3.54.0
## 新增功能
- 账号分组可设置模型允许或拒绝列表、子代理权限及 Ultrafast 档位,已有分组默认允许全部模型和子代理
- API 密钥支持批量编辑,可查看近 7 天或 30 天的模型用量、费用和请求数,也可将本期日、周预算窗口对齐到指定账号
- OpenAI 请求国家默认跟随代理或全局位置,也可在「系统设置 → 上游配置 → 请求位置覆盖」中选择发送空值、透传或指定国家
- OpenAI OAuth 同步审核默认优先使用有权限的 `codex-auto-review`,可在「系统设置 → 上游配置 → 模型映射」中关闭「专用审核模型」
## 优化改进
- 账号模型白名单可快速添加图片模型,账号额度页区分定时预热和额度重置后的预热
- 账号授权或凭据刷新失败时,管理端显示更具体的原因
# v3.54.2
## 问题修复
- OpenAI Responses 回退到 HTTP/SSE 后,继续使用已失效的响应 ID 会返回 `previous_response_not_found`,客户端可移除旧 ID 并携带完整历史重试
- OpenAI OAuth 配额刷新识别到访问令牌被撤销时会使其过期,刷新模型目录时保留凭据错误原因
- 「请求国家」策略仅对 Codex OAuth 账号生效,OpenAI API Key 请求保留客户端的 `request_country` 原值,省略时也保持省略
## 升级须知
## 优化改进
- 从正式版 `v3.53.1` 可直接升级,已验证分组、密钥和运行设置保留。运行过旧 `0045_account_group_policies` 或 `0046_openai_request_settings` 的源码部署无法直接复用该数据库,需从执行旧迁移前的备份升级,或另行迁移业务数据
- 自建管理 API 客户端保存运行设置时,须提交 `resetCreditOnLowWeeklyQuota`、`openaiOauthGuardianReviewModel` 和 `openaiRequestCountry`,可从当前设置读取并原样回传
- 管理 API 的账号代理绑定改用 `outboundProxyId`,全局和密钥的客户端身份配置分别改用 `providerRequestProfiles` 和 `providerRequestProfileOverrides`
- 读取仪表盘账号用量的客户端请改用 `metric`、`metricValueRaw` 和 `lastUsedRelative`,需要原始时间时读取 `lastUsedAt`
- 尚未识别为 CPR 互联的 OpenAI API Key 账号可在「更多操作」中选择「检测 CPR 互联」,识别成功后可在额度卡片中刷新额度
+5 -5
View File
@@ -1,7 +1,7 @@
version: 3.54.0
version: 3.54.2
published:
'3':
stable: 3.53.1
rc: 3.53.1
beta: 3.53.1
alpha: 3.53.1
stable: 3.54.2
rc: 3.54.2
beta: 3.54.2
alpha: 3.54.2