Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): SuperGrok 重置后缺百分比按 0% 刷新,不再卡在剩余 0 (#3249)

Dash589a244b24c0
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts
index 56330582fe..7019365f48 100644
--- a/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts
+++ b/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts
@@ -112,4 +112,25 @@ describe('xai subscription snapshot hydration', () => {
accountFingerprint: 'bbbb',
});
});
+
+ it('lets a reset to 0% overwrite a previously exhausted weekly percent', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ mocks.queryOne.mockResolvedValue(null);
+ await broadcaster.recordXaiSubscriptionUsageSnapshot({
+ planLabel: 'SuperGrok Heavy',
+ creditUsagePercent: 100,
+ accountFingerprint: 'bbbb',
+ updatedAt: 2,
+ });
+ await broadcaster.recordXaiSubscriptionUsageSnapshot({
+ planLabel: 'SuperGrok Heavy',
+ creditUsagePercent: 0,
+ accountFingerprint: 'bbbb',
+ updatedAt: 3,
+ });
+ await expect(broadcaster.readXaiSubscriptionUsageSnapshot()).resolves.toMatchObject({
+ creditUsagePercent: 0,
+ updatedAt: 3,
+ });
+ });
});
diff --git a/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.ts b/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.ts
index 6389cd7af0..d9fae202a1 100644
--- a/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/xaiSubscriptionUsage.test.ts
@@ -104,13 +104,80 @@ describe('fetchXaiSubscriptionUsageSnapshot', () => {
})).resolves.toBeNull();
});
- it('does not replace cache when billing 200 only has a reset time', async () => {
+ it('treats a still-open weekly window without percent as 0% used after reset', async () => {
const fetchFn = vi.fn(async (url: string) => {
if (url.includes('/settings')) {
return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });
}
if (url.includes('format=credits')) {
- return jsonResponse(200, { config: { currentPeriod: { end: 1_800_000_000 } } });
+ return jsonResponse(200, {
+ config: {
+ currentPeriod: { type: 'USAGE_PERIOD_TYPE_WEEKLY', end: 1_800_000_000 },
+ },
+ });
+ }
+ 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,
+ now: 1_700_000_000_000,
+ })).resolves.toMatchObject({
+ planLabel: 'SuperGrok Heavy',
+ creditUsagePercent: 0,
+ resetsAt: 1_800_000_000,
+ });
+ });
+
+ it('does not replace cache when weekly percent is present but unparseable', async () => {
+ const fetchFn = vi.fn(async (url: string) => {
+ if (url.includes('/settings')) {
+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });
+ }
+ if (url.includes('format=credits')) {
+ return jsonResponse(200, {
+ config: {
+ currentPeriod: { type: 'USAGE_PERIOD_TYPE_WEEKLY', end: 1_800_000_000 },
+ creditUsagePercent: 'nope',
+ },
+ });
+ }
+ 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,
+ now: 1_700_000_000_000,
+ })).resolves.toBeNull();
+ });
+
+ it('does not replace cache when only a future billingPeriodEnd is present', async () => {
+ const fetchFn = vi.fn(async (url: string) => {
+ if (url.includes('/settings')) {
+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });
+ }
+ if (url.includes('format=credits')) {
+ return jsonResponse(200, { config: { billingPeriodEnd: 1_800_000_000 } });
+ }
+ 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,
+ now: 1_700_000_000_000,
+ })).resolves.toBeNull();
+ });
+
+ it('does not replace cache when the reset time is already in the past and percent is missing', async () => {
+ const fetchFn = vi.fn(async (url: string) => {
+ if (url.includes('/settings')) {
+ return jsonResponse(200, { subscription_tier_display: 'SuperGrok Heavy' });
+ }
+ if (url.includes('format=credits')) {
+ return jsonResponse(200, { config: { currentPeriod: { end: 1_600_000_000 } } });
}
if (url.includes('/user?') || url.includes('/userinfo')) return jsonResponse(200, {});
return jsonResponse(404, {});
@@ -118,6 +185,7 @@ describe('fetchXaiSubscriptionUsageSnapshot', () => {
await expect(fetchXaiSubscriptionUsageSnapshot({
accessToken: 'tok',
fetchFn: fetchFn as unknown as typeof fetch,
+ now: 1_700_000_000_000,
})).resolves.toBeNull();
});
diff --git a/apps/desktop/src/main/usage/xaiSubscriptionUsage.ts b/apps/desktop/src/main/usage/xaiSubscriptionUsage.ts
index 2a46621a28..de42f21072 100644
--- a/apps/desktop/src/main/usage/xaiSubscriptionUsage.ts
+++ b/apps/desktop/src/main/usage/xaiSubscriptionUsage.ts
@@ -6,6 +6,9 @@
*
* 请求头与模型发现共用 buildXaiCliProxyHeaders。邮箱/姓名/完整响应当场丢弃。
* settings/billing 的 401/403/429 才控制配额可用性;5xx / 半成功无字段返回 null 保缓存。
+ * 仅当 currentPeriod.type=USAGE_PERIOD_TYPE_WEEKLY、窗口未结束、
+ * 且响应里没有 creditUsagePercent 键时,视为 0%(重置后常见)。
+ * 字段在但解不出数,仍当残缺 200 保缓存。
*/
import { createHash } from 'node:crypto';
@@ -164,7 +167,7 @@ export async function fetchXaiSubscriptionUsageSnapshot(opts: {
void userIdFromAccountUser(accountUser);
const planLabel = parseXaiSettingsPlanLabel(settings.data);
- const parsedCredits = parseXaiBillingCreditsConfig(credits.data);
+ const parsedCredits = parseXaiBillingCreditsConfig(credits.data, now);
const subject = subjectFromUserinfo(userinfo);
if (
!settings.ok
@@ -172,7 +175,8 @@ export async function fetchXaiSubscriptionUsageSnapshot(opts: {
|| !parsedCredits
|| typeof parsedCredits.creditUsagePercent !== 'number'
) {
- // 权威端点失败,或 200 但缺周用量百分比:残缺快照不能盖掉缓存。
+ // 权威端点失败,或 200 但没有仍开放的 weekly currentPeriod 可推出百分比:
+ // 残缺快照不能盖掉缓存。明确的未结束周窗口省略该字段已在 parse 里当成 0%。
return null;
}
const snapshot = buildXaiSubscriptionUsageSnapshot({
diff --git a/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.ts b/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.ts
index ca80a560b6..73fc54939b 100644
--- a/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.ts
+++ b/apps/desktop/src/shared/__tests__/xaiSubscriptionUsage.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
buildXaiSubscriptionUsageSnapshot,
formatXaiProductLabel,
+ inferXaiWeeklyUsagePercent,
isXaiSubscriptionAlerting,
isXaiWeeklyUsageCurrent,
parseXaiBillingCreditsConfig,
@@ -66,6 +67,73 @@ describe('parseXaiBillingCreditsConfig', () => {
expect(parseXaiBillingCreditsConfig(null)).toBeNull();
});
+ it('treats an omitted percent as 0% while the weekly window is still open', () => {
+ const nowMs = Date.parse('2026-08-15T00:00:00.000Z');
+ const parsed = parseXaiBillingCreditsConfig({
+ config: {
+ currentPeriod: {
+ type: 'USAGE_PERIOD_TYPE_WEEKLY',
+ end: '2026-08-18T09:53:45.527500+00:00',
+ },
+ },
+ }, nowMs);
+ expect(parsed?.creditUsagePercent).toBe(0);
+ expect(parsed?.resetsAt).toBe(Math.floor(Date.parse('2026-08-18T09:53:45.527500+00:00') / 1000));
+ });
+
+ it('does not invent 0% after the weekly window has already ended', () => {
+ const nowMs = Date.parse('2026-08-19T00:00:00.000Z');
+ const parsed = parseXaiBillingCreditsConfig({
+ config: {
+ currentPeriod: {
+ type: 'USAGE_PERIOD_TYPE_WEEKLY',
+ end: '2026-08-18T09:53:45.527500+00:00',
+ },
+ },
+ }, nowMs);
+ expect(parsed?.creditUsagePercent).toBeNull();
+ expect(inferXaiWeeklyUsagePercent(null, 1_800_000_000, 1_800_000_000 * 1000, true)).toBeNull();
+ expect(inferXaiWeeklyUsagePercent(null, 1_800_000_000, 1_800_000_000 * 1000 - 1, true)).toBe(0);
+ expect(inferXaiWeeklyUsagePercent(null, 1_800_000_000, 1_800_000_000 * 1000 - 1, false)).toBeNull();
+ });
+
+ it('does not invent 0% when creditUsagePercent is present but unparseable', () => {
+ const nowMs = Date.parse('2026-08-15T00:00:00.000Z');
+ const weekly = {
+ type: 'USAGE_PERIOD_TYPE_WEEKLY',
+ end: '2026-08-18T09:53:45.527500+00:00',
+ };
+ expect(parseXaiBillingCreditsConfig({
+ config: { currentPeriod: weekly, creditUsagePercent: 'nope' },
+ }, nowMs)?.creditUsagePercent).toBeNull();
+ expect(parseXaiBillingCreditsConfig({
+ config: { currentPeriod: weekly, creditUsagePercent: { val: 2 } },
+ }, nowMs)?.creditUsagePercent).toBeNull();
+ expect(parseXaiBillingCreditsConfig({
+ config: { currentPeriod: weekly, creditUsagePercent: null },
+ }, nowMs)?.creditUsagePercent).toBeNull();
+ });
+
+ it('does not invent 0% from a future billingPeriodEnd or non-weekly period', () => {
+ const nowMs = Date.parse('2026-08-15T00:00:00.000Z');
+ expect(parseXaiBillingCreditsConfig({
+ config: { billingPeriodEnd: '2026-09-18T00:00:00.000Z' },
+ }, nowMs)?.creditUsagePercent).toBeNull();
+ expect(parseXaiBillingCreditsConfig({
+ config: {
+ currentPeriod: {
+ type: 'USAGE_PERIOD_TYPE_MONTHLY',
+ end: '2026-09-18T00:00:00.000Z',
+ },
+ },
+ }, nowMs)?.creditUsagePercent).toBeNull();
+ expect(parseXaiBillingCreditsConfig({
+ config: {
+ currentPeriod: { end: '2026-09-18T00:00:00.000Z' },
+ },
+ }, nowMs)?.creditUsagePercent).toBeNull();
+ });
+
it('skips malformed product rows', () => {
const parsed = parseXaiBillingCreditsConfig({
config: {
diff --git a/apps/desktop/src/shared/xaiSubscriptionUsage.ts b/apps/desktop/src/shared/xaiSubscriptionUsage.ts
index e1ac3549f2..2b94013ce6 100644
--- a/apps/desktop/src/shared/xaiSubscriptionUsage.ts
+++ b/apps/desktop/src/shared/xaiSubscriptionUsage.ts
@@ -8,6 +8,9 @@
*
* 这是账号级「每周包含限额」,不是单次任务配额,也不是 api.x.ai 的 RPM/TPM 限流。
* 解析必须 fail-safe:字段缺失 / 形状不符就跳过,绝不从 token 数反推百分比。
+ * 例外:仅当 currentPeriod.type 明确是 USAGE_PERIOD_TYPE_WEEKLY、窗口尚未结束、
+ * 且响应里根本没有 creditUsagePercent 键时,按 proto3 默认值当成 0%。
+ * 字段在但解不出数、只有未来 billingPeriodEnd、或非周窗口,都不能推断 0%。
*/
/** 分产品周用量(页面「Grok Build 2%」)。 */
@@ -92,11 +95,48 @@ function parseProductUsage(raw: unknown): XaiProductUsage[] {
return out;
}
+const XAI_WEEKLY_PERIOD_TYPE = 'USAGE_PERIOD_TYPE_WEEKLY';
+
+/** 只有上游标明的周窗口才能用来推断省略的 creditUsagePercent。 */
+export function isXaiWeeklyUsagePeriod(period: unknown): period is Record<string, unknown> {
+ if (!isPlainObject(period)) return false;
+ const type = toOptionalString(period.type);
+ return type === XAI_WEEKLY_PERIOD_TYPE;
+}
+
+/**
+ * 未结束的周窗口里,省略的 creditUsagePercent 就是 0%。
+ * weeklyResetsAt 必须来自 USAGE_PERIOD_TYPE_WEEKLY 的 currentPeriod.end;
+ * fieldOmitted 必须是键不存在。字段在但解不出、月度 billingPeriodEnd、
+ * 非周窗口、已过期窗口都保持 null,让 fetch 保缓存。
+ */
+export function inferXaiWeeklyUsagePercent(
+ creditUsagePercent: number | null,
+ weeklyResetsAt: number | null,
+ nowMs: number,
+ fieldOmitted = false,
+): number | null {
+ if (creditUsagePercent !== null) return clampPercent(creditUsagePercent);
+ if (!fieldOmitted) return null;
+ if (
+ typeof weeklyResetsAt === 'number'
+ && Number.isFinite(weeklyResetsAt)
+ && weeklyResetsAt > 0
+ && nowMs < weeklyResetsAt * 1000
+ ) {
+ return 0;
+ }
+ return null;
+}
+
/**
* 解析 billing?format=credits 的 config。
* 至少要有 creditUsagePercent 或重置时间,否则返回 null。
*/
-export function parseXaiBillingCreditsConfig(data: unknown): {
+export function parseXaiBillingCreditsConfig(
+ data: unknown,
+ nowMs: number = Date.now(),
+): {
creditUsagePercent: number | null;
resetsAt: number | null;
productUsage: XaiProductUsage[];
@@ -104,15 +144,25 @@ export function parseXaiBillingCreditsConfig(data: unknown): {
} | null {
if (!isPlainObject(data)) return null;
const config = isPlainObject(data.config) ? data.config : data;
+ const percentOmitted = !Object.prototype.hasOwnProperty.call(config, 'creditUsagePercent');
const creditUsagePercent = toFiniteNumber(config.creditUsagePercent);
const period = isPlainObject(config.currentPeriod) ? config.currentPeriod : null;
+ const weeklyResetsAt = isXaiWeeklyUsagePeriod(period)
+ ? toXaiUsageEpochSeconds(period.end)
+ : null;
const resetsAt =
- toXaiUsageEpochSeconds(period?.end)
+ weeklyResetsAt
+ ?? 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),
+ creditUsagePercent: inferXaiWeeklyUsagePercent(
+ creditUsagePercent,
+ weeklyResetsAt,
+ nowMs,
+ percentOmitted,
+ ),
resetsAt,
productUsage: parseProductUsage(config.productUsage),
prepaidBalance,