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): respect organization daily limit visibility

fmfsaisaibdf1fcebb9ec
diff --git a/apps/desktop/scripts/fixtures/organization-quota/quota-fixture.tsx b/apps/desktop/scripts/fixtures/organization-quota/quota-fixture.tsx
new file mode 100644
index 0000000000..202ff117ad
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/organization-quota/quota-fixture.tsx
@@ -0,0 +1,20 @@
+import { mountPage, subscription } from '../../ui-page/harness';
+import { TodaySpendChip } from '../../../src/renderer/components/status/TodaySpendChip';
+
+void mountPage({
+ host: (ctx) => ({
+ maker: { usage: {
+ getAccount: async () => ({
+ spend: 3, maxBudget: 30, currency: 'USD', fetchedAt: Date.now(),
+ todaySpend: ctx.data.todaySpend,
+ ...(ctx.data.dailyLimitEnabled === undefined ? {} : { dailyLimitEnabled: ctx.data.dailyLimitEnabled }),
+ }),
+ onClaudeAccountChanged: subscription('quota'),
+ } },
+ }),
+ render: () => (
+ <main className="flex h-full items-end justify-end p-8">
+ <TodaySpendChip vendorKey="cc" providerId="xd" />
+ </main>
+ ),
+});
diff --git a/apps/desktop/scripts/fixtures/organization-quota/ui-page.mjs b/apps/desktop/scripts/fixtures/organization-quota/ui-page.mjs
new file mode 100644
index 0000000000..c9b44de6e1
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/organization-quota/ui-page.mjs
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict';
+
+export default {
+ name: 'organization-quota',
+ entry: './quota-fixture.tsx',
+ viewport: { width: 560, height: 440 },
+ real: 'TodaySpendChip, QuotaHoverCard, useClaudeAccountUsage, translations and themes',
+ notCovered: 'Server reads, menu bar, device-link transport, subscription providers and the unmounted home dashboard',
+ stubs: {
+ 'src/renderer/contexts/AuthContext': 'export const useAuth = () => ({ dataOwnerId: "fixture", dataOwnerGeneration: 1, mode: "cloud", user: { membershipKind: "org" } });',
+ 'src/renderer/hooks/useApiKey': 'export const useApiKey = () => ({ hasSavedKey: true, isReconciling: false });',
+ 'src/renderer/hooks/useProviders': 'export const useProviders = () => ({ providers: [] });',
+ 'src/renderer/hooks/useDeviceProviders': 'export const useDeviceProviders = () => ({ providers: [] });',
+ 'src/renderer/hooks/useClaudeOAuthConnected': 'export const useClaudeOAuthConnected = () => false;',
+ 'src/renderer/hooks/useClaudeSessionRoute': 'export const useClaudeSessionRoute = () => null;',
+ 'src/renderer/hooks/useSessionUsageMoney': 'export const useSessionUsageMoney = () => ({ actualMoney: null, estimatedValueMoney: null, totalMoney: null });',
+ 'src/renderer/hooks/useSessionTokens': 'export const useSessionTokens = () => null;',
+ 'src/renderer/hooks/useAccountUsage': 'export const useAccountUsage = () => null; export const requestCodexAccountRefresh = () => {};',
+ 'src/renderer/hooks/useModelAccessCreditUsage': 'export const useModelAccessCreditUsage = () => null;',
+ 'src/renderer/hooks/useClaudeSubscriptionUsage': 'export const useClaudeSubscriptionUsage = () => null; export const requestClaudeSubscriptionRefresh = () => {};',
+ 'src/renderer/hooks/useCodexRuntimeRoute': 'export const useCodexRuntimeRoute = () => ({ authInjection: null });',
+ 'src/renderer/hooks/useCodexRateLimits': 'export const useCodexRateLimits = () => ({ snapshot: null, refresh: () => {} });',
+ 'src/renderer/hooks/useRemoteDeviceUsage': 'export const useRemoteClaudeAccountUsage = () => null; export const useRemoteCodexAccountUsage = () => null; export const useRemoteXaiSubscriptionUsage = () => null; export const useRemoteXaiRateLimit = () => null; export const selectRemoteCodexAccountUsage = () => null; export const requestRemoteCodexAccountRefresh = () => {}; export const requestRemoteXaiSubscriptionRefresh = () => {};',
+ 'src/renderer/hooks/useRemoteClaudeSubscriptionUsage': 'export const useRemoteClaudeSubscriptionUsage = () => null; export const requestRemoteClaudeSubscriptionRefresh = () => {};',
+ 'src/renderer/hooks/useRemoteClaudeSessionRoute': 'export const useRemoteClaudeSessionRoute = () => null;',
+ 'src/renderer/hooks/useXaiSubscriptionUsage': 'export const useXaiSubscriptionUsage = () => null; export const requestXaiSubscriptionRefresh = () => {};',
+ 'src/renderer/hooks/useXaiRateLimit': 'export const useXaiRateLimit = () => null;',
+ 'src/renderer/components/chat/ChatDisplaySnapshotContext': 'export const useChatDisplaySnapshot = () => null;',
+ 'src/renderer/lib/makerChatStore': 'export const makerChatStore = { getSnapshot: () => ({ messages: [] }), subscribe: () => () => {} };',
+ },
+ cases: {
+ default: { about: 'Daily limit enabled with a valid spend', data: { dailyLimitEnabled: true, todaySpend: 3 } },
+ unavailable: { about: 'Daily limit enabled but daily spend unavailable', data: { dailyLimitEnabled: true, todaySpend: null } },
+ disabled: { about: 'Daily limit disabled: monthly quota without a warning', data: { dailyLimitEnabled: false, todaySpend: null } },
+ legacy: { about: 'Legacy gateway snapshot without the optional flag', data: { todaySpend: 3 } },
+ },
+ async ready(page) {
+ const trigger = page.getByRole('button', { name: /./ });
+ await trigger.waitFor();
+ await trigger.focus();
+ await page.getByTestId('quota-hover-card').getByRole('progressbar').first().waitFor();
+ },
+ async check(page, ui) {
+ const card = page.getByTestId('quota-hover-card');
+ assert.equal(await card.getByText(await ui.t('quotaCard.monthlyLabel'), { exact: true }).count(), 1);
+ assert.equal(await card.getByText(await ui.t('quotaCard.dailyLabel'), { exact: true }).count(), ['default', 'legacy'].includes(ui.case) ? 1 : 0);
+ assert.equal(await card.getByText(await ui.t('todaySpend.tooltip.dailyUnavailable'), { exact: true }).count(), ui.case === 'unavailable' ? 1 : 0);
+ },
+};
diff --git a/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts b/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts
index 60bfa2702b..8cf63ad904 100644
--- a/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts
+++ b/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts
@@ -103,17 +103,21 @@ describe('buildMenubarView', () => {
expect(view.sources[0].fill).toBeCloseTo(0.6);
});
- it('shows an organization quota with its reset and sends it to Settings', () => {
+ // Unit: the public view builder must keep monthly quota while hiding disabled
+ // daily limits; undefined is the pre-switch gateway contract.
+ it.each([true, false, undefined])('shows quota details for dailyLimitEnabled=%s', (dailyLimitEnabled) => {
const quota: MenubarSourceInput = {
kind: 'balance', id: 'cindy', logoSvg: MENUBAR_CINDY_LOGO, available: 19_996.38, fullAmount: 20_000,
- burnPerDay: null, observedAtMs: NOW, currency: 'USD', quota: { resetsAtMs: NOW + 20 * DAY + 3 * HOUR, todaySpend: 3.62 },
+ burnPerDay: null, observedAtMs: NOW, currency: 'USD', quota: { resetsAtMs: NOW + 20 * DAY + 3 * HOUR, todaySpend: 3.62, dailyLimitEnabled },
};
const view = buildMenubarView(input([quota], { locale: 'zh-CN' }));
expect(view.sources[0]).toMatchObject({ when: '20天3时后重置' });
expect(view.sources[0].fill).toBeCloseTo(0.9998);
expect(view.headlinePrimary).toBe('Cindy 本期配额还能用。');
expect(view.details.cindy).toMatchObject({ title: 'Cindy 本期配额', action: { kind: 'open-settings' } });
- expect(view.details.cindy.facts).toContainEqual({ label: '今日已用', value: '$3.62', sub: '每日建议 $3,000 以内' });
+ const dailyFact = view.details.cindy.facts.find(fact => fact.label === '今日已用');
+ if (dailyLimitEnabled === false) expect(dailyFact).toBeUndefined();
+ else expect(dailyFact).toEqual({ label: '今日已用', value: '$3.62', sub: '每日建议 $3,000 以内' });
});
it('splits a wallet into its pools and names the gift that expires first', () => {
diff --git a/apps/desktop/src/main/menubar/service.ts b/apps/desktop/src/main/menubar/service.ts
index eefcacaf81..fbba18cf19 100644
--- a/apps/desktop/src/main/menubar/service.ts
+++ b/apps/desktop/src/main/menubar/service.ts
@@ -560,6 +560,7 @@ export class MenubarService {
quota: {
resetsAtMs: Number.isFinite(resetsAtMs) ? resetsAtMs : null,
todaySpend: Number.isFinite(quota.todaySpend) ? quota.todaySpend : null,
+ dailyLimitEnabled: quota.dailyLimitEnabled,
},
};
}
diff --git a/apps/desktop/src/main/menubar/snapshot.ts b/apps/desktop/src/main/menubar/snapshot.ts
index 7bd887c55f..3419b866a7 100644
--- a/apps/desktop/src/main/menubar/snapshot.ts
+++ b/apps/desktop/src/main/menubar/snapshot.ts
@@ -117,6 +117,8 @@ export interface MenubarQuotaPeriod {
resetsAtMs: number | null;
/** Spent today (UTC day) across every client; null when the gateway did not say. */
todaySpend: number | null;
+ /** Undefined preserves the legacy gateway's daily display. */
+ dailyLimitEnabled?: boolean;
}
export interface MenubarPaygInput {
@@ -712,7 +714,7 @@ class Builder {
: this.t('fact.cindyModels'),
},
);
- if (quota.todaySpend !== null) {
+ if (quota.dailyLimitEnabled !== false && quota.todaySpend !== null) {
const suggested = source.fullAmount ? (source.fullAmount / 30) * DAILY_SOFT_LIMIT_FACTOR : null;
facts.push({
label: this.t('fact.todaySpent'),
diff --git a/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts
index 2f161644f7..f60d8a9aff 100644
--- a/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts
@@ -150,5 +150,11 @@ describe('claudeAccountUsage Cindy AI key rejection', () => {
expect(mocks.outboundFetch).toHaveBeenCalledTimes(2);
expect(mocks.report).not.toHaveBeenCalled();
+ // Unit compatibility: the legacy reader keeps daily data without opting in
+ // to the enterprise switch (missing switch must not disable this path).
+ expect(usage.readClaudeAccountUsageSnapshot()).toEqual({
+ spend: 1, maxBudget: 10, currency: 'USD', budgetResetAt: null,
+ todaySpend: 0, fetchedAt: expect.any(Number),
+ });
});
});
diff --git a/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts b/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts
index b2e1d573e1..91682aa3b2 100644
--- a/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts
@@ -8,22 +8,28 @@ const valid = { spend: 12, maxBudget: 100, currency: 'CNY', budgetResetAt: '2026
beforeEach(() => { fetch.mockReset().mockResolvedValue(valid); });
describe('organization account usage', () => {
it('uses authenticated Model Access and preserves the gateway currency', async () => {
- expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend: null });
+ expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend: null, dailyLimitEnabled: false });
expect(fetch).toHaveBeenCalledWith('/api/model-access/quota', expect.objectContaining({ redactErrorDetails: true, timeoutMs: 8000 }));
});
// Unit regression: the public reader discarded the server's daily spend. Existing
// coverage only used null; todaySpend: 0 is the smallest input exposing the bug.
// Missing/invalid daily data must preserve the monthly quota without inventing zero.
it.each([1.25, 0])('preserves a valid daily spend of %s', async todaySpend => {
- fetch.mockResolvedValue({ ...valid, todaySpend });
- expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend });
+ fetch.mockResolvedValue({ ...valid, todaySpend, dailyLimitEnabled: true });
+ expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend, dailyLimitEnabled: true });
});
it.each([undefined, null, -1, NaN, Infinity, -Infinity, '1.25', false, {}])(
'keeps the monthly quota when daily spend is %s', async todaySpend => {
- fetch.mockResolvedValue({ ...valid, todaySpend });
- expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend: null });
+ fetch.mockResolvedValue({ ...valid, todaySpend, dailyLimitEnabled: true });
+ expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend: null, dailyLimitEnabled: true });
},
);
+ // Unit: only an explicit true enables enterprise daily limits. A numeric spend
+ // with a missing switch previously exposed a limit that the organization never enabled.
+ it.each([false, null, undefined, 'true', 1, {}])('disables daily limits for switch %s', async dailyLimitEnabled => {
+ fetch.mockResolvedValue({ ...valid, todaySpend: 1.25, dailyLimitEnabled });
+ expect(await readOrganizationAccountUsage()).toMatchObject({ ...valid, todaySpend: null, dailyLimitEnabled: false });
+ });
it.each([[404, 'NOT_FOUND'], [501, 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED']])('allows legacy fallback only for an unavailable capability', async (status, code) => {
fetch.mockRejectedValue(new ServerApiError(code, status, 'safe'));
expect(await readOrganizationAccountUsage()).toBeUndefined();
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index cb5ebcdb5c..efcfff05c3 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -80,6 +80,8 @@ export interface ClaudeAccountUsageSnapshot {
* 任一可能失败); chip 的 daily 段会因此变 unavailable。
*/
todaySpend: number | null;
+ /** 企业日额度开关;false 隐藏日额度和读取失败提示,旧网关路径不设置。 */
+ dailyLimitEnabled?: boolean;
/** 拉取时戳 (Date.now)。 */
fetchedAt: number;
}
diff --git a/apps/desktop/src/main/usage/organizationAccountUsage.ts b/apps/desktop/src/main/usage/organizationAccountUsage.ts
index 1d305f91c3..43ac4318f9 100644
--- a/apps/desktop/src/main/usage/organizationAccountUsage.ts
+++ b/apps/desktop/src/main/usage/organizationAccountUsage.ts
@@ -17,10 +17,11 @@ export async function readOrganizationAccountUsage(): Promise<ClaudeAccountUsage
(row.currency !== 'CNY' && row.currency !== 'USD') ||
(row.budgetResetAt !== null && (typeof row.budgetResetAt !== 'string' || !Number.isFinite(Date.parse(row.budgetResetAt))))) return null;
if (row.maxBudget === null) return 'unlimited';
- const todaySpend = typeof row.todaySpend === 'number' && Number.isFinite(row.todaySpend) && row.todaySpend >= 0
+ const dailyLimitEnabled = row.dailyLimitEnabled === true;
+ const todaySpend = dailyLimitEnabled && typeof row.todaySpend === 'number' && Number.isFinite(row.todaySpend) && row.todaySpend >= 0
? row.todaySpend : null;
return { spend: row.spend, maxBudget: row.maxBudget, currency: row.currency,
- budgetResetAt: row.budgetResetAt, todaySpend, fetchedAt: Date.now() };
+ budgetResetAt: row.budgetResetAt, todaySpend, dailyLimitEnabled, fetchedAt: Date.now() };
} catch (error) {
if (error instanceof ServerApiError && (error.statusCode === 404 ||
(error.statusCode === 501 && error.code === 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED'))) return undefined;
diff --git a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
index dba5910cd7..f2513bc993 100644
--- a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
@@ -65,14 +65,17 @@ it('settles failed credit loading, retries, and ignores the previous account’s
expect(view.result.current.usage?.available).toBe('2');
});
-it('uses the enterprise quota API and never returns personal credit for an organization', async () => {
- state.owner = 'quota-org';
+// Unit: the real quota hook must preserve the optional switch through IPC reads;
+// previous coverage had only snapshots without the switch.
+it.each([true, false, undefined])('preserves enterprise dailyLimitEnabled=%s without personal credit', async (dailyLimitEnabled) => {
+ state.owner = `quota-org-${dailyLimitEnabled}`;
state.membership = 'org';
state.quota.mockResolvedValue({
spend: 12,
maxBudget: 100,
currency: 'USD',
todaySpend: 1,
+ ...(dailyLimitEnabled === undefined ? {} : { dailyLimitEnabled }),
fetchedAt: 1,
});
const view = renderHook(() => ({
@@ -80,6 +83,7 @@ it('uses the enterprise quota API and never returns personal credit for an organ
credit: useModelAccessCreditUsageResult(true),
}));
await waitFor(() => expect(view.result.current.quota.usage?.currency).toBe('USD'));
+ expect(view.result.current.quota.usage?.dailyLimitEnabled).toBe(dailyLimitEnabled);
expect(view.result.current.credit.usage).toBeNull();
expect(state.credit).not.toHaveBeenCalled();
act(() => view.result.current.quota.refresh());
diff --git a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
index 63718be247..c6a87b6183 100644
--- a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
@@ -383,6 +383,19 @@ describe('remote account parity', () => {
});
});
+// Unit: the remote mirror must retain the daily-limit switch on reads and pushes,
+// including a switch-off update without dropping the monthly quota.
+it('mirrors enterprise daily-limit changes through device-link', async () => {
+ const quota = { spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: 1, fetchedAt: 1, dailyLimitEnabled: true };
+ mocks.invoke.mockResolvedValue(quota);
+ const view = renderHook(() => useRemoteClaudeAccountUsage('daily-switch'));
+ await flushMicrotasks();
+ expect(view.result.current).toEqual(quota);
+ const disabled = { ...quota, todaySpend: null, dailyLimitEnabled: false };
+ act(() => emitPush({ deviceId: 'daily-switch', channel: 'usage:claude-account-changed', payload: disabled }));
+ expect(view.result.current).toEqual(disabled);
+});
+
it.each(['unlimited', 'invalidated'])('retains remote quota on unavailable reads but replays a missed %s clear', async (quotaState) => {
const quota = { spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 };
mocks.invoke.mockResolvedValue(quota);
diff --git a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
index 57bc6c3229..c4d29e448c 100644
--- a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
@@ -187,7 +187,7 @@ export function HomeUsageDashboard(): React.JSX.Element {
}, []);
const accountTodayMoney =
- typeof claudeQuota?.todaySpend === 'number'
+ claudeQuota?.dailyLimitEnabled !== false && typeof claudeQuota?.todaySpend === 'number'
? gatewayMoney(claudeQuota.todaySpend, claudeQuota.currency)
: null;
const hasAccountTodaySpend = accountTodayMoney !== null;
@@ -197,7 +197,8 @@ export function HomeUsageDashboard(): React.JSX.Element {
const showLocalSpendAnomaly =
layoutHistory.anomaly.isAnomalous &&
isSameDisplayedTodaySpend(accountTodayMoney, layoutHistory.totals.today);
- const softDailyLimit = hasMonthly ? (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR : null;
+ const softDailyLimit = hasMonthly && claudeQuota.dailyLimitEnabled !== false
+ ? (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR : null;
const softDailyLimitMoney =
softDailyLimit === null || claudeQuota === null
? null
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 089e859dcd..850bc625a1 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -225,7 +225,7 @@ function computeMetricSlots(
}),
available: true,
};
- if (typeof claudeQuota.todaySpend === 'number') {
+ if (claudeQuota.dailyLimitEnabled !== false && typeof claudeQuota.todaySpend === 'number') {
const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;
slots.daily = {
label: t('todaySpend.dailyLimitLabel', {
@@ -1524,7 +1524,7 @@ export function TodaySpendChip({
});
}
if (claudeQuota && claudeQuota.maxBudget > 0) {
- if (typeof claudeQuota.todaySpend === 'number') {
+ if (claudeQuota.dailyLimitEnabled !== false && typeof claudeQuota.todaySpend === 'number') {
const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;
account.windows.push({
key: 'daily',
@@ -1548,7 +1548,7 @@ export function TodaySpendChip({
}
if (!claudeQuota && !creditTotals) {
account.emptyText = t('todaySpend.tooltip.monthlyUnavailable');
- } else if (claudeQuota?.todaySpend === null) {
+ } else if (claudeQuota?.dailyLimitEnabled !== false && claudeQuota?.todaySpend === null) {
account.details = [t('todaySpend.tooltip.dailyUnavailable')];
}
}
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 d28ff3220c..9823b58a8f 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
@@ -312,6 +312,28 @@ describe('TodaySpendChip credit snapshot time', () => {
return screen.getByTestId('quota-hover-card');
}
+ // Unit regression: the rendered chip and card must distinguish a disabled
+ // enterprise daily limit from a failed daily read; omitted flags retain legacy behavior.
+ it.each([
+ { dailyLimitEnabled: true, todaySpend: 3, daily: true, warning: false },
+ { dailyLimitEnabled: true, todaySpend: null, daily: false, warning: true },
+ { dailyLimitEnabled: false, todaySpend: null, daily: false, warning: false },
+ { dailyLimitEnabled: false, todaySpend: 3, daily: false, warning: false },
+ { dailyLimitEnabled: undefined, todaySpend: 3, daily: true, warning: false },
+ { dailyLimitEnabled: undefined, todaySpend: null, daily: false, warning: true },
+ ])('respects the daily limit state %j', ({ dailyLimitEnabled, todaySpend, daily, warning }) => {
+ mocks.gatewaySnapshot = {
+ spend: 40, maxBudget: 100, currency: 'CNY', fetchedAt: Date.now(),
+ todaySpend, ...(dailyLimitEnabled === undefined ? {} : { dailyLimitEnabled }),
+ };
+ render(gatewayChip());
+ expect(screen.getByRole('button', { name: '用量明细' }).textContent?.includes('todaySpend.dailyLimitLabel')).toBe(daily);
+ const card = openUsageCard();
+ expect(Boolean(within(card).queryByText('quotaCard.dailyLabel'))).toBe(daily);
+ expect(Boolean(within(card).queryByText('todaySpend.tooltip.dailyUnavailable'))).toBe(warning);
+ expect(within(card).getByText('quotaCard.monthlyLabel')).toBeTruthy();
+ });
+
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());
diff --git a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
index fcf7da8262..637b615431 100644
--- a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
@@ -47,6 +47,8 @@ export interface ClaudeAccountUsageSnapshot {
* 此时消费方应隐藏 daily 段。
*/
todaySpend: number | null;
+ /** 企业日额度开关;false 隐藏日额度和读取失败提示,旧网关路径不设置。 */
+ dailyLimitEnabled?: boolean;
fetchedAt: number;
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index d80175a6a1..fb15f5b2fa 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2854,15 +2854,19 @@ Claude 原生 `user` 范围投影为 `global`;控制端读取早期 Host 的 `
沿用现有 account-usage IPC 和账号作用域缓存,所以设置卡片与任务用量提示使用相同来源。
服务端尚未提供接口(404),或明确返回 501/MODEL_ACCESS_QUOTA_NOT_SUPPORTED(Nova),
才使用原有网关查询。鉴权失败、上游故障或响应无效均显示不可用,不回退或借用其他身份数据。
-`todaySpend` 为有限且 ≥ 0 的数字时,表示 UTC 当天的消费;缺失、`null` 或非法值均按
-`null` 处理,表示拿不到今日消费,不影响其余额度字段。旧版服务端不返回该字段或固定返回
-`null` 时,客户端照常显示月额度,只是不显示今日消费。未设周期上限时不伪造有限配额的
-原有行为保持不变。
+`dailyLimitEnabled` 只有严格等于 `true` 才表示企业开启日额度;`false`、`null`、缺失或
+非法值均视为未开启。企业快照明确带出布尔值,未开启时 `todaySpend` 按 `null` 处理,
+隐藏日额度、软限额口径和今日明细不可用警告,月额度不受影响。旧服务端缺少开关字段时
+也按未开启处理。开启时,`todaySpend` 为有限且 ≥ 0 的数字表示 UTC 当天消费;缺失、
+`null` 或非法值按 `null` 处理,只显示今日明细不可用提示,不影响其余额度字段。
+快照新增可选 `dailyLimitEnabled?: boolean`,沿既有 IPC 和 device-link 原样传递;非企业
+旧网关路径不设置此字段,保留原有日额度及不可用提示行为。旧控制端忽略新增字段,
+需更新控制端才能隐藏未开启时的警告。未设周期上限时不伪造有限配额的原有行为保持不变。
本地手填网关和个人计费路径保持原协议。无新环境变量或数据库变更。
管理员取消周期上限后,主进程明确清空当前 owner 的配额缓存,并通过现有
`usage:claude-account-changed` 广播 null;renderer 同步清除当前 owner 的快照与热缓存。
-已有未知载荷消费者会忽略 null,新旧有限配额快照字段不变;网络失败仍保留既有缓存策略。
+已有未知载荷消费者会忽略 null,其余有限配额快照字段不变;网络失败仍保留既有缓存策略。
配额读取 IPC 返回 null 仅表示当前无可用快照,不清除 renderer 已缓存的同账号额度;只有权威 clear 读取结果或显式 clear push 才清除缓存。