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(desktop): clarify Claude usage window labels (#568)

JiangJiahao0977054af6ab
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.behavior.test.tsx b/apps/desktop/src/renderer/__tests__/todaySpendChip.behavior.test.tsx
new file mode 100644
index 0000000000..3fb687f347
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.behavior.test.tsx
@@ -0,0 +1,178 @@
+// @vitest-environment jsdom
+
+import React from 'react';
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useTranslation } from 'react-i18next';
+
+import enCommon from '../i18n/locales/en/common.json';
+import koCommon from '../i18n/locales/ko/common.json';
+import type { ClaudeSubscriptionUsageSnapshot } from '../hooks/useClaudeSubscriptionUsage';
+
+const mocks = vi.hoisted(() => ({
+ useClaudeSubscriptionUsage: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: vi.fn(),
+}));
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ text, children }: { text: React.ReactNode; children: React.ReactElement }) => (
+ <>
+ {children}
+ <div data-testid="usage-tooltip">{text}</div>
+ </>
+ ),
+}));
+
+vi.mock('@/hooks/useApiKey', () => ({
+ useApiKey: () => ({ hasSavedKey: false, isReconciling: false }),
+}));
+vi.mock('@/hooks/useClaudeOAuthConnected', () => ({
+ useClaudeOAuthConnected: () => true,
+}));
+vi.mock('@/hooks/useClaudeSessionRoute', () => ({
+ useClaudeSessionRoute: () => null,
+}));
+vi.mock('@/hooks/useSessionSpend', () => ({
+ useSessionSpend: () => null,
+}));
+vi.mock('@/hooks/useSessionEstimatedValue', () => ({
+ useSessionEstimatedValue: () => null,
+}));
+vi.mock('@/hooks/useSessionTokens', () => ({
+ useSessionTokens: () => null,
+}));
+vi.mock('@/components/chat/ChatDisplaySnapshotContext', () => ({
+ useChatDisplaySnapshot: () => null,
+}));
+vi.mock('@/hooks/useAccountUsage', () => ({
+ requestCodexAccountRefresh: vi.fn(),
+ useAccountUsage: () => null,
+}));
+vi.mock('@/hooks/useClaudeAccountUsage', () => ({
+ useClaudeAccountUsage: () => null,
+}));
+vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({
+ requestClaudeSubscriptionRefresh: vi.fn(),
+ useClaudeSubscriptionUsage: mocks.useClaudeSubscriptionUsage,
+}));
+vi.mock('@/hooks/useCodexRuntimeRoute', () => ({
+ useCodexRuntimeRoute: () => ({ authInjection: null }),
+}));
+vi.mock('@/hooks/useXaiRateLimit', () => ({
+ useXaiRateLimit: () => null,
+}));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ getSnapshot: () => ({ messages: [] }),
+ subscribe: () => () => {},
+ },
+}));
+vi.mock('../components/status/quotaResetRollup', () => ({
+ RESET_PENDING_MAX_MS: 10 * 60_000,
+ computeCountdownTickDelayMs: () => 60_000,
+ useQuotaResetRollup: (
+ slot: { remainingPercent: number } | null,
+ ) => slot ? { percent: slot.remainingPercent, celebrating: false } : null,
+}));
+vi.mock('../components/status/QuotaResetConfetti', () => ({
+ QuotaResetConfetti: () => null,
+}));
+
+import { TodaySpendChip } from '../components/status/TodaySpendChip';
+
+type LocaleCatalog = Record<string, unknown>;
+
+function readCatalogValue(catalog: LocaleCatalog, key: string): string {
+ const value = key.split('.').reduce<unknown>((current, segment) => {
+ if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined;
+ return (current as Record<string, unknown>)[segment];
+ }, catalog);
+ if (typeof value !== 'string') throw new Error(`Missing test translation: ${key}`);
+ return value;
+}
+
+function makeTranslator(catalog: LocaleCatalog) {
+ return (key: string, values?: Record<string, unknown>): string =>
+ readCatalogValue(catalog, key).replace(/\{\{(\w+)\}\}/g, (_match, name: string) =>
+ String(values?.[name] ?? ''),
+ );
+}
+
+// 选择 UTC / Asia-Shanghai 下都不会跨天的时刻,让 resetAt 稳定走“当天只显时分”分支。
+const NOW_MS = Date.parse('2026-07-25T08:00:00.000Z');
+const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
+const RESET_AT_SECONDS = Math.floor((NOW_MS + FIVE_HOURS_MS) / 1000);
+
+function usageSnapshot(): ClaudeSubscriptionUsageSnapshot {
+ return {
+ subscriptionType: 'pro',
+ fiveHour: { utilization: 5, resetsAt: RESET_AT_SECONDS },
+ sevenDay: { utilization: 25, resetsAt: RESET_AT_SECONDS },
+ scoped: [{
+ modelDisplayName: 'Fable',
+ utilization: 25,
+ resetsAt: RESET_AT_SECONDS,
+ }],
+ };
+}
+
+function renderClaudeUsage(catalog: LocaleCatalog) {
+ vi.mocked(useTranslation).mockReturnValue({
+ t: makeTranslator(catalog),
+ } as never);
+ mocks.useClaudeSubscriptionUsage.mockReturnValue(usageSnapshot());
+ render(
+ <TodaySpendChip
+ vendorKey="cc"
+ providerId="anthropic"
+ modelId="claude-fable"
+ />,
+ );
+}
+
+describe('TodaySpendChip Claude subscription presentation', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW_MS);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it('keeps stable chip identities and renders complete reset details in the tooltip', () => {
+ renderClaudeUsage(enCommon);
+
+ expect(screen.getByText('5h 95% left')).toBeTruthy();
+ expect(screen.getByText('Fable weekly 75% left')).toBeTruthy();
+
+ const resetAt = new Date(RESET_AT_SECONDS * 1000).toLocaleTimeString(undefined, {
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+ const tooltipText = screen.getByTestId('usage-tooltip').textContent;
+ expect(tooltipText).toContain(
+ `Weekly 75% left (25% used) · resets in 5h (${resetAt})`,
+ );
+ expect(tooltipText).toContain(
+ `Fable weekly 75% left (25% used) · resets in 5h (${resetAt})`,
+ );
+ });
+
+ it('keeps a space before the Korean reset-time parenthesis', () => {
+ renderClaudeUsage(koCommon);
+
+ const resetAt = new Date(RESET_AT_SECONDS * 1000).toLocaleTimeString(undefined, {
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+ expect(screen.getByTestId('usage-tooltip').textContent).toContain(
+ `재설정 (${resetAt})`,
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index 5700df7eec..5185c25f27 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -139,7 +139,7 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).toContain('getCodexWindowUsages(snapshot, t, nowMs)');
expect(source).toContain('todaySpend.codex.planCreditsLine');
expect(source).toContain('todaySpend.codex.windowLine');
- // chip 主体 label 统一为距 reset 的剩余时长倒计时 (Claude / Codex 同一函数),
+ // Codex chip 主体 label 为距 reset 的剩余时长倒计时,
// tooltip 保留窗口名 + 精确 reset 时间点
expect(source).toContain('function formatCompactTimeUntilReset(');
expect(source).toContain('function toCodexChipWindow(');
@@ -189,8 +189,9 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).toContain('todaySpend.claude.weeklyLabel');
expect(source).toContain('todaySpend.claude.windowLine');
expect(source).toContain('todaySpend.claude.resetAt');
- // chip 周限段: scoped 命中时倒计时前带模型名标注口径 (「Fable 7天 剩余 78%」)
- expect(source).toContain('weekly.modelDisplayName ? `${weekly.modelDisplayName} ${countdown}` : countdown');
+ expect(source).toContain('todaySpend.claude.resetInAt');
+ // 稳定窗口身份与完整 reset tooltip 的最终输出由 todaySpendChip.behavior.test.tsx
+ // 直接渲染组件验证;这里仅保留形态路由契约。
expect(source).toContain('todaySpend.claude.sessionValueLabel');
expect(source).toContain('todaySpend.claude.planLine');
// 告警判定是纯数据判定, 统一收在 shared/claudeSubscriptionUsage.ts (有直接单测:
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index de067e6473..500ec01625 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -235,8 +235,8 @@ function formatResetAt(epochSeconds: number | null | undefined): string | null {
/**
* chip 主体用的紧凑剩余时长(距 reset 还有多久): 单级精度 + 向上取整 ——
- * 「7天」/「3小时」/「45分钟」/「41秒」。Codex 与 Claude 订阅两种形态统一用它当窗口
- * label(所有限额窗口都算给用户);无数据 / 已过期 → null, 调用方回退窗口名。
+ * 「7天」/「3小时」/「45分钟」/「41秒」。Codex 订阅用它当窗口 label,
+ * Claude 订阅只在 tooltip 展示;主 chip 保留稳定窗口名。无数据 / 已过期 → null。
* 天级向上取整与 Codex 既有 getDaysUntilReset 口径一致(剩 6天10小时 → 7天)。
* 最后一分钟降到秒级, 配合秒级 tick(computeCountdownTickDelayMs)逐秒走动。
*/
@@ -271,7 +271,7 @@ function toEpochMs(epochSeconds: number | null | undefined): number | null {
}
/**
- * chip 上一个限额窗口段的素材: 倒计时 label + 数值化剩余百分比 + 窗口身份/reset
+ * chip 上一个限额窗口段的素材: 展示 label + 数值化剩余百分比 + 窗口身份/reset
* 时点(useQuotaResetRollup 检测重置并驱动 0% → 100% 滚动动画的输入)。
* Codex 订阅与 Claude 订阅两种形态共用, 成品字符串在组件里统一格式化。
*/
@@ -534,6 +534,8 @@ interface ClaudeWindowUsage {
label: string;
used: string;
remaining: string;
+ /** tooltip 用的相对 reset 倒计时;无数据 / 已过期 → null。 */
+ resetIn: string | null;
/** tooltip 用的精确 reset 时间点;无数据 → null。 */
resetAt: string | null;
}
@@ -541,6 +543,8 @@ interface ClaudeWindowUsage {
function toClaudeWindowUsage(
label: string,
window: ClaudeUsageWindow | null | undefined,
+ nowMs: number,
+ t: TFunction,
): ClaudeWindowUsage | null {
if (!window || typeof window.utilization !== 'number' || !Number.isFinite(window.utilization)) {
return null;
@@ -550,6 +554,7 @@ function toClaudeWindowUsage(
label,
used: formatPercent(usedPercent),
remaining: formatPercent(100 - usedPercent),
+ resetIn: formatCompactTimeUntilReset(window.resetsAt, nowMs, t),
resetAt: formatResetAt(window.resetsAt),
};
}
@@ -557,7 +562,7 @@ function toClaudeWindowUsage(
/**
* 当前会话生效的周限窗口: 命中当前模型的 weekly_scoped 条目优先 (label 带模型名,
* 如 "Fable 周限"), 否则回退总周限 —— 两种 label 口径可区分, 绝不臆造数字。
- * modelDisplayName 仅 scoped 命中时有, chip 倒计时 label 用它拼「Fable 7天」。
+ * modelDisplayName 仅 scoped 命中时有, 用于区分窗口身份。
*/
function resolveClaudeWeeklyWindow(
snapshot: ClaudeSubscriptionUsageSnapshot,
@@ -579,9 +584,9 @@ function resolveClaudeWeeklyWindow(
}
/**
- * chip 段素材 (方案 B + 倒计时 label): 窗口 label 直接用距 reset 的剩余时长 ——
- * 「3小时 剩余 45% · Fable 7天 剩余 78%」;scoped 命中时时长前带模型名标注口径。
- * 无 reset 数据回退窗口名 (5h / Fable 周限 / 周限), 绝不显示算不出的时间。
+ * chip 段素材 (方案 B): 保留稳定窗口身份 ——
+ * 「5h 剩余 45% · Fable 周限 剩余 78%」;reset 时间只放 tooltip,避免周限恰好
+ * 剩 5 小时时与 5h 窗口显示成两个同名「5h」。
* 剩余百分比留数值形态, 由组件经 useQuotaResetRollup(重置滚动动画)后再格式化。
*/
function getClaudeChipWindows(
@@ -594,11 +599,10 @@ function getClaudeChipWindows(
const windows: ChipWindowSegment[] = [];
const fiveHour = snapshot.fiveHour;
if (fiveHour && typeof fiveHour.utilization === 'number' && Number.isFinite(fiveHour.utilization)) {
- const countdown = formatCompactTimeUntilReset(fiveHour.resetsAt, nowMs, t);
const resetsAtMs = toEpochMs(fiveHour.resetsAt);
windows.push({
key: 'claude-5h',
- label: countdown ?? '5h',
+ label: '5h',
remainingPercent: 100 - clampPercent(fiveHour.utilization),
resetsAtMs,
resetPending: isResetPending(resetsAtMs, nowMs),
@@ -610,15 +614,11 @@ function getClaudeChipWindows(
&& typeof weekly.window.utilization === 'number'
&& Number.isFinite(weekly.window.utilization)
) {
- const countdown = formatCompactTimeUntilReset(weekly.window.resetsAt, nowMs, t);
- const label = countdown
- ? (weekly.modelDisplayName ? `${weekly.modelDisplayName} ${countdown}` : countdown)
- : weekly.label;
const resetsAtMs = toEpochMs(weekly.window.resetsAt);
windows.push({
// 身份 key 区分总周限与各 scoped 周限: 切模型导致窗口切换时只重置动画基线。
key: weekly.modelDisplayName ? `claude-weekly:${weekly.modelDisplayName}` : 'claude-weekly:total',
- label,
+ label: weekly.label,
remainingPercent: 100 - clampPercent(weekly.window.utilization),
resetsAtMs,
resetPending: isResetPending(resetsAtMs, nowMs),
@@ -638,6 +638,7 @@ function buildClaudeSubscriptionTooltipNode(
modelId: string | null | undefined,
sessionValueMoney: RegionalMoney | null,
t: TFunction,
+ nowMs: number,
usageDashboardLabel: string | null,
latestTurnUsage: LatestTurnUsageSummary | null,
): React.ReactNode {
@@ -660,16 +661,23 @@ function buildClaudeSubscriptionTooltipNode(
}
// 窗口明细: 5h → 总周限 → 全部分模型周限 (含非当前模型, 用户能看到谁先见底)。
- // tooltip 保留精确 reset 时间点 (chip 上是倒计时, 两层信息互补)。
+ // chip 保留稳定窗口名;tooltip 同时给相对倒计时和精确 reset 时间点。
const windows: ClaudeWindowUsage[] = [];
- const fiveHour = toClaudeWindowUsage('5h', snapshot.fiveHour);
+ const fiveHour = toClaudeWindowUsage('5h', snapshot.fiveHour, nowMs, t);
if (fiveHour) windows.push(fiveHour);
- const sevenDay = toClaudeWindowUsage(t('todaySpend.claude.weeklyLabel'), snapshot.sevenDay);
+ const sevenDay = toClaudeWindowUsage(
+ t('todaySpend.claude.weeklyLabel'),
+ snapshot.sevenDay,
+ nowMs,
+ t,
+ );
if (sevenDay) windows.push(sevenDay);
for (const scoped of snapshot.scoped ?? []) {
const usage = toClaudeWindowUsage(
t('todaySpend.claude.modelWeeklyLabel', { model: scoped.modelDisplayName }),
scoped,
+ nowMs,
+ t,
);
if (usage) windows.push(usage);
}
@@ -679,10 +687,16 @@ function buildClaudeSubscriptionTooltipNode(
remaining: window.remaining,
used: window.used,
});
- lines.push(window.resetAt
- ? `${base} · ${t('todaySpend.claude.resetAt', { at: window.resetAt })}`
- : base,
- );
+ let resetLabel: string | null = null;
+ if (window.resetAt && window.resetIn) {
+ resetLabel = t('todaySpend.claude.resetInAt', {
+ countdown: window.resetIn,
+ at: window.resetAt,
+ });
+ } else if (window.resetAt) {
+ resetLabel = t('todaySpend.claude.resetAt', { at: window.resetAt });
+ }
+ lines.push(resetLabel ? `${base} · ${resetLabel}` : base);
}
// tooltip 比 chip 宽一档: allowed_warning (服务端综合全部窗口的模糊信号) 也提示 ——
@@ -1183,9 +1197,9 @@ export function TodaySpendChip({
);
React.useEffect(() => {
- // 订阅形态 (codex-oauth / cc+chatgpt bridge / claude 订阅) 的 reset 倒计时文案
- // 需要随时间走动: 常态分钟级 tick 足够; 任一窗口进入最后一分钟切秒级 tick,
- // 让「59秒 → 1秒」逐秒跳动。setTimeout 链每次 tick 后按最新窗口重估下一次延迟。
+ // Codex 订阅的 reset 倒计时文案与全部订阅窗口的 resetPending 判定需要随时间走动:
+ // 常态分钟级 tick 足够;任一窗口进入最后一分钟切秒级 tick,让倒计时准确归零,
+ // Claude 稳定窗口名也能及时切到「重置中」。setTimeout 链每次 tick 后重估延迟。
if (!usesCodexQuotaForm && !isClaudeSubscription) return undefined;
const delay = computeCountdownTickDelayMs(chipResetsAtMsList, Date.now());
const timer = window.setTimeout(() => {
@@ -1288,8 +1302,8 @@ export function TodaySpendChip({
latestTurnUsage,
);
} else if (isClaudeSubscription) {
- // Claude 订阅形态 (方案 B): chip 显示「剩余时长 剩余%」倒计时段 + 本会话价值,
- // 倒计时由 windowLabelNowMs 驱动 (常态 60s tick, 最后一分钟逐秒); tooltip 保留精确时间。
+ // Claude 订阅形态 (方案 B): chip 显示稳定窗口名 + 剩余% + 本会话价值;
+ // tooltip 保留相对倒计时和精确 reset 时间。
const chipSegments = [...windowSegments];
if (sessionEstimatedValueMoney) {
chipSegments.push(t('todaySpend.claude.sessionValueLabel', {
@@ -1304,6 +1318,7 @@ export function TodaySpendChip({
modelId,
sessionEstimatedValueMoney,
t,
+ windowLabelNowMs,
usageDashboardLabel,
latestTurnUsage,
);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 70adae07ad..aa4e3fa11c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3109,6 +3109,7 @@
"modelWeeklyLabel": "{{model}} weekly",
"windowSegment": "{{label}} {{remaining}} left",
"resetAt": "resets {{at}}",
+ "resetInAt": "resets in {{countdown}} ({{at}})",
"windowLine": "{{label}} {{remaining}} left ({{used}} used)",
"sessionValueLabel": "Session value {{cost}}",
"planLine": "Plan {{plan}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 0d6df9b04a..e39cb264e3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3108,6 +3108,7 @@
"modelWeeklyLabel": "{{model}} 週間",
"windowSegment": "{{label}} 残り {{remaining}}",
"resetAt": "{{at}} にリセット",
+ "resetInAt": "{{countdown}}後にリセット({{at}})",
"windowLine": "{{label}} 残り {{remaining}} (使用済み {{used}})",
"sessionValueLabel": "このセッションの価値 {{cost}}",
"planLine": "プラン {{plan}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a069c9659b..e3df99b72b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3108,6 +3108,7 @@
"modelWeeklyLabel": "{{model}} 주간",
"windowSegment": "{{label}} {{remaining}} 남음",
"resetAt": "{{at}} 재설정",
+ "resetInAt": "{{countdown}} 후 재설정 ({{at}})",
"windowLine": "{{label}} 남음 {{remaining}} (사용 {{used}})",
"sessionValueLabel": "세션 가치 {{cost}}",
"planLine": "플랜 {{plan}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b5fcd56d10..e89bba3218 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3108,6 +3108,7 @@
"modelWeeklyLabel": "{{model}} 周限",
"windowSegment": "{{label}} 剩余 {{remaining}}",
"resetAt": "{{at}} 重置",
+ "resetInAt": "{{countdown}}后重置({{at}})",
"windowLine": "{{label}} 剩余 {{remaining}}(已用 {{used}})",
"sessionValueLabel": "本对话价值 {{cost}}",
"planLine": "套餐 {{plan}}",