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 用量按 limitId 分桶, 修模型专属桶串到别的会话 (#379)
Dash8a6bc9118899
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.tsindex aadbf56df2..7da2e445ed 100644--- a/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts+++ b/apps/desktop/src/main/__tests__/usageBroadcasterCodexAccount.test.ts@@ -148,3 +148,281 @@ describe('codex account usage source slots', () => {expect(await broadcaster.readCodexAccountUsageSnapshot()).toBeNull();});});++describe('codex app-server limit buckets', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.queryOne.mockReset().mockResolvedValue(null);+ mocks.exec.mockReset().mockResolvedValue(undefined);+ mocks.getCurrentUserId.mockReturnValue('user-1');+ });++ // 2026-07-25 用户实报的真实污染行: app 槽被模型专属促销桶(Spark)占据,+ // 于是 gpt-5.6-sol 会话的 chip 显示「8天 剩余 100%」。+ const SPARK_BUCKET = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowDurationMins: 10_080, resetsAt: 1_785_548_762, windowMinutes: 10_080 },+ secondary: null,+ source: 'codex-app-server',+ };++ it('keeps different limit buckets isolated instead of overwriting each other', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot(SPARK_BUCKET);++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ // 顶层 = 最近更新桶(兼容位), 但主桶数据必须完整活在桶表里+ expect(payload?.limitId).toBe('codex_bengalfox');+ expect(payload?.appServerBuckets?.codex?.primary?.usedPercent).toBe(82);+ expect(payload?.appServerBuckets?.codex?.secondary?.usedPercent).toBe(55);+ expect(payload?.appServerBuckets?.codex_bengalfox?.primary?.usedPercent).toBe(0);+ // 跨桶不得合并成杂交体: Spark 桶没有 secondary, 不该继承主桶的+ expect(payload?.appServerBuckets?.codex_bengalfox?.secondary ?? null).toBeNull();+ });++ it('merges repeated updates within the same bucket', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot({+ ...APP_SERVER_SNAPSHOT,+ primary: { usedPercent: 91, windowMinutes: 300, resetsAt: 1_800_000_000 },+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex']);+ expect(payload?.appServerBuckets?.codex?.primary?.usedPercent).toBe(91);+ });++ it('hydrates a pre-bucket persisted row into its matching bucket', async () => {+ const broadcaster = await import('../usageBroadcaster');+ // 分槽版(有 webSnapshot 键、无 appServerBuckets)写下的行 —— 顶层是 Spark 桶+ mocks.queryOne.mockResolvedValue({+ snapshot: JSON.stringify({ ...SPARK_BUCKET, webSnapshot: null }),+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(payload?.appServerBuckets?.codex_bengalfox?.limitName).toBe('GPT-5.3-Codex-Spark');+ // 主桶此时未知: 表里只有 Spark 桶, 主桶会在下一个 turn 事件到达时建立+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex_bengalfox']);+ });++ it('round-trips the bucket table through persistence', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(APP_SERVER_SNAPSHOT);+ await broadcaster.recordCodexAccountUsageSnapshot(SPARK_BUCKET);+ 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?.appServerBuckets?.codex?.primary?.usedPercent).toBe(82);+ expect(payload?.appServerBuckets?.codex_bengalfox?.primary?.usedPercent).toBe(0);+ });++ it('drops malformed bucket entries on hydration', async () => {+ const broadcaster = await import('../usageBroadcaster');+ mocks.queryOne.mockResolvedValue({+ snapshot: JSON.stringify({+ ...APP_SERVER_SNAPSHOT,+ webSnapshot: null,+ appServerBuckets: { codex: APP_SERVER_SNAPSHOT, broken: [], alsoBroken: 'nope' },+ }),+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex']);+ });+});++describe('codex bucket edge cases (review follow-up)', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.queryOne.mockReset().mockResolvedValue(null);+ mocks.exec.mockReset().mockResolvedValue(undefined);+ mocks.getCurrentUserId.mockReturnValue('user-1');+ });++ const BUCKET_A = {+ limitId: 'codex',+ primary: { usedPercent: 40, windowMinutes: 300, resetsAt: 1_800_000_000 },+ source: 'codex-app-server',+ };+ const BUCKET_B = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: 1_785_548_762 },+ source: 'codex-app-server',+ };++ it('restores the latest bucket after A → B → A across a restart', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(BUCKET_A);+ await broadcaster.recordCodexAccountUsageSnapshot(BUCKET_B);+ await broadcaster.recordCodexAccountUsageSnapshot({+ ...BUCKET_A,+ primary: { usedPercent: 58, windowMinutes: 300, resetsAt: 1_800_000_000 },+ });+ 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();+ // 覆盖已有键不会把它移到对象末尾 —— 顶层兼容位必须仍是最近更新的 A+ expect(payload?.limitId).toBe('codex');+ expect(payload?.primary?.usedPercent).toBe(58);+ });++ it('never uses prototype-polluting limitIds as bucket keys', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot({+ ...BUCKET_A,+ limitId: '__proto__',+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['__default__']);+ expect(({} as Record<string, unknown>).primary).toBeUndefined();+ });++ it('drops prototype-polluting keys when hydrating a bucket table', async () => {+ const broadcaster = await import('../usageBroadcaster');+ mocks.queryOne.mockResolvedValue({+ snapshot: JSON.stringify({+ ...BUCKET_A,+ webSnapshot: null,+ appServerBuckets: { codex: BUCKET_A, __proto__: BUCKET_B },+ }),+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex']);+ });++ // 本仓写入路径不会产出这种行(顶层就是从桶表取的), 但外部 / 损坏 / 跨版本行+ // 可能给出桶表里没有的最近桶键。旧实现会让 currentCodexAppServerSnapshot()+ // 返 null —— app-server 配额一直空到下一次推送(review 反馈)。+ it('re-seeds the latest bucket when a persisted row references a missing key', async () => {+ const broadcaster = await import('../usageBroadcaster');+ mocks.queryOne.mockResolvedValue({+ snapshot: JSON.stringify({+ ...BUCKET_A,+ webSnapshot: null,+ // 顶层是 codex, 桶表却只有无 ID 更新建出来的缺省桶+ appServerBuckets: { __default__: { ...BUCKET_B, limitId: undefined } },+ }),+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ // 顶层配额没有消失, 且它自己的桶被补种回桶表+ expect(payload?.limitId).toBe('codex');+ expect(payload?.primary?.usedPercent).toBe(40);+ expect(Object.keys(payload?.appServerBuckets ?? {}).sort()).toEqual(['__default__', 'codex']);+ });++ it('keeps hydration safe when the missing latest key is prototype-polluting', async () => {+ const broadcaster = await import('../usageBroadcaster');+ mocks.queryOne.mockResolvedValue({+ snapshot: JSON.stringify({+ ...BUCKET_A,+ limitId: '__proto__',+ webSnapshot: null,+ appServerBuckets: {},+ }),+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ // 危险 limitId 早在 codexLimitBucketKey 就被映射成缺省桶, 补种不污染原型+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['__default__']);+ expect(({} as Record<string, unknown>).primary).toBeUndefined();+ });+});++describe('codex stale bucket pruning', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.queryOne.mockReset().mockResolvedValue(null);+ mocks.exec.mockReset().mockResolvedValue(undefined);+ mocks.getCurrentUserId.mockReturnValue('user-1');+ });++ it('prunes buckets whose windows expired long ago, keeping the latest one', async () => {+ const broadcaster = await import('../usageBroadcaster');+ // 促销早已结束的 Spark 桶(窗口过点远超宽限)+ await broadcaster.recordCodexAccountUsageSnapshot({+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: 1_600_000_000 },+ source: 'codex-app-server',+ });+ // 新的通用桶事件到来 → 触发剪枝+ await broadcaster.recordCodexAccountUsageSnapshot({+ limitId: 'codex',+ primary: { usedPercent: 51, windowMinutes: 300, resetsAt: 4_100_000_000 },+ source: 'codex-app-server',+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex']);+ });++ it('never prunes the latest bucket even if its window looks expired', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot({+ limitId: 'codex',+ primary: { usedPercent: 51, windowMinutes: 300, resetsAt: 1_600_000_000 },+ source: 'codex-app-server',+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex']);+ });+});++describe('sparse rate-limit updates without a limitId', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.queryOne.mockReset().mockResolvedValue(null);+ mocks.exec.mockReset().mockResolvedValue(undefined);+ mocks.getCurrentUserId.mockReturnValue('user-1');+ });++ const SPARK = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: 4_100_000_000 },+ source: 'codex-app-server',+ };++ it('merges an id-less sparse update into the most recent bucket, not the default one', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot(SPARK);+ // app-server 契约: 稀疏更新缺 limitId 时合并进最近一次结果, 不得另建缺省桶+ await broadcaster.recordCodexAccountUsageSnapshot({+ primary: { usedPercent: 14, windowMinutes: 10_080, resetsAt: 4_100_000_000 },+ source: 'codex-app-server',+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['codex_bengalfox']);+ expect(payload?.appServerBuckets?.codex_bengalfox?.primary?.usedPercent).toBe(14);+ // 身份元数据不被稀疏更新清除+ expect(payload?.appServerBuckets?.codex_bengalfox?.limitName).toBe('GPT-5.3-Codex-Spark');+ });++ it('falls back to the default bucket when nothing has been observed yet', async () => {+ const broadcaster = await import('../usageBroadcaster');+ await broadcaster.recordCodexAccountUsageSnapshot({+ primary: { usedPercent: 9, windowMinutes: 300, resetsAt: 4_100_000_000 },+ source: 'codex-app-server',+ });++ const payload = await broadcaster.readCodexAccountUsageSnapshot();+ expect(Object.keys(payload?.appServerBuckets ?? {})).toEqual(['__default__']);+ });+});diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex b2d602accd..d82915bb7d 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -33,6 +33,12 @@ import {} from '../shared/claudeSubscriptionUsage';import type { AgentKind } from '@cindy/maker-core';+import {+ UNSAFE_BUCKET_KEYS,+ codexLimitBucketKey,+ isCodexBucketStale,+} from '@cindy/maker-shared/codex-usage-buckets';+import { createLogger } from './logger';import type { RegionalMoney } from '../shared/regionalMoney.js';@@ -291,17 +297,61 @@ export async function readAgentTodayUsage(agentKind: AgentKind): Promise<AgentTo// 「8天 剩余 100%」—— WHAM 的 Spark 桶窗口顶掉了 app-server 的主配额窗口)。// 分槽后各源只更新自己的槽, 消费方按会话形态选槽(CLI → 顶层, bridge →// webSnapshot), payload 形状对旧消费者(mobile 防御解析)加性兼容。+//+// **同源内还要按 limitId 再分桶**(2026-07-25 用户复报: 用 gpt-5.6-sol 的会话里+// chip 仍显示「8天 剩余 100%」, 持久化 app 槽是 codex_bengalfox /+// GPT-5.3-Codex-Spark 的 7 天窗口)。app-server 的 account/rateLimits/updated 每次+// 只推**一个**桶(带 limitId, 即该 turn 实际消耗的桶); 用过 Spark 类模型专属桶后,+// 它会覆盖主配额桶并挂在全局缓存上, 之后所有 Codex 会话的 chip 都读到它。+// 桶表按 limitId 隔离, 同桶才 merge。renderer 按**当前会话模型**匹配桶+// (limitName 命中模型 → 该桶; 否则通用桶, 由稳定桶键 'codex'/缺省桶识别;+// 都不匹配 → 不显示 app-server 配额, 绝不退到别的模型的桶)——+// **不能**用 account_usage 事件判会话归属: 它是账号级 fan-out, host 把同一条+// 广播给所有 subscriber 再各自包 sessionId(见 app-server host.routeNotification)。+// 详见 useAccountUsage.matchCodexBucketForModel。-/** 组合 payload: 顶层 = codex-app-server 槽(CLI 权威), webSnapshot = WHAM 槽。 */+/**+ * 组合 payload:+ * - 顶层 = app-server **最近更新的**桶(旧消费者与冷启动兜底, 形状不变);+ * - appServerBuckets = app-server 全部桶(按 limitId), renderer 据会话选桶;+ * - webSnapshot = WHAM 槽。+ * 后两者都是加性字段, 旧消费者(mobile 防御解析)忽略即退化为原行为。+ */export interface CodexAccountUsagePayload extends RateLimitSnapshot {webSnapshot?: RateLimitSnapshot | null;+ appServerBuckets?: Record<string, RateLimitSnapshot> | null;}let codexAccountUsageOwner: string | null = null;let codexAccountUsageLoaded = false;-let codexAppServerUsageSnapshot: RateLimitSnapshot | null = null;+/** app-server 桶表: limitId → 该桶最近快照(同桶 merge, 跨桶隔离)。 */+let codexAppServerBuckets: Record<string, RateLimitSnapshot> = {};+/** 最近更新的 app-server 桶键 —— 顶层兼容位取它。 */+let codexAppServerLatestBucketKey: string | null = null;let codexWebAccountUsageSnapshot: RateLimitSnapshot | null = null;+/**+ * 剪掉陈旧桶(保留最近更新桶本身, 它是顶层兼容位的来源)。桶表持久化且纯累加,+ * 不剪枝会让促销结束后的旧桶永远留着并被模型匹配选中(review 反馈)。+ */+function pruneStaleCodexBuckets(nowMs: number): void {+ const next: Record<string, RateLimitSnapshot> = {};+ for (const [key, bucket] of Object.entries(codexAppServerBuckets)) {+ if (key !== codexAppServerLatestBucketKey && isCodexBucketStale(bucket, nowMs)) continue;+ next[key] = bucket;+ }+ codexAppServerBuckets = next;+}++/** 当前 app-server 展示快照(最近更新桶);无桶 → null。 */+function currentCodexAppServerSnapshot(): RateLimitSnapshot | null {+ if (codexAppServerLatestBucketKey) {+ return codexAppServerBuckets[codexAppServerLatestBucketKey] ?? null;+ }+ const keys = Object.keys(codexAppServerBuckets);+ return keys.length > 0 ? codexAppServerBuckets[keys[keys.length - 1]] ?? null : null;+}+function currentAccountUsageOwner(): string | null {try {return getCurrentUserId();@@ -315,7 +365,8 @@ function resetCodexAccountUsageCacheIfOwnerChanged(): void {if (owner === codexAccountUsageOwner) return;codexAccountUsageOwner = owner;codexAccountUsageLoaded = false;- codexAppServerUsageSnapshot = null;+ codexAppServerBuckets = {};+ codexAppServerLatestBucketKey = null;codexWebAccountUsageSnapshot = null;}@@ -334,8 +385,11 @@ function hasCodexSnapshotContent(snapshot: RateLimitSnapshot | null | undefined)/** 两槽 → 组合 payload;两槽全空 → null。 */function buildCodexAccountUsagePayload(): CodexAccountUsagePayload | null {- const app = codexAppServerUsageSnapshot;+ const app = currentCodexAppServerSnapshot();const web = codexWebAccountUsageSnapshot;+ const buckets = Object.keys(codexAppServerBuckets).length > 0+ ? codexAppServerBuckets+ : null;if (!app && !web) return null;if (!app && web) {// web-only: 顶层无 CLI 数据, 但归属字段必须上浮 —— WHAM reader 用顶层@@ -345,7 +399,11 @@ function buildCodexAccountUsagePayload(): CodexAccountUsagePayload | null {// 不会据此伪造出 app 槽。return { accountId: web.accountId, updatedAt: web.updatedAt, webSnapshot: web };}- return { ...(app as RateLimitSnapshot), webSnapshot: web ?? null };+ return {+ ...(app as RateLimitSnapshot),+ webSnapshot: web ?? null,+ appServerBuckets: buckets,+ };}/**@@ -353,23 +411,60 @@ function buildCodexAccountUsagePayload(): CodexAccountUsagePayload | null {* 归入对应槽(旧行可能是被 WHAM 污染过的单槽杂交体, 归 web 槽即自然隔离)。*/export function splitPersistedCodexAccountUsage(parsed: Record<string, unknown>): {- appServer: RateLimitSnapshot | null;+ appServerBuckets: Record<string, RateLimitSnapshot>;+ /** 落库时的最近更新桶键(顶层兼容位派生);未知 → null。 */+ latestBucketKey: string | null;web: RateLimitSnapshot | null;} {if ('webSnapshot' in parsed) {- const { webSnapshot, ...rest } = parsed as CodexAccountUsagePayload;+ const { webSnapshot, appServerBuckets, ...rest } = parsed as CodexAccountUsagePayload;+ // 新格式带桶表 → 直接水合; 只有顶层(分桶前写入的行)→ 下面按其 limitId 归桶。+ const buckets = isPlainRecord(appServerBuckets)+ ? sanitizeCodexBuckets(appServerBuckets)+ : {};+ // 顶层兼容位记录的就是落库时的最近更新桶 —— 水合必须据此恢复, 否则+ // 「A→B→A」后重启会按对象键序错选 B(覆盖已有键不会移到末尾, review 反馈)。+ const latestBucketKey = hasCodexSnapshotContent(rest) ? codexLimitBucketKey(rest) : null;+ // 但这个键必须在桶表里真的存在。本仓写入路径两者恒一致(顶层就是从桶表取+ // 的), 外部/损坏/跨版本行却可能给出桶表里没有的键 —— 那样+ // currentCodexAppServerSnapshot() 直接返 null, app-server 配额会一直空到+ // 下一次推送(review 反馈)。顶层快照本身就是那个桶的内容, 补种回去即可。+ // codexLimitBucketKey 已把 __proto__ 等危险键映射成缺省桶, 补种不会污染原型。+ if (latestBucketKey && !Object.prototype.hasOwnProperty.call(buckets, latestBucketKey)) {+ buckets[latestBucketKey] = rest as RateLimitSnapshot;+ }return {- appServer: hasCodexSnapshotContent(rest) ? rest : null,+ appServerBuckets: buckets,+ latestBucketKey,// 拒绝数组等畸形持久化值(与 renderer 的 isRateLimitSnapshot 守卫同口径),// 否则损坏行会被当有效快照再次广播 + 回写。- web: webSnapshot && typeof webSnapshot === 'object' && !Array.isArray(webSnapshot)- ? webSnapshot- : null,+ web: isPlainRecord(webSnapshot) ? (webSnapshot as RateLimitSnapshot) : null,};}const legacy = parsed as RateLimitSnapshot;- if (legacy.source === 'openai-web') return { appServer: null, web: legacy };- return { appServer: hasCodexSnapshotContent(legacy) ? legacy : null, web: null };+ if (legacy.source === 'openai-web') {+ return { appServerBuckets: {}, latestBucketKey: null, web: legacy };+ }+ const hasContent = hasCodexSnapshotContent(legacy);+ return {+ appServerBuckets: hasContent ? { [codexLimitBucketKey(legacy)]: legacy } : {},+ latestBucketKey: hasContent ? codexLimitBucketKey(legacy) : null,+ web: null,+ };+}++function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++/** 桶表水合守卫: 丢掉非对象条目, 不让损坏行被当有效快照广播 / 回写。 */+function sanitizeCodexBuckets(raw: Record<string, unknown>): Record<string, RateLimitSnapshot> {+ const out: Record<string, RateLimitSnapshot> = {};+ for (const [key, value] of Object.entries(raw)) {+ if (UNSAFE_BUCKET_KEYS.has(key)) continue;+ if (isPlainRecord(value)) out[key] = value as RateLimitSnapshot;+ }+ return out;}function mergeCodexAccountUsageSnapshot(@@ -408,6 +503,9 @@ function mergeCodexAccountUsageSnapshot(planType: keepPreviousWebFields ? previous.planType : incoming.planType ?? previous.planType,credits,source: keepPreviousWebFields ? previous.source : incoming.source ?? 'codex-app-server',+ // 身份元数据不可被部分通知抹掉(limitName 丢失会让模型专属桶伪装成通用桶)。+ limitId: incoming.limitId ?? previous.limitId,+ limitName: incoming.limitName ?? previous.limitName,updatedAt: incoming.updatedAt ?? previous.updatedAt,accountId: incoming.accountId ?? previous.accountId,};@@ -453,7 +551,8 @@ async function ensureCodexAccountUsageLoaded(): Promise<void> {const parsed = JSON.parse(row.snapshot);if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {const slots = splitPersistedCodexAccountUsage(parsed as Record<string, unknown>);- codexAppServerUsageSnapshot = slots.appServer;+ codexAppServerBuckets = slots.appServerBuckets;+ codexAppServerLatestBucketKey = slots.latestBucketKey;codexWebAccountUsageSnapshot = slots.web;}} catch (err) {@@ -477,10 +576,28 @@ export async function recordCodexAccountUsageSnapshot(snapshot: unknown): Promisincoming,);} else {- codexAppServerUsageSnapshot = mergeCodexAccountUsageSnapshot(- codexAppServerUsageSnapshot,- incoming,- );+ // 同 limitId 桶内 merge(保留 windowless / 部分字段兜底语义), 跨桶隔离 ——+ // Spark 类模型专属桶不得覆盖主配额桶(见本节头注释)。+ //+ // account/rateLimits/updated 是**稀疏滚动更新**(app-server 0.144 契约原文:+ // "Clients should merge available values into the most recent+ // account/rateLimits/read response or refetch that snapshot. Nullable account+ // metadata may be unavailable in a rolling update and does not clear a+ // previously observed value.")。因此缺 limitId 时不能当作「缺省桶」新建 ——+ // 那会把模型专属窗口塞进通用桶、显示给所有会话(review 反馈)。按契约并入+ // 最近观察到的桶; 尚无任何桶时才落缺省桶(此时无歧义)。+ const bucketKey = incoming.limitId+ ? codexLimitBucketKey(incoming)+ : codexAppServerLatestBucketKey ?? codexLimitBucketKey(incoming);+ codexAppServerBuckets = {+ ...codexAppServerBuckets,+ [bucketKey]: mergeCodexAccountUsageSnapshot(+ codexAppServerBuckets[bucketKey] ?? null,+ incoming,+ ),+ };+ codexAppServerLatestBucketKey = bucketKey;+ pruneStaleCodexBuckets(Date.now());}const payload = buildCodexAccountUsagePayload();broadcastCodexAccountUsage(payload);@@ -505,7 +622,8 @@ export async function recordCodexAccountUsageSnapshot(snapshot: unknown): Promisexport async function clearCodexAccountUsageSnapshot(): Promise<void> {resetCodexAccountUsageCacheIfOwnerChanged();codexAccountUsageLoaded = true;- codexAppServerUsageSnapshot = null;+ codexAppServerBuckets = {};+ codexAppServerLatestBucketKey = null;codexWebAccountUsageSnapshot = null;broadcastCodexAccountUsage(null);diff --git a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.tsindex 3cc817521b..79a4354b32 100644--- a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts@@ -3,6 +3,11 @@ import { readFileSync } from 'node:fs';import { describe, expect, it } from 'vitest';import {+ CODEX_DEFAULT_LIMIT_BUCKET,+ codexLimitBucketKey,+ isCodexBucketStale,+ nextCodexBucketStaleAtMs,+ matchCodexBucketForModel,mergeCodexAccountUsageSnapshot,splitCodexAccountUsagePayload,} from '@/hooks/useAccountUsage';@@ -207,7 +212,7 @@ describe('mergeCodexAccountUsageSnapshot', () => {expect(preloadSource).toContain('onCodexAccountChanged: fanOutMakerUsageCodexAccount');expect(hookSource).toContain('api.onCodexAccountChanged');expect(hookSource).toContain('options: { clearOnNull?: boolean } = {}');- expect(hookSource).toContain('() => setSnapshot(selectCodexSlot(quotaSource))');+ expect(hookSource).toContain('selectCodexSlot(quotaSource');// 按来源分槽: 两个数据源不得互相覆盖(main / renderer 双份实现同口径)expect(mainSource).toContain('function splitPersistedCodexAccountUsage(');expect(mainSource).toContain("incoming.source === 'openai-web'");@@ -322,3 +327,233 @@ describe('module subscription install (behavior)', () => {}});});++describe('codex limit bucket isolation', () => {+ // 2026-07-25 用户实报: gpt-5.6-sol 会话的 chip 显示 codex_bengalfox /+ // GPT-5.3-Codex-Spark 桶的「8天 剩余 100%」。app-server 每次只推一个桶,+ // 不按 limitId 隔离就会串桶。+ const SPARK_BUCKET = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowMinutes: 10080, resetsAt: 1785548762 },+ source: 'codex-app-server',+ };+ const MAIN_BUCKET = {+ limitId: 'codex',+ primary: { usedPercent: 63, windowMinutes: 300, resetsAt: 1785440000 },+ secondary: { usedPercent: 41, windowMinutes: 10080, resetsAt: 1785900000 },+ source: 'codex-app-server',+ };++ it('derives a stable bucket key, defaulting when limitId is absent', () => {+ expect(codexLimitBucketKey(SPARK_BUCKET)).toBe('codex_bengalfox');+ expect(codexLimitBucketKey(MAIN_BUCKET)).toBe('codex');+ expect(codexLimitBucketKey({ primary: { usedPercent: 3 } })).toBe(CODEX_DEFAULT_LIMIT_BUCKET);+ expect(codexLimitBucketKey(null)).toBe(CODEX_DEFAULT_LIMIT_BUCKET);+ expect(codexLimitBucketKey({ limitId: '' })).toBe(CODEX_DEFAULT_LIMIT_BUCKET);+ });++ it('keeps a combined payload bucket table separate from the top-level slot', () => {+ const parts = splitCodexAccountUsagePayload({+ ...MAIN_BUCKET,+ appServerBuckets: {+ codex: MAIN_BUCKET,+ codex_bengalfox: SPARK_BUCKET,+ },+ webSnapshot: null,+ } as never);+ expect(parts.appServer?.limitId).toBe('codex');+ expect(Object.keys(parts.appServerBuckets ?? {}).sort()).toEqual(['codex', 'codex_bengalfox']);+ // Spark 桶原样保留在表里, 不与主桶合并成杂交体+ expect(parts.appServerBuckets?.codex_bengalfox?.primary?.usedPercent).toBe(0);+ expect(parts.appServerBuckets?.codex?.primary?.usedPercent).toBe(63);+ });++ it('drops malformed bucket entries instead of caching them', () => {+ const parts = splitCodexAccountUsagePayload({+ ...MAIN_BUCKET,+ appServerBuckets: { codex: MAIN_BUCKET, broken: [], alsoBroken: 'nope' },+ webSnapshot: null,+ } as never);+ const table = parts.appServerBuckets ?? {};+ expect(Object.keys(table)).toEqual(['codex']);+ // Object.keys 看不到原型污染 —— 显式断言注入值没经原型链泄漏出来。+ // sanitize 用 null 原型对象兜底, 顺带断言全局 Object.prototype 未被污染。+ expect((table as Record<string, unknown>).limitId).toBeUndefined();+ expect(Object.getPrototypeOf(table)).toBeNull();+ expect(({} as Record<string, unknown>).limitId).toBeUndefined();+ });+});++describe('matchCodexBucketForModel', () => {+ // 会话归属**不能**用 account_usage 事件判定(账号级 fan-out, 见 hook 注释),+ // 必须按当前会话模型匹配桶。+ const MAIN = { limitId: 'codex', primary: { usedPercent: 63 } };+ const SPARK = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0 },+ };+ const buckets = { codex: MAIN, codex_bengalfox: SPARK };++ it('matches a model-scoped bucket by its limitName', () => {+ expect(matchCodexBucketForModel(buckets, 'gpt-5.3-codex-spark')).toBe(SPARK);+ expect(matchCodexBucketForModel(buckets, 'GPT-5.3-Codex-Spark')).toBe(SPARK);+ });++ it('falls back to the generic bucket for unrelated models', () => {+ // 用户实报场景: gpt-5.6-sol 绝不能拿到 Spark 桶+ expect(matchCodexBucketForModel(buckets, 'gpt-5.6-sol')).toBe(MAIN);+ expect(matchCodexBucketForModel(buckets, 'gpt-5.4')).toBe(MAIN);+ expect(matchCodexBucketForModel(buckets, null)).toBe(MAIN);+ });++ it('returns null when no generic bucket exists (caller falls back)', () => {+ expect(matchCodexBucketForModel({ codex_bengalfox: SPARK }, 'gpt-5.6-sol')).toBeNull();+ expect(matchCodexBucketForModel({}, 'gpt-5.6-sol')).toBeNull();+ });+});++describe('bucket key safety and authoritative top-level slot', () => {+ it('never returns prototype-polluting bucket keys', () => {+ expect(codexLimitBucketKey({ limitId: '__proto__' })).toBe(CODEX_DEFAULT_LIMIT_BUCKET);+ expect(codexLimitBucketKey({ limitId: 'constructor' })).toBe(CODEX_DEFAULT_LIMIT_BUCKET);+ expect(codexLimitBucketKey({ limitId: 'prototype' })).toBe(CODEX_DEFAULT_LIMIT_BUCKET);+ });++ it('marks combined payloads authoritative so the top-level slot is replaced, not merged', () => {+ // 跨桶 merge 会造出「B 的 limitId + A 的窗口」杂交体(windowless 兜底保留旧窗口),+ // 冷启动会话回退顶层时显示错桶数据(review 反馈)。组合 payload 必须直接替换。+ const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');+ expect(hookSource).toContain("const isAuthoritative = 'appServerBuckets' in parts;");+ expect(hookSource).toContain('? parts.appServer');+ });++ it('drops prototype-polluting keys from a combined payload bucket table', () => {+ const parts = splitCodexAccountUsagePayload({+ limitId: 'codex',+ primary: { usedPercent: 5 },+ appServerBuckets: { codex: { limitId: 'codex' }, __proto__: { limitId: 'evil' } },+ webSnapshot: null,+ } as never);+ expect(Object.keys(parts.appServerBuckets ?? {})).toEqual(['codex']);+ });+});++describe('bucket selection safety (review follow-up)', () => {+ const SPARK = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: 4_100_000_000 },+ };+ const MAIN = {+ limitId: 'codex',+ primary: { usedPercent: 63, windowMinutes: 300, resetsAt: 4_100_000_000 },+ };+ const NOW = 1_785_000_000_000;++ it('returns null rather than a mismatched model bucket', () => {+ // 旧格式水合只有 Spark 桶时, gpt-5.6-sol 必须什么都不显示, 而不是显示 Spark+ expect(matchCodexBucketForModel({ codex_bengalfox: SPARK }, 'gpt-5.6-sol', NOW)).toBeNull();+ });++ it('identifies the generic bucket by its stable key, not by a missing limitName', () => {+ // 同桶 merge 遇到省略 limitName 的部分通知 → 名字丢了, 但它仍是 Spark 桶+ const namelessSpark = { ...SPARK, limitName: undefined };+ const buckets = { codex_bengalfox: namelessSpark, codex: MAIN };+ expect(matchCodexBucketForModel(buckets, 'gpt-5.6-sol', NOW)).toBe(MAIN);+ });++ it('skips stale buckets whose windows all expired long ago', () => {+ const expiredSpark = {+ ...SPARK,+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: 1_700_000_000 },+ };+ expect(isCodexBucketStale(expiredSpark, NOW)).toBe(true);+ expect(isCodexBucketStale(MAIN, NOW)).toBe(false);+ // 促销结束后的过期 Spark 桶不再被同名模型选中+ expect(matchCodexBucketForModel({ codex_bengalfox: expiredSpark }, 'gpt-5.3-codex-spark', NOW))+ .toBeNull();+ });++ it('does not treat window-less or reset-less buckets as stale', () => {+ const windowless = { limitId: 'codex' };+ const resetless = { limitId: 'codex', primary: { usedPercent: 5 } };+ expect(isCodexBucketStale(windowless, NOW)).toBe(false);+ expect(isCodexBucketStale(resetless, NOW)).toBe(false);+ // 只有部分窗口带 resetsAt 时不得判陈旧(review 反馈): 缺时间戳的周窗口可能仍有效+ const partialTimestamps = {+ limitId: 'codex_bengalfox',+ primary: { usedPercent: 100, resetsAt: 1_700_000_000 },+ secondary: { usedPercent: 40 },+ };+ expect(isCodexBucketStale(partialTimestamps, NOW)).toBe(false);+ });++ it('keeps identity metadata when a later partial snapshot omits it', () => {+ const merged = mergeCodexAccountUsageSnapshot(SPARK, {+ primary: { usedPercent: 12, windowMinutes: 10_080, resetsAt: 4_100_000_000 },+ });+ expect(merged.limitId).toBe('codex_bengalfox');+ expect(merged.limitName).toBe('GPT-5.3-Codex-Spark');+ });+});++describe('nextCodexBucketStaleAtMs', () => {+ const NOW = 1_785_000_000_000;+ const DAY_MS = 24 * 60 * 60 * 1000;+ const resetsAtSec = (offsetMs: number) => Math.floor((NOW + offsetMs) / 1000);++ it('returns the soonest upcoming stale moment (reset + 24h grace)', () => {+ const soon = { limitId: 'codex_bengalfox', primary: { usedPercent: 0, resetsAt: resetsAtSec(60_000) } };+ const later = { limitId: 'codex', primary: { usedPercent: 30, resetsAt: resetsAtSec(10 * 60_000) } };+ const staleAt = nextCodexBucketStaleAtMs({ a: soon, b: later }, NOW);+ expect(staleAt).toBe(resetsAtSec(60_000) * 1000 + DAY_MS);+ });++ it('ignores already-stale buckets and reset-less windows', () => {+ const alreadyStale = { limitId: 'x', primary: { usedPercent: 0, resetsAt: resetsAtSec(-3 * DAY_MS) } };+ const resetless = { limitId: 'y', primary: { usedPercent: 10 } };+ expect(nextCodexBucketStaleAtMs({ a: alreadyStale }, NOW)).toBeNull();+ expect(nextCodexBucketStaleAtMs({ b: resetless }, NOW)).toBeNull();+ expect(nextCodexBucketStaleAtMs({}, NOW)).toBeNull();+ });++ it('skips buckets where only some windows carry a timestamp', () => {+ // 与 isCodexBucketStale 同口径: 这类桶永不进入陈旧, 不需要定时重选+ const partial = {+ limitId: 'z',+ primary: { usedPercent: 10, resetsAt: resetsAtSec(60_000) },+ secondary: { usedPercent: 20 },+ };+ expect(nextCodexBucketStaleAtMs({ z: partial }, NOW)).toBeNull();+ });+});++describe('bucket table keeps a null prototype across incremental updates', () => {+ it('never re-attaches Object.prototype when merging a turn event bucket', () => {+ // sanitize 建立 null 原型后, 增量写入若用对象字面量 spread 会把原型换回来,+ // 削弱防御(review 反馈)。这里用源码断言锁定实现选择。+ const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');+ expect(hookSource).toContain('function emptyBucketTable(');+ expect(hookSource).toContain('function withCodexBucket(');+ // 增量分支不得再出现桶表字面量 spread+ expect(hookSource).not.toContain('...lastCodexAccountUsage.appServerBuckets,');+ expect(hookSource).not.toContain('appServerBuckets: {}');+ });+});++describe('renderer sparse update bucket routing', () => {+ it('routes id-less sparse updates to the latest bucket, mirroring main', () => {+ // main 侧已按 app-server 契约把缺 limitId 的稀疏更新并入最近观察到的桶;+ // renderer 增量路径若仍按缺省桶归类, 模型专属窗口会被当通用桶暴露给其它+ // 会话(review 反馈)。这里锁定实现选择。+ const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');+ expect(hookSource).toContain('let lastCodexAppServerBucketKey: string | null = null;');+ expect(hookSource).toContain('function resolveIncrementalBucketKey(');+ expect(hookSource).toContain('return lastCodexAppServerBucketKey ?? codexLimitBucketKey(incoming);');+ // 增量分支必须走 resolveIncrementalBucketKey, 不能直接用 codexLimitBucketKey+ expect(hookSource).toContain('resolveIncrementalBucketKey(parts.appServer),');+ expect(hookSource).not.toContain('codexLimitBucketKey(parts.appServer),\n parts.appServer,');+ });+});diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 6aa52dba49..673ea71900 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -1054,6 +1054,9 @@ export function TodaySpendChip({sessionId,shouldReadLocalCodexAccountUsage ? 'codex' : undefined,isChatgptBridge ? 'openai-web' : 'app-server',+ // app-server 形态下据当前模型匹配限额桶(账号可能同时有主配额桶与模型专属+ // 促销桶, 见 useAccountUsage.matchCodexBucketForModel)。+ modelId,);// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession);diff --git a/apps/desktop/src/renderer/hooks/useAccountUsage.ts b/apps/desktop/src/renderer/hooks/useAccountUsage.tsindex 84985758e5..dfdd123b9f 100644--- a/apps/desktop/src/renderer/hooks/useAccountUsage.ts+++ b/apps/desktop/src/renderer/hooks/useAccountUsage.ts@@ -26,7 +26,24 @@* useSessionSpend 同惯例 (它也 inline { sessionId, totalCostUsd })。*/-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';++import {+ CODEX_DEFAULT_LIMIT_BUCKET,+ UNSAFE_BUCKET_KEYS,+ codexLimitBucketKey,+ isCodexBucketStale,+ matchCodexBucketForModel,+ nextCodexBucketStaleAtMs,+} from '@cindy/maker-shared/codex-usage-buckets';++export {+ CODEX_DEFAULT_LIMIT_BUCKET,+ codexLimitBucketKey,+ isCodexBucketStale,+ matchCodexBucketForModel,+ nextCodexBucketStaleAtMs,+};export interface RateLimitWindow {usedPercent: number;@@ -59,16 +76,59 @@ export interface RateLimitSnapshot {export type CodexQuotaSource = 'app-server' | 'openai-web';interface CodexAccountUsageSlots {+ /** app-server 展示快照 = 最近更新的桶(冷启动 / 未知会话桶时的兜底)。 */appServer: RateLimitSnapshot | null;+ /** app-server 桶表: limitId → 快照。跨桶隔离, 见 main usageBroadcaster 头注释。 */+ appServerBuckets: Record<string, RateLimitSnapshot>;web: RateLimitSnapshot | null;}-let lastCodexAccountUsage: CodexAccountUsageSlots = { appServer: null, web: null };+let lastCodexAccountUsage: CodexAccountUsageSlots = {+ appServer: null,+ appServerBuckets: Object.create(null) as Record<string, RateLimitSnapshot>,+ web: null,+};++/**+ * 最近观察到的 app-server 桶键 —— 稀疏更新缺 limitId 时并入它(与 main 的+ * codexAppServerLatestBucketKey 同口径)。account/rateLimits/updated 契约:+ * "merge available values into the most recent read response"; 直接按缺省桶+ * 归类会把模型专属窗口暴露成通用桶(review 反馈)。+ */+let lastCodexAppServerBucketKey: string | null = null;-function selectCodexSlot(quotaSource: CodexQuotaSource): RateLimitSnapshot | null {- return quotaSource === 'openai-web'- ? lastCodexAccountUsage.web- : lastCodexAccountUsage.appServer;+/**+ * 桶表代号 —— app-server 桶表每次被替换时 +1, 供陈旧重选定时器判断「该重算下+ * 一个到期时刻了」。不能拿 snapshot 当这个信号: 变化的桶不是当前选中桶时+ * snapshot 不变(漏重算), 反过来 snapshot 变了也不必然意味着桶表变了(白重排+ * 定时器, review 反馈)。+ */+let codexBucketTableGeneration = 0;++/** 稀疏更新的落桶键: 带 limitId 用它自己的桶; 缺失则并入最近观察到的桶。 */+function resolveIncrementalBucketKey(incoming: RateLimitSnapshot): string {+ if (incoming.limitId) return codexLimitBucketKey(incoming);+ return lastCodexAppServerBucketKey ?? codexLimitBucketKey(incoming);+}++/**+ * 选槽 + 选桶。app-server 形态下按**当前会话模型**匹配桶(见+ * matchCodexBucketForModel): 账号可能同时有主配额桶与模型专属促销桶+ * (codex_bengalfox / GPT-5.3-Codex-Spark), 不选桶就会显示别的模型的配额+ * (2026-07-25 用户实报: gpt-5.6-sol 会话显示 Spark 桶的「8天 剩余 100%」)。+ * 匹配不到 → 不显示 app-server 配额(见函数体注释); 仅桶表为空时用顶层兼容位。+ */+function selectCodexSlot(+ quotaSource: CodexQuotaSource,+ modelId?: string | null,+): RateLimitSnapshot | null {+ if (quotaSource === 'openai-web') return lastCodexAccountUsage.web;+ const buckets = lastCodexAccountUsage.appServerBuckets;+ // 桶表已建立: 选桶结果就是最终答案 —— 匹配不到宁可不显示 app-server 配额,+ // 也不回退顶层兼容位(它可能正是别的模型的桶, review 反馈)。+ if (Object.keys(buckets).length > 0) return matchCodexBucketForModel(buckets, modelId);+ // 桶表为空(旧 main / 尚无 app-server 数据): 保持旧行为用顶层兼容位。+ return lastCodexAccountUsage.appServer;}function readUsageApi(): {@@ -91,6 +151,44 @@ function isRateLimitSnapshot(value: unknown): value is RateLimitSnapshot {return Boolean(value) && typeof value === 'object' && !Array.isArray(value);}+function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++/**+ * 桶表守卫: 丢掉非对象条目与原型污染键(畸形 payload 不得进缓存, 与 main+ * sanitize 同口径)。用 null 原型对象兜底 —— 即便上游再加键也碰不到 Object.prototype。+ */+function sanitizeCodexBuckets(raw: Record<string, unknown>): Record<string, RateLimitSnapshot> {+ const out: Record<string, RateLimitSnapshot> = Object.create(null);+ for (const [key, value] of Object.entries(raw)) {+ if (UNSAFE_BUCKET_KEYS.has(key)) continue;+ if (isRateLimitSnapshot(value)) out[key] = value;+ }+ return out;+}+++/** 空桶表 —— 与 sanitize 同为 null 原型, 保持「桶表永不挂原型链」的不变量。 */+function emptyBucketTable(): Record<string, RateLimitSnapshot> {+ return Object.create(null) as Record<string, RateLimitSnapshot>;+}++/**+ * 增量写入一个桶并返回**新的 null 原型**桶表。不能用对象字面量 spread ——+ * 那会把 sanitize 建立的 null 原型换回 Object.prototype(review 反馈)。+ */+function withCodexBucket(+ buckets: Record<string, RateLimitSnapshot>,+ key: string,+ incoming: RateLimitSnapshot,+): Record<string, RateLimitSnapshot> {+ const next = emptyBucketTable();+ for (const [existingKey, bucket] of Object.entries(buckets)) next[existingKey] = bucket;+ next[key] = mergeCodexAccountUsageSnapshot(buckets[key] ?? null, incoming);+ return next;+}+export function mergeCodexAccountUsageSnapshot(previous: RateLimitSnapshot | null,incoming: RateLimitSnapshot,@@ -127,6 +225,10 @@ export function mergeCodexAccountUsageSnapshot(planType: keepPreviousWebFields ? previous.planType : incoming.planType ?? previous.planType,credits,source: keepPreviousWebFields ? previous.source : incoming.source ?? 'codex-app-server',+ // 身份元数据不可被部分通知抹掉 —— limitName 丢失会让模型专属桶伪装成通用桶+ // (通用桶判定虽已改用桶键, 但 label / 模型匹配仍依赖它; review 反馈)。+ limitId: incoming.limitId ?? previous.limitId,+ limitName: incoming.limitName ?? previous.limitName,updatedAt: incoming.updatedAt ?? previous.updatedAt,accountId: incoming.accountId ?? previous.accountId,};@@ -181,14 +283,20 @@ function hasCodexSnapshotContent(snapshot: RateLimitSnapshot | null | undefined)*/export function splitCodexAccountUsagePayload(incoming: RateLimitSnapshot): {appServer?: RateLimitSnapshot | null;+ appServerBuckets?: Record<string, RateLimitSnapshot> | null;web?: RateLimitSnapshot | null;} {if ('webSnapshot' in incoming) {- const { webSnapshot, ...rest } = incoming as RateLimitSnapshot & {+ const { webSnapshot, appServerBuckets, ...rest } = incoming as RateLimitSnapshot & {webSnapshot?: unknown;+ appServerBuckets?: unknown;};return {appServer: hasCodexSnapshotContent(rest) ? rest : null,+ // 桶表随组合 payload 全量下发; 缺失(旧 main / 无 app 数据)→ 显式清空。+ appServerBuckets: isPlainRecord(appServerBuckets)+ ? sanitizeCodexBuckets(appServerBuckets)+ : null,web: isRateLimitSnapshot(webSnapshot) ? webSnapshot : null,};}@@ -203,7 +311,9 @@ function applyCodexAccountUsageSnapshot(): void {if (incoming === null) {if (options.clearOnNull === false) return;- lastCodexAccountUsage = { appServer: null, web: null };+ lastCodexAccountUsage = { appServer: null, appServerBuckets: emptyBucketTable(), web: null };+ lastCodexAppServerBucketKey = null;+ codexBucketTableGeneration += 1;onApplied();return;}@@ -212,12 +322,39 @@ function applyCodexAccountUsageSnapshot(// 键存在即生效: 快照 → 槽内 merge; null → 显式清空(组合 payload 是权威全量,// 见 splitCodexAccountUsagePayload); 键缺失 → 保留现值(裸快照只带自己的槽)。if ('appServer' in parts) {+ if ('appServerBuckets' in parts) {+ // 权威全量: 顶层兼容位就是 main 记录的最近更新桶。+ lastCodexAppServerBucketKey = parts.appServer+ ? codexLimitBucketKey(parts.appServer)+ : null;+ } else if (parts.appServer) {+ lastCodexAppServerBucketKey = resolveIncrementalBucketKey(parts.appServer);+ }+ // 组合 payload 是 main 的权威全量: 顶层直接替换。跨桶 merge 会造出+ // 「B 的 limitId + A 的窗口」杂交体(windowless 兜底会保留旧窗口),+ // 冷启动会话回退顶层时就显示错桶数据(review 反馈)。+ const isAuthoritative = 'appServerBuckets' in parts;+ const nextAppServer = parts.appServer+ ? isAuthoritative+ ? parts.appServer+ : mergeCodexAccountUsageSnapshot(lastCodexAccountUsage.appServer, parts.appServer)+ : null;lastCodexAccountUsage = {...lastCodexAccountUsage,- appServer: parts.appServer- ? mergeCodexAccountUsageSnapshot(lastCodexAccountUsage.appServer, parts.appServer)- : null,+ appServer: nextAppServer,+ // 桶表: 组合 payload 带全量 → 覆盖; 裸 turn 事件 → 只更新自己那个桶+ // (同桶 merge, 跨桶隔离, 与 main 同口径)。+ appServerBuckets: 'appServerBuckets' in parts+ ? parts.appServerBuckets ?? emptyBucketTable()+ : parts.appServer+ ? withCodexBucket(+ lastCodexAccountUsage.appServerBuckets,+ resolveIncrementalBucketKey(parts.appServer),+ parts.appServer,+ )+ : emptyBucketTable(),};+ codexBucketTableGeneration += 1;}if ('web' in parts) {lastCodexAccountUsage = {@@ -263,20 +400,52 @@ export function useAccountUsage(sessionId: string | undefined,vendorKey: 'cc' | 'codex' | undefined,quotaSource: CodexQuotaSource = 'app-server',+ /** 当前会话模型 —— app-server 形态下据它匹配限额桶(见 matchCodexBucketForModel)。 */+ modelId?: string | null,): RateLimitSnapshot | null {// 幂等; 首个 codex 实例装上 module 常驻订阅, 保证之后卸载窗口内的广播(尤其// 换号清空)不丢。非 codex 会话不装 —— 从没有 codex chip 消费过就没有可残留// 的缓存, 常驻监听纯属白耗(review 反馈)。if (vendorKey === 'codex') ensureModuleSubscription();const [snapshot, setSnapshot] = useState<RateLimitSnapshot | null>(() =>- vendorKey === 'codex' ? selectCodexSlot(quotaSource) : null,+ vendorKey === 'codex' ? selectCodexSlot(quotaSource, modelId) : null,);+ // 订阅 effect 不把 modelId 放进依赖(切模型不该重装 IPC 订阅, 重装窗口还会漏+ // push);回调经 ref 读最新模型。模型变化时由下方 reselect effect 立即重选。+ const modelIdRef = useRef(modelId);+ modelIdRef.current = modelId;+ // 桶表代号进 state 才能当定时器依赖; 桶表没变时 setState 同值被 React bail+ // out, 不会多一次渲染。+ const [bucketGeneration, setBucketGeneration] = useState(codexBucketTableGeneration);+ const reselect = useCallback(() => {+ setSnapshot(selectCodexSlot(quotaSource, modelIdRef.current));+ setBucketGeneration(codexBucketTableGeneration);+ }, [quotaSource]);++ // Codex rate limits 是账号级数据, 不是 session 级数据。切回 Codex session /+ // 切模型时按新模型重新选桶(桶表已在缓存里, 无需等下一次 push)。+ useEffect(() => {+ setSnapshot(vendorKey === 'codex' ? selectCodexSlot(quotaSource, modelId) : null);+ }, [sessionId, vendorKey, quotaSource, modelId]);- // Codex rate limits 是账号级数据, 不是 session 级数据。切回 Codex session 时- // 直接复用最近一次快照, 等 host replay/下一次 push 再覆盖。+ // 陈旧转变是纯时间驱动的: 没有新 payload 时也要在到点那一刻重选一次, 否则+ // 常驻挂载的 chip 会一直显示已过期的促销桶(review 反馈)。+ const [staleTick, setStaleTick] = useState(0);useEffect(() => {- setSnapshot(vendorKey === 'codex' ? selectCodexSlot(quotaSource) : null);- }, [sessionId, vendorKey, quotaSource]);+ if (vendorKey !== 'codex' || quotaSource !== 'app-server') return undefined;+ const now = Date.now();+ const staleAt = nextCodexBucketStaleAtMs(lastCodexAccountUsage.appServerBuckets, now);+ if (staleAt === null) return undefined;+ // setTimeout 上限 ~24.8 天, 超出就分段等待(到期再重算)。+ const delay = Math.min(Math.max(staleAt - now, 0) + 1_000, 6 * 60 * 60 * 1000);+ const timer = window.setTimeout(() => {+ reselect();+ setStaleTick((tick) => tick + 1);+ }, delay);+ return () => window.clearTimeout(timer);+ // bucketGeneration: 桶表变了要重算到期时刻; staleTick: 本次到点后要接着排+ // 下一个桶的到期时刻(纯时间驱动, 期间没有新 payload)。+ }, [vendorKey, quotaSource, reselect, bucketGeneration, staleTick]);useEffect(() => {if (vendorKey !== 'codex') return;@@ -290,7 +459,7 @@ export function useAccountUsage(if (cancelled) return;applyCodexAccountUsageSnapshot(persisted,- () => setSnapshot(selectCodexSlot(quotaSource)),+ reselect,{ clearOnNull: false },);})@@ -301,7 +470,7 @@ export function useAccountUsage(return () => {cancelled = true;};- }, [vendorKey, quotaSource]);+ }, [vendorKey, quotaSource, reselect]);useEffect(() => {if (vendorKey !== 'codex') return;@@ -311,13 +480,13 @@ export function useAccountUsage(let cancelled = false;const unsubscribe = api.onCodexAccountChanged((payload: unknown) => {if (cancelled) return;- applyCodexAccountUsageSnapshot(payload, () => setSnapshot(selectCodexSlot(quotaSource)));+ applyCodexAccountUsageSnapshot(payload, reselect);});return () => {cancelled = true;unsubscribe();};- }, [vendorKey, quotaSource]);+ }, [vendorKey, quotaSource, reselect]);useEffect(() => {if (vendorKey !== 'codex' || !sessionId) return;@@ -344,16 +513,15 @@ 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(selectCodexSlot(quotaSource)),- );+ // 只更新桶表(事件带 limitId, 进它自己的桶); **不**据此判会话归属 ——+ // 这是账号级 fan-out 事件(见 matchCodexBucketForModel 注释)。+ applyCodexAccountUsageSnapshot(payload.event.data, reselect);});return () => {cancelled = true;unsubscribe();};- }, [sessionId, vendorKey, quotaSource]);+ }, [sessionId, vendorKey, quotaSource, reselect]);return snapshot;}diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsxindex c0ffd15f2e..330d79ea4c 100644--- a/apps/mobile/src/session/SessionMenuSheet.tsx+++ b/apps/mobile/src/session/SessionMenuSheet.tsx@@ -47,6 +47,11 @@ import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-linimport { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';import { writeClipboardText } from '@/session/messageActions';import { normalizeExtraDirs } from '@/session/newSession';+import {+ nextCodexBucketStaleAtMs,+ resolveCodexBucketTable,+ selectCodexUsageForModel,+} from '@cindy/maker-shared/codex-usage-buckets';import {summarizeAccountRateLimits,summarizeCodexRateLimitReset,@@ -411,10 +416,41 @@ export function SessionMenuSheet({const spend = summarizeSessionSpend(session);const usage = summarizeContextUsage(contextUsage);// 账号限额行:窗口构成完全跟随被控端上游接口返回(不假设 5h/周),解析不出内容 → null 不渲染。- const accountLimits = useMemo(- () => summarizeAccountRateLimits(accountUsage, Date.now()),- [accountUsage],- );+ // 陈旧判定依赖当前时间: 重开面板要重算, 面板长开跨过失效时刻也要重算+ // (与 desktop 的定时重选同口径; review 反馈)。+ const [quotaStaleTick, setQuotaStaleTick] = useState(0);+ const quotaBucketTables = useMemo(() => ({+ byLimitId: codexRateLimits?.rateLimitsByLimitId,+ appServerBuckets: (accountUsage as { appServerBuckets?: unknown } | null)?.appServerBuckets,+ }), [accountUsage, codexRateLimits]);+ useEffect(() => {+ if (!visible) return undefined;+ const now = Date.now();+ // 与选桶共用同一套桶表解析(空表也要回退, 不能用 ?? —— review 反馈)。+ const staleAt = nextCodexBucketStaleAtMs(resolveCodexBucketTable(quotaBucketTables), now);+ if (staleAt === null) return undefined;+ const timer = setTimeout(+ () => setQuotaStaleTick((tick) => tick + 1),+ Math.min(Math.max(staleAt - now, 0) + 1_000, 6 * 60 * 60 * 1000),+ );+ return () => clearTimeout(timer);+ }, [visible, quotaBucketTables, quotaStaleTick]);++ const accountLimits = useMemo(() => {+ const now = Date.now();+ // 账号可能同时有主配额桶与模型专属促销桶(如 GPT-5.3-Codex-Spark), 上游每次+ // 只报一个桶 —— 必须按**本会话模型**选桶, 否则会显示别的模型的额度+ // (desktop 同源问题见 useAccountUsage.matchCodexBucketForModel)。+ const scoped = selectCodexUsageForModel({+ fallback: accountUsage,+ byLimitId: quotaBucketTables.byLimitId,+ appServerBuckets: quotaBucketTables.appServerBuckets,+ modelId: session.model,+ nowMs: now,+ });+ return summarizeAccountRateLimits(scoped, now);+ // visible / quotaStaleTick 进依赖: 重开与到点失效都要按当前时间重选。+ }, [accountUsage, quotaBucketTables, session.model, visible, quotaStaleTick]);const resetSummary = useMemo(() => summarizeCodexRateLimitReset(codexRateLimits, Date.now()),[codexRateLimits],diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 1fd9267d1f..d5bcf6b01b 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -54,7 +54,8 @@"./system-card": "./src/systemCard.ts","./thinking-text": "./src/thinkingText.ts","./tool-use-descriptor": "./src/toolUseDescriptor.ts",- "./work-activity-projection": "./src/workActivityProjection.ts"+ "./work-activity-projection": "./src/workActivityProjection.ts",+ "./codex-usage-buckets": "./src/codexUsageBuckets.ts"},"scripts": {"build": "tsc --noEmit",diff --git a/packages/maker-shared/src/__tests__/sessionControls.test.ts b/packages/maker-shared/src/__tests__/sessionControls.test.tsindex 21e1509e6b..2c689670e6 100644--- a/packages/maker-shared/src/__tests__/sessionControls.test.ts+++ b/packages/maker-shared/src/__tests__/sessionControls.test.ts@@ -1,4 +1,9 @@import { describe, expect, it } from 'vitest';+import {+ nextCodexBucketStaleAtMs,+ resolveCodexBucketTable,+ selectCodexUsageForModel,+} from '../codexUsageBuckets';import {summarizeAccountRateLimits,summarizeCodexRateLimitReset,@@ -175,3 +180,164 @@ describe('summarizeAccountRateLimits', () => {expect(summarizeAccountRateLimits({ primary: { windowMinutes: 300 } }, NOW_MS)).toBeNull();});});++describe('selectCodexUsageForModel (per-model bucket selection)', () => {+ // 与 desktop 同源的问题: 账号同时有主配额桶与模型专属促销桶时, 手机端的+ // 用量详情不能显示别的模型的桶(PR #379 / issue #382)。+ const NOW = 1_785_000_000_000;+ const future = Math.floor((NOW + 3 * 24 * 60 * 60 * 1000) / 1000);+ const MAIN = { limitId: 'codex', primary: { usedPercent: 63, resetsAt: future } };+ const SPARK = {+ limitId: 'codex_bengalfox',+ limitName: 'GPT-5.3-Codex-Spark',+ primary: { usedPercent: 0, windowMinutes: 10_080, resetsAt: future },+ };++ it('picks the generic bucket for an unrelated model', () => {+ const picked = selectCodexUsageForModel({+ fallback: SPARK,+ byLimitId: { codex: MAIN, codex_bengalfox: SPARK },+ modelId: 'gpt-5.6-sol',+ nowMs: NOW,+ });+ expect(picked).toBe(MAIN);+ });++ it('picks the model-scoped bucket when the model matches', () => {+ const picked = selectCodexUsageForModel({+ fallback: MAIN,+ byLimitId: { codex: MAIN, codex_bengalfox: SPARK },+ modelId: 'gpt-5.3-codex-spark',+ nowMs: NOW,+ });+ expect(picked).toBe(SPARK);+ });++ it('falls back to appServerBuckets when the authoritative table is absent', () => {+ const picked = selectCodexUsageForModel({+ fallback: SPARK,+ byLimitId: null,+ appServerBuckets: { codex: MAIN, codex_bengalfox: SPARK },+ modelId: 'gpt-5.6-sol',+ nowMs: NOW,+ });+ expect(picked).toBe(MAIN);+ });++ it('returns null instead of another model bucket when nothing matches', () => {+ const picked = selectCodexUsageForModel({+ fallback: SPARK,+ byLimitId: { codex_bengalfox: SPARK },+ modelId: 'gpt-5.6-sol',+ nowMs: NOW,+ });+ expect(picked).toBeNull();+ });++ it('keeps the legacy top-level snapshot when no bucket table is available', () => {+ const picked = selectCodexUsageForModel({+ fallback: MAIN,+ modelId: 'gpt-5.6-sol',+ nowMs: NOW,+ });+ expect(picked).toBe(MAIN);+ });+});++describe('generic bucket alias priority', () => {+ const NOW = 1_785_000_000_000;+ const future = Math.floor((NOW + 3 * 24 * 60 * 60 * 1000) / 1000);++ it('prefers the explicit codex bucket over the legacy __default__ alias', () => {+ // 旧快照没带 limitId → 落到 __default__; 之后真正的 codex 通知新建第二个通用桶。+ // 按插入序查找会一直返回旧的缺省桶(review 反馈)。+ const legacyDefault = { primary: { usedPercent: 5, resetsAt: future } };+ const currentCodex = { limitId: 'codex', primary: { usedPercent: 71, resetsAt: future } };+ const picked = selectCodexUsageForModel({+ byLimitId: { __default__: legacyDefault, codex: currentCodex },+ modelId: 'gpt-5.6-sol',+ nowMs: NOW,+ });+ expect(picked).toBe(currentCodex);+ });++ it('still uses the default alias when no explicit codex bucket exists', () => {+ const legacyDefault = { primary: { usedPercent: 5, resetsAt: future } };+ const picked = selectCodexUsageForModel({+ byLimitId: { __default__: legacyDefault },+ modelId: 'gpt-5.6-sol',+ nowMs: NOW,+ });+ expect(picked).toBe(legacyDefault);+ });++ it('computes the next stale moment from an unknown-shaped bucket table', () => {+ const table = { codex: { limitId: 'codex', primary: { usedPercent: 10, resetsAt: future } } };+ expect(nextCodexBucketStaleAtMs(table, NOW)).toBe(future * 1000 + 24 * 60 * 60 * 1000);+ expect(nextCodexBucketStaleAtMs(null, NOW)).toBeNull();+ expect(nextCodexBucketStaleAtMs({}, NOW)).toBeNull();+ });+});++describe('overlapping bucket names', () => {+ const NOW = 1_785_000_000_000;+ const future = Math.floor((NOW + 3 * 24 * 60 * 60 * 1000) / 1000);+ const BASE = { limitId: 'codex_base', limitName: 'GPT-5.3-Codex', primary: { usedPercent: 20, resetsAt: future } };+ const SPARK = { limitId: 'codex_bengalfox', limitName: 'GPT-5.3-Codex-Spark', primary: { usedPercent: 0, resetsAt: future } };++ it('prefers the longest matching bucket name over insertion order', () => {+ // 'GPT-5.3-Codex' 先插入时不得抢走 Spark 会话(review 反馈)+ const picked = selectCodexUsageForModel({+ byLimitId: { codex_base: BASE, codex_bengalfox: SPARK },+ modelId: 'gpt-5.3-codex-spark',+ nowMs: NOW,+ });+ expect(picked).toBe(SPARK);+ });++ it('prefers an exact name match even when a longer name also matches', () => {+ const picked = selectCodexUsageForModel({+ byLimitId: { codex_bengalfox: SPARK, codex_base: BASE },+ modelId: 'gpt-5.3-codex',+ nowMs: NOW,+ });+ expect(picked).toBe(BASE);+ });++ it('does not let a broad name capture unrelated specialized models', () => {+ const broad = { limitId: 'codex_broad', limitName: 'Codex', primary: { usedPercent: 12, resetsAt: future } };+ const picked = selectCodexUsageForModel({+ byLimitId: { codex_broad: broad, codex_bengalfox: SPARK },+ modelId: 'gpt-5.3-codex-spark',+ nowMs: NOW,+ });+ expect(picked).toBe(SPARK);+ });+});++describe('resolveCodexBucketTable (selector / timer must agree)', () => {+ const NOW = 1_785_000_000_000;+ const future = Math.floor((NOW + 3 * 24 * 60 * 60 * 1000) / 1000);+ const MAIN = { limitId: 'codex', primary: { usedPercent: 40, resetsAt: future } };++ it('falls back past an empty authoritative table (not just null/undefined)', () => {+ // `a ?? b` 会把 {} 当有效表 —— 选桶与定时器就此漂移(review 反馈)+ const table = resolveCodexBucketTable({ byLimitId: {}, appServerBuckets: { codex: MAIN } });+ expect(table).not.toBeNull();+ expect(Object.keys(table ?? {})).toEqual(['codex']);+ });++ it('keeps selector and expiry timer consistent for an empty authoritative table', () => {+ const input = { byLimitId: {}, appServerBuckets: { codex: MAIN } };+ const picked = selectCodexUsageForModel({ ...input, modelId: 'gpt-5.6-sol', nowMs: NOW });+ const staleAt = nextCodexBucketStaleAtMs(resolveCodexBucketTable(input), NOW);+ expect(picked).toBe(MAIN);+ expect(staleAt).toBe(future * 1000 + 24 * 60 * 60 * 1000);+ });++ it('returns null when neither table is usable', () => {+ expect(resolveCodexBucketTable({ byLimitId: {}, appServerBuckets: {} })).toBeNull();+ expect(resolveCodexBucketTable({ byLimitId: null, appServerBuckets: undefined })).toBeNull();+ expect(resolveCodexBucketTable({ byLimitId: [], appServerBuckets: 'nope' })).toBeNull();+ });+});diff --git a/packages/maker-shared/src/codexUsageBuckets.ts b/packages/maker-shared/src/codexUsageBuckets.tsnew file mode 100644index 0000000000..5f2b120883--- /dev/null+++ b/packages/maker-shared/src/codexUsageBuckets.ts@@ -0,0 +1,223 @@+/**+ * codexUsageBuckets — Codex 账号限额「桶」的共享语义(main 与 renderer 共用一份)。+ *+ * 账号可能同时存在多个限额桶: 主配额桶与模型专属促销桶(如 codex_bengalfox /+ * GPT-5.3-Codex-Spark)。app-server 的 account/rateLimits/updated 每次只推**一个**+ * 桶(带 limitId), 因此存储必须按 limitId 隔离, 展示必须按当前会话模型选桶。+ *+ * 这里放各端必须**同口径**的判定与常量 —— 多份实现会漂移(review 实例: 陈旧+ * 宽限一侧 1h 一侧 24h, 导致 main 仍保留而 renderer 已隐藏)。+ * desktop(main / renderer)与 mobile 会话用量详情共用本模块。+ */++/** 桶表的缺省键: 快照没带 limitId 时用它(单桶账号 / 老 app-server)。 */+export const CODEX_DEFAULT_LIMIT_BUCKET = '__default__';++/** 用作对象键会污染原型链的保留名 —— 一律回退缺省桶 / 丢弃。 */+export const UNSAFE_BUCKET_KEYS: ReadonlySet<string> = new Set([+ '__proto__',+ 'constructor',+ 'prototype',+]);++/**+ * 通用(非模型专属)桶的稳定标识 —— 只认桶键, 不看易在部分通知里丢失的 limitName。+ * **按优先级排列**: 显式 'codex' 优先于缺省桶别名 —— 旧快照没带 limitId 时会+ * 落到 '__default__', 之后真正的 'codex' 通知会新建第二个通用桶; 按插入序查找+ * 会一直命中旧的缺省桶并显示陈旧百分比(review 反馈)。+ */+export const GENERIC_BUCKET_KEYS_BY_PRIORITY: readonly string[] = [+ 'codex',+ CODEX_DEFAULT_LIMIT_BUCKET,+];++/** 集合形式(成员判定用);优先级查找请用 GENERIC_BUCKET_KEYS_BY_PRIORITY。 */+export const GENERIC_BUCKET_KEYS: ReadonlySet<string> = new Set(GENERIC_BUCKET_KEYS_BY_PRIORITY);++/**+ * 陈旧桶宽限: 窗口全部过点超过它, 视为服务端已停推该 limitId(促销结束等)。+ * main(记录时剪枝)与 renderer(选桶时跳过)必须用同一个值, 否则会出现+ * 「main 保留但 renderer 隐藏」的空窗。+ */+export const STALE_BUCKET_GRACE_MS = 24 * 60 * 60 * 1000;++/**+ * 判定所需的最小窗口 / 快照形状 —— main 与 renderer 各自更宽的 RateLimitSnapshot+ * 结构兼容(结构子类型), 这里只声明本模块真正读的字段。+ */+export interface BucketWindowLike {+ usedPercent?: number;+ windowMinutes?: number | null;+ resetsAt?: number | null;+}++export interface BucketSnapshotLike {+ limitId?: string | null;+ limitName?: string | null;+ primary?: BucketWindowLike | null;+ secondary?: BucketWindowLike | null;+}++/** 快照 → 桶键。limitId 缺失 / 为危险保留名时归缺省桶。 */+export function codexLimitBucketKey(snapshot: BucketSnapshotLike | null | undefined): string {+ const limitId = snapshot?.limitId;+ if (typeof limitId !== 'string' || limitId.length === 0) return CODEX_DEFAULT_LIMIT_BUCKET;+ return UNSAFE_BUCKET_KEYS.has(limitId) ? CODEX_DEFAULT_LIMIT_BUCKET : limitId;+}++/**+ * 陈旧桶 = **所有**窗口都带有效 resetsAt 且全部过点超宽限。+ *+ * 只要有一个窗口缺 resetsAt 就不判陈旧 —— 该字段是可选的, 拿「有时间戳的那些+ * 都过期了」当全体过期的证据, 会在周窗口没给时间戳时误删仍然有效的桶+ * (review 反馈)。无窗口同样不判陈旧(信息不足, 交给上层兜底)。+ */+export function isCodexBucketStale(+ bucket: BucketSnapshotLike | null | undefined,+ nowMs: number,+): boolean {+ if (!bucket) return true;+ const windows = [bucket.primary, bucket.secondary].filter(+ (window): window is BucketWindowLike => Boolean(window),+ );+ if (windows.length === 0) return false;+ const resets = windows+ .map((window) => window.resetsAt)+ .filter((value): value is number => typeof value === 'number'+ && Number.isFinite(value)+ && value > 0);+ // 有窗口没给 resetsAt → 信息不足, 保守视为未过期。+ if (resets.length !== windows.length) return false;+ return Math.max(...resets) * 1000 + STALE_BUCKET_GRACE_MS < nowMs;+}++/** 模型 id / 桶名 → 可比较 token(小写, 去非字母数字)。 */+function normalizeModelToken(value: string | null | undefined): string {+ return typeof value === 'string' ? value.toLowerCase().replace(/[^a-z0-9]/g, '') : '';+}++/**+ * 按**当前会话模型**选桶(desktop chip 与 mobile 用量详情共用)。+ *+ * 不能用 account_usage 事件判会话归属: 该 notification 是账号级的, host 把同一条+ * fan-out 给所有 subscriber 再各自包上 sessionId(app-server host.routeNotification),+ * 拿它当会话事实等于把任意会话触发的桶串给所有会话。+ *+ * 规则(按序):+ * 1. 桶的 limitName 命中当前模型(如 'GPT-5.3-Codex-Spark' ↔ gpt-5.3-codex-spark);+ * 精确匹配优先, 其次取最长匹配(重叠桶名下 'GPT-5.3-Codex' 不得抢走 Spark 会话);+ * 2. 通用桶 —— 由**稳定桶键**(limitId 'codex' / 缺省桶)识别, 不能靠「没有+ * limitName」判断: limitName 可选, 同桶 merge 遇到省略该字段的部分通知会把它+ * 抹成 undefined, 模型专属桶会伪装成通用桶;+ * 3. 都没有 → null。**绝不**退而求其次选一个已知属于别的模型的桶。+ * 陈旧桶(窗口全部过期超宽限, 如促销结束后服务端停推)不参与匹配。+ */+export function matchCodexBucketForModel<T extends BucketSnapshotLike>(+ buckets: Record<string, T> | null | undefined,+ modelId: string | null | undefined,+ nowMs: number = Date.now(),+): T | null {+ const entries = Object.entries(buckets ?? {}).filter(+ ([, bucket]) => !isCodexBucketStale(bucket, nowMs),+ );+ if (entries.length === 0) return null;+ const model = normalizeModelToken(modelId);+ if (model) {+ // 精确匹配优先; 否则取**最长**的 substring 匹配 —— 桶顺序反映更新 / 持久化+ // 顺序, 按首个匹配返回会让 'GPT-5.3-Codex' 抢走本属于 'GPT-5.3-Codex-Spark'+ // 的会话, 通用名 'Codex' 更会命中所有 codex/* 模型(review 反馈)。+ let longest: { bucket: T; length: number } | null = null;+ for (const [, bucket] of entries) {+ const name = normalizeModelToken(bucket.limitName);+ if (!name) continue;+ if (name === model) return bucket;+ if (model.includes(name) && (longest === null || name.length > longest.length)) {+ longest = { bucket, length: name.length };+ }+ }+ if (longest) return longest.bucket;+ }+ // 按优先级取通用桶(不能靠 entries 的插入序, 见 GENERIC_BUCKET_KEYS_BY_PRIORITY)。+ for (const key of GENERIC_BUCKET_KEYS_BY_PRIORITY) {+ const hit = entries.find(([entryKey]) => entryKey === key);+ if (hit) return hit[1];+ }+ return null;+}++/**+ * 防御式选桶入口(unknown 进 / unknown 出)—— 供 mobile 会话用量详情直接串在+ * summarizeAccountRateLimits 之前使用: 两端拿到的 payload 形状都不保证。+ *+ * 桶来源优先级: 权威 rateLimitsByLimitId > 组合 payload 的 appServerBuckets;+ * 两者都没有(旧被控端 / 尚无数据)→ 原样返回 fallback 顶层快照, 保持旧行为。+ * 有桶表时以选桶结果为准, 匹配不到返回 null(不渲染限额区), 绝不显示别的模型的桶。+ */+export function selectCodexUsageForModel(input: {+ fallback?: unknown;+ byLimitId?: unknown;+ appServerBuckets?: unknown;+ modelId?: string | null;+ nowMs?: number;+}): unknown {+ const nowMs = input.nowMs ?? Date.now();+ const buckets = resolveCodexBucketTable(input);+ if (!buckets) return input.fallback ?? null;+ return matchCodexBucketForModel(buckets, input.modelId, nowMs);+}++/**+ * 解析出**实际生效**的桶表: 权威 rateLimitsByLimitId 优先, 空表 / 畸形则回退+ * appServerBuckets, 都不可用 → null。+ *+ * 选桶与「到点重选」定时器必须共用它 —— 用 `a ?? b` 只挡 null/undefined,+ * 空对象 `{}` 会被当成有效表, 于是选桶回退到了 appServerBuckets 而定时器却按+ * 空表算出「无需定时」, 面板跨过失效时刻不会重选(review 反馈)。+ */+export function resolveCodexBucketTable(input: {+ byLimitId?: unknown;+ appServerBuckets?: unknown;+}): Record<string, BucketSnapshotLike> | null {+ return readBucketTable(input.byLimitId) ?? readBucketTable(input.appServerBuckets);+}++/**+ * 桶表中最近一个「由有效转为陈旧」的时刻(ms);没有可预期的转变 → null。+ * 陈旧判定只在选桶时求值, 界面常驻时不会自己重算 —— desktop chip 与 mobile+ * 用量面板都用它安排一次到点重选, 否则过期促销桶会一直挂着(review 反馈)。+ */+export function nextCodexBucketStaleAtMs(buckets: unknown, nowMs: number): number | null {+ const table = readBucketTable(buckets);+ if (!table) return null;+ let soonest: number | null = null;+ for (const bucket of Object.values(table)) {+ if (isCodexBucketStale(bucket, nowMs)) continue;+ const windows = [bucket.primary, bucket.secondary].filter(+ (window): window is BucketWindowLike => Boolean(window),+ );+ if (windows.length === 0) continue;+ const resets = windows+ .map((window) => window.resetsAt)+ .filter((value): value is number => typeof value === 'number'+ && Number.isFinite(value)+ && value > 0);+ // 与 isCodexBucketStale 同口径: 有窗口缺时间戳就永不进入陈旧, 无需定时。+ if (resets.length !== windows.length) continue;+ const staleAt = Math.max(...resets) * 1000 + STALE_BUCKET_GRACE_MS;+ if (staleAt > nowMs && (soonest === null || staleAt < soonest)) soonest = staleAt;+ }+ return soonest;+}++/** unknown → 桶表(丢弃非对象条目与危险键);不是可用桶表 → null。 */+function readBucketTable(value: unknown): Record<string, BucketSnapshotLike> | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const out: Record<string, BucketSnapshotLike> = {};+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {+ if (UNSAFE_BUCKET_KEYS.has(key)) continue;+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {+ out[key] = entry as BucketSnapshotLike;+ }+ }+ return Object.keys(out).length > 0 ? out : null;+}