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): replay authoritative quota clear across local and remote reads

qianbo5afa0dffee22
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
index 2a8743f5eb..af84b5b483 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
@@ -1310,6 +1310,17 @@ describe('maker usage IPC handlers', () => {
expect(triggerClaudeAccountUsageRefresh).toHaveBeenCalledWith(true);
});
+ it('only returns authoritative quota clear to opted-in readers', async () => {
+ const harness = new IpcHarness();
+ registerMakerUsageHandlers(harness, makeUsageDeps({
+ readClaudeAccountUsageSnapshot: vi.fn(() => null),
+ readClaudeAccountQuotaClear: vi.fn(() => ({ quotaState: 'unlimited' as const })),
+ triggerClaudeAccountUsageRefresh: vi.fn().mockResolvedValue(undefined),
+ }));
+ await expect(harness.invoke(MAKER_INVOKE.USAGE_ACCOUNT, 'claude-code')).resolves.toBeNull();
+ await expect(harness.invoke(MAKER_INVOKE.USAGE_ACCOUNT, 'claude-code', 'cindy-quota-state-v1')).resolves.toEqual({ quotaState: 'unlimited' });
+ });
+
it('refreshes a cached Gateway quota through the throttled fetcher and returns the updated value', async () => {
const harness = new IpcHarness();
const previous = {
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index ee56c12c98..3cbe1d72d3 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -17,6 +17,7 @@ import { createLogger } from '../logger.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import {
readClaudeAccountUsageSnapshot,
+ readClaudeAccountQuotaClear,
triggerClaudeAccountUsageRefresh,
} from '../usage/claudeAccountUsage.js';
import {
@@ -328,6 +329,7 @@ export function registerMakerUsageIpc(maker: Maker): void {
assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);
},
readClaudeAccountUsageSnapshot,
+ readClaudeAccountQuotaClear,
triggerClaudeAccountUsageRefresh,
readModelPricing: getGatewayModelPricing,
readReferenceModelPricing: getReferenceModelPricing,
diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
index e5d732851d..4776b7e571 100644
--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
@@ -1,3 +1,4 @@
+import { CLAUDE_QUOTA_STATE_READ } from '../../shared/claudeQuotaState';
/**
* maker:usage:* IPC 的纯 handler body。
*
@@ -71,6 +72,7 @@ export function toLegacyUsdModelPricing(
/** usage handler 需要的 host-level 查询与刷新能力。 */
export interface MakerUsageHandlerDeps {
+ readClaudeAccountQuotaClear?(): { quotaState: 'unlimited' } | null;
readAgentTodayUsage(agentKind: AgentKind): Promise<AgentTodayUsage>;
readCodexAccountUsageSnapshot(providerId?: string): Promise<RateLimitSnapshot | null>;
readCodexRateLimits(providerId?: string): Promise<MobileCodexRateLimitsResult>;
@@ -110,7 +112,8 @@ export function registerMakerUsageHandlers(
// 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);
- return deps.readClaudeAccountUsageSnapshot();
+ return deps.readClaudeAccountUsageSnapshot()
+ ?? (providerId === CLAUDE_QUOTA_STATE_READ ? deps.readClaudeAccountQuotaClear?.() ?? null : null);
}
return null;
});
diff --git a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
index ff2b14ccb2..9c1329a6a1 100644
--- a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
@@ -58,6 +58,12 @@ describe('Cindy AI enterprise quota refresh', () => {
mocks.managed.mockResolvedValue('unlimited');
await api.triggerClaudeAccountUsageRefresh(true);
expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'unlimited' });
+ mocks.managed.mockResolvedValue(null);
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'unlimited' });
+ mocks.auth = { ...mocks.auth, dataOwnerId: 'other-owner' };
+ expect(api.readClaudeAccountQuotaClear()).toBeNull();
expect(mocks.broadcast).toHaveBeenLastCalledWith('usage:claude-account-changed', null);
expect(mocks.outbound).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 07b600c172..5524603941 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -317,6 +317,13 @@ export function readClaudeAccountUsageSnapshot(): ClaudeAccountUsageSnapshot | n
return owner && snapshotOwnerKey === owner.key ? snapshot : null;
}
+/** Authoritative no-limit state is replayable even if no renderer heard its push. */
+export function readClaudeAccountQuotaClear(): { quotaState: 'unlimited' } | null {
+ const owner = currentQuotaOwner();
+ return owner && snapshotOwnerKey === owner.key && snapshot === null
+ ? { quotaState: 'unlimited' } : null;
+}
+
function broadcast(payload: ClaudeAccountUsageSnapshot | null): void {
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
diff --git a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
index 1fad536e88..9dfc1aebbe 100644
--- a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
@@ -102,14 +102,14 @@ 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(1);
+ 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(1);
+ expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 3 : 1);
act(() => reopened.result.current.refresh());
- await waitFor(() => expect(request).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(request).toHaveBeenCalledTimes(kind === 'quota' ? 4 : 2));
});
}
@@ -147,9 +147,24 @@ 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(2));
+ await waitFor(() => expect(state.quota).toHaveBeenCalledTimes(3));
await waitFor(() => expect(reopened.result.current.loading).toBe(false));
expect(reopened.result.current.usage?.spend).toBe(12);
reopened.unmount();
- expect(renderHook(() => useClaudeAccountUsageResult(true)).result.current.usage?.spend).toBe(12);
+ const finalView = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(finalView.result.current.loading).toBe(false));
+ expect(finalView.result.current.usage?.spend).toBe(12);
+});
+
+it('replays an authoritative unlimited read after the clear push was missed while unmounted', async () => {
+ state.owner = 'quota-missed-clear';
+ state.membership = 'org';
+ state.quota.mockResolvedValue({ spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 });
+ const first = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(first.result.current.usage?.spend).toBe(12));
+ first.unmount();
+ state.quota.mockResolvedValue({ quotaState: 'unlimited' });
+ const reopened = renderHook(() => useClaudeAccountUsageResult(true));
+ await waitFor(() => expect(reopened.result.current.loading).toBe(false));
+ expect(reopened.result.current.usage).toBeNull();
});
diff --git a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
index 2698e7f44d..0534cbddf5 100644
--- a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
@@ -19,6 +19,7 @@ import { createRemoteDeviceUsageMirror } from '../hooks/remoteDeviceUsageMirror'
import {
selectRemoteCodexAccountUsage,
useRemoteCodexAccountUsage,
+ useRemoteClaudeAccountUsage,
useRemoteXaiRateLimit,
resetRemoteDeviceUsageMirrorsForTest,
} from '../hooks/useRemoteDeviceUsage';
@@ -357,3 +358,21 @@ describe('remote account parity', () => {
expect(seen).toEqual([null]);
});
});
+
+it('retains remote quota on unavailable reads but replays a missed unlimited clear', async () => {
+ const quota = { spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 };
+ mocks.invoke.mockResolvedValue(quota);
+ const first = renderHook(() => useRemoteClaudeAccountUsage('device-quota'));
+ await flushMicrotasks();
+ expect(first.result.current).toEqual(quota);
+ first.unmount();
+ mocks.invoke.mockResolvedValue(null);
+ const unavailable = renderHook(() => useRemoteClaudeAccountUsage('device-quota'));
+ await flushMicrotasks();
+ expect(unavailable.result.current).toEqual(quota);
+ unavailable.unmount();
+ mocks.invoke.mockResolvedValue({ quotaState: 'unlimited' });
+ const cleared = renderHook(() => useRemoteClaudeAccountUsage('device-quota'));
+ await flushMicrotasks();
+ expect(cleared.result.current).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts b/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts
index 30d58dc419..62011cb4e0 100644
--- a/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts
+++ b/apps/desktop/src/renderer/hooks/remoteDeviceUsageMirror.ts
@@ -22,6 +22,7 @@ export interface RemoteDeviceUsageMirror<T> {
export function createRemoteDeviceUsageMirror<T extends object>(cfg: {
invokeChannel: string | null;
+ decodeRead?: (value: unknown) => T | null | undefined;
invokeArgs?: unknown[];
pushChannel: string;
defaultProviderId?: string;
@@ -88,7 +89,10 @@ export function createRemoteDeviceUsageMirror<T extends object>(cfg: {
(!isSnapshotShape(value) || value.providerId !== providerId)
)
return;
- if (value === null || isSnapshotShape(value)) apply(entry, value as T | null);
+ if (cfg.decodeRead) {
+ const decoded = cfg.decodeRead(value);
+ if (decoded !== undefined) apply(entry, decoded);
+ } else if (value === null || isSnapshotShape(value)) apply(entry, value as T | null);
})
.catch((error: unknown) => {
if (!isDataOwnerGenerationCurrent(entry.owner) || entry.revision !== revision) return;
diff --git a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
index 9877aeac60..3b4fd9fa9f 100644
--- a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
@@ -25,6 +25,7 @@
* 启用;自定义供应商即使复用相同 host 也不会读这份账号配额。
*/
+import { CLAUDE_QUOTA_STATE_READ, isClaudeQuotaClear } from '../../shared/claudeQuotaState';
import { useCallback, useEffect, useState } from 'react';
import type { MoneyCurrency } from '../../shared/regionalMoney';
@@ -90,19 +91,19 @@ export function useClaudeAccountUsageResult(enabled: boolean) {
if (!ownerKey) return;
const cached = lastSnapshot?.ownerKey === ownerKey ? lastSnapshot : null;
if (cached) setSnapshot(cached);
- // Reopening settings reuses the same account snapshot as the task status bar.
- if (revision === 0 && cached && Date.now() - cached.cachedAt < 60_000) {
- setRequest({ ownerKey, loading: false });
- return;
- }
+ // 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')
+ .getAccount('claude-code', CLAUDE_QUOTA_STATE_READ)
.then((res) => {
if (cancelled) return;
- // A read may return null when main has no snapshot for this owner.
- // Only an explicit clear push is authoritative enough to evict cached quota.
+ if (isClaudeQuotaClear(res)) {
+ if (lastSnapshot?.ownerKey === ownerKey) lastSnapshot = null;
+ setSnapshot(null);
+ return;
+ }
+ // Unavailable reads must retain the last owner-bound snapshot.
if (!isSnapshot(res)) return;
lastSnapshot = { ownerKey, cachedAt: Date.now(), usage: res };
setSnapshot(lastSnapshot);
diff --git a/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts b/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts
index 7efb1905cf..986fe09a29 100644
--- a/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useRemoteDeviceUsage.ts
@@ -1,3 +1,4 @@
+import { CLAUDE_QUOTA_STATE_READ, isClaudeQuotaClear } from '../../shared/claudeQuotaState';
/**
* useRemoteDeviceUsage — device-link 远程会话各计费形态的被控端用量镜像集。
*
@@ -45,7 +46,12 @@ const codexAccountMirror = createRemoteDeviceUsageMirror<RemoteCodexAccountUsage
});
const claudeAccountMirror = createRemoteDeviceUsageMirror<ClaudeAccountUsageSnapshot>({
invokeChannel: 'maker:usage:account',
- invokeArgs: ['claude-code'],
+ invokeArgs: ['claude-code', CLAUDE_QUOTA_STATE_READ],
+ decodeRead: (value) => {
+ if (isClaudeQuotaClear(value)) return null;
+ if (!value || typeof value !== 'object' || !('maxBudget' in value)) return undefined;
+ return value as ClaudeAccountUsageSnapshot;
+ },
pushChannel: 'usage:claude-account-changed',
});
const xaiSubscriptionMirror = createRemoteDeviceUsageMirror<XaiSubscriptionUsageSnapshot>({
diff --git a/apps/desktop/src/shared/claudeQuotaState.ts b/apps/desktop/src/shared/claudeQuotaState.ts
new file mode 100644
index 0000000000..e6cbb1888f
--- /dev/null
+++ b/apps/desktop/src/shared/claudeQuotaState.ts
@@ -0,0 +1,7 @@
+/** Opt-in read capability; old hosts ignore it and retain snapshot/null replies. */
+export const CLAUDE_QUOTA_STATE_READ = 'cindy-quota-state-v1';
+export interface ClaudeQuotaClear { quotaState: 'unlimited' }
+export function isClaudeQuotaClear(value: unknown): value is ClaudeQuotaClear {
+ return !!value && typeof value === 'object' && !Array.isArray(value)
+ && (value as ClaudeQuotaClear).quotaState === 'unlimited';
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7c8a7a6c87..5ec140c214 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1764,4 +1764,6 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca
`usage:claude-account-changed` 广播 null;renderer 同步清除当前 owner 的快照与热缓存。
已有未知载荷消费者会忽略 null,新旧有限配额快照字段不变;网络失败仍保留既有缓存策略。
-配额读取 IPC 返回 null 仅表示当前无可用快照,不清除 renderer 已缓存的同账号额度;只有显式 clear push 才清除缓存。
+配额读取 IPC 返回 null 仅表示当前无可用快照,不清除 renderer 已缓存的同账号额度;只有权威 clear 读取结果或显式 clear push 才清除缓存。
+
+`maker:usage:account('claude-code', 'cindy-quota-state-v1')` 为可选读取能力:有限额度保持原快照,权威不限额返回 `{ quotaState: 'unlimited' }`,暂无当前账号快照返回 null。无该能力参数的旧消费者仍只收到快照/null;旧主机忽略该参数,新消费者对其 null 保留旧缓存。本地重新挂载和远程读取均查询该状态,避免错过 clear 推送;仅权威 clear 可淘汰同账号缓存。