Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修正账户看板与并发查询回退
Dash22170966e1b2
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.tsindex 73289b4593..fdfbeae446 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@@ -331,6 +331,7 @@ describe('readProviderAccountUsage', () => {status: 'ready',stale: false,agent: 'claude-code',+ dashboardUrl: 'https://platform.deepseek.com/usage',snapshot: {kind: 'deepseek-balance',isAvailable: true,@@ -375,12 +376,48 @@ describe('readProviderAccountUsage', () => {upstream = 'https://api.z.ai/api/anthropic';await expect(readProviderAccountUsage({ providerId: 'deepseek' })).resolves.toEqual({status: 'unavailable', error: 'auth',+ dashboardUrl: 'https://z.ai/manage-apikey/coding-plan/personal/my-plan',});expect(fetchMock).toHaveBeenLastCalledWith('https://api.z.ai/api/monitor/usage/quota/limit', expect.anything(),);});+ // PR #7031 review: a delayed failure must neither replace a concurrent success+ // nor discard its TTL/Retry-After state. Unit, promises control ordering without waits.+ it.each([false, true])('retains a concurrent fresh balance after a late failure (prior cache: %s)', async (seedCache) => {+ if (seedCache) {+ setAccountUsageFetch((async () => jsonRes(DEEPSEEK_BALANCE)) as typeof fetch);+ await readProviderAccountUsage({ providerId: 'deepseek' });+ nowMs += 6 * 60_000;+ }+ let finishLate!: (response: Response) => void;+ const updated = { ...DEEPSEEK_BALANCE, balance_infos: [{ ...DEEPSEEK_BALANCE.balance_infos[0], total_balance: '99.00' }] };+ const fetchMock = vi.fn()+ .mockImplementationOnce(() => new Promise<Response>(resolve => { finishLate = resolve; }))+ .mockResolvedValueOnce(jsonRes(updated));+ setAccountUsageFetch(fetchMock as typeof fetch);+ const late = readProviderAccountUsage({ providerId: 'deepseek', forceRefresh: true });+ const fresh = await readProviderAccountUsage({ providerId: 'deepseek', forceRefresh: true });+ finishLate(jsonRes({}, 429, { 'retry-after': '60' }));+ await expect(late).resolves.toEqual(fresh);+ await expect(readProviderAccountUsage({ providerId: 'deepseek' })).resolves.toEqual(fresh);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ // The settings page may use a later engine's key; metadata follows the endpoint+ // actually queried, including unavailable results, rather than the first route.+ it.each([200, 401])('returns the Global dashboard for the resolved engine (HTTP %s)', async (status) => {+ setAccountUsageProviderReader(() => mkProvider({ routing: {+ 'claude-code': { upstream: 'https://open.bigmodel.cn/api/anthropic', authStrategy: 'api-key-header' },+ pi: { upstream: 'https://api.z.ai/api/coding/paas/v4', authStrategy: 'api-key-header' },+ } }));+ setAccountUsageKeyReader((_id, agent) => agent === 'pi' ? 'test-key' : null);+ setAccountUsageFetch((async () => jsonRes(ZHIPU_QUOTA, status)) as typeof fetch);+ const result = await readProviderAccountUsage({ providerId: 'deepseek' });+ expect(result).toMatchObject({ dashboardUrl: 'https://z.ai/manage-apikey/coding-plan/personal/my-plan' });+ });+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.tsindex b4a30b9060..6372271445 100644--- a/apps/desktop/src/main/maker-host/provider-account-usage.ts+++ b/apps/desktop/src/main/maker-host/provider-account-usage.ts@@ -21,6 +21,7 @@ import type { AgentKind, Provider } from '@cindy/model-providers';import {PROVIDER_ACCOUNT_USAGE_AGENTS,+ getProviderAccountUsageDashboardUrl,type DeepSeekAccountUsageSnapshot,type ProviderAccountUsageError,type ProviderAccountUsageRequest,@@ -413,6 +414,15 @@ export async function readProviderAccountUsage(}return { status: 'unsupported' };}+ const result = await readResolvedAccountUsage(request, resolution, ownerStamp);+ return { ...result, dashboardUrl: getProviderAccountUsageDashboardUrl(resolution.endpoint) };+}++async function readResolvedAccountUsage(+ request: ProviderAccountUsageRequest,+ resolution: ProviderAccountUsageResolution,+ ownerStamp: ReturnType<OwnerStampReader>,+): Promise<ProviderAccountUsageResult> {// 缓存键含凭证指纹:同一供应商下换 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.endpoint}:${resolution.agent}:${keyFingerprint}`;@@ -465,6 +475,21 @@ export async function readProviderAccountUsage('provider account usage fetch failed',{ providerId: request.providerId, integrationId: resolution.integrationId, code },);+ // 等待上游期间其它查询可能已更新同一账户;迟到失败不能覆盖该记录,+ // 也不能把新余额/TTL/限流状态回退到本次请求开始前的值。+ const latest = cache.get(cacheKey);+ if (latest && latest !== record) {+ if (latest.snapshot) {+ return {+ status: 'ready', snapshot: latest.snapshot,+ stale: latest.expiresAt <= accountUsageNow() || latest.lastError !== undefined,+ ...(latest.lastError ? { error: latest.lastError } : {}),+ ...(latest.retryAt ? { retryAt: latest.retryAt } : {}),+ agent: resolution.agent,+ };+ }+ return { status: 'unavailable', error: latest.lastError ?? code, ...(latest.retryAt ? { retryAt: latest.retryAt } : {}) };+ }if (err instanceof AccountUsageRequestError && err.retryAt) {cache.set(cacheKey, {snapshot: record?.snapshot,diff --git a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsxindex ee0d9edd31..e2e4947d3f 100644--- a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx+++ b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx@@ -16,6 +16,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ProviderView } from '@cindy/model-providers';+import { ProviderAccountUsageModule } from '../components/settings/ProviderAccountUsageModule';const {providersState,@@ -245,6 +246,29 @@ afterEach(() => {vi.clearAllMocks();});+// PR #7031: settings and chip must both open the queried account's dashboard.+// Unit/jsdom, a CN-first configuration whose usable key belongs to Global/Pi.+it.each(['ready', 'unavailable'])('uses the queried dashboard in the settings card (%s)', async (status) => {+ const dashboardUrl = 'https://z.ai/manage-apikey/coding-plan/personal/my-plan';+ Object.assign(window.electronAPI, { openExternal: vi.fn(async () => undefined) });+ Object.assign(window.electronAPI.maker, { fetchProviderAccountUsage: vi.fn(async () => ({+ status, dashboardUrl,+ ...(status === 'ready'+ ? { agent: 'pi', stale: false, snapshot: { kind: 'zhipu-coding-plan-quota', noPlan: true, level: null, fiveHour: null, weekly: null, fetchedAt: 1 } }+ : { error: 'auth' }),+ })) });+ render(<ProviderAccountUsageModule provider={{+ id: 'mixed-glm', auth: { method: 'apiKey' },+ routing: {+ 'claude-code': { upstream: 'https://open.bigmodel.cn/api/anthropic', authStrategy: 'api-key-header' },+ pi: { upstream: 'https://api.z.ai/api/coding/paas/v4', authStrategy: 'api-key-header' },+ },+ } as ProviderView} />);+ await screen.findByText(status === 'ready' ? 'Pi' : 'providerAccountUsage.error.auth');+ fireEvent.click(screen.getByRole('button', { name: 'providerAccountUsage.zhipuCodingPlan.usage' }));+ expect(window.electronAPI.openExternal).toHaveBeenCalledExactlyOnceWith(dashboardUrl);+});+describe('ProvidersSection — Cindy AI 账户资产模块', () => {it('仅免费个人账号在 Cindy AI 名称后显示身份标签', async () => {modelAccessState.accountTier = 'free';diff --git a/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx b/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsxindex 5acdbc2d82..137e745bc0 100644--- a/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx+++ b/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx@@ -11,8 +11,8 @@ import { useTranslation } from 'react-i18next';import type { ProviderView } from '@cindy/model-providers';-import { ZHIPU_CODING_PLAN_USAGE_URL } from '../../../shared/providerAccountUsage';import {+ getProviderAccountUsageDashboardUrlView,hasDeepSeekOfficialRouteView,isZhipuCodingPlanProviderView,} from '../../lib/providerAccountUsageView';@@ -20,14 +20,13 @@ import { useProviderAccountUsage } from '../../hooks/useProviderAccountUsage';import { QuotaHoverCard } from '../status/QuotaHoverCard';import { buildDeepSeekUsageCard, buildZhipuUsageCard } from '../status/usageCardModel';-const DEEPSEEK_USAGE_DASHBOARD_URL = 'https://platform.deepseek.com/usage';-export function ProviderAccountUsageModule({ provider }: { provider?: ProviderView }) {const { t, i18n } = useTranslation();const locale = i18n.resolvedLanguage ?? i18n.language;const deepSeek = hasDeepSeekOfficialRouteView(provider);const zhipu = isZhipuCodingPlanProviderView(provider);const usage = useProviderAccountUsage(deepSeek || zhipu ? provider : undefined);+ const dashboardUrl = usage.result?.dashboardUrl ?? getProviderAccountUsageDashboardUrlView(provider);if (!deepSeek && !zhipu) return null;const snapshot = usage.result?.status === 'ready' ? usage.result.snapshot : null;const errorText =@@ -58,11 +57,7 @@ export function ProviderAccountUsageModule({ provider }: { provider?: ProviderVivariant="embedded"account={account}dashboardLabel={deepSeek ? t('providerAccountUsage.openDashboard') : t('providerAccountUsage.zhipuCodingPlan.usage')}- onOpenDashboard={- deepSeek- ? () => void window.electronAPI.openExternal(DEEPSEEK_USAGE_DASHBOARD_URL)- : () => void window.electronAPI.openExternal(ZHIPU_CODING_PLAN_USAGE_URL)- }+ onOpenDashboard={dashboardUrl ? () => void window.electronAPI.openExternal(dashboardUrl) : undefined}/></div>);diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 62d92bb8a8..7f5fe5ee8c 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -134,10 +134,11 @@ import {} from './usageCardModel';import { useProviderAccountUsage } from '@/hooks/useProviderAccountUsage';import {+ getProviderAccountUsageDashboardUrlView,hasDeepSeekOfficialRouteView,isZhipuCodingPlanProviderView,} from '@/lib/providerAccountUsageView';-import { ZHIPU_CODING_PLAN_USAGE_URL, type ProviderAccountUsageSnapshot, type ZhipuCodingPlanQuotaSnapshot } from '../../../shared/providerAccountUsage';+import { type ProviderAccountUsageSnapshot, type ZhipuCodingPlanQuotaSnapshot } from '../../../shared/providerAccountUsage';// XD 网关 / 托管账号之前会跳到内部用量看板(内部域名)—— 开源前移除该硬编码。// 登录随凭据只下发 { endpoint, apiKey }(见 main/model-access/credentialsSync.ts),不含@@ -147,7 +148,6 @@ import { ZHIPU_CODING_PLAN_USAGE_URL, type ProviderAccountUsageSnapshot, type Zh// usageDashboardUrl / consoleUrl),据此恢复网关账号的跳转 + tooltip 链接行// (i18n 文案 todaySpend.openProxyUsage 已保留待复用,勿当死 key 删)。const CODEX_USAGE_DASHBOARD_URL = 'https://chatgpt.com/codex/settings/usage';-const DEEPSEEK_USAGE_DASHBOARD_URL = 'https://platform.deepseek.com/usage';const XAI_USAGE_DASHBOARD_URL = 'https://grok.com';const CLAUDE_USAGE_DASHBOARD_URL = 'https://claude.ai/settings/usage';@@ -1383,11 +1383,11 @@ export function TodaySpendChip({? CODEX_USAGE_DASHBOARD_URL: isClaudeSubscription? CLAUDE_USAGE_DASHBOARD_URL- : usesDeepSeekAccountForm- ? DEEPSEEK_USAGE_DASHBOARD_URL- : usesZhipuCodingPlanForm- ? ZHIPU_CODING_PLAN_USAGE_URL- : null;+ : usesProviderAccountUsageForm+ ? providerAccountUsage.result?.dashboardUrl+ ?? getProviderAccountUsageDashboardUrlView(selectedQuotaProvider, providerAccountAgent)+ ?? null+ : null;// 看板链接行文案:与 usageDashboardUrl 一一对应;网关账号无看板 → null// (tooltip 不显示"打开看板"行,chip 也不可点)。const usageDashboardLabel: string | null = isDeviceLinkRemotediff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsxindex 738ce7a1e7..5e80d92f22 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@@ -301,6 +301,7 @@ it.each<{{ vendorKey: 'pi', providerId: 'xai', label: '打开 Grok 用量页面', url: 'https://grok.com' },{ vendorKey: 'pi', providerId: 'deepseek', upstream: 'https://api.deepseek.com', label: 'providerAccountUsage.openDashboard', url: 'https://platform.deepseek.com/usage' },{ vendorKey: 'pi', providerId: 'glm', upstream: 'https://open.bigmodel.cn/api/coding/paas/v4', label: 'providerAccountUsage.zhipuCodingPlan.usage', url: 'https://www.bigmodel.cn/coding-plan/personal/usage' },+ { vendorKey: 'pi', providerId: 'zai', upstream: 'https://api.z.ai/api/coding/paas/v4', label: 'providerAccountUsage.zhipuCodingPlan.usage', url: 'https://z.ai/manage-apikey/coding-plan/personal/my-plan' },{ vendorKey: 'cc', providerId: 'xd', label: '用量明细', url: null },])('opens the selected $providerId account dashboard', async ({ vendorKey, providerId, upstream, label, url }) => {if (upstream) {@@ -308,7 +309,7 @@ it.each<{id: providerId, auth: { method: 'apiKey' },routing: { pi: { upstream, authStrategy: 'api-key-header' } },} as ProviderView];- mocks.fetchProviderAccountUsage.mockResolvedValue({ status: 'unsupported' });+ mocks.fetchProviderAccountUsage.mockResolvedValue({ status: 'unavailable', error: 'auth', dashboardUrl: url });}render(<TodaySpendChip vendorKey={vendorKey} providerId={providerId} sessionId="session-1" />);await act(async () => {});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b15d2182ac..bb8ea36bcb 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1110,8 +1110,8 @@"DEVICE_LINK_MEDIA_ACCESS_DENIED": "Cindy cannot read the source attachment; the message was not sent. Save a copy to Downloads or another accessible folder, remove the original attachment, and add the copy using the attachment button before sending again."},"providerError": {- "AUTH_INVALID": "Invalid or expired API key (401). Check the key and try again",- "AUTH_FORBIDDEN": "Key is valid but access is denied (403). Check plan or model permissions",+ "AUTH_INVALID": "Authentication failed for this interface. Check the address, key, and authentication method.",+ "AUTH_FORBIDDEN": "This interface denied access. Check your plan, model, or regional permissions.","RATE_LIMITED": "Rate limited (429). Try again later","QUOTA_EXCEEDED": "Quota or balance exhausted. Check your provider account","MODEL_NOT_FOUND": "Model not found or not accessible. Check the model ID",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex f09500daa7..0f23c54410 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1098,8 +1098,8 @@"DEVICE_LINK_MEDIA_ACCESS_DENIED": "Cindy が元の添付ファイルを読み取れないため、メッセージは送信されていません。「ダウンロード」などアクセス可能なフォルダーにコピーを保存し、元の添付ファイルを削除してから、添付ボタンでコピーを追加し、再送信してください。"},"providerError": {- "AUTH_INVALID": "API キーが無効か期限切れです(401)。キーを確認して再試行してください",- "AUTH_FORBIDDEN": "キーは有効ですがアクセス権がありません(403)。プランやモデルの権限を確認してください",+ "AUTH_INVALID": "このインターフェースで認証に失敗しました。アドレス、キー、認証方式を確認してください。",+ "AUTH_FORBIDDEN": "このインターフェースへのアクセスが拒否されました。プラン、モデル、地域のアクセス権を確認してください。","RATE_LIMITED": "レート制限中です(429)。しばらくしてから再試行してください","QUOTA_EXCEEDED": "クォータまたは残高が不足しています。プロバイダーのアカウントを確認してください","MODEL_NOT_FOUND": "モデルが存在しないか利用権限がありません。モデル ID を確認してください",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 82594c8f55..8543993f47 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1098,8 +1098,8 @@"DEVICE_LINK_MEDIA_ACCESS_DENIED": "Cindy가 원본 첨부 파일을 읽을 수 없어 메시지가 전송되지 않았습니다. 다운로드 등 접근 가능한 폴더에 사본을 저장하고, 원본 첨부 파일을 제거한 뒤 첨부 버튼으로 사본을 추가하여 다시 전송하세요."},"providerError": {- "AUTH_INVALID": "API 키가 유효하지 않거나 만료되었습니다(401). 키를 확인한 후 다시 시도하세요",- "AUTH_FORBIDDEN": "키는 유효하지만 접근 권한이 없습니다(403). 요금제 또는 모델 권한을 확인하세요",+ "AUTH_INVALID": "이 인터페이스에서 인증에 실패했습니다. 주소, 키 및 인증 방식을 확인하세요.",+ "AUTH_FORBIDDEN": "이 인터페이스가 접근을 거부했습니다. 요금제, 모델 또는 지역 권한을 확인하세요.","RATE_LIMITED": "요청이 제한되었습니다(429). 잠시 후 다시 시도하세요","QUOTA_EXCEEDED": "할당량 또는 잔액이 부족합니다. 제공자 계정을 확인하세요","MODEL_NOT_FOUND": "모델이 존재하지 않거나 사용 권한이 없습니다. 모델 ID를 확인하세요",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1e9879ecdb..e1a7596759 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1098,8 +1098,8 @@"DEVICE_LINK_MEDIA_ACCESS_DENIED": "Cindy 无法读取源附件,消息未发送。请将文件另存到“下载”或其他可访问的文件夹,移除原附件,再用附件按钮添加副本后发送。"},"providerError": {- "AUTH_INVALID": "API 密钥无效或已过期(401),请检查密钥后重试",- "AUTH_FORBIDDEN": "密钥有效但无权访问(403),请检查套餐或模型权限",+ "AUTH_INVALID": "当前接口认证失败,请检查地址、密钥和认证方式",+ "AUTH_FORBIDDEN": "当前接口拒绝访问,请检查套餐、模型或地区权限","RATE_LIMITED": "请求被限流(429),请稍后重试","QUOTA_EXCEEDED": "配额或余额不足,请检查供应商账户","MODEL_NOT_FOUND": "模型不存在或无权使用,请检查模型 ID",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 86a4a57ff7..e29786365a 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1098,8 +1098,8 @@"DEVICE_LINK_MEDIA_ACCESS_DENIED": "Cindy 無法讀取來源附件,訊息未傳送。請將檔案另存到「下載」或其他可存取的資料夾,移除原附件,再用附件按鈕加入副本後傳送。"},"providerError": {- "AUTH_INVALID": "API 金鑰無效或已過期(401),請檢查金鑰後重試",- "AUTH_FORBIDDEN": "金鑰有效但無權訪問(403),請檢查套餐或模型權限",+ "AUTH_INVALID": "目前介面驗證失敗,請檢查位址、金鑰和驗證方式",+ "AUTH_FORBIDDEN": "目前介面拒絕存取,請檢查方案、模型或地區權限","RATE_LIMITED": "請求被限流(429),請稍後重試","QUOTA_EXCEEDED": "配額或餘額不足,請檢查供應商帳戶","MODEL_NOT_FOUND": "模型不存在或無權使用,請檢查模型 ID",diff --git a/apps/desktop/src/renderer/lib/providerAccountUsageView.ts b/apps/desktop/src/renderer/lib/providerAccountUsageView.tsindex b449d2bef0..4674c5ad9e 100644--- a/apps/desktop/src/renderer/lib/providerAccountUsageView.ts+++ b/apps/desktop/src/renderer/lib/providerAccountUsageView.ts@@ -6,7 +6,20 @@* baseUrl 识别;走代理 / 自定义域名的连接不算(key 属于代理,main 侧也不会认领)。*/-import type { ProviderView } from '@cindy/model-providers';+import type { AgentKind, ProviderView } from '@cindy/model-providers';+import { getProviderAccountUsageDashboardUrl, PROVIDER_ACCOUNT_USAGE_AGENTS } from '../../shared/providerAccountUsage';++/** 查询完成前的看板入口;完成后优先消费 main 回带的实际查询端点。 */+export function getProviderAccountUsageDashboardUrlView(+ provider: ProviderView | undefined,+ agent?: AgentKind,+): string | undefined {+ for (const runtime of agent ? [agent] : PROVIDER_ACCOUNT_USAGE_AGENTS) {+ const url = getProviderAccountUsageDashboardUrl(provider?.routing[runtime]?.upstream ?? '');+ if (url) return url;+ }+ return undefined;+}const DEEPSEEK_ORIGIN = 'https://api.deepseek.com';const ZHIPU_ANTHROPIC_BASES = [diff --git a/apps/desktop/src/shared/providerAccountUsage.ts b/apps/desktop/src/shared/providerAccountUsage.tsindex 38be2029d3..4a95e05227 100644--- a/apps/desktop/src/shared/providerAccountUsage.ts+++ b/apps/desktop/src/shared/providerAccountUsage.ts@@ -77,7 +77,7 @@ export type ProviderAccountUsageError =| 'throttled'| 'unknown';-export type ProviderAccountUsageResult =+export type ProviderAccountUsageResult = (/** 该供应商没有可读的账户余额 / 用量接口(renderer 不渲染模块)。 */| { status: 'unsupported' }| { status: 'unavailable'; error: ProviderAccountUsageError; retryAt?: number }@@ -89,7 +89,11 @@ export type ProviderAccountUsageResult =retryAt?: number;/** 本次查询实际使用的 runtime;设置页用它标注余额来自哪个引擎的密钥。 */agent?: AgentKind;- };+ }+) & {+ /** 本次实际查询端点对应的官方看板;同样随鉴权等失败结果返回。 */+ dashboardUrl?: string;+};/*** 智谱 GLM Coding Plan 的官方用量页。无套餐(noPlan)/ 想看积分细则时的一键入口;@@ -97,6 +101,23 @@ export type ProviderAccountUsageResult =*/export const ZHIPU_CODING_PLAN_USAGE_URL = 'https://www.bigmodel.cn/coding-plan/personal/usage';+/** 按官方端点选择看板,不从界面语言或 Cindy 区域推断账号所属网站。 */+export function getProviderAccountUsageDashboardUrl(upstream: string): string | undefined {+ try {+ switch (new URL(upstream).origin) {+ case 'https://api.deepseek.com':+ return 'https://platform.deepseek.com/usage';+ case 'https://open.bigmodel.cn':+ return ZHIPU_CODING_PLAN_USAGE_URL;+ case 'https://api.z.ai':+ return 'https://z.ai/manage-apikey/coding-plan/personal/my-plan';+ }+ } catch {+ // 未配置或非法地址没有对应的官方看板。+ }+ return undefined;+}+/** 余额查询优先用的 runtime 顺序(与用户实际配置密度对齐,命中即止)。 */export const PROVIDER_ACCOUNT_USAGE_AGENTS: readonly AgentKind[] = ['claude-code',