Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Codex 账号用量快照按来源分槽, 修 chip 被别的限额桶顶掉 (#259)
Dashb3043bd06565
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.tsnew file mode 100644index 0000000000..7a83246f5c--- /dev/null+++ b/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts@@ -0,0 +1,138 @@+/**+ * usageBroadcaster 的 Codex 账号快照分槽单测 —— 两个数据源(codex-app-server /+ * openai-web WHAM)各写各的槽, 不得互相覆盖窗口(2026-07-24 用户实报: WHAM 的+ * Spark 促销桶把 app-server 主配额顶成「8天 剩余 100%」)。+ */++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'),+}));++vi.mock('electron', () => ({+ BrowserWindow: { getAllWindows: () => [] },+}));+vi.mock('../logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../localDb/dailySpend', () => ({+ incrementDailySpend: vi.fn(),+ getTodaySpend: vi.fn(async () => 0),+ localDayKey: () => '2026-07-24',+}));+vi.mock('../localDb/dailyModelUsage', () => ({+ incrementDailyModelUsage: vi.fn(),+}));+vi.mock('../localDb/client/current', () => ({+ getDbClient: () => ({ queryOne: mocks.queryOne, exec: mocks.exec, drizzle: {} }),+}));+vi.mock('../localDb/index', () => ({+ getCurrentUserId: mocks.getCurrentUserId,+}));++const APP_SERVER_SNAPSHOT = {+ limitId: 'codex',+ primary: { usedPercent: 82, windowMinutes: 300, resetsAt: 1_800_000_000 },+ secondary: { usedPercent: 55, windowMinutes: 10_080, resetsAt: 1_800_400_000 },+ source: 'codex-app-server',+ updatedAt: 1,+ accountId: 'acc-1',+};++// 典型污染源: WHAM 返回另一个限额桶(模型专属促销桶)的近乎全新 7 天窗口。+const WEB_SNAPSHOT = {+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: 1_800_700_000 },+ secondary: null,+ planType: 'pro',+ source: 'openai-web',+ updatedAt: 2,+ accountId: 'acc-1',+};++describe('codex account usage source slots', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.queryOne.mockReset().mockResolvedValue(null);+ mocks.exec.mockReset().mockResolvedValue(undefined);+ mocks.getCurrentUserId.mockReturnValue('user-1');+ });++ it('keeps app-server windows when a WHAM snapshot arrives (no cross-source overwrite)', async () => {+ const broadcaster = await import('../usageBroadcaster');++ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot(WEB_SNAPSHOT);++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ // 顶层(CLI 权威槽)保持 app-server 的 5h/周双窗, 不被 WHAM 的桶顶掉+ expect(payload?.primary?.usedPercent).toBe(82);+ expect(payload?.secondary?.usedPercent).toBe(55);+ expect(payload?.source).toBe('codex-app-server');+ // WHAM 数据完整落在 webSnapshot 槽(bridge 形态消费)+ expect(payload?.webSnapshot?.primary?.usedPercent).toBe(0);+ expect(payload?.webSnapshot?.source).toBe('openai-web');+ });++ it('keeps the web slot intact when app-server events arrive afterwards', async () => {+ const broadcaster = await import('../usageBroadcaster');++ await broadcaster.recordCodexAccountUsageSnapshot(WEB_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(payload?.primary?.usedPercent).toBe(82);+ expect(payload?.webSnapshot?.primary?.usedPercent).toBe(0);+ });++ it('hydrates a legacy single-snapshot row into the slot matching its source', async () => {+ const broadcaster = await import('../usageBroadcaster');+ // 旧格式行: 被 WHAM 污染过的单快照(source=openai-web)—— 归 web 槽隔离,+ // 顶层不得把它当成 CLI 配额展示。+ mocks.queryOne.mockResolvedValue({+ snapshot: JSON.stringify({ ...WEB_SNAPSHOT, limitId: 'codex_bengalfox' }),+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(payload?.primary).toBeUndefined();+ expect(payload?.webSnapshot?.limitId).toBe('codex_bengalfox');+ // web-only payload 必须上浮归属字段: WHAM reader 用顶层 accountId 判缓存归属,+ // 缺失会被当成账号失配, 每次读都清缓存 + 强刷 (review 反馈)。+ expect(payload?.accountId).toBe('acc-1');+ });++ it('hydrates a legacy app-server row into the top-level slot', async () => {+ const broadcaster = await import('../usageBroadcaster');+ mocks.queryOne.mockResolvedValue({ snapshot: JSON.stringify(APP_SERVER_SNAPSHOT) });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(payload?.primary?.usedPercent).toBe(82);+ expect(payload?.webSnapshot ?? null).toBeNull();+ });++ it('round-trips the combined payload through persistence', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot(WEB_SNAPSHOT);+ // exec(sql, ['codex', json, ts]) —— 取最后一次落库的 JSON 行原文重新水合。+ const lastExecParams = (mocks.exec.mock.calls.at(-1) as unknown[] | undefined)?.[1] as unknown[];+ const persistedJson = lastExecParams[1] as string;++ vi.resetModules();+ const rehydrated = await import('../usageBroadcaster');+ mocks.queryOne.mockResolvedValue({ snapshot: persistedJson });+ const payload = await rehydrated.readCodexAccountUsageSnapshot();+ expect(payload?.primary?.usedPercent).toBe(82);+ expect(payload?.webSnapshot?.primary?.usedPercent).toBe(0);+ });++ it('clear wipes both slots', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot(WEB_SNAPSHOT);+ await broadcaster.clearCodexAccountUsageSnapshot();+ expect(await broadcaster.readCodexAccountUsageSnapshot()).toBeNull();+ });+});diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex bd2b466182..6fb3d9ea01 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -261,11 +261,28 @@ export async function readAgentTodayUsage(agentKind: AgentKind): Promise<AgentToreturn { day: localDayKey() };}-// ── Codex account usage (persisted latest snapshot) ─────────────────────────+// ── Codex account usage (persisted latest snapshot, 按来源分槽) ──────────────+//+// 账号可能同时存在多个限额桶(主 codex 配额 + 模型专属促销桶, 如+// GPT-5.3-Codex-Spark / codex_bengalfox), 且两个数据源报告的桶可能不同:+// - codex-app-server: 每 turn account_usage 事件 / rateLimits 读 —— CLI 会话+// 实际消耗的配额, Codex 会话 chip 的权威来源;+// - openai-web (WHAM): chatgpt.com/backend-api/wham/usage —— 为 cc + chatgpt/+// bridge 会话引入(bridge 轮不产生 app-server 事件), 报告的桶与 CLI 可能不同。+// 单槽存储会让两个来源互相覆盖(2026-07-24 用户实报: Codex chip 突然跳成+// 「8天 剩余 100%」—— WHAM 的 Spark 桶窗口顶掉了 app-server 的主配额窗口)。+// 分槽后各源只更新自己的槽, 消费方按会话形态选槽(CLI → 顶层, bridge →+// webSnapshot), payload 形状对旧消费者(mobile 防御解析)加性兼容。++/** 组合 payload: 顶层 = codex-app-server 槽(CLI 权威), webSnapshot = WHAM 槽。 */+export interface CodexAccountUsagePayload extends RateLimitSnapshot {+ webSnapshot?: RateLimitSnapshot | null;+}let codexAccountUsageOwner: string | null = null;let codexAccountUsageLoaded = false;-let codexAccountUsageSnapshot: RateLimitSnapshot | null = null;+let codexAppServerUsageSnapshot: RateLimitSnapshot | null = null;+let codexWebAccountUsageSnapshot: RateLimitSnapshot | null = null;function currentAccountUsageOwner(): string | null {try {@@ -280,7 +297,57 @@ function resetCodexAccountUsageCacheIfOwnerChanged(): void {if (owner === codexAccountUsageOwner) return;codexAccountUsageOwner = owner;codexAccountUsageLoaded = false;- codexAccountUsageSnapshot = null;+ codexAppServerUsageSnapshot = null;+ codexWebAccountUsageSnapshot = null;+}++/** 顶层槽是否有可展示内容(区分「空 app 槽 + 仅 web 槽」的 payload)。 */+function hasCodexSnapshotContent(snapshot: RateLimitSnapshot | null | undefined): boolean {+ if (!snapshot) return false;+ return Boolean(+ snapshot.primary+ || snapshot.secondary+ || snapshot.limitId+ || snapshot.planType+ || snapshot.credits+ || snapshot.rateLimitReachedType,+ );+}++/** 两槽 → 组合 payload;两槽全空 → null。 */+function buildCodexAccountUsagePayload(): CodexAccountUsagePayload | null {+ const app = codexAppServerUsageSnapshot;+ const web = codexWebAccountUsageSnapshot;+ if (!app && !web) return null;+ if (!app && web) {+ // web-only: 顶层无 CLI 数据, 但归属字段必须上浮 —— WHAM reader 用顶层+ // accountId 判断缓存归属(codexAccountUsageRefresh), 缺失会被当成账号失配,+ // 每次读都清缓存 + 强刷(bridge-only 用户 warm-start 永远拿 null)。+ // accountId / updatedAt 不算「内容」(hasCodexSnapshotContent), 归槽水合+ // 不会据此伪造出 app 槽。+ return { accountId: web.accountId, updatedAt: web.updatedAt, webSnapshot: web };+ }+ return { ...(app as RateLimitSnapshot), webSnapshot: web ?? null };+}++/**+ * 持久化行 → 两槽。新格式带 webSnapshot 键;旧格式是单快照 —— 按其 source+ * 归入对应槽(旧行可能是被 WHAM 污染过的单槽杂交体, 归 web 槽即自然隔离)。+ */+export function splitPersistedCodexAccountUsage(parsed: Record<string, unknown>): {+ appServer: RateLimitSnapshot | null;+ web: RateLimitSnapshot | null;+} {+ if ('webSnapshot' in parsed) {+ const { webSnapshot, ...rest } = parsed as CodexAccountUsagePayload;+ return {+ appServer: hasCodexSnapshotContent(rest) ? rest : null,+ web: webSnapshot && typeof webSnapshot === 'object' ? webSnapshot : null,+ };+ }+ const legacy = parsed as RateLimitSnapshot;+ if (legacy.source === 'openai-web') return { appServer: null, web: legacy };+ return { appServer: hasCodexSnapshotContent(legacy) ? legacy : null, web: null };}function mergeCodexAccountUsageSnapshot(@@ -363,7 +430,9 @@ async function ensureCodexAccountUsageLoaded(): Promise<void> {if (!row?.snapshot) return;const parsed = JSON.parse(row.snapshot);if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {- codexAccountUsageSnapshot = parsed as RateLimitSnapshot;+ const slots = splitPersistedCodexAccountUsage(parsed as Record<string, unknown>);+ codexAppServerUsageSnapshot = slots.appServer;+ codexWebAccountUsageSnapshot = slots.web;}} catch (err) {log.warn(@@ -377,12 +446,22 @@ export async function recordCodexAccountUsageSnapshot(snapshot: unknown): Promisif (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return;await ensureCodexAccountUsageLoaded();- const next = mergeCodexAccountUsageSnapshot(- codexAccountUsageSnapshot,- snapshot as RateLimitSnapshot,- );- codexAccountUsageSnapshot = next;- broadcastCodexAccountUsage(next);+ // 按来源路由到自己的槽 —— 槽内 merge 保留原有的 windowless / 部分字段兜底+ // 语义, 但两个来源不再互相覆盖窗口(见本节头注释)。+ const incoming = snapshot as RateLimitSnapshot;+ if (incoming.source === 'openai-web') {+ codexWebAccountUsageSnapshot = mergeCodexAccountUsageSnapshot(+ codexWebAccountUsageSnapshot,+ incoming,+ );+ } else {+ codexAppServerUsageSnapshot = mergeCodexAccountUsageSnapshot(+ codexAppServerUsageSnapshot,+ incoming,+ );+ }+ const payload = buildCodexAccountUsagePayload();+ broadcastCodexAccountUsage(payload);try {await getDbClient().exec(@@ -391,7 +470,7 @@ export async function recordCodexAccountUsageSnapshot(snapshot: unknown): PromisON CONFLICT(agent_kind) DO UPDATE SETsnapshot = excluded.snapshot,updated_at = excluded.updated_at`,- ['codex', JSON.stringify(next), Date.now()],+ ['codex', JSON.stringify(payload), Date.now()],);} catch (err) {log.warn(@@ -404,7 +483,8 @@ export async function recordCodexAccountUsageSnapshot(snapshot: unknown): Promisexport async function clearCodexAccountUsageSnapshot(): Promise<void> {resetCodexAccountUsageCacheIfOwnerChanged();codexAccountUsageLoaded = true;- codexAccountUsageSnapshot = null;+ codexAppServerUsageSnapshot = null;+ codexWebAccountUsageSnapshot = null;broadcastCodexAccountUsage(null);try {@@ -420,9 +500,9 @@ export async function clearCodexAccountUsageSnapshot(): Promise<void> {}}-export async function readCodexAccountUsageSnapshot(): Promise<RateLimitSnapshot | null> {+export async function readCodexAccountUsageSnapshot(): Promise<CodexAccountUsagePayload | null> {await ensureCodexAccountUsageLoaded();- return codexAccountUsageSnapshot;+ return buildCodexAccountUsagePayload();}// ── xAI(SuperGrok bridge)限流快照 ─────────────────────────────────────────diff --git a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.tsindex e8685ff115..cb45cac919 100644--- a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts@@ -2,7 +2,10 @@ import { readFileSync } from 'node:fs';import { describe, expect, it } from 'vitest';-import { mergeCodexAccountUsageSnapshot } from '@/hooks/useAccountUsage';+import {+ mergeCodexAccountUsageSnapshot,+ splitCodexAccountUsagePayload,+} from '@/hooks/useAccountUsage';describe('mergeCodexAccountUsageSnapshot', () => {it('preserves the last known credit balance when a later snapshot omits credits', () => {@@ -196,7 +199,7 @@ describe('mergeCodexAccountUsageSnapshot', () => {const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');expect(mainSource).toContain("USAGE_CODEX_ACCOUNT_CHANGED = 'usage:codex-account-changed'");- expect(mainSource).toContain('broadcastCodexAccountUsage(next);');+ expect(mainSource).toContain('broadcastCodexAccountUsage(payload);');expect(mainSource).toContain('isCodexZeroWindowFallback(incoming)');expect(mainSource).toContain('isCodexWindowlessFallback(incoming)');expect(mainSource).toContain('broadcastCodexAccountUsage(null);');@@ -204,6 +207,70 @@ describe('mergeCodexAccountUsageSnapshot', () => {expect(preloadSource).toContain('onCodexAccountChanged: fanOutMakerUsageCodexAccount');expect(hookSource).toContain('api.onCodexAccountChanged');expect(hookSource).toContain('options: { clearOnNull?: boolean } = {}');- expect(hookSource).toContain("applyCodexAccountUsageSnapshot(persisted, setSnapshot, { clearOnNull: false })");+ expect(hookSource).toContain('() => setSnapshot(selectCodexSlot(quotaSource))');+ // 按来源分槽: 两个数据源不得互相覆盖(main / renderer 双份实现同口径)+ expect(mainSource).toContain('function splitPersistedCodexAccountUsage(');+ expect(mainSource).toContain("incoming.source === 'openai-web'");+ expect(hookSource).toContain('function splitCodexAccountUsagePayload(');+ // CLI turn 事件后不再拉 getAccount 触发 WHAM 刷新 (CLI chip 不显示 web 槽,+ // 白耗后台请求; review 反馈) —— bridge 槽保鲜走 main 的 bridge turn-done+ // 触发 + mount 读 + 悬念期催刷+ expect(hookSource).not.toContain('refreshWebUsage');+ // module 常驻订阅: chip 全部卸载期间的换号清空广播不丢 (与 claude hook 同语义)+ expect(hookSource).toContain('function ensureModuleSubscription(');+ expect(hookSource).toContain('ensureModuleSubscription();');+ // web-only 组合 payload 上浮归属字段, WHAM reader 的 accountId 归属判断不失配+ expect(mainSource).toContain('accountId: web.accountId');+ });+});++describe('splitCodexAccountUsagePayload', () => {+ it('routes combined payloads into per-source slots', () => {+ const parts = splitCodexAccountUsagePayload({+ limitId: 'codex',+ primary: { usedPercent: 82 },+ source: 'codex-app-server',+ webSnapshot: { primary: { usedPercent: 0 }, source: 'openai-web' },+ } as never);+ expect(parts.appServer?.primary?.usedPercent).toBe(82);+ expect((parts.appServer as { webSnapshot?: unknown } | undefined)?.webSnapshot)+ .toBeUndefined();+ expect(parts.web?.primary?.usedPercent).toBe(0);+ });++ it('routes bare snapshots by their source field (per-turn events vs WHAM)', () => {+ expect(splitCodexAccountUsagePayload({+ primary: { usedPercent: 40 },+ source: 'codex-app-server',+ }).appServer?.primary?.usedPercent).toBe(40);+ expect(splitCodexAccountUsagePayload({+ primary: { usedPercent: 5 },+ source: 'openai-web',+ }).web?.primary?.usedPercent).toBe(5);+ });++ it('treats combined payloads as authoritative: empty slots clear explicitly', () => {+ // web-only 组合 payload: app 槽显式清空(null), 不是「未携带」—— 否则换号 /+ // 切形态后旧 app 槽数据一直挂着 (review 反馈)+ const webOnly = splitCodexAccountUsagePayload({+ accountId: 'acc-2',+ webSnapshot: { primary: { usedPercent: 5 }, source: 'openai-web' },+ } as never);+ expect(webOnly.appServer).toBeNull();+ expect(webOnly.web?.primary?.usedPercent).toBe(5);+ // app-only 组合 payload (webSnapshot: null): web 槽显式清空+ const appOnly = splitCodexAccountUsagePayload({+ primary: { usedPercent: 82 },+ source: 'codex-app-server',+ webSnapshot: null,+ } as never);+ expect(appOnly.appServer?.primary?.usedPercent).toBe(82);+ expect(appOnly.web).toBeNull();+ // 裸快照是增量: 只携带自己的槽, 另一个槽键缺失(保留现值)+ const bare = splitCodexAccountUsagePayload({+ primary: { usedPercent: 40 },+ source: 'codex-app-server',+ });+ expect('web' in bare).toBe(false);});});diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.tsindex fcd70bfbaf..93d20a4222 100644--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts@@ -82,7 +82,10 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).toContain('const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;',);- expect(source).toContain("useAccountUsage(sessionId, shouldReadLocalCodexAccountUsage ? 'codex' : undefined)");+ // 按会话形态选配额槽: bridge → WHAM(openai-web)槽, CLI → app-server 槽,+ // 不跨槽回退(账号多限额桶互相污染, 2026-07-24 实报 bug)+ expect(source).toContain("shouldReadLocalCodexAccountUsage ? 'codex' : undefined,");+ expect(source).toContain("isChatgptBridge ? 'openai-web' : 'app-server',");});it('keeps Codex OAuth subscription details in the chip and tooltip', () => {@@ -248,14 +251,13 @@ describe('TodaySpendChip dashboard routing', () => {// motion-safe = 尊重 prefers-reduced-motion (review P1, PR #546)expect(source).toContain('<span className="motion-safe:animate-pulse">…</span>');expect(source).not.toContain('"animate-pulse"');- // 悬念期主动催余量刷新, Claude / Codex 两侧都要 (main 侧 cached-first + 节流,- // 重复调用安全; Codex 缺催刷会在空闲期卡悬念态, review P1)。分支优先级必须- // 与 chipWindows 形态选择一致 —— Codex 形态优先: cc + chatgpt/ bridge 会话里- // usesCodexQuotaForm 与 isClaudeSubscription 可同时为真 (review P1 第二轮)+ // 悬念期催刷通道必须与 chip 显示的配额槽一致: bridge 形态催 WHAM; Codex CLI+ // 形态显示 app-server 槽, WHAM 刷新帮不上它(靠 turn 事件 / 悬念超时兜底),+ // 不得催 —— WHAM 桶与 CLI 配额可能不同(账号多限额桶, 2026-07-24 实报 bug)expect(source).toContain(- 'if (usesCodexQuotaForm) {\n'+ 'if (isChatgptBridge) {\n'+ ' requestCodexAccountRefresh();\n'- + ' } else if (isClaudeSubscription) {\n'+ + ' } else if (isClaudeSubscription && !usesCodexQuotaForm) {\n'+ ' requestClaudeSubscriptionRefresh();\n'+ ' }',);diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 60a5fafcc5..e5ec7df43b 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -1010,7 +1010,14 @@ export function TodaySpendChip({sessionId,isCodexSubscription || isClaudeSubscription || isSubscriptionBridge,);- const accountUsage = useAccountUsage(sessionId, shouldReadLocalCodexAccountUsage ? 'codex' : undefined);+ // 按会话形态选配额槽: chatgpt/ bridge 消耗 WHAM(openai-web)报告的配额,+ // Codex CLI 会话消耗 app-server 报告的配额 —— 不跨槽回退, 绝不显示不是这个+ // 会话在消耗的配额(账号多限额桶会互相污染, 见 useAccountUsage 头注释)。+ const accountUsage = useAccountUsage(+ sessionId,+ shouldReadLocalCodexAccountUsage ? 'codex' : undefined,+ isChatgptBridge ? 'openai-web' : 'app-server',+ );// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession);// cc 与 codex-api 共用同一把 XD gateway key 的 LiteLLM quota; codex-oauth 不订阅。@@ -1143,21 +1150,23 @@ export function TodaySpendChip({return () => window.clearTimeout(timer);}, [usesCodexQuotaForm, isClaudeSubscription, windowLabelNowMs, chipResetsAtMsList]);- // 悬念期主动催一次余量刷新, 让「重置揭晓」尽快到来 —— 两侧的 main read 都是+ // 悬念期主动催一次余量刷新, 让「重置揭晓」尽快到来 —— main read 都是// cached-first + 节流(Claude 订阅端点 180s + 退避; Codex WHAM 10s + in-flight// 去重), 每个 tick 重试一次是安全的; 新快照落地即结束悬念期。- // 分支优先级必须与上面 chipWindows 的形态选择一致(Codex 形态优先): cc 会话跑- // chatgpt/ bridge 模型时 usesCodexQuotaForm 与 isClaudeSubscription 可同时为真,- // 此时 chip 显示的是 ChatGPT 窗口, 催刷也必须走 Codex 通道。+ // 催刷通道必须与 chip 实际显示的配额槽一致:+ // - chatgpt/ bridge 形态显示 WHAM(openai-web)槽 → 催 WHAM;+ // - Codex CLI 形态显示 app-server 槽 —— WHAM 刷新只落 web 槽、帮不上它,+ // 且无空闲期 app-server 催刷通道, 靠下一个 turn 事件或悬念超时回落兜底;+ // - Claude 订阅形态催订阅端点。const hasPendingResetWindow = chipWindows.some((window) => window.resetPending);React.useEffect(() => {if (!hasPendingResetWindow) return;- if (usesCodexQuotaForm) {+ if (isChatgptBridge) {requestCodexAccountRefresh();- } else if (isClaudeSubscription) {+ } else if (isClaudeSubscription && !usesCodexQuotaForm) {requestClaudeSubscriptionRefresh();}- }, [hasPendingResetWindow, isClaudeSubscription, usesCodexQuotaForm, windowLabelNowMs]);+ }, [hasPendingResetWindow, isChatgptBridge, isClaudeSubscription, usesCodexQuotaForm, windowLabelNowMs]);const isDashboardClickable = usageDashboardUrl !== null;const handleClick = () => {diff --git a/apps/desktop/src/renderer/hooks/useAccountUsage.ts b/apps/desktop/src/renderer/hooks/useAccountUsage.tsindex a17332744b..db3a081f64 100644--- a/apps/desktop/src/renderer/hooks/useAccountUsage.ts+++ b/apps/desktop/src/renderer/hooks/useAccountUsage.ts@@ -10,6 +10,13 @@* → preload window.electronAPI.maker.usage.onCodexAccountChanged* → 本 hook 直接更新账号级快照*+ * 按来源分槽(与 main usageBroadcaster 同口径): 账号可能同时存在多个限额桶,+ * codex-app-server(每 turn 事件, CLI 会话消耗的配额)与 openai-web(WHAM,+ * chatgpt/ bridge 消耗的配额)报告的桶可能不同, 单槽缓存会互相覆盖(2026-07-24+ * 用户实报: Codex chip 突然跳成「8天 剩余 100%」)。组合 payload 顶层 =+ * app-server 槽, webSnapshot = WHAM 槽;调用方按会话形态选槽, 不跨槽回退+ * (绝不显示不是这个会话在消耗的配额)。+ ** 设计与 useSessionSpend 对齐:* - 按 sessionId 过滤 (虽然 host 端是 fan-out 给所有 active subscriber, 每个 session 都收一份)* - Codex 账号用量是账号级数据, 切 session 时复用最近一次快照, 避免 chip 闪回占位态@@ -48,7 +55,21 @@ export interface RateLimitSnapshot {accountId?: string | null;}-let lastCodexAccountUsage: RateLimitSnapshot | null = null;+/** chip 选槽依据: Codex CLI 会话消耗 app-server 报告的配额, chatgpt/ bridge 消耗 WHAM 报告的配额。 */+export type CodexQuotaSource = 'app-server' | 'openai-web';++interface CodexAccountUsageSlots {+ appServer: RateLimitSnapshot | null;+ web: RateLimitSnapshot | null;+}++let lastCodexAccountUsage: CodexAccountUsageSlots = { appServer: null, web: null };++function selectCodexSlot(quotaSource: CodexQuotaSource): RateLimitSnapshot | null {+ return quotaSource === 'openai-web'+ ? lastCodexAccountUsage.web+ : lastCodexAccountUsage.appServer;+}function readUsageApi(): {getAccount?: (agentKind: 'claude-code' | 'codex') => Promise<unknown | null>;@@ -136,21 +157,92 @@ function isCodexWindowlessFallback(snapshot: RateLimitSnapshot): boolean {return !snapshot.primary && !snapshot.secondary;}+/** 顶层槽是否有可展示内容(区分「空 app 槽 + 仅 webSnapshot」的组合 payload)。 */+function hasCodexSnapshotContent(snapshot: RateLimitSnapshot | null | undefined): boolean {+ if (!snapshot) return false;+ return Boolean(+ snapshot.primary+ || snapshot.secondary+ || snapshot.limitId+ || snapshot.planType+ || snapshot.credits+ || snapshot.rateLimitReachedType,+ );+}++/**+ * 入站 payload → 两槽更新(纯函数, 供单测)。三种形状:+ * - 组合 payload(带 webSnapshot 键, 来自 IPC read / usage push): 是 main 侧+ * **两槽的权威全量** —— 顶层有内容归 app 槽、无内容 = app 槽显式清空(null);+ * webSnapshot 同理。不清会让换号 / 切形态后旧槽数据一直挂着(review 反馈)。+ * - 单快照(per-turn account_usage 事件 / 旧格式): 增量, 按 source 只更新+ * 自己的槽 —— openai-web → web, 其余 → app。+ * 语义: 键缺失 = 本次不携带该槽信息(保留现值); 键为 null = 显式清空。+ */+export function splitCodexAccountUsagePayload(incoming: RateLimitSnapshot): {+ appServer?: RateLimitSnapshot | null;+ web?: RateLimitSnapshot | null;+} {+ if ('webSnapshot' in incoming) {+ const { webSnapshot, ...rest } = incoming as RateLimitSnapshot & {+ webSnapshot?: unknown;+ };+ return {+ appServer: hasCodexSnapshotContent(rest) ? rest : null,+ web: isRateLimitSnapshot(webSnapshot) ? webSnapshot : null,+ };+ }+ if (incoming.source === 'openai-web') return { web: incoming };+ return { appServer: incoming };+}+function applyCodexAccountUsageSnapshot(incoming: unknown,- updateSnapshot: (snapshot: RateLimitSnapshot | null) => void,+ onApplied: () => void,options: { clearOnNull?: boolean } = {},): void {if (incoming === null) {if (options.clearOnNull === false) return;- lastCodexAccountUsage = null;- updateSnapshot(null);+ lastCodexAccountUsage = { appServer: null, web: null };+ onApplied();return;}if (!isRateLimitSnapshot(incoming)) return;- const next = mergeCodexAccountUsageSnapshot(lastCodexAccountUsage, incoming);- lastCodexAccountUsage = next;- updateSnapshot(next);+ const parts = splitCodexAccountUsagePayload(incoming);+ // 键存在即生效: 快照 → 槽内 merge; null → 显式清空(组合 payload 是权威全量,+ // 见 splitCodexAccountUsagePayload); 键缺失 → 保留现值(裸快照只带自己的槽)。+ if ('appServer' in parts) {+ lastCodexAccountUsage = {+ ...lastCodexAccountUsage,+ appServer: parts.appServer+ ? mergeCodexAccountUsageSnapshot(lastCodexAccountUsage.appServer, parts.appServer)+ : null,+ };+ }+ if ('web' in parts) {+ lastCodexAccountUsage = {+ ...lastCodexAccountUsage,+ web: parts.web+ ? mergeCodexAccountUsageSnapshot(lastCodexAccountUsage.web, parts.web)+ : null,+ };+ }+ onApplied();+}++// module 级常驻订阅 —— 与组件生命周期解耦: 所有 codex chip 卸载期间发生登出 /+// 换号时, main 的 null / 新 payload 广播也要同步进 module 缓存, 否则下次 mount+// 的 useState initializer 会先 seed 旧账号槽数据闪一帧。幂等安装, 随 renderer+// 进程存活, 不退订(与 useClaudeSubscriptionUsage 的常驻语义一致)。+let moduleSubscriptionInstalled = false;+function ensureModuleSubscription(): void {+ if (moduleSubscriptionInstalled) return;+ const api = readUsageApi();+ if (!api?.onCodexAccountChanged) return;+ moduleSubscriptionInstalled = true;+ api.onCodexAccountChanged((payload: unknown) => {+ applyCodexAccountUsageSnapshot(payload, () => {});+ });}/**@@ -170,16 +262,19 @@ export function requestCodexAccountRefresh(): void {export function useAccountUsage(sessionId: string | undefined,vendorKey: 'cc' | 'codex' | undefined,+ quotaSource: CodexQuotaSource = 'app-server',): RateLimitSnapshot | null {+ // 幂等; 首个实例装上 module 常驻订阅, 保证卸载窗口内的广播(尤其换号清空)不丢。+ ensureModuleSubscription();const [snapshot, setSnapshot] = useState<RateLimitSnapshot | null>(() =>- vendorKey === 'codex' ? lastCodexAccountUsage : null,+ vendorKey === 'codex' ? selectCodexSlot(quotaSource) : null,);// Codex rate limits 是账号级数据, 不是 session 级数据。切回 Codex session 时// 直接复用最近一次快照, 等 host replay/下一次 push 再覆盖。useEffect(() => {- setSnapshot(vendorKey === 'codex' ? lastCodexAccountUsage : null);- }, [sessionId, vendorKey]);+ setSnapshot(vendorKey === 'codex' ? selectCodexSlot(quotaSource) : null);+ }, [sessionId, vendorKey, quotaSource]);useEffect(() => {if (vendorKey !== 'codex') return;@@ -191,7 +286,11 @@ export function useAccountUsage(.getAccount('codex').then((persisted) => {if (cancelled) return;- applyCodexAccountUsageSnapshot(persisted, setSnapshot, { clearOnNull: false });+ applyCodexAccountUsageSnapshot(+ persisted,+ () => setSnapshot(selectCodexSlot(quotaSource)),+ { clearOnNull: false },+ );}).catch(() => {/* Best-effort warm start; live account_usage events still update the chip. */@@ -200,7 +299,7 @@ export function useAccountUsage(return () => {cancelled = true;};- }, [vendorKey]);+ }, [vendorKey, quotaSource]);useEffect(() => {if (vendorKey !== 'codex') return;@@ -210,13 +309,13 @@ export function useAccountUsage(let cancelled = false;const unsubscribe = api.onCodexAccountChanged((payload: unknown) => {if (cancelled) return;- applyCodexAccountUsageSnapshot(payload, setSnapshot);+ applyCodexAccountUsageSnapshot(payload, () => setSnapshot(selectCodexSlot(quotaSource)));});return () => {cancelled = true;unsubscribe();};- }, [vendorKey]);+ }, [vendorKey, quotaSource]);useEffect(() => {if (vendorKey !== 'codex' || !sessionId) return;@@ -224,26 +323,15 @@ export function useAccountUsage(electronAPI?: {maker?: {onEvent?: (cb: (data: unknown) => void) => () => void;- usage?: {- getAccount?: (agentKind: 'claude-code' | 'codex') => Promise<unknown | null>;- };};};}).electronAPI?.maker;if (!api?.onEvent) return;let cancelled = false;- const refreshWebUsage = (): void => {- const getAccount = api.usage?.getAccount;- if (!getAccount) return;- void getAccount('codex')- .then((persisted) => {- if (cancelled) return;- applyCodexAccountUsageSnapshot(persisted, setSnapshot, { clearOnNull: false });- })- .catch(() => {- /* Best-effort refresh; keep the last reliable snapshot. */- });- };+ // 注: 这里不再在 turn 事件后拉 getAccount 触发 WHAM 刷新 —— CLI chip 只显示+ // app-server 槽, WHAM 刷新帮不上它, 白耗后台请求(旧行为还会把 WHAM 桶合并+ // 进单槽缓存, 正是「turn 刚结束数据被顶掉」的来源)。bridge 槽的保鲜由+ // main 的 bridge turn-done 触发 + mount 读 + 悬念期催刷负责。const unsubscribe = api.onEvent((data: unknown) => {if (cancelled) return;const payload = data as {@@ -254,14 +342,16 @@ export function useAccountUsage(if (payload.event?.type !== 'account_usage') return;if (payload.event.source !== 'codex') return;if (!payload.event.data) return;- applyCodexAccountUsageSnapshot(payload.event.data, setSnapshot);- refreshWebUsage();+ applyCodexAccountUsageSnapshot(+ payload.event.data,+ () => setSnapshot(selectCodexSlot(quotaSource)),+ );});return () => {cancelled = true;unsubscribe();};- }, [sessionId, vendorKey]);+ }, [sessionId, vendorKey, quotaSource]);return snapshot;}