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): show personal credit snapshot age (#6604)

guyong-zapoe3c582860d6a
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 95dd83ddb2..089e859dcd 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -1510,6 +1510,9 @@ export function TodaySpendChip({
if (usesGatewayQuota || isDeviceLinkRemoteGateway) {
account.title = t('quotaCard.gatewayTitle');
if (creditTotals) {
+ // Keep the retained balance's observation time; a render/refresh is not new data.
+ const observedAt = Date.parse(creditUsage?.observedAt ?? '');
+ if (Number.isFinite(observedAt)) account.updatedAt = observedAt;
account.windows.push({
key: 'balance',
title: t('quotaCard.balanceLabel'),
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
index 4f75371b2b..d28ff3220c 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
@@ -18,12 +18,14 @@ import type { ClaudeAccountUsageSnapshot } from '@/hooks/useClaudeAccountUsage';
import type { RegionalMoney } from '../../../../shared/regionalMoney';
import type { SessionUsageMoney } from '@/hooks/useSessionUsageMoney';
import type { ProviderView } from '@cindy/model-providers';
+import type { ModelAccessCreditUsage } from '../../../../shared/modelAccess';
const mocks = vi.hoisted(() => ({
claudeSnapshot: null as ClaudeSubscriptionUsageSnapshot | null,
codexSnapshot: null as RateLimitSnapshot | null,
xaiSnapshot: null as XaiSubscriptionUsageSnapshot | null,
gatewaySnapshot: null as ClaudeAccountUsageSnapshot | null,
+ creditSnapshot: null as ModelAccessCreditUsage | null,
sessionTokens: null as number | null,
codexAuthInjection: null as string | null,
providers: [] as ProviderView[],
@@ -48,6 +50,7 @@ vi.mock('react-i18next', () => ({
t: (key: string, options: Record<string, string | number> = {}) => {
const templates: Record<string, string> = {
'quotaCard.usageTitle': '用量明细',
+ 'quotaCard.staleData': '数据更新于 {{minutes}} 分钟前',
'todaySpend.openXaiUsage': '打开 Grok 用量页面',
'todaySpend.codex.sessionTokensLine': '本任务 Token {{tokens}}',
'quotaCard.speedLabel': '速度',
@@ -134,7 +137,9 @@ vi.mock('@/hooks/useAccountUsage', () => ({
vi.mock('@/hooks/useClaudeAccountUsage', () => ({
useClaudeAccountUsage: (enabled: boolean) => (enabled ? mocks.gatewaySnapshot : null),
}));
-vi.mock('@/hooks/useModelAccessCreditUsage', () => ({ useModelAccessCreditUsage: () => null }));
+vi.mock('@/hooks/useModelAccessCreditUsage', () => ({
+ useModelAccessCreditUsage: (enabled: boolean) => (enabled ? mocks.creditSnapshot : null),
+}));
vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({
requestClaudeSubscriptionRefresh: vi.fn(),
useClaudeSubscriptionUsage: () => mocks.claudeSnapshot,
@@ -262,6 +267,7 @@ beforeEach(() => {
mocks.consumeReset.mockReset();
mocks.xaiSnapshot = null;
mocks.gatewaySnapshot = null;
+ mocks.creditSnapshot = null;
mocks.sessionTokens = null;
mocks.codexAuthInjection = null;
mocks.providers = [];
@@ -279,6 +285,80 @@ afterEach(() => {
vi.clearAllMocks();
});
+// #4907: QuotaHoverCard tests cover the threshold, but the real chip never supplied
+// the personal balance observation time. Unit/jsdom: stale balance 60 is sufficient.
+describe('TodaySpendChip credit snapshot time', () => {
+ function creditSnapshot(observedAt: string): ModelAccessCreditUsage {
+ return {
+ available: '60',
+ plan: { remaining: '60', used: '40', total: '100' },
+ purchased: { remaining: '0', used: '0', total: '0' },
+ promotional: { remaining: '0', used: '0', total: '0' },
+ promotionalGrants: [],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'OBSERVED',
+ ledgerUpdatedAt: null,
+ scale: 9,
+ observedAt,
+ };
+ }
+
+ function gatewayChip() {
+ return <TodaySpendChip vendorKey="cc" providerId="xd" sessionId="session-1" />;
+ }
+
+ function openUsageCard() {
+ act(() => screen.getByRole('button', { name: '用量明细' }).focus());
+ return screen.getByTestId('quota-hover-card');
+ }
+
+ it('shows the retained balance observation time and clears it after a fresh snapshot', () => {
+ mocks.creditSnapshot = creditSnapshot(new Date(Date.now() - 10 * 60_000).toISOString());
+ const view = render(gatewayChip());
+ const card = openUsageCard();
+ expect(within(card).getByText('数据更新于 10 分钟前')).toBeTruthy();
+ const balance = within(card).getByRole('progressbar');
+ expect(balance.getAttribute('aria-valuenow')).toBe('60');
+ const balanceText = card.textContent;
+
+ mocks.creditSnapshot = { ...mocks.creditSnapshot, observedAt: new Date().toISOString() };
+ view.rerender(gatewayChip());
+ expect(within(card).queryByText(/数据更新于/)).toBeNull();
+ expect(card.textContent).toBe(balanceText?.replace('数据更新于 10 分钟前', ''));
+ });
+
+ it.each([null, '', 'invalid-time'])(
+ 'does not invent a snapshot time for missing or invalid observations (%s)',
+ (observedAt) => {
+ mocks.creditSnapshot = observedAt === null ? null : creditSnapshot(observedAt);
+ render(gatewayChip());
+ expect(within(openUsageCard()).queryByText(/数据更新于/)).toBeNull();
+ },
+ );
+
+ it('keeps the enterprise quota fetchedAt when a credit snapshot is also present', () => {
+ mocks.creditSnapshot = creditSnapshot(new Date(Date.now() - 10 * 60_000).toISOString());
+ mocks.gatewaySnapshot = {
+ spend: 40, maxBudget: 100, currency: 'CNY', todaySpend: 3,
+ fetchedAt: Date.now() - 20 * 60_000,
+ };
+ render(gatewayChip());
+ expect(within(openUsageCard()).getByText('数据更新于 20 分钟前')).toBeTruthy();
+ });
+
+ it.each([
+ { providerId: 'custom-api' },
+ { providerId: 'xd', remoteHostId: 'ssh-host' },
+ { providerId: 'xd', deviceLinkDeviceId: 'remote-device' },
+ ])('does not borrow local balance or observation time for %j', (route) => {
+ mocks.creditSnapshot = creditSnapshot(new Date(Date.now() - 10 * 60_000).toISOString());
+ render(<TodaySpendChip vendorKey="cc" sessionId="session-1" {...route} />);
+ const card = openUsageCard();
+ expect(within(card).queryByRole('progressbar')).toBeNull();
+ expect(within(card).queryByText(/数据更新于/)).toBeNull();
+ });
+});
+
describe('TodaySpendChip Claude subscription popover', () => {
it.each(['accountId', 'source', 'limitId'] as const)(
'does not celebrate a Codex %s switch as a reset',