Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 在设置和会话 chip 显示 SuperGrok 账号周用量
Dash35484813bea8
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex b9cca600ef..4d0fc51fe7 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -631,6 +631,7 @@ import { registerMakerStatusIpc } from './maker-ipc/status.js';import {registerMakerUsageIpc,syncClaudeSubscriptionUsageForAuthChange,+ syncXaiSubscriptionUsageForAuthChange,} from './maker-ipc/usage.js';import { prewarmModelPricing } from './usage/modelPricing.js';import { registerMakerBinaryVersionIpc } from './maker-ipc/binary-version.js';@@ -3773,7 +3774,9 @@ const registerIpcHandlers = () => {clearXaiDiscoveredModels();clearXaiMediaModels();clearXaiRateLimitSnapshot();- broadcastXaiAuthStateChanged();+ void syncXaiSubscriptionUsageForAuthChange().then(() => {+ broadcastXaiAuthStateChanged();+ });});// xAI(SuperGrok 订阅)OAuth —— 与 claude-oauth 同形态。登录成功后 bridge 的 xai provider 立即可用@@ -3795,6 +3798,7 @@ const registerIpcHandlers = () => {// xAI 连接态,不再等 remount/手动刷新(对齐 CLAUDE_OAUTH_LOGIN 的 broadcastClaudeAuthStateChanged)。// 限流快照是账号级的:重登可能换账号,旧快照一并清掉(等新账号首个 xai/ 轮自然补上)。clearXaiRateLimitSnapshot();+ await syncXaiSubscriptionUsageForAuthChange();broadcastXaiAuthStateChanged();void refreshXaiModelsFromHttp();void refreshProviderModelsManually('xai').catch((error) => {@@ -3821,6 +3825,7 @@ const registerIpcHandlers = () => {// 登出后同步广播给其它窗口,让已挂载的 useProviders 立刻重拉连接态;// 并清掉账号级限流快照 —— 登出后没有下一个成功响应来覆盖,不清会一直挂着旧账号余量。clearXaiRateLimitSnapshot();+ await syncXaiSubscriptionUsageForAuthChange();broadcastXaiAuthStateChanged();return { authorized: hasGrokOAuthLogin() };});diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.tsindex bf08cff7ae..630b472173 100644--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts@@ -288,8 +288,8 @@ function xaiProviderConfig(): BridgeProviderConfig {buildHeaders: async () => ({authorization: `Bearer ${await getGrokAccessToken()}`,}),- // api.x.ai 无 ChatGPT 那种订阅窗口端点;尽力抓响应头 x-ratelimit-* 给底部 chip 展示,- // 拿不到(上游不返头)则 renderer 诚实降级为仅价值估算。+ // 周用量走 cli-chat-proxy billing,不在这条推理链上。这里只尽力抓 x-ratelimit-*+ // 作为 RPM/TPM 瞬时值;拿不到不影响账号周用量 chip。onRateLimit: (info) => recordXaiRateLimitSnapshot(info),// 上游判定 OAuth 凭证失效时收口本地登录态。缺这一步的话:token 被服务端提前作废后// 本地 expires_at 仍未到期 → 永不刷新 → 每次请求都 403,而「设置 → 模型供应商」还diff --git a/apps/desktop/src/main/maker-host/model-discovery/xai.ts b/apps/desktop/src/main/maker-host/model-discovery/xai.tsindex 3844d05b6e..ad8d387bd6 100644--- a/apps/desktop/src/main/maker-host/model-discovery/xai.ts+++ b/apps/desktop/src/main/maker-host/model-discovery/xai.ts@@ -295,15 +295,25 @@ async function fetchJson(}}-function baseHeaders(accessToken: string): Record<string, string> {+/** SuperGrok cli-chat-proxy 共用请求头。用量查询与模型发现走同一套。 */+export function buildXaiCliProxyHeaders(+ accessToken: string,+ extras?: { userId?: string },+): Record<string, string> {return {Authorization: `Bearer ${accessToken}`,+ Accept: 'application/json','X-XAI-Token-Auth': 'xai-grok-cli','x-grok-client-version': XAI_GROK_CLIENT_VERSION,'x-grok-client-mode': 'interactive',+ ...(extras?.userId ? { 'x-userid': extras.userId } : {}),};}+function baseHeaders(accessToken: string): Record<string, string> {+ return buildXaiCliProxyHeaders(accessToken);+}+function parseUserIdentity(payload: unknown): XaiUserIdentity {if (!isRecord(payload))throw new Error('xAI account model discovery returned an invalid user payload');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.tsindex b7bfe4ceac..473308efff 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts@@ -1193,6 +1193,7 @@ describe('maker usage IPC handlers', () => {readCodexRateLimits: vi.fn(),consumeCodexRateLimitReset: vi.fn(),readClaudeSubscriptionUsageSnapshot: vi.fn().mockResolvedValue(null),+ readXaiSubscriptionUsageSnapshot: vi.fn().mockResolvedValue(null),readClaudeAccountUsageSnapshot: vi.fn(),triggerClaudeAccountUsageRefresh: vi.fn(),readModelPricing: vi.fn(),@@ -1216,6 +1217,37 @@ describe('maker usage IPC handlers', () => {expect(readAgentTodayUsage).toHaveBeenCalledWith('codex');});+ it('rejects SuperGrok usage reads from untrusted senders', async () => {+ const harness = new IpcHarness();+ const readXaiSubscriptionUsageSnapshot = vi.fn().mockResolvedValue({ planLabel: 'SuperGrok Heavy' });+ const assertTrustedSender = vi.fn(() => {+ throw new Error('[PERMISSION_DENIED] untrusted');+ });+ registerMakerUsageHandlers(harness, makeUsageDeps({+ readXaiSubscriptionUsageSnapshot,+ assertTrustedSender,+ }));++ await expect(harness.invoke(MAKER_INVOKE.USAGE_XAI_SUBSCRIPTION)).rejects.toThrow(+ /PERMISSION_DENIED/,+ );+ expect(readXaiSubscriptionUsageSnapshot).not.toHaveBeenCalled();+ });++ it('reads SuperGrok usage after the trusted-sender gate passes', async () => {+ const harness = new IpcHarness();+ const snapshot = { planLabel: 'SuperGrok Heavy', creditUsagePercent: 2 };+ const readXaiSubscriptionUsageSnapshot = vi.fn().mockResolvedValue(snapshot);+ const assertTrustedSender = vi.fn();+ registerMakerUsageHandlers(harness, makeUsageDeps({+ readXaiSubscriptionUsageSnapshot,+ assertTrustedSender,+ }));++ await expect(harness.invoke(MAKER_INVOKE.USAGE_XAI_SUBSCRIPTION)).resolves.toEqual(snapshot);+ expect(assertTrustedSender).toHaveBeenCalledOnce();+ });+it('warm-starts Claude account usage refresh when snapshot is empty', async () => {const harness = new IpcHarness();const triggerClaudeAccountUsageRefresh = vi.fn().mockResolvedValue(undefined);diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 4ac12800ae..7ed0012238 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -309,6 +309,8 @@ export const MAKER_INVOKE = {USAGE_CODEX_RATE_LIMIT_RESET: 'maker:usage:codex-rate-limit-reset',// Claude 订阅账号余量 (oauth/usage 端点 + unified headers 双源, cached-first) — 状态栏 chip 用USAGE_CLAUDE_SUBSCRIPTION: 'maker:usage:claude-subscription',+ // SuperGrok 账号周用量 (cli-chat-proxy settings + billing?format=credits)+ USAGE_XAI_SUBSCRIPTION: 'maker:usage:xai-subscription',// device-link v1 模型单价表:保留 modelId → USD/Mtok 扁平形状,旧控制端继续可读。USAGE_MODEL_PRICING: 'maker:usage:model-pricing',// Desktop renderer v2:Cindy AI `/models` 下发的 XD 原生报价。diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 7b01923958..21ff3a1239 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -502,7 +502,11 @@ import {} from '../../shared/regionalMoney.js';import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';-import { triggerClaudeSubscriptionUsageRefresh, triggerCodexAccountUsageRefresh } from './usage.js';+import {+ triggerClaudeSubscriptionUsageRefresh,+ triggerCodexAccountUsageRefresh,+ triggerXaiSubscriptionUsageRefresh,+} from './usage.js';import {rebroadcastCodexTodayUsage,rebroadcastTodaySpend,@@ -4620,6 +4624,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidvoid modelPromise.then((m) => {if (m && m.startsWith(CHATGPT_MODEL_PREFIX)) triggerCodexAccountUsageRefresh();+ if (m && m.startsWith(XAI_MODEL_PREFIX)) triggerXaiSubscriptionUsageRefresh();}).catch(() => {/* 模型解析失败: 跳过, 非致命 */@@ -4831,6 +4836,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidvoid modelPromise.then((model) => {const hasGatewayKey = Boolean(readClaudeApiKey());+ if (!isRemoteCodexSession && model.startsWith(XAI_MODEL_PREFIX)) {+ triggerXaiSubscriptionUsageRefresh();+ return;+ }if (!isRemoteCodexSession &&!isCustomProviderRoute &&@@ -4992,11 +5001,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidtriggerCodexAccountUsageRefresh();} else if (effectiveProvider === 'anthropic') {triggerClaudeSubscriptionUsageRefresh();+ } else if (effectiveProvider === 'xai') {+ triggerXaiSubscriptionUsageRefresh();} else if (effectiveProvider === 'xd' || effectiveProvider == null) {void triggerClaudeAccountUsageRefresh();}- // xAI 没有独立订阅窗口端点;Responses bridge 从响应 headers 实时更新- // useXaiRateLimit 消费的快照,无需额外网络请求。})();}}diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.tsindex 14c04d1e3e..23a8edbb8c 100644--- a/apps/desktop/src/main/maker-ipc/usage.ts+++ b/apps/desktop/src/main/maker-ipc/usage.ts@@ -11,6 +11,7 @@ import path from 'node:path';import type { Maker } from '@cindy/maker-core';import { createLogger } from '../logger.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { getCachedBinaryStatus } from '../agent-binaries/index.js';import {readClaudeAccountUsageSnapshot,@@ -22,6 +23,12 @@ import {fetchClaudeSubscriptionUsageSnapshot,} from '../usage/claudeSubscriptionUsage.js';import { createClaudeSubscriptionUsageReader } from '../usage/claudeSubscriptionUsageRefresh.js';+import {+ XaiSubscriptionUsageRateLimitedError,+ XaiSubscriptionUsageUnauthorizedError,+ fetchXaiSubscriptionUsageSnapshot,+} from '../usage/xaiSubscriptionUsage.js';+import { createXaiSubscriptionUsageReader } from '../usage/xaiSubscriptionUsageRefresh.js';import { createCodexAccountUsageSnapshotReader } from '../usage/codexAccountUsageRefresh.js';import { getGatewayModelPricing } from '../usage/modelPricing.js';import { getReferenceModelPricing } from '../usage/referenceModelPricing.js';@@ -33,14 +40,19 @@ import { emptyUsageHistoryPayload, readUsageHistory } from '../usage/usageHistorimport {clearClaudeSubscriptionUsageSnapshot,clearCodexAccountUsageSnapshot,+ clearXaiSubscriptionUsageSnapshot,readAgentTodayUsage,readClaudeSubscriptionUsageSnapshot,readCodexAccountUsageSnapshot,+ readXaiSubscriptionUsageSnapshot,recordClaudeSubscriptionUsageSnapshot,recordCodexAccountUsageSnapshot,+ recordXaiSubscriptionUsageSnapshot,} from '../usageBroadcaster.js';import { desktopCodexAuthAdapter } from '../maker-host/auth-adapters.js';import { readClaudeAiOAuth } from '../maker-host/claude-credentials-store.js';+import { getGrokAccessToken, hasGrokOAuthLogin } from '../maker-host/grok-oauth-login.js';+import { outboundFetch } from '../maker-host/outbound-fetch.js';import { setClaudeRateLimitHeadersListener } from '../maker-host/claude-rate-limit-headers-observer.js';import { createCodexRateLimitResetService } from '../usage/codexRateLimitReset.js';@@ -165,6 +177,49 @@ export function syncClaudeSubscriptionUsageForAuthChange(): void {});}+async function readXaiCredentialsInfo(): Promise<{ accessToken: string } | null> {+ if (!hasGrokOAuthLogin()) return null;+ try {+ const accessToken = await getGrokAccessToken();+ return accessToken ? { accessToken } : null;+ } catch {+ return null;+ }+}++const xaiSubscriptionUsageReader = createXaiSubscriptionUsageReader({+ readCredentials: readXaiCredentialsInfo,+ fetchSnapshot: (credentials) =>+ fetchXaiSubscriptionUsageSnapshot({+ accessToken: credentials.accessToken,+ fetchFn: outboundFetch,+ }),+ recordSnapshot: recordXaiSubscriptionUsageSnapshot,+ clearSnapshot: clearXaiSubscriptionUsageSnapshot,+ readCachedSnapshot: readXaiSubscriptionUsageSnapshot,+ now: () => Date.now(),+ isUnauthorizedError: (err) => err instanceof XaiSubscriptionUsageUnauthorizedError,+ isRateLimitedError: (err) => err instanceof XaiSubscriptionUsageRateLimitedError,+ onRefreshError: (err) => {+ log.warn(+ 'xAI subscription usage refresh failed:',+ err instanceof Error ? err.message : String(err),+ );+ },+});++/** SuperGrok 周用量:turn-done 钩子,节流 / 退避 / 未登录 no-op 都在 reader 内。 */+export function triggerXaiSubscriptionUsageRefresh(): void {+ xaiSubscriptionUsageReader.triggerRefresh();+}++/** SuperGrok 登录 / 登出 / 换号后强制同步(先清再拉)。调用方应 await 后再广播连接态。 */+export function syncXaiSubscriptionUsageForAuthChange(): Promise<void> {+ return xaiSubscriptionUsageReader.syncForCredentialChange().catch(() => {+ /* reader 内部已把错误交给 onRefreshError */+ });+}+const readCodexAccountUsageSnapshotWithWebRefresh = createCodexAccountUsageSnapshotReader({readAccessToken: () => desktopCodexAuthAdapter.getAccessToken(),readAccountId: () => desktopCodexAuthAdapter.getAccountId(),@@ -218,6 +273,10 @@ export function registerMakerUsageIpc(maker: Maker): void {desktopCodexAuthAdapter.verifyRecoveryWithAccountRpc(() => codexRateLimitResetService.read()),consumeCodexRateLimitReset: codexRateLimitResetService.consume,readClaudeSubscriptionUsageSnapshot: () => claudeSubscriptionUsageReader.read(),+ readXaiSubscriptionUsageSnapshot: () => xaiSubscriptionUsageReader.read(),+ assertTrustedSender: (event) => {+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);+ },readClaudeAccountUsageSnapshot,triggerClaudeAccountUsageRefresh,readModelPricing: getGatewayModelPricing,diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.tsindex 0f7bb18968..0d1dd0f8f1 100644--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts@@ -11,6 +11,7 @@ import type {MobileCodexRateLimitsResult,} from '@cindy/maker-shared/device-link-contract';import type { ClaudeSubscriptionUsageSnapshot } from '../../shared/claudeSubscriptionUsage.js';+import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage.js';import type { ClaudeAccountUsageSnapshot } from '../usage/claudeAccountUsage.js';import type { ModelPricingMap } from '../usage/modelPricing.js';import type { UsageHistoryPayload, UsageHistoryReadOptions } from '../usage/usageHistory.js';@@ -60,6 +61,8 @@ export interface MakerUsageHandlerDeps {readCodexRateLimits(): Promise<MobileCodexRateLimitsResult>;consumeCodexRateLimitReset(idempotencyKey: string): Promise<MobileCodexRateLimitResetResult>;readClaudeSubscriptionUsageSnapshot(): Promise<ClaudeSubscriptionUsageSnapshot | null>;+ readXaiSubscriptionUsageSnapshot(): Promise<XaiSubscriptionUsageSnapshot | null>;+ assertTrustedSender?(event: unknown): void;readClaudeAccountUsageSnapshot(): ClaudeAccountUsageSnapshot | null;triggerClaudeAccountUsageRefresh(force: boolean): Promise<void>;readModelPricing(): Promise<ModelPricingMap | null>;@@ -123,6 +126,11 @@ export function registerMakerUsageHandlers(return await deps.readClaudeSubscriptionUsageSnapshot();});+ registry.handle(MAKER_INVOKE.USAGE_XAI_SUBSCRIPTION, async (event) => {+ deps.assertTrustedSender?.(event);+ return await deps.readXaiSubscriptionUsageSnapshot();+ });+// device-link v1:保留旧扁平 USD 形状,不能把 CNY 伪装成 *Usd。registry.handle(MAKER_INVOKE.USAGE_MODEL_PRICING, async () => {return toLegacyUsdModelPricing(await deps.readModelPricing());diff --git a/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.ts b/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.tsnew file mode 100644index 0000000000..b326ca3780--- /dev/null+++ b/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.ts@@ -0,0 +1,181 @@+import { describe, expect, it, vi } from 'vitest';++import { XAI_GROK_CLIENT_VERSION } from '../../maker-host/model-discovery/xai';+import {+ fetchXaiSubscriptionUsageSnapshot,+ fingerprintXaiSubject,+ XaiSubscriptionUsageRateLimitedError,+ XaiSubscriptionUsageUnauthorizedError,+} from '../xaiSubscriptionUsage';++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++describe('fetchXaiSubscriptionUsageSnapshot', () => {+ it('sends grok-cli headers, optional x-userid, and hashes only the OIDC subject', async () => {+ const fetchFn = vi.fn(async (url: string, init?: RequestInit) => {+ const headers = new Headers(init?.headers);+ expect(headers.get('Authorization')).toBe('Bearer tok');+ expect(headers.get('X-XAI-Token-Auth')).toBe('xai-grok-cli');+ expect(headers.get('x-grok-client-version')).toBe(XAI_GROK_CLIENT_VERSION);+ expect(headers.get('x-grok-client-mode')).toBe('interactive');+ if (url.includes('/user?')) {+ return jsonResponse(200, { userId: 'user-1', unknownField: 'keep-out' });+ }+ if (url.includes('/settings')) {+ expect(headers.get('x-userid')).toBeNull();+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });+ }+ if (url.includes('format=credits')) {+ expect(headers.get('x-userid')).toBeNull();+ return jsonResponse(200, {+ config: {+ creditUsagePercent: 2,+ currentPeriod: { end: '2026-08-18T09:53:45.527500+00:00' },+ productUsage: [{ product: 'GrokBuild', usagePercent: 2 }],+ prepaidBalance: { val: 0 },+ },+ });+ }+ if (url.includes('/userinfo')) {+ return jsonResponse(200, {+ sub: '9098ceb0-3131-495a-a957-fe40a8891014',+ unknownField: 'keep-out',+ });+ }+ return jsonResponse(404, {});+ });++ const snapshot = await fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: fetchFn as unknown as typeof fetch,+ now: 100,+ });+ expect(snapshot).toMatchObject({+ planLabel: 'SuperGrok Heavy',+ creditUsagePercent: 2,+ productUsage: [{ product: 'GrokBuild', usagePercent: 2 }],+ prepaidBalance: 0,+ accountFingerprint: fingerprintXaiSubject('9098ceb0-3131-495a-a957-fe40a8891014'),+ updatedAt: 100,+ });+ expect(JSON.stringify(snapshot)).not.toContain('keep-out');+ });++ it('still returns plan-only data when userinfo fails', async () => {+ const fetchFn = vi.fn(async (url: string) => {+ if (url.includes('/user?')) return jsonResponse(200, { userId: 'user-1' });+ if (url.includes('/settings')) {+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok' });+ }+ if (url.includes('format=credits')) return jsonResponse(500, {});+ if (url.includes('/userinfo')) return jsonResponse(500, {});+ return jsonResponse(404, {});+ });+ const snapshot = await fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: fetchFn as unknown as typeof fetch,+ });+ expect(snapshot).toMatchObject({+ planLabel: 'SuperGrok',+ accountFingerprint: null,+ });+ });++ it('keeps quota when identity endpoints fail', async () => {+ const fetchFn = vi.fn(async (url: string) => {+ if (url.includes('/user?')) return jsonResponse(401, { error: 'nope' });+ if (url.includes('/userinfo')) return jsonResponse(429, { error: 'slow' });+ if (url.includes('/settings')) {+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });+ }+ if (url.includes('format=credits')) {+ return jsonResponse(200, { config: { creditUsagePercent: 2 } });+ }+ return jsonResponse(404, {});+ });+ const snapshot = await fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: fetchFn as unknown as typeof fetch,+ });+ expect(snapshot).toMatchObject({+ planLabel: 'SuperGrok Heavy',+ creditUsagePercent: 2,+ accountFingerprint: null,+ });+ });++ it('does not let a hung identity request abort quota', async () => {+ const fetchFn = vi.fn(async (url: string, init?: RequestInit) => {+ if (url.includes('/user?')) {+ return await new Promise((_resolve, reject) => {+ init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));+ });+ }+ if (url.includes('/userinfo')) return jsonResponse(200, { sub: 'abc' });+ if (url.includes('/settings')) {+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });+ }+ if (url.includes('format=credits')) {+ return jsonResponse(200, { config: { creditUsagePercent: 2 } });+ }+ return jsonResponse(404, {});+ });+ const snapshot = await fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: fetchFn as unknown as typeof fetch,+ identityTimeoutMs: 20,+ });+ expect(snapshot).toMatchObject({+ planLabel: 'SuperGrok Heavy',+ creditUsagePercent: 2,+ });+ expect(fetchFn.mock.calls.some(([url]) => String(url).includes('/settings'))).toBe(true);+ });++ it('keeps cache on partial quota failure instead of treating it as empty', async () => {+ const fetchFn = vi.fn(async (url: string) => {+ if (url.includes('/settings')) return jsonResponse(503, {});+ if (url.includes('format=credits')) return jsonResponse(200, { config: {} });+ if (url.includes('/user?') || url.includes('/userinfo')) return jsonResponse(200, {});+ return jsonResponse(404, {});+ });+ await expect(fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: fetchFn as unknown as typeof fetch,+ })).resolves.toBeNull();+ });++ it('treats quota 5xx as a transient miss instead of empty', async () => {+ const fetchFn = vi.fn(async (url: string) => {+ if (url.includes('/user?')) return jsonResponse(200, { userId: 'user-1' });+ if (url.includes('/settings') || url.includes('format=credits') || url.includes('/userinfo')) {+ return jsonResponse(503, {});+ }+ return jsonResponse(404, {});+ });+ await expect(fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: fetchFn as unknown as typeof fetch,+ })).resolves.toBeNull();+ });++ it('throws unauthorized/rate-limited without logging response bodies', async () => {+ await expect(fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: vi.fn(async (url: string) => {+ if (url.includes('/user?') || url.includes('/userinfo')) return jsonResponse(200, {});+ return jsonResponse(401, { error: 'nope' });+ }) as unknown as typeof fetch,+ })).rejects.toBeInstanceOf(XaiSubscriptionUsageUnauthorizedError);++ await expect(fetchXaiSubscriptionUsageSnapshot({+ accessToken: 'tok',+ fetchFn: vi.fn(async () => jsonResponse(429, { error: 'slow' })) as unknown as typeof fetch,+ })).rejects.toBeInstanceOf(XaiSubscriptionUsageRateLimitedError);+ });+});diff --git a/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsageRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsageRefresh.test.tsnew file mode 100644index 0000000000..74b0506cc1--- /dev/null+++ b/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsageRefresh.test.ts@@ -0,0 +1,202 @@+import { describe, expect, it, vi } from 'vitest';++import type { XaiSubscriptionUsageSnapshot } from '../../../shared/xaiSubscriptionUsage';+import {+ createXaiSubscriptionUsageReader,+ type XaiSubscriptionCredentialInfo,+} from '../xaiSubscriptionUsageRefresh';++class UnauthorizedError extends Error {}+class RateLimitedError extends Error {}++function makeSnapshot(updatedAt: number): XaiSubscriptionUsageSnapshot {+ return { planLabel: 'SuperGrok Heavy', creditUsagePercent: 2, source: 'cli-billing', updatedAt };+}++function makeDeps(overrides: Partial<{+ credentials: XaiSubscriptionCredentialInfo | null;+ cached: XaiSubscriptionUsageSnapshot | null;+ fetchSnapshot: ReturnType<typeof vi.fn>;+}> = {}) {+ const recordSnapshot = vi.fn().mockResolvedValue(undefined);+ const clearSnapshot = vi.fn().mockResolvedValue(undefined);+ const fetchSnapshot = overrides.fetchSnapshot+ ?? vi.fn().mockResolvedValue(makeSnapshot(1));+ const deps = {+ readCredentials: vi.fn(async () => (+ overrides.credentials === undefined+ ? { accessToken: 'token-a' }+ : overrides.credentials+ )),+ fetchSnapshot,+ recordSnapshot,+ clearSnapshot,+ readCachedSnapshot: vi.fn().mockResolvedValue(overrides.cached ?? null),+ now: () => 1_000_000,+ isUnauthorizedError: (err: unknown) => err instanceof UnauthorizedError,+ isRateLimitedError: (err: unknown) => err instanceof RateLimitedError,+ onRefreshError: vi.fn(),+ };+ return { deps, recordSnapshot, clearSnapshot, fetchSnapshot };+}++async function settle(): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));+}++describe('createXaiSubscriptionUsageReader', () => {+ it('returns the cached snapshot immediately and refreshes in the background', async () => {+ const cached = makeSnapshot(0);+ const fresh = makeSnapshot(2);+ const { deps, recordSnapshot } = makeDeps({+ cached,+ fetchSnapshot: vi.fn().mockResolvedValue(fresh),+ });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 1_000 });++ await expect(reader.read()).resolves.toBe(cached);+ await settle();+ expect(recordSnapshot).toHaveBeenCalledWith(fresh);+ });++ it('clears on logout and on explicit credential change before refetching', async () => {+ const { deps, clearSnapshot, fetchSnapshot } = makeDeps({+ cached: makeSnapshot(0),+ });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 1 });++ deps.readCredentials = vi.fn(async () => null);+ await reader.syncForCredentialChange();+ expect(clearSnapshot).toHaveBeenCalledOnce();+ expect(fetchSnapshot).not.toHaveBeenCalled();++ clearSnapshot.mockClear();+ deps.readCredentials = vi.fn(async () => ({ accessToken: 'token-b' }));+ await reader.syncForCredentialChange();+ expect(clearSnapshot).toHaveBeenCalledOnce();+ await settle();+ expect(fetchSnapshot).toHaveBeenCalledWith({ accessToken: 'token-b' });+ });++ it('clears the snapshot on 401 and does not treat it as a login failure here', async () => {+ const { deps, clearSnapshot } = makeDeps({+ cached: makeSnapshot(0),+ fetchSnapshot: vi.fn().mockRejectedValue(new UnauthorizedError()),+ });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 1 });+ await reader.read();+ await settle();+ expect(clearSnapshot).toHaveBeenCalled();+ });++ it('backs off on 429 and skips fetches until the window elapses', async () => {+ let now = 1_000_000;+ const fetchSnapshot = vi.fn().mockRejectedValue(new RateLimitedError());+ const { deps } = makeDeps({ fetchSnapshot });+ deps.now = () => now;+ const reader = createXaiSubscriptionUsageReader(deps, {+ throttleMs: 1,+ rateLimitBackoffInitialMs: 5_000,+ });++ reader.triggerRefresh();+ await settle();+ expect(fetchSnapshot).toHaveBeenCalledOnce();++ fetchSnapshot.mockClear();+ reader.triggerRefresh();+ await settle();+ expect(fetchSnapshot).not.toHaveBeenCalled();++ now += 5_001;+ reader.triggerRefresh();+ await settle();+ expect(fetchSnapshot).toHaveBeenCalledOnce();+ });++ it('does not refetch inside the throttle window', async () => {+ const fetchSnapshot = vi.fn().mockResolvedValue(makeSnapshot(1));+ const { deps } = makeDeps({ fetchSnapshot });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 60_000 });+ await reader.read();+ await settle();+ fetchSnapshot.mockClear();+ reader.triggerRefresh();+ await settle();+ expect(fetchSnapshot).not.toHaveBeenCalled();+ });++ it('replays the latest account after an in-flight refresh is superseded by login', async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const fetchSnapshot = vi.fn(async (creds: XaiSubscriptionCredentialInfo) => {+ if (creds.accessToken === 'token-a') await gate;+ return makeSnapshot(1);+ });+ const { deps, recordSnapshot } = makeDeps({ fetchSnapshot });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 1 });++ await reader.read();+ deps.readCredentials = vi.fn(async () => ({ accessToken: 'token-b' }));+ await reader.syncForCredentialChange();+ release();+ await settle();+ await settle();++ expect(fetchSnapshot).toHaveBeenCalledWith({ accessToken: 'token-b' });+ expect(recordSnapshot).toHaveBeenCalledWith(makeSnapshot(1));+ });++ it('keeps throttle after 401 so the next turn does not immediately refetch', async () => {+ const fetchSnapshot = vi.fn().mockRejectedValue(new UnauthorizedError());+ const { deps } = makeDeps({ fetchSnapshot });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 60_000 });+ await reader.read();+ await settle();+ fetchSnapshot.mockClear();+ reader.triggerRefresh();+ await settle();+ expect(fetchSnapshot).not.toHaveBeenCalled();+ });++ it('clears the old snapshot before reading the new credential so a later read cannot leak it', async () => {+ let cached: XaiSubscriptionUsageSnapshot | null = {+ planLabel: 'OLD',+ creditUsagePercent: 9,+ };+ const { deps, clearSnapshot } = makeDeps({ cached });+ deps.clearSnapshot = vi.fn(async () => {+ cached = null;+ });+ deps.readCachedSnapshot = vi.fn(async () => cached);+ deps.readCredentials = vi.fn(async () => ({ accessToken: 'token-b' }));+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 1 });+ const sync = reader.syncForCredentialChange();+ await settle();+ expect(deps.clearSnapshot).toHaveBeenCalled();+ await expect(reader.read()).resolves.toBeNull();+ await sync;+ });++ it('does not queue a second fetch for the same in-flight token', async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const fetchSnapshot = vi.fn(async () => {+ await gate;+ return makeSnapshot(1);+ });+ const { deps } = makeDeps({ fetchSnapshot });+ const reader = createXaiSubscriptionUsageReader(deps, { throttleMs: 1 });+ const first = reader.read();+ const second = reader.read();+ await Promise.all([first, second]);+ release();+ await settle();+ expect(fetchSnapshot).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/usage/xaiSubscriptionUsage.ts b/apps/desktop/src/main/usage/xaiSubscriptionUsage.tsnew file mode 100644index 0000000000..c84bed5336--- /dev/null+++ b/apps/desktop/src/main/usage/xaiSubscriptionUsage.ts@@ -0,0 +1,200 @@+/**+ * xaiSubscriptionUsage(main) — 拉取 SuperGrok 账号周用量。+ *+ * 配额权威源只有 settings + billing?format=credits,共用独立超时信号。+ * /v1/user 与 userinfo 是可选 identity:独立短超时,失败或超时不得 abort 配额请求。+ *+ * 请求头与模型发现共用 buildXaiCliProxyHeaders。邮箱/姓名/完整响应当场丢弃。+ * settings/billing 的 401/403/429 才控制配额可用性;5xx / 半成功无字段返回 null 保缓存。+ */++import { createHash } from 'node:crypto';++import { createLogger } from '../logger.js';+import {+ XAI_ACCOUNT_USER_URL,+ buildXaiCliProxyHeaders,+} from '../maker-host/model-discovery/xai.js';+import {+ buildXaiSubscriptionUsageSnapshot,+ parseXaiBillingCreditsConfig,+ parseXaiSettingsPlanLabel,+ type XaiSubscriptionUsageSnapshot,+} from '../../shared/xaiSubscriptionUsage.js';++const log = createLogger('usage:xai-subscription');++const XAI_SETTINGS_URL = 'https://cli-chat-proxy.grok.com/v1/settings';+const XAI_BILLING_CREDITS_URL = 'https://cli-chat-proxy.grok.com/v1/billing?format=credits';+const XAI_USERINFO_URL = 'https://auth.x.ai/oauth2/userinfo';+const XAI_SUB_FINGERPRINT_SALT = 'cindy-xai-subscription-sub-fp-v1';+const QUOTA_FETCH_TIMEOUT_MS = 8_000;+const IDENTITY_FETCH_TIMEOUT_MS = 2_500;++export class XaiSubscriptionUsageUnauthorizedError extends Error {+ readonly status: number;++ constructor(status: number) {+ super(`xAI subscription usage unauthorized (${status})`);+ this.name = 'XaiSubscriptionUsageUnauthorizedError';+ this.status = status;+ }+}++export class XaiSubscriptionUsageRateLimitedError extends Error {+ constructor() {+ super('xAI subscription usage rate limited (429)');+ this.name = 'XaiSubscriptionUsageRateLimitedError';+ }+}++export const XAI_SUBSCRIPTION_USAGE_EMPTY = 'empty' as const;+export type XaiSubscriptionUsageFetchResult =+ | XaiSubscriptionUsageSnapshot+ | typeof XAI_SUBSCRIPTION_USAGE_EMPTY+ | null;++export function fingerprintXaiSubject(sub: string): string {+ return createHash('sha256')+ .update(`${XAI_SUB_FINGERPRINT_SALT}:${sub}`)+ .digest('hex')+ .slice(0, 16);+}++function throwIfQuotaFatalStatus(status: number): void {+ if (status === 401 || status === 403) {+ throw new XaiSubscriptionUsageUnauthorizedError(status);+ }+ if (status === 429) {+ throw new XaiSubscriptionUsageRateLimitedError();+ }+}++async function readQuotaJson(+ fetchFn: typeof fetch,+ url: string,+ headers: Record<string, string>,+ signal: AbortSignal,+): Promise<{ ok: boolean; data: unknown }> {+ const res = await fetchFn(url, {+ method: 'GET',+ headers,+ signal,+ });+ throwIfQuotaFatalStatus(res.status);+ if (!res.ok) return { ok: false, data: null };+ try {+ return { ok: true, data: await res.json() };+ } catch {+ return { ok: false, data: null };+ }+}++async function readIdentityJson(+ fetchFn: typeof fetch,+ url: string,+ headers: Record<string, string>,+ signal: AbortSignal,+): Promise<unknown> {+ try {+ const res = await fetchFn(url, {+ method: 'GET',+ headers,+ signal,+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++function subjectFromUserinfo(data: unknown): string | null {+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;+ const sub = (data as { sub?: unknown }).sub;+ return typeof sub === 'string' && sub.trim().length > 0 ? sub.trim() : null;+}++function userIdFromAccountUser(data: unknown): string | null {+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;+ const userId = (data as { userId?: unknown }).userId;+ return typeof userId === 'string' && userId.trim().length > 0 ? userId.trim() : null;+}++export async function fetchXaiSubscriptionUsageSnapshot(opts: {+ accessToken: string;+ fetchFn?: typeof fetch;+ timeoutMs?: number;+ identityTimeoutMs?: number;+ now?: number;+}): Promise<XaiSubscriptionUsageFetchResult> {+ const quotaController = new AbortController();+ const identityController = new AbortController();+ const quotaTimeout = setTimeout(+ () => quotaController.abort(),+ opts.timeoutMs ?? QUOTA_FETCH_TIMEOUT_MS,+ );+ const identityTimeout = setTimeout(+ () => identityController.abort(),+ opts.identityTimeoutMs ?? IDENTITY_FETCH_TIMEOUT_MS,+ );+ const fetchFn = opts.fetchFn ?? fetch;+ const now = opts.now ?? Date.now();+ const baseHeaders = buildXaiCliProxyHeaders(opts.accessToken);+ try {+ // 配额与 identity 同时发出。identity 即使先返回 userId,也不回头改配额请求:+ // billing/settings 无 x-userid 已实测可用,不能让 /v1/user 拖住或 abort 配额。+ const accountUserPromise = readIdentityJson(+ fetchFn,+ XAI_ACCOUNT_USER_URL,+ baseHeaders,+ identityController.signal,+ );+ const userinfoPromise = readIdentityJson(+ fetchFn,+ XAI_USERINFO_URL,+ baseHeaders,+ identityController.signal,+ );+ const [settings, credits] = await Promise.all([+ readQuotaJson(fetchFn, XAI_SETTINGS_URL, baseHeaders, quotaController.signal),+ readQuotaJson(fetchFn, XAI_BILLING_CREDITS_URL, baseHeaders, quotaController.signal),+ ]);+ const [accountUser, userinfo] = await Promise.all([accountUserPromise, userinfoPromise]);+ void userIdFromAccountUser(accountUser);++ const planLabel = parseXaiSettingsPlanLabel(settings.data);+ const parsedCredits = parseXaiBillingCreditsConfig(credits.data);+ const subject = subjectFromUserinfo(userinfo);+ const snapshot = buildXaiSubscriptionUsageSnapshot({+ planLabel,+ credits: parsedCredits,+ accountFingerprint: subject ? fingerprintXaiSubject(subject) : null,+ now,+ });+ if (!snapshot) {+ // 两个权威端点都成功但解析不出字段 → empty(清缓存)。任一非 ok 当瞬时失败保缓存。+ if (settings.ok && credits.ok) {+ log.warn('xAI subscription usage response had no parsable plan or weekly window');+ return XAI_SUBSCRIPTION_USAGE_EMPTY;+ }+ return null;+ }+ return snapshot;+ } catch (err) {+ if (+ err instanceof XaiSubscriptionUsageUnauthorizedError+ || err instanceof XaiSubscriptionUsageRateLimitedError+ ) {+ throw err;+ }+ log.warn('xAI subscription usage fetch failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ return null;+ } finally {+ clearTimeout(quotaTimeout);+ clearTimeout(identityTimeout);+ if (!identityController.signal.aborted) identityController.abort();+ }+}diff --git a/apps/desktop/src/main/usage/xaiSubscriptionUsageRefresh.ts b/apps/desktop/src/main/usage/xaiSubscriptionUsageRefresh.tsnew file mode 100644index 0000000000..988f77667b--- /dev/null+++ b/apps/desktop/src/main/usage/xaiSubscriptionUsageRefresh.ts@@ -0,0 +1,217 @@+/**+ * xaiSubscriptionUsageRefresh — SuperGrok 周用量 cached-first reader。+ *+ * 单源全量替换。登录 / 登出 / 换号走 syncForCredentialChange:**先清快照再读新凭证**,+ * 避免凭证读取期间并发 read() 把旧账号周用量交出去。+ *+ * 同 token 的并发 refresh 复用 in-flight,不排队加打;只有换了凭证才排队。+ * 节流默认 60s。429 指数退避。401/403 只清配额快照并进入冷却,不断开登录。+ */++import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage.js';++export interface XaiSubscriptionCredentialInfo {+ accessToken: string;+}++interface XaiSubscriptionUsageRefreshDeps {+ readCredentials(): Promise<XaiSubscriptionCredentialInfo | null>;+ fetchSnapshot(+ args: XaiSubscriptionCredentialInfo,+ ): Promise<XaiSubscriptionUsageSnapshot | 'empty' | null>;+ recordSnapshot(snapshot: XaiSubscriptionUsageSnapshot): Promise<void>;+ clearSnapshot(): Promise<void>;+ readCachedSnapshot(): Promise<XaiSubscriptionUsageSnapshot | null>;+ now(): number;+ isUnauthorizedError(err: unknown): boolean;+ isRateLimitedError(err: unknown): boolean;+ onRefreshError(err: unknown): void;+}++interface XaiSubscriptionUsageRefreshOptions {+ throttleMs?: number;+ rateLimitBackoffInitialMs?: number;+ rateLimitBackoffMaxMs?: number;+}++const DEFAULT_THROTTLE_MS = 60_000;+const DEFAULT_BACKOFF_INITIAL_MS = 5 * 60_000;+const DEFAULT_BACKOFF_MAX_MS = 30 * 60_000;++export interface XaiSubscriptionUsageReader {+ read(): Promise<XaiSubscriptionUsageSnapshot | null>;+ triggerRefresh(): void;+ syncForCredentialChange(): Promise<void>;+}++export function createXaiSubscriptionUsageReader(+ deps: XaiSubscriptionUsageRefreshDeps,+ options: XaiSubscriptionUsageRefreshOptions = {},+): XaiSubscriptionUsageReader {+ const throttleMs = options.throttleMs ?? DEFAULT_THROTTLE_MS;+ const backoffInitialMs = options.rateLimitBackoffInitialMs ?? DEFAULT_BACKOFF_INITIAL_MS;+ const backoffMaxMs = options.rateLimitBackoffMaxMs ?? DEFAULT_BACKOFF_MAX_MS;++ let inFlight: Promise<void> | null = null;+ let inFlightToken: string | null = null;+ let queuedCredentials: XaiSubscriptionCredentialInfo | null = null;+ let lastRefreshAt = 0;+ let backoffMs = 0;+ let backoffUntil = 0;+ let hadCredentials = false;+ let noCredentialsUntil = 0;+ let refreshGeneration = 0;++ async function readCredentialsSafe(): Promise<XaiSubscriptionCredentialInfo | null> {+ try {+ return await deps.readCredentials();+ } catch (err) {+ deps.onRefreshError(err);+ return null;+ }+ }++ async function clearCachedSnapshot(opts: { resetThrottle: boolean }): Promise<void> {+ refreshGeneration += 1;+ queuedCredentials = null;+ if (opts.resetThrottle) {+ lastRefreshAt = 0;+ backoffMs = 0;+ backoffUntil = 0;+ }+ try {+ await deps.clearSnapshot();+ } catch (err) {+ deps.onRefreshError(err);+ }+ }++ function markAttemptSettled(): void {+ lastRefreshAt = deps.now();+ }++ async function runRefresh(+ credentials: XaiSubscriptionCredentialInfo,+ generation: number,+ ): Promise<void> {+ try {+ const result = await deps.fetchSnapshot(credentials);+ if (generation !== refreshGeneration) return;+ const stillCurrent = await readCredentialsSafe();+ if (!stillCurrent || stillCurrent.accessToken !== credentials.accessToken) return;+ if (result === 'empty') {+ await deps.clearSnapshot();+ markAttemptSettled();+ backoffMs = 0;+ backoffUntil = 0;+ return;+ }+ if (!result) {+ markAttemptSettled();+ return;+ }+ await deps.recordSnapshot(result);+ markAttemptSettled();+ backoffMs = 0;+ backoffUntil = 0;+ } catch (err) {+ if (generation !== refreshGeneration) return;+ if (deps.isUnauthorizedError(err)) {+ await clearCachedSnapshot({ resetThrottle: false });+ lastRefreshAt = deps.now();+ return;+ }+ if (deps.isRateLimitedError(err)) {+ markAttemptSettled();+ backoffMs = backoffMs > 0+ ? Math.min(backoffMs * 2, backoffMaxMs)+ : backoffInitialMs;+ backoffUntil = deps.now() + backoffMs;+ deps.onRefreshError(err);+ return;+ }+ markAttemptSettled();+ deps.onRefreshError(err);+ }+ }++ function startRefresh(+ credentials: XaiSubscriptionCredentialInfo,+ opts?: { bypassThrottle?: boolean },+ ): void {+ const now = deps.now();+ if (inFlight) {+ // 同凭证:复用在途请求,不要再排队绕过节流。换号才覆盖排队。+ if (inFlightToken === credentials.accessToken) return;+ queuedCredentials = credentials;+ return;+ }+ if (!opts?.bypassThrottle) {+ if (now < backoffUntil) return;+ if (lastRefreshAt > 0 && now - lastRefreshAt < throttleMs) return;+ }+ const generation = refreshGeneration;+ inFlightToken = credentials.accessToken;+ const pending = runRefresh(credentials, generation).finally(() => {+ if (inFlight === pending) {+ inFlight = null;+ inFlightToken = null;+ }+ const queued = queuedCredentials;+ queuedCredentials = null;+ if (queued) startRefresh(queued, { bypassThrottle: true });+ });+ inFlight = pending;+ }++ return {+ async read(): Promise<XaiSubscriptionUsageSnapshot | null> {+ const credentials = await readCredentialsSafe();+ if (!credentials) {+ noCredentialsUntil = deps.now() + throttleMs;+ if (hadCredentials) {+ hadCredentials = false;+ await clearCachedSnapshot({ resetThrottle: true });+ }+ return null;+ }+ noCredentialsUntil = 0;+ hadCredentials = true;+ const cached = await deps.readCachedSnapshot();+ startRefresh(credentials);+ return cached;+ },++ triggerRefresh(): void {+ const now = deps.now();+ if (inFlight) return;+ if (now < backoffUntil) return;+ if (now < noCredentialsUntil) return;+ if (lastRefreshAt > 0 && now - lastRefreshAt < throttleMs) return;+ void (async () => {+ const credentials = await readCredentialsSafe();+ if (!credentials) {+ noCredentialsUntil = deps.now() + throttleMs;+ return;+ }+ noCredentialsUntil = 0;+ hadCredentials = true;+ startRefresh(credentials);+ })();+ },++ async syncForCredentialChange(): Promise<void> {+ // 先清再读凭证:凭证读取稍慢时,并发 read() 不能再把旧快照交出去。+ hadCredentials = false;+ await clearCachedSnapshot({ resetThrottle: true });+ const credentials = await readCredentialsSafe();+ if (!credentials) {+ noCredentialsUntil = deps.now() + throttleMs;+ return;+ }+ noCredentialsUntil = 0;+ hadCredentials = true;+ startRefresh(credentials, { bypassThrottle: true });+ },+ };+}diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex 3eddde000a..15ff28b269 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -22,6 +22,8 @@import { BrowserWindow } from 'electron';+import { isTrustedAppRendererWindow } from './security/trustedAppRenderer.js';+import { incrementDailySpend, getTodaySpend, localDayKey } from './localDb/dailySpend';import { getGatewayModelPricing } from './usage/modelPricing';import type { XaiRateLimitSnapshot } from '../shared/xaiRateLimit';@@ -32,6 +34,7 @@ import {mergeClaudeSubscriptionUsageSnapshot,type ClaudeSubscriptionUsageSnapshot,} from '../shared/claudeSubscriptionUsage';+import type { XaiSubscriptionUsageSnapshot } from '../shared/xaiSubscriptionUsage';import type { AgentKind } from '@cindy/maker-core';import {@@ -55,6 +58,8 @@ export const USAGE_CODEX_ACCOUNT_CHANGED = 'usage:codex-account-changed';export const USAGE_XAI_RATE_LIMIT_CHANGED = 'usage:xai-rate-limit-changed';/** IPC channel: main → renderer 推 Claude 订阅账号余量变化 (端点刷新 / headers 旁路)。 */export const USAGE_CLAUDE_SUBSCRIPTION_CHANGED = 'usage:claude-subscription-changed';+/** IPC channel: main → renderer 推 SuperGrok 账号周用量快照。 */+export const USAGE_XAI_SUBSCRIPTION_CHANGED = 'usage:xai-subscription-changed';export interface TodaySpendPayload {/** 本地时区 YYYY-MM-DD。 */@@ -885,6 +890,150 @@ export async function readClaudeSubscriptionUsageSnapshot(): Promise<ClaudeSubscreturn claudeSubscriptionUsageSnapshot;}+// ── xAI / SuperGrok subscription usage (persisted latest snapshot) ──────────+// agent_kind='xai'。单源全量替换,没有 headers 增量 merge。++const XAI_SUBSCRIPTION_USAGE_KIND = 'xai';++let xaiSubscriptionUsageOwnerInitialized = false;+let xaiSubscriptionUsageOwner: string | null = null;+let xaiSubscriptionUsageHydrated = false;+let xaiSubscriptionUsageSnapshot: XaiSubscriptionUsageSnapshot | null = null;+let xaiSubscriptionUsageLoadPromise: Promise<void> | null = null;+let xaiSubscriptionUsageGeneration = 0;++function resetXaiSubscriptionUsageCacheIfOwnerChanged(): void {+ const owner = currentAccountUsageOwner();+ if (xaiSubscriptionUsageOwnerInitialized && owner === xaiSubscriptionUsageOwner) return;+ const isFirstInit = !xaiSubscriptionUsageOwnerInitialized;+ xaiSubscriptionUsageOwnerInitialized = true;+ xaiSubscriptionUsageOwner = owner;+ if (isFirstInit) return;+ xaiSubscriptionUsageHydrated = false;+ xaiSubscriptionUsageSnapshot = null;+ xaiSubscriptionUsageGeneration += 1;+}++async function ensureXaiSubscriptionUsageLoaded(): Promise<void> {+ resetXaiSubscriptionUsageCacheIfOwnerChanged();+ if (xaiSubscriptionUsageHydrated) return;+ if (!xaiSubscriptionUsageLoadPromise) {+ const generation = xaiSubscriptionUsageGeneration;+ xaiSubscriptionUsageLoadPromise = (async () => {+ try {+ if (!xaiSubscriptionUsageOwner) return;+ const row = await getDbClient().queryOne<{ snapshot?: string | null }>(+ 'SELECT snapshot FROM account_usage_snapshots WHERE agent_kind = ?',+ [XAI_SUBSCRIPTION_USAGE_KIND],+ );+ if (generation !== xaiSubscriptionUsageGeneration) return;+ xaiSubscriptionUsageHydrated = true;+ if (!row?.snapshot) return;+ const parsed = JSON.parse(row.snapshot);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ const persisted = parsed as XaiSubscriptionUsageSnapshot;+ // record() 可能在 hydration 失败期间已经把更新的快照放进内存;+ // 迟到的磁盘行只能补空,不能盖掉更新的内存值。+ if (!xaiSubscriptionUsageSnapshot) {+ xaiSubscriptionUsageSnapshot = persisted;+ } else {+ const memoryAt = xaiSubscriptionUsageSnapshot.updatedAt ?? 0;+ const diskAt = persisted.updatedAt ?? 0;+ if (diskAt > memoryAt) xaiSubscriptionUsageSnapshot = persisted;+ }+ }+ } catch (err) {+ log.warn(+ 'readXaiSubscriptionUsageSnapshot failed:',+ err instanceof Error ? err.message : String(err),+ );+ }+ })();+ }+ try {+ await xaiSubscriptionUsageLoadPromise;+ } finally {+ xaiSubscriptionUsageLoadPromise = null;+ }+}++export async function recordXaiSubscriptionUsageSnapshot(snapshot: unknown): Promise<void> {+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return;++ const generation = xaiSubscriptionUsageGeneration;+ await ensureXaiSubscriptionUsageLoaded();+ if (generation !== xaiSubscriptionUsageGeneration) return;++ const incoming = snapshot as XaiSubscriptionUsageSnapshot;+ if (+ xaiSubscriptionUsageSnapshot?.accountFingerprint+ && incoming.accountFingerprint+ && xaiSubscriptionUsageSnapshot.accountFingerprint !== incoming.accountFingerprint+ ) {+ xaiSubscriptionUsageSnapshot = incoming;+ } else {+ xaiSubscriptionUsageSnapshot = {+ ...xaiSubscriptionUsageSnapshot,+ ...incoming,+ accountFingerprint: incoming.accountFingerprint ?? xaiSubscriptionUsageSnapshot?.accountFingerprint ?? null,+ };+ }+ const next = xaiSubscriptionUsageSnapshot;+ broadcastXaiSubscriptionUsage(next);++ if (!xaiSubscriptionUsageHydrated) {+ log.warn('skip persisting xai subscription usage snapshot: hydration unavailable');+ return;+ }++ try {+ await getDbClient().exec(+ `INSERT INTO account_usage_snapshots (agent_kind, snapshot, updated_at)+ VALUES (?, ?, ?)+ ON CONFLICT(agent_kind) DO UPDATE SET+ snapshot = excluded.snapshot,+ updated_at = excluded.updated_at`,+ [XAI_SUBSCRIPTION_USAGE_KIND, JSON.stringify(next), Date.now()],+ );+ if (generation !== xaiSubscriptionUsageGeneration) {+ await getDbClient().exec(+ 'DELETE FROM account_usage_snapshots WHERE agent_kind = ?',+ [XAI_SUBSCRIPTION_USAGE_KIND],+ );+ }+ } catch (err) {+ log.warn(+ 'recordXaiSubscriptionUsageSnapshot failed:',+ err instanceof Error ? err.message : String(err),+ );+ }+}++export async function clearXaiSubscriptionUsageSnapshot(): Promise<void> {+ resetXaiSubscriptionUsageCacheIfOwnerChanged();+ xaiSubscriptionUsageHydrated = true;+ xaiSubscriptionUsageSnapshot = null;+ xaiSubscriptionUsageGeneration += 1;+ broadcastXaiSubscriptionUsage(null);++ try {+ await getDbClient().exec(+ 'DELETE FROM account_usage_snapshots WHERE agent_kind = ?',+ [XAI_SUBSCRIPTION_USAGE_KIND],+ );+ } catch (err) {+ log.warn(+ 'clearXaiSubscriptionUsageSnapshot failed:',+ err instanceof Error ? err.message : String(err),+ );+ }+}++export async function readXaiSubscriptionUsageSnapshot(): Promise<XaiSubscriptionUsageSnapshot | null> {+ await ensureXaiSubscriptionUsageLoaded();+ return xaiSubscriptionUsageSnapshot;+}+// ── 内部广播 ─────────────────────────────────────────────────────────────────function broadcastTodaySpend(payload: TodaySpendPayload): void {@@ -918,3 +1067,10 @@ function broadcastClaudeSubscriptionUsage(payload: ClaudeSubscriptionUsageSnapsh}}}++function broadcastXaiSubscriptionUsage(payload: XaiSubscriptionUsageSnapshot | null): void {+ for (const win of BrowserWindow.getAllWindows()) {+ if (!isTrustedAppRendererWindow(win)) continue;+ win.webContents.send(USAGE_XAI_SUBSCRIPTION_CHANGED, payload);+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 6b1ce91a35..cb8cfaccd0 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -640,6 +640,7 @@ const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-chanconst fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量const fanOutMakerUsageXaiRateLimit = createIpcFanOut('usage:xai-rate-limit-changed'); // xAI bridge 限流快照const fanOutMakerUsageClaudeSubscription = createIpcFanOut('usage:claude-subscription-changed'); // Claude 订阅余量+const fanOutMakerUsageXaiSubscription = createIpcFanOut('usage:xai-subscription-changed'); // SuperGrok 周用量// 跨 Agent 工作区互转 — 转换进度 push (per step)const fanOutCrossAgentStep = createIpcFanOut('maker:cross-agent:step');// Scheduler (Phase 4) — 4 个 SchedulerEvent 类型 ('fired'|'completed'|'failed'|'changed')@@ -6256,6 +6257,8 @@ contextBridge.exposeInMainWorld('electronAPI', {/** Claude 订阅账号余量 (5h/周/分模型窗口, cached-first, main 侧按需后台刷新)。 */getClaudeSubscription: (): Promise<unknown | null> =>ipcRenderer.invoke('maker:usage:claude-subscription'),+ getXaiSubscription: (): Promise<unknown | null> =>+ ipcRenderer.invoke('maker:usage:xai-subscription'),/** Cindy AI /models 下发的 XD 原生报价。 */getModelPricing: (): Promise<unknown | null> =>ipcRenderer.invoke('maker:usage:model-pricing-v2'),@@ -6279,6 +6282,7 @@ contextBridge.exposeInMainWorld('electronAPI', {onXaiRateLimitChanged: fanOutMakerUsageXaiRateLimit,/** Claude 订阅余量推送 (端点后台刷新 / proxy 旁路 headers 更新时推送)。 */onClaudeSubscriptionChanged: fanOutMakerUsageClaudeSubscription,+ onXaiSubscriptionChanged: fanOutMakerUsageXaiSubscription,},// ── Scheduler (Phase 4) ────────────────────────────────────────────────diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.tsindex 8552171a70..5863a2666c 100644--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts@@ -45,11 +45,11 @@ describe('TodaySpendChip dashboard routing', () => {it('routes Codex/CC/Pi subscription providers to their account usage pages and keeps gateway routes local', () => {expect(source).toContain('https://chatgpt.com/codex/settings/usage');- expect(source).toContain('https://accounts.x.ai');+ expect(source).toContain('https://grok.com');expect(source).toContain('https://claude.ai/settings/usage');// 网关 / 托管账号这一路 URL 落到 null(点击无跳转);其余三路指向各自公开看板。expect(source).toMatch(- /usesXaiQuotaForm\s*\?\s*XAI_ACCOUNT_URL\s*:\s*isCodexOauth \|\| isChatgptBridge\s*\?\s*CODEX_USAGE_DASHBOARD_URL\s*:\s*isClaudeSubscription\s*\?\s*CLAUDE_USAGE_DASHBOARD_URL\s*:\s*null/,+ /usesXaiQuotaForm\s*\?\s*XAI_USAGE_DASHBOARD_URL\s*:\s*isCodexOauth \|\| isChatgptBridge\s*\?\s*CODEX_USAGE_DASHBOARD_URL\s*:\s*isClaudeSubscription\s*\?\s*CLAUDE_USAGE_DASHBOARD_URL\s*:\s*null/,);expect(source).toContain('todaySpend.openCodexUsage');expect(source).toContain('todaySpend.openXaiUsage');@@ -68,19 +68,23 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).toContain("providerId === 'openai'");expect(source).toContain("providerId === 'xai'");expect(source).toContain('const isSubscriptionBridge = isChatgptBridge || isXaiBridge;');- // bridge 只在匹配其内建来源时成立;显式自定义供应商优先于模型前缀。+ // ChatGPT 仍要前缀;xAI 显式选中供应商即可(Pi 模型是 grok-4.6,没有 xai/ 前缀)。expect(source).toContain("(providerId == null || providerId === 'openai')");- expect(source).toContain("(providerId == null || providerId === 'xai')");+ expect(source).toContain('providerId == null && isXaiPrefixedModel');expect(source).toContain('useClaudeAccountUsage(usesGatewayQuota)');// gateway quota 对订阅 bridge 会话关闭;device-link 远程同样不读本机网关配额expect(source).toContain('&& !isDeviceLinkRemote');- // chatgpt bridge 复用 codex 订阅 chip 形态;xai bridge / codex xai model 走价值估算 + 尽力限流 tooltip+ // chatgpt bridge 复用 codex 订阅 chip 形态;xai 走账号周用量 + 限流 tooltipexpect(source).toContain('const usesCodexQuotaForm = isCodexOauth || isChatgptBridge;');expect(source).toContain('const usesXaiQuotaForm = isCodexXaiProvider || isXaiBridge;');expect(source).toContain('tooltipNode = buildXaiTooltipNode(');+ expect(source).toContain('getXaiChipWindows(xaiSubscriptionUsage');+ expect(source).toContain('const weekly = isXaiWeeklyUsageCurrent(usage, nowMs) ? usage : null;');+ expect(source).toContain('useXaiSubscriptionUsage(usesXaiQuotaForm && !isAnyRemoteSession)');// 远程会话(SSH / device-link)抑制本机 xAI 限流快照读取expect(source).toContain('useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession)');expect(source).toContain('todaySpend.xai.noQuotaDetail');+ expect(source).toContain('todaySpend.xai.accountWeeklyHint');// bridge 形态优先于 Claude 订阅形态(model 前缀决定实际消耗的额度);device-link 远程不读本机订阅余量expect(source).toContain('isClaudeSubscription && !isSubscriptionBridge && !isDeviceLinkRemote',@@ -393,6 +397,8 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).toContain('if (isChatgptBridge) {\n' +' requestCodexAccountRefresh();\n' ++ ' } else if (usesXaiQuotaForm) {\n' ++ ' requestXaiSubscriptionRefresh();\n' +' } else if (isClaudeSubscription && !usesCodexQuotaForm) {\n' +' requestClaudeSubscriptionRefresh();\n' +' }',diff --git a/apps/desktop/src/renderer/__tests__/useXaiSubscriptionUsage.test.ts b/apps/desktop/src/renderer/__tests__/useXaiSubscriptionUsage.test.tsnew file mode 100644index 0000000000..b5a46d86cc--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/useXaiSubscriptionUsage.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import {+ reduceXaiSubscriptionPush,+ resolvePersistedXaiSubscriptionRead,+ shouldApplyXaiSubscriptionRead,+} from '../hooks/useXaiSubscriptionUsage';++describe('useXaiSubscriptionUsage reducers', () => {+ it('clears on null and applies snapshots', () => {+ const prev = { planLabel: 'SuperGrok Heavy', creditUsagePercent: 2 };+ expect(reduceXaiSubscriptionPush(prev, null)).toBeNull();+ expect(reduceXaiSubscriptionPush(prev, { planLabel: 'SuperGrok' })).toEqual({+ planLabel: 'SuperGrok',+ });+ expect(reduceXaiSubscriptionPush(prev, 'nope')).toBe(prev);+ });++ it('resolves persisted IPC reads', () => {+ expect(resolvePersistedXaiSubscriptionRead(null)).toEqual({ action: 'clear' });+ expect(resolvePersistedXaiSubscriptionRead({ planLabel: 'SuperGrok Heavy' })).toEqual({+ action: 'apply',+ snapshot: { planLabel: 'SuperGrok Heavy' },+ });+ expect(resolvePersistedXaiSubscriptionRead('x')).toEqual({ action: 'ignore' });+ });++ it('ignores a late IPC read after a newer push', () => {+ expect(shouldApplyXaiSubscriptionRead(3, 3)).toBe(true);+ expect(shouldApplyXaiSubscriptionRead(3, 4)).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex 04c1c1c287..f0f991d179 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -71,6 +71,11 @@ import {import { BILLING_CURRENCY, formatBillingAmount } from '@/features/billing/money';import { canAccessBillingSettings } from './billingVisibility';import { resolveXdAssetModuleState } from './providerAssetModule';+import { useXaiSubscriptionUsage } from '@/hooks/useXaiSubscriptionUsage';+import {+ formatXaiProductLabel,+ isXaiWeeklyUsageCurrent,+} from '../../../shared/xaiSubscriptionUsage';import { CustomProviderDialog } from './CustomProviderDialog';import { AddProviderWizard, type WizardEntry } from './AddProviderWizard';import { OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';@@ -770,6 +775,84 @@ function ImageApiKeyRow({// xAI —— OAuth(SuperGrok 订阅),复用 maker.xaiOAuth*。// ---------------------------------------------------------------------------+function formatXaiResetLabel(resetsAt: number | null | undefined, locale: string): string | null {+ if (typeof resetsAt !== 'number' || !Number.isFinite(resetsAt) || resetsAt <= 0) return null;+ try {+ return new Date(resetsAt * 1000).toLocaleString(locale, {+ month: 'numeric',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ });+ } catch {+ return null;+ }+}++function XaiAssetModule({ connected }: { connected: boolean }) {+ const { t, i18n } = useTranslation();+ const usage = useXaiSubscriptionUsage(connected);+ const [nowMs, setNowMs] = useState(() => Date.now());+ useEffect(() => {+ if (!connected) return undefined;+ const timer = window.setInterval(() => setNowMs(Date.now()), 60_000);+ return () => window.clearInterval(timer);+ }, [connected]);+ if (!connected || !usage) return null;+ const hasWeekly = isXaiWeeklyUsageCurrent(usage, nowMs);+ if (!usage.planLabel && !hasWeekly) return null;+ const resetLabel = formatXaiResetLabel(usage.resetsAt, i18n.resolvedLanguage ?? i18n.language);+ return (+ <div+ className="flex flex-wrap justify-between gap-x-6 gap-y-4 border-t px-5 py-5"+ style={{ borderColor: 'var(--settings-theme-card-border)' }}+ >+ <div className="min-w-0">+ <p className="text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>+ {usage.planLabel ?? t('settings.providers.xai.asset.weeklyTitle')}+ </p>+ {hasWeekly && (+ <p+ className="mt-1.5 text-20 font-medium leading-[1.3] tracking-[-0.02em] tabular-nums"+ style={{ color: 'var(--text-primary)' }}+ >+ {t('settings.providers.xai.asset.weeklyUsed', {+ percent: Math.round(usage.creditUsagePercent ?? 0),+ })}+ </p>+ )}+ {hasWeekly && resetLabel && (+ <p className="mt-1 text-12 leading-tight" style={{ color: 'var(--text-secondary)' }}>+ {t('settings.providers.xai.asset.resetsAt', { at: resetLabel })}+ </p>+ )}+ {hasWeekly && (usage.productUsage ?? []).map((product) => (+ <p+ key={product.product}+ className="mt-1 text-12 leading-tight tabular-nums"+ style={{ color: 'var(--text-secondary)' }}+ >+ {t('settings.providers.xai.asset.productLine', {+ product: formatXaiProductLabel(product.product),+ percent: Math.round(product.usagePercent),+ })}+ </p>+ ))}+ </div>+ <div className="flex shrink-0 items-center pt-3.5">+ <button+ type="button"+ onClick={() => void window.electronAPI.openExternal('https://grok.com')}+ className="text-13 transition-colors hover:text-[var(--text-primary)]"+ style={{ color: 'var(--text-secondary)' }}+ >+ {t('settings.providers.xai.asset.openUsage')}+ </button>+ </div>+ </div>+ );+}+function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged: () => void }) {const { t } = useTranslation();const { confirm } = useConfirmDialog();@@ -850,6 +933,7 @@ function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged})}trailing={trailing}provider={provider}+ assetModule={<XaiAssetModule connected={connected} />}/>);}diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 832ffb39df..329bb05f83 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -87,6 +87,16 @@ import {import { useCodexRuntimeRoute } from '@/hooks/useCodexRuntimeRoute';import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLimit';+import {+ requestXaiSubscriptionRefresh,+ useXaiSubscriptionUsage,+ type XaiSubscriptionUsageSnapshot,+} from '@/hooks/useXaiSubscriptionUsage';+import {+ formatXaiProductLabel,+ isXaiSubscriptionAlerting,+ isXaiWeeklyUsageCurrent,+} from '../../../shared/xaiSubscriptionUsage';import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';import {buildTurnUsageTooltipLines,@@ -123,7 +133,7 @@ import { QuotaResetConfetti } from './QuotaResetConfetti';// usageDashboardUrl / consoleUrl),据此恢复网关账号的跳转 + tooltip 链接行// (i18n 文案 todaySpend.openProxyUsage 已保留待复用,勿当死 key 删)。const CODEX_USAGE_DASHBOARD_URL = 'https://chatgpt.com/codex/settings/usage';-const XAI_ACCOUNT_URL = 'https://accounts.x.ai';+const XAI_USAGE_DASHBOARD_URL = 'https://grok.com';const CLAUDE_USAGE_DASHBOARD_URL = 'https://claude.ai/settings/usage';const METRIC_KEYS = ['daily', 'monthly', 'credit', 'session'] as const;@@ -950,15 +960,44 @@ function pushCodexResetCreditLines(* 显示剩余请求/tokens,拿不到诚实标注「无订阅额度明细」,只显示价值估算 + token 累计。*/function buildXaiTooltipNode(+ usage: XaiSubscriptionUsageSnapshot | null,rateLimit: XaiRateLimitSnapshot | null,sessionTokens: number | null,sessionUsage: SessionUsageMoney,t: TFunction,usageDashboardLabel: string | null,latestTurnUsage: LatestTurnUsageSummary | null,+ nowMs: number,): React.ReactNode {const lines: string[] = [];pushSessionUsageLines(lines, sessionUsage, sessionTokens, t);+ if (usage?.planLabel) {+ lines.push(t('todaySpend.xai.planLine', { plan: usage.planLabel }));+ }+ const weekly = isXaiWeeklyUsageCurrent(usage, nowMs) ? usage : null;+ if (weekly && typeof weekly.creditUsagePercent === 'number') {+ lines.push(t('todaySpend.xai.windowLine', {+ label: t('todaySpend.xai.weeklyLabel'),+ remaining: formatPercent(100 - clampPercent(weekly.creditUsagePercent)),+ used: formatPercent(clampPercent(weekly.creditUsagePercent)),+ }));+ lines.push(t('todaySpend.xai.accountWeeklyHint'));+ }+ if (weekly?.resetsAt) {+ const resetAt = formatResetAt(weekly.resetsAt);+ if (resetAt) lines.push(t('todaySpend.xai.resetAt', { at: resetAt }));+ }+ for (const product of weekly?.productUsage ?? []) {+ lines.push(t('todaySpend.xai.productLine', {+ product: formatXaiProductLabel(product.product),+ percent: formatPercent(product.usagePercent),+ }));+ }+ if (weekly && typeof weekly.prepaidBalance === 'number' && weekly.prepaidBalance > 0) {+ lines.push(t('todaySpend.xai.extraCreditsLine', {+ amount: `US$${weekly.prepaidBalance.toFixed(2)}`,+ }));+ }if (rateLimit && typeof rateLimit.remainingRequests === 'number' && typeof rateLimit.limitRequests === 'number') {lines.push(t('todaySpend.xai.requestsLine', {remaining: rateLimit.remainingRequests.toLocaleString(),@@ -971,7 +1010,7 @@ function buildXaiTooltipNode(limit: formatCompactTokens(rateLimit.limitTokens),}));}- if (!rateLimit) {+ if (!usage && !rateLimit) {lines.push(t('todaySpend.xai.noQuotaDetail'));}appendLatestTurnUsageLines(lines, latestTurnUsage, t);@@ -979,6 +1018,24 @@ function buildXaiTooltipNode(return buildTooltipNode(lines);}+function getXaiChipWindows(+ snapshot: XaiSubscriptionUsageSnapshot | null,+ t: TFunction,+ nowMs: number,+): ChipWindowSegment[] {+ if (!isXaiWeeklyUsageCurrent(snapshot, nowMs) || !snapshot) return [];+ const used = snapshot.creditUsagePercent ?? 0;+ const countdown = formatCompactTimeUntilReset(snapshot.resetsAt ?? undefined, nowMs, t);+ const resetsAtMs = toEpochMs(snapshot.resetsAt ?? undefined);+ return [{+ key: 'xai-weekly',+ label: countdown ?? t('todaySpend.xai.weeklyLabel'),+ remainingPercent: 100 - clampPercent(used),+ resetsAtMs,+ resetPending: isResetPending(resetsAtMs, nowMs),+ }];+}+function renderSegmentedLabel(segments: React.ReactNode[]): React.ReactNode {return segments.map((seg, i) => (<React.Fragment key={i}>@@ -1086,18 +1143,23 @@ export function TodaySpendChip({// cc 走「订阅直连 bridge」= model 带 chatgpt/ / xai/ 前缀(经本地 responses-bridge 打用户个人// 订阅额度,真实计费恒 0,gateway quota 与之无关):// - chatgpt/ → 与 codex 同一 ChatGPT 账户,复用 codex 订阅 chip 形态(限额窗口 + 价值估算);- // - xai/ → SuperGrok 无订阅窗口端点,尽力显示 bridge 抓到的限流头,否则仅价值估算。+ // - xai/ → SuperGrok 账号周用量(cli-chat-proxy billing) + 尽力显示限流头。// 优先级高于 Claude 订阅形态(model 前缀决定实际消耗的额度)。const isChatgptBridge =(vendorKey === 'cc' || vendorKey === 'pi')&& (providerId == null || providerId === 'openai')&& typeof modelId === 'string'&& modelId.startsWith(CHATGPT_MODEL_PREFIX);+ // SuperGrok 周用量是账号级。Pi catalog 的模型 id 是 grok-4.6,没有 xai/ 前缀,+ // 只靠前缀会漏掉「显式选了 xAI」的 Pi/CC 会话(设置页看得到、chip 没有)。+ const isXaiPrefixedModel =+ typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX);const isXaiBridge =(vendorKey === 'cc' || vendorKey === 'pi')- && (providerId == null || providerId === 'xai')- && typeof modelId === 'string'- && modelId.startsWith(XAI_MODEL_PREFIX);+ && (+ providerId === 'xai'+ || (providerId == null && isXaiPrefixedModel)+ );const isSubscriptionBridge = isChatgptBridge || isXaiBridge;const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);const isCodexBudgetModel = typeof modelId === 'string' && modelId.startsWith('codex/');@@ -1105,9 +1167,10 @@ export function TodaySpendChip({isCodexBudgetModel && (providerId == null || providerId === 'xd');const isCodexXaiProvider =vendorKey === 'codex'- && (providerId == null || providerId === 'xai')- && typeof modelId === 'string'- && modelId.startsWith(XAI_MODEL_PREFIX);+ && (+ providerId === 'xai'+ || (providerId == null && isXaiPrefixedModel)+ );// codex 走订阅价值估算:ChatGPT 订阅需要 oauth-bearer + OpenAI 来源;xAI 由 proxy 注入// SuperGrok OAuth。显式自定义供应商优先于共享 host 的 authInjection 和模型名前缀。// 远端 Codex 的事实在远端 daemon 上,本机只记录 token 价值估算,不写本地 gateway cost。@@ -1202,6 +1265,7 @@ export function TodaySpendChip({} = useCodexRateLimits(isCodexOauth && !isAnyRemoteSession);// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession);+ const xaiSubscriptionUsage = useXaiSubscriptionUsage(usesXaiQuotaForm && !isAnyRemoteSession);// 只有实际 Gateway 会话读取同一把 XD key 的 LiteLLM quota。订阅与自定义供应商// 均只展示各自的额度/本地会话统计,不读取 Model Access 账号配额。const claudeQuota = useClaudeAccountUsage(usesGatewayQuota);@@ -1332,13 +1396,13 @@ export function TodaySpendChip({cost: formatTurnCostMoney(sessionMoney),}): null;- // codex-oauth / cc+chatgpt bridge → ChatGPT 用量看板; cc+xai bridge → xAI 账户页;+ // codex-oauth / cc+chatgpt bridge → ChatGPT 用量看板; cc+xai bridge → grok.com 用量页;// cc Claude 订阅 → claude.ai 用量页; 其余(cc 网关 / codex-api)→ 暂无看板(null,见文件头 TODO)。// device-link 远程会话额度属于被控端账号,本机浏览器打开的看板是控制端自己的账号 → 不跳。const usageDashboardUrl: string | null = isDeviceLinkRemote? null: usesXaiQuotaForm- ? XAI_ACCOUNT_URL+ ? XAI_USAGE_DASHBOARD_URL: isCodexOauth || isChatgptBridge? CODEX_USAGE_DASHBOARD_URL: isClaudeSubscription@@ -1365,6 +1429,8 @@ export function TodaySpendChip({// 其它形态为空数组, 两个 rollup slot 空转。const chipWindows: ChipWindowSegment[] = usesCodexQuotaForm? getCodexChipWindows(accountUsage, t, windowLabelNowMs)+ : usesXaiQuotaForm+ ? getXaiChipWindows(xaiSubscriptionUsage, t, windowLabelNowMs): isClaudeSubscription? getClaudeChipWindows(claudeSubscriptionUsage, modelId, t, windowLabelNowMs): [];@@ -1392,7 +1458,11 @@ export function TodaySpendChip({}const rollup = index === 0 ? rollupA : rollupB;const text = t(- usesCodexQuotaForm ? 'todaySpend.codex.windowSegment' : 'todaySpend.claude.windowSegment',+ usesCodexQuotaForm+ ? 'todaySpend.codex.windowSegment'+ : usesXaiQuotaForm+ ? 'todaySpend.xai.windowSegment'+ : 'todaySpend.claude.windowSegment',{label: window.label,remaining: formatPercent(rollup?.percent ?? window.remainingPercent),@@ -1451,13 +1521,13 @@ export function TodaySpendChip({// 订阅形态 (codex-oauth / cc+chatgpt bridge / claude 订阅) 的 reset 倒计时文案// 需要随时间走动: 常态分钟级 tick 足够; 任一窗口进入最后一分钟切秒级 tick,// 让「59秒 → 1秒」逐秒跳动。setTimeout 链每次 tick 后按最新窗口重估下一次延迟。- if (!usesCodexQuotaForm && !isClaudeSubscription) return undefined;+ if (!usesCodexQuotaForm && !usesXaiQuotaForm && !isClaudeSubscription) return undefined;const delay = computeCountdownTickDelayMs(chipResetsAtMsList, Date.now());const timer = window.setTimeout(() => {setWindowLabelNowMs(Date.now());}, delay);return () => window.clearTimeout(timer);- }, [usesCodexQuotaForm, isClaudeSubscription, windowLabelNowMs, chipResetsAtMsList]);+ }, [usesCodexQuotaForm, usesXaiQuotaForm, isClaudeSubscription, windowLabelNowMs, chipResetsAtMsList]);// 悬念期主动催一次余量刷新, 让「重置揭晓」尽快到来 —— main read 都是// cached-first + 节流(Claude 订阅端点 180s + 退避; Codex WHAM 10s + in-flight@@ -1472,10 +1542,12 @@ export function TodaySpendChip({if (!hasPendingResetWindow) return;if (isChatgptBridge) {requestCodexAccountRefresh();+ } else if (usesXaiQuotaForm) {+ requestXaiSubscriptionRefresh();} else if (isClaudeSubscription && !usesCodexQuotaForm) {requestClaudeSubscriptionRefresh();}- }, [hasPendingResetWindow, isChatgptBridge, isClaudeSubscription, usesCodexQuotaForm, windowLabelNowMs]);+ }, [hasPendingResetWindow, isChatgptBridge, isClaudeSubscription, usesCodexQuotaForm, usesXaiQuotaForm, windowLabelNowMs]);const isDashboardClickable = usageDashboardUrl !== null;const handleClick = () => {@@ -1514,18 +1586,21 @@ export function TodaySpendChip({latestTurnUsage,);} else if (usesXaiQuotaForm) {- // xAI 无订阅窗口数据源;限流细节进 tooltip,会话金额仍走统一合计。- const chipSegments = sessionSegment ? [sessionSegment] : [];+ // 账号周用量进 chip;限流头与额外积分只在 tooltip。文案是账号级,不是本任务配额。+ const chipSegments = [...windowSegments];+ if (sessionSegment) chipSegments.push(sessionSegment);labelNode = chipSegments.length > 0? renderSegmentedLabel(chipSegments): <span className="tabular-nums opacity-60">{DEFAULT_MONEY_SYMBOL}</span>;tooltipNode = buildXaiTooltipNode(+ xaiSubscriptionUsage,xaiRateLimit,sessionTokens,sessionUsage,t,usageDashboardLabel,latestTurnUsage,+ windowLabelNowMs,);} else if (isClaudeSubscription) {// Claude 订阅形态 (方案 B): chip 显示「剩余时长 剩余%」倒计时段 + 本会话合计,@@ -1614,13 +1689,15 @@ export function TodaySpendChip({// isClaudeSubscriptionAlerting 对 allowed_warning 的取舍)。const claudeSubscriptionAlerting = isClaudeSubscription&& isClaudeSubscriptionAlerting(claudeSubscriptionUsage, modelId);+ const xaiSubscriptionAlerting = usesXaiQuotaForm+ && isXaiSubscriptionAlerting(xaiSubscriptionUsage);// 与 ContextCapacityRing 视觉对齐 (h-5 = 20px) + reset button UA 默认 padding/border。// tabular-nums 让 "$306 / $1.2k" 这类数字段的字符宽度等宽, 段间数字落点对齐。const buttonClass = cn('inline-flex h-5 shrink-0 items-center','text-12 font-medium leading-none tabular-nums',- claudeSubscriptionAlerting+ claudeSubscriptionAlerting || xaiSubscriptionAlerting? 'text-[var(--error-fg)] hover:text-[var(--error-fg-strong)]'// 不可点(网关账号)时不加 hover 变色,避免暗示可交互。: cn('text-[var(--msg-tool-card-chevron)]', isDashboardClickable && 'hover:text-foreground'),diff --git a/apps/desktop/src/renderer/hooks/useXaiRateLimit.ts b/apps/desktop/src/renderer/hooks/useXaiRateLimit.tsindex 73d369c0d6..402dfda29b 100644--- a/apps/desktop/src/renderer/hooks/useXaiRateLimit.ts+++ b/apps/desktop/src/renderer/hooks/useXaiRateLimit.ts@@ -6,8 +6,8 @@* recordXaiRateLimitSnapshot 广播 `usage:xai-rate-limit-changed` → 本 hook。* null payload = main 主动清空(xAI 登出 / 换账号,clearXaiRateLimitSnapshot)。*- * 与 useAccountUsage 的取舍差异:xAI 没有 ChatGPT 那种订阅窗口端点,这份数据是**请求级瞬时值**、- * 不落库 —— 应用重启后为 null,等下一个 xai/ 轮自然补上;为 null 时 chip 诚实降级为仅价值估算。+ * 这是请求级 RPM/TPM 瞬时值,不是 SuperGrok 周用量(周用量见 useXaiSubscriptionUsage)。+ * 不落库 —— 应用重启后为 null,等下一个 xai/ 轮自然补上。** 模块缓存用**全局订阅**维护(首个 hook 挂载时绑定一次、进程内常驻),与组件的 enabled 解耦:* 若订阅跟随 enabled 挂/卸,chip 卸载期间(切走了 xAI 模型 / 无会话)到达的清空广播会没有diff --git a/apps/desktop/src/renderer/hooks/useXaiSubscriptionUsage.ts b/apps/desktop/src/renderer/hooks/useXaiSubscriptionUsage.tsnew file mode 100644index 0000000000..a63bea21a9--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useXaiSubscriptionUsage.ts@@ -0,0 +1,152 @@+/**+ * useXaiSubscriptionUsage — SuperGrok 账号周用量推送。+ *+ * IPC: getXaiSubscription / onXaiSubscriptionChanged。+ * push 与 warm-start read 共用一份 epoch:push 先到时,迟到的旧 read 不得把+ * 已清除/已更新的 lastSnapshot 盖回去。+ */++import { useEffect, useState } from 'react';++import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage';++export type { XaiSubscriptionUsageSnapshot };++let lastSnapshot: XaiSubscriptionUsageSnapshot | null = null;+let snapshotEpoch = 0;++function isSnapshot(v: unknown): v is XaiSubscriptionUsageSnapshot {+ return Boolean(v) && typeof v === 'object' && !Array.isArray(v);+}++export function reduceXaiSubscriptionPush(+ current: XaiSubscriptionUsageSnapshot | null,+ payload: unknown,+): XaiSubscriptionUsageSnapshot | null {+ if (payload === null) return null;+ if (isSnapshot(payload)) return payload;+ return current;+}++export function resolvePersistedXaiSubscriptionRead(+ persisted: unknown,+):+ | { action: 'clear' }+ | { action: 'apply'; snapshot: XaiSubscriptionUsageSnapshot }+ | { action: 'ignore' } {+ if (persisted === null) return { action: 'clear' };+ if (isSnapshot(persisted)) return { action: 'apply', snapshot: persisted };+ return { action: 'ignore' };+}++/** 迟到的 IPC read 是否还能落地:期间若已经有 push,就信 push。 */+export function shouldApplyXaiSubscriptionRead(+ epochAtStart: number,+ currentEpoch: number,+): boolean {+ return epochAtStart === currentEpoch;+}++function readUsageApi(): {+ getXaiSubscription?: () => Promise<unknown | null>;+ onXaiSubscriptionChanged?: (cb: (payload: unknown) => void) => () => void;+} | undefined {+ return (window as unknown as {+ electronAPI?: {+ maker?: {+ usage?: {+ getXaiSubscription?: () => Promise<unknown | null>;+ onXaiSubscriptionChanged?: (cb: (payload: unknown) => void) => () => void;+ };+ };+ };+ }).electronAPI?.maker?.usage;+}++function applyPush(payload: unknown): void {+ snapshotEpoch += 1;+ lastSnapshot = reduceXaiSubscriptionPush(lastSnapshot, payload);+}++let moduleSubscriptionInstalled = false;+function ensureModuleSubscription(): void {+ if (moduleSubscriptionInstalled) return;+ const api = readUsageApi();+ if (!api?.onXaiSubscriptionChanged) return;+ moduleSubscriptionInstalled = true;+ api.onXaiSubscriptionChanged((payload: unknown) => {+ applyPush(payload);+ });+}++export function requestXaiSubscriptionRefresh(): void {+ const api = readUsageApi();+ if (!api?.getXaiSubscription) return;+ void api.getXaiSubscription().catch(() => {+ /* Best-effort nudge */+ });+}++export function useXaiSubscriptionUsage(+ enabled: boolean,+): XaiSubscriptionUsageSnapshot | null {+ ensureModuleSubscription();+ const [snapshot, setSnapshot] = useState<XaiSubscriptionUsageSnapshot | null>(() =>+ enabled ? lastSnapshot : null,+ );++ useEffect(() => {+ setSnapshot(enabled ? lastSnapshot : null);+ }, [enabled]);++ useEffect(() => {+ if (!enabled) return;+ const api = readUsageApi();+ if (!api?.getXaiSubscription) return;++ let cancelled = false;+ const epochAtStart = snapshotEpoch;+ void api+ .getXaiSubscription()+ .then((persisted) => {+ if (cancelled) return;+ if (!shouldApplyXaiSubscriptionRead(epochAtStart, snapshotEpoch)) return;+ const resolved = resolvePersistedXaiSubscriptionRead(persisted);+ if (resolved.action === 'clear') {+ lastSnapshot = null;+ setSnapshot(null);+ return;+ }+ if (resolved.action === 'apply') {+ lastSnapshot = resolved.snapshot;+ setSnapshot(resolved.snapshot);+ }+ })+ .catch(() => {+ /* Best-effort warm start */+ });++ return () => {+ cancelled = true;+ };+ }, [enabled]);++ useEffect(() => {+ if (!enabled) return;+ const api = readUsageApi();+ if (!api?.onXaiSubscriptionChanged) return;++ let cancelled = false;+ const unsubscribe = api.onXaiSubscriptionChanged((payload: unknown) => {+ if (cancelled) return;+ applyPush(payload);+ setSnapshot(lastSnapshot);+ });+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, [enabled]);++ return snapshot;+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 3dbfa71296..182a3285fe 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1306,7 +1306,14 @@"title": "xAI","subtitle": "Grok models · SuperGrok subscription (direct)","modelLabel": "Grok models",- "billingLabel": "SuperGrok subscription (direct)"+ "billingLabel": "SuperGrok subscription (direct)",+ "asset": {+ "weeklyTitle": "Weekly limit",+ "weeklyUsed": "{{percent}}% used",+ "resetsAt": "Resets {{at}}",+ "productLine": "{{product}} {{percent}}%",+ "openUsage": "Open Grok usage"+ }},"xd": {"title": "Cindy AI",@@ -4350,11 +4357,19 @@"second": "s"},"openProxyUsage": "Open the full usage dashboard in your browser",- "openXaiUsage": "Open your xAI account page",+ "openXaiUsage": "Open Grok usage page","xai": {"requestsLine": "Rate limit (requests): {{remaining}}/{{limit}} left","tokensLine": "Rate limit (tokens): {{remaining}}/{{limit}} left",- "noQuotaDetail": "xAI doesn't expose subscription quota details; only the estimated value is shown"+ "noQuotaDetail": "SuperGrok weekly usage is unavailable; only the estimated value is shown",+ "weeklyLabel": "Weekly",+ "windowSegment": "{{label}} {{remaining}} left",+ "windowLine": "{{label}} {{remaining}} left ({{used}} used)",+ "planLine": "Plan {{plan}}",+ "resetAt": "Resets {{at}}",+ "productLine": "{{product}} {{percent}}",+ "extraCreditsLine": "Extra credits {{amount}}",+ "accountWeeklyHint": "Account weekly usage, not this session's quota"},"dailyLimitLabel": "Today {{spend}}/{{limit}}","monthlyLimitLabel": "Cycle {{spend}}/{{limit}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 3ff84b50d4..28b2289e4a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1306,7 +1306,14 @@"title": "xAI","subtitle": "Grok モデル · SuperGrok サブスク直結","modelLabel": "Grok モデル",- "billingLabel": "SuperGrok サブスク直結"+ "billingLabel": "SuperGrok サブスク直結",+ "asset": {+ "weeklyTitle": "週間上限",+ "weeklyUsed": "{{percent}}% 使用済み",+ "resetsAt": "{{at}} にリセット",+ "productLine": "{{product}} {{percent}}%",+ "openUsage": "Grok の使用量ページを開く"+ }},"xd": {"title": "Cindy AI",@@ -4348,11 +4355,19 @@"second": "秒"},"openProxyUsage": "ブラウザで完全な使用量ダッシュボードを開く",- "openXaiUsage": "xAI アカウントページを開く",+ "openXaiUsage": "Grok の使用量ページを開く","xai": {"requestsLine": "レート制限(リクエスト): 残り {{remaining}}/{{limit}}","tokensLine": "レート制限(トークン): 残り {{remaining}}/{{limit}}",- "noQuotaDetail": "xAI はサブスクリプションクォータの詳細を提供していないため、価値の推定のみ表示します"+ "noQuotaDetail": "SuperGrok の週間使用量を取得できないため、価値の推定のみ表示します",+ "weeklyLabel": "週間",+ "windowSegment": "{{label}} 残り {{remaining}}",+ "windowLine": "{{label}} 残り {{remaining}}(使用 {{used}})",+ "planLine": "プラン {{plan}}",+ "resetAt": "{{at}} にリセット",+ "productLine": "{{product}} {{percent}}",+ "extraCreditsLine": "追加クレジット {{amount}}",+ "accountWeeklyHint": "アカウントの週間使用量であり、このセッションのクォータではありません"},"dailyLimitLabel": "本日 {{spend}}/{{limit}}","monthlyLimitLabel": "周期 {{spend}}/{{limit}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 114c479548..94a20c1d5f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1306,7 +1306,14 @@"title": "xAI","subtitle": "Grok 모델 · SuperGrok 구독 직접 연결","modelLabel": "Grok 모델",- "billingLabel": "SuperGrok 구독 직접 연결"+ "billingLabel": "SuperGrok 구독 직접 연결",+ "asset": {+ "weeklyTitle": "주간 한도",+ "weeklyUsed": "{{percent}}% 사용됨",+ "resetsAt": "{{at}} 초기화",+ "productLine": "{{product}} {{percent}}%",+ "openUsage": "Grok 사용량 페이지 열기"+ }},"xd": {"title": "Cindy AI",@@ -4348,11 +4355,19 @@"second": "초"},"openProxyUsage": "브라우저에서 전체 사용량 대시보드 열기",- "openXaiUsage": "xAI 계정 페이지 열기",+ "openXaiUsage": "Grok 사용량 페이지 열기","xai": {"requestsLine": "속도 제한(요청): 남음 {{remaining}}/{{limit}}","tokensLine": "속도 제한(토큰): 남음 {{remaining}}/{{limit}}",- "noQuotaDetail": "xAI는 구독 잔여량 세부 정보를 제공하지 않아 가치 추정치만 표시됩니다"+ "noQuotaDetail": "SuperGrok 주간 사용량을 가져오지 못해 가치 추정치만 표시됩니다",+ "weeklyLabel": "주간",+ "windowSegment": "{{label}} 남음 {{remaining}}",+ "windowLine": "{{label}} 남음 {{remaining}}(사용 {{used}})",+ "planLine": "플랜 {{plan}}",+ "resetAt": "{{at}} 초기화",+ "productLine": "{{product}} {{percent}}",+ "extraCreditsLine": "추가 크레딧 {{amount}}",+ "accountWeeklyHint": "계정 주간 사용량이며 이 작업의 할당량이 아닙니다"},"dailyLimitLabel": "오늘 {{spend}}/{{limit}}","monthlyLimitLabel": "주기 {{spend}}/{{limit}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 23253eb3a4..7a6f34b9d1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1306,7 +1306,14 @@"title": "xAI","subtitle": "Grok 模型 · SuperGrok 订阅直连","modelLabel": "Grok 模型",- "billingLabel": "SuperGrok 订阅直连"+ "billingLabel": "SuperGrok 订阅直连",+ "asset": {+ "weeklyTitle": "每周限额",+ "weeklyUsed": "{{percent}}% 已使用",+ "resetsAt": "{{at}} 重置",+ "productLine": "{{product}} {{percent}}%",+ "openUsage": "打开 Grok 用量页面"+ }},"xd": {"title": "Cindy AI",@@ -4348,11 +4355,19 @@"second": "秒"},"openProxyUsage": "打开浏览器查看完整用量看板",- "openXaiUsage": "打开 xAI 账户页面",+ "openXaiUsage": "打开 Grok 用量页面","xai": {"requestsLine": "限流(请求):剩余 {{remaining}}/{{limit}}","tokensLine": "限流(token):剩余 {{remaining}}/{{limit}}",- "noQuotaDetail": "xAI 未提供订阅配额明细,此处仅显示价值估算"+ "noQuotaDetail": "暂未获取到 SuperGrok 周用量,此处仅显示价值估算",+ "weeklyLabel": "周限",+ "windowSegment": "{{label}} 剩余 {{remaining}}",+ "windowLine": "{{label}} 剩余 {{remaining}}(已用 {{used}})",+ "planLine": "套餐 {{plan}}",+ "resetAt": "{{at}} 重置",+ "productLine": "{{product}} {{percent}}",+ "extraCreditsLine": "额外积分 {{amount}}",+ "accountWeeklyHint": "账号周用量,不是本任务配额"},"dailyLimitLabel": "今日 {{spend}}/{{limit}}","monthlyLimitLabel": "本周期 {{spend}}/{{limit}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 00dac4d299..eec36d8e6a 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1306,7 +1306,14 @@"title": "xAI","subtitle": "Grok 模型 · SuperGrok 訂閱直連","modelLabel": "Grok 模型",- "billingLabel": "SuperGrok 訂閱直連"+ "billingLabel": "SuperGrok 訂閱直連",+ "asset": {+ "weeklyTitle": "每週限額",+ "weeklyUsed": "{{percent}}% 已使用",+ "resetsAt": "{{at}} 重設",+ "productLine": "{{product}} {{percent}}%",+ "openUsage": "開啟 Grok 用量頁面"+ }},"xd": {"title": "Cindy AI",@@ -4348,11 +4355,19 @@"second": "秒"},"openProxyUsage": "開啟瀏覽器檢視完整用量看板",- "openXaiUsage": "開啟 xAI 帳戶頁面",+ "openXaiUsage": "開啟 Grok 用量頁面","xai": {"requestsLine": "限流(請求):剩餘 {{remaining}}/{{limit}}","tokensLine": "限流(token):剩餘 {{remaining}}/{{limit}}",- "noQuotaDetail": "xAI 未提供訂閱配額明細,此處僅顯示價值估算"+ "noQuotaDetail": "暫未取得 SuperGrok 週用量,此處僅顯示價值估算",+ "weeklyLabel": "週限",+ "windowSegment": "{{label}} 剩餘 {{remaining}}",+ "windowLine": "{{label}} 剩餘 {{remaining}}(已用 {{used}})",+ "planLine": "方案 {{plan}}",+ "resetAt": "{{at}} 重設",+ "productLine": "{{product}} {{percent}}",+ "extraCreditsLine": "額外點數 {{amount}}",+ "accountWeeklyHint": "帳號週用量,不是本任務配額"},"dailyLimitLabel": "今日 {{spend}}/{{limit}}","monthlyLimitLabel": "本週期 {{spend}}/{{limit}}",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 7bf33a637f..e94bb52bcb 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5775,6 +5775,8 @@ interface ElectronAPI {} | null,) => void,) => () => void;+ getXaiSubscription: () => Promise<unknown | null>;+ onXaiSubscriptionChanged: (cb: (payload: unknown) => void) => () => void;};/* ── 跨 Agent 工作区互转(双向,5 项独立判断;进度 step 通过 push 流转)── */diff --git a/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.ts b/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.tsnew file mode 100644index 0000000000..ca80a560b6--- /dev/null+++ b/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from 'vitest';++import {+ buildXaiSubscriptionUsageSnapshot,+ formatXaiProductLabel,+ isXaiSubscriptionAlerting,+ isXaiWeeklyUsageCurrent,+ parseXaiBillingCreditsConfig,+ parseXaiSettingsPlanLabel,+} from '../xaiSubscriptionUsage';++const CREDITS_FIXTURE = {+ config: {+ currentPeriod: {+ type: 'USAGE_PERIOD_TYPE_WEEKLY',+ start: '2026-08-11T09:53:45.527500+00:00',+ end: '2026-08-18T09:53:45.527500+00:00',+ },+ creditUsagePercent: 2,+ onDemandCap: { val: 0 },+ onDemandUsed: { val: 0 },+ productUsage: [{ product: 'GrokBuild', usagePercent: 2 }],+ isUnifiedBillingUser: true,+ prepaidBalance: { val: 0 },+ billingPeriodEnd: '2026-08-18T09:53:45.527500+00:00',+ },+};++describe('parseXaiSettingsPlanLabel', () => {+ it('reads subscription_tier_display', () => {+ expect(parseXaiSettingsPlanLabel({ subscription_tier_display: 'SuperGrok Heavy' }))+ .toBe('SuperGrok Heavy');+ });++ it('returns null for missing or empty labels', () => {+ expect(parseXaiSettingsPlanLabel({})).toBeNull();+ expect(parseXaiSettingsPlanLabel({ subscription_tier_display: ' ' })).toBeNull();+ expect(parseXaiSettingsPlanLabel(null)).toBeNull();+ });+});++describe('parseXaiBillingCreditsConfig', () => {+ it('reads the grok.com weekly included pool fields', () => {+ const parsed = parseXaiBillingCreditsConfig(CREDITS_FIXTURE);+ expect(parsed).toEqual({+ creditUsagePercent: 2,+ resetsAt: Math.floor(Date.parse('2026-08-18T09:53:45.527500+00:00') / 1000),+ productUsage: [{ product: 'GrokBuild', usagePercent: 2 }],+ prepaidBalance: 0,+ });+ });++ it('ignores onDemand counters when computing weekly percent', () => {+ const parsed = parseXaiBillingCreditsConfig({+ config: {+ creditUsagePercent: 40,+ onDemandCap: { val: 0 },+ onDemandUsed: { val: 0 },+ },+ });+ expect(parsed?.creditUsagePercent).toBe(40);+ });++ it('returns null when neither percent nor reset exists', () => {+ expect(parseXaiBillingCreditsConfig({ config: { prepaidBalance: { val: 0 } } })).toBeNull();+ expect(parseXaiBillingCreditsConfig(null)).toBeNull();+ });++ it('skips malformed product rows', () => {+ const parsed = parseXaiBillingCreditsConfig({+ config: {+ creditUsagePercent: 1,+ productUsage: [+ { product: 'GrokBuild', usagePercent: 1 },+ { product: '', usagePercent: 9 },+ { usagePercent: 3 },+ null,+ ],+ },+ });+ expect(parsed?.productUsage).toEqual([{ product: 'GrokBuild', usagePercent: 1 }]);+ });+});++describe('buildXaiSubscriptionUsageSnapshot', () => {+ it('requires at least a plan or a credits window', () => {+ expect(buildXaiSubscriptionUsageSnapshot({ now: 1 })).toBeNull();+ expect(buildXaiSubscriptionUsageSnapshot({+ planLabel: 'SuperGrok Heavy',+ now: 10,+ accountFingerprint: 'abc',+ })).toMatchObject({+ planLabel: 'SuperGrok Heavy',+ source: 'cli-billing',+ updatedAt: 10,+ accountFingerprint: 'abc',+ });+ });+});++describe('formatXaiProductLabel', () => {+ it('splits GrokBuild into Grok Build', () => {+ expect(formatXaiProductLabel('GrokBuild')).toBe('Grok Build');+ expect(formatXaiProductLabel('Grok Build')).toBe('Grok Build');+ });+});++describe('isXaiSubscriptionAlerting', () => {+ it('alerts at 90% used', () => {+ const now = Date.now();+ const fresh = { creditUsagePercent: 89, updatedAt: now, resetsAt: now / 1000 + 3600 };+ expect(isXaiSubscriptionAlerting({ ...fresh, creditUsagePercent: 89 }, now)).toBe(false);+ expect(isXaiSubscriptionAlerting({ ...fresh, creditUsagePercent: 90 }, now)).toBe(true);+ expect(isXaiSubscriptionAlerting(null, now)).toBe(false);+ });+});++describe('isXaiWeeklyUsageCurrent', () => {+ it('hides numbers after TTL or after reset', () => {+ const now = 2_000_000;+ expect(isXaiWeeklyUsageCurrent({+ creditUsagePercent: 2,+ updatedAt: now - 60_000,+ resetsAt: now / 1000 + 3600,+ }, now)).toBe(true);+ expect(isXaiWeeklyUsageCurrent({+ creditUsagePercent: 2,+ updatedAt: now - 31 * 60 * 1000,+ resetsAt: now / 1000 + 3600,+ }, now)).toBe(false);+ expect(isXaiWeeklyUsageCurrent({+ creditUsagePercent: 2,+ updatedAt: now - 1000,+ resetsAt: now / 1000 - 1,+ }, now)).toBe(false);+ expect(isXaiWeeklyUsageCurrent({+ creditUsagePercent: 2,+ resetsAt: now / 1000 + 3600,+ }, now)).toBe(false);+ });+});diff --git a/apps/desktop/src/shared/xaiSubscriptionUsage.ts b/apps/desktop/src/shared/xaiSubscriptionUsage.tsnew file mode 100644index 0000000000..fb8c3d0b71--- /dev/null+++ b/apps/desktop/src/shared/xaiSubscriptionUsage.ts@@ -0,0 +1,189 @@+/**+ * xaiSubscriptionUsage — SuperGrok 账号周用量的共享类型与纯解析。+ *+ * 数据来自 grok-cli 代理未文档化接口(与 grok.com Settings → Usage 对过字段):+ * - GET cli-chat-proxy.grok.com/v1/settings → subscription_tier_display+ * - GET cli-chat-proxy.grok.com/v1/billing?format=credits → 周已用百分比 /+ * 重置时间 / 分产品+ *+ * 这是账号级「每周包含限额」,不是单次任务配额,也不是 api.x.ai 的 RPM/TPM 限流。+ * 解析必须 fail-safe:字段缺失 / 形状不符就跳过,绝不从 token 数反推百分比。+ */++/** 分产品周用量(页面「Grok Build 2%」)。 */+export interface XaiProductUsage {+ /** 上游 product id,如 GrokBuild。 */+ product: string;+ /** 0-100 已用百分比。 */+ usagePercent: number;+}++export interface XaiSubscriptionUsageSnapshot {+ /** 套餐展示名,如 SuperGrok Heavy。 */+ planLabel?: string | null;+ /** 0-100 本周已用百分比(页面「2% 已使用」)。 */+ creditUsagePercent?: number | null;+ /** Unix epoch 秒;周窗口重置时刻。 */+ resetsAt?: number | null;+ /** 分产品已用百分比。 */+ productUsage?: XaiProductUsage[];+ /**+ * 额外使用积分余额。单位按 grok.com 页面为美元;0 / 缺失不要当「免费额度」展示。+ */+ prepaidBalance?: number | null;+ source?: 'cli-billing' | string | null;+ updatedAt?: number | null;+ /**+ * 稳定账号指纹(OIDC sub 的不可逆哈希)。换 SuperGrok 号时用来丢掉旧快照。+ * 不是 access token 哈希 —— token 刷新会轮换。+ */+ accountFingerprint?: string | null;+}++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v);+}++function toFiniteNumber(v: unknown): number | null {+ if (v === null || v === undefined || v === '') return null;+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : null;+}++function clampPercent(v: number): number {+ return Math.min(100, Math.max(0, v));+}++function toOptionalString(v: unknown): string | null {+ return typeof v === 'string' && v.trim().length > 0 ? v.trim() : null;+}++/** ISO8601 / epoch 秒 → epoch 秒;解析不了 → null。 */+export function toXaiUsageEpochSeconds(v: unknown): number | null {+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) return Math.floor(v);+ if (typeof v === 'string' && v.length > 0) {+ const ms = Date.parse(v);+ if (Number.isFinite(ms) && ms > 0) return Math.floor(ms / 1000);+ }+ return null;+}++function unwrapVal(v: unknown): unknown {+ if (isPlainObject(v) && 'val' in v) return v.val;+ return v;+}++/** settings JSON → 套餐名。没有 subscription_tier_display 则 null。 */+export function parseXaiSettingsPlanLabel(data: unknown): string | null {+ if (!isPlainObject(data)) return null;+ return toOptionalString(data.subscription_tier_display);+}++function parseProductUsage(raw: unknown): XaiProductUsage[] {+ if (!Array.isArray(raw)) return [];+ const out: XaiProductUsage[] = [];+ for (const entry of raw) {+ if (!isPlainObject(entry)) continue;+ const product = toOptionalString(entry.product);+ const usagePercent = toFiniteNumber(entry.usagePercent);+ if (!product || usagePercent === null) continue;+ out.push({ product, usagePercent: clampPercent(usagePercent) });+ }+ return out;+}++/**+ * 解析 billing?format=credits 的 config。+ * 至少要有 creditUsagePercent 或重置时间,否则返回 null。+ */+export function parseXaiBillingCreditsConfig(data: unknown): {+ creditUsagePercent: number | null;+ resetsAt: number | null;+ productUsage: XaiProductUsage[];+ prepaidBalance: number | null;+} | null {+ if (!isPlainObject(data)) return null;+ const config = isPlainObject(data.config) ? data.config : data;+ const creditUsagePercent = toFiniteNumber(config.creditUsagePercent);+ const period = isPlainObject(config.currentPeriod) ? config.currentPeriod : null;+ const resetsAt =+ toXaiUsageEpochSeconds(period?.end)+ ?? toXaiUsageEpochSeconds(config.billingPeriodEnd);+ const prepaidBalance = toFiniteNumber(unwrapVal(config.prepaidBalance));+ if (creditUsagePercent === null && resetsAt === null) return null;+ return {+ creditUsagePercent: creditUsagePercent === null ? null : clampPercent(creditUsagePercent),+ resetsAt,+ productUsage: parseProductUsage(config.productUsage),+ prepaidBalance,+ };+}++export function buildXaiSubscriptionUsageSnapshot(input: {+ planLabel?: string | null;+ credits?: ReturnType<typeof parseXaiBillingCreditsConfig>;+ accountFingerprint?: string | null;+ now: number;+}): XaiSubscriptionUsageSnapshot | null {+ const planLabel = toOptionalString(input.planLabel);+ const credits = input.credits;+ if (!planLabel && !credits) return null;+ return {+ planLabel,+ creditUsagePercent: credits?.creditUsagePercent ?? null,+ resetsAt: credits?.resetsAt ?? null,+ productUsage: credits?.productUsage ?? [],+ prepaidBalance: credits?.prepaidBalance ?? null,+ source: 'cli-billing',+ updatedAt: input.now,+ accountFingerprint: toOptionalString(input.accountFingerprint),+ };+}++/** GrokBuild → Grok Build;已有空格的原样返回。 */+export function formatXaiProductLabel(product: string): string {+ const trimmed = product.trim();+ if (!trimmed) return trimmed;+ if (/\s/.test(trimmed)) return trimmed;+ return trimmed.replace(/([a-z])([A-Z])/g, '$1 $2');+}++/** 超过这个时间没刷新到新快照,就不再当「当前额度」展示。 */+export const XAI_USAGE_STALE_MS = 30 * 60 * 1000;++/**+ * 周窗口数字是否还能当当前额度:过了 TTL,或已经过了 resetsAt 却还没新快照,+ * 都不当当前值(避免无限显示旧百分比 / 卡在「重置中」)。套餐名仍可单独展示。+ */+export function isXaiWeeklyUsageCurrent(+ snapshot: XaiSubscriptionUsageSnapshot | null | undefined,+ nowMs: number,+): boolean {+ if (!snapshot) return false;+ if (+ typeof snapshot.creditUsagePercent !== 'number'+ || !Number.isFinite(snapshot.creditUsagePercent)+ ) {+ return false;+ }+ if (typeof snapshot.updatedAt !== 'number' || !Number.isFinite(snapshot.updatedAt) || snapshot.updatedAt <= 0) {+ return false;+ }+ if (nowMs - snapshot.updatedAt > XAI_USAGE_STALE_MS) return false;+ if (typeof snapshot.resetsAt === 'number' && Number.isFinite(snapshot.resetsAt) && snapshot.resetsAt > 0) {+ if (nowMs >= snapshot.resetsAt * 1000) return false;+ }+ return true;+}++const WINDOW_ALERT_UTILIZATION_PERCENT = 90;++/** chip 警示:周已用 ≥90%。 */+export function isXaiSubscriptionAlerting(+ snapshot: XaiSubscriptionUsageSnapshot | null,+ nowMs: number = Date.now(),+): boolean {+ if (!isXaiWeeklyUsageCurrent(snapshot, nowMs)) return false;+ const used = snapshot?.creditUsagePercent;+ return typeof used === 'number' && Number.isFinite(used) && clampPercent(used) >= WINDOW_ALERT_UTILIZATION_PERCENT;+}