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): restore complete account quota display (#3318)

fico-hub8c53ec069ae0
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts
index e143b2d832..a3ae0408b7 100644
--- a/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts
+++ b/apps/desktop/src/main/__tests__/usageBroadcasterClaudeSubscription.test.ts
@@ -9,7 +9,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
queryOne: vi.fn(),
exec: vi.fn(async () => undefined),
- getCurrentUserId: vi.fn(() => 'user-1'),
+ getCurrentDbClientUserId: vi.fn(() => 'user-1'),
}));
vi.mock('electron', () => ({
@@ -28,9 +28,7 @@ vi.mock('../localDb/dailyModelUsage', () => ({
}));
vi.mock('../localDb/client/current', () => ({
getDbClient: () => ({ queryOne: mocks.queryOne, exec: mocks.exec, drizzle: {} }),
-}));
-vi.mock('../localDb/index', () => ({
- getCurrentUserId: mocks.getCurrentUserId,
+ getCurrentDbClientUserId: mocks.getCurrentDbClientUserId,
}));
function deferred<T>() {
@@ -44,7 +42,7 @@ describe('claude subscription snapshot hydration race', () => {
vi.resetModules();
mocks.queryOne.mockReset();
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
});
it('does not drop the very first snapshot after main start (owner init is not invalidation)', async () => {
@@ -156,7 +154,7 @@ describe('claude subscription snapshot hydration race', () => {
// 否则会被外层赋值写回, 之后永远复用这个已 resolve 的 Promise, 再也不查库。
it('reads the database once the owner becomes available', async () => {
const broadcaster = await import('../usageBroadcaster');
- mocks.getCurrentUserId.mockReturnValue(null as unknown as string);
+ mocks.getCurrentDbClientUserId.mockReturnValue(null as unknown as string);
await broadcaster.recordClaudeSubscriptionUsageSnapshot({
fiveHour: { utilization: 10 }, source: 'unified-headers', updatedAt: 1,
@@ -166,7 +164,7 @@ describe('claude subscription snapshot hydration race', () => {
// 登录后必须重新查库。跨 owner 变化的那一笔按既有世代语义会被丢弃(它属于换号前
// 的上下文), 下一笔恢复正常落库。
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.queryOne.mockResolvedValue(null);
await broadcaster.recordClaudeSubscriptionUsageSnapshot({
fiveHour: { utilization: 20 }, source: 'unified-headers', updatedAt: 2,
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts
index 757c5bd052..55e8bdbc18 100644
--- a/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts
+++ b/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts
@@ -9,7 +9,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
queryOne: vi.fn(),
exec: vi.fn(async () => undefined),
- getCurrentUserId: vi.fn(() => 'user-1'),
+ getCurrentDbClientUserId: vi.fn(() => 'user-1'),
+ legacyCurrentUserId: vi.fn(() => null),
/** 广播到 renderer 的 payload —— 并发用例据此断言不会闪出空快照。 */
broadcasts: [] as unknown[],
}));
@@ -37,9 +38,10 @@ vi.mock('../localDb/dailyModelUsage', () => ({
}));
vi.mock('../localDb/client/current', () => ({
getDbClient: () => ({ queryOne: mocks.queryOne, exec: mocks.exec, drizzle: {} }),
+ getCurrentDbClientUserId: mocks.getCurrentDbClientUserId,
}));
vi.mock('../localDb/index', () => ({
- getCurrentUserId: mocks.getCurrentUserId,
+ getCurrentUserId: mocks.legacyCurrentUserId,
}));
const APP_SERVER_SNAPSHOT = {
@@ -66,7 +68,8 @@ describe('codex account usage source slots', () => {
vi.resetModules();
mocks.queryOne.mockReset().mockResolvedValue(null);
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
+ mocks.legacyCurrentUserId.mockReturnValue(null);
mocks.broadcasts.length = 0;
});
@@ -164,7 +167,7 @@ describe('codex app-server limit buckets', () => {
vi.resetModules();
mocks.queryOne.mockReset().mockResolvedValue(null);
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.broadcasts.length = 0;
});
@@ -206,6 +209,34 @@ describe('codex app-server limit buckets', () => {
expect(payload?.appServerBuckets?.codex?.primary?.usedPercent).toBe(91);
});
+ it('keeps the sibling window when a sparse update only carries one window', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);
+ await broadcaster.recordCodexAccountUsageSnapshot({
+ limitId: 'codex',
+ primary: { usedPercent: 91, windowMinutes: 300, resetsAt: 1_800_000_000 },
+ source: 'codex-app-server',
+ });
+
+ const payload = await broadcaster.readCodexAccountUsageSnapshot();
+ expect(payload?.appServerBuckets?.codex?.primary?.usedPercent).toBe(91);
+ expect(payload?.appServerBuckets?.codex?.secondary?.usedPercent).toBe(55);
+ });
+
+ it('clears an explicitly null window while preserving an omitted sibling', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);
+ await broadcaster.recordCodexAccountUsageSnapshot({
+ limitId: 'codex',
+ primary: null,
+ source: 'codex-app-server',
+ });
+
+ const payload = await broadcaster.readCodexAccountUsageSnapshot();
+ expect(payload?.appServerBuckets?.codex?.primary ?? null).toBeNull();
+ expect(payload?.appServerBuckets?.codex?.secondary?.usedPercent).toBe(55);
+ });
+
it('hydrates a pre-bucket persisted row into its matching bucket', async () => {
const broadcaster = await import('../usageBroadcaster');
// 分槽版(有 webSnapshot 键、无 appServerBuckets)写下的行 —— 顶层是 Spark 桶
@@ -254,7 +285,7 @@ describe('codex bucket edge cases (review follow-up)', () => {
vi.resetModules();
mocks.queryOne.mockReset().mockResolvedValue(null);
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.broadcasts.length = 0;
});
@@ -360,7 +391,7 @@ describe('codex stale bucket pruning', () => {
vi.resetModules();
mocks.queryOne.mockReset().mockResolvedValue(null);
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.broadcasts.length = 0;
});
@@ -402,7 +433,7 @@ describe('empty snapshot must not clobber the persisted row', () => {
vi.resetModules();
mocks.queryOne.mockReset().mockResolvedValue(null);
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.broadcasts.length = 0;
});
@@ -509,14 +540,14 @@ describe('empty snapshot must not clobber the persisted row', () => {
// hydrated 永远为 false, 本进程之后所有落库都被守卫跳过。
it('reads the database once the owner becomes available', async () => {
const broadcaster = await import('../usageBroadcaster');
- mocks.getCurrentUserId.mockReturnValue(null as unknown as string);
+ mocks.getCurrentDbClientUserId.mockReturnValue(null as unknown as string);
await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);
expect(mocks.queryOne).not.toHaveBeenCalled();
expect(mocks.exec).not.toHaveBeenCalled();
// 用户登录后必须重新查库, 并恢复正常落库。
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.queryOne.mockResolvedValue(null);
await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);
@@ -524,10 +555,27 @@ describe('empty snapshot must not clobber the persisted row', () => {
expect(mocks.exec).toHaveBeenCalled();
});
+ it('hydrates through the current DbClient after the legacy database is closed', async () => {
+ const broadcaster = await import('../usageBroadcaster');
+ // DbClient 接管会关闭 legacy localDb 并清空它的 owner;新 client 仍持有当前用户。
+ mocks.legacyCurrentUserId.mockReturnValue(null);
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
+ mocks.queryOne.mockResolvedValue({ snapshot: JSON.stringify(APP_SERVER_SNAPSHOT) });
+
+ const payload = await broadcaster.readCodexAccountUsageSnapshot();
+
+ expect(mocks.queryOne).toHaveBeenCalledWith(
+ 'SELECT snapshot FROM account_usage_snapshots WHERE agent_kind = ?',
+ ['codex'],
+ );
+ expect(payload?.primary?.usedPercent).toBe(82);
+ expect(payload?.secondary?.usedPercent).toBe(55);
+ });
+
it('skips persistence when the owner is not initialized yet', async () => {
const broadcaster = await import('../usageBroadcaster');
- // 启动早期 getCurrentUserId 尚不可用 → hydration 被跳过, 内存为空。
- mocks.getCurrentUserId.mockReturnValue(null as unknown as string);
+ // 启动早期 DbClient owner 尚不可用 → hydration 被跳过, 内存为空。
+ mocks.getCurrentDbClientUserId.mockReturnValue(null as unknown as string);
await broadcaster.recordCodexAccountUsageSnapshot(NULL_SPARSE_EVENT);
@@ -651,7 +699,7 @@ describe('sparse rate-limit updates without a limitId', () => {
vi.resetModules();
mocks.queryOne.mockReset().mockResolvedValue(null);
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
mocks.broadcasts.length = 0;
});
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts
index 7019365f48..90a53c0900 100644
--- a/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts
+++ b/apps/desktop/src/main/__tests__/usageBroadcasterXaiSubscription.test.ts
@@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
queryOne: vi.fn(),
exec: vi.fn(async () => undefined),
- getCurrentUserId: vi.fn(() => 'user-1'),
+ getCurrentDbClientUserId: vi.fn(() => 'user-1'),
}));
vi.mock('electron', () => ({
@@ -26,9 +26,7 @@ vi.mock('../localDb/dailyModelUsage', () => ({
}));
vi.mock('../localDb/client/current', () => ({
getDbClient: () => ({ queryOne: mocks.queryOne, exec: mocks.exec, drizzle: {} }),
-}));
-vi.mock('../localDb/index', () => ({
- getCurrentUserId: mocks.getCurrentUserId,
+ getCurrentDbClientUserId: mocks.getCurrentDbClientUserId,
}));
describe('xai subscription snapshot hydration', () => {
@@ -36,7 +34,7 @@ describe('xai subscription snapshot hydration', () => {
vi.resetModules();
mocks.queryOne.mockReset();
mocks.exec.mockReset().mockResolvedValue(undefined);
- mocks.getCurrentUserId.mockReturnValue('user-1');
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-1');
});
it('does not serve a disk snapshot until this process records one', async () => {
diff --git a/apps/desktop/src/main/usage/__tests__/codexWebUsage.test.ts b/apps/desktop/src/main/usage/__tests__/codexWebUsage.test.ts
index 4c1de2dea9..71dbfe89d6 100644
--- a/apps/desktop/src/main/usage/__tests__/codexWebUsage.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/codexWebUsage.test.ts
@@ -1,4 +1,9 @@
-import { describe, expect, it, vi } from 'vitest';
+import { net } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ net: { fetch: vi.fn() },
+}));
import {
CodexWebUsageUnauthorizedError,
@@ -7,6 +12,10 @@ import {
} from '../codexWebUsage';
describe('codexWebUsageResponseToSnapshot', () => {
+ beforeEach(() => {
+ vi.mocked(net.fetch).mockReset();
+ });
+
it('maps ChatGPT wham usage into the shared Codex account snapshot shape', () => {
const snapshot = codexWebUsageResponseToSnapshot({
plan_type: 'pro',
@@ -133,4 +142,43 @@ describe('codexWebUsageResponseToSnapshot', () => {
timeoutMs: 1000,
})).resolves.toBeNull();
});
+
+ it('uses Electron net.fetch by default so system proxy settings are honored', async () => {
+ vi.mocked(net.fetch).mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ plan_type: 'pro',
+ rate_limit: {
+ primary_window: {
+ limit_window_seconds: 604_800,
+ used_percent: 14,
+ },
+ },
+ }),
+ } as unknown as Response);
+
+ await expect(fetchCodexWebUsageSnapshot({
+ accessToken: 'token',
+ accountId: 'account-1',
+ timeoutMs: 1000,
+ })).resolves.toMatchObject({
+ source: 'openai-web',
+ accountId: 'account-1',
+ primary: {
+ usedPercent: 14,
+ windowMinutes: 10080,
+ },
+ });
+
+ expect(net.fetch).toHaveBeenCalledWith(
+ 'https://chatgpt.com/backend-api/wham/usage',
+ expect.objectContaining({
+ method: 'GET',
+ headers: expect.objectContaining({
+ 'ChatGPT-Account-Id': 'account-1',
+ }),
+ }),
+ );
+ });
});
diff --git a/apps/desktop/src/main/usage/codexWebUsage.ts b/apps/desktop/src/main/usage/codexWebUsage.ts
index 93d825c62e..e25cdb94e3 100644
--- a/apps/desktop/src/main/usage/codexWebUsage.ts
+++ b/apps/desktop/src/main/usage/codexWebUsage.ts
@@ -1,3 +1,5 @@
+import { net } from 'electron';
+
import { createLogger } from '../logger.js';
import type { CreditsSnapshot, RateLimitSnapshot, RateLimitWindow } from '../usageBroadcaster.js';
@@ -139,7 +141,11 @@ export async function fetchCodexWebUsageSnapshot(
};
if (opts.accountId) headers['ChatGPT-Account-Id'] = opts.accountId;
- const res = await (opts.fetchFn ?? fetch)(CODEX_WEB_USAGE_URL, {
+ // Electron net.fetch uses Chromium's network stack, so it honors the
+ // system proxy/PAC configuration. A bare Node fetch bypasses that stack;
+ // on managed or poisoned-DNS networks it can resolve chatgpt.com to the
+ // wrong host even while the desktop app's proxied requests work normally.
+ const res = await (opts.fetchFn ?? net.fetch)(CODEX_WEB_USAGE_URL, {
method: 'GET',
headers,
signal: controller.signal,
diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.ts
index b702de4dc1..e750ecc38e 100644
--- a/apps/desktop/src/main/usageBroadcaster.ts
+++ b/apps/desktop/src/main/usageBroadcaster.ts
@@ -28,8 +28,7 @@ import { incrementDailySpend, getTodaySpend, localDayKey } from './localDb/daily
import { getGatewayModelPricing } from './usage/modelPricing';
import type { XaiRateLimitSnapshot } from '../shared/xaiRateLimit';
import { incrementDailyModelUsage, type DailyModelUsageDelta } from './localDb/dailyModelUsage';
-import { getDbClient } from './localDb/client/current';
-import { getCurrentUserId } from './localDb/index';
+import { getCurrentDbClientUserId, getDbClient } from './localDb/client/current';
import {
mergeClaudeSubscriptionUsageSnapshot,
type ClaudeSubscriptionUsageSnapshot,
@@ -379,7 +378,7 @@ function currentCodexAppServerSnapshot(): RateLimitSnapshot | null {
function currentAccountUsageOwner(): string | null {
try {
- return getCurrentUserId();
+ return getCurrentDbClientUserId();
} catch {
return null;
}
@@ -501,9 +500,28 @@ function mergeCodexAccountUsageSnapshot(
previous.source === 'openai-web'
&& incoming.source !== 'openai-web'
&& (isCodexZeroWindowFallback(incoming) || isCodexWindowlessFallback(incoming));
+ const incomingHasPrimary = Object.prototype.hasOwnProperty.call(incoming, 'primary');
+ const incomingHasSecondary = Object.prototype.hasOwnProperty.call(incoming, 'secondary');
const keepPreviousWindows =
keepPreviousWebFields
- || (hasCodexUsageWindow(previous) && isCodexWindowlessFallback(incoming));
+ || (
+ hasCodexUsageWindow(previous)
+ && isCodexWindowlessFallback(incoming)
+ // Preserve the known generic placeholder shapes (no window fields, or
+ // both null). A single explicit null is authoritative for withdrawing
+ // that window while its omitted sibling remains sparse.
+ && (incomingHasPrimary === incomingHasSecondary)
+ );
+ // account/rateLimits/updated is sparse: an app-server notification may refresh
+ // only primary or secondary. A missing sibling means "not included in this
+ // update", not "the window was removed". Preserve each omitted window
+ // independently so a one-window tick cannot make the other quota disappear.
+ // WHAM snapshots are full reads and must still be allowed to clear a window;
+ // an explicit reached marker is authoritative for clearing both windows.
+ const preserveMissingAppServerWindows =
+ previous.source !== 'openai-web'
+ && incoming.source !== 'openai-web'
+ && !hasCodexRateLimitReached(incoming);
const incomingCredits = incoming.credits;
const previousCredits = previous.credits ?? null;
@@ -523,8 +541,12 @@ function mergeCodexAccountUsageSnapshot(
return {
...incoming,
- primary: keepPreviousWindows ? previous.primary : incoming.primary,
- secondary: keepPreviousWindows ? previous.secondary : incoming.secondary,
+ primary: keepPreviousWindows || (preserveMissingAppServerWindows && !incomingHasPrimary)
+ ? previous.primary
+ : incoming.primary,
+ secondary: keepPreviousWindows || (preserveMissingAppServerWindows && !incomingHasSecondary)
+ ? previous.secondary
+ : incoming.secondary,
planType: keepPreviousWebFields ? previous.planType : incoming.planType ?? previous.planType,
credits,
source: keepPreviousWebFields ? previous.source : incoming.source ?? 'codex-app-server',
diff --git a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
index 79a4354b32..354a69abc2 100644
--- a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
+++ b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
@@ -13,6 +13,42 @@ import {
} from '@/hooks/useAccountUsage';
describe('mergeCodexAccountUsageSnapshot', () => {
+ it('preserves the sibling app-server window during a one-window sparse update', () => {
+ const previous = {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 24, windowMinutes: 300 },
+ secondary: { usedPercent: 31, windowMinutes: 10_080 },
+ };
+
+ const merged = mergeCodexAccountUsageSnapshot(previous, {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 25, windowMinutes: 300 },
+ });
+
+ expect(merged.primary?.usedPercent).toBe(25);
+ expect(merged.secondary).toEqual(previous.secondary);
+ });
+
+ it('clears an explicitly null app-server window but preserves an omitted sibling', () => {
+ const previous = {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 24, windowMinutes: 300 },
+ secondary: { usedPercent: 31, windowMinutes: 10_080 },
+ };
+
+ const merged = mergeCodexAccountUsageSnapshot(previous, {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ secondary: null,
+ });
+
+ expect(merged.primary).toEqual(previous.primary);
+ expect(merged.secondary ?? null).toBeNull();
+ });
+
it('preserves the last known credit balance when a later snapshot omits credits', () => {
const previous = {
credits: {
diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
index 0e036398e2..2df559bb9e 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx
@@ -4,11 +4,14 @@ import { act, cleanup, fireEvent, render, screen, within } from '@testing-librar
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ClaudeSubscriptionUsageSnapshot } from '../../../../shared/claudeSubscriptionUsage';
+import type { RateLimitSnapshot } from '@/hooks/useAccountUsage';
import type { RegionalMoney } from '../../../../shared/regionalMoney';
import type { SessionUsageMoney } from '@/hooks/useSessionUsageMoney';
const mocks = vi.hoisted(() => ({
claudeSnapshot: null as ClaudeSubscriptionUsageSnapshot | null,
+ codexSnapshot: null as RateLimitSnapshot | null,
+ codexAuthInjection: null as string | null,
displaySnapshot: {
messages: [] as Array<Record<string, unknown>>,
},
@@ -27,8 +30,14 @@ vi.mock('react-i18next', () => ({
t: (key: string, options: Record<string, string | number> = {}) => {
const templates: Record<string, string> = {
'todaySpend.openClaudeUsage': '打开 Claude 用量页面',
+ 'todaySpend.openCodexUsage': '打开 Codex 用量页面',
'todaySpend.claude.weeklyLabel': '周限',
+ 'todaySpend.claude.modelWeeklyLabel': '{{model}} 周限',
'todaySpend.claude.windowSegment': '{{label}} 剩余 {{remaining}}',
+ 'todaySpend.codex.weekWindow': '周限',
+ 'todaySpend.codex.limitWindow': '限额',
+ 'todaySpend.codex.daysWindow': '{{days}}天',
+ 'todaySpend.codex.windowSegment': '{{label}} 剩余 {{remaining}}',
'todaySpend.sessionCostLabel': '本任务 {{cost}}',
'todaySpend.tooltip.sessionUsed': '本任务已用 {{cost}}',
'todaySpend.codex.sessionValueLabel': '本任务价值 {{cost}}',
@@ -85,7 +94,7 @@ vi.mock('@/hooks/useSessionUsageMoney', () => ({
vi.mock('@/hooks/useSessionTokens', () => ({ useSessionTokens: () => null }));
vi.mock('@/hooks/useAccountUsage', () => ({
requestCodexAccountRefresh: vi.fn(),
- useAccountUsage: () => null,
+ useAccountUsage: () => mocks.codexSnapshot,
}));
vi.mock('@/hooks/useClaudeAccountUsage', () => ({ useClaudeAccountUsage: () => null }));
vi.mock('@/hooks/useModelAccessCreditUsage', () => ({ useModelAccessCreditUsage: () => null }));
@@ -94,7 +103,7 @@ vi.mock('@/hooks/useClaudeSubscriptionUsage', () => ({
useClaudeSubscriptionUsage: () => mocks.claudeSnapshot,
}));
vi.mock('@/hooks/useCodexRuntimeRoute', () => ({
- useCodexRuntimeRoute: () => ({ authInjection: null }),
+ useCodexRuntimeRoute: () => ({ authInjection: mocks.codexAuthInjection }),
}));
vi.mock('@/hooks/useCodexRateLimits', () => ({
useCodexRateLimits: () => ({
@@ -183,6 +192,8 @@ beforeEach(() => {
subscriptionType: 'max',
sevenDay: { utilization: 34, resetsAt: Date.now() / 1000 + 86_400 },
};
+ mocks.codexSnapshot = null;
+ mocks.codexAuthInjection = null;
Object.defineProperty(window, 'electronAPI', {
configurable: true,
value: { openExternal: mocks.openExternal },
@@ -197,6 +208,44 @@ afterEach(() => {
});
describe('TodaySpendChip Claude subscription popover', () => {
+ it('完整渲染 Claude 的 5h 与当前模型周窗口', () => {
+ mocks.claudeSnapshot = {
+ source: 'oauth-endpoint',
+ fiveHour: { utilization: 12 },
+ sevenDay: { utilization: 25 },
+ scoped: [{ modelDisplayName: 'Opus', utilization: 34 }],
+ };
+
+ renderClaudeSubscriptionChip();
+
+ const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });
+ expect(trigger.textContent).toContain('5h 剩余 88%');
+ expect(trigger.textContent).toContain('Opus 周限 剩余 66%');
+ });
+
+ it('完整渲染 Codex app-server 的两个权威窗口', () => {
+ mocks.codexAuthInjection = 'oauth-bearer';
+ mocks.codexSnapshot = {
+ source: 'codex-app-server',
+ limitId: 'codex',
+ primary: { usedPercent: 12, windowMinutes: 300 },
+ secondary: { usedPercent: 34, windowMinutes: 10_080 },
+ };
+
+ render(
+ <TodaySpendChip
+ vendorKey="codex"
+ providerId="openai"
+ modelId="gpt-5.6-sol"
+ sessionId="session-codex"
+ />,
+ );
+
+ const trigger = screen.getByRole('button', { name: '打开 Codex 用量页面' });
+ expect(trigger.textContent).toContain('5h 剩余 88%');
+ expect(trigger.textContent).toContain('7天 剩余 66%');
+ });
+
it('悬停约 300ms 后显示额度卡片', () => {
renderClaudeSubscriptionChip();
const trigger = screen.getByRole('button', { name: '打开 Claude 用量页面' });
diff --git a/apps/desktop/src/renderer/hooks/useAccountUsage.ts b/apps/desktop/src/renderer/hooks/useAccountUsage.ts
index dfdd123b9f..ac2520e653 100644
--- a/apps/desktop/src/renderer/hooks/useAccountUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useAccountUsage.ts
@@ -198,9 +198,23 @@ export function mergeCodexAccountUsageSnapshot(
previous.source === 'openai-web'
&& incoming.source !== 'openai-web'
&& (isCodexZeroWindowFallback(incoming) || isCodexWindowlessFallback(incoming));
+ const incomingHasPrimary = Object.prototype.hasOwnProperty.call(incoming, 'primary');
+ const incomingHasSecondary = Object.prototype.hasOwnProperty.call(incoming, 'secondary');
const keepPreviousWindows =
keepPreviousWebFields
- || (hasCodexUsageWindow(previous) && isCodexWindowlessFallback(incoming));
+ || (
+ hasCodexUsageWindow(previous)
+ && isCodexWindowlessFallback(incoming)
+ && (incomingHasPrimary === incomingHasSecondary)
+ );
+ // 裸 account_usage 是 app-server 的稀疏滚动通知:只带 primary 时 secondary
+ // 不是被删除,只是本次没携带(反之亦然)。逐窗保留,避免 renderer 在 main 的
+ // 权威组合 payload 到达前先把另一段额度闪没。WHAM 是全量读取,仍允许清窗;
+ // reached marker 则是权威清空信号。
+ const preserveMissingAppServerWindows =
+ previous.source !== 'openai-web'
+ && incoming.source !== 'openai-web'
+ && !hasCodexRateLimitReached(incoming);
const incomingCredits = incoming.credits;
const previousCredits = previous.credits ?? null;
@@ -220,8 +234,12 @@ export function mergeCodexAccountUsageSnapshot(
return {
...incoming,
- primary: keepPreviousWindows ? previous.primary : incoming.primary,
- secondary: keepPreviousWindows ? previous.secondary : incoming.secondary,
+ primary: keepPreviousWindows || (preserveMissingAppServerWindows && !incomingHasPrimary)
+ ? previous.primary
+ : incoming.primary,
+ secondary: keepPreviousWindows || (preserveMissingAppServerWindows && !incomingHasSecondary)
+ ? previous.secondary
+ : incoming.secondary,
planType: keepPreviousWebFields ? previous.planType : incoming.planType ?? previous.planType,
credits,
source: keepPreviousWebFields ? previous.source : incoming.source ?? 'codex-app-server',