diff --git a/backend/crates/gateway-admin/src/model/reset_credit_automation.rs b/backend/crates/gateway-admin/src/model/reset_credit_automation.rs index ae67b65fa..a76441774 100644 --- a/backend/crates/gateway-admin/src/model/reset_credit_automation.rs +++ b/backend/crates/gateway-admin/src/model/reset_credit_automation.rs @@ -19,6 +19,9 @@ pub struct PendingResetCredit { pub struct ResetCreditAutomationState { pub next_discovery_at: DateTime, pub credits: Vec, + pub next_weekly_check_at: Option>, + /// 同一次低额度只消费一次,等待消费后的恢复观测再允许提前用卡 + pub awaiting_weekly_recovery_since: Option>, pub pending: Option, pub retry_at: Option>, pub failures: u32, @@ -39,6 +42,7 @@ pub struct ResetCreditAutomation { pub struct ResetCreditAutomationStatus { pub enabled: bool, pub lead_minutes: u32, + pub weekly_trigger_remaining_percent: Option, pub next_discovery_at: Option>, pub next_consume_at: Option>, pub last_result: Option, diff --git a/backend/crates/gateway-admin/src/model/settings.rs b/backend/crates/gateway-admin/src/model/settings.rs index d77973193..f4eef2210 100644 --- a/backend/crates/gateway-admin/src/model/settings.rs +++ b/backend/crates/gateway-admin/src/model/settings.rs @@ -72,6 +72,8 @@ pub struct RuntimeSettingsValues { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, + #[serde(default)] + pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, } diff --git a/backend/crates/gateway-admin/src/use_case/accounts/reset_credit_automation.rs b/backend/crates/gateway-admin/src/use_case/accounts/reset_credit_automation.rs index daf92dc65..001cdcb15 100644 --- a/backend/crates/gateway-admin/src/use_case/accounts/reset_credit_automation.rs +++ b/backend/crates/gateway-admin/src/use_case/accounts/reset_credit_automation.rs @@ -2,12 +2,66 @@ use super::*; -use crate::model::{MutationActor, reset_credit_automation::*}; +use crate::model::{MutationActor, reset_credit_automation::*, settings::RuntimeSettingsValues}; use chrono::{DateTime, Utc}; use gateway_core::time::DeploymentTimeZone; use rand_core::{OsRng, RngCore as _}; use sha2::{Digest as _, Sha256}; +#[derive(Clone, Copy)] +enum Trigger { + Expiry { + lead: u32, + max_remaining: Option, + }, + Weekly { + max_remaining: u32, + }, +} + +impl Trigger { + fn from_settings(settings: &RuntimeSettingsValues) -> Self { + if settings.reset_credit_on_low_weekly_quota { + Self::Weekly { + max_remaining: settings + .reset_credit_max_weekly_remaining_percent + .unwrap_or(0), + } + } else { + Self::Expiry { + lead: settings.reset_credit_lead_minutes, + max_remaining: settings.reset_credit_max_weekly_remaining_percent, + } + } + } + + fn weekly_trigger(self) -> Option { + match self { + Self::Expiry { .. } => None, + Self::Weekly { max_remaining } => Some(max_remaining), + } + } + + fn quota_limit(self) -> Option { + match self { + Self::Expiry { max_remaining, .. } => max_remaining, + Self::Weekly { max_remaining } => Some(max_remaining), + } + } + + fn eligible(self, remaining: f64, limit: u32) -> bool { + // 周额度模式即使配置 100% 也不消耗卡片重置满额窗口 + match self { + Self::Expiry { .. } => remaining <= f64::from(limit), + Self::Weekly { .. } => weekly_low(remaining, limit), + } + } + + fn expiry_due(self, account_id: &str, credit: &PlannedResetCredit, now: DateTime) -> bool { + matches!(self, Self::Expiry { lead, .. } if consume_at(account_id, credit, lead) <= now) + } +} + impl DefaultAccountsService { pub(super) async fn reset_credits_upstream( &self, @@ -74,7 +128,9 @@ impl DefaultAccountsService { account_id: &ProviderAccountId, ) -> Result { self.require_reset_credit_automation(account_id).await?; - let lead_minutes = self.automation_settings().await?.reset_credit_lead_minutes; + let settings = self.automation_settings().await?; + let lead_minutes = settings.reset_credit_lead_minutes; + let weekly_trigger_remaining_percent = Trigger::from_settings(&settings).weekly_trigger(); let record = self .accounts .reset_credit_automation(account_id.as_str()) @@ -83,20 +139,23 @@ impl DefaultAccountsService { Ok(ResetCreditAutomationStatus { enabled: record.as_ref().is_some_and(|r| r.enabled), lead_minutes, + weekly_trigger_remaining_percent, next_discovery_at: record .as_ref() .filter(|r| r.enabled) .map(|r| r.state.next_discovery_at), - next_consume_at: record.as_ref().filter(|r| r.enabled).and_then(|r| { - next_consumption(r, lead_minutes) - .or_else(|| { - r.state - .pending - .as_ref() - .map(|pending| consume_at(&r.account_id, &pending.credit, lead_minutes)) - }) - .map(|due| r.state.retry_at.map_or(due, |retry| due.max(retry))) - }), + next_consume_at: record + .as_ref() + .filter(|r| r.enabled && weekly_trigger_remaining_percent.is_none()) + .and_then(|r| { + next_consumption(r, lead_minutes) + .or_else(|| { + r.state.pending.as_ref().map(|pending| { + consume_at(&r.account_id, &pending.credit, lead_minutes) + }) + }) + .map(|due| r.state.retry_at.map_or(due, |retry| due.max(retry))) + }), last_result: record.and_then(|r| { if r.state .pending @@ -104,6 +163,15 @@ impl DefaultAccountsService { .is_some_and(|pending| pending.credit.expires_at <= Utc::now()) { Some("expired_unknown".to_owned()) + } else if r.enabled + && weekly_trigger_remaining_percent.is_some() + && r.state.awaiting_weekly_recovery_since.is_some() + && matches!( + r.state.last_result.as_deref(), + Some("reset" | "already_redeemed") + ) + { + Some("awaiting_weekly_recovery".to_owned()) } else { r.state.last_result } @@ -145,6 +213,8 @@ impl DefaultAccountsService { revision: 0, next_run_at: now, state: ResetCreditAutomationState { + next_weekly_check_at: None, + awaiting_weekly_recovery_since: None, next_discovery_at: now, credits: vec![], pending: None, @@ -160,8 +230,8 @@ impl DefaultAccountsService { record.state.next_discovery_at = now + chrono::Duration::seconds(i64::from(OsRng.next_u32() % 60)); } - let lead = self.automation_settings().await?.reset_credit_lead_minutes; - reschedule(&mut record, lead, now); + let trigger = Trigger::from_settings(&self.automation_settings().await?); + reschedule(&mut record, trigger, now); self.save_automation(&mut record, Some(context)).await?; let settings = self .settings @@ -246,7 +316,7 @@ impl DefaultAccountsService { self.observe_reset_credits(&mut record, credits, now)?; reschedule( &mut record, - self.automation_settings().await?.reset_credit_lead_minutes, + Trigger::from_settings(&self.automation_settings().await?), now, ); self.save_automation(&mut record, None).await @@ -255,18 +325,16 @@ impl DefaultAccountsService { async fn automation_failed( &self, record: &mut ResetCreditAutomation, - lead: u32, + trigger: Trigger, now: DateTime, ) -> Result<(), AdminError> { - if record.state.pending.is_none() - && !next_consumption(record, lead).is_some_and(|due| due <= now) - { + if record.state.pending.is_none() && record.state.retry_at.is_none() { record.state.next_discovery_at = next_discovery(now, self.timezone, OsRng.next_u64()) .ok_or_else(|| AdminError::internal("无法计算重置卡发现时间"))?; record.state.retry_at = None; record.state.last_result = Some("discovery_failed".to_owned()); - reschedule(record, lead, now); + reschedule(record, trigger, now); return self.save_automation(record, None).await; } record.state.failures = record.state.failures.saturating_add(1); @@ -281,7 +349,7 @@ impl DefaultAccountsService { } .to_owned(), ); - reschedule(record, lead, now); + reschedule(record, trigger, now); self.save_automation(record, None).await } @@ -289,7 +357,7 @@ impl DefaultAccountsService { async fn defer_automation( &self, record: &mut ResetCreditAutomation, - lead: u32, + trigger: Trigger, reason: &str, ) -> Result<(), AdminError> { let now = Utc::now(); @@ -305,38 +373,24 @@ impl DefaultAccountsService { ); record.state.last_result = Some(reason.to_owned()); record.state.failures = 0; - reschedule(record, lead, now); + reschedule(record, trigger, now); self.save_automation(record, None).await } - async fn weekly_reset_credit_gate( + async fn reset_credit_quota( &self, account_id: &ProviderAccountId, - max_remaining: u32, - ) -> Result, AdminError> { + refresh: bool, + ) -> Result { let (_, provider) = self.provider_for_account(account_id).await?; - let quota = provider + provider .quota(ProviderQuotaRequest { account_id: account_id.clone(), - refresh: true, + refresh, rolling_usage: None, }) .await - .map_err(|error| map_provider_error(error, "reset-credit weekly quota"))?; - // 复用账号周窗口归属,不把短期、月度或模型专属桶当作剩余周额度 - let remaining = quota - .usage_windows() - .find(|(_, period)| *period == AccountUsagePeriod::Weekly) - .and_then(|(window, _)| window.used_percent) - .filter(|used| used.is_finite()) - .map(|used| 100.0 - used.clamp(0.0, 100.0)); - Ok(match remaining { - Some(remaining) if remaining > f64::from(max_remaining) => { - Some("weekly_quota_above_threshold") - } - Some(_) => None, - None => Some("weekly_quota_unavailable"), - }) + .map_err(|error| map_provider_error(error, "reset-credit weekly quota")) } pub(super) async fn reconcile_automation( @@ -368,7 +422,7 @@ impl DefaultAccountsService { } let now = Utc::now(); let settings = self.automation_settings().await?; - let lead = settings.reset_credit_lead_minutes; + let trigger = Trigger::from_settings(&settings); record .state .credits @@ -382,18 +436,51 @@ impl DefaultAccountsService { record.state.pending = None; record.state.retry_at = None; record.state.last_result = Some("expired_unknown".to_owned()); + record.state.awaiting_weekly_recovery_since = Some(now); } if record.state.retry_at.is_some_and(|retry| retry > now) { - reschedule(&mut record, lead, now); + reschedule(&mut record, trigger, now); return self.save_automation(&mut record, None).await; } let context = MutationContext { actor: MutationActor::System, request_id: "reset-credit-automation".to_owned(), }; - let due_credit = next_consumption(&record, lead).is_some_and(|due| due <= now); + let due_credit = record + .state + .credits + .iter() + .any(|credit| trigger.expiry_due(account_id.as_str(), credit, now)); + let early_limit = trigger.weekly_trigger(); + // 错峰读取本地快照,等待恢复期间不因卡片用完而漏过下一轮额度 + record.state.next_weekly_check_at = early_limit + .map(|_| now + chrono::Duration::seconds(60 + i64::from(OsRng.next_u32() % 30))); + let mut early_due = false; + if let Some(limit) = early_limit + && record.state.pending.is_none() + && needs_weekly_observation(&record.state) + { + match self.reset_credit_quota(account_id, false).await { + Ok(quota) => { + observe_weekly_recovery(&mut record.state, "a, limit); + early_due = !record.state.credits.is_empty() + && record.state.awaiting_weekly_recovery_since.is_none() + && weekly_remaining("a) + .is_some_and(|remaining| trigger.eligible(remaining, limit)); + } + Err(error) => { + // 额度读取失败不能阻塞独立的卡片发现计划 + tracing::warn!( + account_id = account_id.as_str(), + error_kind = error.kind().as_str(), + "重置卡周额度快照读取失败" + ); + } + } + } if record.state.pending.is_none() && (due_credit + || early_due || record.state.next_discovery_at <= now || record.state.retry_at.is_some()) { @@ -403,10 +490,10 @@ impl DefaultAccountsService { next_discovery(now, self.timezone, OsRng.next_u64()) .ok_or_else(|| AdminError::internal("无法计算重置卡发现时间"))?; } - if due_credit || record.state.retry_at.is_some() { + if due_credit || early_due || record.state.retry_at.is_some() { record.state.retry_at = Some(now + chrono::Duration::seconds(30)); } - reschedule(&mut record, lead, now); + reschedule(&mut record, trigger, now); self.save_automation(&mut record, None).await?; // 真正消费前重新核对卡片;每日发现结果也可直接承担本次核对 match self @@ -415,7 +502,7 @@ impl DefaultAccountsService { { Ok(credits) => self.observe_reset_credits(&mut record, &credits, Utc::now())?, Err(error) => { - self.automation_failed(&mut record, lead, Utc::now()) + self.automation_failed(&mut record, trigger, Utc::now()) .await?; return Err(error); } @@ -424,24 +511,28 @@ impl DefaultAccountsService { .state .credits .iter() - .find(|credit| consume_at(account_id.as_str(), credit, lead) <= Utc::now()) + .find(|credit| { + early_due || trigger.expiry_due(account_id.as_str(), credit, Utc::now()) + }) .cloned() { - if let Some(max_remaining) = settings.reset_credit_max_weekly_remaining_percent { - // 已发出的未决请求跳过此检查,继续沿原幂等键确认结果 - match self - .weekly_reset_credit_gate(account_id, max_remaining) - .await - { - Ok(Some(reason)) => { - return self.defer_automation(&mut record, lead, reason).await; - } - Ok(None) => {} + if let Some(limit) = trigger.quota_limit() { + // 缓存只能唤醒检查,实际选中的卡片与额度都要重新核实 + let quota = match self.reset_credit_quota(account_id, true).await { + Ok(quota) => quota, Err(error) => { - self.defer_automation(&mut record, lead, "weekly_quota_unavailable") + self.defer_automation(&mut record, trigger, "weekly_quota_unavailable") .await?; return Err(error); } + }; + let reason = match weekly_remaining("a) { + Some(remaining) if trigger.eligible(remaining, limit) => None, + Some(_) => Some("weekly_quota_above_threshold"), + None => Some("weekly_quota_unavailable"), + }; + if let Some(reason) = reason { + return self.defer_automation(&mut record, trigger, reason).await; } } // 刷新额度期间卡片可能到期,不能把已过期卡片持久化为待消费 @@ -450,7 +541,7 @@ impl DefaultAccountsService { .state .credits .retain(|credit| credit.expires_at > Utc::now()); - reschedule(&mut record, lead, Utc::now()); + reschedule(&mut record, trigger, Utc::now()); return self.save_automation(&mut record, None).await; } record.state.pending = Some(PendingResetCredit { @@ -459,13 +550,13 @@ impl DefaultAccountsService { }); record.state.last_result = Some("pending".to_owned()); record.state.retry_at = Some(Utc::now() + chrono::Duration::seconds(30)); - reschedule(&mut record, lead, Utc::now()); + reschedule(&mut record, trigger, Utc::now()); // 必须在发送消费请求前落盘,进程退出或响应丢失继续使用相同幂等键 self.save_automation(&mut record, None).await?; } } let Some(pending) = record.state.pending.clone() else { - reschedule(&mut record, lead, Utc::now()); + reschedule(&mut record, trigger, Utc::now()); return self.save_automation(&mut record, None).await; }; let command = ConsumeProviderResetCredit { @@ -478,9 +569,12 @@ impl DefaultAccountsService { Ok(result) => { let confirmed = matches!(result.code.as_str(), "reset" | "already_redeemed"); record.state.pending = None; + if confirmed { + record.state.awaiting_weekly_recovery_since = Some(Utc::now()); + } if result.code == "nothing_to_reset" { return self - .defer_automation(&mut record, lead, "nothing_to_reset") + .defer_automation(&mut record, trigger, "nothing_to_reset") .await; } record @@ -494,15 +588,20 @@ impl DefaultAccountsService { } else { "not_redeemed".to_owned() }); - reschedule(&mut record, lead, Utc::now()); + reschedule(&mut record, trigger, Utc::now()); // 已确认的结果先落盘,再刷新额度;观测失败不能重放已完成的消费 self.save_automation(&mut record, None).await?; - if confirmed { - let _ = self.quota(account_id, true).await; + if confirmed + && let Ok(account) = self.quota(account_id, true).await + && let Some(limit) = early_limit + && observe_weekly_recovery(&mut record.state, &account.quota, limit) + { + reschedule(&mut record, trigger, Utc::now()); + self.save_automation(&mut record, None).await?; } } Err(error) => { - self.automation_failed(&mut record, lead, Utc::now()) + self.automation_failed(&mut record, trigger, Utc::now()) .await?; return Err(error); } @@ -511,6 +610,42 @@ impl DefaultAccountsService { } } +/// 复用账号周窗口归属,忽略短期、模型专属和过期窗口 +fn weekly_remaining(quota: &ProviderQuota) -> Option { + quota + .usage_windows() + .find(|(window, period)| { + *period == AccountUsagePeriod::Weekly + && window.reset_at.is_some_and(|end| end > Utc::now()) + }) + .and_then(|(window, _)| window.used_percent) + .filter(|used| used.is_finite()) + .map(|used| 100.0 - used.clamp(0.0, 100.0)) +} + +fn weekly_low(remaining: f64, limit: u32) -> bool { + remaining < 100.0 && remaining <= f64::from(limit) +} + +fn needs_weekly_observation(state: &ResetCreditAutomationState) -> bool { + !state.credits.is_empty() || state.awaiting_weekly_recovery_since.is_some() +} + +fn observe_weekly_recovery( + state: &mut ResetCreditAutomationState, + quota: &ProviderQuota, + limit: u32, +) -> bool { + if let Some(since) = state.awaiting_weekly_recovery_since + && quota.observed_at.is_some_and(|at| at > since) + && weekly_remaining(quota).is_some_and(|remaining| !weekly_low(remaining, limit)) + { + state.awaiting_weekly_recovery_since = None; + return true; + } + false +} + /// 当地次日随机发现时间;随机数由调用者提供,结果持久化后不会因重启重抽 fn next_discovery( now: DateTime, @@ -550,14 +685,21 @@ fn next_consumption(record: &ResetCreditAutomation, lead_minutes: u32) -> Option .min() } -fn reschedule(record: &mut ResetCreditAutomation, lead_minutes: u32, now: DateTime) { +fn reschedule(record: &mut ResetCreditAutomation, trigger: Trigger, now: DateTime) { record.next_run_at = if let Some(retry) = record.state.retry_at { retry } else if record.state.pending.is_some() { now } else { - next_consumption(record, lead_minutes).map_or(record.state.next_discovery_at, |due| { - due.min(record.state.next_discovery_at) + let scheduled = match trigger { + Trigger::Expiry { lead, .. } => next_consumption(record, lead), + Trigger::Weekly { .. } if needs_weekly_observation(&record.state) => { + Some(record.state.next_weekly_check_at.unwrap_or(now)) + } + Trigger::Weekly { .. } => None, + }; + scheduled.map_or(record.state.next_discovery_at, |at| { + at.min(record.state.next_discovery_at) }) }; } diff --git a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs index d35fc055a..e615c1317 100644 --- a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs @@ -1128,6 +1128,7 @@ impl AccountStore for FakeAccountStore { #[derive(Default)] struct StaticSettingsStore { + reset_credit_on_low_weekly_quota: bool, reset_credit_max_weekly_remaining_percent: Option, } @@ -1186,6 +1187,7 @@ impl SettingsStore for StaticSettingsStore { account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: self.reset_credit_on_low_weekly_quota, reset_credit_max_weekly_remaining_percent: self .reset_credit_max_weekly_remaining_percent, }, diff --git a/backend/crates/gateway-admin/tests/use_case/accounts/reset_credit_automation.rs b/backend/crates/gateway-admin/tests/use_case/accounts/reset_credit_automation.rs index 41d671c89..a7adf5bde 100644 --- a/backend/crates/gateway-admin/tests/use_case/accounts/reset_credit_automation.rs +++ b/backend/crates/gateway-admin/tests/use_case/accounts/reset_credit_automation.rs @@ -231,6 +231,8 @@ fn plan(expires_at: chrono::DateTime) -> ResetCreditAutomation { revision: 1, next_run_at: Utc::now(), state: ResetCreditAutomationState { + next_weekly_check_at: None, + awaiting_weekly_recovery_since: None, next_discovery_at: Utc::now() + TimeDelta::days(1), credits: vec![PlannedResetCredit { id: "card_1".into(), @@ -309,7 +311,7 @@ async fn automation_restores_pending_idempotency_after_service_restart() { .state .retry_at = Some(Utc::now() - TimeDelta::seconds(1)); drop(services); - let restarted = threshold_services(provider.clone(), store.clone(), Some(0)).await; + let restarted = threshold_services(provider.clone(), store.clone(), Some(0), true).await; restarted .accounts() .reconcile_reset_credit_automation(account_id) @@ -712,10 +714,12 @@ async fn threshold_services( provider: Arc, store: Arc, max_remaining: Option, + early: bool, ) -> AdminServices { super::super::AdminHarness::new() .accounts(store) .settings(Arc::new(StaticSettingsStore { + reset_credit_on_low_weekly_quota: early, reset_credit_max_weekly_remaining_percent: max_remaining, })) .provider(provider) @@ -783,7 +787,7 @@ async fn automation_weekly_threshold_is_optional_inclusive_and_uses_remaining_qu let store = FakeAccountStore::new("openai", events()); schedule_due_credit(&provider, &store); provider.set_quota(weekly_quota(used)); - let services = threshold_services(provider.clone(), store.clone(), threshold).await; + let services = threshold_services(provider.clone(), store.clone(), threshold, false).await; services .accounts() .reconcile_reset_credit_automation(ProviderAccountId::new("acct_test").unwrap()) @@ -825,7 +829,7 @@ async fn automation_retains_skipped_credit_and_refreshes_quota_on_next_attempt() let store = FakeAccountStore::new("openai", events()); schedule_due_credit(&provider, &store); provider.set_quota(weekly_quota(10.0)); - let services = threshold_services(provider.clone(), store.clone(), Some(70)).await; + let services = threshold_services(provider.clone(), store.clone(), Some(70), false).await; let id = ProviderAccountId::new("acct_test").unwrap(); services .accounts() @@ -897,7 +901,7 @@ async fn automation_defers_missing_invalid_or_failed_weekly_quota() { schedule_due_credit(&provider, &store); provider.set_quota(quota); *provider.quota_failure.lock().unwrap() = failure; - let services = threshold_services(provider.clone(), store.clone(), Some(70)).await; + let services = threshold_services(provider.clone(), store.clone(), Some(70), false).await; let result = services .accounts() .reconcile_reset_credit_automation(ProviderAccountId::new("acct_test").unwrap()) @@ -971,3 +975,256 @@ async fn automation_nothing_to_reset_retains_credit_and_retries_with_a_new_key() .is_empty() ); } + +#[tokio::test] +async fn early_use_checks_only_known_cards_and_confirms_low_quota_before_spending() { + for (enabled, threshold, used, expiring, expected) in [ + (false, Some(10), 100.0, false, false), + (true, None, 99.9, true, false), + (true, None, 100.0, false, true), + (true, Some(10), 90.0, false, true), + (true, Some(100), 0.0, false, false), + ] { + let provider = FakeProviderAdmin::new("openai", events()); + let store = FakeAccountStore::new("openai", events()); + enable_capability(&provider); + let expiry = Utc::now() + + if expiring { + TimeDelta::minutes(5) + } else { + TimeDelta::days(3) + }; + provider.reset_credits.lock().unwrap().push(card(expiry)); + let mut record = plan(expiry); + let credits = std::mem::take(&mut record.state.credits); + store + .automations + .lock() + .unwrap() + .insert("acct_test".into(), record); + let services = + threshold_services(provider.clone(), store.clone(), threshold, enabled).await; + let id = ProviderAccountId::new("acct_test").unwrap(); + provider.set_quota(weekly_quota(used)); + services + .accounts() + .reconcile_reset_credit_automation(id.clone()) + .await + .unwrap(); + assert!(provider.quota_requests().is_empty()); + let no_card = store + .reset_credit_automation("acct_test") + .await + .unwrap() + .unwrap(); + assert_eq!(no_card.next_run_at, no_card.state.next_discovery_at); + store + .automations + .lock() + .unwrap() + .get_mut("acct_test") + .unwrap() + .state + .credits = credits; + services + .accounts() + .reconcile_reset_credit_automation(id) + .await + .unwrap(); + assert_eq!( + provider.reset_credit_commands().len(), + usize::from(expected) + ); + let status = services + .accounts() + .reset_credit_automation_status(ProviderAccountId::new("acct_test").unwrap()) + .await + .unwrap(); + assert_eq!( + status.weekly_trigger_remaining_percent, + enabled.then_some(threshold.unwrap_or(0)) + ); + if enabled { + assert!(status.next_consume_at.is_none()); + } + let requests = provider.quota_requests(); + assert_eq!( + requests.iter().filter(|r| !r.refresh).count(), + usize::from(enabled) + ); + assert_eq!(requests.iter().any(|r| r.refresh), expected); + if enabled && !expected { + assert!( + store + .reset_credit_automation("acct_test") + .await + .unwrap() + .unwrap() + .next_run_at + <= Utc::now() + TimeDelta::seconds(90) + ); + } + } +} + +#[tokio::test] +async fn early_use_rechecks_live_quota_and_waits_for_a_new_recovery_after_restart() { + let provider = FakeProviderAdmin::new("openai", events()); + let store = FakeAccountStore::new("openai", events()); + enable_capability(&provider); + let expiry = Utc::now() + TimeDelta::days(3); + let mut later = card(expiry + TimeDelta::days(1)); + later.id = "later".into(); + *provider.reset_credits.lock().unwrap() = vec![later, card(expiry)]; + store + .automations + .lock() + .unwrap() + .insert("acct_test".into(), plan(expiry)); + let id = ProviderAccountId::new("acct_test").unwrap(); + let services = threshold_services(provider.clone(), store.clone(), Some(10), true).await; + let high = ProviderQuota { + observed_at: Some(Utc::now()), + ..weekly_quota(15.0) + }; + provider.set_quota(weekly_quota(90.0)); + let (release, gate) = tokio::sync::oneshot::channel(); + *provider.reset_credit_query_gate.lock().unwrap() = Some(gate); + let (result, ()) = tokio::join!( + services + .accounts() + .reconcile_reset_credit_automation(id.clone()), + async { + tokio::time::timeout( + std::time::Duration::from_secs(2), + provider.reset_credit_query_started.notified(), + ) + .await + .unwrap(); + provider.set_quota(high.clone()); + release.send(()).unwrap(); + } + ); + result.unwrap(); + assert!(provider.reset_credit_commands().is_empty()); + + advance_retry(&store); + provider.set_quota(weekly_quota(95.0)); + services + .accounts() + .reconcile_reset_credit_automation(id.clone()) + .await + .unwrap(); + let commands = provider.reset_credit_commands(); + assert_eq!(commands.len(), 1); + assert_eq!(commands[0].credit_id.as_deref(), Some("card_1")); + provider + .reset_credits + .lock() + .unwrap() + .retain(|credit| credit.id != "card_1"); + + let services = threshold_services(provider.clone(), store.clone(), Some(10), true).await; + for quota in [weekly_quota(95.0), high, weekly_quota(95.0)] { + provider.set_quota(quota); + services + .accounts() + .reconcile_reset_credit_automation(id.clone()) + .await + .unwrap(); + } + assert_eq!(provider.reset_credit_commands().len(), 1); + provider.set_quota(ProviderQuota { + observed_at: Some(Utc::now()), + ..weekly_quota(20.0) + }); + services + .accounts() + .reconcile_reset_credit_automation(id.clone()) + .await + .unwrap(); + provider.set_quota(weekly_quota(100.0)); + services + .accounts() + .reconcile_reset_credit_automation(id) + .await + .unwrap(); + let commands = provider.reset_credit_commands(); + assert_eq!(commands.len(), 2); + assert_eq!(commands[1].credit_id.as_deref(), Some("later")); +} + +#[tokio::test] +async fn weekly_recovery_is_observed_without_cards_after_a_failed_quota_readback() { + let events = events(); + let provider = FakeProviderAdmin::new("openai", events.clone()); + enable_capability(&provider); + let store = FakeAccountStore::new("openai", events.clone()); + let expiry = Utc::now() + TimeDelta::days(3); + let mut record = plan(expiry); + record.state.pending = Some(PendingResetCredit { + credit: record.state.credits[0].clone(), + redeem_request_id: uuid::Uuid::new_v4().to_string(), + }); + store + .automations + .lock() + .unwrap() + .insert("acct_test".into(), record); + let id = ProviderAccountId::new("acct_test").unwrap(); + let services = threshold_services(provider.clone(), store.clone(), Some(10), true).await; + let accounts = services.accounts(); + *provider.quota_failure.lock().unwrap() = Some(ProviderAdminErrorKind::Unavailable); + accounts + .reconcile_reset_credit_automation(id.clone()) + .await + .unwrap(); + let waiting = store + .reset_credit_automation("acct_test") + .await + .unwrap() + .unwrap(); + assert!(waiting.state.credits.is_empty()); + assert_eq!(waiting.state.last_result.as_deref(), Some("reset")); + assert!(waiting.next_run_at <= Utc::now() + TimeDelta::seconds(90)); + + provider.set_quota(ProviderQuota { + observed_at: Some(Utc::now()), + ..weekly_quota(20.0) + }); + accounts + .reconcile_reset_credit_automation(id.clone()) + .await + .unwrap(); + let recovered = store + .reset_credit_automation("acct_test") + .await + .unwrap() + .unwrap(); + assert_eq!(recovered.next_run_at, recovered.state.next_discovery_at); + assert!(!recorded(&events).contains(&"provider.reset_credits")); + assert_eq!( + provider + .quota_requests() + .iter() + .map(|r| r.refresh) + .collect::>(), + [true, false] + ); + + provider.set_quota(weekly_quota(95.0)); + let mut new_card = card(expiry); + new_card.id = "next".into(); + provider.reset_credits.lock().unwrap().push(new_card); + accounts + .reset_credits(&context("new-card"), id.clone()) + .await + .unwrap(); + accounts + .reconcile_reset_credit_automation(id) + .await + .unwrap(); + let commands = provider.reset_credit_commands(); + assert_eq!(commands.len(), 2); + assert_eq!(commands[1].credit_id.as_deref(), Some("next")); +} diff --git a/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs b/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs index 44fc59a44..352f0f73e 100644 --- a/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs +++ b/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs @@ -76,6 +76,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings { account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: false, reset_credit_max_weekly_remaining_percent: None, }, } diff --git a/backend/crates/gateway-admin/tests/use_case/observability/mod.rs b/backend/crates/gateway-admin/tests/use_case/observability/mod.rs index eb415968f..56d8dc815 100644 --- a/backend/crates/gateway-admin/tests/use_case/observability/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/observability/mod.rs @@ -1442,6 +1442,7 @@ impl SettingsStore for FixtureSettingsStore { account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: false, reset_credit_max_weekly_remaining_percent: None, }, }) diff --git a/backend/crates/gateway-admin/tests/use_case/settings.rs b/backend/crates/gateway-admin/tests/use_case/settings.rs index ff7a4549e..be80347b6 100644 --- a/backend/crates/gateway-admin/tests/use_case/settings.rs +++ b/backend/crates/gateway-admin/tests/use_case/settings.rs @@ -354,6 +354,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() { account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: false, reset_credit_max_weekly_remaining_percent: None, }, }, diff --git a/backend/crates/gateway-api/src/admin/accounts/wire.rs b/backend/crates/gateway-api/src/admin/accounts/wire.rs index 7a3d4945f..e86c0ca90 100644 --- a/backend/crates/gateway-api/src/admin/accounts/wire.rs +++ b/backend/crates/gateway-api/src/admin/accounts/wire.rs @@ -1237,6 +1237,7 @@ pub struct AccountResetCreditAutomationRequest { pub struct AccountResetCreditAutomationData { pub enabled: bool, pub lead_minutes: u32, + pub weekly_trigger_remaining_percent: Option, pub next_discovery_at_display: Option, pub next_consume_at_display: Option, pub last_result: Option, @@ -1257,6 +1258,7 @@ impl Self { enabled: status.enabled, lead_minutes: status.lead_minutes, + weekly_trigger_remaining_percent: status.weekly_trigger_remaining_percent, next_discovery_at_display: status .next_discovery_at .as_ref() diff --git a/backend/crates/gateway-api/src/admin/settings.rs b/backend/crates/gateway-api/src/admin/settings.rs index 067a0a5d4..521f19eaa 100644 --- a/backend/crates/gateway-api/src/admin/settings.rs +++ b/backend/crates/gateway-api/src/admin/settings.rs @@ -63,6 +63,8 @@ pub struct RuntimeSettingsFields { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, + #[serde(default)] + pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, } @@ -775,6 +777,7 @@ impl RuntimeSettingsFields { account_warmup_enabled: self.account_warmup_enabled, account_warmup_cron: self.account_warmup_cron, account_warmup_model: self.account_warmup_model, + reset_credit_on_low_weekly_quota: self.reset_credit_on_low_weekly_quota, reset_credit_lead_minutes: self.reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent: self .reset_credit_max_weekly_remaining_percent, @@ -814,6 +817,7 @@ impl From for RuntimeSett account_warmup_enabled: settings.account_warmup_enabled, account_warmup_cron: settings.account_warmup_cron, account_warmup_model: settings.account_warmup_model, + reset_credit_on_low_weekly_quota: settings.reset_credit_on_low_weekly_quota, reset_credit_lead_minutes: settings.reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent: settings .reset_credit_max_weekly_remaining_percent, diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index 1e634faa5..52d5dc73d 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -674,6 +674,7 @@ impl SettingsStore for MemorySettingsStore { account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: false, reset_credit_max_weekly_remaining_percent: None, }, }; @@ -1943,6 +1944,7 @@ fn test_runtime_settings() -> RuntimeSettings { account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: false, reset_credit_max_weekly_remaining_percent: None, }, } diff --git a/backend/crates/gateway-api/tests/admin/settings.rs b/backend/crates/gateway-api/tests/admin/settings.rs index 41497a2b3..23f2f8fac 100644 --- a/backend/crates/gateway-api/tests/admin/settings.rs +++ b/backend/crates/gateway-api/tests/admin/settings.rs @@ -1538,11 +1538,14 @@ fn reset_credit_weekly_threshold_accepts_unset_and_zero_to_one_hundred() { .reset_credit_max_weekly_remaining_percent .is_none() ); + assert!(!request.values.reset_credit_on_low_weekly_quota); for value in [json!(null), json!(0), json!(70), json!(100)] { let mut body = update_body(); + body["resetCreditOnLowWeeklyQuota"] = json!(true); body["resetCreditMaxWeeklyRemainingPercent"] = value.clone(); let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap(); request.validate().unwrap(); + assert!(request.values.reset_credit_on_low_weekly_quota); assert_eq!( serde_json::to_value(request.values.reset_credit_max_weekly_remaining_percent).unwrap(), value diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index 3b58c99f5..03abf67fb 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -356,10 +356,10 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与 版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务 `accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、 -下次发现与使用时间、最近结果;时间为 RFC 3339 字符串,无计划时为 `None`。 +生效的周额度触发值(临期模式为 `None`)、下次发现与使用时间、最近结果;时间为 RFC 3339 字符串,无计划时为 `None`。 `accounts::SetResetCreditAutomation` 接收 `(account_id, enabled)`,返回保存后的同一状态;审计主体与调用标识由宿主提供。 -两者复用原生账号校验和自动重置用例,不立即查询或消费上游卡片。提前时间与剩余周额度上限通过 `settings::Load` / `Replace` 的 -`reset_credit_lead_minutes` 和可选的 `reset_credit_max_weekly_remaining_percent` 读取和设置,范围见[主动额度重置卡](../../../../../docs/api.md#主动额度重置卡) +两者复用原生账号校验和自动重置用例,不立即查询或消费上游卡片。使用时机、提前时间与剩余周额度上限通过 `settings::Load` / `Replace` 的 +`reset_credit_on_low_weekly_quota`、`reset_credit_lead_minutes` 和可选的 `reset_credit_max_weekly_remaining_percent` 读取和设置,范围见[主动额度重置卡](../../../../../docs/api.md#主动额度重置卡) ```rust,ignore use gateway_plugin_sdk::call::services::accounts::{GetResetCreditAutomation, SetResetCreditAutomation}; diff --git a/backend/crates/gateway-plugin/sdk/src/call/services/accounts.rs b/backend/crates/gateway-plugin/sdk/src/call/services/accounts.rs index 1f2b7ac37..b6bc416d2 100644 --- a/backend/crates/gateway-plugin/sdk/src/call/services/accounts.rs +++ b/backend/crates/gateway-plugin/sdk/src/call/services/accounts.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; pub struct ResetCreditAutomationStatus { pub enabled: bool, pub lead_minutes: u32, + pub weekly_trigger_remaining_percent: Option, pub next_discovery_at: Option, pub next_consume_at: Option, pub last_result: Option, diff --git a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs index b04e6232b..54a7532be 100644 --- a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs +++ b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs @@ -163,6 +163,8 @@ pub struct RuntimeSettings { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, + #[serde(default)] + pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, pub request_profiles: ProviderRequestProfiles, @@ -201,6 +203,8 @@ pub struct ReplaceRuntimeSettings { pub account_warmup_enabled: bool, pub account_warmup_cron: String, pub account_warmup_model: Option, + #[serde(default)] + pub reset_credit_on_low_weekly_quota: bool, pub reset_credit_lead_minutes: u32, pub reset_credit_max_weekly_remaining_percent: Option, /// 读取设置时的版本;与写入在同一事务内比较,防止覆盖并发更新 @@ -401,6 +405,7 @@ impl From for ReplaceRuntimeSettings { account_warmup_enabled: settings.account_warmup_enabled, account_warmup_cron: settings.account_warmup_cron, account_warmup_model: settings.account_warmup_model, + reset_credit_on_low_weekly_quota: settings.reset_credit_on_low_weekly_quota, reset_credit_lead_minutes: settings.reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent: settings .reset_credit_max_weekly_remaining_percent, diff --git a/backend/crates/gateway-store/src/postgres/runtime_settings.rs b/backend/crates/gateway-store/src/postgres/runtime_settings.rs index 28ecfbd78..1362051ee 100644 --- a/backend/crates/gateway-store/src/postgres/runtime_settings.rs +++ b/backend/crates/gateway-store/src/postgres/runtime_settings.rs @@ -157,7 +157,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul audit_retention_days, min_codex_desktop_version, min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_account_affinity, max_account_rotations, openai_session_affinity_ttl_hours, account_error_protection_json, account_error_protection_revision, - account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent + account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1", ) .fetch_optional(pool) @@ -313,7 +313,7 @@ pub(crate) async fn load_runtime_settings_in_transaction( audit_retention_days, min_codex_desktop_version, min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_account_affinity, max_account_rotations, openai_session_affinity_ttl_hours, account_error_protection_json, account_error_protection_revision, - account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent + account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1", ) .fetch_optional(&mut **transaction) @@ -332,8 +332,8 @@ pub(crate) async fn update_runtime_settings_in_transaction( update: &RuntimeSettingsUpdate, ) -> StoreResult { update.validate()?; - let previous_reset_settings: (i32, Option) = sqlx::query_as( - "select reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent from runtime_settings where id = 1 for update", + let previous_reset_settings: (i32, Option, bool) = sqlx::query_as( + "select reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1 for update", ) .fetch_one(&mut **transaction) .await @@ -394,6 +394,7 @@ pub(crate) async fn update_runtime_settings_in_transaction( max_retry_after_seconds = $31, account_queue_timeout_seconds = $32, switch_account_on_queue_failure = $33, + reset_credit_on_low_weekly_quota = $34, updated_at = now() where id = 1 returning config_revision", @@ -439,6 +440,7 @@ pub(crate) async fn update_runtime_settings_in_transaction( .bind(i64::from(update.values.max_retry_after_seconds)) .bind(i64::from(update.values.account_queue_timeout_seconds)) .bind(update.values.switch_account_on_queue_failure) + .bind(update.values.reset_credit_on_low_weekly_quota) .fetch_optional(&mut **transaction) .await .map_err(|source| postgres_unavailable("update runtime settings in transaction", source))? @@ -449,6 +451,7 @@ pub(crate) async fn update_runtime_settings_in_transaction( })?; // 自动使用配置变化只唤醒本地计划重算,不触发账号全量上游查询 if i64::from(previous_reset_settings.0) != i64::from(update.values.reset_credit_lead_minutes) + || previous_reset_settings.2 != update.values.reset_credit_on_low_weekly_quota || previous_reset_settings.1.map(i64::from) != update .values @@ -539,6 +542,7 @@ struct RuntimeSettingsRow { account_warmup_enabled: bool, account_warmup_cron: String, account_warmup_model: Option, + reset_credit_on_low_weekly_quota: bool, reset_credit_lead_minutes: i32, reset_credit_max_weekly_remaining_percent: Option, } @@ -608,6 +612,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult RuntimeSettin account_warmup_cron: "0 8 * * *".to_owned(), account_warmup_model: None, reset_credit_lead_minutes: 10, + reset_credit_on_low_weekly_quota: false, reset_credit_max_weekly_remaining_percent: None, }, } @@ -1248,19 +1249,15 @@ async fn reset_credit_weekly_threshold_defaults_unset_and_round_trips() { settings.values.reset_credit_max_weekly_remaining_percent, None ); + assert!(!settings.values.reset_credit_on_low_weekly_quota); for threshold in [Some(70), Some(0), Some(100), None] { let mut update = settings_with_margin(600); + update.values.reset_credit_on_low_weekly_quota = true; update.values.reset_credit_max_weekly_remaining_percent = threshold; repository.update_runtime_settings(update).await.unwrap(); - assert_eq!( - repository - .load_runtime_settings() - .await - .unwrap() - .values - .reset_credit_max_weekly_remaining_percent, - threshold - ); + let values = repository.load_runtime_settings().await.unwrap().values; + assert!(values.reset_credit_on_low_weekly_quota); + assert_eq!(values.reset_credit_max_weekly_remaining_percent, threshold); } for threshold in [-1, 101] { assert!(sqlx::query("update runtime_settings set reset_credit_max_weekly_remaining_percent = $1 where id = 1") diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index 78961c88a..386f286e8 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -39,3 +39,4 @@ b215ea90d5c8753aeb8192b17ffe65f7a95c1d620aaeaf9fc4337d8cf6f2634e 0037_retry_aft a6b4e81d38e5d70776a75eba22749354573ebcb186160ff9eb45fd91157b3e0d 0039_queue_timeouts_quota_credits_and_installation_seed.sql 13db1dccac37cc20a716a605934e281a71e75c1aa626a3d7e6328f7a0ef3750d 0040_account_warmup_cron.sql 3451931b9296d9db9cd580e15c9256c4576936ce6580d52600c4e85e959d7c36 0041_explicit_budget_windows.sql +3685caa890f06d1537ddf5bfe8e139c481575340d5d852886d8d200282aadd4a 0042_reset_credit_weekly_trigger.sql diff --git a/backend/migrations/0042_reset_credit_weekly_trigger.sql b/backend/migrations/0042_reset_credit_weekly_trigger.sql new file mode 100644 index 000000000..dbd85133a --- /dev/null +++ b/backend/migrations/0042_reset_credit_weekly_trigger.sql @@ -0,0 +1,2 @@ +alter table runtime_settings + add column reset_credit_on_low_weekly_quota boolean not null default false; diff --git a/docs/api.md b/docs/api.md index 98601c998..f9185b2e6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1894,15 +1894,20 @@ revision 变化时丢弃结果 消费期间账号身份或凭据版本变化时返回结果未知,不将旧结果套用到新绑定账号 自动使用通过 `/api/admin/accounts/reset-credits/automation` 按账号开启,默认关闭;账号本身停用时暂停执行。 -GET 和 POST 均返回 `enabled`、`leadMinutes`、`nextDiscoveryAtDisplay`、`nextConsumeAtDisplay`、`lastResult`, +GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercent`、`nextDiscoveryAtDisplay`、`nextConsumeAtDisplay`、`lastResult`, 时间展示沿用部署时区,无计划时为 `null`。运行设置 `resetCreditLeadMinutes` 默认 10,范围 1~1440 分钟 -`resetCreditMaxWeeklyRemainingPercent` 是可选的全局剩余周额度上限,范围 0~100 的整数,默认 `null` 表示不限制。 -设置后,每次新的自动消费前刷新账号周额度;剩余比例大于上限或无法确认周额度时,保留卡片并在到期前错峰重查, -等于上限时允许使用。仅采用账号级周窗口,不回退到短期、月度或模型专属额度;手动使用不受此上限影响 +`resetCreditOnLowWeeklyQuota` 为已开启自动使用的账号选择一种用卡时机。两种模式共用可选的剩余周额度上限 `resetCreditMaxWeeklyRemainingPercent`(整数 0~100),只认账号级周窗口,不采用短期、月度或模型专属额度: + +| 模式 | 触发条件 | 上限留空 | +| --- | --- | --- | +| 临期使用(默认,`false`) | 进入卡片到期提前窗口;设置上限时还须确认剩余周额度不高于上限 | 临期使用不限制额度 | +| 按周额度使用(`true`) | 周额度已有消耗且剩余比例不高于上限,优先使用最早到期的有效卡片;仅临期不会触发 | 周额度耗尽时使用 | + +周额度模式下,`weeklyTriggerRemainingPercent` 返回生效的上限(留空为 0),`nextConsumeAtDisplay` 为 `null`;临期模式下该上限投影为 `null`,`nextConsumeAtDisplay` 显示计划时间。手动使用不受模式与上限限制 开启后在一分钟内错峰执行首次发现,此后按部署时区每天随机发现一次,普通发现失败也等待下一日。 -已知且有明确到期时间的可用卡片在提前窗口内错峰执行,消费前重新查询;已在其他地方使用或已到期的卡片 +临期模式在提前窗口内错峰执行;周额度模式在有卡且本地快照达线时刷新上游周额度核实。两者消费前均重新查询卡片;已在其他地方使用或已到期的卡片 会移出计划,查询失败不直接消费。上游返回 `already_redeemed` 后结束该次操作,不切换另一张卡重试。 无卡片 ID 或到期时间时不自动消费;每天发现一次可能错过两次发现之间发放并到期的卡片 @@ -1911,6 +1916,7 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`nextDiscoveryAtDisplay`、`n `discovery_failed` 表示最近查询失败,`not_redeemed` 表示上游明确未完成消费。 `weekly_quota_above_threshold` 表示剩余周额度高于上限,`weekly_quota_unavailable` 表示暂时无法确认周额度; `nothing_to_reset` 表示当前没有可重置窗口,这三种状态均保留卡片并稍后重查,其中 `nothing_to_reset` 的下一次消费使用新幂等键。 +`awaiting_weekly_recovery` 表示已确认用卡,等待消费后更新的周额度回到上限以上或满额,再允许下一次按周额度使用。即使用完最后一张卡,等待期间仍会检查本地额度快照。 结果未知的未决操作继续使用原幂等键确认,不重新应用周额度上限;自动操作未决且对应卡片尚未到期时,手动消费返回 `409` ## 6. 账号分组 @@ -2132,7 +2138,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly | [历史保留](#历史保留) | `usageRetentionDays`、`opsEventRetentionDays`、`auditRetentionDays` | | [账号错误保护](#账号错误保护) | `accountErrorProtection` | | [账号预热](#账号预热) | `accountWarmupEnabled`、`accountWarmupCron`、`accountWarmupModel` | -| [主动额度重置卡](#主动额度重置卡) | `resetCreditLeadMinutes`、`resetCreditMaxWeeklyRemainingPercent` | +| [主动额度重置卡](#主动额度重置卡) | `resetCreditOnLowWeeklyQuota`、`resetCreditLeadMinutes`、`resetCreditMaxWeeklyRemainingPercent` | ### 历史保留 diff --git a/docs/architecture.md b/docs/architecture.md index 3ec681b4f..760228316 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1066,11 +1066,13 @@ OpenAI 订阅周期属于按需个人信息,不是额度事实。Admin 账号 Admin 仅为开启自动使用的账号保存卡片 ID、到期时间、下一次发现时间和未决消费。每日发现按账号独立随机, 已知到期计划在提前窗口前段错峰;Worker 租约限制为单个执行者,每轮最多处理 100 个到期账号,并发复用 -凭据刷新配置。周期扫描只访问本地计划,消费前重新核对上游;外部已消费的卡片移出计划,已消费响应为终态。 +凭据刷新配置。临期模式只调度到期计划。周额度模式在有卡或等待额度恢复时错峰检查本地快照; +有卡且额度达线才复核上游。消费后的新观测确认额度恢复后解除重复用卡保护,若已无卡则只保留每日发现。 +消费前重新核对上游卡片;外部已消费的卡片移出计划,已消费响应为终态。 消费幂等键先持久化再发送,结果未确认时退避重试,到期后停止;确认结果先落库再刷新额度。 设置剩余周额度上限时,Admin 在新消费前通过 Provider 刷新额度,复用账号周窗口归属;超过上限或无法确认时保留卡片重查。 上游明确返回 `nothing_to_reset` 时清除未决键并保留卡片,下一次消费使用新键;未确认操作始终沿原键完成确认。 -计划写入通过版本比较拒绝过期覆盖,全局提前时间或周额度上限变更唤醒本地重算,关闭自动使用保留未决键供重新开启后恢复 +计划写入通过版本比较拒绝过期覆盖,全局使用时机、提前时间或周额度上限变更唤醒本地重算,关闭自动使用保留未决键供重新开启后恢复 ### CPR 互联观测 diff --git a/frontend/src/api/modules/accounts/reset-credits.ts b/frontend/src/api/modules/accounts/reset-credits.ts index cceafe51e..0e85f52ab 100644 --- a/frontend/src/api/modules/accounts/reset-credits.ts +++ b/frontend/src/api/modules/accounts/reset-credits.ts @@ -23,6 +23,7 @@ export interface AccountResetCreditResultResponse { export interface AccountResetCreditAutomation { enabled: boolean + weeklyTriggerRemainingPercent: number | null leadMinutes: number nextDiscoveryAtDisplay: string | null nextConsumeAtDisplay: string | null diff --git a/frontend/src/api/modules/settings/index.ts b/frontend/src/api/modules/settings/index.ts index 6748cdfa6..966a52714 100644 --- a/frontend/src/api/modules/settings/index.ts +++ b/frontend/src/api/modules/settings/index.ts @@ -68,6 +68,7 @@ export interface RuntimeSettings { accountWarmupEnabled: boolean accountWarmupCron: string accountWarmupModel: string | null + resetCreditOnLowWeeklyQuota: boolean resetCreditLeadMinutes: number resetCreditMaxWeeklyRemainingPercent: number | null updatedAt: string diff --git a/frontend/src/i18n/locales/en/accounts.json b/frontend/src/i18n/locales/en/accounts.json index 72ffc79e3..baba66223 100644 --- a/frontend/src/i18n/locales/en/accounts.json +++ b/frontend/src/i18n/locales/en/accounts.json @@ -514,20 +514,21 @@ "unconfirmed": "The last automatic reset is unconfirmed", "expiredUnconfirmed": "The last reset could not be confirmed and the reset credit has expired", "queryFailed": "The last query failed, retrying on schedule", + "awaitingWeeklyRecovery": "Waiting for weekly quota to recover after the last credit", "aboveThreshold": "Remaining weekly quota exceeds the threshold, checking again later", "quotaUnavailable": "Weekly quota is unavailable, checking again later", "resetNotNeeded": "This quota window does not need a reset, checking again later", "resetIncomplete": "The upstream service did not complete the last automatic reset", "scheduleHelp": "Check once a day at a random time, staggered across accounts", - "verifyHelp": "Verify reset credits before expiry, automatically skip credits already used elsewhere", + "verifyHelp": "Recheck the credit and any weekly quota conditions before use", "label": "Automatically use expiring reset credits" }, "automaticallyUseResetCard": "Automatically use resets", "automaticUsageRules": "Automatic usage rules", - "setGlobalLeadTime": "Set global lead time", + "setTiming": "Set when to use credits", + "weeklyThreshold": "Weekly quota remaining ≤ {percent}%", "minutesInAdvance": "{leadMinutes} min in advance", - "leadTime": "Lead time", - "nextUse": "Next use: {nextConsumeAtDisplay}", + "nextUse": "Scheduled expiry use: {nextConsumeAtDisplay}", "limitReset": "Limit reset", "confirmLastReset": "Confirm last reset", "confirmResetAmount": "Confirm reset amount", diff --git a/frontend/src/i18n/locales/en/settings.json b/frontend/src/i18n/locales/en/settings.json index db5e735eb..0e7376872 100644 --- a/frontend/src/i18n/locales/en/settings.json +++ b/frontend/src/i18n/locales/en/settings.json @@ -308,7 +308,11 @@ "quotaReset": { "title": "Quota reset credits", "enableHelp": "Enable automatic use in the account's Quota reset panel", - "description": "Global settings for accounts with automatic use enabled", + "description": "How long before expiry to use a reset credit", + "timing": "When to use a credit", + "expiryMode": "Before expiry", + "weeklyMode": "By weekly quota", + "earlyThresholdHelp": "Use at or below this percentage, leave blank or enter 0 to wait until exhausted", "thresholdHelp": "Skip automatic use when the remaining quota exceeds this threshold, leave blank for no limit", "weeklyQuotaLimit": "Reset credit remaining weekly quota threshold" }, diff --git a/frontend/src/i18n/locales/zh-Hans/accounts.json b/frontend/src/i18n/locales/zh-Hans/accounts.json index 765efc057..35f340bba 100644 --- a/frontend/src/i18n/locales/zh-Hans/accounts.json +++ b/frontend/src/i18n/locales/zh-Hans/accounts.json @@ -514,20 +514,21 @@ "unconfirmed": "上次自动重置结果待确认", "expiredUnconfirmed": "上次重置结果未能确认,卡片已到期", "queryFailed": "最近查询失败,将按计划重试", + "awaitingWeeklyRecovery": "已用卡,等待周额度恢复", "aboveThreshold": "剩余周额度高于上限,稍后检查", "quotaUnavailable": "暂时无法确认周额度,稍后检查", "resetNotNeeded": "当前额度窗口不需要重置,稍后检查", "resetIncomplete": "上游未完成最近一次自动重置", "scheduleHelp": "每天随机查询一次,各账号错开时间", - "verifyHelp": "临期使用前核对卡片,已在其他地方使用的会自动跳过", + "verifyHelp": "使用前重新核对卡片和适用的周额度条件", "label": "自动使用临期重置卡" }, "automaticallyUseResetCard": "自动使用重置卡", "automaticUsageRules": "自动使用规则", - "setGlobalLeadTime": "设置全局提前时间", + "setTiming": "设置用卡时机", + "weeklyThreshold": "剩余周额度 ≤ {percent}%", "minutesInAdvance": "提前 {leadMinutes} 分钟", - "leadTime": "提前时间", - "nextUse": "下次使用 {nextConsumeAtDisplay}", + "nextUse": "临期用卡时间 {nextConsumeAtDisplay}", "limitReset": "额度重置", "confirmLastReset": "确认上次重置", "confirmResetAmount": "确认重置额度", diff --git a/frontend/src/i18n/locales/zh-Hans/settings.json b/frontend/src/i18n/locales/zh-Hans/settings.json index f0d35b2ac..094859ddc 100644 --- a/frontend/src/i18n/locales/zh-Hans/settings.json +++ b/frontend/src/i18n/locales/zh-Hans/settings.json @@ -308,7 +308,11 @@ "quotaReset": { "title": "主动重置卡", "enableHelp": "在账号的「额度重置」中开启自动使用", - "description": "全局设置,对已开启自动使用的账号生效", + "description": "到期前多久使用重置卡", + "timing": "使用时机", + "expiryMode": "临期使用", + "weeklyMode": "按周额度使用", + "earlyThresholdHelp": "剩余比例不高于此值时使用,留空或填 0 表示耗尽时使用", "thresholdHelp": "高于此值时暂不自动使用,留空表示不限制", "weeklyQuotaLimit": "重置卡剩余周额度上限" }, diff --git a/frontend/src/i18n/locales/zh-Hant/accounts.json b/frontend/src/i18n/locales/zh-Hant/accounts.json index 88eca1600..1e84d007b 100644 --- a/frontend/src/i18n/locales/zh-Hant/accounts.json +++ b/frontend/src/i18n/locales/zh-Hant/accounts.json @@ -514,20 +514,21 @@ "unconfirmed": "上次自動重置結果待確認", "expiredUnconfirmed": "上次重置結果未能確認,卡片已到期", "queryFailed": "最近查詢失敗,將按計劃重試", + "awaitingWeeklyRecovery": "已用卡,等待週額度恢復", "aboveThreshold": "剩餘周額度高於上限,稍後檢查", "quotaUnavailable": "暫時無法確認周額度,稍後檢查", "resetNotNeeded": "當前額度窗口不需要重置,稍後檢查", "resetIncomplete": "上游未完成最近一次自動重置", "scheduleHelp": "每天隨機查詢一次,各賬號錯開時間", - "verifyHelp": "臨期使用前核對卡片,已在其他地方使用的會自動跳過", + "verifyHelp": "使用前重新核對卡片和適用的週額度條件", "label": "自動使用臨期重置卡" }, "automaticallyUseResetCard": "自動使用重置卡", "automaticUsageRules": "自動使用規則", - "setGlobalLeadTime": "設置全局提前時間", + "setTiming": "設定用卡時機", + "weeklyThreshold": "剩餘週額度 ≤ {percent}%", "minutesInAdvance": "提前 {leadMinutes} 分鐘", - "leadTime": "提前時間", - "nextUse": "下次使用 {nextConsumeAtDisplay}", + "nextUse": "臨期用卡時間 {nextConsumeAtDisplay}", "limitReset": "額度重置", "confirmLastReset": "確認上次重置", "confirmResetAmount": "確認重置額度", diff --git a/frontend/src/i18n/locales/zh-Hant/settings.json b/frontend/src/i18n/locales/zh-Hant/settings.json index 2fb0471b6..f2335c185 100644 --- a/frontend/src/i18n/locales/zh-Hant/settings.json +++ b/frontend/src/i18n/locales/zh-Hant/settings.json @@ -308,7 +308,11 @@ "quotaReset": { "title": "主動重置卡", "enableHelp": "在賬號的「額度重置」中開啓自動使用", - "description": "全局設置,對已開啓自動使用的賬號生效", + "description": "到期前多久使用重置卡", + "timing": "使用時機", + "expiryMode": "臨期使用", + "weeklyMode": "按週額度使用", + "earlyThresholdHelp": "剩餘比例不高於此值時使用,留空或填 0 表示耗盡時使用", "thresholdHelp": "高於此值時暫不自動使用,留空表示不限制", "weeklyQuotaLimit": "重置卡剩餘周額度上限" }, diff --git a/frontend/src/views/accounts/components/account-quota-panel/ResetCreditAutomation.vue b/frontend/src/views/accounts/components/account-quota-panel/ResetCreditAutomation.vue index ab1a2b2c2..3d32715cc 100644 --- a/frontend/src/views/accounts/components/account-quota-panel/ResetCreditAutomation.vue +++ b/frontend/src/views/accounts/components/account-quota-panel/ResetCreditAutomation.vue @@ -19,6 +19,14 @@ const switchEnabled = shallowRef(false) const loadAction = useAsyncAction() const saveAction = useAsyncAction() const busy = computed(() => loadAction.loading.value || saveAction.loading.value) +const timingLabel = computed(() => { + if (!status.value) + return t('accounts.quotaReset.setTiming') + const { weeklyTriggerRemainingPercent, leadMinutes } = status.value + return weeklyTriggerRemainingPercent == null + ? t('accounts.quotaReset.minutesInAdvance', { leadMinutes }) + : t('accounts.quotaReset.weeklyThreshold', { percent: weeklyTriggerRemainingPercent }) +}) const resultText = computed(() => { switch (status.value?.lastResult) { case 'pending': return status.value?.enabled @@ -27,6 +35,7 @@ const resultText = computed(() => { case 'expired_unknown': return t('accounts.quotaReset.automation.expiredUnconfirmed') case 'discovery_failed': return t('accounts.quotaReset.automation.queryFailed') case 'weekly_quota_above_threshold': return t('accounts.quotaReset.automation.aboveThreshold') + case 'awaiting_weekly_recovery': return t('accounts.quotaReset.automation.awaitingWeeklyRecovery') case 'weekly_quota_unavailable': return t('accounts.quotaReset.automation.quotaUnavailable') case 'nothing_to_reset': return t('accounts.quotaReset.automation.resetNotNeeded') case 'not_redeemed': return t('accounts.quotaReset.automation.resetIncomplete') @@ -84,11 +93,11 @@ watch(() => props.accountId, () => {
- + - {{ status ? t('accounts.quotaReset.minutesInAdvance', { leadMinutes: status.leadMinutes }) : t('accounts.quotaReset.leadTime') }} + {{ timingLabel }} -import { ZCard, ZFormItem, ZInput } from '@codex-proxy/ui' +import { ZCard, ZFormItem, ZInput, ZSegmented } from '@codex-proxy/ui' +import { computed } from 'vue' import { useI18n } from 'vue-i18n' const { t } = useI18n({ useScope: 'global' }) const leadMinutes = defineModel({ required: true }) +const onLowWeeklyQuota = defineModel('onLowWeeklyQuota', { required: true }) const maxWeeklyRemainingPercent = defineModel('maxWeeklyRemainingPercent', { required: true }) +const modes = computed(() => [ + { + value: 'expiry', + label: t('settings.quotaReset.expiryMode'), + }, + { + value: 'weekly', + label: t('settings.quotaReset.weeklyMode'), + }, +])