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): 隔离账户用量查询并展示失败状态

Dash4789ab58eb77
diff --git a/apps/desktop/src/main/maker-host/__tests__/provider-account-usage.test.ts b/apps/desktop/src/main/maker-host/__tests__/provider-account-usage.test.ts
index af2b6df5d1..73289b4593 100644
--- a/apps/desktop/src/main/maker-host/__tests__/provider-account-usage.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/provider-account-usage.test.ts
@@ -358,6 +358,29 @@ describe('readProviderAccountUsage', () => {
).resolves.toEqual({ status: 'unavailable', error: 'no-credentials' });
});
+ // PR #7031: CN and Global share an integration id, not an account/cache namespace.
+ // Unit: changing only the upstream must fetch the new endpoint, never return old quota.
+ it('isolates CN and Global snapshots even when the stored key is unchanged', async () => {
+ let upstream = 'https://open.bigmodel.cn/api/anthropic';
+ setAccountUsageProviderReader(() => mkProvider({
+ routing: { 'claude-code': { upstream, authStrategy: 'api-key-header' } },
+ }));
+ const fetchMock = vi.fn(async (url: string | URL | Request) =>
+ String(url).includes('api.z.ai')
+ ? jsonRes({}, 401)
+ : jsonRes(ZHIPU_QUOTA),
+ );
+ setAccountUsageFetch(fetchMock as typeof fetch);
+ expect((await readProviderAccountUsage({ providerId: 'deepseek' })).status).toBe('ready');
+ upstream = 'https://api.z.ai/api/anthropic';
+ await expect(readProviderAccountUsage({ providerId: 'deepseek' })).resolves.toEqual({
+ status: 'unavailable', error: 'auth',
+ });
+ expect(fetchMock).toHaveBeenLastCalledWith(
+ 'https://api.z.ai/api/monitor/usage/quota/limit', expect.anything(),
+ );
+ });
+
it('treats a swapped key as a different account (cache key includes key fingerprint)', async () => {
const fetchMock = vi.fn(async () => jsonRes(DEEPSEEK_BALANCE));
setAccountUsageFetch(fetchMock as unknown as typeof fetch);
diff --git a/apps/desktop/src/main/maker-host/provider-account-usage.ts b/apps/desktop/src/main/maker-host/provider-account-usage.ts
index cd5e2faecc..b4a30b9060 100644
--- a/apps/desktop/src/main/maker-host/provider-account-usage.ts
+++ b/apps/desktop/src/main/maker-host/provider-account-usage.ts
@@ -415,7 +415,7 @@ export async function readProviderAccountUsage(
}
// 缓存键含凭证指纹:同一供应商下换 key(不同账户)后旧账户快照绝不复用。
const keyFingerprint = createHash('sha256').update(resolution.key).digest('hex').slice(0, 12);
- const cacheKey = `${ownerStamp.dataOwnerId ?? 'local'}:${ownerStamp.generation}:${request.providerId}:${resolution.integrationId}:${resolution.agent}:${keyFingerprint}`;
+ const cacheKey = `${ownerStamp.dataOwnerId ?? 'local'}:${ownerStamp.generation}:${request.providerId}:${resolution.integrationId}:${resolution.endpoint}:${resolution.agent}:${keyFingerprint}`;
const now = accountUsageNow();
const record = cache.get(cacheKey);
const manualRefreshBlocked =
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 62775d7fe0..62d92bb8a8 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -1664,6 +1664,9 @@ export function TodaySpendChip({
t,
)
: buildClaudeUsageCard(claudeSubscriptionUsage, t);
+ if (usesProviderAccountUsageForm && providerAccountUsage.result?.status === 'unavailable') {
+ account.emptyText = t(`providerAccountUsage.error.${providerAccountUsage.result.error}`);
+ }
if (
!usesProviderAccountUsageForm &&
(usesCodexQuotaForm || usesXaiQuotaForm || isClaudeSubscription)
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 9823b58a8f..8956b94a4b 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
@@ -42,6 +42,7 @@ const mocks = vi.hoisted(() => ({
refreshCodexRateLimits: vi.fn(),
resetSnapshot: null as MobileCodexRateLimitsResult | null,
consumeReset: vi.fn(),
+ fetchProviderAccountUsage: vi.fn(),
}));
vi.mock('react-i18next', () => ({
@@ -272,9 +273,10 @@ beforeEach(() => {
mocks.codexAuthInjection = null;
mocks.providers = [];
mocks.accountSnapshots = {};
+ mocks.fetchProviderAccountUsage.mockReset();
Object.defineProperty(window, 'electronAPI', {
configurable: true,
- value: { openExternal: mocks.openExternal, maker: { usage: { consumeCodexRateLimitReset: mocks.consumeReset } } },
+ value: { openExternal: mocks.openExternal, maker: { fetchProviderAccountUsage: mocks.fetchProviderAccountUsage, usage: { consumeCodexRateLimitReset: mocks.consumeReset } } },
});
});
@@ -285,6 +287,22 @@ afterEach(() => {
vi.clearAllMocks();
});
+// PR #7031: service error mapping alone does not verify the real chip's visible
+// result. Unit/jsdom, no saved snapshot + an auth/network failure must end waiting.
+it.each(['auth', 'network'])('shows API account %s errors instead of waiting forever', async (error) => {
+ mocks.providers = [{
+ id: 'deepseek', auth: { method: 'apiKey' },
+ routing: { pi: { upstream: 'https://api.deepseek.com', authStrategy: 'api-key-header' } },
+ } as ProviderView];
+ mocks.fetchProviderAccountUsage.mockResolvedValue({ status: 'unavailable', error });
+ render(<TodaySpendChip vendorKey="pi" providerId="deepseek" sessionId="session-1" />);
+ await act(async () => {});
+ act(() => screen.getByRole('button', { name: 'providerAccountUsage.openDashboard' }).focus());
+ const card = screen.getByTestId('quota-hover-card');
+ expect(within(card).getByText(`providerAccountUsage.error.${error}`)).toBeTruthy();
+ expect(within(card).queryByText('等待额度数据')).toBeNull();
+});
+
// #4907: QuotaHoverCard tests cover the threshold, but the real chip never supplied
// the personal balance observation time. Unit/jsdom: stale balance 60 is sufficient.
describe('TodaySpendChip credit snapshot time', () => {
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useProviderAccountUsage.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useProviderAccountUsage.test.ts
new file mode 100644
index 0000000000..c9bae3a04f
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useProviderAccountUsage.test.ts
@@ -0,0 +1,102 @@
+// @vitest-environment jsdom
+// PR #7031: unit/jsdom coverage through the real hook. Existing service tests cannot
+// catch renderer results surviving an engine/connection change or a disabled query.
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { AgentKind, ProviderView } from '@cindy/model-providers';
+import type { ProviderAccountUsageResult } from '../../../shared/providerAccountUsage';
+import { useProviderAccountUsage } from '../useProviderAccountUsage';
+
+const provider = {
+ id: 'deepseek',
+ auth: { method: 'apiKey' },
+ routing: {
+ 'claude-code': { upstream: 'https://api.deepseek.com/anthropic' },
+ pi: { upstream: 'https://api.deepseek.com' },
+ },
+} as ProviderView;
+const ready: ProviderAccountUsageResult = {
+ status: 'ready',
+ stale: false,
+ agent: 'claude-code',
+ snapshot: {
+ kind: 'deepseek-balance',
+ isAvailable: true,
+ fetchedAt: 1,
+ balances: [
+ { currency: 'CNY', totalBalance: '123', grantedBalance: '0', toppedUpBalance: '123' },
+ ],
+ },
+};
+const fetchUsage = vi.fn<() => Promise<ProviderAccountUsageResult>>();
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ fetchUsage.mockReset();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { maker: { fetchProviderAccountUsage: fetchUsage } },
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+it.each([
+ { name: 'engine', nextProvider: provider, nextAgent: 'pi' as AgentKind },
+ {
+ name: 'connection',
+ nextProvider: { ...provider, id: 'deepseek-b' },
+ nextAgent: 'claude-code' as AgentKind,
+ },
+ {
+ name: 'route',
+ nextProvider: {
+ ...provider,
+ routing: {
+ ...provider.routing,
+ 'claude-code': {
+ ...provider.routing['claude-code']!,
+ upstream: 'https://api.deepseek.com/v1',
+ },
+ },
+ },
+ nextAgent: 'claude-code' as AgentKind,
+ },
+])('hides the old account while the new $name is loading', async ({ nextProvider, nextAgent }) => {
+ let resolveNext!: (result: ProviderAccountUsageResult) => void;
+ fetchUsage.mockResolvedValueOnce(ready).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveNext = resolve;
+ }),
+ );
+ const hook = renderHook(({ source, agent }) => useProviderAccountUsage(source, agent), {
+ initialProps: { source: provider, agent: 'claude-code' as AgentKind },
+ });
+ await act(async () => {});
+ expect(hook.result.current.result).toEqual(ready);
+ hook.rerender({ source: nextProvider, agent: nextAgent });
+ expect(hook.result.current.result).toBeNull();
+ await act(async () => resolveNext({ status: 'unavailable', error: 'auth' }));
+ expect(hook.result.current.result).toEqual({ status: 'unavailable', error: 'auth' });
+});
+
+it('discards a pending result after the query becomes unsupported', async () => {
+ let resolvePending!: (result: ProviderAccountUsageResult) => void;
+ fetchUsage.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePending = resolve;
+ }),
+ );
+ const hook = renderHook(({ source }) => useProviderAccountUsage(source, 'pi'), {
+ initialProps: { source: provider as ProviderView | undefined },
+ });
+ hook.rerender({ source: undefined });
+ await act(async () => resolvePending(ready));
+ expect(hook.result.current.supported).toBe(false);
+ expect(hook.result.current.result).toBeNull();
+ expect(hook.result.current.busy).toBe(false);
+});
diff --git a/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts b/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts
index 3bfd91cb54..8a12317372 100644
--- a/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts
@@ -3,8 +3,8 @@
*
* 与订阅卡的 useProviderSubscriptionCard 互补:那边读 OAuth 订阅配额,这边经
* PROVIDER_ACCOUNT_USAGE 读供应商自己的账户接口。挂载时拉一次,之后每 60s 静默
- * 刷新一次(main 侧缓存优先 + 节流,重复轮询不会放大上游请求);失败不轮询重试,
- * 重挂载即重试。不支持(unsupported)时 supported=false,模块不渲染。
+ * 刷新一次(main 侧缓存优先 + 节流),失败同样在后续轮询重试。
+ * 结果绑定连接、引擎和接入地址;切换身份或停用查询时不返回旧快照。
*
* `agent` 用于会话场景(输入框 chip):同一供应商各引擎可用不同账户的独立密钥,
* 传入会话所在引擎才能对准当前会话实际消耗的账户;设置页供应商级视图不传。
@@ -14,7 +14,10 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import type { AgentKind, ProviderView } from '@cindy/model-providers';
-import type { ProviderAccountUsageResult } from '../../shared/providerAccountUsage';
+import {
+ PROVIDER_ACCOUNT_USAGE_AGENTS,
+ type ProviderAccountUsageResult,
+} from '../../shared/providerAccountUsage';
import {
hasDeepSeekOfficialRouteView,
isZhipuCodingPlanProviderView,
@@ -35,33 +38,54 @@ export function useProviderAccountUsage(
agent?: AgentKind,
): ProviderAccountUsageState {
const supported =
- !!provider
- && provider.auth?.method !== 'oauth'
- && (hasDeepSeekOfficialRouteView(provider) || isZhipuCodingPlanProviderView(provider));
- const [result, setResult] = useState<ProviderAccountUsageResult | null>(null);
- const [busy, setBusy] = useState(false);
+ !!provider &&
+ provider.auth?.method !== 'oauth' &&
+ (hasDeepSeekOfficialRouteView(provider) || isZhipuCodingPlanProviderView(provider));
+ const identity = JSON.stringify([
+ provider?.id,
+ agent,
+ provider?.auth?.method,
+ (agent ? [agent] : PROVIDER_ACCOUNT_USAGE_AGENTS).map(
+ (runtime) => provider?.routing[runtime]?.upstream,
+ ),
+ ]);
+ const [state, setState] = useState<{
+ identity: string;
+ result: ProviderAccountUsageResult | null;
+ busy: boolean;
+ }>({ identity, result: null, busy: false });
const requestId = useRef(0);
const load = useCallback(
async (forceRefresh: boolean) => {
- if (!provider?.id) return;
+ if (!supported || !provider?.id) return;
const id = ++requestId.current;
- setBusy(true);
+ setState((previous) => ({
+ identity,
+ result: previous.identity === identity ? previous.result : null,
+ busy: true,
+ }));
try {
const next = await window.electronAPI.maker.fetchProviderAccountUsage({
providerId: provider.id,
forceRefresh,
...(agent ? { agent } : {}),
});
- if (id === requestId.current) setResult(next);
+ if (id === requestId.current) setState({ identity, result: next, busy: false });
} catch {
- // IPC 层异常(不该发生)按未知失败处理,保留已有快照。
- if (id === requestId.current) setResult(null);
- } finally {
- if (id === requestId.current) setBusy(false);
+ // IPC 异常也结束等待;只保留同一查询身份的已有快照。
+ if (id === requestId.current)
+ setState((previous) => ({
+ identity,
+ result:
+ previous.identity === identity && previous.result?.status === 'ready'
+ ? { ...previous.result, stale: true, error: 'unknown' }
+ : { status: 'unavailable', error: 'unknown' },
+ busy: false,
+ }));
}
},
- [provider?.id, agent],
+ [provider?.id, agent, identity, supported],
);
useEffect(() => {
@@ -69,18 +93,17 @@ export function useProviderAccountUsage(
void load(false);
// 余额/窗口会随使用变化,挂载期间低频静默刷新(main 缓存优先,不会放大上游请求)。
const timer = window.setInterval(() => void load(false), REFRESH_INTERVAL_MS);
- return () => window.clearInterval(timer);
+ return () => {
+ window.clearInterval(timer);
+ // 停用、切换或卸载后,迟到响应不得再提交。
+ requestId.current += 1;
+ };
}, [supported, provider?.id, load]);
- // 换供应商即清空:旧连接的余额绝不能短暂挂在新连接的卡片下。
- useEffect(() => {
- setResult(null);
- }, [provider?.id]);
-
return {
supported,
- result,
- busy,
+ result: supported && state.identity === identity ? state.result : null,
+ busy: supported && state.identity === identity && state.busy,
refresh: () => void load(true),
};
}