fix(pool): 配额倒计时归零后进度条与列表恢复显示 100%

- 后端读取层 provider_key_status_snapshot_payload 复用调度侧同一判定
  provider_pool_reset_deadline_elapsed,对已到期的 Codex 配额窗口归一化为
  used_ratio=0 / remaining_ratio=1,并清除窗口级耗尽标记;跳过
  window_minutes=0 与无用量观测的窗口
- 前端展示层在倒计时归零(isExpired)时兜底显示 100%,并隐藏重置前的旧用量
  文本,保证归零瞬间即时恢复,与后端读取口径、调度口径一致
- 补充后端 2 个单测(到期归一化、遗留耗尽状态清理)与前端 1 个回归用例
  (负向验证可复现旧行为)

验证:aether-provider-pool 71/71;aether-gateway lib 回归通过(仅 3 个依赖
PostgreSQL 服务端的用例因本机环境缺失失败,与本改动无关);前端 222 文件 /
1718 用例全部通过;clippy -D warnings、cargo fmt、vue-tsc、eslint 均通过。
This commit is contained in:
AAEE86
2026-09-29 16:52:26 +08:00
parent 00a315e3bf
commit 309f507ef4
5 changed files with 285 additions and 17 deletions
@@ -2575,6 +2575,63 @@ fn windsurf_quota_snapshot_has_stale_cooldown(quota_snapshot: &Map<String, Value
has_capacity || !exhausted
}
/// 读取状态快照时,把已越过重置时间点的 Codex 配额窗口按“已重置”口径归一化。
///
/// 背景:调度侧早已把到期窗口视为未耗尽(`provider_pool_reset_deadline_elapsed`),
/// 账号额度文本也会按到期强制显示 100%,但列表读取此前直接返回存量快照,
/// 导致管理端倒计时归零后进度条仍停留在旧的剩余百分比。这里让读取层与
/// 调度侧、文本侧使用同一口径,避免三处状态互相矛盾。
fn normalize_expired_codex_quota_windows(
snapshot: &mut serde_json::Map<String, Value>,
provider_type: &str,
) {
if !provider_type.trim().eq_ignore_ascii_case("codex") {
return;
}
let Some(quota) = snapshot.get_mut("quota").and_then(Value::as_object_mut) else {
return;
};
let now_unix_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0);
let fallback_observed_at = provider_quota_timestamp_unix_secs(quota.get("observed_at"))
.or_else(|| provider_quota_timestamp_unix_secs(quota.get("updated_at")));
let Some(windows) = quota.get_mut("windows").and_then(Value::as_array_mut) else {
return;
};
for window in windows.iter_mut().filter_map(Value::as_object_mut) {
// 与同类 Codex 窗口处理保持一致:window_minutes=0 不是真实配额窗口。
if window.get("window_minutes").and_then(Value::as_u64) == Some(0) {
continue;
}
if !aether_provider_pool::provider_pool_reset_deadline_elapsed(
window,
fallback_observed_at,
now_unix_secs,
) {
continue;
}
// 只归一化带用量观测的窗口,避免把没有观测数据的窗口凭空显示成 100%。
let has_usage_observation = ["used_ratio", "remaining_ratio"]
.into_iter()
.any(|field| window.get(field).is_some_and(Value::is_number));
if !has_usage_observation {
continue;
}
window.insert("used_ratio".to_string(), json!(0.0));
window.insert("remaining_ratio".to_string(), json!(1.0));
// 同步清掉窗口级耗尽标记,避免展示与调度口径互相矛盾。
for field in ["is_exhausted", "exhausted"] {
if let Some(slot) = window.get_mut(field) {
*slot = json!(false);
}
}
}
}
pub(crate) fn provider_key_status_snapshot_payload(
key: &StoredProviderCatalogKey,
provider_type: &str,
@@ -2626,6 +2683,9 @@ pub(crate) fn provider_key_status_snapshot_payload(
}
}
}
// 读取时归一化已到期的 Codex 配额窗口,保证列表进度条与调度侧、
// 账号额度文本使用同一“已重置”口径。
normalize_expired_codex_quota_windows(&mut snapshot, provider_type);
snapshot.insert(
"oauth".to_string(),
build_provider_key_oauth_status_snapshot(key),
@@ -3674,6 +3734,153 @@ mod tests {
assert_eq!(window.get("reset_seconds"), Some(&json!(3_600u64)));
}
#[test]
fn provider_key_status_snapshot_payload_normalizes_expired_codex_quota_windows() {
let mut key = sample_catalog_key();
key.status_snapshot = Some(json!({
"quota": {
"version": 2,
"provider_type": "codex",
"code": "ok",
"exhausted": false,
"updated_at": 1_700_000_000u64,
"windows": [
{
"code": "5h",
"label": "5H",
"scope": "account",
"unit": "percent",
"used_ratio": 0.88,
"remaining_ratio": 0.12,
"reset_at": 1_700_003_600u64,
"window_minutes": 300
},
{
"code": "weekly",
"label": "周",
"scope": "account",
"unit": "percent",
"used_ratio": 0.5,
"remaining_ratio": 0.5,
"reset_at": 2_000_000_000u64,
"window_minutes": 10_080
},
{
"code": "spark_5h",
"label": "Spark 5H",
"scope": "account",
"unit": "percent",
"reset_at": 1_700_003_600u64,
"window_minutes": 300
},
{
"code": "unlimited",
"label": "无限",
"scope": "account",
"unit": "percent",
"used_ratio": 0.3,
"remaining_ratio": 0.7,
"reset_at": 1_700_003_600u64,
"window_minutes": 0
}
]
}
}));
let payload = provider_key_status_snapshot_payload(&key, "codex");
// 已到期的窗口按“已重置”口径归一化:用量清零、剩余 100%。
assert_eq!(payload.pointer("/quota/windows/0/code"), Some(&json!("5h")));
assert_eq!(
payload.pointer("/quota/windows/0/used_ratio"),
Some(&json!(0.0))
);
assert_eq!(
payload.pointer("/quota/windows/0/remaining_ratio"),
Some(&json!(1.0))
);
// 未到期的窗口保留原始观测值。
assert_eq!(
payload.pointer("/quota/windows/1/code"),
Some(&json!("weekly"))
);
assert_eq!(
payload.pointer("/quota/windows/1/used_ratio"),
Some(&json!(0.5))
);
assert_eq!(
payload.pointer("/quota/windows/1/remaining_ratio"),
Some(&json!(0.5))
);
// 没有用量观测的窗口不会被凭空补成 100%。
assert_eq!(
payload.pointer("/quota/windows/2/code"),
Some(&json!("spark_5h"))
);
assert_eq!(payload.pointer("/quota/windows/2/used_ratio"), None);
assert_eq!(payload.pointer("/quota/windows/2/remaining_ratio"), None);
// window_minutes=0 不是真实配额窗口,与同类 Codex 窗口处理保持一致,不归一化。
assert_eq!(
payload.pointer("/quota/windows/3/code"),
Some(&json!("unlimited"))
);
assert_eq!(
payload.pointer("/quota/windows/3/used_ratio"),
Some(&json!(0.3))
);
assert_eq!(
payload.pointer("/quota/windows/3/remaining_ratio"),
Some(&json!(0.7))
);
}
#[test]
fn provider_key_status_snapshot_payload_clears_expired_codex_window_exhausted_state() {
let mut key = sample_catalog_key();
key.status_snapshot = Some(json!({
"quota": {
"version": 2,
"provider_type": "codex",
"code": "exhausted",
"exhausted": true,
"usage_ratio": 1.0,
"updated_at": 1_700_000_000u64,
"windows": [
{
"code": "weekly",
"label": "周",
"scope": "account",
"unit": "percent",
"used_ratio": 1.0,
"remaining_ratio": 0.0,
"reset_at": 1_700_003_600u64,
"window_minutes": 10_080,
"is_exhausted": true
}
]
}
}));
let payload = provider_key_status_snapshot_payload(&key, "codex");
// 汇总标志沿用既有调度口径(窗口已到期 → 不再视为耗尽)。
assert_eq!(payload.pointer("/quota/exhausted"), Some(&json!(false)));
assert_eq!(payload.pointer("/quota/code"), Some(&json!("ok")));
// 窗口级耗尽标记与剩余比例同步归一化。
assert_eq!(
payload.pointer("/quota/windows/0/is_exhausted"),
Some(&json!(false))
);
assert_eq!(
payload.pointer("/quota/windows/0/used_ratio"),
Some(&json!(0.0))
);
assert_eq!(
payload.pointer("/quota/windows/0/remaining_ratio"),
Some(&json!(1.0))
);
}
#[test]
fn provider_key_status_snapshot_payload_backfills_chatgpt_web_image_quota() {
let mut key = sample_catalog_key();
+1 -1
View File
@@ -43,7 +43,7 @@ pub use quota::{
provider_pool_key_model_quota_hard_blocked, provider_pool_key_quota_hard_blocked,
provider_pool_key_scheduling_label, provider_pool_member_quota_snapshot,
provider_pool_quota_metadata_provider_type, provider_pool_quota_metadata_updated_at,
provider_pool_quota_snapshot_updated_at,
provider_pool_quota_snapshot_updated_at, provider_pool_reset_deadline_elapsed,
};
pub use quota_refresh::ProviderPoolQuotaRequestSpec;
pub use service::ProviderPoolService;
+8 -1
View File
@@ -857,7 +857,14 @@ fn provider_pool_reset_deadline_unix_secs(
})
}
pub(crate) fn provider_pool_reset_deadline_elapsed(
/// Whether the quota window's reset deadline has already passed.
///
/// The deadline is taken from `reset_at`/`next_reset_at` when present, otherwise
/// derived from `reset_seconds`/`reset_after_seconds` anchored at the window (or
/// fallback) observation time. Scheduling ignores exhausted windows once this is
/// true; read paths can reuse the same predicate so the displayed quota matches
/// the scheduling decision after a reset.
pub fn provider_pool_reset_deadline_elapsed(
item: &Map<String, Value>,
fallback_observed_at: Option<u64>,
now_unix_secs: u64,
+25 -14
View File
@@ -2061,17 +2061,23 @@ const quotaProgressMap = computed<Record<string, QuotaProgressItem[]>>(() => {
const quotaProgressDisplayMap = computed<Record<string, QuotaProgressDisplayItem[]>>(() => {
const map: Record<string, QuotaProgressDisplayItem[]> = {}
for (const key of keyPage.value.keys) {
map[key.key_id] = (quotaProgressMap.value[key.key_id] || []).map(item => ({
label: getQuotaProgressLabel(item.label),
remainingPercent: item.remainingPercent,
resetText: getQuotaProgressResetDisplayText(item),
meterText: item.numericOnly
? item.detail || formatQuotaValue(item.remainingPercent)
: getQuotaProgressMeterDisplayText(item),
barClass: getQuotaRemainingBarColorByRemaining(item.remainingPercent),
meterClass: getQuotaRemainingClassByRemaining(item.remainingPercent),
numericOnly: item.numericOnly,
}))
map[key.key_id] = (quotaProgressMap.value[key.key_id] || []).map(item => {
// 倒计时归零表示窗口已越过重置时间点:按“已重置”展示 100%,
// 不再显示重置前的旧用量文本,与后端读取口径、调度口径保持一致。
const expired = !item.numericOnly && getQuotaProgressCountdown(item)?.isExpired === true
const remainingPercent = expired ? 100 : item.remainingPercent
return {
label: getQuotaProgressLabel(item.label),
remainingPercent,
resetText: getQuotaProgressResetDisplayText(item),
meterText: item.numericOnly
? item.detail || formatQuotaValue(remainingPercent)
: getQuotaProgressMeterDisplayText(item, remainingPercent, expired),
barClass: getQuotaRemainingBarColorByRemaining(remainingPercent),
meterClass: getQuotaRemainingClassByRemaining(remainingPercent),
numericOnly: item.numericOnly,
}
})
}
return map
})
@@ -3544,10 +3550,15 @@ function getQuotaProgressResetDisplayText(item: QuotaProgressItem): string {
return ''
}
function getQuotaProgressMeterDisplayText(item: QuotaProgressItem): string {
const detail = item.detail?.trim() || ''
function getQuotaProgressMeterDisplayText(
item: QuotaProgressItem,
remainingPercent = item.remainingPercent,
suppressDetail = false,
): string {
// 窗口已重置时忽略重置前的旧用量文本,直接显示归一化后的剩余百分比。
const detail = suppressDetail ? '' : (item.detail?.trim() || '')
if (!shouldHideQuotaProgressDetailText(detail) && detail) return detail
return `${item.remainingPercent.toFixed(1)}%`
return `${remainingPercent.toFixed(1)}%`
}
function getQuotaFallbackText(key: PoolKeyDetail): string | null {
@@ -35,6 +35,10 @@ const routeMocks = vi.hoisted(() => ({
}),
}))
const countdownMocks = vi.hoisted(() => ({
isExpired: false,
}))
const proxyStoreMocks = vi.hoisted(() => ({
ensureLoaded: vi.fn(),
}))
@@ -106,7 +110,7 @@ vi.mock('@/composables/useCountdownTimer', async () => {
start: vi.fn(),
}),
getCodexResetCountdown: () => ({
isExpired: false,
isExpired: countdownMocks.isExpired,
text: '1h',
}),
}
@@ -604,6 +608,7 @@ beforeEach(() => {
window.sessionStorage.clear()
routeMocks.patchQuery.mockClear()
proxyStoreMocks.ensureLoaded.mockClear()
countdownMocks.isExpired = false
endpointMocks.getPoolOverview.mockReset()
endpointMocks.getPoolSchedulingPresets.mockReset()
@@ -736,6 +741,44 @@ describe('PoolManagement Codex cycle stats mode', () => {
expect(root.textContent).toContain('生图')
})
it('shows expired Codex quota windows as fully restored', async () => {
countdownMocks.isExpired = true
const expiredKey = createPoolKey('codex', {
status_snapshot: {
oauth: { code: 'valid' },
account: { code: 'ok', blocked: false },
quota: {
code: 'ok',
exhausted: false,
provider_type: 'codex',
windows: [
{
code: '5h',
label: '5H',
scope: 'account',
remaining_ratio: 0.12,
reset_at: 1_700_000_000,
window_minutes: 300,
},
],
},
},
})
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(expiredKey))
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
const root = mountPoolManagement()
await settle()
// 倒计时归零后进度条与文本按“已重置”显示 100%,不再显示旧百分比。
expect(root.querySelector('[data-testid="pool-quota-meter-text"]')?.textContent?.trim()).toBe('100.0%')
const track = root.querySelector('[data-testid="pool-quota-progress-track"]')
const bar = track?.firstElementChild as HTMLElement | null
expect(bar?.style.width).toBe('100%')
expect(root.querySelector('[data-testid="pool-quota-reset-text"]')).toBeNull()
})
it('labels Codex quota by the actual refresh window duration', async () => {
const monthlyCodexKey = createPoolKey('codex', {
status_snapshot: {