Compare commits

...
6 Commits
Author SHA1 Message Date
ZyyandCodex 0e02a056b5 chore: bump version to 3.47.0
Co-authored-by: Codex <noreply@openai.com>
2026-11-13 12:40:31 +08:00
1eac929e9d perf(store): reduce temporary writes in analytics projections (#698)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-13 12:37:40 +08:00
9b4a042be5 feat(settings): support multiple account warmup cron expressions (#697)
Match independently scheduled hour and minute pairs while claiming each local minute once. Keep the existing string setting and database constraint, and edit the rules as tags using UI v0.11.0.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-11-13 12:17:50 +08:00
ZyyandCodex 3bd042181e fix(openai): preserve model exclusions during catalog refresh
Use the last successful catalog for the same account, credential revision, and plan until a refresh replaces it. Apply the same exclusions in memory and in PostgreSQL while preserving explicit allowlists and accounts with no catalog.

Co-authored-by: Codex <noreply@openai.com>
2026-11-13 10:16:12 +08:00
ZyyandCodex 2cae28d7f4 fix(ui): restore themed surfaces in the admin console
Use UI v0.10.1 so built-in presets tint pages and cards while preserving explicit background and semantic color settings.

Co-authored-by: Codex <noreply@openai.com>
2026-11-12 22:29:24 +08:00
github-actions[bot] bab781cbe0 chore(release): update release channels to 3.46.0 2026-11-12 13:56:39 +00:00
34 changed files with 357 additions and 196 deletions
@@ -423,7 +423,12 @@ fn settings_request_validates_cron_and_allows_disabled_empty_schedule() {
(false, "08:00", false),
(true, "0 8 * * MON-FRI", true),
(true, "60 8 * * *", false),
(true, "0 8 * * *;30 13 * * *", true),
(true, "0 8 * * *\n30 13 * * *", false),
(true, "0 8 * * *;60 13 * * *", false),
(false, "0 8 * * *;", false),
(true, "0 8 * * *;;30 13 * * *", false),
(true, "0 8 * * *\r\n30 13 * * *", false),
] {
let mut body = update_body();
body["accountWarmupEnabled"] = json!(enabled);
@@ -436,6 +441,11 @@ fn settings_request_validates_cron_and_allows_disabled_empty_schedule() {
assert_eq!(error.field(), "accountWarmupCron");
}
}
let mut oversized = update_body();
oversized["accountWarmupCron"] = json!(["* * * * *"; 26].join(";"));
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(oversized).unwrap();
assert_eq!(request.validate().unwrap_err().field(), "accountWarmupCron");
let mut legacy = update_body();
legacy.as_object_mut().unwrap().remove("accountWarmupCron");
legacy["accountWarmupScheduleTime"] = json!("08:00");
@@ -28,11 +28,10 @@ pub struct StoredAccountCatalog {
pub document: bytes::Bytes,
}
/// 批量选号的存储优化:只有账号自己的当前版本、有效时间和目录摘要都匹配才可跳过
/// 批量选号只按账号当前凭据和套餐的目录摘要排除候选
pub struct AccountCatalogOmissions {
pub documents: Vec<[u8; 32]>,
pub exceptions: Vec<ProviderAccountId>,
pub observed_after: std::time::SystemTime,
pub as_of: std::time::SystemTime,
}
@@ -52,7 +52,7 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
}
}
/// 校验五段 Cron 预热计划
/// 校验单条五段 Cron 表达式
#[must_use]
pub fn valid_warmup_cron(value: &str) -> bool {
parse_warmup_cron(value).is_some()
@@ -73,7 +73,7 @@ fn parse_warmup_cron(value: &str) -> Option<cron::Schedule> {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderWarmupPolicy {
enabled: bool,
cron: String,
schedules: Vec<cron::Schedule>,
model: Option<String>,
}
@@ -84,29 +84,47 @@ impl ProviderWarmupPolicy {
cron: &str,
model: Option<&str>,
) -> Result<(), &'static str> {
if (enabled || !cron.is_empty()) && !valid_warmup_cron(cron) {
Self::validate_and_parse(enabled, cron, model).map(|_| ())
}
fn validate_and_parse(
enabled: bool,
cron: &str,
model: Option<&str>,
) -> Result<Vec<cron::Schedule>, &'static str> {
if cron.len() > 255 || (enabled && cron.is_empty()) {
return Err("account_warmup_cron");
}
// 分号分隔独立表达式,逗号保留给 Cron 字段内的列表
let schedules = if cron.is_empty() {
Vec::new()
} else {
cron.split(';')
.map(parse_warmup_cron)
.collect::<Option<Vec<_>>>()
.ok_or("account_warmup_cron")?
};
if (enabled && model.is_none()) || !valid_optional_probe_model(model) {
return Err("account_warmup_model");
}
Ok(())
Ok(schedules)
}
pub fn try_new(
enabled: bool,
cron: String,
cron: &str,
model: Option<String>,
) -> Result<Self, ProviderStoreError> {
if Self::validate_values(enabled, &cron, model.as_deref()).is_err() {
return Err(ProviderStoreError::new(
ProviderStoreErrorKind::InvalidData,
"validate warmup policy",
));
}
let schedules =
Self::validate_and_parse(enabled, cron, model.as_deref()).map_err(|_| {
ProviderStoreError::new(
ProviderStoreErrorKind::InvalidData,
"validate warmup policy",
)
})?;
Ok(Self {
enabled,
cron,
schedules,
model,
})
}
@@ -115,7 +133,7 @@ impl ProviderWarmupPolicy {
pub const fn disabled() -> Self {
Self {
enabled: false,
cron: String::new(),
schedules: Vec::new(),
model: None,
}
}
@@ -125,11 +143,6 @@ impl ProviderWarmupPolicy {
self.enabled
}
#[must_use]
pub fn cron(&self) -> &str {
&self.cron
}
#[must_use]
pub fn model(&self) -> Option<&str> {
self.model.as_deref()
@@ -138,7 +151,10 @@ impl ProviderWarmupPolicy {
/// 匹配部署时区中的整分钟时刻,时区重叠及执行去重由 Worker 与存储端口负责
#[must_use]
pub fn matches_slot(&self, slot: chrono::NaiveDateTime) -> bool {
parse_warmup_cron(&self.cron).is_some_and(|schedule| schedule.includes(slot.and_utc()))
let instant = slot.and_utc();
self.schedules
.iter()
.any(|schedule| schedule.includes(instant))
}
}
@@ -252,14 +252,10 @@ fn warmup_cron_validation_and_calendar_matching() {
] {
assert!(!valid_warmup_cron(value), "{value:?}");
}
let policy = ProviderWarmupPolicy::try_new(
true,
"0 8,13 * * MON-FRI".to_owned(),
Some("test-model".to_owned()),
)
.unwrap();
let policy =
ProviderWarmupPolicy::try_new(true, "0 8,13 * * MON-FRI", Some("test-model".to_owned()))
.unwrap();
assert!(policy.enabled());
assert_eq!(policy.cron(), "0 8,13 * * MON-FRI");
assert_eq!(policy.model(), Some("test-model"));
for (day, hour, minute, expected) in [
(9, 8, 0, true),
@@ -275,19 +271,39 @@ fn warmup_cron_validation_and_calendar_matching() {
.unwrap();
assert_eq!(policy.matches_slot(slot), expected, "{slot}");
}
assert!(ProviderWarmupPolicy::try_new(false, String::new(), None).is_ok());
assert!(
ProviderWarmupPolicy::try_new(true, String::new(), Some("test-model".to_owned())).is_err()
);
assert!(ProviderWarmupPolicy::try_new(false, "08:00".to_owned(), None).is_err());
assert!(ProviderWarmupPolicy::try_new(false, "", None).is_ok());
assert!(ProviderWarmupPolicy::try_new(true, "", Some("test-model".to_owned())).is_err());
assert!(ProviderWarmupPolicy::try_new(false, "08:00", None).is_err());
assert!(!valid_warmup_cron(&format!("0{}8 * * *", " ".repeat(256))));
let leap = ProviderWarmupPolicy::try_new(false, "0 0 29 FEB *".to_owned(), None).unwrap();
let leap = ProviderWarmupPolicy::try_new(false, "0 0 29 FEB *", None).unwrap();
let slot = NaiveDate::from_ymd_opt(2028, 2, 29)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap();
assert!(leap.matches_slot(slot));
assert!(!leap.matches_slot(slot + chrono::Duration::days(1)));
assert!(ProviderWarmupPolicy::try_new(true, "invalid".to_owned(), None).is_err());
assert!(ProviderWarmupPolicy::try_new(true, "0 8 * * *".to_owned(), None).is_err());
assert!(ProviderWarmupPolicy::try_new(true, "invalid", None).is_err());
assert!(ProviderWarmupPolicy::try_new(true, "0 8 * * *", None).is_err());
}
#[test]
fn warmup_matches_only_the_scheduled_hour_and_minute_pairs() {
use chrono::NaiveDate;
use gateway_core::provider_ports::ProviderWarmupPolicy;
let policy = ProviderWarmupPolicy::try_new(
true,
"58 5 * * *;59 10 * * *;0 16 * * *;1 21 * * *;0 16 * * MON-FRI",
Some("test-model".to_owned()),
)
.unwrap();
let date = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
for minute in 0..1440 {
let slot = date.and_hms_opt(minute / 60, minute % 60, 0).unwrap();
assert_eq!(
policy.matches_slot(slot),
[358, 659, 960, 1261].contains(&minute),
"{slot}"
);
}
}
+2 -1
View File
@@ -336,7 +336,8 @@ async fn connect(
),
};
let analytics =
postgres::PgRequestAnalyticsRepository::new(pool.clone(), observability_query_budget);
postgres::PgRequestAnalyticsRepository::new(pool.clone(), observability_query_budget)
.with_projection_work_mem_mb(config.pool.analytics_projection_work_mem_mb);
Ok(StoreBundle {
pool,
analytics,
@@ -37,6 +37,7 @@ pub struct StorePoolConfig {
pub max_connections: u32,
pub acquire_timeout_seconds: u64,
pub observability_timeout_seconds: u64,
pub analytics_projection_work_mem_mb: Option<u32>,
}
impl Default for StorePoolConfig {
@@ -45,12 +46,15 @@ impl Default for StorePoolConfig {
max_connections: 20,
acquire_timeout_seconds: 5,
observability_timeout_seconds: 120,
analytics_projection_work_mem_mb: None,
}
}
}
impl StorePoolConfig {
pub(crate) fn validate(&self) -> StoreResult<()> {
// PostgreSQL 以有符号 32 位的 kB 保存 work_mem,配置按整 MB 填写
const MAX_WORK_MEM_MB: u32 = i32::MAX as u32 / 1024;
if self.max_connections < 2 || self.acquire_timeout_seconds == 0 {
return Err(StoreError::InvalidData {
source: None,
@@ -69,6 +73,18 @@ impl StorePoolConfig {
message: "pool.observability_timeout_seconds must be positive and fit PostgreSQL statement_timeout".to_owned(),
});
}
if self
.analytics_projection_work_mem_mb
.is_some_and(|mb| !(1..=MAX_WORK_MEM_MB).contains(&mb))
{
return Err(StoreError::InvalidData {
source: None,
entity: "store config",
message: format!(
"pool.analytics_projection_work_mem_mb must be between 1 and {MAX_WORK_MEM_MB}"
),
});
}
Ok(())
}
@@ -2,7 +2,7 @@
use super::*;
/// 输入 matching 提供 output_bucket、name 和完整事实列及 is_completed_usage
/// 输入 matching 提供分组键、指标输入列及 is_completed_usage
/// 精确分位数在整个结果组内计算,不把局部分位数合并成新的分位数
pub(super) fn push_fact_aggregation(
query: &mut QueryBuilder<Postgres>,
@@ -379,8 +379,17 @@ async fn rebuild_groups(
rebuilt.insert((*key).clone(), MetricState::default());
}
// 等值桶键避免范围连接反复比较其他时间桶,范围和游标仍限定已发布前缀
// 计数、费用和直方图复用匹配结果,只物化这些聚合需要的列
let mut query = QueryBuilder::<Postgres>::new(
"with matching as materialized (select mr.*,k.bucket_start as output_bucket,k.name,coalesce((",
"with matching as materialized (select k.bucket_start as output_bucket,k.name,
mr.started_at,mr.outcome,mr.client_status_code,mr.upstream_status_code,mr.attempt_count,
mr.image_generation_succeeded,mr.error_kind,mr.ops_failure_count,mr.ops_rate_limited_count,
mr.ops_auth_failure_count,mr.ops_provider_5xx_count,mr.input_tokens,mr.output_tokens,
mr.cached_input_tokens,mr.cache_write_input_tokens,mr.reasoning_output_tokens,
mr.image_input_tokens,mr.image_output_tokens,mr.total_tokens,
mr.cost_source,mr.cost_currency,mr.cost_amount,mr.standard_cost_amount,mr.no_cache_cost_amount,
mr.first_token_ms,mr.latency_ms,mr.admission_decision_ms,mr.account_selection_wait_ms,
mr.upstream_response_ms,mr.capacity_used_slots,mr.capacity_total_slots,coalesce((",
);
query.push(completed_usage_fact_predicate("mr"))
.push("),false) as is_completed_usage from jsonb_to_recordset(")
@@ -32,6 +32,7 @@ pub struct AnalyticsStatus {
pub struct PgRequestAnalyticsRepository {
pool: PgPool,
query_budget: ObservabilityQueryBudget,
projection_work_mem_mb: Option<u32>,
billing_projector: Option<Arc<dyn UsageBillingProjector>>,
}
@@ -41,10 +42,17 @@ impl PgRequestAnalyticsRepository {
Self {
pool,
query_budget,
projection_work_mem_mb: None,
billing_projector: None,
}
}
#[must_use]
pub fn with_projection_work_mem_mb(mut self, work_mem_mb: Option<u32>) -> Self {
self.projection_work_mem_mb = work_mem_mb;
self
}
#[must_use]
pub fn with_billing_projector(mut self, projector: Arc<dyn UsageBillingProjector>) -> Self {
self.billing_projector = Some(projector);
@@ -82,6 +90,10 @@ impl PgRequestAnalyticsRepository {
transaction.commit().await.map_err(|error| postgres_unavailable("save analytics reset progress", error))?;
return Ok(AnalyticsMaintenance { reset_progress: true, ..Default::default() });
}
if let Some(mb) = self.projection_work_mem_mb {
sqlx::query("select set_config('work_mem',$1,true)").bind(format!("{mb}MB"))
.execute(&mut *transaction).await.map_err(|error| postgres_unavailable("set analytics projection work_mem", error))?;
}
let mut result = AnalyticsMaintenance::default();
// 历史删除可能一次排入大量旧任务,给仍存在的请求预留半批名额,避免实时统计饥饿
// 其余名额仍按最早入队消费,两类任务都能前进;同一快照内选版本,沿用精确版本 ACK
@@ -144,8 +144,7 @@ impl PgProviderAccountRepository {
query.push(" and not exists (select 1 from provider_account_model_catalogs c
where c.account_id=provider_accounts.id and c.credential_revision=provider_accounts.credential_revision
and c.plan_type is not distinct from provider_accounts.plan_type and c.document_hash=any(")
.push_bind(hashes).push("::bytea[]) and c.observed_at > ").push_bind(DateTime::<Utc>::from(omit.observed_after))
.push(" and c.observed_at <= ").push_bind(DateTime::<Utc>::from(omit.as_of))
.push_bind(hashes).push("::bytea[]) and c.observed_at <= ").push_bind(DateTime::<Utc>::from(omit.as_of))
.push(" and not (c.account_id=any(").push_bind(exceptions).push("::text[])))");
}
query.push(" order by provider_kind, name, id");
@@ -296,7 +296,7 @@ impl ProviderRuntimePolicyPort for PgRuntimeSettingsRepository {
.map_err(|source| crate::provider_unavailable("load warmup policy", source))?;
ProviderWarmupPolicy::try_new(
settings.values.account_warmup_enabled,
settings.values.account_warmup_cron,
&settings.values.account_warmup_cron,
settings.values.account_warmup_model,
)
})
+22 -2
View File
@@ -7,7 +7,7 @@ const PASSWORD: &str = "111111111111111111111111111111111111111111111111";
#[test]
fn store_config_should_derive_backup_staging_from_runtime_data_dir() {
let root = tempfile::tempdir().expect("runtime data root");
let mut config = valid_config();
let mut config = config_with_pool(serde_json::json!({}));
config
.resolve_and_validate(root.path())
@@ -28,6 +28,7 @@ fn store_pool_config_defaults_reserve_capacity_for_observability() {
assert_eq!(pool.max_connections, 20);
assert_eq!(pool.acquire_timeout_seconds, 5);
assert_eq!(pool.observability_timeout_seconds, 120);
assert_eq!(pool.analytics_projection_work_mem_mb, None);
assert_eq!(pool.observability_max_connections(), 16);
assert_eq!(
StorePoolConfig {
@@ -68,7 +69,7 @@ fn store_config_rejects_a_pool_that_cannot_reserve_both_traffic_classes() {
));
}
fn valid_config() -> StoreConfig {
fn config_with_pool(pool: serde_json::Value) -> StoreConfig {
serde_json::from_value(serde_json::json!({
"database": {
"url": "postgres://codex_proxy@127.0.0.1:5432/codex_proxy",
@@ -78,10 +79,29 @@ fn valid_config() -> StoreConfig {
"url": "redis://127.0.0.1:6379/",
"password": PASSWORD,
},
"pool": pool,
}))
.expect("test Store configuration")
}
#[test]
fn analytics_projection_work_mem_accepts_whole_mb_within_postgres_limits() {
let root = tempfile::tempdir().unwrap();
for mb in [1_u32, 8, 2_097_151] {
config_with_pool(serde_json::json!({"analytics_projection_work_mem_mb": mb}))
.resolve_and_validate(root.path())
.unwrap();
}
for mb in [0_u32, 2_097_152] {
let error = config_with_pool(serde_json::json!({"analytics_projection_work_mem_mb": mb}))
.resolve_and_validate(root.path())
.unwrap_err();
assert!(
matches!(error, StoreError::InvalidData { message, .. } if message.contains("analytics_projection_work_mem_mb"))
);
}
}
#[test]
fn store_config_accepts_custom_observability_timeout_and_rejects_invalid_values() {
let root = tempfile::tempdir().unwrap();
@@ -316,6 +316,80 @@ async fn incremental_deletions_repair_extrema_last_usage_and_zero_currency_prese
database.close().await;
}
#[tokio::test]
async fn projection_work_mem_is_local_to_the_worker_transaction() {
let Some(database) = TestDatabase::create("work_mem").await else {
return;
};
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_with(database.pool.connect_options().as_ref().clone())
.await
.unwrap();
// 固定同一会话,直接记录事实写入和队列确认时的值,并在复用连接时检查恢复
sqlx::raw_sql(
"set work_mem='2MB';
create table work_mem_audit(stage text, value text);
create function record_work_mem() returns trigger language plpgsql as $$
begin
insert into work_mem_audit values (tg_argv[0], current_setting('work_mem'));
return null;
end $$;
create trigger audit_fact after insert on request_analytics_facts
for each row execute function record_work_mem('projection');
create trigger audit_ack after delete on request_analytics_pending_requests
for each row execute function record_work_mem('ack')",
)
.execute(&pool)
.await
.unwrap();
let worker = PgRequestAnalyticsRepository::new(pool.clone(), observability_query_budget());
let session = || {
sqlx::query_as::<_, (i32, String)>("select pg_backend_pid(), current_setting('work_mem')")
};
let original = session().fetch_one(&pool).await.unwrap();
for (worker, expected) in [
(worker.clone(), "2MB"),
(worker.with_projection_work_mem_mb(Some(8)), "8MB"),
] {
seed(&pool, expected, hour(), &[]).await;
assert_eq!(worker.maintain(10).await.unwrap().projected_requests, 1);
let audit: Vec<(String, String)> =
sqlx::query_as("select stage, value from work_mem_audit order by stage")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(
audit,
[
("ack".into(), "2MB".into()),
("projection".into(), expected.into())
]
);
assert_eq!(session().fetch_one(&pool).await.unwrap(), original);
sqlx::query("truncate work_mem_audit")
.execute(&pool)
.await
.unwrap();
}
// 事实写入失败时投影事务回滚,原会话仍可供下一轮使用
sqlx::query("alter table work_mem_audit add check (value <> '8MB')")
.execute(&pool)
.await
.unwrap();
seed(&pool, "rollback", hour(), &[]).await;
let worker = PgRequestAnalyticsRepository::new(pool.clone(), observability_query_budget())
.with_projection_work_mem_mb(Some(8));
let error = worker.maintain(10).await.unwrap_err();
assert!(
error.to_string().contains("project analytics facts"),
"{error}"
);
assert_eq!(session().fetch_one(&pool).await.unwrap(), original);
pool.close().await;
database.close().await;
}
#[tokio::test]
async fn incremental_summary_write_failure_rolls_back_facts_and_preserves_queue() {
let Some(database) = TestDatabase::create("analytics_incremental_rollback").await else {
@@ -170,7 +170,7 @@ async fn bulk_catalog_restore_keeps_ten_thousand_owners_and_fences_late_writes()
.iter()
.all(|a| !matches!(a.account_id.as_str(), "acct_1" | "acct_2" | "acct_3"))
);
// 数据库只能排除有当前版本、未过期的账号证据;显式例外仍进入选号
// 刷新到期不改变目录排除结果;凭据变化与显式例外仍进入选号
let hash: Vec<u8> = sqlx::query_scalar("select sha256($1::bytea)")
.bind(&document)
.fetch_one(&database.pool)
@@ -181,7 +181,6 @@ async fn bulk_catalog_restore_keeps_ten_thousand_owners_and_fences_late_writes()
let filter = gateway_core::account::AccountCatalogOmissions {
documents: vec![hash.try_into().unwrap()],
exceptions: vec![ProviderAccountId::new("acct_5").unwrap()],
observed_after: now - std::time::Duration::from_secs(1800),
as_of: now,
};
let ids = (1..=10000)
@@ -195,9 +194,6 @@ async fn bulk_catalog_restore_keeps_ten_thousand_owners_and_fences_late_writes()
.iter()
.map(|a| a.id().as_str())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
ids,
std::collections::BTreeSet::from(["acct_1", "acct_4", "acct_5"])
);
assert_eq!(ids, std::collections::BTreeSet::from(["acct_1", "acct_5"]));
database.close().await;
}
@@ -183,7 +183,7 @@ async fn warmup_settings_round_trip_with_database_constraint() {
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
let mut update = settings_with_margin(3_600);
update.values.account_warmup_enabled = true;
update.values.account_warmup_cron = "0 8,13 * * MON-FRI".to_owned();
update.values.account_warmup_cron = "0 8,13 * * MON-FRI;59 10 * * *".to_owned();
update.values.account_warmup_model = Some("test-model".to_owned());
repository
.update_runtime_settings(update)
@@ -195,7 +195,10 @@ async fn warmup_settings_round_trip_with_database_constraint() {
.await
.expect("load warmup settings");
assert!(settings.values.account_warmup_enabled);
assert_eq!(settings.values.account_warmup_cron, "0 8,13 * * MON-FRI");
assert_eq!(
settings.values.account_warmup_cron,
"0 8,13 * * MON-FRI;59 10 * * *"
);
assert_eq!(
settings.values.account_warmup_model.as_deref(),
Some("test-model")
@@ -32,8 +32,7 @@ use crate::transport::{CodexBackendClient, CodexCatalogModel, CodexRequestContex
const MAX_RESPONSE_ETAG_BYTES: usize = 256;
const ACCOUNT_CATALOG_CACHE_TTL: Duration = Duration::from_secs(5 * 60);
// 调度证据覆盖默认 15 分钟刷新周期及抖动,长期未刷新时恢复上游验证
const SCHEDULING_CATALOG_MAX_AGE: Duration = Duration::from_secs(30 * 60);
const CATALOG_REFRESH_AFTER: Duration = Duration::from_secs(30 * 60);
const MAX_ACCOUNT_CATALOG_MODELS: usize = 2_048;
const MODEL_CATALOG_TIMEOUT: Duration = Duration::from_secs(15);
@@ -141,7 +140,6 @@ impl CatalogContent {
struct AccountEntry {
observed_at: SystemTime,
content: Arc<CatalogContent>,
invalidated: Arc<std::sync::atomic::AtomicBool>,
etag: Option<String>,
}
@@ -197,13 +195,7 @@ impl CodexCredentialCatalogSnapshot {
pub(super) fn excludes(&self, account: &ProviderAccount, model: &str, now: SystemTime) -> bool {
self.entries
.get(&CodexCatalogScope::for_account(account))
.is_some_and(|e| {
!e.invalidated.load(std::sync::atomic::Ordering::Relaxed)
&& now
.duration_since(e.observed_at)
.is_ok_and(|age| age < SCHEDULING_CATALOG_MAX_AGE)
&& !e.content.ids.iter().any(|id| id == model)
})
.is_some_and(|e| e.observed_at <= now && !e.content.ids.iter().any(|id| id == model))
}
pub fn account_models(&self, account: &ProviderAccount) -> Option<&[String]> {
@@ -466,14 +458,7 @@ impl CodexCredentialCatalogService {
if ids.len() < MIN_CATALOG_PUSHDOWN {
return None;
}
let cache = self.cache.read().ok()?;
let snapshot = cache.snapshot.as_ref()?.clone();
let pending = cache
.pending
.keys()
.map(|s| s.account_id.clone())
.collect::<BTreeSet<_>>();
drop(cache);
let snapshot = self.cached().ok()??;
let documents = snapshot
.sources
.iter()
@@ -483,16 +468,10 @@ impl CodexCredentialCatalogService {
if documents.is_empty() {
return None;
}
let as_of = SystemTime::now();
Some(gateway_core::account::AccountCatalogOmissions {
documents,
exceptions: ids
.iter()
.filter(|id| pending.contains(*id) || exempt(id))
.cloned()
.collect(),
observed_after: as_of.checked_sub(SCHEDULING_CATALOG_MAX_AGE)?,
as_of,
exceptions: ids.iter().filter(|id| exempt(id)).cloned().collect(),
as_of: SystemTime::now(),
})
}
@@ -582,7 +561,6 @@ impl CodexCredentialCatalogService {
observed_at,
content,
etag: observed.etag,
invalidated: Default::default(),
},
))
}
@@ -41,7 +41,6 @@ impl CodexCredentialCatalogService {
observed_at: a.observed_at,
content: content.clone(),
etag: a.etag,
invalidated: Default::default(),
},
);
}
@@ -131,11 +130,6 @@ impl CodexCredentialCatalogService {
{
return Ok(false);
}
if let Some(entry) = state.snapshot.as_ref().and_then(|s| s.entries.get(&scope)) {
entry
.invalidated
.store(true, std::sync::atomic::Ordering::Relaxed);
}
state.pending.insert(scope, etag.to_owned());
drop(state);
self.refresh_notification.notify_one();
@@ -210,15 +204,12 @@ impl CodexCredentialCatalogService {
let Some(entry) = snapshot.entries.get(scope) else {
return true;
};
if entry.etag.as_deref() == Some(tag)
&& !entry.invalidated.load(std::sync::atomic::Ordering::Relaxed)
{
return false;
}
entry
.invalidated
.store(true, std::sync::atomic::Ordering::Relaxed);
true
// 发布其他账号时保留通知,只有该账号更新的观测才能确认 ETag
entry.etag.as_deref() != Some(tag)
|| old
.as_ref()
.and_then(|s| s.entries.get(scope))
.is_some_and(|previous| previous.observed_at >= entry.observed_at)
});
}
cache.snapshot = next.clone();
@@ -289,7 +280,7 @@ impl CodexCredentialCatalogService {
pending.contains_key(scope)
|| !entries.get(scope).is_some_and(|e| {
now.duration_since(e.observed_at)
.is_ok_and(|age| age < SCHEDULING_CATALOG_MAX_AGE)
.is_ok_and(|age| age < CATALOG_REFRESH_AFTER)
})
})
.collect::<Vec<_>>();
@@ -222,15 +222,23 @@ async fn account_allowlists_override_catalog_omissions_but_weight_affinity_and_p
store.set_scheduling("acct_scope_new", None, AccountWeight::new(100).unwrap());
let affinity = Arc::new(MemorySessionAffinity::default());
let leases = Arc::new(TestLeaseCoordinator::default());
let (provider, _) = provider_and_quota_with_catalog(
let (provider, _, _, catalog) = provider_and_quota_with_runtime_ports(
&store,
affinity.clone(),
native.uri(),
leases.clone(),
u32::try_from(DEFAULT_STREAM_MAX_RETRIES).unwrap(),
)
.await;
Arc::new(MemoryCooldownPort::new()),
crate::support::runtime_policy(),
);
catalog.refresh_catalogs().await.unwrap();
provider.query_model_capabilities().await.unwrap();
// 次账号目录待刷新时,仍须按各自的目录和白名单选号
assert!(
catalog
.observe_response_etag(&store.account("acct_scope_new").unwrap(), "new")
.unwrap()
);
for (model, expected) in [
("gpt-6-luna", "acct_scope_new"),
("gpt-6-astra", "acct_provider_contract"),
@@ -364,7 +372,7 @@ async fn account_allowlists_override_catalog_omissions_but_weight_affinity_and_p
}
#[tokio::test]
async fn only_a_current_account_catalog_can_exclude_a_model() {
async fn selection_uses_the_last_catalog_for_the_same_account_identity() {
use gateway_core::account::{CredentialCasOutcome, CredentialCasUpdate, ProviderAccountUpdate};
use provider_openai::credential::ResponsesTransport;
@@ -423,7 +431,16 @@ async fn only_a_current_account_catalog_can_exclude_a_model() {
.expect(if scenario == "unknown_plan" { 0 } else { 1 })
.mount(upstream)
.await;
let provider = if scenario == "expired" {
let (provider, _, _, catalog) = provider_and_quota_with_runtime_ports(
&store,
Arc::new(MemorySessionAffinity::default()),
native.uri(),
Arc::new(TestLeaseCoordinator::default()),
u32::try_from(DEFAULT_STREAM_MAX_RETRIES).unwrap(),
Arc::new(MemoryCooldownPort::new()),
crate::support::runtime_policy(),
);
if scenario == "expired" {
use gateway_core::account::AccountCatalogObservation;
let a = store.account("acct_scope_new").unwrap();
store
@@ -439,26 +456,8 @@ async fn only_a_current_account_catalog_can_exclude_a_model() {
)
.await
.unwrap();
let (provider, _, _, catalog) = provider_and_quota_with_runtime_ports(
&store,
Arc::new(MemorySessionAffinity::default()),
native.uri(),
Arc::new(TestLeaseCoordinator::default()),
u32::try_from(DEFAULT_STREAM_MAX_RETRIES).unwrap(),
Arc::new(MemoryCooldownPort::new()),
crate::support::runtime_policy(),
);
catalog.restore().await.unwrap();
// B 的失败不能清空上次成功结果,也不能继续以旧的缺失条目拒绝请求
catalog.refresh_catalogs().await.unwrap();
assert_eq!(
catalog.cached_account_models(&a).unwrap().unwrap(),
["gpt-6-luna"]
);
provider
} else {
provider_with_catalog_and_base_url(&store, native.uri()).await
};
}
catalog.refresh_catalogs().await.unwrap();
provider.query_model_capabilities().await.unwrap();
if scenario == "rotated" {
let account = store.account("acct_scope_new").unwrap();
@@ -483,21 +482,34 @@ async fn only_a_current_account_catalog_can_exclude_a_model() {
CredentialCasOutcome::Updated(_)
));
}
let result = provider
.execute(
let execute = || {
provider.clone().execute(
planned_request_for_model("openai", operation("gpt-6-astra"), "gpt-6-astra"),
context("req_unknown_catalog", CancellationToken::new()),
)
.await;
if scenario == "unknown_plan" {
// 未知套餐也有该账号亲自返回的目录,不能借套餐缺失绕过资格
};
if matches!(scenario, "unknown_plan" | "expired") {
assert_eq!(
result.err().unwrap().kind(),
ProviderErrorKind::NoEligibleAccount
execute().await.err().unwrap().kind(),
ProviderErrorKind::NoEligibleAccount,
"{scenario}"
);
continue;
if scenario == "unknown_plan" {
continue;
}
// 刷新失败保留排除结果,直到新目录确认该账号已支持模型
Mock::given(method("GET"))
.and(path("/models"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"data": [{"id": "gpt-6-astra"}]
})))
.with_priority(1)
.expect(1)
.mount(&api)
.await;
catalog.refresh_catalogs().await.unwrap();
}
let mut stream = result.unwrap();
let mut stream = execute().await.unwrap();
assert_eq!(
stream.metadata().provider_account_id().as_str(),
"acct_scope_new",
+3
View File
@@ -122,6 +122,9 @@ store:
应用默认上限为 20,允许的最小值为 2;降低上限可以限制实际数据库连接数,但也会增加请求、后台写入与管理查询之间的等待。
如果出现连接获取超时,应结合数据库负载调大池容量,不要仅延长等待时间
统计 Worker 重算分组时,若临时文件写入较多且数据库有内存余量,可在 `store.pool` 下设置 `analytics_projection_work_mem_mb: 8`(单位 MB)。
默认省略,沿用 PostgreSQL 的 `work_mem`;显式设置仅影响增量投影和历史回填所在的事务,队列确认、整桶重建和在线查询继续沿用原值
将 `deploy/compose.yaml` 中 `services.postgres.command` 替换为以下列表,保留 UTC 参数:
```yaml
+2 -1
View File
@@ -52,12 +52,13 @@ store:
url: 'redis://127.0.0.1:6379/'
# 与 PostgreSQL 共用密码格式要求,并满足 Redis 服务端密码策略
password: &redis_password ''
# 可选:PostgreSQL 连接池预算;下列值与当前推荐默认一致。
# 可选:PostgreSQL 连接池与统计投影配置
# 小内存低并发部署的池上限与数据库调优见 deploy/README.md#小内存优化
# pool:
# max_connections: 20
# acquire_timeout_seconds: 5
# observability_timeout_seconds: 120 # 观测操作保护时限,不是性能目标
# analytics_projection_work_mem_mb: 8 # 仅统计投影事务;省略时沿用数据库设置
admin:
# 不活动期限与从登录起计算的最长有效期,单位为分钟
+5 -7
View File
@@ -1373,11 +1373,9 @@ Key 预算及其访问状态随互联默认公开,不要求开启 `shareQuota`
例如 Plus 设置 `allowlist` 并选中 luna 的实际 ID,Pro 设置 `denylist` 并选中同一 ID,即可严格分流;
Pro 使用 `all` 时也能参与 luna 调度。套餐名称不自动生成或修改规则
原生 Responses 默认排除有效目录未列出目标模型的账号。OpenAI OAuth 或 API Key 账号的白名单精确包含映射后的上游 ID 时,
允许通过该账号请求目录外模型,由上游确认是否可用。此设置只对配置它的账号生效,已有白名单同样适用。
账号禁用、Key 分组、认证类型、黑名单和模型冷却仍参与选号。xAI 账号使用有效套餐目录与账号模型政策的交集。
OpenAI 只使用该账号当前凭据和套餐对应、最近 30 分钟内同步的目录,不借用同套餐其他账号的模型。
没有有效账号目录时交由上游验证,仍执行 `modelAccess`。xAI 使用已知套餐的有效目录缓存
原生 OpenAI Responses 按账号当前凭据和套餐最近一次成功同步的目录选号。目录未列出的模型在刷新期间或刷新失败后仍被排除。
账号白名单精确包含映射后的上游 ID 时,允许该账号尝试目录外模型;当前凭据和套餐没有目录时,也可在账号模型政策允许的范围内交由上游验证。
账号禁用、Key 分组、认证类型、黑名单和模型冷却仍参与选号。xAI 按账号模型政策与有效的套餐目录筛选
原生 OpenAI Responses 上游返回 `error.code=model_not_found`,且状态为 400/403/404 或流内错误未提供状态时,
该账号与模型组合冷却 30 分钟;其他模型仍可使用该账号。仅消息提及模型不支持不触发冷却;
@@ -2178,8 +2176,8 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
### 账号预热
定时账号预热默认关闭。`accountWarmupCron` 使用部署时区的五段 Cron 表达式,
顺序为分、时、日、月、星期,总长度不超过 255 字节,默认空字符串,关闭时允许留空。
定时账号预热默认关闭。`accountWarmupCron` 是字符串,使用半角分号(`;`)分隔多条五段 Cron 表达式,总长度(含分隔符)不超过 255 字节,各条不可留空。默认空字符串,关闭时允许留空。
每条规则按部署时区依次匹配分、时、日、月、星期。任一规则命中即执行,例如 `"58 5 * * *;59 10 * * *"` 只在每天 05:58 和 10:59 触发。
支持列表、范围和步长,例如 `0 8,13,19 * * *` 每天执行三次,`0 8 * * MON-FRI` 在工作日 08:00 执行。
星期可用 `SUN` 至 `SAT` 或数字 1 至 7(日到六),同时指定日与星期时两者均须满足。
同一分钟只领取一次;`accountWarmupModel` 默认 `null`,开启前必须填写有效表达式并显式选择模型。
+4 -5
View File
@@ -658,9 +658,8 @@ OpenAI Provider 的账号资格模块统一解释请求类型、认证与套餐
资格检查复用账号持久事实,在获取租约前与冻结的模型黑白名单共同过滤候选;亲和与重试沿用同一检查
原生 Responses 在评分、亲和和租约前检查冻结的账号模型政策。OpenAI 账号白名单精确命中目标 ID 时允许上游验证,
其余 OpenAI 账号及 xAI 账号按有效目录排除未列出的模型。OpenAI 目录按来源账号、凭据版本和套餐隔离;同套餐账号可以有不同的模型。
OpenAI 只使用未满 30 分钟且尚未收到变化通知的账号目录排除候选。大池可在读取账号时按目录摘要筛选,数据库逐账号核对版本、套餐和观测时间;白名单、待刷新通知及受管适配器不参与该筛选。xAI 按套餐去重读取 TTL 目录缓存,选号不请求上游目录。
没有有效目录时保留上游验证,不从其他账号借用 OpenAI 模型资格,也不从其他套餐借用 xAI 模型资格
其余原生 OpenAI 请求按来源账号、凭据版本和套餐匹配最近一次成功的目录,排除未列出的模型。大池可在读取账号时按目录摘要筛选,白名单和受管适配器由选号时单独判断。
xAI 按套餐读取有效期内的目录缓存。两者在没有对应目录时保留上游验证,选号不请求上游目录
原生 OpenAI Responses 按[官方 Codex 0.166.0](https://github.com/openai/codex/blob/6ff1e1ca3b30fc8b914720681fcf5fe62e95f856/codex-rs/codex-api/src/error.rs#L73)的结构化 `model_not_found` 错误码与状态合同识别模型拒绝,
不从消息或任意正文推断模型权限;通过既有模型级冷却端口记录账号、凭据版本与上游模型,30 分钟内不再选用该组合。
@@ -968,8 +967,8 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规
### 账号模型目录
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
后台只刷新目录缺失、已过刷新窗口或收到新 ETag 的账号;凭据轮换后按新版本重新发现。失败保留最后成功的结果,过期资料只用于展示,不能据此排除候选账号。
新鲜度窗口、刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
后台刷新缺少目录、距上次成功观测已满 30 分钟或收到新 ETag 的账号。刷新期间及失败后继续使用上次成功的目录;凭据或套餐变化后不沿用旧目录。
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再读取本地账号状态核对凭据版本。同一份正文可以复用,但不会把一个账号的模型授予同套餐的其他账号。客户端版本和 Key 身份不触发额外发现
+4 -4
View File
@@ -15,7 +15,7 @@
设置保存在浏览器本地,不会同步到服务器或其他设备。只想换配色时,选择品牌色预置即可
下文说明实现和扩展方式。颜色使用 Ant Design 十阶色板与项目的明暗角色规则,
中性表面从背景和文字 Seed 派生;Vue 组件通过 CSS Variables 与 Tailwind CSS 4 使用这些值。
中性表面从当前底色和文字基色派生;Vue 组件通过 CSS Variables 与 Tailwind CSS 4 使用这些值。
项目不依赖 Ant Design 组件库或 CSS-in-JS
> [!IMPORTANT]
@@ -26,7 +26,7 @@
- **Seed 与 Map 可追踪**:主色和功能色均按 Ant Design 从 Seed 派生 P1-P10;浅色 P6 等于 Seed,深色 P6
经过暗色色板适配。全局 `colorPrimary` 保留原始 Seed;功能色 Base 保留 P6。文字和按钮组件可在派生层做对比度校正,Seed 不随之改写
- **主色与表面分离**:品牌色负责交互和强调,页面、容器、浮层与文字由独立的背景和文本 Seed 派生
- **主色与表面分离**:品牌色负责交互和强调,页面、容器与浮层使用预设底色或自定义背景,文字由文本 Seed 派生
- **语义独立**:成功、警告、错误、信息和链接色各自派生,不随品牌色改变
- **无边设计**:默认依靠表面色差、间距和轻阴影表达层级;边框只用于焦点、错误和必要分隔
- **运行时可定制**:用户输入在浏览器中实时派生,因此使用 CSS Variables,不使用构建时 SCSS 变量
@@ -205,7 +205,7 @@ Preset 的实心色使用 P6,普通 Container、Strong Container 与边界按
- `colorText / Heading / Secondary / Tertiary / Quaternary / Disabled`
- `colorBorder / BorderSecondary / Split / Shadow`
所有品牌色共用当前明暗模式的背景和文字基色。手动设置 `colorBgBase` 或 `colorTextBase` 后,两个模式都使用该字段的自定义值;单项恢复后重新跟随明暗模式。
编辑器中的背景和文字基色只随明暗模式或手动设置改变。未指定 `colorBgBase` 时,页面、卡片和浮层从当前预设的明暗底色派生;无预设底色时使用模式默认值。手动设置 `colorBgBase` 后,两个模式均以该值为底色,直至单项恢复
默认浅色采用中性锚点,默认深色使用 HSL 色调派生;自定义中性色按外观距离平滑过渡到背景和文字 Seed 的 RGB 混色结果。
Input、阴影与其他 Component Token 从 Fill、Surface、Primary 和 Semantic 派生,不在常量文件维护整套颜色表
@@ -449,7 +449,7 @@ utility / arbitrary variant;Vue Transition、跨浏览器 Range、动态富文
单独增加品牌配色:
1. 在 `ThemeColorPresetId` 增加稳定 ID
2. 在 `themeColorPresets` 声明名称、描述与主色 Seed
2. 在 `themeColorPresets` 声明名称、描述与主色 Seed;需要独立底色时在 `PRESET_SURFACE_BACKGROUNDS` 中指定浅色和深色值
3. 不新增页面特判,确认预置可通过同一 `createTheme()` 派生
4. 在浅色、深色和系统模式下检查文本、浮层、Input、表格与图表
+1 -1
View File
@@ -17,7 +17,7 @@
},
"dependencies": {
"@boxicons/vue": "1.0.1",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.10.0",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.11.0",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lucide/vue": "^1.70.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.10.0
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/45b076735d67f973588d93144078c7605cf1ade7(axios@1.21.0(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.6(@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.11.0
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/68458e62e7fb9fadbacea75ce48522f2ba85b8b2(axios@1.21.0(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.6(@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/45b076735d67f973588d93144078c7605cf1ade7':
resolution: {gitHosted: true, integrity: sha512-TyY1/D8rzd1MwU5HUbKOEzca5q7nPqydWaRpb5iMUrSy6G4dXleZNSZd6VXAum9WXZrZGb9ZzBm9cOMIOg+/xg==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/45b076735d67f973588d93144078c7605cf1ade7}
version: 0.10.0
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/68458e62e7fb9fadbacea75ce48522f2ba85b8b2':
resolution: {gitHosted: true, integrity: sha512-VSw6WQntuIQmVLY1uMCouUKYbUZyzT4zDmA7CJ/fWT/yBZwvaH+i16SAp++twYYIvKwYMBR6WmNlV7RA6zXKOw==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/68458e62e7fb9fadbacea75ce48522f2ba85b8b2}
version: 0.11.0
engines: {node: '>=24'}
peerDependencies:
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
@@ -3530,7 +3530,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/45b076735d67f973588d93144078c7605cf1ade7(axios@1.21.0(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.6(@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/68458e62e7fb9fadbacea75ce48522f2ba85b8b2(axios@1.21.0(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.6(@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
+3 -2
View File
@@ -208,13 +208,13 @@
"description": "Try to start quota windows for idle Codex OAuth accounts",
"enableWarmup": "Enable warmup",
"cronExpression": "Cron expression",
"cronHelp": "Five fields: minute hour day month weekday",
"cronHelp": "Press Enter after each tag",
"modelLabel": "Warmup model",
"modelHelp": "Required when enabled, use an available model",
"modelPlaceholder": "Enter model name",
"helpTitle": "About account warmup",
"help": "Sends a lightweight request to available Codex OAuth accounts, skipping exhausted quotas and confirmed active windows, accounts at 0% may be warmed up, activation is not guaranteed",
"cronExample": "Uses the deployment time zone, for example 0 8 * * MON-FRI runs at 08:00 on weekdays, at most once per minute"
"scheduleHelp": "Runs in the deployment time zone, once per matching minute"
},
"adminApiKey": {
"adminApiKey": "Admin API key",
@@ -630,6 +630,7 @@
"invalidQueueSettings": "Queue capacity must be an integer from 0 to 1,000 and timeout from 1 to 120 seconds",
"invalidProbeModel": "The probe model must be at most 128 characters without control characters",
"invalidWarmupCron": "Enter a valid Cron expression",
"warmupCronTooLong": "Keep all rules within 255 bytes",
"warmupModelRequired": "Select a model to enable warmup",
"invalidWarmupModel": "Warmup model name must not exceed 128 characters",
"settingsSaved": "Settings saved",
@@ -208,13 +208,13 @@
"description": "尝试启动空闲 Codex OAuth 账号的额度窗口",
"enableWarmup": "启用预热",
"cronExpression": "Cron 表达式",
"cronHelp": "五段表达式:分 时 日 月 星期",
"cronHelp": "回车添加 Tag,支持多个",
"modelLabel": "预热模型",
"modelHelp": "启用时必填,需为账号可用模型",
"modelPlaceholder": "输入模型名称",
"helpTitle": "账号预热说明",
"help": "向可用的 Codex OAuth 账号发送轻量请求,跳过额度耗尽和已确认活跃的窗口,0% 账号允许预热,不保证窗口成功启动",
"cronExample": "按部署时区执行,例如 0 8 * * MON-FRI 表示工作日 08:00,同一分钟只执行一次"
"scheduleHelp": "按部署时区执行,同一分钟只预热一次"
},
"adminApiKey": {
"adminApiKey": "管理员 API密钥",
@@ -630,6 +630,7 @@
"invalidQueueSettings": "队列容量应为 0~1000 的整数,排队超时应为 1~120 秒的整数",
"invalidProbeModel": "探测模型最多 128 个字符,不能包含控制字符",
"invalidWarmupCron": "请输入有效的 Cron 表达式",
"warmupCronTooLong": "总长度不能超过 255 字节",
"warmupModelRequired": "启用预激活时请选择模型",
"invalidWarmupModel": "预激活模型名称不能超过 128 个字符",
"settingsSaved": "设置已保存",
@@ -208,13 +208,13 @@
"description": "嘗試啓動空閒 Codex OAuth 賬號的額度窗口",
"enableWarmup": "啟用預熱",
"cronExpression": "Cron 表達式",
"cronHelp": "五段表達式:分 時 日 月 星期",
"cronHelp": "按 Enter 新增 Tag,支援多個",
"modelLabel": "預熱模型",
"modelHelp": "啓用時必填,需爲賬號可用模型",
"modelPlaceholder": "輸入模型名稱",
"helpTitle": "賬號預熱說明",
"help": "向可用的 Codex OAuth 帳號傳送輕量請求,略過額度耗盡和已確認活躍的視窗,0% 帳號允許預熱,不保證視窗成功啟動",
"cronExample": "按部署時區執行,例如 0 8 * * MON-FRI 表示工作日 08:00,同一分鐘只執行一次"
"scheduleHelp": "依部署時區執行,同一分鐘只預熱一次"
},
"adminApiKey": {
"adminApiKey": "管理員 API密鑰",
@@ -630,6 +630,7 @@
"invalidQueueSettings": "隊列容量應爲 0~1000 的整數,排隊超時應爲 1~120 秒的整數",
"invalidProbeModel": "探測模型最多 128 個字符,不能包含控制字符",
"invalidWarmupCron": "請輸入有效的 Cron 表達式",
"warmupCronTooLong": "總長度不可超過 255 位元組",
"warmupModelRequired": "啓用預激活時請選擇模型",
"invalidWarmupModel": "預激活模型名稱不能超過 128 個字符",
"settingsSaved": "設置已保存",
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ZCard, ZFormItem, ZIconButton, ZInput, ZPopover, ZSwitch } from '@codex-proxy/ui'
import { ZCard, ZFormItem, ZIconButton, ZInput, ZInputTag, ZPopover, ZSwitch } from '@codex-proxy/ui'
import { CircleAlert, Clock, Sparkles } from '@lucide/vue'
import { useI18n } from 'vue-i18n'
@@ -7,7 +7,7 @@ import { useI18n } from 'vue-i18n'
const { t } = useI18n({ useScope: 'global' })
const enabled = defineModel<boolean>('enabled', { required: true })
const cron = defineModel<string>('cron', { required: true })
const cron = defineModel<string[]>('cron', { required: true })
const model = defineModel<string>('model', { required: true })
</script>
@@ -26,7 +26,7 @@ const model = defineModel<string>('model', { required: true })
</template>
<div class="max-w-80 space-y-2 px-3 py-2 text-z-sm font-regular leading-relaxed text-z-text-secondary">
<p>{{ t('settings.warmup.help') }}</p>
<p>{{ t('settings.warmup.cronExample') }}</p>
<p>{{ t('settings.warmup.scheduleHelp') }}</p>
</div>
</ZPopover>
</span>
@@ -39,14 +39,16 @@ const model = defineModel<string>('model', { required: true })
/>
<ZFormItem
:show-message="enabled"
:show-message="enabled || cron.length > 0"
prop="accountWarmupCron"
:label="t('settings.warmup.cronExpression')"
:description="t('settings.warmup.cronHelp')"
:required="enabled"
>
<ZInput
<ZInputTag
v-model="cron"
collapse-tags
collapse-tags-tooltip
:disabled="!enabled"
:aria-label="t('settings.warmup.cronExpression')"
placeholder="0 8 * * *"
@@ -56,7 +58,7 @@ const model = defineModel<string>('model', { required: true })
<template #prefix>
<Clock class="size-4" />
</template>
</ZInput>
</ZInputTag>
</ZFormItem>
<ZFormItem
@@ -71,7 +71,7 @@ export function useSettingsForm() {
probeModel: '',
} as ProtectionDraft,
accountWarmupEnabled: false,
accountWarmupCron: '',
accountWarmupCron: [] as string[],
accountWarmupModel: '',
resetCreditOnLowWeeklyQuota: false,
resetCreditLeadMinutes: 10 as number | null,
@@ -162,7 +162,9 @@ export function useSettingsForm() {
probeModel: data.accountErrorProtection.probeModel ?? '',
}
form.accountWarmupEnabled = data.accountWarmupEnabled
form.accountWarmupCron = data.accountWarmupCron ?? ''
form.accountWarmupCron = data.accountWarmupCron
? data.accountWarmupCron.split(';')
: []
form.accountWarmupModel = data.accountWarmupModel ?? ''
form.resetCreditOnLowWeeklyQuota = data.resetCreditOnLowWeeklyQuota
form.resetCreditLeadMinutes = data.resetCreditLeadMinutes
@@ -294,7 +296,7 @@ export function useSettingsForm() {
probeModel: trimProtectionText(form.accountErrorProtection.probeModel) || null,
},
accountWarmupEnabled: form.accountWarmupEnabled,
accountWarmupCron: form.accountWarmupCron.trim(),
accountWarmupCron: form.accountWarmupCron.join(';'),
accountWarmupModel: form.accountWarmupModel.trim() || null,
resetCreditOnLowWeeklyQuota: form.resetCreditOnLowWeeklyQuota,
resetCreditLeadMinutes: (form.resetCreditOnLowWeeklyQuota ? savedSettings.form.resetCreditLeadMinutes : resetCreditLeadMinutes)!,
@@ -50,14 +50,19 @@ export function useSettingsFormRules(form: () => SettingsForm) {
'usageRetentionDays': integer(1, 31, t('settings.form.invalidRetention')),
'minCodexDesktopVersion': version(),
'minCodexCliVersion': version(),
'accountWarmupCron': {
required: form().accountWarmupEnabled,
pattern: /^\S+(?: +\S+){4}$/,
max: 255,
transform: value => value.trim(),
trigger: ['blur', 'change'],
message: t('settings.form.invalidWarmupCron'),
},
'accountWarmupCron': [
{
validator: (_rule, expressions: string[]) => (!form().accountWarmupEnabled || expressions.length > 0)
&& expressions.every(expression => /^[^\s;]+(?: +[^\s;]+){4}$/u.test(expression)),
message: t('settings.form.invalidWarmupCron'),
trigger: ['blur', 'change'],
},
{
validator: (_rule, expressions: string[]) => new TextEncoder().encode(expressions.join(';')).length <= 255,
message: t('settings.form.warmupCronTooLong'),
trigger: ['blur', 'change'],
},
],
'accountWarmupModel': [
{
required: form().accountWarmupEnabled,
+10 -14
View File
@@ -1,23 +1,19 @@
# v3.46.0
> [!IMPORTANT]
> **出站代理规则已统一。** 账号请求、插件受管网络和网关下载优先使用显式指定的代理。账号未绑定代理或绑定的代理已禁用时,使用「部署默认出口」
>
> 默认出口按目标协议读取网关进程的环境变量:HTTP/WS 使用 `HTTP_PROXY`,HTTPS/WSS 使用 `HTTPS_PROXY`,未设置对应变量时使用 `ALL_PROXY`。命中 `NO_PROXY` 或没有适用的环境代理时直连;选中的代理连接失败会报错,不会回退直连
>
> 如果网关已设置环境代理,升级前请检查原先依赖直连的目标是否已列入 `NO_PROXY`。使用 Docker Compose 时,环境变量应配置在网关服务的 `environment` 中,修改后需重新创建容器
# v3.47.0
## 新增功能
- 智能调度:可分别设置 5 小时、周、月额度重置对选号的影响,例如只优先选择周额度即将重置的账号
- 账号预热:支持配置多条独立 Cron 规则,分别安排预热时间,同一分钟命中多条规则也只执行一次
## 优化改进
- 用量统计:减少分组重算的临时文件写入
- 统计任务:可通过 `store.pool.analytics_projection_work_mem_mb` 调整增量投影和历史回填事务的工作内存,默认沿用 PostgreSQL 设置
## 问题修复
- OpenAI WebSocket:按上游连接声明的消息大小上限发送请求,避免大请求过早切换到 HTTP;仅能在原连接续写的请求超限时,提示客户端重发完整历史
- 系统更新:修复 macOS 和 Linux 移动只读目录时可能导致的更新或回滚失败,保留目录原有权限
- 管理界面:切换主题预设时保留自定义功能色、背景色和文字色
- OpenAI 模型调度:目录刷新期间或刷新失败后保留最近一次成功目录的排除规则,避免选中不支持目标模型的账号
- 管理界面:恢复主题预设的页面、卡片和浮层底色,保留自定义背景及功能色
## 升级须知
- 原有智能调度配置的三个重置窗口系数默认为 0;此前依赖额度重置评分的部署,请至少为一个窗口设置正系数
- 发往 OpenAI Responses 上游的生成请求会忽略客户端指定的输出 Token 上限,实际输出可能超过该值;OAuth 和 API Key 账号均适用
- 原有单条预热配置可直接沿用,API 中的多条规则以半角分号分隔,总长度含分隔符不超过 255 字节
+5 -5
View File
@@ -1,7 +1,7 @@
version: 3.46.0
version: 3.47.0
published:
'3':
stable: 3.45.2
rc: 3.45.2
beta: 3.45.2
alpha: 3.45.2
stable: 3.46.0
rc: 3.46.0
beta: 3.46.0
alpha: 3.46.0