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): read enterprise Cindy AI quota through Model Access

qianbod1af5fad4cea
diff --git a/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts b/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts
new file mode 100644
index 0000000000..34d1e9d9ed
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/organizationAccountUsage.test.ts
@@ -0,0 +1,26 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+const fetch = vi.hoisted(() => vi.fn());
+vi.mock('../../serverApiClient.js', () => ({ serverApiFetch: fetch, ServerApiError: class extends Error { constructor(public code: string, public statusCode: number) { super(code); } } }));
+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://models.example.test' }));
+import { ServerApiError } from '../../serverApiClient.js';
+import { readOrganizationAccountUsage } from '../organizationAccountUsage';
+const valid = { spend: 12, maxBudget: 100, currency: 'CNY', budgetResetAt: '2026-11-01T00:00:00Z', todaySpend: null };
+beforeEach(() => { fetch.mockReset().mockResolvedValue(valid); });
+describe('organization account usage', () => {
+ it('uses authenticated Model Access and preserves the gateway currency', async () => {
+ expect(await readOrganizationAccountUsage()).toMatchObject(valid);
+ expect(fetch).toHaveBeenCalledWith('/api/model-access/quota', expect.objectContaining({ redactErrorDetails: true, timeoutMs: 8000 }));
+ });
+ it.each([[404, 'NOT_FOUND'], [501, 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED']])('allows legacy fallback only for an unavailable capability', async (status, code) => {
+ fetch.mockRejectedValue(new ServerApiError(code, status, 'safe'));
+ expect(await readOrganizationAccountUsage()).toBeUndefined();
+ });
+ it.each([401, 403, 429, 500, 503])('never falls back after status %s', async status => {
+ fetch.mockRejectedValue(new ServerApiError('ERROR', status, 'safe'));
+ expect(await readOrganizationAccountUsage()).toBeNull();
+ });
+ it.each([{ ...valid, spend: NaN }, { ...valid, currency: 'unknown' }, { ...valid, maxBudget: null }])('does not invent a finite quota for malformed or unlimited data', async data => {
+ fetch.mockResolvedValue(data);
+ expect(await readOrganizationAccountUsage()).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
new file mode 100644
index 0000000000..fe571dc5a6
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts
@@ -0,0 +1,61 @@
+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' } },
+ managed: vi.fn(), outbound: vi.fn(),
+}));
+vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } }));
+vi.mock('../../authManager', () => ({ getAuthState: () => mocks.auth }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({ tapWindowBroadcast: vi.fn() }));
+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('../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(() => {
+ vi.resetModules(); vi.useFakeTimers(); vi.clearAllMocks();
+ mocks.auth = { mode: 'cloud', dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } };
+ mocks.managed.mockResolvedValue(quota);
+ mocks.outbound.mockResolvedValue({ ok: true, json: async () => ({ spend: 2, max_budget: 20, results: [] }) });
+});
+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+describe('Cindy AI enterprise quota refresh', () => {
+ it('publishes server quota without calling LiteLLM APIs on an inference gateway', async () => {
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);
+ expect(mocks.outbound).not.toHaveBeenCalled();
+ });
+ it('preserves legacy Nova quota reads when the server capability is unsupported', async () => {
+ mocks.managed.mockResolvedValue(undefined);
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(api.readClaudeAccountUsageSnapshot()).toMatchObject({ spend: 2, maxBudget: 20 });
+ expect(mocks.outbound).toHaveBeenCalledTimes(2);
+ });
+ it('does not query legacy credentials on managed-query errors', async () => {
+ mocks.managed.mockResolvedValue(null);
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ expect(mocks.outbound).not.toHaveBeenCalled();
+ });
+ it('drops an in-flight response when switching enterprise accounts', async () => {
+ let resolve!: (value: unknown) => void;
+ mocks.managed.mockImplementationOnce(() => new Promise(r => { resolve = r; }));
+ const api = await import('../claudeAccountUsage');
+ const pending = api.triggerClaudeAccountUsageRefresh(true);
+ mocks.auth = { ...mocks.auth, dataOwnerId: 'owner-b' };
+ resolve(quota); await pending;
+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();
+ });
+ it('keeps local gateway reads on the original endpoint', async () => {
+ mocks.auth.mode = 'local';
+ const api = await import('../claudeAccountUsage');
+ await api.triggerClaudeAccountUsageRefresh(true);
+ expect(mocks.managed).not.toHaveBeenCalled();
+ expect(mocks.outbound).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 43f26d7bd0..4c0718286d 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -1,3 +1,4 @@
+import { readOrganizationAccountUsage } from './organizationAccountUsage.js';
/**
* claudeAccountUsage — Claude 账号配额 (LiteLLM spend / max_budget) 拉取与广播。
*
@@ -203,6 +204,13 @@ function resolveDailyActivitySpend(activity: LiteLlmDailyActivity): { todaySpend
}
async function fetchOnce(authenticatedUserId?: string): Promise<ClaudeAccountUsageSnapshot | null> {
+ // Enterprise AIGateway inference endpoints need not expose LiteLLM management APIs.
+ // Resolve the signed-in member's tenant in Model Access. Nova/older servers keep
+ // the existing direct query; authorization/network errors never trigger fallback.
+ if (getAuthState().mode === 'cloud') {
+ const managed = await readOrganizationAccountUsage();
+ if (managed !== undefined) return managed;
+ }
// 币种优先取账号目录声明。取不到时**不放弃整个快照**,回落本地账本币种:
// 手填 XD key 是明确支持的兜底流程(Model Access 处于 disabled / failed 时),那时没有
// 目录可推导,若直接 return 会让这些会话永久看不到账号配额 —— 比"币种按账本回落"更糟。
diff --git a/apps/desktop/src/main/usage/organizationAccountUsage.ts b/apps/desktop/src/main/usage/organizationAccountUsage.ts
new file mode 100644
index 0000000000..9f9da5bb85
--- /dev/null
+++ b/apps/desktop/src/main/usage/organizationAccountUsage.ts
@@ -0,0 +1,25 @@
+import { serverApiFetch, ServerApiError } from '../serverApiClient.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import type { ClaudeAccountUsageSnapshot } from './claudeAccountUsage.js';
+
+/** undefined means legacy gateway/server; null means unavailable, with no credential fallback. */
+export async function readOrganizationAccountUsage(): Promise<ClaudeAccountUsageSnapshot | null | undefined> {
+ try {
+ const data = await serverApiFetch<unknown>('/api/model-access/quota', {
+ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
+ timeoutMs: 8000, redactErrorDetails: true,
+ });
+ if (!data || typeof data !== 'object') return null;
+ const row = data as Record<string, unknown>;
+ if (typeof row.spend !== 'number' || !Number.isFinite(row.spend) || row.spend < 0 ||
+ typeof row.maxBudget !== 'number' || !Number.isFinite(row.maxBudget) || row.maxBudget <= 0 ||
+ (row.currency !== 'CNY' && row.currency !== 'USD') ||
+ (row.budgetResetAt !== null && (typeof row.budgetResetAt !== 'string' || !Number.isFinite(Date.parse(row.budgetResetAt))))) return null;
+ return { spend: row.spend, maxBudget: row.maxBudget, currency: row.currency,
+ budgetResetAt: row.budgetResetAt, todaySpend: null, fetchedAt: Date.now() };
+ } catch (error) {
+ if (error instanceof ServerApiError && (error.statusCode === 404 ||
+ (error.statusCode === 501 && error.code === 'MODEL_ACCESS_QUOTA_NOT_SUPPORTED'))) return undefined;
+ return null;
+ }
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 8379f8b4de..247be7fad9 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1749,3 +1749,13 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca
当前 PC 窗口的停靠位置不在此声明投影内,有面板只报告存在,无面板沿用 PC 文案。
旧 Host 缺字段时新手机仅显示原有 Version 与资源 Identifier,说明其余数据未提供;旧控制端忽略新增字段。
服务端、relay、协议版本及原生 fingerprint 均不变。
+
+### Cindy AI 企业周期配额
+
+云端组织账号优先通过 Model Access `GET /api/model-access/quota` 查询本人周期配额,
+不再假定推理入口暴露 LiteLLM 管理 API。返回 spend/maxBudget/budgetResetAt/currency;
+沿用现有 account-usage IPC 和账号作用域缓存,所以设置卡片与任务用量提示使用相同来源。
+服务端尚未提供接口(404),或明确返回 501/MODEL_ACCESS_QUOTA_NOT_SUPPORTED(Nova),
+才使用原有网关查询。鉴权失败、上游故障或响应无效均显示不可用,不回退或借用其他身份数据。
+本接口尚无当日统计,todaySpend 为 null;未设周期上限时不伪造有限配额。
+本地手填网关和个人计费路径保持原协议。无新环境变量或数据库变更。