Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 智谱 GLM Coding Plan 额度卡(/api/monitor/usage/quota/limit)
JupiterTheWarlock0352c70a4168
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 12304af474..02454ba7af 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@@ -5,6 +5,7 @@ import type { AgentKind, Provider } from '@cindy/model-providers';import {isZhipuCodingPlanProvider,parseDeepSeekAccountUsage,+ parseZhipuCodingPlanQuota,readProviderAccountUsage,resetProviderAccountUsageForTest,resolveProviderAccountUsage,@@ -97,6 +98,48 @@ describe('parseDeepSeekAccountUsage', () => {});});+const ZHIPU_QUOTA = {+ code: 200,+ msg: 'Operation successful',+ success: true,+ data: {+ limits: [+ { type: 'TIME_LIMIT', unit: 5, number: 1, usage: 1000, currentValue: 0, remaining: 1000, percentage: 0, nextResetTime: 1793129464999 },+ { type: 'TOKENS_LIMIT', unit: 3, number: 5, percentage: 18, nextResetTime: 1792786868808 },+ { type: 'TOKENS_LIMIT', unit: 6, number: 2, percentage: 44, nextResetTime: 1793129464999 },+ ],+ level: 'pro',+ },+};++describe('parseZhipuCodingPlanQuota', () => {+ it('maps unit 3 to the 5-hour window and unit 6 to weekly, keeping level', () => {+ const snapshot = parseZhipuCodingPlanQuota(ZHIPU_QUOTA, 7);+ expect(snapshot).toEqual({+ kind: 'zhipu-coding-plan-quota',+ noPlan: false,+ level: 'pro',+ fiveHour: { usedPercent: 18, resetsAt: 1792786868808 },+ weekly: { usedPercent: 44, resetsAt: 1793129464999 },+ fetchedAt: 7,+ });+ });++ it('recognizes pay-as-you-go accounts (200 + business error mentioning coding plan)', () => {+ const snapshot = parseZhipuCodingPlanQuota(+ { code: 500, msg: '当前用户不存在coding plan', success: false },+ 7,+ );+ expect(snapshot).toMatchObject({ kind: 'zhipu-coding-plan-quota', noPlan: true, level: null });+ });++ it('rejects unrelated business errors and malformed payloads', () => {+ expect(() => parseZhipuCodingPlanQuota({ success: false, msg: 'server busy' }, 1)).toThrow(/invalid/);+ expect(() => parseZhipuCodingPlanQuota({ success: true }, 1)).toThrow(/invalid/);+ expect(() => parseZhipuCodingPlanQuota(null, 1)).toThrow(/invalid/);+ });+});+describe('resolveProviderAccountUsage', () => {beforeEach(() => {resetProviderAccountUsageForTest();@@ -121,6 +164,44 @@ describe('resolveProviderAccountUsage', () => {expect(resolveProviderAccountUsage('deepseek')?.agent).toBe('pi');});+ it('claims zhipu coding-plan routes with the monitor endpoint, not pay-as-you-go', () => {+ setAccountUsageProviderReader(() =>+ 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 },+ },+ }),+ );+ setAccountUsageKeyReader(() => 'glm-key');+ expect(resolveProviderAccountUsage('glm-coding-plan')).toMatchObject({+ integrationId: 'zhipu-coding-plan-quota-v1',+ endpoint: 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',+ });+ // 按量付费(/api/paas)同域不认领。+ setAccountUsageProviderReader(() =>+ mkProvider({+ id: 'zhipu-glm',+ routing: { codex: { upstream: 'https://open.bigmodel.cn/api/paas/v4', authStrategy: 'api-key-header' as const } },+ }),+ );+ expect(resolveProviderAccountUsage('zhipu-glm')).toBeNull();+ });++ it('routes the global coding plan to the z.ai monitor endpoint', () => {+ setAccountUsageProviderReader(() =>+ mkProvider({+ id: 'zai-coding',+ routing: { pi: { upstream: 'https://api.z.ai/api/coding/paas/v4', authStrategy: 'api-key-header' as const } },+ }),+ );+ setAccountUsageKeyReader(() => 'zai-key');+ expect(resolveProviderAccountUsage('zai-coding')).toMatchObject({+ endpoint: 'https://api.z.ai/api/monitor/usage/quota/limit',+ });+ });+it('never claims proxied base URLs or oauth providers', () => {setAccountUsageProviderReader(() =>mkProvider({@@ -265,6 +346,34 @@ describe('readProviderAccountUsage', () => {expect(fetchMock).toHaveBeenCalledTimes(2);});+ it('fetches zhipu quota with raw-key authorization', async () => {+ setAccountUsageProviderReader(() =>+ mkProvider({+ id: 'glm-coding-plan',+ routing: {+ 'claude-code': { upstream: 'https://open.bigmodel.cn/api/anthropic', authStrategy: 'api-key-header' as const },+ },+ }),+ );+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {+ expect(String(input)).toBe('https://open.bigmodel.cn/api/monitor/usage/quota/limit');+ // 智谱不加 Bearer 前缀。+ expect((init?.headers as Record<string, string>).Authorization).toBe('sk-test');+ return jsonRes(ZHIPU_QUOTA);+ });+ setAccountUsageFetch(fetchMock as unknown as typeof fetch);+ const result = await readProviderAccountUsage({ providerId: 'glm-coding-plan' });+ expect(result).toMatchObject({+ status: 'ready',+ snapshot: {+ kind: 'zhipu-coding-plan-quota',+ level: 'pro',+ fiveHour: { usedPercent: 18 },+ weekly: { usedPercent: 44 },+ },+ });+ });+it('classifies invalid JSON as invalid-response', async () => {const fetchMock = vi.fn(async () => new Response('<html>gateway login</html>', { status: 200 }),diff --git a/apps/desktop/src/main/maker-host/provider-account-usage.ts b/apps/desktop/src/main/maker-host/provider-account-usage.tsindex 7358e150d1..d9d16a43b4 100644--- a/apps/desktop/src/main/maker-host/provider-account-usage.ts+++ b/apps/desktop/src/main/maker-host/provider-account-usage.ts@@ -23,6 +23,8 @@ import {type ProviderAccountUsageError,type ProviderAccountUsageRequest,type ProviderAccountUsageResult,+ type ProviderAccountUsageSnapshot,+ type ZhipuCodingPlanQuotaSnapshot,} from '../../shared/providerAccountUsage.js';import { createMakerLogger } from './logger-adapter.js';@@ -37,13 +39,33 @@ const MAX_RETRY_AFTER_MS = 60 * 60_000;/** 官方账户接口清单。端点是唯一事实源,不从目录 / 用户配置推导。 */const INTEGRATIONS = {'deepseek-balance-v1': {- origin: 'https://api.deepseek.com',+ origins: ['https://api.deepseek.com'],endpoint: 'https://api.deepseek.com/user/balance',},+ // 智谱 GLM Coding Plan 额度(GET /api/monitor/usage/quota/limit,裸 key 鉴权)。+ // CN 与 Global 共享路径,端点跟认领到的 runtime 同域;按量付费(/api/paas)不认领。+ 'zhipu-coding-plan-quota-v1': {+ origins: ['https://open.bigmodel.cn', 'https://api.z.ai'],+ endpointFor: (origin: string) =>+ origin === 'https://api.z.ai'+ ? 'https://api.z.ai/api/monitor/usage/quota/limit'+ : 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',+ // Coding Plan 专属接入路径:/api/anthropic(cc)或 /api/coding/*(codex/pi)。+ // 按量付费连接也在这两个域,但路径是 /api/paas/*,不认领。+ pathPrefixes: ['/api/anthropic', '/api/coding/'],+ },} as const;export type ProviderAccountUsageIntegrationId = keyof typeof INTEGRATIONS;+/** 迭代时的宽化视图(异构配置统一成可选字段集合)。 */+type IntegrationView = {+ origins: readonly string[];+ pathPrefixes?: readonly string[];+ endpoint?: string;+ endpointFor?: (origin: string) => string;+};+/** 该供应商是否命中智谱 GLM Coding Plan 的官方接入端点(设置页给「查看套餐用量」入口用)。 */export function isZhipuCodingPlanProvider(provider: Provider | undefined | null): boolean {if (!provider) return false;@@ -65,7 +87,6 @@ export interface ProviderAccountUsageResolution {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 };@@ -103,7 +124,7 @@ export function setAccountUsageNow(now: () => number): void {}interface CacheRecord {- snapshot?: DeepSeekAccountUsageSnapshot;+ snapshot?: ProviderAccountUsageSnapshot;expiresAt: number;lastAttemptAt: number;lastError?: ProviderAccountUsageError;@@ -162,52 +183,75 @@ export function parseDeepSeekAccountUsage(}/**- * 认领规则:apiKey 鉴权 + 某 runtime 的 baseUrl origin 与官方端点 origin 全等。+ * 认领规则:apiKey 鉴权 + 某 runtime 的 baseUrl 与官方端点同域且路径匹配。* https 之外一律不认领(规则同 provider-route 的上游判定,不做子串包含)。+ * 智谱只认领 Coding Plan 接入路径,按量付费(/api/paas)同域也不认领。*/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;+ for (const agent of PROVIDER_ACCOUNT_USAGE_AGENTS) {+ const upstream = provider.routing[agent]?.upstream;+ if (!upstream) continue;+ let url: URL;+ try {+ url = new URL(upstream);+ } catch {+ continue;+ }+ if (url.protocol !== 'https:') continue;+ const origin = url.origin;+ for (const [integrationId, integration] of Object.entries(INTEGRATIONS) as [+ ProviderAccountUsageIntegrationId,+ IntegrationView,+ ][]) {+ if (!integration.origins.includes(origin)) continue;+ if (+ integration.pathPrefixes+ && !integration.pathPrefixes.some((p) => url.pathname === p || url.pathname.startsWith(p))+ ) {+ continue;}- if (!matches) continue;const key = keyReader(providerId, agent)?.trim();if (!key) continue;- return { integrationId, endpoint: integration.endpoint, agent, key };+ const endpoint = integration.endpointFor+ ? integration.endpointFor(origin)+ : integration.endpoint!;+ return { integrationId, endpoint, agent, key };}}return null;}-/** key 归属该 provider 的哪个 runtime 都不关键;余额接口对全账号生效,取任一可用 key。 */+/** 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;- }- }),- );+ return PROVIDER_ACCOUNT_USAGE_AGENTS.some((agent) => {+ const upstream = provider.routing[agent]?.upstream;+ if (!upstream) return false;+ return matchesAnyIntegration(upstream);+ });+}++function matchesAnyIntegration(upstream: string): boolean {+ let url: URL;+ try {+ url = new URL(upstream);+ } catch {+ return false;+ }+ if (url.protocol !== 'https:') return false;+ return Object.values(INTEGRATIONS).some((integration) => {+ const view = integration as IntegrationView;+ if (!view.origins.includes(url.origin)) return false;+ if (view.pathPrefixes) {+ return view.pathPrefixes.some((p) => url.pathname === p || url.pathname.startsWith(p));+ }+ return true;+ });}function mapHttpStatusToError(status: number): ProviderAccountUsageError | null {@@ -217,6 +261,70 @@ function mapHttpStatusToError(status: number): ProviderAccountUsageError | nullreturn null;}+/**+ * 解析智谱 /api/monitor/usage/quota/limit 响应。+ * 按量付费账户回 200 + 业务错误(success:false 且 msg 提到没有 coding plan)→ noPlan+ * 快照(不是故障);其余业务错误 → invalid-response。+ */+export function parseZhipuCodingPlanQuota(+ value: unknown,+ fetchedAt: number,+): ZhipuCodingPlanQuotaSnapshot {+ const fail = (): never => {+ throw new Error('invalid Zhipu coding plan quota response');+ };+ if (!value || typeof value !== 'object' || Array.isArray(value)) return fail();+ const body = value as Record<string, unknown>;+ if (body.success === false) {+ const msg = typeof body.msg === 'string' ? body.msg : '';+ const compact = msg.replace(/[\s_-]/g, '').toLowerCase();+ if (+ compact.includes('codingplan')+ && /不存在|没有|未开通|not exist|not found|not have|doesn't have|no coding plan|not subscribed/.test(msg)+ ) {+ return { kind: 'zhipu-coding-plan-quota', noPlan: true, level: null, fiveHour: null, weekly: null, fetchedAt };+ }+ return fail();+ }+ const data = body.data;+ if (!data || typeof data !== 'object' || Array.isArray(data)) return fail();+ const payload = data as Record<string, unknown>;+ const level = typeof payload.level === 'string' && payload.level.trim() ? payload.level.trim() : null;+ const limits = Array.isArray(payload.limits) ? payload.limits : [];+ let fiveHour: ZhipuCodingPlanQuotaSnapshot['fiveHour'] = null;+ let weekly: ZhipuCodingPlanQuotaSnapshot['weekly'] = null;+ const unclassified: { reset: number | null; percent: number }[] = [];+ for (const item of limits) {+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue;+ const line = item as Record<string, unknown>;+ const type = typeof line.type === 'string' ? line.type.toUpperCase() : '';+ if (type !== 'TOKENS_LIMIT' && type !== 'CREDIT_LIMIT') continue;+ const percent = typeof line.percentage === 'number' && Number.isFinite(line.percentage)+ ? Math.max(0, Math.min(100, line.percentage))+ : null;+ if (percent === null) continue;+ const resetsAt =+ typeof line.nextResetTime === 'number' && Number.isFinite(line.nextResetTime) && line.nextResetTime > 0+ ? line.nextResetTime+ : null;+ const unit = typeof line.unit === 'number' ? line.unit : null;+ // unit 3 = 5 小时窗口、6 = 每周窗口;缺失时兑底:无 reset 优先归 5 小时。+ if (unit === 3 && !fiveHour) fiveHour = { usedPercent: percent, resetsAt };+ else if (unit === 6 && !weekly) weekly = { usedPercent: percent, resetsAt };+ else if (unit == null) unclassified.push({ reset: resetsAt, percent });+ }+ for (const entry of unclassified) {+ if (!fiveHour && entry.reset === null) fiveHour = { usedPercent: entry.percent, resetsAt: null };+ else if (!fiveHour || !weekly) {+ const target = fiveHour ? 'weekly' : 'fiveHour';+ const window = { usedPercent: entry.percent, resetsAt: entry.reset };+ if (target === 'weekly') weekly = window;+ else fiveHour = window;+ }+ }+ return { kind: 'zhipu-coding-plan-quota', noPlan: false, level, fiveHour, weekly, fetchedAt };+}+function parseRetryAfterMs(header: string | null, now: number): number | undefined {if (!header) return undefined;const seconds = Number(header);@@ -227,13 +335,31 @@ function parseRetryAfterMs(header: string | null, now: number): number | undefinasync function fetchDeepSeekBalance(resolution: ProviderAccountUsageResolution,): Promise<DeepSeekAccountUsageSnapshot> {+ return fetchAccountJson(resolution, `Bearer ${resolution.key}`, parseDeepSeekAccountUsage);+}++async function fetchZhipuCodingPlanQuota(+ resolution: ProviderAccountUsageResolution,+): Promise<ZhipuCodingPlanQuotaSnapshot> {+ // 智谱额度接口用裸 key(不带 Bearer),与 cc 实测一致(Bearer 亦可用,取裸 key 更稳)。+ return fetchAccountJson(resolution, resolution.key, parseZhipuCodingPlanQuota);+}++async function fetchAccountJson<T>(+ resolution: ProviderAccountUsageResolution,+ authorization: string,+ parse: (value: unknown, fetchedAt: number) => T,+): Promise<T> {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 headers: Record<string, string> = { Authorization: authorization };+ if (resolution.integrationId === 'zhipu-coding-plan-quota-v1') {+ // 与社区工具(cc-switch)实测口径一致:要求 JSON + 英文文案,响应 msg 语言稳定。+ headers['Content-Type'] = 'application/json';+ headers['Accept-Language'] = 'en-US,en';+ }+ const response = await fetchImpl(resolution.endpoint, { headers, signal: controller.signal });const retryAfterMs = parseRetryAfterMs(response.headers.get('retry-after'), accountUsageNow());const mapped = mapHttpStatusToError(response.status);if (mapped) throw new AccountUsageRequestError(mapped, retryAfterMs);@@ -248,7 +374,7 @@ async function fetchDeepSeekBalance(throw new AccountUsageRequestError('invalid-response');}try {- return parseDeepSeekAccountUsage(payload, accountUsageNow());+ return parse(payload, accountUsageNow());} catch {throw new AccountUsageRequestError('invalid-response');}@@ -295,7 +421,10 @@ export async function readProviderAccountUsage(return { status: 'ready', snapshot: record.snapshot, stale: false };}try {- const snapshot = await fetchDeepSeekBalance(resolution);+ const snapshot =+ resolution.integrationId === 'zhipu-coding-plan-quota-v1'+ ? await fetchZhipuCodingPlanQuota(resolution)+ : await fetchDeepSeekBalance(resolution);cache.set(cacheKey, {snapshot,expiresAt: accountUsageNow() + CACHE_TTL_MS,diff --git a/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx b/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsxindex d71fe45970..1751e69a96 100644--- a/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx+++ b/apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx@@ -21,6 +21,7 @@ import { useProviderAccountUsage } from '../../hooks/useProviderAccountUsage';import { cn } from '@/lib/utils';import { Tip } from '@/components/ui/tooltip';+import { QuotaBar } from '@/components/status/QuotaBar';function formatCurrency(value: string, currency: string, locale: string): string {try {@@ -58,6 +59,78 @@ function UsageMetric({ label, value }: { label: string; value: string }) {);}+/** 智谱 GLM Coding Plan 额度体:套餐档位 + 5 小时 / 每周窗口进度。 */+function ZhipuQuotaBody({+ snapshot,+ locale,+}: {+ snapshot: Extract<ProviderAccountUsageResult, { status: 'ready' }>['snapshot'];+ locale: string;+}) {+ const { t } = useTranslation();+ if (snapshot.kind !== 'zhipu-coding-plan-quota') return null;+ if (snapshot.noPlan) {+ 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('providerAccountUsage.zhipuCodingPlan.noPlan')}</span>+ </p>+ );+ }+ const resetFmt = (resetsAt: number | null) =>+ resetsAt == null+ ? null+ : new Intl.DateTimeFormat(locale, { timeStyle: 'short' }).format(resetsAt);+ const windows: { label: string; usedPercent: number; resetsAt: number | null }[] = [];+ if (snapshot.fiveHour) {+ windows.push({ label: t('providerAccountUsage.zhipuCodingPlan.fiveHour'), ...snapshot.fiveHour });+ }+ if (snapshot.weekly) {+ windows.push({ label: t('providerAccountUsage.zhipuCodingPlan.weekly'), ...snapshot.weekly });+ }+ return (+ <div className="mt-3 space-y-3">+ {snapshot.level && (+ <p className="text-11 text-[var(--text-tertiary)]">+ {t('providerAccountUsage.zhipuCodingPlan.level', { level: snapshot.level })}+ </p>+ )}+ {windows.length === 0 ? (+ <p className="text-13 text-[var(--text-secondary)]">+ {t('providerAccountUsage.zhipuCodingPlan.empty')}+ </p>+ ) : (+ windows.map((window) => {+ const resets = resetFmt(window.resetsAt);+ return (+ <div key={window.label} 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)]">{window.label}</span>+ <span className="text-13 font-medium tabular-nums text-[var(--text-primary)]">+ {t('providerAccountUsage.zhipuCodingPlan.usedPercent', {+ value: Math.round(window.usedPercent),+ })}+ </span>+ </div>+ <div className="mt-2">+ <QuotaBar+ usedPercent={window.usedPercent}+ ariaLabel={window.label}+ />+ </div>+ {resets && (+ <p className="mt-1.5 text-11 text-[var(--text-tertiary)]">+ {t('providerAccountUsage.zhipuCodingPlan.resetsAt', { time: resets })}+ </p>+ )}+ </div>+ );+ })+ )}+ </div>+ );+}+function BalanceBody({result,locale,@@ -200,14 +273,17 @@ export function ProviderAccountUsageModule({ provider }: { provider?: ProviderVi)}</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>+ <ZhipuQuotaBody snapshot={result.snapshot} locale={locale} />+ {result.snapshot.kind === 'deepseek-balance' ? (+ <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}</>) : null)}diff --git a/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts b/apps/desktop/src/renderer/hooks/useProviderAccountUsage.tsindex 9c8d713630..bd156410e6 100644--- a/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts+++ b/apps/desktop/src/renderer/hooks/useProviderAccountUsage.ts@@ -12,6 +12,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import type { ProviderView } from '@cindy/model-providers';import type { ProviderAccountUsageResult } from '../../shared/providerAccountUsage';+import { isZhipuCodingPlanProviderView } from '../lib/zhipuCodingPlan';export interface ProviderAccountUsageState {/** false = 该供应商没有可读的账户接口,调用方不应渲染模块。 */@@ -23,7 +24,7 @@ export interface ProviderAccountUsageState {const DEEPSEEK_ORIGIN = 'https://api.deepseek.com';-/** 供应商任一 runtime 是否指向官方 DeepSeek 端点(与 main 的认领规则同一口径,仅用于首屏免查询裁剪)。 */+/** 任一 runtime 是否指向官方 DeepSeek 端点(与 main 认领规则同口径,首屏免查询裁剪用)。 */function hasDeepSeekOfficialRoute(provider: ProviderView | undefined): boolean {if (!provider) return false;return Object.values(provider.routing ?? {}).some((route) => {@@ -44,7 +45,7 @@ export function useProviderAccountUsage(const supported =!!provider&& provider.auth?.method !== 'oauth'- && hasDeepSeekOfficialRoute(provider);+ && (hasDeepSeekOfficialRoute(provider) || isZhipuCodingPlanProviderView(provider));const [result, setResult] = useState<ProviderAccountUsageResult | null>(null);const [busy, setBusy] = useState(false);const requestId = useRef(0);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9d2ea1fcc7..7d60bb79b1 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,5 +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."}},+ "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", "level": "Plan: {{level}}", "fiveHour": "5-hour credits", "weekly": "Weekly credits", "usedPercent": "{{value}}% used", "resetsAt": "Resets {{time}}", "noPlan": "This key has no GLM Coding Plan subscription (likely a pay-as-you-go account). Check the website.", "empty": "Zhipu returned no quota windows. Retry later or open the usage page."},"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.jsonindex 633dc150b6..38994c95dc 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,5 +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":"プロバイダーの残高を読み込めませんでした。後でもう一度お試しください。"}},+ "providerAccountUsage": {"title":"アカウント残高","refresh":"残高を更新","retry":"残高の取得を再試行","updating":"残高を確認しています…","updatedAt":"{{time}} に更新","stale":"古いスナップショットを表示中","openDashboard":"DeepSeek の使用量ページを開く","deepSeek":{"granted":"付与残高","toppedUp":"チャージ残高","unavailable":"DeepSeek が残高情報を返しませんでした。使用量ページを開くか、後でもう一度お試しください。","empty":"DeepSeek から残高明細が返されませんでした。使用量ページでアカウントを確認してください。"},"zhipuCodingPlan":{"usage":"Zhipu プランの使用量を見る", "level": "プラン:{{level}}", "fiveHour": "5時間クレジット", "weekly": "週間クレジット", "usedPercent": "{{value}}% 使用済み", "resetsAt": "{{time}} にリセット", "noPlan": "このキーには GLM Coding Plan のサブスクリプションがありません(従量課金アカウントの可能性)。公式サイトで確認してください。", "empty": "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.jsonindex 556e5c66b3..e55435aeb4 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,5 +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":"제공자 잔액을 불러올 수 없습니다. 나중에 다시 시도하세요."}},+ "providerAccountUsage": {"title":"계정 잔액","refresh":"잔액 새로 고침","retry":"잔액 조회 다시 시도","updating":"잔액을 확인하는 중…","updatedAt":"{{time}}에 업데이트됨","stale":"이전 스냅샷 표시 중","openDashboard":"DeepSeek 사용량 페이지 열기","deepSeek":{"granted":"증여 잔액","toppedUp":"충전 잔액","unavailable":"DeepSeek가 잔액 내역을 제공하지 않았습니다. 사용량 페이지를 열거나 나중에 다시 시도하세요.","empty":"DeepSeek가 잔액 내역을 반환하지 않았습니다. 사용량 페이지에서 계정을 확인하세요."},"zhipuCodingPlan":{"usage":"Zhipu 플랜 사용량 보기", "level": "플랜: {{level}}", "fiveHour": "5시간 크레딧", "weekly": "주간 크레딧", "usedPercent": "{{value}}% 사용됨", "resetsAt": "{{time}} 초기화", "noPlan": "이 키에는 GLM Coding Plan 구독이 없습니다(종량제 계정일 가능성). 공식 사이트에서 확인하세요.", "empty": "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": "첨부 파일 접근 확인",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 9ed83041fb..a3ec799cb0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,5 +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 无法加载供应商余额,请稍后重试。"}},+ "providerAccountUsage": {"title":"账户余额","refresh":"刷新余额","retry":"重试余额查询","updating":"正在查询余额…","updatedAt":"更新于 {{time}}","stale":"正在显示旧快照","openDashboard":"打开 DeepSeek 用量页","deepSeek":{"granted":"赠送余额","toppedUp":"充值余额","unavailable":"DeepSeek 暂时没有提供余额明细,请打开用量页或稍后重试。","empty":"DeepSeek 没有返回余额明细,请打开用量页检查账户。"},"zhipuCodingPlan":{"usage":"查看智谱套餐用量", "level": "套餐:{{level}}", "fiveHour": "5 小时积分", "weekly": "每周积分", "usedPercent": "已用 {{value}}%", "resetsAt": "{{time}} 重置", "noPlan": "这个 key 没有订阅 GLM Coding Plan(可能是按量付费账户),请在官网确认。", "empty": "智谱没有返回配额窗口信息,请稍后重试或打开用量页。"},"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.jsonindex 5b1bb48cb9..e9ccf19f32 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,5 +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 無法載入供應商餘額,請稍後重試。"}},+ "providerAccountUsage": {"title":"帳戶餘額","refresh":"重新整理餘額","retry":"重試餘額查詢","updating":"正在查詢餘額…","updatedAt":"更新於 {{time}}","stale":"正在顯示舊快照","openDashboard":"開啟 DeepSeek 用量頁","deepSeek":{"granted":"贈送餘額","toppedUp":"儲值餘額","unavailable":"DeepSeek 暫時沒有提供餘額明細,請開啟用量頁或稍後重試。","empty":"DeepSeek 沒有回傳餘額明細,請開啟用量頁檢查帳戶。"},"zhipuCodingPlan":{"usage":"查看智譜套餐用量", "level": "方案:{{level}}", "fiveHour": "5 小時積分", "weekly": "每週積分", "usedPercent": "已用 {{value}}%", "resetsAt": "{{time}} 重置", "noPlan": "這把金鑰沒有訂閱 GLM Coding Plan(可能是按用量付費帳戶),請在官網確認。", "empty": "智譜沒有回傳配額窗口資訊,請稍後重試或開啟用量頁。"},"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/shared/providerAccountUsage.ts b/apps/desktop/src/shared/providerAccountUsage.tsindex dbc71d96d0..3ea047d7ba 100644--- a/apps/desktop/src/shared/providerAccountUsage.ts+++ b/apps/desktop/src/shared/providerAccountUsage.ts@@ -33,7 +33,32 @@ export interface DeepSeekAccountUsageSnapshot {fetchedAt: number;}-export type ProviderAccountUsageSnapshot = DeepSeekAccountUsageSnapshot;+export type ProviderAccountUsageSnapshot =+ | DeepSeekAccountUsageSnapshot+ | ZhipuCodingPlanQuotaSnapshot;++/** 智谱 GLM Coding Plan 一个计费窗口的已用比例与重置时间。 */+export interface ZhipuCodingPlanWindow {+ /** 已用百分比(0-100,上游原值)。 */+ usedPercent: number;+ /** epoch ms;null = 上游未提供(如 0% 状态下可能缺席)。 */+ resetsAt: number | null;+}++/**+ * 智谱 GLM Coding Plan 额度快照(GET /api/monitor/usage/quota/limit,鉴权用裸 key)。+ * 窗口语义按上游 unit 字段:3 = 5 小时积分、6 = 每周积分;老套餐只回 5 小时一条。+ * 按量付费账户无套餐:HTTP 200 + 业务错误(msg 提 coding plan 不存在)→ noPlan=true。+ */+export interface ZhipuCodingPlanQuotaSnapshot {+ kind: 'zhipu-coding-plan-quota';+ noPlan: boolean;+ /** 套餐档位(如 lite / pro / max);noPlan 或未回时为 null。 */+ level: string | null;+ fiveHour: ZhipuCodingPlanWindow | null;+ weekly: ZhipuCodingPlanWindow | null;+ fetchedAt: number;+}export type ProviderAccountUsageError =| 'no-credentials'@@ -59,10 +84,8 @@ export type ProviderAccountUsageResult =};/**- * 智谱 GLM Coding Plan 的官方用量页。套餐额度(5 小时 / 每周积分)只能在这页看:- * 开放平台对 Coding Plan key 没有公开的余额 / 配额查询 API(2026-10 实测 + 官方文档- * 「积分额度」节指引),余额接口对 Coding key 也是 404。因此 GLM Coding Plan 不做余额- * 拉取,只给这个入口。+ * 智谱 GLM Coding Plan 的官方用量页。无套餐(noPlan)/ 想看积分细则时的一键入口;+ * 额度数值由 /api/monitor/usage/quota/limit 拉取(2026-10 实测可用)。*/export const ZHIPU_CODING_PLAN_USAGE_URL = 'https://www.bigmodel.cn/coding-plan/personal/usage';