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): invalidate quota across enterprise gateway migrations

qianbo4068445361cf
diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
index 4776b7e571..0390838784 100644
--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
@@ -72,7 +72,7 @@ export function toLegacyUsdModelPricing(
/** usage handler 需要的 host-level 查询与刷新能力。 */
export interface MakerUsageHandlerDeps {
- readClaudeAccountQuotaClear?(): { quotaState: 'unlimited' } | null;
+ readClaudeAccountQuotaClear?(): { quotaState: 'unlimited' | 'invalidated' } | null;
readAgentTodayUsage(agentKind: AgentKind): Promise<AgentTodayUsage>;
readCodexAccountUsageSnapshot(providerId?: string): Promise<RateLimitSnapshot | null>;
readCodexRateLimits(providerId?: string): Promise<MobileCodexRateLimitsResult>;
diff --git a/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.ts b/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.ts
new file mode 100644
index 0000000000..78fa3a58c0
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/quotaCredentialState.test.ts
@@ -0,0 +1,30 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+beforeEach(() => vi.resetModules());
+const status = { state: 'ok', source: 'server', endpoint: 'https://gateway.example.test', accountTier: null } as const;
+it('requires a successful current-process sync and matches both owner and endpoint', async () => {
+ const state = await import('../quotaCredentialState');
+ expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);
+ state.noteQuotaCredentialStatus('owner', { ...status, state: 'syncing' });
+ expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);
+ state.noteQuotaCredentialStatus('owner', status);
+ expect(state.quotaCredentialsReady('owner', status.endpoint + '/')).toBe(true);
+ expect(state.quotaCredentialsReady('other', status.endpoint)).toBe(false);
+ expect(state.quotaCredentialsReady('owner', 'https://other.example.test')).toBe(false);
+ state.noteQuotaCredentialStatus('owner', { ...status, state: 'failed' });
+ expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);
+});
+it('invalidates source changes and logout but not repeated successful synchronization', async () => {
+ const state = await import('../quotaCredentialState');
+ const changed = vi.fn();
+ const off = state.onQuotaCredentialSourceChanged(changed);
+ state.noteQuotaCredentialStatus('owner', status);
+ const generation = state.quotaCredentialGeneration();
+ state.noteQuotaCredentialStatus('owner', status);
+ expect(state.quotaCredentialGeneration()).toBe(generation);
+ state.noteQuotaCredentialStatus('owner', { ...status, endpoint: 'https://new.example.test' });
+ expect(state.quotaCredentialGeneration()).toBe(generation + 1);
+ state.noteQuotaCredentialStatus(null, { ...status, state: 'idle' });
+ expect(state.quotaCredentialsReady('owner', status.endpoint)).toBe(false);
+ expect(changed).toHaveBeenCalledTimes(3);
+ off();
+});
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index d30b1be075..f740d59547 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -1,3 +1,4 @@
+import { noteQuotaCredentialStatus } from './quotaCredentialState.js';
import { createByokCache } from './byokCache.js';
import { byokSnapshotSecretIo } from '../secrets/providerSecretStore.js';
import { registerByokIpc } from './byokIpc.js';
@@ -405,6 +406,11 @@ function getSync(): CredentialsSync {
writeXdKey: writeXdKeyWithCodexSideEffect,
store: getModelAccessCredentialsStore(),
onStatusChange: (status) => {
+ const auth = authManager.getAuthState();
+ noteQuotaCredentialStatus(
+ auth.mode === 'cloud' && auth.dataOwnerId ? `cloud:${auth.dataOwnerId}` : null,
+ status,
+ );
if (['failed', 'disabled', 'unsupported', 'idle'].includes(status.state)) {
accountTier = null;
}
diff --git a/apps/desktop/src/main/model-access/quotaCredentialState.ts b/apps/desktop/src/main/model-access/quotaCredentialState.ts
new file mode 100644
index 0000000000..f8d3fad6bc
--- /dev/null
+++ b/apps/desktop/src/main/model-access/quotaCredentialState.ts
@@ -0,0 +1,32 @@
+import type { ModelAccessStatus } from '../../shared/modelAccess.js';
+
+// Process-local readiness only: persisted credentials never count as a successful
+// sync in this process. No keys or endpoint values leave the main process.
+let owner: string | null = null;
+let endpoint: string | null = null;
+let ready = false;
+let generation = 0;
+const listeners = new Set<(ownerKey: string | null) => void>();
+
+export function noteQuotaCredentialStatus(ownerKey: string | null, status: ModelAccessStatus): void {
+ const nextEndpoint = status.endpoint?.trim().replace(/\/+$/, '') || null;
+ const reset = owner !== ownerKey || status.state === 'idle';
+ const changed = status.state === 'ok' && endpoint !== nextEndpoint;
+ if (reset) endpoint = null;
+ owner = ownerKey;
+ ready = status.state === 'ok' && status.source === 'server' && !!nextEndpoint;
+ if (ready) endpoint = nextEndpoint;
+ if (reset || changed) {
+ generation++;
+ for (const listener of listeners) listener(ownerKey);
+ }
+}
+
+export function quotaCredentialsReady(ownerKey: string, effectiveEndpoint: string): boolean {
+ return ready && owner === ownerKey && endpoint === effectiveEndpoint.trim().replace(/\/+$/, '');
+}
+export function quotaCredentialGeneration(): number { return generation; }
+export function onQuotaCredentialSourceChanged(listener: (ownerKey: string | null) => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
diff --git a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
index 9c1329a6a1..87e260241a 100644
--- a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
auth: { mode: 'cloud', dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } },
+ endpoint: 'https://gateway.example.test',
managed: vi.fn(), outbound: vi.fn(), broadcast: vi.fn(),
}));
vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } }));
@@ -9,14 +10,17 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({ tapWindowBroadcast: mocks
vi.mock('../../logger', () => ({ createLogger: () => ({ info: vi.fn(), debug: vi.fn() }) }));
vi.mock('../../maker-host/auth-adapters', () => ({ readClaudeApiKey: () => 'fixture-key' }));
vi.mock('../../maker-host/outbound-fetch', () => ({ outboundFetch: mocks.outbound }));
-vi.mock('../../maker-host/runtime-configs', () => ({ claudeUpstreamEndpoint: () => 'https://gateway.example.test' }));
+vi.mock('../../maker-host/runtime-configs', () => ({ claudeUpstreamEndpoint: () => mocks.endpoint }));
vi.mock('../modelPricing', () => ({ getGatewayAccountCurrency: async () => 'CNY' }));
vi.mock('../ledgerCurrency', () => ({ currentLedgerCurrency: () => 'CNY' }));
vi.mock('../organizationAccountUsage.js', () => ({ readOrganizationAccountUsage: mocks.managed }));
const quota = { spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 };
-beforeEach(() => {
+beforeEach(async () => {
vi.resetModules(); vi.useFakeTimers(); vi.clearAllMocks();
mocks.auth = { mode: 'cloud', dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } };
+ mocks.endpoint = 'https://gateway.example.test';
+ const state = await import('../../model-access/quotaCredentialState');
+ state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });
mocks.managed.mockResolvedValue(quota);
mocks.outbound.mockResolvedValue({ ok: true, json: async () => ({ spend: 2, max_budget: 20, results: [] }) });
});
@@ -75,3 +79,60 @@ describe('Cindy AI enterprise quota refresh', () => {
expect(mocks.outbound).toHaveBeenCalledTimes(2);
});
});
+
+describe('quota gateway migration boundary', () => {
+ it('blocks persisted legacy credentials before this process completes credential sync', async () => {
+ const state = await import('../../model-access/quotaCredentialState');
+ state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });
+ mocks.managed.mockResolvedValue(undefined);
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(mocks.outbound).not.toHaveBeenCalled();
+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });
+ await vi.waitFor(() => expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20));
+ });
+
+ it('reads managed quota before credential sync without contacting the persisted gateway', async () => {
+ const state = await import('../../model-access/quotaCredentialState');
+ state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);
+ expect(mocks.outbound).not.toHaveBeenCalled();
+ });
+
+ it('invalidates the old gateway quota even if the first new gateway query fails', async () => {
+ mocks.managed.mockResolvedValue(undefined);
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20);
+ mocks.managed.mockResolvedValue(null);
+ mocks.endpoint = 'https://new-gateway.example.test';
+ const state = await import('../../model-access/quotaCredentialState');
+ state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });
+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'invalidated' });
+ expect(mocks.broadcast).toHaveBeenLastCalledWith('usage:claude-account-changed', null);
+ await vi.waitFor(() => expect(mocks.managed).toHaveBeenCalledTimes(2));
+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ });
+
+ it('drops a late response from the previous gateway after credentials change', async () => {
+ mocks.managed.mockResolvedValue(undefined);
+ let complete!: (value: unknown) => void;
+ mocks.outbound.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
+ const api = await import('../claudeAccountUsage');
+ const pending = api.triggerClaudeAccountUsageRefresh(true);
+ await vi.waitFor(() => expect(mocks.outbound).toHaveBeenCalledTimes(2));
+ mocks.managed.mockResolvedValue(null);
+ mocks.endpoint = 'https://new-gateway.example.test';
+ const state = await import('../../model-access/quotaCredentialState');
+ state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });
+ complete({ ok: true, json: async () => ({ spend: 99, max_budget: 100 }) });
+ await pending;
+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'invalidated' });
+ expect(mocks.broadcast.mock.calls.some(([, value]) => value?.spend === 99)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 5524603941..02024554ed 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -1,3 +1,5 @@
+import { quotaCredentialsReady, quotaCredentialGeneration, onQuotaCredentialSourceChanged } from '../model-access/quotaCredentialState.js';
+import type { ClaudeQuotaClear } from '../../shared/claudeQuotaState.js';
import { readOrganizationAccountUsage } from './organizationAccountUsage.js';
/**
* claudeAccountUsage — Claude 账号配额 (LiteLLM spend / max_budget) 拉取与广播。
@@ -93,6 +95,7 @@ const IDLE_POLL_INTERVAL_MS = 5 * 60 * 1000;
let snapshot: ClaudeAccountUsageSnapshot | null = null;
let snapshotOwnerKey: string | null = null;
+let clearReason: ClaudeQuotaClear['quotaState'] = 'unlimited';
let fetchInFlight = false;
let fetchOwnerKey: string | null = null;
let refreshQueued = false;
@@ -222,6 +225,8 @@ async function fetchOnce(authenticatedUserId?: string): Promise<ClaudeAccountUsa
// 无关,proxy 只服务于子进程的 chat completion 请求。
const baseUrl = claudeUpstreamEndpoint().trim();
if (!apiKey || !baseUrl) return null;
+ const legacyOwner = currentQuotaOwner();
+ if (getAuthState().mode === 'cloud' && (!legacyOwner || !quotaCredentialsReady(legacyOwner.key, baseUrl))) return null;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
@@ -236,6 +241,7 @@ async function fetchOnce(authenticatedUserId?: string): Promise<ClaudeAccountUsa
fetchTodayActivity(baseUrl, apiKey, controller.signal),
]);
if (!cycle) return null;
+ if (getAuthState().mode === 'cloud' && (!legacyOwner || !quotaCredentialsReady(legacyOwner.key, baseUrl))) return null;
const todaySpend = dailyActivity ? resolveDailyActivitySpend(dailyActivity).todaySpend : null;
log.info(
`refreshed cycle=${cycle.spend.toFixed(2)}/${cycle.maxBudget.toFixed(2)} today=${todaySpend == null ? 'n/a' : todaySpend.toFixed(2)} resetAt=${cycle.budgetResetAt ?? 'n/a'}`,
@@ -273,9 +279,12 @@ export async function triggerClaudeAccountUsageRefresh(force = false): Promise<v
fetchOwnerKey = owner.key;
lastFetchAt = Date.now();
try {
+ 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;
snapshotOwnerKey = owner.key;
broadcast(null);
@@ -318,10 +327,10 @@ export function readClaudeAccountUsageSnapshot(): ClaudeAccountUsageSnapshot | n
}
/** Authoritative no-limit state is replayable even if no renderer heard its push. */
-export function readClaudeAccountQuotaClear(): { quotaState: 'unlimited' } | null {
+export function readClaudeAccountQuotaClear(): ClaudeQuotaClear | null {
const owner = currentQuotaOwner();
return owner && snapshotOwnerKey === owner.key && snapshot === null
- ? { quotaState: 'unlimited' } : null;
+ ? { quotaState: clearReason } : null;
}
function broadcast(payload: ClaudeAccountUsageSnapshot | null): void {
@@ -334,3 +343,17 @@ function broadcast(payload: ClaudeAccountUsageSnapshot | null): void {
// (刷新自带 10s 节流 + turn-done 触发,低频;无 active 链路时 O(1) no-op)。
tapWindowBroadcast(USAGE_CLAUDE_ACCOUNT_CHANGED, payload);
}
+
+// A new gateway invalidates both finite and unlimited results from the previous
+// source. Replayable invalidation also covers renderers that missed the push.
+onQuotaCredentialSourceChanged((ownerKey) => {
+ const owner = currentQuotaOwner();
+ if (!owner || !owner.key.startsWith('cloud:') || owner.key !== ownerKey) return;
+ snapshot = null;
+ snapshotOwnerKey = owner.key;
+ clearReason = 'invalidated';
+ lastFetchAt = 0;
+ broadcast(null);
+ if (fetchInFlight) refreshQueued = true;
+ else void triggerClaudeAccountUsageRefresh(true).catch(() => undefined);
+});
diff --git a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
index 9dfc1aebbe..f9f14e1bd1 100644
--- a/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/gatewayAccountUsageHooks.test.tsx
@@ -156,14 +156,14 @@ it('preserves owner-bound warm quota when a refresh has no main snapshot', async
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';
+it.each(['unlimited', 'invalidated'])('replays an authoritative %s read after the clear push was missed while unmounted', async (quotaState) => {
+ state.owner = `quota-missed-clear-${quotaState}`;
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' });
+ state.quota.mockResolvedValue({ quotaState });
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 1b6fbb207d..53bd995089 100644
--- a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts
@@ -377,7 +377,7 @@ describe('remote account parity', () => {
});
});
-it('retains remote quota on unavailable reads but replays a missed unlimited clear', async () => {
+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);
const first = renderHook(() => useRemoteClaudeAccountUsage('device-quota'));
@@ -389,7 +389,7 @@ it('retains remote quota on unavailable reads but replays a missed unlimited cle
await flushMicrotasks();
expect(unavailable.result.current).toEqual(quota);
unavailable.unmount();
- mocks.invoke.mockResolvedValue({ quotaState: 'unlimited' });
+ mocks.invoke.mockResolvedValue({ quotaState });
const cleared = renderHook(() => useRemoteClaudeAccountUsage('device-quota'));
await flushMicrotasks();
expect(cleared.result.current).toBeNull();
diff --git a/apps/desktop/src/shared/claudeQuotaState.ts b/apps/desktop/src/shared/claudeQuotaState.ts
index e6cbb1888f..8a28a6af7c 100644
--- a/apps/desktop/src/shared/claudeQuotaState.ts
+++ b/apps/desktop/src/shared/claudeQuotaState.ts
@@ -1,7 +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 interface ClaudeQuotaClear { quotaState: 'unlimited' | 'invalidated' }
export function isClaudeQuotaClear(value: unknown): value is ClaudeQuotaClear {
return !!value && typeof value === 'object' && !Array.isArray(value)
- && (value as ClaudeQuotaClear).quotaState === 'unlimited';
+ && ['unlimited', 'invalidated'].includes((value as ClaudeQuotaClear).quotaState);
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 5ec140c214..ed4886b129 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1767,3 +1767,5 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca
配额读取 IPC 返回 null 仅表示当前无可用快照,不清除 renderer 已缓存的同账号额度;只有权威 clear 读取结果或显式 clear push 才清除缓存。
`maker:usage:account('claude-code', 'cindy-quota-state-v1')` 为可选读取能力:有限额度保持原快照,权威不限额返回 `{ quotaState: 'unlimited' }`,暂无当前账号快照返回 null。无该能力参数的旧消费者仍只收到快照/null;旧主机忽略该参数,新消费者对其 null 保留旧缓存。本地重新挂载和远程读取均查询该状态,避免错过 clear 推送;仅权威 clear 可淘汰同账号缓存。
+
+企业凭据迁移:`/quota` 查询不依赖本地推理凭据;仅在当前进程、当前账号已成功同步服务端凭据,且实际 endpoint 与本次同步一致时,允许 404/明确 501 后的旧直连回退。持久化凭据不能作为本轮同步成功的证明。网关 endpoint 或身份代次变化时,失效当前账号额度并丢弃旧代次在途结果;失效结果通过既有 null push 通知,可选状态读取返回 `{ quotaState: 'invalidated' }`,与 unavailable null 区分。新本地/远程消费者将 invalidated 和 unlimited 都作为权威清缓存;未携带能力参数的旧消费者保持 snapshot/null 返回。此处不变更凭据存储、推理回退或额度计算口径。