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。

feat(mobile): 额度标签改为距重置的倒计时 (#5419)

Dash4af648375889
diff --git a/apps/mobile/src/__tests__/mobilePresentationRefresh.test.ts b/apps/mobile/src/__tests__/mobilePresentationRefresh.test.ts
index f78ed251d7..bd384b3f59 100644
--- a/apps/mobile/src/__tests__/mobilePresentationRefresh.test.ts
+++ b/apps/mobile/src/__tests__/mobilePresentationRefresh.test.ts
@@ -111,7 +111,7 @@ describe('mobile localized presentation refresh', () => {
const source = read('src/session/SessionMenuSheet.tsx');
expect(source).toContain(
- '[accountUsage, i18nInstance.language, quotaBucketTables, session.model, visible, quotaStaleTick]',
+ '[accountUsage, i18nInstance.language, quotaBucketTables, session.model, visible, quotaStaleTick, countdownTick, t]',
);
expect(source).toContain('[codexRateLimits, i18nInstance.language]');
});
diff --git a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
index 5336c371b3..03d8c93a37 100644
--- a/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
+++ b/apps/mobile/src/__tests__/sessionUsagePresentation.test.ts
@@ -2,6 +2,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import { i18n } from "@/i18n";
import {
accountUsageRows,
+ formatQuotaResetCountdown,
formatSessionUsageMoney,
sessionUsageAmounts,
} from "@/session/sessionUsagePresentation";
@@ -72,7 +73,7 @@ describe("task menu usage presentation", () => {
updatedAt: 1000,
amounts: [],
windows: [
- { id: "a", minutes: 180, remainingPercent: 8, resetsAt: 2000 },
+ { id: "a", minutes: 180, remainingPercent: 8, resetsAt: null },
{ id: "b", minutes: 10080, remainingPercent: 0, resetsAt: 1 },
],
};
@@ -101,4 +102,33 @@ describe("task menu usage presentation", () => {
const rows = accountUsageRows(account, i18n.t, "zh-CN");
expect(rows[1]).toEqual({ label: "Credits", value, warning });
});
+ it("labels each quota by the time left until it resets, like the desktop status chip", () => {
+ const now = 1_000_000_000_000;
+ const at = (ms: number) => (now + ms) / 1000;
+ const account: SessionMenuAccountUsage = {
+ source: "claude",
+ plan: null,
+ updatedAt: now,
+ amounts: [],
+ windows: [
+ { id: "a", minutes: 300, remainingPercent: 94, resetsAt: at(6.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) },
+ { id: "d", minutes: 300, remainingPercent: 50, resetsAt: at(-1_000) },
+ { id: "e", minutes: 10080, remainingPercent: 50, resetsAt: null },
+ ],
+ };
+ const rows = accountUsageRows(account, i18n.t, "zh-CN", now);
+ expect(rows.map(({ label, value }) => [label, value])).toEqual([
+ ["7小时", "剩余 94%"],
+ ["3天", "剩余 29%"],
+ ["Opus · 3天", "剩余 8%"],
+ ["2分钟", "剩余 50%"],
+ ["5 小时", "等待刷新"],
+ ["本周", "剩余 50%"],
+ ]);
+ expect(rows.every((row) => row.detail === undefined)).toBe(true);
+ expect(formatQuotaResetCountdown(at(45_000), now, i18n.t)).toBe("45秒");
+ });
});
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index a4f72703a2..1aa9e8e461 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -421,7 +421,6 @@
"hours": "{{count}} hours",
"minutes": "{{count}} minutes",
"remaining": "{{percent}}% remaining",
- "resets": "Resets {{time}}",
"awaitingRefresh": "Awaiting refresh",
"balance": "Available balance",
"cycle": "Used this cycle",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index a28f64ba13..ec69891c83 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -421,7 +421,6 @@
"hours": "{{count}} 時間",
"minutes": "{{count}} 分",
"remaining": "残り {{percent}}%",
- "resets": "{{time}} にリセット",
"awaitingRefresh": "更新待ち",
"balance": "利用可能残高",
"cycle": "今サイクルの使用額",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index b0d255167e..0079c6ad52 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -417,7 +417,6 @@
"hours": "{{count}}시간",
"minutes": "{{count}}분",
"remaining": "{{percent}}% 남음",
- "resets": "{{time}}에 초기화",
"awaitingRefresh": "새로고침 대기 중",
"balance": "사용 가능한 잔액",
"cycle": "이번 주기 사용액",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index e90d277d28..70e64683a9 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -417,7 +417,6 @@
"hours": "{{count}} 小时",
"minutes": "{{count}} 分钟",
"remaining": "剩余 {{percent}}%",
- "resets": "{{time}} 重置",
"awaitingRefresh": "等待刷新",
"balance": "可用余额",
"cycle": "本周期已用",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index e9f639069a..45ed437594 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -421,7 +421,6 @@
"hours": "{{count}} 小時",
"minutes": "{{count}} 分鐘",
"remaining": "剩餘 {{percent}}%",
- "resets": "{{time}} 重設",
"awaitingRefresh": "等待重新整理",
"balance": "可用餘額",
"cycle": "本週期已用",
diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsx
index 07c6186b89..ac7711013b 100644
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@ -1,6 +1,7 @@
import { TaskTagLabels, TaskTagsPanel } from './TaskTags';
import { TaskTagsSheet, useTaskTagsSheet } from './TaskTagsSheet';
import type { OpenAiAccountProvider } from './sessionControls';
+import { formatQuotaResetCountdown } from './sessionUsagePresentation';
/**
* SessionMenuSheet —— 会话右上角「…」菜单浮窗(取代旧三 tab 的会话设置面板)。
*
@@ -498,6 +499,15 @@ export function SessionMenuSheet({
return () => clearTimeout(timer);
}, [visible, quotaBucketTables, quotaStaleTick]);
+ // Countdown labels move with the clock while the sheet is open; the card refreshes
+ // on the same 30s cadence through its usage polling.
+ const [countdownTick, setCountdownTick] = useState(0);
+ useEffect(() => {
+ if (!visible) return undefined;
+ const timer = setInterval(() => setCountdownTick((tick) => tick + 1), 30_000);
+ return () => clearInterval(timer);
+ }, [visible]);
+
const accountLimits = useMemo(() => {
const now = Date.now();
// 账号可能同时有主配额桶与模型专属促销桶(如 GPT-5.3-Codex-Spark), 上游每次
@@ -510,9 +520,11 @@ export function SessionMenuSheet({
modelId: session.model,
nowMs: now,
});
- return summarizeAccountRateLimits(scoped, now, mobilePresentationLocalizer);
- // visible / quotaStaleTick 进依赖: 重开与到点失效都要按当前时间重选。
- }, [accountUsage, i18nInstance.language, quotaBucketTables, session.model, visible, quotaStaleTick]);
+ return summarizeAccountRateLimits(scoped, now, mobilePresentationLocalizer, (resetsAt) =>
+ formatQuotaResetCountdown(resetsAt, now, t),
+ );
+ // visible / quotaStaleTick / countdownTick 进依赖: 重开、到点失效与倒计时推进都按当前时间重算。
+ }, [accountUsage, i18nInstance.language, quotaBucketTables, session.model, visible, quotaStaleTick, countdownTick, t]);
const resetSummary = useMemo(
() => summarizeCodexRateLimitReset(codexRateLimits, Date.now(), mobilePresentationLocalizer),
[codexRateLimits, i18nInstance.language],
diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
index d0a25fcccc..fef88c2c88 100644
--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
@@ -1,6 +1,7 @@
import { modelNeedsReselection } from './modelReselection';
import { mobileProviderAccountTitle } from "./mobileModelRowPresentation";
import { mobileCostMarks, quotaCountdown } from "./mobileModelRowPresentation";
+import { formatQuotaResetCountdown } from "./sessionUsagePresentation";
import { useMobileModelQuotas } from "./useMobileModelQuotas";
import { useEffect, useMemo, useRef, useState } from "react";
import * as ExpoCrypto from "expo-crypto";
@@ -611,21 +612,13 @@ export function UnifiedModelPickerSheet(
? {
remaining: quotas[provider.id]!.remaining!,
label: [
- t("session.menu.usage.week"),
+ (quotas[provider.id]!.resetsAt
+ ? formatQuotaResetCountdown(quotas[provider.id]!.resetsAt!, now, t)
+ : null) ?? t("session.menu.usage.week"),
t("session.menu.usage.remaining", {
percent: quotas[provider.id]!.remaining,
}),
- quotas[provider.id]!.resetsAt
- ? t("session.menu.usage.resets", {
- time: countdown(
- quotas[provider.id]!.resetsAt!,
- now,
- ),
- })
- : null,
- ]
- .filter(Boolean)
- .join(" · "),
+ ].join(" · "),
}
: undefined,
providerMark: {
diff --git a/apps/mobile/src/session/sessionUsagePresentation.ts b/apps/mobile/src/session/sessionUsagePresentation.ts
index 3cd15287b4..9cdffc645d 100644
--- a/apps/mobile/src/session/sessionUsagePresentation.ts
+++ b/apps/mobile/src/session/sessionUsagePresentation.ts
@@ -6,6 +6,21 @@ import {
type RemoteMoney,
} from "./remoteMoney";
import type { RemoteSession } from "./types";
+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.
+ */
+export function formatQuotaResetCountdown(
+ resetsAt: number,
+ now: number,
+ t: TFunction,
+): string | null {
+ return quotaCountdown(resetsAt, now, (unit) =>
+ t(`models.unified.timeUnit.${unit}`),
+ );
+}
export function formatSessionUsageMoney(money: RemoteMoney): string {
const symbol = remoteMoneySymbol(money.currency);
@@ -70,14 +85,21 @@ export function accountUsageRows(
if (!account) return [];
const rows: AccountUsageRow[] = [];
for (const window of account.windows) {
+ // The countdown replaces the window name; without one (unknown or elapsed
+ // reset) the row falls back to naming the window.
+ const countdown =
+ window.resetsAt === null
+ ? null
+ : formatQuotaResetCountdown(window.resetsAt, now, t);
const label =
- window.minutes === 10080
+ countdown ??
+ (window.minutes === 10080
? t("session.menu.usage.week")
: window.minutes && window.minutes % 60 === 0
? t("session.menu.usage.hours", { count: window.minutes / 60 })
: window.minutes
? t("session.menu.usage.minutes", { count: window.minutes })
- : t("session.menu.usage.quota");
+ : t("session.menu.usage.quota"));
const expired = window.resetsAt !== null && window.resetsAt * 1000 <= now;
rows.push({
label: window.modelLabel ? `${window.modelLabel} · ${label}` : label,
@@ -87,18 +109,6 @@ export function accountUsageRows(
percent: Math.round(window.remainingPercent),
}),
warning: !expired && window.remainingPercent <= 10,
- ...(window.resetsAt !== null
- ? {
- detail: t("session.menu.usage.resets", {
- time: new Date(window.resetsAt * 1000).toLocaleString(locale, {
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- }),
- }),
- }
- : {}),
});
}
const credits = account.credits;
diff --git a/packages/maker-shared/src/__tests__/sessionControls.test.ts b/packages/maker-shared/src/__tests__/sessionControls.test.ts
index 7a64dc2997..549deac3ad 100644
--- a/packages/maker-shared/src/__tests__/sessionControls.test.ts
+++ b/packages/maker-shared/src/__tests__/sessionControls.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
nextCodexBucketStaleAtMs,
resolveCodexBucketTable,
@@ -153,6 +153,33 @@ describe('summarizeAccountRateLimits', () => {
expect(summary!.rows[2]).toEqual({ label: '周', value: '剩余 87.5% · 已用 12.5%' });
});
+ it('lets callers label windows by their reset countdown instead of duration', () => {
+ const resetsAt = Math.floor(NOW_MS / 1000) + 2 * 60 * 60;
+ const resetLabel = vi.fn((value: number) => (value === resetsAt ? '2小时' : null));
+ const summary = summarizeAccountRateLimits({
+ primary: { usedPercent: 40, windowMinutes: 300, resetsAt },
+ secondary: { usedPercent: 10, windowMinutes: 10080, resetsAt: resetsAt + 1 },
+ }, NOW_MS, undefined, resetLabel);
+ expect(summary!.rows).toEqual([
+ { label: '2小时', value: '剩余 60% · 已用 40%' },
+ { label: '周', value: '剩余 90% · 已用 10%' },
+ ]);
+ });
+
+ it('omits windows whose reset has passed when labelling by countdown', () => {
+ const past = Math.floor(NOW_MS / 1000) - 60;
+ const summary = summarizeAccountRateLimits({
+ primary: { usedPercent: 40, windowMinutes: 300, resetsAt: past },
+ secondary: { usedPercent: 10, windowMinutes: 10080 },
+ }, NOW_MS, undefined, () => 'unused');
+ expect(summary!.rows).toEqual([{ label: '周', value: '剩余 90% · 已用 10%' }]);
+ // Without countdown labels the existing reset-time rendering is unchanged.
+ const legacy = summarizeAccountRateLimits({
+ primary: { usedPercent: 40, windowMinutes: 300, resetsAt: past },
+ }, NOW_MS);
+ expect(legacy!.rows[0].value).toContain('重置');
+ });
+
it('follows upstream window composition instead of assuming 5h exists (weekly-only)', () => {
const summary = summarizeAccountRateLimits({
primary: { usedPercent: 30, windowMinutes: 10080 },
diff --git a/packages/maker-shared/src/sessionControls.ts b/packages/maker-shared/src/sessionControls.ts
index 082f7e2755..43e6f9e165 100644
--- a/packages/maker-shared/src/sessionControls.ts
+++ b/packages/maker-shared/src/sessionControls.ts
@@ -131,6 +131,11 @@ export function summarizeAccountRateLimits(
value: unknown,
nowMs: number,
localizer?: PresentationLocalizer,
+ /**
+ * 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.
+ */
+ resetLabel?: (resetsAt: number) => string | null,
): {
rows: Array<{ label: string; value: string }>;
} | null {
@@ -159,14 +164,22 @@ export function summarizeAccountRateLimits(
percent: formatRateLimitPercent(used),
}),
];
- const resetText = formatRateLimitResetAt(readNumber(window.resetsAt), nowMs, localizer);
- if (resetText) {
- parts.push(presentationText(localizer, 'session.presentation.controls.rateLimit.resetsAt', `${resetText} 重置`, {
- time: resetText,
- }));
+ const resetsAt = readNumber(window.resetsAt);
+ // Countdown mode never presents a window whose reset has passed: its percentage
+ // 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;
+ if (!resetLabel) {
+ const resetText = formatRateLimitResetAt(resetsAt, nowMs, localizer);
+ if (resetText) {
+ parts.push(presentationText(localizer, 'session.presentation.controls.rateLimit.resetsAt', `${resetText} 重置`, {
+ time: resetText,
+ }));
+ }
}
rows.push({
- label: rateLimitWindowLabel(readNumber(window.windowMinutes), localizer),
+ label: countdownLabel ?? rateLimitWindowLabel(readNumber(window.windowMinutes), localizer),
value: parts.join(' · '),
});
}