Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(usage): 额度倒计时以窗口长度封顶,避免周限刚重置显示 8 天 (#5418)

Dash635a56a3974d
diff --git a/apps/desktop/src/renderer/__tests__/modelSourceDetails.test.tsx b/apps/desktop/src/renderer/__tests__/modelSourceDetails.test.tsx
index db422affe2..60c58af95b 100644
--- a/apps/desktop/src/renderer/__tests__/modelSourceDetails.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelSourceDetails.test.tsx
@@ -296,6 +296,44 @@ describe('model source second line', () => {
'claude · Max · 剩余 5% · 2天 · 剩余 20%',
);
});
+ it('caps countdowns at the window length right after a reset, except xAI', () => {
+ // resetsAt 比 now + 窗口长度晚 30 秒(服务端取整 / 时钟偏差),不得向上取整成多一天/一小时
+ reads.accounts['account-a'] = {
+ ...snapshot(0),
+ rateLimits: {
+ // 5h 窗口更紧张,来源行显示它
+ primary: { usedPercent: 50, windowMinutes: 300, resetsAt: now / 1000 + 5 * 3600 + 30 },
+ secondary: { usedPercent: 0, windowMinutes: 10080, resetsAt: now / 1000 + 7 * 86400 + 30 },
+ },
+ };
+ reads.claudeSnapshot = {
+ subscriptionType: 'max',
+ fiveHour: { utilization: 0, resetsAt: now / 1000 + 5 * 3600 + 30 },
+ sevenDay: { utilization: 0, resetsAt: now / 1000 + 7 * 86400 + 30 },
+ };
+ // xAI resetsAt 可能来自非周窗口 / 月度账期,原样显示
+ reads.xaiSnapshot = {
+ planLabel: 'SuperGrok',
+ creditUsagePercent: 0,
+ resetsAt: now / 1000 + 25 * 86400,
+ updatedAt: now,
+ };
+ render(
+ <ModelSourceUsageProvider
+ providers={[provider('account-a'), provider('claude', 'claude'), provider('xai', 'xai')]}
+ scope={local}
+ >
+ {details()}
+ {details('claude', 'claude-opus-5')}
+ {details('xai', 'grok-4')}
+ </ModelSourceUsageProvider>,
+ );
+ expect(screen.getByText(quotaText('5小时 50%'))).toBeTruthy();
+ // Claude 两窗口同为 0% 已用,后一个(周限)胜出
+ expect(screen.getByText(quotaText('7天 100%'))).toBeTruthy();
+ expect(screen.getByText(quotaText('25天 100%'))).toBeTruthy();
+ expect(screen.queryByText(/8天|6小时/)).toBeNull();
+ });
it('shows current xAI weekly quota and hides stale values', () => {
reads.xaiSnapshot = {
planLabel: 'SuperGrok',
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index f00ebf6ff6..098f9d05d9 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -159,6 +159,21 @@ describe('TodaySpendChip dashboard routing', () => {
expect(compact(source)).toContain(compact('todaySpend.codex.unavailableDetail'));
});
+ it('caps the reset countdown at the window length right after a reset', () => {
+ const units = ((key: string) =>
+ key === 'todaySpend.unit.day' ? '天' : key === 'todaySpend.unit.hour' ? '小时' : key) as TFunction;
+ const week = 7 * 24 * 60;
+ // resetsAt 比 now + 7 天晚 30 秒 (服务端取整 / 时钟偏差): 不得向上取整成「8天」
+ const resetsAt = week * 60 + 30;
+ expect(formatCompactTimeUntilReset(resetsAt, 0, units, week)).toBe('7天');
+ expect(formatCompactTimeUntilReset(5 * 3600 + 30, 0, units, 5 * 60)).toBe('5小时');
+ // 未越界时封顶不改变向上取整口径
+ expect(formatCompactTimeUntilReset(6 * 86400 + 60, 0, units, week)).toBe('7天');
+ expect(formatCompactTimeUntilReset(5 * 86400 + 60, 0, units, week)).toBe('6天');
+ // 窗口长度未知时不封顶
+ expect(formatCompactTimeUntilReset(25 * 86400, 0, units)).toBe('25天');
+ });
+
it('ticks the reset countdown per second in the last minute and rolls remaining % up after a reset', () => {
// 最后一分钟秒级倒计时: formatCompactTimeUntilReset 落到秒单位, tick 节奏由
// computeCountdownTickDelayMs 决定 (setTimeout 链, 非固定 interval)
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx
index 0f60a7903f..16ed0d1c3d 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx
@@ -2,7 +2,11 @@ import { createContext, useContext, useEffect, useMemo, useState, type ReactNode
import { useTranslation } from 'react-i18next';
import type { ProviderView } from '@cindy/model-providers';
import { matchCodexBucketForModel } from '@cindy/maker-shared/codex-usage-buckets';
-import { formatCompactTimeUntilReset } from '@/lib/compactQuotaCountdown';
+import {
+ FIVE_HOUR_WINDOW_MINUTES,
+ formatCompactTimeUntilReset,
+ WEEKLY_WINDOW_MINUTES,
+} from '@/lib/compactQuotaCountdown';
import {
formatClaudeSubscriptionPlanLabel,
formatCodexPlanLabel,
@@ -88,6 +92,7 @@ export function ModelSourceUsageProvider({
interface QuotaWindow {
usedPercent: number;
resetsAt?: number | null;
+ windowMinutes?: number | null;
}
function modelSourceQuota(
@@ -119,12 +124,20 @@ function modelSourceQuota(
const weekly = data && (matchScopedWindowForModel(data.scoped, modelId) ?? data.sevenDay);
return {
plan: formatClaudeSubscriptionPlanLabel(data?.subscriptionType),
- windows: [data?.fiveHour, weekly]
+ windows: [
+ data?.fiveHour && { window: data.fiveHour, windowMinutes: FIVE_HOUR_WINDOW_MINUTES },
+ weekly && { window: weekly, windowMinutes: WEEKLY_WINDOW_MINUTES },
+ ]
.filter((w): w is NonNullable<typeof w> => !!w)
- .map((w) => ({ usedPercent: w.utilization, resetsAt: w.resetsAt })),
+ .map(({ window, windowMinutes }) => ({
+ usedPercent: window.utilization,
+ resetsAt: window.resetsAt,
+ windowMinutes,
+ })),
};
}
const data = usage.xai;
+ // xAI resetsAt may fall back to a non-weekly period end, so it is not capped.
return {
plan: data?.planLabel ?? null,
windows:
@@ -150,7 +163,12 @@ export function ModelSourceDetails({
const parts = windows
.filter((window) => Number.isFinite(window.usedPercent))
.map((window) => {
- const countdown = formatCompactTimeUntilReset(window.resetsAt, nowMs, t);
+ const countdown = formatCompactTimeUntilReset(
+ window.resetsAt,
+ nowMs,
+ t,
+ window.windowMinutes,
+ );
// Do not present the previous period's percentage as a fresh quota.
const expired =
typeof window.resetsAt === 'number' &&
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index d5de500633..40b5448e7a 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -1,4 +1,8 @@
-import { formatCompactTimeUntilReset } from '@/lib/compactQuotaCountdown';
+import {
+ FIVE_HOUR_WINDOW_MINUTES,
+ formatCompactTimeUntilReset,
+ WEEKLY_WINDOW_MINUTES,
+} from '@/lib/compactQuotaCountdown';
import { isOpenAiSubscriptionProvider } from '@cindy/model-providers';
import { useDeviceProviders } from '@/hooks/useDeviceProviders';
import { useProviders } from '@/hooks/useProviders';
@@ -300,7 +304,12 @@ function formatWindowLabel(
// chip 模式: label 直接用距 reset 的剩余时长(所有限额窗口都算给用户);
// 无 reset 数据时回退下面的窗口名派生链。tooltip 模式不进这个分支(窗口名 + 精确时间)。
if (options?.preferResetCountdown) {
- const countdown = formatCompactTimeUntilReset(window?.resetsAt, nowMs, t);
+ const countdown = formatCompactTimeUntilReset(
+ window?.resetsAt,
+ nowMs,
+ t,
+ window?.windowMinutes,
+ );
if (countdown !== null) return countdown;
}
@@ -434,7 +443,12 @@ function getClaudeChipWindows(
typeof fiveHour.utilization === 'number' &&
Number.isFinite(fiveHour.utilization)
) {
- const countdown = formatCompactTimeUntilReset(fiveHour.resetsAt, nowMs, t);
+ const countdown = formatCompactTimeUntilReset(
+ fiveHour.resetsAt,
+ nowMs,
+ t,
+ FIVE_HOUR_WINDOW_MINUTES,
+ );
const resetsAtMs = toEpochMs(fiveHour.resetsAt);
windows.push({
key: 'claude-5h',
@@ -451,7 +465,12 @@ function getClaudeChipWindows(
typeof weekly.window.utilization === 'number' &&
Number.isFinite(weekly.window.utilization)
) {
- const countdown = formatCompactTimeUntilReset(weekly.window.resetsAt, nowMs, t);
+ const countdown = formatCompactTimeUntilReset(
+ weekly.window.resetsAt,
+ nowMs,
+ t,
+ WEEKLY_WINDOW_MINUTES,
+ );
const label = countdown
? weekly.modelDisplayName
? `${weekly.modelDisplayName} ${countdown}`
@@ -661,6 +680,7 @@ function getXaiChipWindows(
): ChipWindowSegment[] {
if (!isXaiWeeklyUsageCurrent(snapshot, nowMs) || !snapshot) return [];
const used = snapshot.creditUsagePercent ?? 0;
+ // xAI 的 resetsAt 可能回退到非周窗口 / 月度账期结束时间, 不按周长封顶。
const countdown = formatCompactTimeUntilReset(snapshot.resetsAt ?? undefined, nowMs, t);
const resetsAtMs = toEpochMs(snapshot.resetsAt ?? undefined);
return [
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
index 301dd97e3a..d28f1624f7 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.deviceLink.test.tsx
@@ -53,6 +53,8 @@ vi.mock('react-i18next', () => ({
'todaySpend.codex.daysWindow': '{{days}}天',
'todaySpend.xai.windowSegment': '{{label}} 剩余 {{remaining}}',
'todaySpend.xai.weekWindow': '周限',
+ 'todaySpend.unit.day': '天',
+ 'todaySpend.unit.hour': '小时',
'todaySpend.sessionCostLabel': '本任务 {{cost}}',
'todaySpend.dailyLimitLabel': '今日 {{spend}}/{{limit}}',
'todaySpend.monthlyLimitLabel': '本月 {{spend}}/{{limit}}',
@@ -329,6 +331,53 @@ describe('TodaySpendChip device-link remote sessions', () => {
expect(mocks.remoteCodexDeviceIds).toContain('device-abc');
});
+ it('窗口刚重置时倒计时以窗口长度封顶,不显示「8天」', () => {
+ // resetsAt 比 now + 窗口长度晚 30 秒(服务端取整 / 时钟偏差)
+ const nowSec = Date.now() / 1000;
+ const bucket = {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 10, windowMinutes: 300, resetsAt: nowSec + 5 * 3600 + 30 },
+ secondary: { usedPercent: 20, windowMinutes: 10_080, resetsAt: nowSec + 7 * 86400 + 30 },
+ };
+ mocks.remoteCodexPayload = { ...bucket, appServerBuckets: { codex: bucket }, webSnapshot: null };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="codex"
+ providerId="openai"
+ modelId="gpt-5.6-sol"
+ sessionId="session-remote-codex-reset"
+ deviceLinkDeviceId="device-abc"
+ />,
+ );
+
+ expect(container.textContent).toContain('5小时 剩余 90%');
+ expect(container.textContent).toContain('7天 剩余 80%');
+ expect(container.textContent).not.toContain('8天');
+ });
+
+ it('xai 重置时间可能是非周账期,倒计时不按 7 天封顶', () => {
+ mocks.remoteXaiSnapshot = {
+ planLabel: 'SuperGrok',
+ creditUsagePercent: 25,
+ resetsAt: Date.now() / 1000 + 25 * 86400,
+ updatedAt: Date.now(),
+ };
+
+ const { container } = render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="xai"
+ modelId="grok-4.6"
+ sessionId="session-remote-xai-period"
+ deviceLinkDeviceId="device-abc"
+ />,
+ );
+
+ expect(container.textContent).toContain('25天 剩余 75%');
+ });
+
it('远程 codex 折扣模型(codex/)按网关形态渲染,不显示订阅窗口', () => {
mocks.remoteCodexPayload = {
source: 'codex-app-server',
diff --git a/apps/desktop/src/renderer/lib/compactQuotaCountdown.ts b/apps/desktop/src/renderer/lib/compactQuotaCountdown.ts
index 7d4ba0a24a..9a82cbf90f 100644
--- a/apps/desktop/src/renderer/lib/compactQuotaCountdown.ts
+++ b/apps/desktop/src/renderer/lib/compactQuotaCountdown.ts
@@ -8,17 +8,24 @@ const DAY_MS = 24 * 60 * 60 * 1000;
* label(所有限额窗口都算给用户);无数据 / 已过期 → null, 调用方回退窗口名。
* 天级向上取整与 Codex 既有 getDaysUntilReset 口径一致(剩 6天10小时 → 7天)。
* 最后一分钟降到秒级, 配合秒级 tick(computeCountdownTickDelayMs)逐秒走动。
+ *
+ * windowMinutes 已知时剩余时长以窗口长度封顶: 窗口刚重置时 resetsAt 可能因服务端
+ * 取整或时钟偏差比 now 晚出窗口长度一点点, 向上取整会把 7 天周限显示成「8天」。
*/
export function formatCompactTimeUntilReset(
epochSeconds: number | null | undefined,
nowMs: number,
t: TFunction,
+ windowMinutes?: number | null,
): string | null {
if (typeof epochSeconds !== 'number' || !Number.isFinite(epochSeconds) || epochSeconds <= 0) {
return null;
}
- const remainMs = epochSeconds * 1000 - nowMs;
+ let remainMs = epochSeconds * 1000 - nowMs;
if (remainMs <= 0) return null;
+ if (typeof windowMinutes === 'number' && Number.isFinite(windowMinutes) && windowMinutes > 0) {
+ remainMs = Math.min(remainMs, windowMinutes * 60_000);
+ }
if (remainMs >= DAY_MS) {
return `${Math.ceil(remainMs / DAY_MS)}${t('todaySpend.unit.day')}`;
}
@@ -30,3 +37,7 @@ export function formatCompactTimeUntilReset(
}
return `${Math.max(1, Math.ceil(remainMs / 1000))}${t('todaySpend.unit.second')}`;
}
+
+/** 不下发 windowMinutes 的 Claude 5h / 周限窗口的固定长度。 */
+export const FIVE_HOUR_WINDOW_MINUTES = 5 * 60;
+export const WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
diff --git a/apps/mobile/src/__tests__/mobileModelRowPresentation.test.ts b/apps/mobile/src/__tests__/mobileModelRowPresentation.test.ts
index cec0a71070..921620f6a7 100644
--- a/apps/mobile/src/__tests__/mobileModelRowPresentation.test.ts
+++ b/apps/mobile/src/__tests__/mobileModelRowPresentation.test.ts
@@ -15,13 +15,13 @@ describe('model row cost tiers',()=>{
describe('account weekly quota',()=>{
it('selects account quota instead of model promotion and converts used into remaining',()=>{
const generic={limitId:'codex',primary:{windowMinutes:300,usedPercent:95,resetsAt:200},secondary:{windowMinutes:10080,usedPercent:20,resetsAt:1000}};
- expect(mobileWeeklyQuota('codex',{rateLimits:generic,rateLimitsByLimitId:{codex:generic}},100000)).toEqual({remaining:80,resetsAt:1000});
+ expect(mobileWeeklyQuota('codex',{rateLimits:generic,rateLimitsByLimitId:{codex:generic}},100000)).toEqual({remaining:80,resetsAt:1000,windowMinutes:10080});
});
it('hides expired windows, missing percentages and stale xAI snapshots',()=>{
expect(mobileWeeklyQuota('claude',{sevenDay:{utilization:20,resetsAt:10}},10000)).toBeNull();
expect(mobileWeeklyQuota('claude',{sevenDay:{resetsAt:1000}},10000)).toBeNull();
expect(mobileWeeklyQuota('xai',{creditUsagePercent:20,updatedAt:1},31*60000)).toBeNull();
- expect(mobileWeeklyQuota('xai',{creditUsagePercent:20,updatedAt:100,resetsAt:1000},10000)).toEqual({remaining:80,resetsAt:1000});
+ expect(mobileWeeklyQuota('xai',{creditUsagePercent:20,updatedAt:100,resetsAt:1000},10000)).toEqual({remaining:80,resetsAt:1000,windowMinutes:null});
});
it('does not use same-brand API accounts as subscription accounts',()=>{
expect(mobileQuotaSource(provider({id:'openai'}))).toBeNull();
@@ -38,6 +38,17 @@ it.each([[86400,'1d'],[86399,'24h'],[3600,'1h'],[3599,'60m'],[60,'1m'],[59,'59s'
expect(quotaCountdown(reset as number,0)).toBe(expected);
});
+it('caps the countdown at the known window right after a reset',()=>{
+ const week=mobileWeeklyQuota('claude',{sevenDay:{utilization:0,resetsAt:7*86400+30}},0)!;
+ expect(week.windowMinutes).toBe(10080);
+ expect(quotaCountdown(week.resetsAt!,0,undefined,week.windowMinutes)).toBe('7d');
+ expect(quotaCountdown(6*86400+60,0,undefined,10080)).toBe('7d');
+ expect(quotaCountdown(5*86400+60,0,undefined,10080)).toBe('6d');
+ // xAI resetsAt may be a non-weekly period end: never cap it
+ const xai=mobileWeeklyQuota('xai',{creditUsagePercent:0,updatedAt:1,resetsAt:25*86400},2)!;
+ expect(quotaCountdown(xai.resetsAt!,2,undefined,xai.windowMinutes)).toBe('25d');
+});
+
it('localizes all countdown units using the supplied language',()=>{
const unit=(name:string)=>({day:'天',hour:'小时',minute:'分钟',second:'秒'})[name]!;
expect(quotaCountdown(273600,0,unit)).toBe('4天');
diff --git a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
index 03d8c93a37..15f59dbdbc 100644
--- a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
+++ b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
@@ -111,7 +111,7 @@ describe("task menu usage presentation", () => {
updatedAt: now,
amounts: [],
windows: [
- { id: "a", minutes: 300, remainingPercent: 94, resetsAt: at(6.5 * 3_600_000) },
+ { id: "a", minutes: 300, remainingPercent: 94, resetsAt: at(4.5 * 3_600_000) },
{ id: "b", minutes: 10080, remainingPercent: 29, resetsAt: at(2.2 * 86_400_000) },
{ id: "m", minutes: 10080, modelLabel: "Opus", remainingPercent: 8, resetsAt: at(2.2 * 86_400_000) },
{ id: "c", minutes: 300, remainingPercent: 50, resetsAt: at(90_000) },
@@ -121,7 +121,7 @@ describe("task menu usage presentation", () => {
};
const rows = accountUsageRows(account, i18n.t, "zh-CN", now);
expect(rows.map(({ label, value }) => [label, value])).toEqual([
- ["7小时", "剩余 94%"],
+ ["5小时", "剩余 94%"],
["3天", "剩余 29%"],
["Opus · 3天", "剩余 8%"],
["2分钟", "剩余 50%"],
@@ -131,4 +131,20 @@ describe("task menu usage presentation", () => {
expect(rows.every((row) => row.detail === undefined)).toBe(true);
expect(formatQuotaResetCountdown(at(45_000), now, i18n.t)).toBe("45秒");
});
+ it("caps a just-reset window at its length, but never xAI's possibly non-weekly reset", () => {
+ const now = 1_000_000_000_000;
+ const at = (ms: number) => (now + ms) / 1000;
+ const window = (resetsAt: number) => ({ id: "w", minutes: 10080, remainingPercent: 100, resetsAt });
+ const account = (source: SessionMenuAccountUsage["source"], resetsAt: number): SessionMenuAccountUsage => ({
+ source,
+ plan: null,
+ updatedAt: now,
+ amounts: [],
+ windows: [window(resetsAt)],
+ });
+ // resetsAt lands 30s past now + 7 days (server rounding / clock skew).
+ expect(accountUsageRows(account("claude", at(7 * 86_400_000 + 30_000)), i18n.t, "zh-CN", now)[0].label).toBe("7天");
+ expect(accountUsageRows(account("xai", at(25 * 86_400_000)), i18n.t, "zh-CN", now)[0].label).toBe("25天");
+ expect(formatQuotaResetCountdown(at(7 * 86_400_000 + 30_000), now, i18n.t, 10080)).toBe("7天");
+ });
});
diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsx
index ac7711013b..8074e1ccc7 100644
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@ -520,8 +520,8 @@ export function SessionMenuSheet({
modelId: session.model,
nowMs: now,
});
- return summarizeAccountRateLimits(scoped, now, mobilePresentationLocalizer, (resetsAt) =>
- formatQuotaResetCountdown(resetsAt, now, t),
+ return summarizeAccountRateLimits(scoped, now, mobilePresentationLocalizer, (resetsAt, windowMinutes) =>
+ formatQuotaResetCountdown(resetsAt, now, t, windowMinutes),
);
// visible / quotaStaleTick / countdownTick 进依赖: 重开、到点失效与倒计时推进都按当前时间重算。
}, [accountUsage, i18nInstance.language, quotaBucketTables, session.model, visible, quotaStaleTick, countdownTick, t]);
diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
index fef88c2c88..870090981a 100644
--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
@@ -1,6 +1,6 @@
import { modelNeedsReselection } from './modelReselection';
import { mobileProviderAccountTitle } from "./mobileModelRowPresentation";
-import { mobileCostMarks, quotaCountdown } from "./mobileModelRowPresentation";
+import { mobileCostMarks } from "./mobileModelRowPresentation";
import { formatQuotaResetCountdown } from "./sessionUsagePresentation";
import { useMobileModelQuotas } from "./useMobileModelQuotas";
import { useEffect, useMemo, useRef, useState } from "react";
@@ -129,8 +129,6 @@ export function UnifiedModelPickerSheet(
p: ModelPickerSheetProps & { unified: UnifiedMobilePickerOptions },
) {
const { t } = useTranslation();
- const countdown = (reset: number, now: number) =>
- quotaCountdown(reset, now, (unit) => t(`models.unified.timeUnit.${unit}`));
const { quotas, now } = useMobileModelQuotas(
p.unified.scope,
p.visible,
@@ -316,7 +314,14 @@ export function UnifiedModelPickerSheet(
: null;
return modelQuota
? [
- modelQuota.resetsAt ? countdown(modelQuota.resetsAt, now) : null,
+ modelQuota.resetsAt
+ ? formatQuotaResetCountdown(
+ modelQuota.resetsAt,
+ now,
+ t,
+ modelQuota.windowMinutes,
+ )
+ : null,
`${modelQuota.remaining}%`,
]
.filter(Boolean)
@@ -613,7 +618,12 @@ export function UnifiedModelPickerSheet(
remaining: quotas[provider.id]!.remaining!,
label: [
(quotas[provider.id]!.resetsAt
- ? formatQuotaResetCountdown(quotas[provider.id]!.resetsAt!, now, t)
+ ? formatQuotaResetCountdown(
+ quotas[provider.id]!.resetsAt!,
+ now,
+ t,
+ quotas[provider.id]!.windowMinutes ?? null,
+ )
: null) ?? t("session.menu.usage.week"),
t("session.menu.usage.remaining", {
percent: quotas[provider.id]!.remaining,
diff --git a/apps/mobile/src/session/mobileModelRowPresentation.ts b/apps/mobile/src/session/mobileModelRowPresentation.ts
index 228a1e93dc..e1e31e81c1 100644
--- a/apps/mobile/src/session/mobileModelRowPresentation.ts
+++ b/apps/mobile/src/session/mobileModelRowPresentation.ts
@@ -36,9 +36,12 @@ export function mobileQuotaSource(p: ProviderView): QuotaSource | null {
if (p.source !== "builtin") return null;
return p.id === "anthropic" ? "claude" : p.id === "xai" ? "xai" : null;
}
+const WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
export interface MobileWeeklyQuota {
remaining: number;
resetsAt: number | null;
+ /** Known window length for capping the countdown; null when resetsAt may not be weekly (xAI). */
+ windowMinutes: number | null;
}
const object = (v: unknown): Record<string, unknown> =>
v && typeof v === "object" && !Array.isArray(v)
@@ -53,6 +56,7 @@ export function mobileWeeklyQuota(
const data = object(raw);
let used: unknown;
let resets: unknown;
+ let windowMinutes: number | null = WEEKLY_WINDOW_MINUTES;
if (source === "codex") {
const snapshot = data as unknown as MobileCodexRateLimitsResult;
if (!snapshot.rateLimits) return null;
@@ -82,6 +86,8 @@ export function mobileWeeklyQuota(
return null;
used = data.creditUsagePercent;
resets = data.resetsAt;
+ // resetsAt may fall back to a non-weekly period end.
+ windowMinutes = null;
}
if (typeof used !== "number" || !Number.isFinite(used)) return null;
const resetsAt =
@@ -92,14 +98,23 @@ export function mobileWeeklyQuota(
return {
remaining: Math.round(Math.max(0, Math.min(100, 100 - used))),
resetsAt,
+ windowMinutes,
};
}
-/** Match Desktop compactQuotaCountdown: one unit, rounded up; expired stays unknown. */
+/**
+ * Match Desktop compactQuotaCountdown: one unit, rounded up; expired stays unknown.
+ * A known windowMinutes caps the countdown: right after a reset, server rounding or
+ * clock skew can put resetsAt slightly past now + window, and rounding up would read
+ * "8d" for a 7-day window.
+ */
export type QuotaTimeUnit = 'day' | 'hour' | 'minute' | 'second';
-export function quotaCountdown(reset: number, now: number, unitLabel: (unit: QuotaTimeUnit) => string = unit => ({day:'d',hour:'h',minute:'m',second:'s'})[unit]): string | null {
+export function quotaCountdown(reset: number, now: number, unitLabel: (unit: QuotaTimeUnit) => string = unit => ({day:'d',hour:'h',minute:'m',second:'s'})[unit], windowMinutes?: number | null): string | null {
if (!Number.isFinite(reset) || reset <= 0) return null;
- const remaining = reset * 1000 - now;
+ let remaining = reset * 1000 - now;
if (remaining <= 0) return null;
+ if (typeof windowMinutes === "number" && Number.isFinite(windowMinutes) && windowMinutes > 0) {
+ remaining = Math.min(remaining, windowMinutes * 60000);
+ }
if (remaining >= 86400000) return `${Math.ceil(remaining / 86400000)}${unitLabel("day")}`;
if (remaining >= 3600000) return `${Math.ceil(remaining / 3600000)}${unitLabel("hour")}`;
if (remaining >= 60000) return `${Math.ceil(remaining / 60000)}${unitLabel("minute")}`;
diff --git a/apps/mobile/src/session/sessionUsagePresentation.ts b/apps/mobile/src/session/sessionUsagePresentation.ts
index 9cdffc645d..085f430e98 100644
--- a/apps/mobile/src/session/sessionUsagePresentation.ts
+++ b/apps/mobile/src/session/sessionUsagePresentation.ts
@@ -11,14 +11,19 @@ import { quotaCountdown } from "./mobileModelRowPresentation";
/**
* Time left until a quota resets, used as the window label like the desktop status
* chip ("7 hours": one unit, rounded up). Null once the reset time has passed.
+ * A known windowMinutes caps it so a just-reset weekly window never reads "8 days".
*/
export function formatQuotaResetCountdown(
resetsAt: number,
now: number,
t: TFunction,
+ windowMinutes?: number | null,
): string | null {
- return quotaCountdown(resetsAt, now, (unit) =>
- t(`models.unified.timeUnit.${unit}`),
+ return quotaCountdown(
+ resetsAt,
+ now,
+ (unit) => t(`models.unified.timeUnit.${unit}`),
+ windowMinutes,
);
}
@@ -90,7 +95,13 @@ export function accountUsageRows(
const countdown =
window.resetsAt === null
? null
- : formatQuotaResetCountdown(window.resetsAt, now, t);
+ : formatQuotaResetCountdown(
+ window.resetsAt,
+ now,
+ t,
+ // xAI resetsAt may fall back to a non-weekly period end; only its label is weekly.
+ account.source === "xai" ? null : window.minutes,
+ );
const label =
countdown ??
(window.minutes === 10080
diff --git a/packages/maker-shared/src/__tests__/sessionControls.test.ts b/packages/maker-shared/src/__tests__/sessionControls.test.ts
index 549deac3ad..c701063809 100644
--- a/packages/maker-shared/src/__tests__/sessionControls.test.ts
+++ b/packages/maker-shared/src/__tests__/sessionControls.test.ts
@@ -164,6 +164,9 @@ describe('summarizeAccountRateLimits', () => {
{ label: '2小时', value: '剩余 60% · 已用 40%' },
{ label: '周', value: '剩余 90% · 已用 10%' },
]);
+ // The window length reaches the label so a countdown can cap at it.
+ expect(resetLabel).toHaveBeenCalledWith(resetsAt, 300);
+ expect(resetLabel).toHaveBeenCalledWith(resetsAt + 1, 10080);
});
it('omits windows whose reset has passed when labelling by countdown', () => {
diff --git a/packages/maker-shared/src/sessionControls.ts b/packages/maker-shared/src/sessionControls.ts
index 43e6f9e165..d03cd87c07 100644
--- a/packages/maker-shared/src/sessionControls.ts
+++ b/packages/maker-shared/src/sessionControls.ts
@@ -134,8 +134,9 @@ export function summarizeAccountRateLimits(
/**
* Label a window by its reset (e.g. a countdown) instead of its duration; null keeps
* the duration label. Without it, rows name the window and append the reset time.
+ * windowMinutes lets a countdown cap at the window length.
*/
- resetLabel?: (resetsAt: number) => string | null,
+ resetLabel?: (resetsAt: number, windowMinutes: number | null) => string | null,
): {
rows: Array<{ label: string; value: string }>;
} | null {
@@ -169,7 +170,9 @@ export function summarizeAccountRateLimits(
// belongs to the previous period until a new snapshot arrives.
if (resetLabel && resetsAt !== null && resetsAt > 0 && resetsAt * 1000 <= nowMs) continue;
const countdownLabel =
- resetLabel && resetsAt !== null && resetsAt > 0 ? resetLabel(resetsAt) : null;
+ resetLabel && resetsAt !== null && resetsAt > 0
+ ? resetLabel(resetsAt, readNumber(window.windowMinutes))
+ : null;
if (!resetLabel) {
const resetText = formatRateLimitResetAt(resetsAt, nowMs, localizer);
if (resetText) {