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): rebuild menu bar when finite quota recovers

qianbo2465164794c8
diff --git a/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts b/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts
index 7df1494f65..d672e49cce 100644
--- a/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts
+++ b/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts
@@ -24,7 +24,7 @@ vi.mock('../../maker-ipc/register.js', () => ({}));
vi.mock('../../maker-ipc/usage.js', () => ({}));
vi.mock('../../notificationService.js', () => ({}));
vi.mock('../../serverApiClient.js', () => ({}));
-vi.mock('../../usage/claudeAccountUsage.js', () => ({ readClaudeQuotaClearRevision: () => mocks.revision, observeClaudeQuotaClears: (listener: () => void) => { mocks.listeners.add(listener); return () => { mocks.listeners.delete(listener); }; }, triggerClaudeAccountUsageRefresh: () => mocks.refresh(), readClaudeAccountUsageSnapshot: () => mocks.quota }));
+vi.mock('../../usage/claudeAccountUsage.js', () => ({ readClaudeAccountUsageRevision: () => mocks.revision, observeClaudeAccountUsage: (listener: () => void) => { mocks.listeners.add(listener); return () => { mocks.listeners.delete(listener); }; }, triggerClaudeAccountUsageRefresh: () => mocks.refresh(), readClaudeAccountUsageSnapshot: () => mocks.quota }));
vi.mock('../../usage/ledgerCurrency.js', () => ({}));
vi.mock('../../usage/usageHistory.js', () => ({}));
vi.mock('../../usageBroadcaster.js', () => ({ observeUsageChanges: () => () => {} }));
@@ -81,3 +81,19 @@ it('does not publish a view collected before clear', async () => {
expect(publish).not.toHaveBeenCalled(); expect(schedule).toHaveBeenCalledWith(0);
service.stop();
});
+
+it('rebuilds when finite quota arrives after invalidation cached a temporary null', async () => {
+ const service = new MenubarService({ openNewTask() {} });
+ const schedule = vi.spyOn(service as never, 'scheduleRebuild' as never).mockImplementation(() => undefined);
+ service.init();
+ expect((await service['readBalance'](false, Date.now()))?.available).toBe(8);
+ clearQuota();
+ expect(await service['readBalance'](false, Date.now())).toBeNull();
+ schedule.mockClear();
+ mocks.quota = { spend: 3, maxBudget: 20, currency: 'CNY', fetchedAt: Date.now(), todaySpend: null };
+ mocks.revision++;
+ for (const listener of mocks.listeners) listener();
+ expect(schedule).toHaveBeenCalledWith(0);
+ expect((await service['readBalance'](false, Date.now()))?.available).toBe(17);
+ service.stop();
+});
diff --git a/apps/desktop/src/main/menubar/service.ts b/apps/desktop/src/main/menubar/service.ts
index 865a3fa579..31e58e4ce3 100644
--- a/apps/desktop/src/main/menubar/service.ts
+++ b/apps/desktop/src/main/menubar/service.ts
@@ -58,7 +58,7 @@ import {
} from '../maker-ipc/usage.js';
import { getDesktopNotificationsEnabled } from '../notificationService.js';
import { serverApiFetch } from '../serverApiClient.js';
-import { observeClaudeQuotaClears, readClaudeQuotaClearRevision, readClaudeAccountUsageSnapshot, triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
+import { observeClaudeAccountUsage, readClaudeAccountUsageRevision, readClaudeAccountUsageSnapshot, triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';
import { readUsageHistory, type UsageHistoryPayload } from '../usage/usageHistory.js';
import { observeUsageChanges, readCodexAccountUsageSnapshot } from '../usageBroadcaster.js';
@@ -209,7 +209,7 @@ export class MenubarService {
this.host.prepare();
this.disposers.push(
observeUsageChanges(() => this.scheduleRebuild()),
- observeClaudeQuotaClears(() => {
+ observeClaudeAccountUsage(() => {
if (!this.balanceAccountKey()?.startsWith('quota:')) return;
this.balance = null;
this.scheduleRebuild(0);
@@ -320,7 +320,7 @@ export class MenubarService {
private async collectAndPublish(nowMs: number, force: boolean, markStale: () => void): Promise<void> {
const generation = getActiveAppSession().generation;
- const quotaRevision = readClaudeQuotaClearRevision();
+ const quotaRevision = readClaudeAccountUsageRevision();
const collected = await collectMenubarInputs({
nowMs,
listProviders: () => getDesktopProviderService().listProviders({ allowSideEffects: false }),
@@ -346,7 +346,7 @@ export class MenubarService {
// An owner switch that started during the reads makes them the old owner's data.
const after = getActiveAppSession();
if (!this.started || isAppSessionBoundaryPending() || after.generation !== generation) return;
- if (readClaudeQuotaClearRevision() !== quotaRevision) {
+ if (readClaudeAccountUsageRevision() !== quotaRevision) {
this.scheduleRebuild(0);
return;
}
@@ -495,11 +495,11 @@ export class MenubarService {
*/
private balanceAccountKey(): string | null {
const auth = authManager.getAuthState();
- if (auth.mode === 'local') return auth.dataOwnerId ? `quota:local:${auth.dataOwnerId}:${auth.ownerGeneration}:${readClaudeQuotaClearRevision()}` : null;
+ if (auth.mode === 'local') return auth.dataOwnerId ? `quota:local:${auth.dataOwnerId}:${auth.ownerGeneration}:${readClaudeAccountUsageRevision()}` : null;
if (!getAppCapabilities().canUseCindyAccountServices) return null;
const user = auth.user;
if (!user) return null;
- if (user.membershipKind === 'org') return auth.dataOwnerId ? `quota:cloud:${auth.dataOwnerId}:${auth.ownerGeneration}:${readClaudeQuotaClearRevision()}` : null;
+ if (user.membershipKind === 'org') return auth.dataOwnerId ? `quota:cloud:${auth.dataOwnerId}:${auth.ownerGeneration}:${readClaudeAccountUsageRevision()}` : null;
if (user.membershipKind !== 'personal') return null;
return `${user.id}:${CURRENT_CINDY_REGION}`;
}
diff --git a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
index f0bee61427..68f0ab80e8 100644
--- a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
@@ -75,14 +75,14 @@ describe('Cindy AI enterprise quota refresh', () => {
await api.triggerClaudeAccountUsageRefresh(true);
expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);
const cleared = vi.fn();
- const offClear = api.observeClaudeQuotaClears(cleared);
- const revision = api.readClaudeQuotaClearRevision();
+ const offClear = api.observeClaudeAccountUsage(cleared);
+ const revision = api.readClaudeAccountUsageRevision();
mocks.managed.mockResolvedValue('unlimited');
await api.triggerClaudeAccountUsageRefresh(true);
expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'unlimited' });
expect(cleared).toHaveBeenCalledTimes(1);
- expect(api.readClaudeQuotaClearRevision()).toBe(revision + 1);
+ expect(api.readClaudeAccountUsageRevision()).toBe(revision + 1);
offClear();
mocks.managed.mockResolvedValue(null);
await api.triggerClaudeAccountUsageRefresh(true);
@@ -172,3 +172,18 @@ describe('quota gateway migration boundary', () => {
expect(mocks.broadcast.mock.calls.some(([, value]) => value?.spend === 99)).toBe(false);
});
});
+
+it('notifies main-process consumers when finite quota recovers after a source change', async () => {
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ let resolve!: (value: unknown) => void;
+ mocks.managed.mockImplementationOnce(() => new Promise(done => { resolve = done; }));
+ const snapshots: unknown[] = [];
+ const off = api.observeClaudeAccountUsage(() => snapshots.push(api.readClaudeAccountUsageSnapshot()));
+ const state = await import('../../model-access/quotaCredentialState');
+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: 'https://new.example.test', accountTier: null });
+ expect(snapshots).toEqual([null]);
+ resolve(quota);
+ await vi.waitFor(() => expect(snapshots).toEqual([null, quota]));
+ off();
+});
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index f6b49d75be..777e18d8c3 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -333,19 +333,17 @@ export function readClaudeAccountQuotaClear(): ClaudeQuotaClear | null {
? { quotaState: clearReason } : null;
}
-let quotaClearRevision = 0;
-const quotaClearListeners = new Set<() => void>();
-export function readClaudeQuotaClearRevision(): number { return quotaClearRevision; }
-export function observeClaudeQuotaClears(listener: () => void): () => void {
- quotaClearListeners.add(listener);
- return () => { quotaClearListeners.delete(listener); };
+let quotaSnapshotRevision = 0;
+const quotaSnapshotListeners = new Set<() => void>();
+export function readClaudeAccountUsageRevision(): number { return quotaSnapshotRevision; }
+export function observeClaudeAccountUsage(listener: () => void): () => void {
+ quotaSnapshotListeners.add(listener);
+ return () => { quotaSnapshotListeners.delete(listener); };
}
function broadcast(payload: ClaudeAccountUsageSnapshot | null): void {
- if (payload === null) {
- quotaClearRevision++;
- for (const listener of quotaClearListeners) listener();
- }
+ quotaSnapshotRevision++;
+ for (const listener of quotaSnapshotListeners) listener();
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {