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): 修复 Cindy AI 不限额误显示为获取失败 (#6413)

此间少年e0f2668c5d20
diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
index 0390838784..81e9d7df2c 100644
--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
@@ -111,7 +111,9 @@ export function registerMakerUsageHandlers(
if (kind === 'claude-code') {
// Both first load and explicit refresh must reach the existing owner-scoped fetcher.
// Cached reads retain its throttle; an empty cache gets the existing warm-start path.
- await deps.triggerClaudeAccountUsageRefresh(deps.readClaudeAccountUsageSnapshot() === null);
+ await deps.triggerClaudeAccountUsageRefresh(
+ deps.readClaudeAccountUsageSnapshot() === null && deps.readClaudeAccountQuotaClear?.()?.quotaState !== 'unlimited',
+ );
return deps.readClaudeAccountUsageSnapshot()
?? (providerId === CLAUDE_QUOTA_STATE_READ ? deps.readClaudeAccountQuotaClear?.() ?? null : null);
}
diff --git a/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts
index d8d8ed54f7..2f161644f7 100644
--- a/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/claudeAccountUsageKeyRejection.test.ts
@@ -7,10 +7,12 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vite
const mocks = vi.hoisted(() => ({
outboundFetch: vi.fn(),
report: vi.fn(),
+ readOrganization: vi.fn(),
+ windows: [] as Array<{ isDestroyed: () => boolean; webContents: { send: (...args: unknown[]) => void } }>,
}));
vi.mock('electron', () => ({
- BrowserWindow: { getAllWindows: () => [] },
+ BrowserWindow: { getAllWindows: () => mocks.windows },
}));
vi.mock('../../authManager', () => ({
getAuthState: () => ({
@@ -38,7 +40,7 @@ vi.mock('../../model-access/gatewayKeyRejection', () => ({
}));
// This suite exercises the explicit old-server / Nova compatibility path.
-vi.mock('../organizationAccountUsage.js', () => ({ readOrganizationAccountUsage: async () => undefined }));
+vi.mock('../organizationAccountUsage.js', () => ({ readOrganizationAccountUsage: mocks.readOrganization }));
let usage: typeof import('../claudeAccountUsage');
let credentials: typeof import('../../model-access/quotaCredentialState');
@@ -58,12 +60,49 @@ describe('claudeAccountUsage Cindy AI key rejection', () => {
vi.useFakeTimers();
mocks.outboundFetch.mockReset();
mocks.report.mockReset();
+ mocks.readOrganization.mockReset().mockResolvedValue(undefined);
+ mocks.windows = [];
credentials.__resetQuotaCredentialStateForTesting('cloud:user-1:1', {
state: 'ok', source: 'server', endpoint: 'https://gateway.test.invalid', accountTier: null,
});
});
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+ it('shares the main-process quota read across primary and secondary window IPC senders', async () => {
+ const { registerMakerUsageHandlers } = await import('../../maker-ipc/usageHandlers');
+ const { IpcHarness } = await import('../../maker-ipc/__tests__/helpers/ipcHarness');
+ const { MAKER_INVOKE } = await import('../../maker-ipc/channels');
+ const harness = new IpcHarness();
+ registerMakerUsageHandlers(harness, {
+ readClaudeAccountUsageSnapshot: usage.readClaudeAccountUsageSnapshot,
+ readClaudeAccountQuotaClear: usage.readClaudeAccountQuotaClear,
+ triggerClaudeAccountUsageRefresh: usage.triggerClaudeAccountUsageRefresh,
+ } as Parameters<typeof registerMakerUsageHandlers>[1]);
+ const read = (sender: number) => harness.invokeFrom(sender, MAKER_INVOKE.USAGE_ACCOUNT, 'claude-code', 'cindy-quota-state-v1');
+ const confirmations: Promise<unknown>[] = [];
+ const sends = [1, 2].map(sender => vi.fn(() => { confirmations.push(read(sender)); }));
+ mocks.windows = sends.map(send => ({ isDestroyed: () => false, webContents: { send } }));
+ let complete!: (value: 'unlimited') => void;
+ mocks.readOrganization.mockImplementation(() => new Promise(resolve => { complete = resolve; }));
+ const first = read(1);
+ const second = read(2);
+ let secondFinished = false;
+ void second.then(() => { secondFinished = true; });
+ await Promise.resolve(); await Promise.resolve();
+ expect(mocks.readOrganization).toHaveBeenCalledTimes(1);
+ expect(secondFinished).toBe(false);
+ complete('unlimited');
+ expect(await Promise.all([first, second])).toEqual([{ quotaState: 'unlimited' }, { quotaState: 'unlimited' }]);
+ await Promise.all(confirmations);
+ expect(mocks.readOrganization).toHaveBeenCalledTimes(1);
+ for (const send of sends) expect(send).toHaveBeenCalledTimes(1);
+ mocks.readOrganization.mockResolvedValue('unlimited');
+ await vi.advanceTimersByTimeAsync(11_000);
+ await read(2);
+ expect(mocks.readOrganization).toHaveBeenCalledTimes(2);
+ for (const send of sends) expect(send).toHaveBeenCalledTimes(1);
+ });
+
it('reports the sent key when user/info and daily/activity are rejected with 401', async () => {
mocks.outboundFetch.mockImplementation(async () => jsonResponse({ error: 'invalid key' }, 401));
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 22a8c1e7cc..cb5ebcdb5c 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -98,6 +98,7 @@ let snapshot: ClaudeAccountUsageSnapshot | null = null;
let snapshotOwnerKey: string | null = null;
let clearReason: ClaudeQuotaClear['quotaState'] = 'unlimited';
let fetchInFlight = false;
+let fetchPromise: Promise<void> | null = null;
let fetchOwnerKey: string | null = null;
let refreshQueued = false;
let lastFetchAt = 0;
@@ -112,6 +113,7 @@ export function __resetClaudeAccountUsageForTesting(): void {
snapshotOwnerKey = null;
clearReason = 'unlimited';
fetchInFlight = false;
+ fetchPromise = null;
fetchOwnerKey = null;
refreshQueued = false;
lastFetchAt = 0;
@@ -281,7 +283,7 @@ async function fetchOnce(authenticatedUserId?: string): Promise<ClaudeAccountUsa
/**
* 触发一次 Claude 账号配额刷新 (background)。
- * - in-flight 去重: 已有进行中直接跳过
+ * - in-flight 去重: 已有同账号读取时等待共享结果
* - 节流: 距上次拉取 < 10s 跳过 (force=true 跳过节流, warm-start 用)
* - 拉到新数据后写 in-memory snapshot + broadcast
* - 首次成功 fetch 后启动空闲轮询定时器 (5 分钟周期, 保活 dailyBaselineStore.lastSeenSpend)
@@ -291,6 +293,7 @@ export async function triggerClaudeAccountUsageRefresh(force = false): Promise<v
if (!owner) return;
if (fetchInFlight) {
if (fetchOwnerKey !== owner.key) refreshQueued = true;
+ await fetchPromise;
return;
}
if (!force && lastFetchOwnerKey === owner.key && Date.now() - lastFetchAt < THROTTLE_MS) return;
@@ -299,33 +302,42 @@ export async function triggerClaudeAccountUsageRefresh(force = false): Promise<v
fetchOwnerKey = owner.key;
lastFetchAt = Date.now();
lastFetchOwnerKey = owner.key;
- try {
- if (owner.key.startsWith('cloud:')) refreshQuotaCredentialOwner(owner.key);
- const generation = quotaCredentialGeneration();
- const next = await fetchOnce(owner.authenticatedUserId);
- if (getAuthState().mode === 'cloud' && quotaCredentialGeneration() !== generation) return;
- if (currentQuotaOwner()?.key !== owner.key) return;
- if (next === 'unlimited') {
- clearReason = 'unlimited';
- snapshot = null;
+ let resolveFetch!: () => void;
+ let rejectFetch!: (error: unknown) => void;
+ const pending = new Promise<void>((resolve, reject) => { resolveFetch = resolve; rejectFetch = reject; });
+ fetchPromise = pending;
+ void (async () => {
+ try {
+ if (owner.key.startsWith('cloud:')) refreshQuotaCredentialOwner(owner.key);
+ const generation = quotaCredentialGeneration();
+ const next = await fetchOnce(owner.authenticatedUserId);
+ if (getAuthState().mode === 'cloud' && quotaCredentialGeneration() !== generation) return;
+ if (currentQuotaOwner()?.key !== owner.key) return;
+ if (next === 'unlimited') {
+ const changed = snapshotOwnerKey !== owner.key || snapshot !== null || clearReason !== 'unlimited';
+ clearReason = 'unlimited';
+ snapshot = null;
+ snapshotOwnerKey = owner.key;
+ if (changed) broadcast(null);
+ ensureIdlePoll();
+ return;
+ }
+ if (!next) return;
+ snapshot = next;
snapshotOwnerKey = owner.key;
- broadcast(null);
+ broadcast(next);
ensureIdlePoll();
- return;
- }
- if (!next) return;
- snapshot = next;
- snapshotOwnerKey = owner.key;
- broadcast(next);
- ensureIdlePoll();
- } finally {
- fetchInFlight = false;
- fetchOwnerKey = null;
- if (refreshQueued) {
- refreshQueued = false;
- void triggerClaudeAccountUsageRefresh(true);
+ } finally {
+ fetchInFlight = false;
+ fetchPromise = null;
+ fetchOwnerKey = null;
+ if (refreshQueued) {
+ refreshQueued = false;
+ void triggerClaudeAccountUsageRefresh(true);
+ }
}
- }
+ })().then(resolveFetch, rejectFetch);
+ await pending;
}
/**
diff --git a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
index f9f14e1bd1..dba5910cd7 100644
--- a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
@@ -6,6 +6,7 @@ import { useClaudeAccountUsageResult } from '../hooks/useClaudeAccountUsage';
const state = vi.hoisted(() => ({
owner: 'credit-a',
+ generation: 1,
membership: 'personal',
credit: vi.fn(),
quota: vi.fn(),
@@ -13,6 +14,7 @@ const state = vi.hoisted(() => ({
vi.mock('../contexts/AuthContext', () => ({
useAuth: () => ({
dataOwnerId: state.owner,
+ dataOwnerGeneration: state.generation,
mode: 'cloud',
user: { membershipKind: state.membership },
}),
@@ -26,6 +28,7 @@ const credit = (available: string) => ({
});
beforeEach(() => {
state.owner = 'credit-a';
+ state.generation = 1;
state.membership = 'personal';
state.credit.mockReset();
state.quota.mockReset();
@@ -102,12 +105,12 @@ for (const kind of ['quota', 'credit'] as const) {
await waitFor(() => expect(statusBar.result.current.usage).not.toBeNull());
settings.rerender({ enabled: true });
expect(settings.result.current.usage).toEqual(statusBar.result.current.usage);
- expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 2 : 1);
+ await waitFor(() => expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 2 : 1));
statusBar.unmount();
settings.unmount();
const reopened = renderHook(() => useUsage(true));
expect(reopened.result.current.usage).not.toBeNull();
- expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 3 : 1);
+ await waitFor(() => expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 3 : 1));
act(() => reopened.result.current.refresh());
await waitFor(() => expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 4 : 2));
});
@@ -147,7 +150,7 @@ it('preserves owner-bound warm quota when a refresh has no main snapshot', async
state.quota.mockResolvedValue(null);
const reopened = renderHook(() => useClaudeAccountUsageResult(true));
act(() => reopened.result.current.refresh());
- await waitFor(() => expect(state.quota).toHaveBeenCalledTimes(3));
+ await waitFor(() => expect(state.quota).toHaveBeenCalledTimes(2));
await waitFor(() => expect(reopened.result.current.loading).toBe(false));
expect(reopened.result.current.usage?.spend).toBe(12);
reopened.unmount();
@@ -168,3 +171,105 @@ it.each(['unlimited', 'invalidated'])('replays an authoritative %s read after th
await waitFor(() => expect(reopened.result.current.loading).toBe(false));
expect(reopened.result.current.usage).toBeNull();
});
+
+
+it('preserves unlimited state, invalidates it on gateway change, and isolates accounts', async () => {
+ state.owner = 'unlimited-transitions';
+ state.membership = 'org';
+ let changed!: Parameters<typeof window.electronAPI.maker.usage.onClaudeAccountChanged>[0];
+ window.electronAPI.maker.usage.onClaudeAccountChanged = listener => {
+ changed = listener;
+ return () => {};
+ };
+ state.quota.mockResolvedValue({ quotaState: 'unlimited' });
+ const view = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(view.result.current.unlimited).toBe(true));
+ expect(view.result.current.usage).toBeNull();
+ state.quota.mockResolvedValue(null);
+ act(() => view.result.current.refresh());
+ await waitFor(() => expect(view.result.current.loading).toBe(false));
+ expect(view.result.current.unlimited).toBe(true);
+ state.quota.mockResolvedValue({ quotaState: 'invalidated' });
+ act(() => changed(null));
+ await waitFor(() => expect(view.result.current.loading).toBe(false));
+ expect(view.result.current.unlimited).toBe(false);
+ state.quota.mockResolvedValue({ quotaState: 'unlimited' });
+ act(() => changed(null));
+ await waitFor(() => expect(view.result.current.unlimited).toBe(true));
+ const finite = { spend: 1, maxBudget: 100, currency: 'CNY' as const, todaySpend: null, fetchedAt: 1 };
+ act(() => changed(finite));
+ expect(view.result.current.unlimited).toBe(false);
+ expect(view.result.current.usage).toEqual(finite);
+ state.owner = 'another-unlimited-owner';
+ state.quota.mockResolvedValue(null);
+ view.rerender();
+ expect(view.result.current.usage).toBeNull();
+ expect(view.result.current.unlimited).toBe(false);
+ await waitFor(() => expect(view.result.current.loading).toBe(false));
+});
+
+
+it('does not loop when the quota read itself broadcasts an unlimited clear', async () => {
+ state.owner = 'unlimited-push-during-read';
+ state.membership = 'org';
+ let changed: Parameters<typeof window.electronAPI.maker.usage.onClaudeAccountChanged>[0] | undefined;
+ window.electronAPI.maker.usage.onClaudeAccountChanged = listener => {
+ changed = listener;
+ return () => {};
+ };
+ state.quota.mockImplementation(async () => {
+ await Promise.resolve();
+ changed?.(null);
+ return { quotaState: 'unlimited' };
+ });
+ const view = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(view.result.current.unlimited).toBe(true));
+ expect(state.quota).toHaveBeenCalledTimes(1);
+ act(() => changed?.(null));
+ await waitFor(() => expect(view.result.current.unlimited).toBe(true));
+ expect(state.quota).toHaveBeenCalledTimes(2);
+});
+
+
+it('coalesces unlimited reads across two mounted panes without ping-pong refreshes', async () => {
+ state.owner = 'two-unlimited-panes';
+ state.membership = 'org';
+ const listeners = new Set<Parameters<typeof window.electronAPI.maker.usage.onClaudeAccountChanged>[0]>();
+ window.electronAPI.maker.usage.onClaudeAccountChanged = listener => {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ };
+ let resolveRead!: (value: unknown) => void;
+ state.quota.mockImplementation(() => new Promise(resolve => { resolveRead = resolve; }));
+ const first = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(state.quota).toHaveBeenCalledTimes(1));
+ await act(async () => { resolveRead({ quotaState: 'unlimited' }); });
+ const second = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(state.quota).toHaveBeenCalledTimes(2));
+ act(() => { for (const listener of listeners) listener(null); });
+ await act(async () => { resolveRead({ quotaState: 'unlimited' }); });
+ await waitFor(() => expect(first.result.current.unlimited && second.result.current.unlimited).toBe(true));
+ expect(state.quota).toHaveBeenCalledTimes(2);
+ act(() => { for (const listener of listeners) listener(null); });
+ await waitFor(() => expect(state.quota).toHaveBeenCalledTimes(3));
+ act(() => { for (const listener of listeners) listener(null); });
+ await act(async () => { resolveRead({ quotaState: 'unlimited' }); });
+ expect(first.result.current.unlimited && second.result.current.unlimited).toBe(true);
+ expect(state.quota).toHaveBeenCalledTimes(3);
+});
+
+// Unit regression: projection repair keeps the account ID but advances its generation.
+// Existing account-switch tests cannot detect stale unlimited state for the same account.
+it('invalidates unlimited immediately when the same owner generation changes', async () => {
+ state.owner = 'generation-repair';
+ state.membership = 'org';
+ state.quota.mockResolvedValueOnce({ quotaState: 'unlimited' });
+ const view = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(view.result.current.unlimited).toBe(true));
+ state.quota.mockResolvedValueOnce({ spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 });
+ state.generation += 1;
+ view.rerender();
+ expect(view.result.current.unlimited).toBe(false);
+ await waitFor(() => expect(view.result.current.usage?.maxBudget).toBe(100));
+ expect(state.quota).toHaveBeenCalledTimes(2);
+});
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
index 5c254ea5dc..ee0d9edd31 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx
@@ -33,6 +33,7 @@ const {
dataOwnerId: 'account-1' as string | null,
},
quotaState: {
+ unlimited: false,
usage: null as import('../hooks/useClaudeAccountUsage').ClaudeAccountUsageSnapshot | null,
},
creditUsageState: { available: null as string | null },
@@ -83,6 +84,7 @@ vi.mock('@/hooks/useModelAccessCreditUsage', () => ({
vi.mock('@/hooks/useClaudeAccountUsage', () => ({
useClaudeAccountUsageResult: (enabled: boolean) => ({
usage: enabled ? quotaState.usage : null,
+ unlimited: enabled && quotaState.unlimited,
loading: false,
refresh: vi.fn(),
}),
@@ -218,6 +220,7 @@ beforeEach(() => {
authState.dataOwnerId = 'account-1';
creditUsageState.available = '18.42';
quotaState.usage = null;
+ quotaState.unlimited = false;
modelAccessState.state = 'ok';
modelAccessState.source = 'server';
modelAccessState.accountTier = null;
@@ -365,6 +368,17 @@ describe('ProvidersSection — Cindy AI 账户资产模块', () => {
expect(screen.queryByText('billing.settings.topupCard.action')).toBeNull();
});
+ it('shows no personal limit rather than an unavailable quota for an enterprise', async () => {
+ authState.user = { membershipKind: 'org' };
+ quotaState.unlimited = true;
+ renderSection();
+ expect(await screen.findByText('settings.providers.xd.asset.noPersonalLimit')).toBeTruthy();
+ expect(screen.queryByText('settings.providers.xd.asset.unavailable')).toBeNull();
+ expect(screen.getByText('settings.providers.xd.asset.refresh')).toBeTruthy();
+ expect(screen.queryByText('billing.balance.title')).toBeNull();
+ expect(primaryActionState.lastEnabled).toBe(false);
+ });
+
it('local 会话(未登录云账号):同样不渲染', async () => {
authState.mode = 'local';
authState.user = null;
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 0323a88373..9d826d7a3f 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -1735,6 +1735,7 @@ function XdGatewayHeader({
available: credit.usage?.available ?? null,
quotaAccessible,
quota: quota.usage,
+ quotaUnlimited: quota.unlimited,
loading: billingAccessible ? credit.loading : quota.loading,
});
const primaryAction = useXdAssetPrimaryAction(assetState.kind === 'balance');
@@ -1894,7 +1895,7 @@ function XdGatewayHeader({
</p>
<PillButton label={t('settings.providers.xd.sync.retry')} onClick={handleRetry} />
</>
- ) : assetState.kind === 'loading' || assetState.kind === 'unavailable' ? (
+ ) : assetState.kind === 'loading' || assetState.kind === 'unavailable' || assetState.kind === 'unlimited' ? (
<>
<div>
<p className="text-12 text-[var(--text-secondary)]">
@@ -1908,7 +1909,9 @@ function XdGatewayHeader({
{t(
assetState.kind === 'loading'
? 'settings.providers.xd.asset.loading'
- : 'settings.providers.xd.asset.unavailable',
+ : assetState.kind === 'unlimited'
+ ? 'settings.providers.xd.asset.noPersonalLimit'
+ : 'settings.providers.xd.asset.unavailable',
)}
</p>
</div>
diff --git a/apps/desktop/src/renderer/components/settings/providerAssetModule.ts b/apps/desktop/src/renderer/components/settings/providerAssetModule.ts
index 6e8977dce3..69e20d61c5 100644
--- a/apps/desktop/src/renderer/components/settings/providerAssetModule.ts
+++ b/apps/desktop/src/renderer/components/settings/providerAssetModule.ts
@@ -18,6 +18,7 @@ export type ProviderAssetModuleState =
| { kind: 'hidden' }
| { kind: 'fault' }
| { kind: 'balance'; available: string }
+ | { kind: 'unlimited'; scope: 'quota' }
| { kind: 'quota'; quota: ClaudeAccountUsageSnapshot }
| { kind: 'loading'; scope: 'balance' | 'quota' }
| { kind: 'unavailable'; scope: 'balance' | 'quota' };
@@ -30,6 +31,7 @@ export interface XdAssetModuleInput {
/** 额度池账本里的可用余额(useModelAccessCreditUsage);拿不到为 null。 */
available: string | null;
quotaAccessible?: boolean;
+ quotaUnlimited?: boolean;
quota?: ClaudeAccountUsageSnapshot | null;
loading?: boolean;
}
@@ -128,6 +130,7 @@ export function resolveXdAssetModuleState(input: XdAssetModuleInput): ProviderAs
// personal credit ledger. Never grant billing/purchase access merely to show this quota.
if (input.quotaAccessible) {
if (syncState === 'failed') return { kind: 'fault' };
+ if (input.quotaUnlimited) return { kind: 'unlimited', scope: 'quota' };
return input.quota
? { kind: 'quota', quota: input.quota }
: { kind: input.loading ? 'loading' : 'unavailable', scope: 'quota' };
diff --git a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
index 3b4fd9fa9f..fcf7da8262 100644
--- a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
@@ -26,7 +26,7 @@
*/
import { CLAUDE_QUOTA_STATE_READ, isClaudeQuotaClear } from '../../shared/claudeQuotaState';
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import type { MoneyCurrency } from '../../shared/regionalMoney';
import { useAuth } from '../contexts/AuthContext';
@@ -53,11 +53,28 @@ export interface ClaudeAccountUsageSnapshot {
interface OwnerBoundSnapshot {
ownerKey: string;
cachedAt: number;
- usage: ClaudeAccountUsageSnapshot;
+ usage: ClaudeAccountUsageSnapshot | null;
+ unlimited: boolean;
}
let lastSnapshot: OwnerBoundSnapshot | null = null;
+// All panes for one account share a read. A null push emitted by that read must
+// not make an idle pane start another forced read and wake the other panes again.
+const reads = new Map<string, Promise<unknown>>();
+function readQuota(ownerKey: string): Promise<unknown> {
+ const pending = reads.get(ownerKey);
+ if (pending) return pending;
+ const request = Promise.resolve().then(() =>
+ window.electronAPI.maker.usage.getAccount('claude-code', CLAUDE_QUOTA_STATE_READ),
+ );
+ reads.set(ownerKey, request);
+ const clear = () => { if (reads.get(ownerKey) === request) reads.delete(ownerKey); };
+ void request.then(clear, clear);
+ return request;
+}
+
+
function isSnapshot(v: unknown): v is ClaudeAccountUsageSnapshot {
if (!v || typeof v !== 'object') return false;
const r = v as Partial<ClaudeAccountUsageSnapshot>;
@@ -71,17 +88,18 @@ function isSnapshot(v: unknown): v is ClaudeAccountUsageSnapshot {
}
export function useClaudeAccountUsageResult(enabled: boolean) {
- const { dataOwnerId, mode, user } = useAuth();
+ const { dataOwnerId, dataOwnerGeneration, mode, user } = useAuth();
const ownerKey =
enabled &&
dataOwnerId &&
(mode === 'local' || (mode === 'cloud' && user?.membershipKind === 'org'))
- ? `${mode}:${dataOwnerId}`
+ ? `${mode}:${dataOwnerId}:${dataOwnerGeneration}`
: null;
const [snapshot, setSnapshot] = useState<OwnerBoundSnapshot | null>(() =>
ownerKey && lastSnapshot?.ownerKey === ownerKey ? lastSnapshot : null,
);
+ const reading = useRef(false);
const [revision, setRevision] = useState(0);
const refresh = useCallback(() => setRevision((value) => value + 1), []);
const [request, setRequest] = useState<{ ownerKey: string; loading: boolean } | null>(null);
@@ -94,28 +112,37 @@ export function useClaudeAccountUsageResult(enabled: boolean) {
// Display warm data immediately, but read again to replay a missed authoritative clear.
let cancelled = false;
setRequest({ ownerKey, loading: true });
- void window.electronAPI.maker.usage
- .getAccount('claude-code', CLAUDE_QUOTA_STATE_READ)
+ reading.current = true;
+ void readQuota(ownerKey)
.then((res) => {
if (cancelled) return;
if (isClaudeQuotaClear(res)) {
- if (lastSnapshot?.ownerKey === ownerKey) lastSnapshot = null;
- setSnapshot(null);
+ lastSnapshot = {
+ ownerKey,
+ cachedAt: Date.now(),
+ usage: null,
+ unlimited: res.quotaState === 'unlimited',
+ };
+ setSnapshot(lastSnapshot);
return;
}
// Unavailable reads must retain the last owner-bound snapshot.
if (!isSnapshot(res)) return;
- lastSnapshot = { ownerKey, cachedAt: Date.now(), usage: res };
+ lastSnapshot = { ownerKey, cachedAt: Date.now(), usage: res, unlimited: false };
setSnapshot(lastSnapshot);
})
.catch(() => {
/* best-effort warm-start */
})
.finally(() => {
- if (!cancelled) setRequest({ ownerKey, loading: false });
+ if (!cancelled) {
+ reading.current = false;
+ setRequest({ ownerKey, loading: false });
+ }
});
return () => {
cancelled = true;
+ reading.current = false;
};
}, [ownerKey, revision]);
@@ -126,16 +153,19 @@ export function useClaudeAccountUsageResult(enabled: boolean) {
if (p === null) {
if (lastSnapshot?.ownerKey === ownerKey) lastSnapshot = null;
setSnapshot(null);
+ // The legacy push cannot distinguish unlimited from invalidation. Read the explicit state.
+ if (!reading.current) refresh();
return;
}
if (!isSnapshot(p)) return;
- lastSnapshot = { ownerKey, cachedAt: Date.now(), usage: p };
+ lastSnapshot = { ownerKey, cachedAt: Date.now(), usage: p, unlimited: false };
setSnapshot(lastSnapshot);
});
- }, [ownerKey]);
+ }, [ownerKey, refresh]);
const currentSnapshot = lastSnapshot?.ownerKey === ownerKey ? lastSnapshot : snapshot;
return {
+ unlimited: Boolean(ownerKey && currentSnapshot?.ownerKey === ownerKey && currentSnapshot.unlimited),
usage: ownerKey && currentSnapshot?.ownerKey === ownerKey ? currentSnapshot.usage : null,
loading: Boolean(ownerKey && (request?.ownerKey !== ownerKey || request.loading)),
refresh,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6752f7023a..1fbc094d02 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3024,6 +3024,7 @@
"quotaTitle": "Remaining this period",
"quotaUsed": "Used {{used}} / Period allowance {{total}}",
"loading": "Loading…",
+ "noPersonalLimit": "No personal spending limit set",
"unavailable": "Temporarily unavailable. Refresh to retry.",
"refresh": "Refresh allowance"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index db5f050bec..d207dea2c1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2995,6 +2995,7 @@
"quotaTitle": "今期の残り利用枠",
"quotaUsed": "利用済み {{used}} / 今期の利用枠 {{total}}",
"loading": "取得中…",
+ "noPersonalLimit": "個人の利用上限は未設定です",
"unavailable": "現在取得できません。更新して再試行してください。",
"refresh": "利用枠を更新"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1f7914659a..ac78aa0502 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2995,6 +2995,7 @@
"quotaTitle": "이번 기간 남은 한도",
"quotaUsed": "사용 {{used}} / 이번 기간 한도 {{total}}",
"loading": "불러오는 중…",
+ "noPersonalLimit": "개인 사용 한도가 설정되지 않았습니다",
"unavailable": "일시적으로 불러올 수 없습니다. 새로고침하세요.",
"refresh": "한도 새로고침"
},
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 8e0d1b8114..20e1a4429b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2995,6 +2995,7 @@
"quotaTitle": "本期剩余额度",
"quotaUsed": "已用 {{used}} / 本期额度 {{total}}",
"loading": "正在获取…",
+ "noPersonalLimit": "未设置个人限额",
"unavailable": "暂时无法获取,请刷新重试。",
"refresh": "刷新额度"
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 3c33176827..9c7a51ad51 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2995,6 +2995,7 @@
"quotaTitle": "本期剩餘額度",
"quotaUsed": "已用 {{used}} / 本期額度 {{total}}",
"loading": "正在取得…",
+ "noPersonalLimit": "未設定個人限額",
"unavailable": "暫時無法取得,請重新整理。",
"refresh": "重新整理額度"
},
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 46d6633018..d64c91860e 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2638,3 +2638,5 @@ still use the same host-owned mail workflow as the chat card.
会先在来源 Agent 里停用这些机器人再由伙伴连接;旧控制端的预览校验不认识新分类,所以照旧把 Telegram / Discord
放在 `connections`、不停来源,也不出现飞书 / 企业微信 / 钉钉条目。分类随预览快照与加密检查点保存,开始导入和恢复
都按当时的分类执行。不改 relay 帧、服务端 schema 或 Mobile 原生指纹。
+
+Cindy AI 设置卡片保留可选读取返回的 `unlimited` 状态,显示“未设置个人限额”;它不代表部门或企业没有限制。`invalidated` 清除该状态,有限额快照覆盖该状态,切换账号不复用上一账号结果。旧 `null` push 无法区分失效与不限额,本地卡片收到后通过既有可选读取核对;同一账号的多个组件共享在途读取,收到读取自身的广播时复用该请求,避免多窗口之间反复触发刷新。主进程跨窗口共享在途读取,已知不限额参与既有节流,重复不限额结果不重复广播。IPC payload 与远程消费者保持兼容。