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。

feat(desktop): API Key 供应商余额卡——DeepSeek 余额与智谱套餐用量入口

JupiterTheWarlock874b6485384c
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
new file mode 100644
index 0000000000..12304af474
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/provider-account-usage.test.ts
@@ -0,0 +1,291 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentKind, Provider } from '@cindy/model-providers';
+
+import {
+ isZhipuCodingPlanProvider,
+ parseDeepSeekAccountUsage,
+ readProviderAccountUsage,
+ resetProviderAccountUsageForTest,
+ resolveProviderAccountUsage,
+ setAccountUsageFetch,
+ setAccountUsageKeyReader,
+ setAccountUsageNow,
+ setAccountUsageOwnerStampReader,
+ setAccountUsageProviderReader,
+} from '../provider-account-usage.js';
+
+function mkProvider(overrides: Partial<Provider> = {}): Provider {
+ return {
+ id: 'deepseek',
+ name: 'DeepSeek',
+ source: 'user',
+ agents: ['claude-code', 'codex', 'pi'],
+ auth: { method: 'apiKey' },
+ routing: {
+ 'claude-code': { upstream: 'https://api.deepseek.com/anthropic', authStrategy: 'api-key-header' as const },
+ codex: { upstream: 'https://api.deepseek.com', authStrategy: 'api-key-header' as const },
+ pi: { upstream: 'https://api.deepseek.com', authStrategy: 'api-key-header' as const },
+ },
+ models: {},
+ ...overrides,
+ } as Provider;
+}
+
+const DEEPSEEK_BALANCE = {
+ is_available: true,
+ balance_infos: [
+ {
+ currency: 'CNY',
+ total_balance: '194.06',
+ granted_balance: '0.00',
+ topped_up_balance: '194.06',
+ },
+ ],
+};
+
+function jsonRes(body: unknown, status = 200, headers: Record<string, string> = {}) {
+ return new Response(JSON.stringify(body), { status, headers });
+}
+
+let nowMs = 1_000_000;
+
+describe('parseDeepSeekAccountUsage', () => {
+ it('keeps all documented balance fields and currencies', () => {
+ const snapshot = parseDeepSeekAccountUsage(
+ {
+ is_available: true,
+ balance_infos: [
+ { currency: 'CNY', total_balance: '12.34', granted_balance: '2.00', topped_up_balance: '10.34' },
+ { currency: 'USD', total_balance: '1.25', granted_balance: '0.25', topped_up_balance: '1.00' },
+ ],
+ },
+ 42,
+ );
+ expect(snapshot).toEqual({
+ kind: 'deepseek-balance',
+ isAvailable: true,
+ fetchedAt: 42,
+ balances: [
+ { currency: 'CNY', totalBalance: '12.34', grantedBalance: '2.00', toppedUpBalance: '10.34' },
+ { currency: 'USD', totalBalance: '1.25', grantedBalance: '0.25', toppedUpBalance: '1.00' },
+ ],
+ });
+ });
+
+ it('rejects malformed payloads', () => {
+ expect(() => parseDeepSeekAccountUsage({ is_available: true }, 1)).toThrow(/invalid/);
+ expect(() =>
+ parseDeepSeekAccountUsage({ is_available: true, balance_infos: [{}] }, 1),
+ ).toThrow(/invalid/);
+ expect(() =>
+ parseDeepSeekAccountUsage(
+ { is_available: 'yes', balance_infos: [] },
+ 1,
+ ),
+ ).toThrow(/invalid/);
+ // 非十进制字符串(如科学计数 / 注入)不得进入展示层。
+ expect(() =>
+ parseDeepSeekAccountUsage(
+ {
+ is_available: true,
+ balance_infos: [{ currency: 'CNY', total_balance: '1e3', granted_balance: '0', topped_up_balance: '0' }],
+ },
+ 1,
+ ),
+ ).toThrow(/invalid/);
+ });
+});
+
+describe('resolveProviderAccountUsage', () => {
+ beforeEach(() => {
+ resetProviderAccountUsageForTest();
+ });
+
+ it('claims official deepseek origin api-key providers with any runtime key', () => {
+ setAccountUsageProviderReader(() => mkProvider());
+ setAccountUsageKeyReader((providerId, agent) =>
+ providerId === 'deepseek' && agent === 'claude-code' ? 'sk-test' : null,
+ );
+ expect(resolveProviderAccountUsage('deepseek')).toMatchObject({
+ integrationId: 'deepseek-balance-v1',
+ endpoint: 'https://api.deepseek.com/user/balance',
+ agent: 'claude-code',
+ key: 'sk-test',
+ });
+ });
+
+ it('falls through to a later runtime when the first has no key', () => {
+ setAccountUsageProviderReader(() => mkProvider());
+ setAccountUsageKeyReader((_id, agent) => (agent === 'pi' ? 'sk-pi' : null));
+ expect(resolveProviderAccountUsage('deepseek')?.agent).toBe('pi');
+ });
+
+ it('never claims proxied base URLs or oauth providers', () => {
+ setAccountUsageProviderReader(() =>
+ mkProvider({
+ routing: { 'claude-code': { upstream: 'https://proxy.example/v1', authStrategy: 'api-key-header' as const } },
+ }),
+ );
+ setAccountUsageKeyReader(() => 'sk-test');
+ expect(resolveProviderAccountUsage('deepseek')).toBeNull();
+
+ setAccountUsageProviderReader(() =>
+ mkProvider({ auth: { method: 'oauth' as const } }),
+ );
+ expect(resolveProviderAccountUsage('deepseek')).toBeNull();
+ });
+
+ it('rejects lookalike hosts (exact origin match only)', () => {
+ setAccountUsageProviderReader(() =>
+ mkProvider({
+ routing: { 'claude-code': { upstream: 'https://api.deepseek.com.evil.com/anthropic', authStrategy: 'api-key-header' as const } },
+ }),
+ );
+ setAccountUsageKeyReader(() => 'sk-test');
+ expect(resolveProviderAccountUsage('deepseek')).toBeNull();
+ });
+});
+
+describe('isZhipuCodingPlanProvider', () => {
+ beforeEach(() => resetProviderAccountUsageForTest());
+
+ it('detects coding-plan endpoints and the builtin preset id, not pay-as-you-go', () => {
+ const coding = mkProvider({
+ id: 'glm-coding-plan',
+ routing: {
+ 'claude-code': { upstream: 'https://open.bigmodel.cn/api/anthropic', authStrategy: 'api-key-header' as const },
+ codex: { upstream: 'https://open.bigmodel.cn/api/coding/paas/v4', authStrategy: 'api-key-header' as const },
+ },
+ });
+ expect(isZhipuCodingPlanProvider(coding)).toBe(true);
+ expect(isZhipuCodingPlanProvider(mkProvider({ id: 'zhipu-coding-plan-cn' }))).toBe(true);
+ const payg = mkProvider({
+ id: 'zhipu-glm',
+ routing: { codex: { upstream: 'https://open.bigmodel.cn/api/paas/v4', authStrategy: 'api-key-header' as const } },
+ });
+ expect(isZhipuCodingPlanProvider(payg)).toBe(false);
+ expect(isZhipuCodingPlanProvider(undefined)).toBe(false);
+ });
+});
+
+describe('readProviderAccountUsage', () => {
+ beforeEach(() => {
+ resetProviderAccountUsageForTest();
+ nowMs = 1_000_000;
+ setAccountUsageNow(() => nowMs);
+ setAccountUsageOwnerStampReader(() => ({ dataOwnerId: 'owner-a', generation: 1 }));
+ setAccountUsageProviderReader(() => mkProvider());
+ setAccountUsageKeyReader(() => 'sk-test');
+ });
+
+ afterEach(() => {
+ resetProviderAccountUsageForTest();
+ vi.restoreAllMocks();
+ });
+
+ it('returns unsupported when no official route exists', async () => {
+ setAccountUsageProviderReader(() =>
+ mkProvider({ routing: { 'claude-code': { upstream: 'https://proxy.example/v1', authStrategy: 'api-key-header' as const } } }),
+ );
+ await expect(
+ readProviderAccountUsage({ providerId: 'deepseek' }),
+ ).resolves.toEqual({ status: 'unsupported' });
+ });
+
+ it('reports no-credentials when the official route exists without a key', async () => {
+ setAccountUsageKeyReader(() => null);
+ await expect(
+ readProviderAccountUsage({ providerId: 'deepseek' }),
+ ).resolves.toEqual({ status: 'unavailable', error: 'no-credentials' });
+ });
+
+ it('fetches with bearer auth and returns a ready snapshot', async () => {
+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ expect(String(input)).toBe('https://api.deepseek.com/user/balance');
+ expect((init?.headers as Record<string, string>).Authorization).toBe('Bearer sk-test');
+ return jsonRes(DEEPSEEK_BALANCE);
+ });
+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);
+ const result = await readProviderAccountUsage({ providerId: 'deepseek' });
+ expect(result).toEqual({
+ status: 'ready',
+ stale: false,
+ snapshot: {
+ kind: 'deepseek-balance',
+ isAvailable: true,
+ balances: [
+ { currency: 'CNY', totalBalance: '194.06', grantedBalance: '0.00', toppedUpBalance: '194.06' },
+ ],
+ fetchedAt: nowMs,
+ },
+ });
+ });
+
+ it('serves the cached snapshot inside the TTL and refetches after expiry', async () => {
+ const fetchMock = vi.fn(async () => jsonRes(DEEPSEEK_BALANCE));
+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);
+ await readProviderAccountUsage({ providerId: 'deepseek' });
+ await readProviderAccountUsage({ providerId: 'deepseek' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ nowMs += 6 * 60_000;
+ await readProviderAccountUsage({ providerId: 'deepseek' });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('maps upstream failures to error codes and keeps stale snapshots', async () => {
+ let calls = 0;
+ const fetchMock = vi.fn(async () => {
+ calls += 1;
+ if (calls === 1) return jsonRes(DEEPSEEK_BALANCE);
+ return jsonRes({ error: 'bad key' }, 401);
+ });
+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);
+ const first = await readProviderAccountUsage({ providerId: 'deepseek' });
+ expect(first.status).toBe('ready');
+ nowMs += 6 * 60_000;
+ const second = await readProviderAccountUsage({ providerId: 'deepseek' });
+ expect(second).toMatchObject({ status: 'ready', stale: true, error: 'auth' });
+ expect((second as { snapshot: { balances: unknown[] } }).snapshot.balances).toHaveLength(1);
+ });
+
+ it('rate-limited manual refresh reports throttled', async () => {
+ const fetchMock = vi.fn(async () => jsonRes({}, 429, { 'retry-after': '30' }));
+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);
+ const result = await readProviderAccountUsage({ providerId: 'deepseek', forceRefresh: true });
+ expect(result).toMatchObject({ status: 'unavailable', error: 'throttled' });
+ });
+
+ it('invalidates the cache when the owner stamp changes', async () => {
+ const fetchMock = vi.fn(async () => jsonRes(DEEPSEEK_BALANCE));
+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);
+ await readProviderAccountUsage({ providerId: 'deepseek' });
+ setAccountUsageOwnerStampReader(() => ({ dataOwnerId: 'owner-b', generation: 2 }));
+ await readProviderAccountUsage({ providerId: 'deepseek' });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('classifies invalid JSON as invalid-response', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response('<html>gateway login</html>', { status: 200 }),
+ );
+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);
+ await expect(
+ readProviderAccountUsage({ providerId: 'deepseek' }),
+ ).resolves.toMatchObject({ status: 'unavailable', error: 'invalid-response' });
+ });
+});
+
+describe('provider runtime key order', () => {
+ it('queries claude-code before codex before pi', async () => {
+ resetProviderAccountUsageForTest();
+ const seen: AgentKind[] = [];
+ setAccountUsageProviderReader(() => mkProvider());
+ setAccountUsageKeyReader((_id, agent) => {
+ seen.push(agent);
+ return agent === 'codex' ? 'sk-codex' : null;
+ });
+ expect(resolveProviderAccountUsage('deepseek')?.agent).toBe('codex');
+ expect(seen).toEqual(['claude-code', 'codex']);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/provider-account-usage.ts b/apps/desktop/src/main/maker-host/provider-account-usage.ts
new file mode 100644
index 0000000000..7358e150d1
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/provider-account-usage.ts
@@ -0,0 +1,352 @@
+/**
+ * provider-account-usage —— API Key 供应商账户余额查询(设置页余额卡的数据源)。
+ *
+ * 设计要点:
+ * - **端点钉死在 main**:integration 表是硬编码的官方端点(deepseek →
+ * `https://api.deepseek.com/user/balance`)。renderer 只传 providerId,不传 URL;
+ * key 只发给官方端点,永远不会发到用户配置的第三方代理。
+ * - **按官方 origin 认领**:只有当供应商某个 runtime 的 baseUrl origin 与官方端点
+ * origin 一致且鉴权方式是 apiKey 时才启用。走代理 / 自定义域名的连接不查(key 属于
+ * 代理,不属于官方账户);这也让官方预设创建的老连接无需迁移就能直接生效。
+ * - **key 读取器注入**:同 provider-diagnostics 的 setDiagnosticsKeyReader 模式,模块
+ * 不直接 import safeStorage(maker-host 不触电 Electron),host 注册期接通。
+ * - 查询型结果:失败不 throw,映射为 ProviderAccountUsageError(规则 13 例外条款)。
+ * - 缓存:TTL 5 分钟内存缓存;手动刷新受 15s 节流;账号切换(owner / generation 变化)
+ * 整体失效。缓存键含 providerId + agent,换 runtime 配置不串数据。
+ */
+
+import type { AgentKind, Provider } from '@cindy/model-providers';
+
+import {
+ PROVIDER_ACCOUNT_USAGE_AGENTS,
+ type DeepSeekAccountUsageSnapshot,
+ type ProviderAccountUsageError,
+ type ProviderAccountUsageRequest,
+ type ProviderAccountUsageResult,
+} from '../../shared/providerAccountUsage.js';
+import { createMakerLogger } from './logger-adapter.js';
+
+const log = createMakerLogger('provider-account-usage');
+
+const MAX_RESPONSE_BYTES = 64 * 1024;
+const REQUEST_TIMEOUT_MS = 10_000;
+const CACHE_TTL_MS = 5 * 60_000;
+const MIN_MANUAL_REFRESH_INTERVAL_MS = 15_000;
+const MAX_RETRY_AFTER_MS = 60 * 60_000;
+
+/** 官方账户接口清单。端点是唯一事实源,不从目录 / 用户配置推导。 */
+const INTEGRATIONS = {
+ 'deepseek-balance-v1': {
+ origin: 'https://api.deepseek.com',
+ endpoint: 'https://api.deepseek.com/user/balance',
+ },
+} as const;
+
+export type ProviderAccountUsageIntegrationId = keyof typeof INTEGRATIONS;
+
+/** 该供应商是否命中智谱 GLM Coding Plan 的官方接入端点(设置页给「查看套餐用量」入口用)。 */
+export function isZhipuCodingPlanProvider(provider: Provider | undefined | null): boolean {
+ if (!provider) return false;
+ if (provider.id === 'zhipu-coding-plan-cn') return true;
+ return Object.values(provider.routing).some((route) => {
+ const upstream = route?.upstream;
+ if (!upstream) return false;
+ return (
+ upstream === 'https://open.bigmodel.cn/api/anthropic'
+ || upstream.startsWith('https://open.bigmodel.cn/api/coding/')
+ );
+ });
+}
+
+export interface ProviderAccountUsageResolution {
+ integrationId: ProviderAccountUsageIntegrationId;
+ endpoint: string;
+ /** key 所属 runtime;与缓存键一起区分不同 runtime 的 key。 */
+ agent: AgentKind;
+ key: string;
+}
+
+type ProviderReader = (providerId: string) => Provider | undefined;
+type KeyReader = (providerId: string, agent: AgentKind) => string | null;
+type OwnerStampReader = () => { dataOwnerId: string | null; generation: number };
+
+let providerReader: ProviderReader = () => undefined;
+let keyReader: KeyReader = () => null;
+let ownerStampReader: OwnerStampReader = () => ({ dataOwnerId: null, generation: 0 });
+let fetchImpl: typeof fetch = globalThis.fetch;
+
+/** host 注册期接通真实目录读取(active-catalog)。 */
+export function setAccountUsageProviderReader(reader: ProviderReader): void {
+ providerReader = reader;
+}
+
+/** host 注册期接通真实 safeStorage key 读取(provider_key_<id>_<agent>)。 */
+export function setAccountUsageKeyReader(reader: KeyReader): void {
+ keyReader = reader;
+}
+
+/** host 注册期接通账号身份戳(缓存隔离用)。 */
+export function setAccountUsageOwnerStampReader(reader: OwnerStampReader): void {
+ ownerStampReader = reader;
+}
+
+/** 测试注入 fetch。 */
+export function setAccountUsageFetch(impl: typeof fetch): void {
+ fetchImpl = impl;
+}
+
+/** 测试注入时钟。 */
+export let accountUsageNow: () => number = Date.now;
+
+export function setAccountUsageNow(now: () => number): void {
+ accountUsageNow = now;
+}
+
+interface CacheRecord {
+ snapshot?: DeepSeekAccountUsageSnapshot;
+ expiresAt: number;
+ lastAttemptAt: number;
+ lastError?: ProviderAccountUsageError;
+ retryAt: number;
+}
+
+const cache = new Map<string, CacheRecord>();
+
+class AccountUsageRequestError extends Error {
+ constructor(
+ readonly code: ProviderAccountUsageError,
+ readonly retryAt?: number,
+ ) {
+ super(code);
+ }
+}
+
+function isDecimalString(value: unknown): value is string {
+ return typeof value === 'string' && /^-?\d+(?:\.\d+)?$/.test(value);
+}
+
+/** 解析并校验 DeepSeek `/user/balance` 响应;字段缺失 / 形状不符直接抛错(invalid-response)。 */
+export function parseDeepSeekAccountUsage(
+ value: unknown,
+ fetchedAt: number,
+): DeepSeekAccountUsageSnapshot {
+ const fail = (): never => {
+ throw new Error('invalid DeepSeek balance response');
+ };
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return fail();
+ const payload = value as Record<string, unknown>;
+ if (typeof payload.is_available !== 'boolean' || !Array.isArray(payload.balance_infos)) {
+ return fail();
+ }
+ const balances = payload.balance_infos.map((candidate) => {
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return fail();
+ const line = candidate as Record<string, unknown>;
+ if (
+ typeof line.currency !== 'string'
+ || line.currency.trim().length === 0
+ || line.currency.length > 16
+ || !isDecimalString(line.total_balance)
+ || !isDecimalString(line.granted_balance)
+ || !isDecimalString(line.topped_up_balance)
+ ) {
+ return fail();
+ }
+ return {
+ currency: line.currency,
+ totalBalance: line.total_balance,
+ grantedBalance: line.granted_balance,
+ toppedUpBalance: line.topped_up_balance,
+ };
+ });
+ return { kind: 'deepseek-balance', isAvailable: payload.is_available, balances, fetchedAt };
+}
+
+/**
+ * 认领规则:apiKey 鉴权 + 某 runtime 的 baseUrl origin 与官方端点 origin 全等。
+ * https 之外一律不认领(规则同 provider-route 的上游判定,不做子串包含)。
+ */
+export function resolveProviderAccountUsage(
+ providerId: string,
+): ProviderAccountUsageResolution | null {
+ const provider = providerReader(providerId);
+ if (!provider || provider.auth.method !== 'apiKey') return null;
+ for (const [integrationId, integration] of Object.entries(INTEGRATIONS) as [
+ ProviderAccountUsageIntegrationId,
+ (typeof INTEGRATIONS)[ProviderAccountUsageIntegrationId],
+ ][]) {
+ for (const agent of PROVIDER_ACCOUNT_USAGE_AGENTS) {
+ const upstream = provider.routing[agent]?.upstream;
+ if (!upstream) continue;
+ let matches = false;
+ try {
+ const url = new URL(upstream);
+ matches = url.protocol === 'https:' && url.origin === integration.origin;
+ } catch {
+ matches = false;
+ }
+ if (!matches) continue;
+ const key = keyReader(providerId, agent)?.trim();
+ if (!key) continue;
+ return { integrationId, endpoint: integration.endpoint, agent, key };
+ }
+ }
+ return null;
+}
+
+/** key 归属该 provider 的哪个 runtime 都不关键;余额接口对全账号生效,取任一可用 key。 */
+export function providerAccountUsageSupported(providerId: string): boolean {
+ const provider = providerReader(providerId);
+ if (!provider || provider.auth.method !== 'apiKey') return false;
+ return Object.entries(INTEGRATIONS).some(([, integration]) =>
+ PROVIDER_ACCOUNT_USAGE_AGENTS.some((agent) => {
+ const upstream = provider.routing[agent]?.upstream;
+ if (!upstream) return false;
+ try {
+ return new URL(upstream).protocol === 'https:' && new URL(upstream).origin === integration.origin;
+ } catch {
+ return false;
+ }
+ }),
+ );
+}
+
+function mapHttpStatusToError(status: number): ProviderAccountUsageError | null {
+ if (status === 401 || status === 403) return 'auth';
+ if (status === 429) return 'rate-limited';
+ if (status >= 500) return 'server';
+ return null;
+}
+
+function parseRetryAfterMs(header: string | null, now: number): number | undefined {
+ if (!header) return undefined;
+ const seconds = Number(header);
+ if (!Number.isFinite(seconds) || seconds <= 0) return undefined;
+ return now + Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);
+}
+
+async function fetchDeepSeekBalance(
+ resolution: ProviderAccountUsageResolution,
+): Promise<DeepSeekAccountUsageSnapshot> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+ try {
+ const response = await fetchImpl(resolution.endpoint, {
+ headers: { Authorization: `Bearer ${resolution.key}` },
+ signal: controller.signal,
+ });
+ const retryAfterMs = parseRetryAfterMs(response.headers.get('retry-after'), accountUsageNow());
+ const mapped = mapHttpStatusToError(response.status);
+ if (mapped) throw new AccountUsageRequestError(mapped, retryAfterMs);
+ const text = await response.text();
+ if (text.length > MAX_RESPONSE_BYTES) {
+ throw new AccountUsageRequestError('invalid-response');
+ }
+ let payload: unknown;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ throw new AccountUsageRequestError('invalid-response');
+ }
+ try {
+ return parseDeepSeekAccountUsage(payload, accountUsageNow());
+ } catch {
+ throw new AccountUsageRequestError('invalid-response');
+ }
+ } catch (err) {
+ if (err instanceof AccountUsageRequestError) throw err;
+ if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError')) {
+ throw new AccountUsageRequestError('network');
+ }
+ throw new AccountUsageRequestError('network');
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/** 查询入口:unsupported / unavailable / ready 三态。网络失败时回落过期快照(stale)。 */
+export async function readProviderAccountUsage(
+ request: ProviderAccountUsageRequest,
+): Promise<ProviderAccountUsageResult> {
+ const ownerStamp = ownerStampReader();
+ const resolution = resolveProviderAccountUsage(request.providerId);
+ if (!resolution) {
+ // 没认领到官方端点,或 key 读不到。区分「本来就没有接口」与「有接口但 key 缺失」。
+ if (providerAccountUsageSupported(request.providerId)) {
+ return { status: 'unavailable', error: 'no-credentials' };
+ }
+ return { status: 'unsupported' };
+ }
+ const cacheKey = `${ownerStamp.dataOwnerId ?? 'local'}:${ownerStamp.generation}:${request.providerId}:${resolution.integrationId}`;
+ const now = accountUsageNow();
+ const record = cache.get(cacheKey);
+ const manualRefreshBlocked =
+ request.forceRefresh === true
+ && record !== undefined
+ && now - record.lastAttemptAt < MIN_MANUAL_REFRESH_INTERVAL_MS;
+ if (manualRefreshBlocked && record.snapshot && record.expiresAt > now) {
+ return { status: 'ready', snapshot: record.snapshot, stale: false };
+ }
+ if (
+ !request.forceRefresh
+ && record?.snapshot
+ && record.expiresAt > now
+ && record.lastError === undefined
+ ) {
+ return { status: 'ready', snapshot: record.snapshot, stale: false };
+ }
+ try {
+ const snapshot = await fetchDeepSeekBalance(resolution);
+ cache.set(cacheKey, {
+ snapshot,
+ expiresAt: accountUsageNow() + CACHE_TTL_MS,
+ lastAttemptAt: accountUsageNow(),
+ retryAt: 0,
+ });
+ return { status: 'ready', snapshot, stale: false };
+ } catch (err) {
+ const code = err instanceof AccountUsageRequestError ? err.code : 'unknown';
+ log.warn(
+ 'provider account usage fetch failed',
+ { providerId: request.providerId, integrationId: resolution.integrationId, code },
+ );
+ if (err instanceof AccountUsageRequestError && err.retryAt) {
+ cache.set(cacheKey, {
+ snapshot: record?.snapshot,
+ expiresAt: record?.expiresAt ?? 0,
+ lastAttemptAt: now,
+ lastError: code,
+ retryAt: err.retryAt,
+ });
+ } else {
+ cache.set(cacheKey, {
+ snapshot: record?.snapshot,
+ expiresAt: record?.expiresAt ?? 0,
+ lastAttemptAt: now,
+ lastError: code,
+ retryAt: 0,
+ });
+ }
+ if (
+ err instanceof AccountUsageRequestError
+ && err.code === 'rate-limited'
+ && request.forceRefresh
+ ) {
+ return { status: 'unavailable', error: 'throttled', retryAt: err.retryAt };
+ }
+ const fallback = record?.snapshot;
+ if (fallback) {
+ return { status: 'ready', snapshot: fallback, stale: true, error: code };
+ }
+ return { status: 'unavailable', error: code };
+ }
+}
+
+/** 测试辅助:清空缓存与注入重置。 */
+export function resetProviderAccountUsageForTest(): void {
+ cache.clear();
+ providerReader = () => undefined;
+ keyReader = () => null;
+ ownerStampReader = () => ({ dataOwnerId: null, generation: 0 });
+ fetchImpl = globalThis.fetch;
+ accountUsageNow = Date.now;
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 04df6efaca..da58dc1863 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -132,6 +132,7 @@ function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps
listPresets: () => [],
getModelCatalog: () => BUNDLED_CATALOG,
testConnection: vi.fn(async () => ({ ok: true, latencyMs: 1 })),
+ accountUsage: vi.fn(async (): Promise<import('../../../shared/providerAccountUsage.js').ProviderAccountUsageResult> => ({ status: 'unsupported' })),
fetchModels: vi.fn(async () => ({ ok: true, models: [{ id: 'm1', name: 'M1' }] })),
rediscoverModels: vi.fn(async () => null),
refreshBuiltinModels: vi.fn(async () => {}),
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index a1eb222ff2..ab71ce9272 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -605,6 +605,14 @@ export const MAKER_INVOKE = {
* renderer 需要 code 渲染分类文案与修复引导)。
*/
PROVIDER_TEST_CONNECTION: 'maker:provider:test-connection',
+ /**
+ * 供应商账户余额查询(API Key 计费连接的余额卡,见 maker-host/provider-account-usage)。
+ * 入参 ProviderAccountUsageRequest({providerId, forceRefresh?}),端点在 main 硬编码
+ * 官方清单里,renderer 不传 URL;返回查询型结构化结果 ProviderAccountUsageResult(规则 13
+ * 例外条款:renderer 需要 error 渲染分类文案与重试入口)。快照不含密钥材料;虽只读,
+ * 但会把该供应商已存 key 发往其官方端点,不进 device-link 白名单(口径同 test-connection)。
+ */
+ PROVIDER_ACCOUNT_USAGE: 'maker:provider:account-usage',
/**
* 供应商「获取模型列表」—— 用表单值(baseUrl / modelsUrl / key / headers 内存透传)GET
* 该供应商的列模型端点(见 maker-host/provider-model-fetch)。返回查询型结构化结果
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 4eb3df9cee..6ca6acfe3a 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -106,6 +106,10 @@ import type {
ProviderModelsFetchResult,
ProviderModelsFetchSpec,
} from '../maker-host/provider-model-fetch.js';
+import type {
+ ProviderAccountUsageRequest,
+ ProviderAccountUsageResult,
+} from '../../shared/providerAccountUsage.js';
import { MAKER_INVOKE, MAKER_PUSH } from './channels.js';
import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
@@ -331,6 +335,8 @@ export interface ProviderHandlerDeps {
getModelCatalog(): Pick<Catalog, 'modelRegistry' | 'presets'>;
/** 测试连接(生产 = testProviderConnection;单测注入 stub 不联网)。 */
testConnection(input: ProviderTestInput, signal?: AbortSignal): Promise<ProviderTestResult>;
+ /** 账户余额查询(生产 = readProviderAccountUsage;单测注入 stub 不联网)。 */
+ accountUsage(input: ProviderAccountUsageRequest): Promise<ProviderAccountUsageResult>;
/** 获取模型列表(生产 = fetchProviderModels;单测注入 stub 不联网)。 */
fetchModels(spec: ProviderModelsFetchSpec): Promise<ProviderModelsFetchResult>;
detectProvider?(spec: ProviderModelsFetchSpec, signal: AbortSignal): Promise<DeploymentDetectionResult>;
@@ -486,6 +492,15 @@ export interface ModelContextLimitView {
isCustomized: boolean;
}
+/** 校验 PROVIDER_ACCOUNT_USAGE 入参形状(确定性代码校验,非法直接 INVALID_PARAMS)。 */
+function parseAccountUsageInput(input: unknown): ProviderAccountUsageRequest | null {
+ if (!input || typeof input !== 'object') return null;
+ const i = input as Record<string, unknown>;
+ if (typeof i.providerId !== 'string' || i.providerId.length === 0) return null;
+ if (i.forceRefresh !== undefined && typeof i.forceRefresh !== 'boolean') return null;
+ return { providerId: i.providerId, forceRefresh: i.forceRefresh ?? undefined };
+}
+
/** 校验 PROVIDER_TEST_CONNECTION 入参形状(确定性代码校验,非法直接 INVALID_PARAMS)。 */
function parseTestInput(input: unknown): ProviderTestInput | null {
if (!input || typeof input !== 'object') return null;
@@ -2363,6 +2378,13 @@ export function registerProviderHandlers(
async (): Promise<{ presets: ProviderPreset[] }> => ({ presets: deps.listPresets() }),
);
+ // 账户余额查询:查询型结构化返回(同 test-connection 例外条款);仅网络/上游失败在结果 error 里,不抛。
+ registry.handle(MAKER_INVOKE.PROVIDER_ACCOUNT_USAGE, async (_event, input: unknown) => {
+ const parsed = parseAccountUsageInput(input);
+ if (!parsed) throwIpcError('INVALID_PARAMS', 'invalid account-usage input');
+ return deps.accountUsage(parsed);
+ });
+
// 测试连接:查询型结构化返回(规则 13 例外条款——renderer 需要 code 渲染分类文案)。
// 入参非法 / saved 解析失败(供应商不存在等)仍走 throwIpcError。
const connectionTests = new Map<ProviderOAuthRendererSender, { id: string; controller: AbortController }>();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 4649040908..7edc976aa0 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1186,6 +1186,12 @@ import { refreshAnthropicModelsFromProbe } from '../maker-host/model-discovery/a
import { refreshOpenAiMediaModels } from '../maker-host/model-discovery/openai-media.js';
import { refreshXaiMediaModels } from '../maker-host/model-discovery/xai-media.js';
import { testProviderConnection } from '../maker-host/provider-diagnostics.js';
+import {
+ readProviderAccountUsage,
+ setAccountUsageKeyReader,
+ setAccountUsageOwnerStampReader,
+ setAccountUsageProviderReader,
+} from '../maker-host/provider-account-usage.js';
import { fetchProviderModels, fetchSavedOAuthProviderModels } from '../maker-host/provider-model-fetch.js';
import { detectProviderDeployment } from '../maker-host/provider-detection.js';
import {
@@ -1220,6 +1226,7 @@ import {
} from '../maker-host/custom-provider-store.js';
import {
readCustomProviderHeadersForMutation,
+ readCustomProviderKey,
readCustomProviderKeyForMutation,
removeCustomProviderHeaders,
removeCustomProviderKey,
@@ -7219,6 +7226,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
userDataDir: app.getPath('userData'),
});
+ // 账户余额查询接线:目录读 active-catalog,key 与路由/诊断同源(provider_key_<id>_<agent>),
+ // 账号身份戳与订阅卡同源——换号后缓存整体失效。
+ setAccountUsageProviderReader((providerId) =>
+ getActiveCatalog().providers.find((p) => p.id === providerId));
+ setAccountUsageKeyReader((providerId, agent) => readCustomProviderKey(providerId, agent));
+ setAccountUsageOwnerStampReader(() => {
+ const session = getActiveAppSession();
+ return { dataOwnerId: session.dataOwnerId, generation: session.generation };
+ });
+
registerProviderHandlers(createElectronIpcHandlerRegistry(), {
listProviders: (opts) => getDesktopProviderService().listProviders(opts),
isOrganizationManagedProviderId: (providerId) =>
@@ -7257,6 +7274,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getModelCatalog: () => getActiveCatalog(),
testConnection: (input, signal) => testProviderConnection(input, undefined, signal),
detectProvider: detectProviderDeployment,
+ accountUsage: (input) => readProviderAccountUsage(input),
fetchModels: async (spec) => {
if (spec.savedProviderId && subscriptionAccountKind(spec.savedProviderId)) {
return { ok: await refreshSubscriptionAccountModels(spec.savedProviderId), models: [] };
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index ace0a54e98..c4f022c920 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6459,6 +6459,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
input: import('../shared/providerConnectionTest').ProviderConnectionTestRequest,
): Promise<import('../shared/providerConnectionTest').ProviderConnectionTestResult> =>
ipcRenderer.invoke('maker:provider:test-connection', input),
+ /**
+ * 供应商账户余额查询(API Key 计费连接的余额卡)。查询型结构化结果:
+ * ready 带 snapshot;unsupported / unavailable(error) 不拖拽 UI,快照不含密钥材料。
+ */
+ fetchProviderAccountUsage: (input: {
+ providerId: string;
+ forceRefresh?: boolean;
+ }): Promise<
+ import('../shared/providerAccountUsage').ProviderAccountUsageResult
+ > => ipcRenderer.invoke('maker:provider:account-usage', input),
/**
* 供应商「获取模型列表」—— 用表单值 GET 该供应商的列模型端点(key 仅内存透传)。
* 结构化结果:ok=true 带 models;失败 code 走 providerError.* i18n。
diff --git a/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx b/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx
new file mode 100644
index 0000000000..d71fe45970
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx
@@ -0,0 +1,229 @@
+/**
+ * ProviderAccountUsageModule —— API Key 计费供应商的账户余额卡(设置 → 模型供应商详情)。
+ *
+ * 与订阅卡(QuotaHoverCard + providerWeeklyQuotaSource)互斥呈现:订阅制读 OAuth 周期
+ * 配额,这里读供应商自己的账户接口(DeepSeek `/user/balance`)。账户余额对整个账号生效
+ * (与 runtime 无关),因此一个供应商一张卡;查询用的 key 按 claude-code → codex → pi
+ * 顺序取第一个指向官方端点的 runtime(main 侧同一口径,见 provider-account-usage.ts)。
+ *
+ * 智谱 GLM Coding Plan 没有公开的额度查询 API(官方只给网页用量页),这里只给
+ * 「查看套餐用量」外链,不做任何余额拉取。两类内容都缺席时模块不渲染。
+ */
+
+import { AlertTriangle, ExternalLink, RefreshCw } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import type { ProviderView } from '@cindy/model-providers';
+
+import { ZHIPU_CODING_PLAN_USAGE_URL, type ProviderAccountUsageResult } from '../../../shared/providerAccountUsage';
+import { isZhipuCodingPlanProviderView } from '../../lib/zhipuCodingPlan';
+import { useProviderAccountUsage } from '../../hooks/useProviderAccountUsage';
+
+import { cn } from '@/lib/utils';
+import { Tip } from '@/components/ui/tooltip';
+
+function formatCurrency(value: string, currency: string, locale: string): string {
+ try {
+ const fractionLength = value.split('.')[1]?.replace(/0+$/, '').length ?? 0;
+ const formatter = new Intl.NumberFormat(locale, {
+ style: 'currency',
+ currency,
+ });
+ const defaultDigits = formatter.resolvedOptions().minimumFractionDigits ?? 0;
+ if (fractionLength > 20) return `${value} ${currency}`;
+ // ECMA-402 允许直接 format 十进制字符串,避免先过 Number 再舍入。
+ const precise = new Intl.NumberFormat(locale, {
+ style: 'currency',
+ currency,
+ maximumFractionDigits: Math.max(defaultDigits, fractionLength),
+ });
+ return (precise.format as unknown as (input: string) => string)(value);
+ } catch {
+ return `${value} ${currency}`;
+ }
+}
+
+function errorKey(error: string): string {
+ return `providerAccountUsage.error.${error}`;
+}
+
+function UsageMetric({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="min-w-0">
+ <p className="text-11 text-[var(--text-tertiary)]">{label}</p>
+ <p className="mt-0.5 truncate text-13 font-medium tabular-nums text-[var(--text-primary)]">
+ {value}
+ </p>
+ </div>
+ );
+}
+
+function BalanceBody({
+ result,
+ locale,
+}: {
+ result: Extract<ProviderAccountUsageResult, { status: 'ready' }>;
+ locale: string;
+}) {
+ const { t } = useTranslation();
+ const { snapshot } = result;
+ if (snapshot.kind !== 'deepseek-balance') return null;
+ if (!snapshot.isAvailable || snapshot.balances.length === 0) {
+ return (
+ <p className="mt-3 flex items-start gap-2 text-13 text-[var(--text-secondary)]">
+ <AlertTriangle size={14} className="mt-0.5 shrink-0 text-[var(--warning-fg)]" aria-hidden />
+ <span>
+ {t(
+ snapshot.isAvailable
+ ? 'providerAccountUsage.deepSeek.empty'
+ : 'providerAccountUsage.deepSeek.unavailable',
+ )}
+ </span>
+ </p>
+ );
+ }
+ return (
+ <div className="mt-3 space-y-3">
+ {snapshot.balances.map((balance) => (
+ <div key={balance.currency} className="rounded-lg bg-[var(--surface-chip)] px-3 py-2.5">
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="text-12 font-medium text-[var(--text-secondary)]">
+ {balance.currency}
+ </span>
+ <span className="text-16 font-medium tabular-nums text-[var(--text-primary)]">
+ {formatCurrency(balance.totalBalance, balance.currency, locale)}
+ </span>
+ </div>
+ <div className="mt-2 grid grid-cols-2 gap-3">
+ <UsageMetric
+ label={t('providerAccountUsage.deepSeek.granted')}
+ value={formatCurrency(balance.grantedBalance, balance.currency, locale)}
+ />
+ <UsageMetric
+ label={t('providerAccountUsage.deepSeek.toppedUp')}
+ value={formatCurrency(balance.toppedUpBalance, balance.currency, locale)}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/** API Key 供应商的账户余额 / 用量入口卡。两类内容都缺席时返回 null。 */
+export function ProviderAccountUsageModule({ provider }: { provider?: ProviderView }) {
+ const { t, i18n } = useTranslation();
+ const locale = i18n.resolvedLanguage ?? i18n.language;
+ const usage = useProviderAccountUsage(provider);
+ const zhipuUsageLink = isZhipuCodingPlanProviderView(provider);
+ const showBalance = usage.supported;
+ if (!showBalance && !zhipuUsageLink) return null;
+ const { result, busy } = usage;
+
+ return (
+ <div
+ data-testid="provider-account-usage-module"
+ className="border-t border-[var(--settings-theme-card-border)] px-5 py-4"
+ >
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-12 font-medium text-[var(--settings-section-title)]">
+ {t('providerAccountUsage.title')}
+ </span>
+ {showBalance && (
+ <Tip text={t('providerAccountUsage.refresh')} side="top">
+ <button
+ type="button"
+ aria-label={t('providerAccountUsage.refresh')}
+ disabled={busy}
+ onClick={usage.refresh}
+ className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:opacity-50"
+ >
+ <span
+ className={cn(
+ 'inline-flex',
+ busy && 'animate-spinner motion-reduce:animate-none',
+ )}
+ >
+ <RefreshCw size={14} aria-hidden />
+ </span>
+ </button>
+ </Tip>
+ )}
+ </div>
+
+ {showBalance &&
+ (result === null ? (
+ <p className="mt-2 text-13 text-[var(--text-secondary)]">
+ {t('providerAccountUsage.updating')}
+ </p>
+ ) : result.status === 'unavailable' ? (
+ <div className="mt-2 flex flex-wrap items-center justify-between gap-3">
+ <p className="flex min-w-0 items-center gap-2 text-13 text-[var(--text-secondary)]">
+ <AlertTriangle size={14} className="shrink-0 text-[var(--error-fg)]" aria-hidden />
+ <span>{t(errorKey(result.error))}</span>
+ </p>
+ {/* no-credentials 下重试必然失败:错误文案已指引补密钥,不给死按钮。 */}
+ {result.error !== 'no-credentials' && (
+ <button
+ type="button"
+ onClick={usage.refresh}
+ className="rounded-full border border-[var(--border-default)] px-3 py-1 text-12 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"
+ >
+ {t('providerAccountUsage.retry')}
+ </button>
+ )}
+ </div>
+ ) : result.status === 'ready' ? (
+ <>
+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-11 text-[var(--text-tertiary)]">
+ <span>
+ {t('providerAccountUsage.updatedAt', {
+ time: new Intl.DateTimeFormat(locale, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(result.snapshot.fetchedAt),
+ })}
+ </span>
+ {result.stale && (
+ <span
+ data-testid="provider-account-usage-stale"
+ className="inline-flex items-center gap-1 text-[var(--warning-fg)]"
+ >
+ <AlertTriangle size={12} aria-hidden />
+ {t('providerAccountUsage.stale')}
+ </span>
+ )}
+ {result.error && (
+ <span className="basis-full text-[var(--text-secondary)]">
+ {t(errorKey(result.error))}
+ </span>
+ )}
+ </div>
+ <BalanceBody result={result} locale={locale} />
+ <button
+ type="button"
+ onClick={() => void window.electronAPI.openExternal('https://platform.deepseek.com/usage')}
+ className="mt-3 inline-flex items-center gap-1.5 text-12 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"
+ >
+ {t('providerAccountUsage.openDashboard')}
+ <ExternalLink size={12} aria-hidden />
+ </button>
+ </>
+ ) : null)}
+
+ {zhipuUsageLink && (
+ <button
+ type="button"
+ onClick={() => void window.electronAPI.openExternal(ZHIPU_CODING_PLAN_USAGE_URL)}
+ className={cn(
+ 'inline-flex items-center gap-1.5 text-12 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
+ showBalance && 'mt-3',
+ )}
+ >
+ {t('providerAccountUsage.zhipuCodingPlan.usage')}
+ <ExternalLink size={12} aria-hidden />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 6a8d3a782d..8555e9c536 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -91,6 +91,7 @@ import { BILLING_CURRENCY, formatBillingAmount } from '@/features/billing/money'
import { canAccessBillingSettings } from './billingVisibility';
import { resolveXdAssetModuleState } from './providerAssetModule';
import { useProviderSubscriptionCard } from './useProviderSubscriptionCard';
+import { ProviderAccountUsageModule } from './ProviderAccountUsageModule';
import { QuotaHoverCard } from '../status/QuotaHoverCard';
import { ProviderConnectionDialog } from './ProviderConnectionDialog';
import { AddProviderWizard, type WizardEntry } from './AddProviderWizard';
@@ -872,7 +873,7 @@ function DetailHeader({
{detail && <div className="px-5 pb-4">{detail}</div>}
{provider?.subscriptionFastPolicy && <div className="px-5 pb-4"><SubscriptionFastSetting key={provider.id} provider={provider} /></div>}
{assetModule ??
- (subscription && (
+ (subscription ? (
<div
data-testid="provider-usage-module"
className="border-t px-1 py-2"
@@ -910,6 +911,8 @@ function DetailHeader({
) : null}
</QuotaHoverCard>
</div>
+ ) : (
+ <ProviderAccountUsageModule provider={provider} />
))}
{children}
</div>
diff --git a/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts b/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts
new file mode 100644
index 0000000000..9c8d713630
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts
@@ -0,0 +1,84 @@
+/**
+ * useProviderAccountUsage —— API Key 供应商余额卡数据 hook。
+ *
+ * 与订阅卡的 useProviderSubscriptionCard 互补:那边读 OAuth 订阅配额,这边经
+ * PROVIDER_ACCOUNT_USAGE 读供应商自己的账户接口。挂载时拉一次,刷新按钮手动
+ * forceRefresh;不支持(unsupported)时 hook 返回 supported=false,模块不渲染。
+ * 失败不重试轮询——重试入口是刷新按钮本身。
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type { ProviderView } from '@cindy/model-providers';
+
+import type { ProviderAccountUsageResult } from '../../shared/providerAccountUsage';
+
+export interface ProviderAccountUsageState {
+ /** false = 该供应商没有可读的账户接口,调用方不应渲染模块。 */
+ supported: boolean;
+ result: ProviderAccountUsageResult | null;
+ busy: boolean;
+ refresh: () => void;
+}
+
+const DEEPSEEK_ORIGIN = 'https://api.deepseek.com';
+
+/** 供应商任一 runtime 是否指向官方 DeepSeek 端点(与 main 的认领规则同一口径,仅用于首屏免查询裁剪)。 */
+function hasDeepSeekOfficialRoute(provider: ProviderView | undefined): boolean {
+ if (!provider) return false;
+ return Object.values(provider.routing ?? {}).some((route) => {
+ const upstream = (route as { upstream?: string } | undefined)?.upstream;
+ if (!upstream) return false;
+ try {
+ const url = new URL(upstream);
+ return url.protocol === 'https:' && url.origin === DEEPSEEK_ORIGIN;
+ } catch {
+ return false;
+ }
+ });
+}
+
+export function useProviderAccountUsage(
+ provider: ProviderView | undefined,
+): ProviderAccountUsageState {
+ const supported =
+ !!provider
+ && provider.auth?.method !== 'oauth'
+ && hasDeepSeekOfficialRoute(provider);
+ const [result, setResult] = useState<ProviderAccountUsageResult | null>(null);
+ const [busy, setBusy] = useState(false);
+ const requestId = useRef(0);
+
+ const load = useCallback(
+ async (forceRefresh: boolean) => {
+ if (!provider?.id) return;
+ const id = ++requestId.current;
+ setBusy(true);
+ try {
+ const next = await window.electronAPI.maker.fetchProviderAccountUsage({
+ providerId: provider.id,
+ forceRefresh,
+ });
+ if (id === requestId.current) setResult(next);
+ } catch {
+ // IPC 层异常(不该发生)按未知失败处理,保留已有快照。
+ if (id === requestId.current) setResult(null);
+ } finally {
+ if (id === requestId.current) setBusy(false);
+ }
+ },
+ [provider?.id],
+ );
+
+ useEffect(() => {
+ if (!supported) return;
+ void load(false);
+ }, [supported, provider?.id, load]);
+
+ return {
+ supported,
+ result,
+ busy,
+ refresh: () => void load(true),
+ };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fd904388c2..9d2ea1fcc7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1,4 +1,5 @@
{
+ "providerAccountUsage": {"title":"Account balance","refresh":"Refresh balance","retry":"Retry balance query","updating":"Checking balance…","updatedAt":"Updated {{time}}","stale":"Showing an older snapshot","openDashboard":"Open DeepSeek usage dashboard","deepSeek":{"granted":"Granted balance","toppedUp":"Topped-up balance","unavailable":"DeepSeek did not provide balance details. Open the usage dashboard or retry later.","empty":"DeepSeek returned no balance details. Open the usage dashboard to check the account."},"zhipuCodingPlan":{"usage":"View Zhipu plan usage"},"error":{"no-credentials":"No API key is available for this provider. Edit the provider and add the key.","auth":"The provider rejected this API key. Check or replace the key, then retry.","rate-limited":"The provider is limiting balance queries. Retry later.","network":"Cindy cannot reach the provider. Check the network and retry.","server":"The provider cannot return the balance right now. Retry later.","invalid-response":"The provider returned unreadable balance data. Retry later.","throttled":"The balance was just refreshed. Retry a bit later.","unknown":"Cindy cannot load the provider balance. Retry later."}},
"localAgent": {"title":"Local App Connections","empty":"No connected apps","description":"Authorized local apps can use Cindy models and agent capabilities. Cindy keeps supplier credentials.","revoke":"Revoke Connection","failed":"Could not read app connections.","connectTitle":"Connect a Local App","connectMessage":"Allow “{{app}}” to use Cindy?","connectDetail":"This app can list models and providers, create its own executions, and supply tools. Native execution can read and write files and run commands with your system user permissions; the working directory does not restrict access. Provider credentials stay in Cindy. Revoke individual connections in Settings → Remote Connections → Local App Connections.","cancel":"Cancel","allow":"Allow Connection","revokeMessage":"Revoke all local app connections?","revokeDetail":"All local app connections will stop working and their running tasks will stop. Apps can request a new connection when needed.","clientIdentity":"App-reported ID: {{id}}\nVersion: {{version}}\nThe requesting app supplies its name and ID; Cindy has not verified its publisher.","revokeOneMessage":"Revoke this connection for “{{app}}”?","revokeOneDetail":"Tasks running through this connection will stop. Other app connections will keep working. The app can request a new connection when needed.","revokeConnection":"Revoke connection for “{{app}}”","clientId":"App ID: {{id}}","operationFailed":"Could not confirm the local app operation. Check its current state before continuing.","invalidConnection":"The app connection ID is invalid.","revokeFailed":"Could not confirm the revocation. Check the current connection state.","loading":"Loading app connections…","revoking":"Revoking connection…","authorizationRequired":"This operation requires valid local app authorization.","pairExpired":"The connection request expired or was cancelled. Request a new connection from the app.","busy":"A local app execution is still running or the execution limit is reached. End unused executions first.","limitReached":"The local app connection limit is reached. Revoke unused connections in Settings.","invalidWorkspace":"The app must specify an existing absolute working directory on this computer.","sessionExists":"This execution ID is already in use by this app connection.","executionUnavailable":"The requested execution or tool call is unavailable. Messages and tool operations were not replayed.","selectionUnavailable":"The selected model, provider, or reasoning effort is unavailable. Select an available option in the app.","requestNotReplayed":"This request was not repeated. Check the original operation result in the app.","storageUnavailable":"Could not read or save local app connection data. Existing authorization records were retained.","stopUnconfirmed":"Further messages to this execution are blocked, but the process has not been confirmed stopped.","interactionUnavailable":"The engine requires an interaction that this app cannot receive.","interrupted":"This send was interrupted.","toolTimeout":"The app tool timed out. It was not automatically retried.","connectResult":"Return to the requesting app for the connection result. Authorization is decided in the Cindy confirmation window.","invalidRequest":"The app request is invalid or the operation is unsupported.","hostInUse":"Another Cindy instance manages local app connections for this profile. View the connections in that instance.","developerConnection":"Development Connection","copyCode":"Copy Connection Code","codeCopied":"Connection code copied","codeCopyFailed":"Could not copy the connection code","developerState":{"ready":"For temporary connections from apps on this computer. Approval in this Cindy is still required. Copy a new code after restarting.","starting":"Preparing connection…","owner-unavailable":"Sign in or enter local mode first","host-in-use":"Another Cindy manages connections for this data folder","failed":"The local connection could not start","stopped":"The local connection has stopped"}},
"attachmentAccessConfirmation": {
"title": "Confirm Attachment Access",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5658a2a556..633dc150b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1,4 +1,5 @@
{
+ "providerAccountUsage": {"title":"アカウント残高","refresh":"残高を更新","retry":"残高の取得を再試行","updating":"残高を確認しています…","updatedAt":"{{time}} に更新","stale":"古いスナップショットを表示中","openDashboard":"DeepSeek の使用量ページを開く","deepSeek":{"granted":"付与残高","toppedUp":"チャージ残高","unavailable":"DeepSeek が残高情報を返しませんでした。使用量ページを開くか、後でもう一度お試しください。","empty":"DeepSeek から残高明細が返されませんでした。使用量ページでアカウントを確認してください。"},"zhipuCodingPlan":{"usage":"Zhipu プランの使用量を見る"},"error":{"no-credentials":"このプロバイダーには利用可能な API キーがありません。プロバイダーを編集してキーを追加してください。","auth":"プロバイダーがこの API キーを拒否しました。確認または交換してから再試行してください。","rate-limited":"プロバイダーが残高照会を制限しています。後でもう一度お試しください。","network":"プロバイダーに接続できません。ネットワークを確認して再試行してください。","server":"プロバイダーが現在一時的に残高を返せません。後でもう一度お試しください。","invalid-response":"プロバイダーが認識できない残高データを返しました。後でもう一度お試しください。","throttled":"残高は更新されたばかりです。少し待ってから再試行してください。","unknown":"プロバイダーの残高を読み込めませんでした。後でもう一度お試しください。"}},
"localAgent": {"title":"ローカルアプリの接続","empty":"接続済みのアプリはありません","description":"承認したローカルアプリが Cindy のモデルと実行機能を利用できます。認証情報は Cindy が管理します。","revoke":"接続を解除","failed":"アプリの接続を読み込めませんでした。","connectTitle":"ローカルアプリを接続","connectMessage":"「{{app}}」に Cindy の利用を許可しますか?","connectDetail":"このアプリはモデルとプロバイダーの一覧を取得し、独自の実行を作成してツールを提供できます。ネイティブ実行では、現在の OS ユーザーの権限でファイルを読み書きし、コマンドを実行できます。作業ディレクトリはアクセス範囲を制限しません。認証情報は Cindy が保持します。設定 → リモート接続 → ローカルアプリの接続で個別に解除できます。","cancel":"キャンセル","allow":"接続を許可","revokeMessage":"すべてのローカルアプリ接続を取り消しますか?","revokeDetail":"すべてのローカルアプリ接続が無効になり、実行中のタスクが停止します。必要に応じて再接続できます。","clientIdentity":"アプリが申告した ID:{{id}}\nバージョン:{{version}}\n名前と ID は申請元の申告であり、Cindy が発行元を確認したことを意味しません。","revokeOneMessage":"「{{app}}」のこの接続を取り消しますか?","revokeOneDetail":"この接続で実行中のタスクが停止します。他のアプリ接続には影響しません。必要に応じて再接続できます。","revokeConnection":"「{{app}}」の接続を取り消す","clientId":"アプリ ID:{{id}}","operationFailed":"ローカルアプリの操作結果を確認できませんでした。現在の状態を確認してから続けてください。","invalidConnection":"アプリ接続の ID が無効です。","revokeFailed":"接続の解除を確認できませんでした。現在の接続状態を確認してください。","loading":"アプリの接続を読み込み中…","revoking":"接続を解除中…","authorizationRequired":"この操作には有効なローカルアプリの承認が必要です。","pairExpired":"接続リクエストの有効期限が切れたか、キャンセルされました。アプリから接続を再申請してください。","busy":"ローカルアプリの実行が続いているか、実行数の上限に達しています。不要な実行を先に終了してください。","limitReached":"ローカルアプリの接続数が上限に達しています。設定で不要な接続を解除してください。","invalidWorkspace":"アプリは、このコンピューター上に存在する作業ディレクトリを絶対パスで指定する必要があります。","sessionExists":"このアプリ接続では、その実行 ID がすでに使われています。","executionUnavailable":"要求された実行またはツール呼び出しは利用できません。メッセージやツール操作は再実行されていません。","selectionUnavailable":"選択したモデル、プロバイダー、または推論強度は利用できません。アプリで利用可能な項目を選択してください。","requestNotReplayed":"このリクエストは再実行されていません。アプリで元の操作結果を確認してください。","storageUnavailable":"ローカルアプリの接続データを読み込めないか、保存できませんでした。既存の承認記録は保持されています。","stopUnconfirmed":"この実行への追加メッセージは停止しましたが、プロセスの終了はまだ確認できていません。","interactionUnavailable":"エンジンが必要とする操作を、このアプリでは受け取れません。","interrupted":"今回の送信は中断されました。","toolTimeout":"アプリのツールがタイムアウトしました。自動で再試行していません。","connectResult":"接続結果は申請元のアプリで確認してください。承認は Cindy の確認ウィンドウで決定します。","invalidRequest":"アプリのリクエストが無効か、この操作はサポートされていません。","hostInUse":"このプロファイルのローカルアプリ接続は、別の Cindy インスタンスが管理しています。そのインスタンスで接続を確認してください。","developerConnection":"開発用接続","copyCode":"接続コードをコピー","codeCopied":"接続コードをコピーしました","codeCopyFailed":"接続コードをコピーできませんでした","developerState":{"ready":"このパソコンのアプリから一時的に接続できます。この Cindy での許可が必要です。再起動後はコードをコピーし直してください。","starting":"接続を準備しています…","owner-unavailable":"先にログインするかローカルモードに入ってください","host-in-use":"このデータフォルダーの接続は別の Cindy が管理しています","failed":"ローカル接続を開始できませんでした","stopped":"ローカル接続は停止しています"}},
"attachmentAccessConfirmation": {
"title": "添付ファイルへのアクセスを確認",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ee7ef042a9..556e5c66b3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1,4 +1,5 @@
{
+ "providerAccountUsage": {"title":"계정 잔액","refresh":"잔액 새로 고침","retry":"잔액 조회 다시 시도","updating":"잔액을 확인하는 중…","updatedAt":"{{time}}에 업데이트됨","stale":"이전 스냅샷 표시 중","openDashboard":"DeepSeek 사용량 페이지 열기","deepSeek":{"granted":"증여 잔액","toppedUp":"충전 잔액","unavailable":"DeepSeek가 잔액 내역을 제공하지 않았습니다. 사용량 페이지를 열거나 나중에 다시 시도하세요.","empty":"DeepSeek가 잔액 내역을 반환하지 않았습니다. 사용량 페이지에서 계정을 확인하세요."},"zhipuCodingPlan":{"usage":"Zhipu 플랜 사용량 보기"},"error":{"no-credentials":"이 제공자에게 사용 가능한 API 키가 없습니다. 제공자를 편집해 키를 추가하세요.","auth":"제공자가 이 API 키를 거부했습니다. 확인하거나 교체한 후 다시 시도하세요.","rate-limited":"제공자가 잔액 조회를 제한하고 있습니다. 나중에 다시 시도하세요.","network":"제공자에 연결할 수 없습니다. 네트워크를 확인한 후 다시 시도하세요.","server":"제공자가 현재 잔액을 반환할 수 없습니다. 나중에 다시 시도하세요.","invalid-response":"제공자가 인식할 수 없는 잔액 데이터를 반환했습니다. 나중에 다시 시도하세요.","throttled":"잔액을 방금 새로 고쳤습니다. 잠시 후 다시 시도하세요.","unknown":"제공자 잔액을 불러올 수 없습니다. 나중에 다시 시도하세요."}},
"localAgent": {"title":"로컬 앱 연결","empty":"연결된 앱 없음","description":"승인된 로컬 앱이 Cindy 모델과 실행 기능을 사용할 수 있습니다. 제공자 인증 정보는 Cindy가 관리합니다.","revoke":"연결 해제","failed":"앱 연결을 불러오지 못했습니다.","connectTitle":"로컬 앱 연결","connectMessage":"“{{app}}”의 Cindy 사용을 허용할까요?","connectDetail":"이 앱은 모델과 제공자 목록을 확인하고 자체 실행을 만들며 도구를 제공할 수 있습니다. 네이티브 실행은 현재 시스템 사용자 권한으로 파일을 읽고 쓰거나 명령을 실행할 수 있으며, 작업 디렉터리가 접근 범위를 제한하지 않습니다. 제공자 인증 정보는 Cindy가 보관합니다. 설정 → 원격 연결 → 로컬 앱 연결에서 개별 연결을 해제할 수 있습니다.","cancel":"취소","allow":"연결 허용","revokeMessage":"모든 로컬 앱 연결을 해제할까요?","revokeDetail":"모든 로컬 앱 연결이 무효화되고 실행 중인 작업이 중지됩니다. 필요하면 다시 연결할 수 있습니다.","clientIdentity":"앱이 제공한 ID: {{id}}\n버전: {{version}}\n이름과 ID는 요청 앱이 제공하며, Cindy가 게시자를 확인했다는 의미가 아닙니다.","revokeOneMessage":"“{{app}}”의 이 연결을 취소할까요?","revokeOneDetail":"이 연결에서 실행 중인 작업이 중지됩니다. 다른 앱 연결에는 영향을 주지 않습니다. 필요하면 다시 연결할 수 있습니다.","revokeConnection":"“{{app}}” 연결 취소","clientId":"앱 ID: {{id}}","operationFailed":"로컬 앱 작업 결과를 확인하지 못했습니다. 현재 상태를 확인한 후 계속하세요.","invalidConnection":"앱 연결 ID가 유효하지 않습니다.","revokeFailed":"연결 해제 결과를 확인하지 못했습니다. 현재 연결 상태를 확인하세요.","loading":"앱 연결을 불러오는 중…","revoking":"연결 해제 중…","authorizationRequired":"이 작업에는 유효한 로컬 앱 승인이 필요합니다.","pairExpired":"연결 요청이 만료되었거나 취소되었습니다. 앱에서 새 연결을 요청하세요.","busy":"로컬 앱 실행이 진행 중이거나 실행 한도에 도달했습니다. 사용하지 않는 실행을 먼저 종료하세요.","limitReached":"로컬 앱 연결 한도에 도달했습니다. 설정에서 사용하지 않는 연결을 해제하세요.","invalidWorkspace":"앱은 이 컴퓨터에 존재하는 작업 디렉터리의 절대 경로를 지정해야 합니다.","sessionExists":"이 앱 연결에서 해당 실행 ID를 이미 사용하고 있습니다.","executionUnavailable":"요청한 실행 또는 도구 호출을 사용할 수 없습니다. 메시지와 도구 작업은 다시 실행되지 않았습니다.","selectionUnavailable":"선택한 모델, 제공자 또는 추론 강도을 사용할 수 없습니다. 앱에서 사용 가능한 항목을 선택하세요.","requestNotReplayed":"이 요청은 다시 실행되지 않았습니다. 앱에서 원래 작업 결과를 확인하세요.","storageUnavailable":"로컬 앱 연결 데이터를 읽거나 저장하지 못했습니다. 기존 승인 기록은 유지되었습니다.","stopUnconfirmed":"이 실행에 추가 메시지를 보내는 것은 차단되었지만 프로세스가 중지되었는지는 확인되지 않았습니다.","interactionUnavailable":"엔진에 필요한 상호작용을 이 앱이 받을 수 없습니다.","interrupted":"이번 전송이 중단되었습니다.","toolTimeout":"앱 도구 호출 시간이 초과되었습니다. 자동으로 재시도하지 않았습니다.","connectResult":"연결 결과는 요청한 앱에서 확인하세요. 승인은 Cindy 확인 창에서 결정합니다.","invalidRequest":"앱 요청이 유효하지 않거나 지원하지 않는 작업입니다.","hostInUse":"이 프로필의 로컬 앱 연결은 다른 Cindy 인스턴스가 관리합니다. 해당 인스턴스에서 연결을 확인하세요.","developerConnection":"개발용 연결","copyCode":"연결 코드 복사","codeCopied":"연결 코드를 복사했습니다","codeCopyFailed":"연결 코드를 복사하지 못했습니다","developerState":{"ready":"이 컴퓨터의 앱에서 임시로 연결합니다. 이 Cindy에서 승인이 필요합니다. 다시 시작하면 코드를 다시 복사하세요.","starting":"연결 준비 중…","owner-unavailable":"먼저 로그인하거나 로컬 모드로 들어가세요","host-in-use":"다른 Cindy가 이 데이터 폴더의 연결을 관리하고 있습니다","failed":"로컬 연결을 시작하지 못했습니다","stopped":"로컬 연결이 중지되었습니다"}},
"attachmentAccessConfirmation": {
"title": "첨부 파일 접근 확인",
@@ -7731,7 +7732,7 @@
"disagree": "취소"
},
"ssoVerificationTitle": "기업 신원 확인",
- "ssoVerificationSubtitle": "최초 로그인 시 ID 공급자가 반환한 연락처 {{target}} 확인이 필요합니다",
+ "ssoVerificationSubtitle": "최초 로그인 시 ID 제공자가 반환한 연락처 {{target}} 확인이 필요합니다",
"enterCode": "인증 코드 입력",
"codeSentTo": "{{identifier}}에 코드를 보냈습니다",
"codePlaceholder": "6자리 코드",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 99a89422e1..9ed83041fb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1,4 +1,5 @@
{
+ "providerAccountUsage": {"title":"账户余额","refresh":"刷新余额","retry":"重试余额查询","updating":"正在查询余额…","updatedAt":"更新于 {{time}}","stale":"正在显示旧快照","openDashboard":"打开 DeepSeek 用量页","deepSeek":{"granted":"赠送余额","toppedUp":"充值余额","unavailable":"DeepSeek 暂时没有提供余额明细,请打开用量页或稍后重试。","empty":"DeepSeek 没有返回余额明细,请打开用量页检查账户。"},"zhipuCodingPlan":{"usage":"查看智谱套餐用量"},"error":{"no-credentials":"这个供应商没有可用的 API 密钥,请编辑供应商并补齐密钥。","auth":"供应商拒绝了这个 API 密钥,请检查或更换密钥后重试。","rate-limited":"供应商限制了余额查询频率,请稍后重试。","network":"Cindy 无法连接供应商,请检查网络后重试。","server":"供应商暂时无法返回余额,请稍后重试。","invalid-response":"供应商返回了无法识别的余额数据,请稍后重试。","throttled":"刚刚刷新过余额,请稍后重试。","unknown":"Cindy 无法加载供应商余额,请稍后重试。"}},
"localAgent": {"title":"本机应用连接","empty":"尚未连接应用","description":"允许已授权的本机应用使用 Cindy 的模型与执行能力。供应商登录仍由 Cindy 管理。","revoke":"撤销连接","failed":"无法读取应用连接。","connectTitle":"连接本机应用","connectMessage":"允许“{{app}}”使用 Cindy?","connectDetail":"此应用可以查看模型与供应商目录、创建自己的执行并提供工具。原生执行可以按当前系统用户的权限读写文件、运行命令;工作目录不限制访问范围。供应商凭证保留在 Cindy。可在设置 → 远程连接 → 本机应用连接中单独撤销连接。","cancel":"取消","allow":"允许连接","revokeMessage":"撤销所有本机应用连接?","revokeDetail":"所有本机应用的连接会失效,正在运行的接入任务会停止。需要使用时可重新申请连接。","clientIdentity":"应用自报编号:{{id}}\n版本:{{version}}\n名称和编号由申请方提供,不代表 Cindy 已验证其发布者。","revokeOneMessage":"撤销“{{app}}”的这条连接?","revokeOneDetail":"这条连接正在运行的任务会停止。其他应用连接不受影响。需要使用时可重新申请连接。","revokeConnection":"撤销“{{app}}”的连接","clientId":"应用编号:{{id}}","operationFailed":"无法确认本机应用操作的结果,请先查看当前状态。","invalidConnection":"应用连接编号无效。","revokeFailed":"无法确认撤销结果,请查看当前连接状态。","loading":"正在读取应用连接…","revoking":"正在撤销连接…","authorizationRequired":"此操作需要有效的本机应用授权。","pairExpired":"连接申请已过期或取消,请从应用重新申请连接。","busy":"本机应用仍有执行正在运行,或已达到执行上限,请先结束不用的执行。","limitReached":"已达到本机应用连接上限,请在设置中撤销不用的连接。","invalidWorkspace":"应用须指定此电脑上已存在的绝对工作目录。","sessionExists":"此应用连接已在使用该执行编号。","executionUnavailable":"所请求的执行或工具调用不可用,消息与工具操作未被重放。","selectionUnavailable":"所选模型、供应商或推理强度不可用,请在应用中重新选择。","requestNotReplayed":"此请求未被重复执行,请在应用中查看原操作结果。","storageUnavailable":"无法读取或保存本机应用连接数据,已保留现有授权记录。","stopUnconfirmed":"已阻止继续向此执行发送消息,但尚未确认进程已停止。","interactionUnavailable":"引擎需要此应用无法接收的交互操作。","interrupted":"本次发送已中断。","toolTimeout":"应用工具调用已超时,未自动重试。","connectResult":"请返回申请连接的应用查看结果,授权由 Cindy 确认窗口决定。","invalidRequest":"应用请求无效,或该操作不受支持。","hostInUse":"此配置的本机应用连接正由另一个 Cindy 实例管理,请在该实例中查看连接。","developerConnection":"开发连接","copyCode":"复制连接码","codeCopied":"连接码已复制","codeCopyFailed":"未能复制连接码","developerState":{"ready":"供此电脑上的应用临时连接,仍需在此 Cindy 中授权。重启后需重新复制。","starting":"正在准备连接…","owner-unavailable":"请先登录或进入本地模式","host-in-use":"此数据目录的连接正由另一个 Cindy 管理","failed":"本机连接未能启动","stopped":"本机连接已停止"}},
"attachmentAccessConfirmation": {
"title": "确认附件访问",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 6512ad1390..5b1bb48cb9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1,4 +1,5 @@
{
+ "providerAccountUsage": {"title":"帳戶餘額","refresh":"重新整理餘額","retry":"重試餘額查詢","updating":"正在查詢餘額…","updatedAt":"更新於 {{time}}","stale":"正在顯示舊快照","openDashboard":"開啟 DeepSeek 用量頁","deepSeek":{"granted":"贈送餘額","toppedUp":"儲值餘額","unavailable":"DeepSeek 暫時沒有提供餘額明細,請開啟用量頁或稍後重試。","empty":"DeepSeek 沒有回傳餘額明細,請開啟用量頁檢查帳戶。"},"zhipuCodingPlan":{"usage":"查看智譜套餐用量"},"error":{"no-credentials":"這個供應商沒有可用的 API 金鑰,請編輯供應商並補齊金鑰。","auth":"供應商拒絕了這個 API 金鑰,請檢查或更換金鑰後重試。","rate-limited":"供應商限制了餘額查詢頻率,請稍後重試。","network":"Cindy 無法連線供應商,請檢查網路後重試。","server":"供應商暫時無法回傳餘額,請稍後重試。","invalid-response":"供應商回傳了無法辨識的餘額資料,請稍後重試。","throttled":"剛剛重新整理過餘額,請稍後重試。","unknown":"Cindy 無法載入供應商餘額,請稍後重試。"}},
"localAgent": {"title":"本機應用程式連線","empty":"尚未連接應用程式","description":"允許已授權的本機應用程式使用 Cindy 的模型與執行能力。供應商登入仍由 Cindy 管理。","revoke":"撤銷連線","failed":"無法讀取應用程式連線。","connectTitle":"連接本機應用程式","connectMessage":"允許「{{app}}」使用 Cindy?","connectDetail":"此應用程式可以查看模型與供應商目錄、建立自己的執行並提供工具。原生執行可以依目前系統使用者的權限讀寫檔案、執行命令;工作目錄不限制存取範圍。供應商憑證保留在 Cindy。可在設定 → 遠端連線 → 本機應用程式連線中個別撤銷連線。","cancel":"取消","allow":"允許連接","revokeMessage":"撤銷所有本機應用程式連線?","revokeDetail":"所有本機應用程式連線將失效,正在執行的接入任務會停止。需要時可重新申請連線。","clientIdentity":"應用程式自報編號:{{id}}\n版本:{{version}}\n名稱與編號由申請方提供,不代表 Cindy 已驗證其發行者。","revokeOneMessage":"撤銷「{{app}}」的這條連線?","revokeOneDetail":"透過此連線執行的任務會停止。其他應用程式連線不受影響,需要時可重新申請連線。","revokeConnection":"撤銷「{{app}}」的連線","clientId":"應用程式編號:{{id}}","operationFailed":"無法確認本機應用程式操作的結果,請先查看目前狀態。","invalidConnection":"應用程式連線編號無效。","revokeFailed":"無法確認撤銷結果,請查看目前連線狀態。","loading":"正在讀取應用程式連線…","revoking":"正在撤銷連線…","authorizationRequired":"此操作需要有效的本機應用程式授權。","pairExpired":"連線申請已過期或取消,請從應用程式重新申請連線。","busy":"本機應用程式仍有執行正在運行,或已達執行上限,請先結束不用的執行。","limitReached":"已達本機應用程式連線上限,請在設定中撤銷不用的連線。","invalidWorkspace":"應用程式須指定此電腦上已存在的絕對工作目錄。","sessionExists":"此應用程式連線已在使用該執行編號。","executionUnavailable":"所請求的執行或工具呼叫無法使用,訊息與工具操作未被重播。","selectionUnavailable":"所選模型、供應商或推理強度無法使用,請在應用程式中重新選擇。","requestNotReplayed":"此請求未被重複執行,請在應用程式中查看原操作結果。","storageUnavailable":"無法讀取或儲存本機應用程式連線資料,已保留現有授權紀錄。","stopUnconfirmed":"已阻止繼續向此執行傳送訊息,但尚未確認程序已停止。","interactionUnavailable":"引擎需要此應用程式無法接收的互動操作。","interrupted":"本次傳送已中斷。","toolTimeout":"應用程式工具呼叫已逾時,未自動重試。","connectResult":"請返回申請連線的應用程式查看結果,授權由 Cindy 確認視窗決定。","invalidRequest":"應用程式請求無效,或該操作不受支援。","hostInUse":"此設定檔的本機應用程式連線正由另一個 Cindy 執行個體管理,請在該執行個體中查看連線。","developerConnection":"開發連線","copyCode":"複製連線碼","codeCopied":"連線碼已複製","codeCopyFailed":"無法複製連線碼","developerState":{"ready":"供此電腦上的應用程式暫時連線,仍需在此 Cindy 中授權。重新啟動後需重新複製。","starting":"正在準備連線…","owner-unavailable":"請先登入或進入本機模式","host-in-use":"此資料目錄的連線正由另一個 Cindy 管理","failed":"本機連線未能啟動","stopped":"本機連線已停止"}},
"attachmentAccessConfirmation": {
"title": "確認附件存取",
diff --git a/apps/desktop/src/renderer/lib/zhipuCodingPlan.ts b/apps/desktop/src/renderer/lib/zhipuCodingPlan.ts
new file mode 100644
index 0000000000..437c189da3
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/zhipuCodingPlan.ts
@@ -0,0 +1,23 @@
+/**
+ * 智谱 GLM Coding Plan 连接识别(renderer 侧视图判定;main 侧同口径见
+ * maker-host/provider-account-usage.ts 的 isZhipuCodingPlanProvider)。
+ *
+ * 依据官方接入端点而不是 provider 名字:内置预设(zhipu-coding-plan-cn)与从模板创建的
+ * 自定义连接(baseUrl 指向 open.bigmodel.cn/api/anthropic 或 /api/coding/*)都算;
+ * 按量计费的开放平台连接(open.bigmodel.cn/api/paas/*)不算——它没有 Coding 套餐额度页。
+ */
+
+import type { ProviderView } from '@cindy/model-providers';
+
+const ZHIPU_ANTHROPIC_BASE = 'https://open.bigmodel.cn/api/anthropic';
+const ZHIPU_CODING_PREFIX = 'https://open.bigmodel.cn/api/coding/';
+
+export function isZhipuCodingPlanProviderView(provider: ProviderView | undefined | null): boolean {
+ if (!provider) return false;
+ if (provider.id === 'zhipu-coding-plan-cn') return true;
+ return Object.values(provider.routing ?? {}).some((route) => {
+ const upstream = (route as { upstream?: string } | undefined)?.upstream;
+ if (!upstream) return false;
+ return upstream === ZHIPU_ANTHROPIC_BASE || upstream.startsWith(ZHIPU_CODING_PREFIX);
+ });
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index e795676649..ceb25aed65 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5728,6 +5728,13 @@ interface ElectronAPI {
testProviderConnection: (
input: import('../shared/providerConnectionTest').ProviderConnectionTestRequest,
) => Promise<import('../shared/providerConnectionTest').ProviderConnectionTestResult>;
+ /** 供应商账户余额查询(API Key 计费连接的余额卡,查询型结构化结果,快照不含密钥材料)。 */
+ fetchProviderAccountUsage: (input: {
+ providerId: string;
+ forceRefresh?: boolean;
+ }) => Promise<
+ import('../shared/providerAccountUsage').ProviderAccountUsageResult
+ >;
/** 供应商「获取模型列表」—— 表单值透传,结构化结果(code 走 providerError.* i18n)。 */
detectProvider?: (input: ({ requestId: string; cancel: true } | {
requestId: string; agent: 'claude-code' | 'codex' | 'pi'; baseUrl: string;
diff --git a/apps/desktop/src/shared/providerAccountUsage.ts b/apps/desktop/src/shared/providerAccountUsage.ts
new file mode 100644
index 0000000000..dbc71d96d0
--- /dev/null
+++ b/apps/desktop/src/shared/providerAccountUsage.ts
@@ -0,0 +1,74 @@
+/**
+ * providerAccountUsage —— API Key 计费供应商的账户余额 / 用量快照(renderer ↔ main 共享形状)。
+ *
+ * 与订阅制(Claude / Codex / xAI)的 `providerQuotaSource` 互补:那边读的是 OAuth 订阅的
+ * 周期配额(5h / 7d 窗口),这边读的是 API Key 供应商自己的账户接口(如 DeepSeek
+ * `/user/balance`)。两者互不借用:订阅卡与余额卡各自成立,缺一不显示另一张。
+ *
+ * 结果是查询型结构化返回(规则 13 例外条款):网络 / 上游 / 鉴权失败不 throw,落进
+ * `error`,renderer 按 code 渲染分类文案与重试入口。快照本身不含任何密钥材料。
+ */
+
+import type { AgentKind } from '@cindy/model-providers';
+
+export interface ProviderAccountUsageRequest {
+ providerId: string;
+ /** 手动刷新(设置页刷新按钮)。绕过 TTL 缓存但仍受最小间隔节流。 */
+ forceRefresh?: boolean;
+}
+
+export interface DeepSeekBalanceLine {
+ /** ISO 4217 货币码(如 CNY / USD)。 */
+ currency: string;
+ totalBalance: string;
+ grantedBalance: string;
+ toppedUpBalance: string;
+}
+
+export interface DeepSeekAccountUsageSnapshot {
+ kind: 'deepseek-balance';
+ isAvailable: boolean;
+ balances: DeepSeekBalanceLine[];
+ /** epoch ms。 */
+ fetchedAt: number;
+}
+
+export type ProviderAccountUsageSnapshot = DeepSeekAccountUsageSnapshot;
+
+export type ProviderAccountUsageError =
+ | 'no-credentials'
+ | 'updating'
+ | 'auth'
+ | 'rate-limited'
+ | 'network'
+ | 'server'
+ | 'invalid-response'
+ | 'throttled'
+ | 'unknown';
+
+export type ProviderAccountUsageResult =
+ /** 该供应商没有可读的账户余额 / 用量接口(renderer 不渲染模块)。 */
+ | { status: 'unsupported' }
+ | { status: 'unavailable'; error: ProviderAccountUsageError; retryAt?: number }
+ | {
+ status: 'ready';
+ snapshot: ProviderAccountUsageSnapshot;
+ stale: boolean;
+ error?: ProviderAccountUsageError;
+ retryAt?: number;
+ };
+
+/**
+ * 智谱 GLM Coding Plan 的官方用量页。套餐额度(5 小时 / 每周积分)只能在这页看:
+ * 开放平台对 Coding Plan key 没有公开的余额 / 配额查询 API(2026-10 实测 + 官方文档
+ * 「积分额度」节指引),余额接口对 Coding key 也是 404。因此 GLM Coding Plan 不做余额
+ * 拉取,只给这个入口。
+ */
+export const ZHIPU_CODING_PLAN_USAGE_URL = 'https://www.bigmodel.cn/coding-plan/personal/usage';
+
+/** 余额查询优先用的 runtime 顺序(与用户实际配置密度对齐,命中即止)。 */
+export const PROVIDER_ACCOUNT_USAGE_AGENTS: readonly AgentKind[] = [
+ 'claude-code',
+ 'codex',
+ 'pi',
+];