Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 用量 chip 只在当前会话真受限时变红 (#375)
Dash44bd2460bf2b
diff --git a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsage.test.ts b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsage.test.tsindex 97a0a594c2..539a166db2 100644--- a/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsage.test.ts+++ b/apps/desktop/src/main/usage/__tests__/claudeSubscriptionUsage.test.ts@@ -6,6 +6,7 @@* - parseClaudeUnifiedRateLimitHeaders: headers 0.0-1.0 分数 ×100 归一化* - mergeClaudeSubscriptionUsageSnapshot: headers 增量 / endpoint 全量的双源语义* - claudeModelFamily / matchScopedWindowForModel: 方案 B 的模型 → scoped 窗口匹配+ * - isClaudeSubscriptionAlerting: chip 变红口径(只看影响当前会话的窗口 + rejected)* - fetchClaudeSubscriptionUsageSnapshot: UA / beta 头、401→Unauthorized、429→RateLimited*/@@ -13,6 +14,9 @@ import { describe, expect, it, vi } from 'vitest';import {claudeModelFamily,+ hasAlertingClaudeSessionWindow,+ isClaudeSubscriptionAlerting,+ isClaudeUsageWindowAlerting,matchScopedWindowForModel,mergeClaudeSubscriptionUsageSnapshot,parseClaudeOAuthUsageResponse,@@ -246,6 +250,115 @@ describe('claudeModelFamily / matchScopedWindowForModel', () => {});});+describe('isClaudeSubscriptionAlerting', () => {+ /**+ * 2026-07-25 实测快照:5h / 总周限都很宽裕,只有 Fable 的分模型周限 87% 且服务端+ * 给了 severity=warning。chip 上只显示 5h + 周限两段,所以这份数据只该让 Fable+ * 会话变红。+ */+ const SNAPSHOT: ClaudeSubscriptionUsageSnapshot = {+ fiveHour: { utilization: 10 },+ sevenDay: { utilization: 44 },+ scoped: [{ utilization: 87, severity: 'warning', modelDisplayName: 'Fable' }],+ rateLimitStatus: 'allowed',+ subscriptionType: 'max',+ };++ it('only alerts the model whose scoped weekly window is warning', () => {+ expect(isClaudeSubscriptionAlerting(SNAPSHOT, 'claude-fable-5[1m]')).toBe(true);+ // 跑 Opus / Sonnet 的会话不受 Fable 周限影响 —— chip 上也没有那一段, 不能染红+ expect(isClaudeSubscriptionAlerting(SNAPSHOT, 'claude-opus-5[1m]')).toBe(false);+ expect(isClaudeSubscriptionAlerting(SNAPSHOT, 'claude-sonnet-5')).toBe(false);+ // 家族识别不出来时回退总周限(44%,不告警)+ expect(isClaudeSubscriptionAlerting(SNAPSHOT, null)).toBe(false);+ expect(isClaudeSubscriptionAlerting(null, 'claude-fable-5')).toBe(false);+ });++ it('ignores allowed_warning but honors rejected', () => {+ // allowed_warning 是服务端综合全部窗口(含其它模型周限)的模糊信号:chip 只显示+ // 5h + 周限, 拿它染红会出现「剩余 91% / 56% 却是红的」+ expect(isClaudeSubscriptionAlerting(+ { ...SNAPSHOT, rateLimitStatus: 'allowed_warning' },+ 'claude-opus-5[1m]',+ )).toBe(false);+ // 真限流(请求已被拒)与当前模型无关, 一律告警+ expect(isClaudeSubscriptionAlerting(+ { ...SNAPSHOT, rateLimitStatus: 'rejected' },+ 'claude-opus-5[1m]',+ )).toBe(true);+ expect(isClaudeSubscriptionAlerting(+ { ...SNAPSHOT, rateLimitStatus: 'REJECTED ' },+ 'claude-opus-5[1m]',+ )).toBe(true);+ });++ it('alerts on exhausted or non-normal session-scope windows', () => {+ // 打满(headers 源不带 severity, 只能靠 utilization)+ expect(isClaudeSubscriptionAlerting(+ { fiveHour: { utilization: 100 } },+ 'claude-opus-5',+ )).toBe(true);+ // 总周限 severity 非 normal —— 所有模型共用, 与当前模型无关+ expect(isClaudeSubscriptionAlerting(+ { sevenDay: { utilization: 80, severity: 'warning' } },+ 'claude-opus-5',+ )).toBe(true);+ // 水位远未见底且 severity=normal → 不告警+ expect(isClaudeSubscriptionAlerting(+ { fiveHour: { utilization: 60, severity: 'normal' }, sevenDay: { utilization: 44 } },+ 'claude-opus-5',+ )).toBe(false);+ });++ it('alerts when a displayed window runs down to the last 10%', () => {+ // unified-headers 源不带 per-window severity, 只有 utilization: 光靠「打满」会让+ // chip 一直到 99.95% 才变红。剩余 ≤10% 即告警, 判据是 chip 上正在显示的那个数字。+ expect(isClaudeSubscriptionAlerting({ fiveHour: { utilization: 90 } }, 'claude-opus-5'))+ .toBe(true);+ expect(isClaudeSubscriptionAlerting({ sevenDay: { utilization: 92 } }, 'claude-opus-5'))+ .toBe(true);+ // 水位判定优先于服务端 severity: 只剩 5% 时说 normal 也照样提醒+ expect(isClaudeSubscriptionAlerting(+ { fiveHour: { utilization: 95, severity: 'normal' } },+ 'claude-opus-5',+ )).toBe(true);+ // 阈值下方不告警(89% 已用 = 剩余 11%)+ expect(isClaudeSubscriptionAlerting({ fiveHour: { utilization: 89 } }, 'claude-opus-5'))+ .toBe(false);+ // 其它模型的 scoped 窗口即使见底也不染红当前会话 —— 与阈值无关+ expect(isClaudeSubscriptionAlerting(+ { fiveHour: { utilization: 10 }, scoped: [{ utilization: 99, modelDisplayName: 'Fable' }] },+ 'claude-opus-5',+ )).toBe(false);+ });++ it('hasAlertingClaudeSessionWindow excludes the overall status signal', () => {+ // tooltip 用它 + status 分流, chip 用 isClaudeSubscriptionAlerting; 窗口维度本身+ // 不看 status(rejected 也不例外)+ expect(hasAlertingClaudeSessionWindow(+ { ...SNAPSHOT, rateLimitStatus: 'rejected' },+ 'claude-opus-5[1m]',+ )).toBe(false);+ expect(hasAlertingClaudeSessionWindow(SNAPSHOT, 'claude-fable-5[1m]')).toBe(true);+ expect(isClaudeUsageWindowAlerting(undefined)).toBe(false);+ expect(isClaudeUsageWindowAlerting({ utilization: 87, severity: 'warning' })).toBe(true);+ });++ it('ignores non-finite utilization instead of treating it as exhausted', () => {+ // 持久化快照是 JSON.parse 后直接断言的, 不重新校验字段: 脏值不能被 clampPercent+ // 夹成 100 而误判额度耗尽。severity 缺失时一律不告警。+ expect(isClaudeUsageWindowAlerting({ utilization: Number.POSITIVE_INFINITY })).toBe(false);+ expect(isClaudeUsageWindowAlerting({ utilization: Number.NaN })).toBe(false);+ expect(isClaudeSubscriptionAlerting(+ { fiveHour: { utilization: Number.POSITIVE_INFINITY } },+ 'claude-opus-5',+ )).toBe(false);+ // 脏 utilization 不影响 severity 这条独立判据+ expect(isClaudeUsageWindowAlerting({ utilization: Number.NaN, severity: 'warning' }))+ .toBe(true);+ });+});+describe('fetchClaudeSubscriptionUsageSnapshot', () => {function jsonResponse(status: number, body: unknown): Response {return {diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.tsindex e30ab11141..4bfad77834 100644--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts@@ -193,10 +193,20 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).toContain('weekly.modelDisplayName ? `${weekly.modelDisplayName} ${countdown}` : countdown');expect(source).toContain('todaySpend.claude.sessionValueLabel');expect(source).toContain('todaySpend.claude.planLine');- // 告警只看影响当前会话的窗口 (5h / 总周限 / 当前模型 scoped);headers 的- // allowed_warning 是 turn 内唯一的「接近限额」实时信号, 必须纳入告警态- expect(source).toContain('isClaudeSubscriptionAlerting(');- expect(source).toContain("status === 'rejected' || status === 'allowed_warning'");+ // 告警判定是纯数据判定, 统一收在 shared/claudeSubscriptionUsage.ts (有直接单测:+ // main/usage/__tests__/claudeSubscriptionUsage.test.ts), 组件只消费, 不再本地重写。+ expect(source).toContain('isClaudeSubscriptionAlerting,');+ expect(source).toContain('hasAlertingClaudeSessionWindow,');+ expect(source).not.toContain('function isClaudeSubscriptionAlerting(');+ expect(source).not.toContain('function hasAlertingClaudeSessionWindow(');+ // chip 变红只看当前会话真受限 (rejected / 影响本会话的窗口告警); headers 的+ // allowed_warning 综合了其它模型的分模型周限, 不得单独染红 —— 否则跑 Opus 的+ // 会话会因 Fable 周限吃紧变红, 而 chip 上根本没有那一段。+ expect(source).not.toContain("status === 'rejected' || status === 'allowed_warning'");+ // tooltip 比 chip 宽一档: allowed_warning 仍提示 (紧邻全量窗口列表, 有上下文)+ expect(source).toContain(+ "status === 'allowed_warning' || hasAlertingClaudeSessionWindow(snapshot, modelId)",+ );// Claude 订阅 / bridge 订阅不读 gateway quota (不反映订阅花费); 默认路由 key reconcile// 完成前形态未定, 同样不放行网关 quota 读 (避免形态闪切)expect(source).toContain("vendorKey === 'cc' && !isClaudeSubscription && !isSubscriptionBridge && !ccBillingFormPending");diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex bf8edb2303..6aa52dba49 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -66,6 +66,8 @@ import {type ClaudeSubscriptionUsageSnapshot,} from '@/hooks/useClaudeSubscriptionUsage';import {+ hasAlertingClaudeSessionWindow,+ isClaudeSubscriptionAlerting,matchScopedWindowForModel,type ClaudeUsageWindow,} from '../../../shared/claudeSubscriptionUsage';@@ -524,22 +526,17 @@ function buildCodexTooltipNode(// 不到回退总周限并标注口径) · 本会话价值 $。tooltip 列全量窗口 (含非当前模型的// scoped 条目) + 套餐 + extra usage。utilization 语义 = 已用百分比 (0-100)。-/** Claude 窗口 → 展示行素材;窗口缺失 / 数据不可解析 → null (调用方过滤)。 */+/**+ * Claude 窗口 → tooltip 行素材;窗口缺失 / 数据不可解析 → null (调用方过滤)。+ * tooltip 的窗口行不做逐行高亮 (纯文本 tooltip), 告警只体现在 chip 配色与末尾的+ * 「接近限额」行 —— 故这里不带 alerting 标记。+ */interface ClaudeWindowUsage {label: string;used: string;remaining: string;/** tooltip 用的精确 reset 时间点;无数据 → null。 */resetAt: string | null;- /** 服务端 severity 非 normal, 或已打满 —— tooltip 高亮 / chip 变警示色的依据。 */- alerting: boolean;-}--function isClaudeWindowAlerting(window: ClaudeUsageWindow | null | undefined): boolean {- if (!window) return false;- if (clampPercent(window.utilization) >= 99.95) return true;- const severity = window.severity?.trim().toLowerCase();- return Boolean(severity && severity !== 'normal');}function toClaudeWindowUsage(@@ -555,7 +552,6 @@ function toClaudeWindowUsage(used: formatPercent(usedPercent),remaining: formatPercent(100 - usedPercent),resetAt: formatResetAt(window.resetsAt),- alerting: isClaudeWindowAlerting(window),};}@@ -632,26 +628,11 @@ function getClaudeChipWindows(return windows;}-/**- * chip 警示态: 只看影响当前会话的窗口 (5h / 总周限 / 当前模型 scoped) 与 headers- * 的整体 status —— 其它模型的窗口打满不限流当前会话, 只在 tooltip 里可见。- * headers 源的窗口不带 severity, turn 内实时阶段「接近限额」只由整体 status 的- * allowed_warning 表达, 因此 warning / rejected 都纳入告警 (rejected 在 tooltip- * 文案分流里优先)。- */-function isClaudeSubscriptionAlerting(- snapshot: ClaudeSubscriptionUsageSnapshot | null,- modelId: string | null | undefined,-): boolean {- if (!snapshot) return false;- const status = snapshot.rateLimitStatus?.trim().toLowerCase();- if (status === 'rejected' || status === 'allowed_warning') return true;- return (- isClaudeWindowAlerting(snapshot.fiveHour)- || isClaudeWindowAlerting(snapshot.sevenDay)- || isClaudeWindowAlerting(matchScopedWindowForModel(snapshot.scoped, modelId))- );-}+// 告警判定 (chip 变红的口径 + allowed_warning 为何不染红、为何不用 representativeClaim+// 的取舍) 已收进 shared/claudeSubscriptionUsage.ts: isClaudeUsageWindowAlerting /+// hasAlertingClaudeSessionWindow / isClaudeSubscriptionAlerting (纯数据判定, 有直接单测)。+// tooltip 不逐行高亮, 它比 chip 宽一档的那一档在 buildClaudeSubscriptionTooltipNode 里+// (整体 status 的 allowed_warning 也出「接近限额」行)。function buildClaudeSubscriptionTooltipNode(snapshot: ClaudeSubscriptionUsageSnapshot | null,@@ -705,10 +686,13 @@ function buildClaudeSubscriptionTooltipNode();}+ // tooltip 比 chip 宽一档: allowed_warning (服务端综合全部窗口的模糊信号) 也提示 ——+ // 上面刚列完全量窗口, 用户能自己看出是哪个窗口吃紧; chip 颜色不吃这个信号 (见+ // isClaudeSubscriptionAlerting)。const status = snapshot.rateLimitStatus?.trim().toLowerCase();if (status === 'rejected') {lines.push(t('todaySpend.claude.limitRejected'));- } else if (isClaudeSubscriptionAlerting(snapshot, modelId)) {+ } else if (status === 'allowed_warning' || hasAlertingClaudeSessionWindow(snapshot, modelId)) {lines.push(t('todaySpend.claude.limitWarning'));}@@ -1394,6 +1378,8 @@ export function TodaySpendChip({// Claude 订阅告警态: 影响当前会话的窗口 (5h / 总周限 / 当前模型 scoped) 任一逼近 /// 打满, 或 headers 报 rejected → chip 变 error 色 (语义豁免色, 跨主题一致)。+ // 其它模型的周限吃紧不染红 —— chip 上没有那一段, 红了也无从解释 (见+ // isClaudeSubscriptionAlerting 对 allowed_warning 的取舍)。const claudeSubscriptionAlerting = isClaudeSubscription&& isClaudeSubscriptionAlerting(claudeSubscriptionUsage, modelId);diff --git a/apps/desktop/src/shared/claudeSubscriptionUsage.ts b/apps/desktop/src/shared/claudeSubscriptionUsage.tsindex 78e49e38f7..7009e69f1f 100644--- a/apps/desktop/src/shared/claudeSubscriptionUsage.ts+++ b/apps/desktop/src/shared/claudeSubscriptionUsage.ts@@ -353,3 +353,80 @@ export function matchScopedWindowForModel(if (!family) return null;return scoped.find((w) => w.modelDisplayName.trim().toLowerCase() === family) ?? null;}++// ── 告警判定(chip 变红的口径;tooltip 另有 status 分流,见 TodaySpendChip) ───++/**+ * 窗口进入告警的剩余水位:剩余 ≤10%(已用 ≥90%)。+ *+ * 兜的是 unified-headers 源没有 per-window `severity` 这个事实 —— 该源只给 utilization,+ * 光靠「打满」判定会让 chip 一直到 99.95% 才变红。用固定水位而不是 headers 的整体+ * `allowed_warning`:水位对着 chip 上正在显示的那个数字,「剩余 8%」是红的能自证;+ * 整体 status 综合了 chip 上没有的窗口,红了无从解释(见 isClaudeSubscriptionAlerting)。+ */+const WINDOW_ALERT_UTILIZATION_PERCENT = 90;++/**+ * 单个窗口告警:剩余水位见底,或服务端 severity 明确非 normal。+ *+ * utilization 走 Number.isFinite 而不只是 typeof —— 与本文件其它调用点同口径。解析层+ * (toFiniteNumber / parseHeaderUtilization)本就只放行有限数, 但持久化快照是 JSON.parse+ * 后直接断言成 snapshot 的(见 usageBroadcaster hydration), 不重新校验字段; 万一有脏值+ * 滑进来, +Infinity 会被 clampPercent 夹成 100 并误判成额度耗尽而染红。+ */+export function isClaudeUsageWindowAlerting(+ window: ClaudeUsageWindow | null | undefined,+): boolean {+ if (!window) return false;+ if (+ typeof window.utilization === 'number'+ && Number.isFinite(window.utilization)+ && clampPercent(window.utilization) >= WINDOW_ALERT_UTILIZATION_PERCENT+ ) {+ return true;+ }+ const severity = window.severity?.trim().toLowerCase();+ return Boolean(severity && severity !== 'normal');+}++/**+ * 影响当前会话的窗口是否告警:只看 5h / 总周限 / **当前模型**的 scoped 周限 ——+ * 其它模型的 scoped 窗口打满不限流当前会话(跑 Opus 时 Fable 周限见底与本会话无关),+ * 只在 tooltip 的全量窗口列表里可见,不参与判定。+ */+export function hasAlertingClaudeSessionWindow(+ snapshot: ClaudeSubscriptionUsageSnapshot | null,+ modelId: string | null | undefined,+): boolean {+ if (!snapshot) return false;+ return (+ isClaudeUsageWindowAlerting(snapshot.fiveHour)+ || isClaudeUsageWindowAlerting(snapshot.sevenDay)+ || isClaudeUsageWindowAlerting(matchScopedWindowForModel(snapshot.scoped, modelId))+ );+}++/**+ * chip 警示态(变红):只在当前会话**真的**受限时亮 —— 请求已被拒(headers 整体+ * status = rejected),或影响当前会话的窗口告警(见上)。+ *+ * headers 的 `allowed_warning` **不**单独染红:它是服务端综合全部窗口(含其它模型的+ * 分模型周限)给出的模糊信号,而 chip 只显示 5h + 周限两段 —— 拿 Fable 周限 87% 把跑+ * Opus 的会话染红,用户看到的是「剩余 91% / 56% 却是红的」,颜色与数字自相矛盾且无处+ * 解释(chip 上没有那个窗口)。真限流时 rejected 会立刻到,不需要它兜底;「接近限额」+ * 提示仍留在 tooltip —— 那里紧邻全量窗口列表,有上下文。+ *+ * 也没有走 `representativeClaim`(「只在 claim 指向 chip 上的窗口时才认 allowed_warning」):+ * 2026-07-25 实测快照里 claim=`five_hour`,而当时真正吃紧的是 Fable 周限(87%,+ * severity=warning),5h 只用了 10% —— 这个字段并不指向触发 warning 的窗口,以它为条件+ * 会原样退回误红。headers 源缺 severity 的预警缺口改由 WINDOW_ALERT_UTILIZATION_PERCENT+ * 的剩余水位兜住,判据始终是 chip 上看得见的那个数字。+ */+export function isClaudeSubscriptionAlerting(+ snapshot: ClaudeSubscriptionUsageSnapshot | null,+ modelId: string | null | undefined,+): boolean {+ if (!snapshot) return false;+ if (snapshot.rateLimitStatus?.trim().toLowerCase() === 'rejected') return true;+ return hasAlertingClaudeSessionWindow(snapshot, modelId);+}