Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 恢复订阅任务累计价值并保留异币种金额 (#4559)
Dash1da09fde00e5
diff --git a/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.ts b/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.tsindex 49440ccc8e..83e0cf2c59 100644--- a/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.ts@@ -30,10 +30,7 @@ function legacyCnyEstimate(amount: number): RegionalMoney {};}-function assistantMessage(- clientId: string,- costUsd?: number,-): ChatMessage {+function assistantMessage(clientId: string, costUsd?: number): ChatMessage {return {clientId,role: 'assistant',@@ -59,11 +56,11 @@ if (!GPT_DETAILS) {describe('syncEstimatedValueCostsFromStoreSnapshot', () => {it('preserves DB-backed costs before chat history has loaded', () => {const current = new Map([['persisted', usdEstimate(0.12)]]);- const result = syncEstimatedValueCostsFromStoreSnapshot(- current,- new Set(),- { messages: [], historyLoaded: false, hasMoreMessages: true },- );+ const result = syncEstimatedValueCostsFromStoreSnapshot(current, new Set(), {+ messages: [],+ historyLoaded: false,+ hasMoreMessages: true,+ });expect(result).toBeNull();});@@ -90,10 +87,7 @@ describe('syncEstimatedValueCostsFromStoreSnapshot', () => {]),new Set(['old-visible']),{- messages: [- assistantMessage('new-visible', 0.04),- assistantMessage('visible-no-cost'),- ],+ messages: [assistantMessage('new-visible', 0.04), assistantMessage('visible-no-cost')],historyLoaded: true,hasMoreMessages: true,},@@ -108,85 +102,128 @@ describe('syncEstimatedValueCostsFromStoreSnapshot', () => {describe('resolveEstimatedValueTurnCostEntry', () => {it('corrects realtime stale full-cache estimates before merging session value', () => {- expect(resolveEstimatedValueTurnCostEntry({- clientId: 'stale',- turnMoney: usdEstimate(8.76),- turnCostIsEstimate: true,- turnUsageDetails: GPT_DETAILS,- })?.money.amount).toBeCloseTo(2.011);+ expect(+ resolveEstimatedValueTurnCostEntry({+ clientId: 'stale',+ turnMoney: usdEstimate(8.76),+ turnCostIsEstimate: true,+ turnUsageDetails: GPT_DETAILS,+ })?.money.amount,+ ).toBeCloseTo(2.011);});it('corrects stale legacy estimates after their CN fixed-FX projection', () => {- expect(resolveEstimatedValueTurnCostEntry({- clientId: 'stale-cn',- turnMoney: legacyCnyEstimate(8.76 * 6.7),- turnCostIsEstimate: true,- turnUsageDetails: GPT_DETAILS,- })?.money.amount).toBeCloseTo(2.011 * 6.7);+ expect(+ resolveEstimatedValueTurnCostEntry({+ clientId: 'stale-cn',+ turnMoney: legacyCnyEstimate(8.76 * 6.7),+ turnCostIsEstimate: true,+ turnUsageDetails: GPT_DETAILS,+ })?.money.amount,+ ).toBeCloseTo(2.011 * 6.7);});it('preserves realtime live pricing estimates that do not match stale full-cache formulas', () => {- expect(resolveEstimatedValueTurnCostEntry({- clientId: 'live',- turnMoney: usdEstimate(3.14),- turnCostIsEstimate: true,- turnUsageDetails: GPT_DETAILS,- })?.money.amount).toBe(3.14);+ expect(+ resolveEstimatedValueTurnCostEntry({+ clientId: 'live',+ turnMoney: usdEstimate(3.14),+ turnCostIsEstimate: true,+ turnUsageDetails: GPT_DETAILS,+ })?.money.amount,+ ).toBe(3.14);});it('ignores non-estimate realtime entries', () => {- expect(resolveEstimatedValueTurnCostEntry({- clientId: 'api-cost',- turnCostUsd: 0.42,- turnCostIsEstimate: false,- turnUsageDetails: GPT_DETAILS,- })).toBeNull();+ expect(+ resolveEstimatedValueTurnCostEntry({+ clientId: 'api-cost',+ turnCostUsd: 0.42,+ turnCostIsEstimate: false,+ turnUsageDetails: GPT_DETAILS,+ }),+ ).toBeNull();});});describe('shouldApplyEstimatedValueEntry', () => {it('ignores delayed entries after an authoritative /clear snapshot', () => {- expect(shouldApplyEstimatedValueEntry(- { messages: [], historyLoaded: true, hasMoreMessages: false },- 'stale-assistant',- true,- )).toBe(false);+ expect(+ shouldApplyEstimatedValueEntry(+ { messages: [], historyLoaded: true, hasMoreMessages: false },+ 'stale-assistant',+ true,+ ),+ ).toBe(false);});it('allows entries for visible messages after a clear', () => {- expect(shouldApplyEstimatedValueEntry(- {- messages: [assistantMessage('new-assistant')],- historyLoaded: true,- hasMoreMessages: false,- },- 'new-assistant',- true,- )).toBe(true);+ expect(+ shouldApplyEstimatedValueEntry(+ {+ messages: [assistantMessage('new-assistant')],+ historyLoaded: true,+ hasMoreMessages: false,+ },+ 'new-assistant',+ true,+ ),+ ).toBe(true);});it('keeps ignoring stale entries after a new transcript starts', () => {- expect(shouldApplyEstimatedValueEntry(- {- messages: [assistantMessage('new-assistant')],- historyLoaded: true,- hasMoreMessages: false,- },- 'stale-assistant',- true,- )).toBe(false);+ expect(+ shouldApplyEstimatedValueEntry(+ {+ messages: [assistantMessage('new-assistant')],+ historyLoaded: true,+ hasMoreMessages: false,+ },+ 'stale-assistant',+ true,+ ),+ ).toBe(false);});it('allows DB-backed entries before any clear marker exists', () => {- expect(shouldApplyEstimatedValueEntry(- { messages: [], historyLoaded: false, hasMoreMessages: true },- 'persisted-history',- false,- )).toBe(true);+ expect(+ shouldApplyEstimatedValueEntry(+ { messages: [], historyLoaded: false, hasMoreMessages: true },+ 'persisted-history',+ false,+ ),+ ).toBe(true);});});describe('combineSessionUsageMoney', () => {+ it.each([+ null,+ { amount: 0, currency: 'CNY', approximate: false, kind: 'actual-cost' } as RegionalMoney,+ ])(+ 'shows USD subscription value when actual cost is absent or a zero CNY placeholder: %j',+ (actual) => {+ const estimate = usdEstimate(0.67052);+ const result = combineSessionUsageMoney(actual, estimate);+ expect(result.estimatedValueMoney).toEqual(estimate);+ expect(result.totalMoney).toMatchObject({+ amount: 0.67052,+ currency: 'USD',+ kind: 'value-estimate',+ });+ },+ );++ it('does not display a total before either source has a positive amount', () => {+ expect(combineSessionUsageMoney(null, null).totalMoney).toBeNull();+ expect(+ combineSessionUsageMoney(+ { amount: 0, currency: 'CNY', approximate: false, kind: 'actual-cost' },+ usdEstimate(0),+ ).totalMoney,+ ).toBeNull();+ });+it('adds CN actual cost and subscription value into one stable session total', () => {const result = combineSessionUsageMoney({@@ -212,7 +249,25 @@ describe('combineSessionUsageMoney', () => {expect(result.totalMoney?.amount).toBeCloseTo(1.259804, 10);});- it('drops an ambiguous legacy USD estimate from an active CNY session total', () => {+ it.each([0, 1])('keeps ambiguous legacy USD hidden against a CNY balance of %s', (amount) => {+ const result = combineSessionUsageMoney(+ { amount, currency: 'CNY', approximate: false, kind: 'actual-cost' },+ { ...usdEstimate(1), estimateReasons: ['legacy-usd', 'subscription-value'] },+ );+ expect(result.estimatedValueMoney).toBeNull();+ if (amount > 0) expect(result.totalMoney).toMatchObject({ amount, currency: 'CNY' });+ else expect(result.totalMoney).toBeNull();+ });++ it('preserves legacy USD estimates within a matching USD ledger', () => {+ const result = combineSessionUsageMoney(+ { amount: 0, currency: 'USD', approximate: false, kind: 'actual-cost' },+ { ...usdEstimate(1), estimateReasons: ['legacy-usd', 'subscription-value'] },+ );+ expect(result.totalMoney).toMatchObject({ amount: 1, currency: 'USD' });+ });++ it('preserves different currencies separately without inventing a combined total', () => {const result = combineSessionUsageMoney({amount: 1,@@ -225,11 +280,12 @@ describe('combineSessionUsageMoney', () => {currency: 'USD',approximate: true,kind: 'value-estimate',- estimateReasons: ['legacy-usd', 'subscription-value'],+ estimateReasons: ['reference-price', 'subscription-value'],},);- expect(result.estimatedValueMoney).toBeNull();- expect(result.totalMoney).toMatchObject({ amount: 1, currency: 'CNY' });+ expect(result.estimatedValueMoney).toMatchObject({ amount: 1, currency: 'USD' });+ expect(result.actualMoney).toMatchObject({ amount: 1, currency: 'CNY' });+ expect(result.totalMoney).toBeNull();});});diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex da18cc8173..a37b88176a 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -156,7 +156,7 @@ interface MetricSlot {function computeMetricSlots(claudeQuota: ClaudeAccountUsageSnapshot | null,creditTotals: CreditTotals | null,- sessionMoney: RegionalMoney | null,+ sessionLabel: string | null,t: TFunction,): Record<MetricKey, MetricSlot> {const slots: Record<MetricKey, MetricSlot> = {@@ -225,11 +225,10 @@ function computeMetricSlots(}}- if (sessionMoney && sessionMoney.amount > 0) {- const cost = formatTurnCostMoney(sessionMoney);+ if (sessionLabel) {slots.session = {- label: t('todaySpend.sessionCostLabel', { cost }),- tooltipLabel: t('todaySpend.tooltip.sessionUsed', { cost }),+ label: sessionLabel,+ tooltipLabel: sessionLabel,available: true,};}@@ -562,7 +561,12 @@ function toQuotaHoverCardSessionUsage(sessionTokens: number | null,): QuotaHoverCardSessionUsage | null {const { actualMoney, estimatedValueMoney, totalMoney } = sessionUsage;- if (!totalMoney?.amount && !hasPositiveSessionTokens(sessionTokens)) return null;+ if (+ !actualMoney?.amount &&+ !estimatedValueMoney?.amount &&+ !hasPositiveSessionTokens(sessionTokens)+ )+ return null;return {costText: totalMoney?.amount ? formatTurnCostMoney(totalMoney) : null,@@ -896,7 +900,6 @@ export function TodaySpendChip({// 会话金额只由已发生的 turn 决定,不由当前选中的 provider/模型决定。实际费用从// session ledger 读取,订阅价值从消息明细重建,再统一汇总成“本对话”投影。const sessionUsage = useSessionUsageMoney(sessionId, sessionInitialMoney, sessionInitialCostUsd);- const sessionMoney = sessionUsage.totalMoney;const sessionTokens = useSessionTokens(vendorKey === 'pi' ||isCodexApi ||@@ -1136,11 +1139,27 @@ export function TodaySpendChip({[clearQuotaPopoverCloseTimer, clearQuotaPopoverOpenTimer],);- const sessionSegment = sessionMoney?.amount- ? t('todaySpend.sessionCostLabel', {- cost: formatTurnCostMoney(sessionMoney),- })- : null;+ const sessionSegment = sessionUsage.totalMoney?.amount+ ? t(+ sessionUsage.totalMoney.kind === 'value-estimate'+ ? 'todaySpend.codex.sessionValueLabel'+ : 'todaySpend.sessionCostLabel',+ { cost: formatTurnCostMoney(sessionUsage.totalMoney) },+ )+ : [+ sessionUsage.actualMoney?.amount+ ? t('todaySpend.tooltip.sessionUsed', {+ cost: formatTurnCostMoney(sessionUsage.actualMoney),+ })+ : null,+ sessionUsage.estimatedValueMoney?.amount+ ? t('todaySpend.codex.sessionValueLabel', {+ cost: formatTurnCostMoney(sessionUsage.estimatedValueMoney),+ })+ : null,+ ]+ .filter(Boolean)+ .join(' · ') || null;// codex-oauth / cc+chatgpt bridge → ChatGPT 用量看板; cc+xai bridge → grok.com 用量页;// cc Claude 订阅 → claude.ai 用量页; 其余(cc 网关 / codex-api)→ 暂无看板(null,见文件头 TODO)。// device-link 远程会话额度属于被控端账号,本机浏览器打开的看板是控制端自己的账号 → 不跳。@@ -1382,7 +1401,7 @@ export function TodaySpendChip({: buildClaudeUsageCard(claudeSubscriptionUsage, t);}} else {- const slots = computeMetricSlots(claudeQuota, creditTotals, sessionMoney, t);+ const slots = computeMetricSlots(claudeQuota, creditTotals, sessionSegment, t);const chipSegments = getGatewayChipSegments(slots);const codexApiHasTokenFallback =isCodexApi && !slots.session.available && hasPositiveSessionTokens(sessionTokens);diff --git a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsxindex 4dfa960ce1..ac3a1911e2 100644--- a/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx+++ b/apps/desktop/src/renderer/components/status/__tests__/TodaySpendChip.popover.test.tsx@@ -692,6 +692,24 @@ describe('TodaySpendChip Claude subscription popover', () => {expect(screen.getByText('本轮消耗:$0.46')).toBeTruthy();});+ it('异币种费用与订阅估值在状态栏和卡片分别显示,无 token 时也保留金额', () => {+ mocks.sessionUsage = {+ actualMoney: { ...usdMoney(1), currency: 'CNY' },+ estimatedValueMoney: usdMoney(0.5, 'value-estimate'),+ totalMoney: null,+ };+ mocks.sessionTokens = null;+ renderClaudeSubscriptionChip();+ const chip = screen.getByRole('button', { name: '打开 Claude 用量页面' });+ expect(chip.textContent).toContain('本任务已用 ¥1.00');+ expect(chip.textContent).toContain('本任务价值 $0.50');+ const { card } = openCardFromHover();+ const section = within(card).getByTestId('quota-session-usage');+ expect(within(section).getByText('本任务已用 ¥1.00')).toBeTruthy();+ expect(within(section).getByText('本任务价值 $0.50')).toBeTruthy();+ expect(section.textContent).not.toContain('1.50');+ });+it('第三方参考价的近似实际费用仍标为本任务已用', () => {const approximateActualMoney: RegionalMoney = {...usdMoney(0.25),@@ -721,6 +739,9 @@ describe('TodaySpendChip Claude subscription popover', () => {};renderClaudeSubscriptionChip();+ expect(screen.getByRole('button', { name: '打开 Claude 用量页面' }).textContent).toContain(+ '本任务价值 $0.50',+ );const { card } = openCardFromHover();const sessionSection = within(card).getByTestId('quota-session-usage');diff --git a/apps/desktop/src/renderer/hooks/useSessionUsageMoney.ts b/apps/desktop/src/renderer/hooks/useSessionUsageMoney.tsindex 83e5b80499..42caefcd88 100644--- a/apps/desktop/src/renderer/hooks/useSessionUsageMoney.ts+++ b/apps/desktop/src/renderer/hooks/useSessionUsageMoney.ts@@ -26,22 +26,25 @@ export function combineSessionUsageMoney(actualMoney: RegionalMoney | null,estimatedValueMoney: RegionalMoney | null,): SessionUsageMoney {- // 历史 turnCostUsd 的真实来源可能是 USD,也可能是曾被误标的 Gateway CNY。- // 只兼容与当前会话账本同币种的值;无法确定换算关系时直接丢弃,不猜测或强转。- const preferredCurrency = actualMoney?.currency ?? DEFAULT_USAGE_CURRENCY;- const compatibleEstimatedValueMoney =- estimatedValueMoney?.currency === preferredCurrency- ? estimatedValueMoney- : null;- const values = [actualMoney, compatibleEstimatedValueMoney].filter(- (money): money is RegionalMoney => Boolean(money && money.amount > 0),+ // 旧 turnCostUsd 没有可靠币种,继续沿用原有兼容边界;仅结构化估值可独立展示。+ const legacyCurrency = actualMoney?.currency ?? DEFAULT_USAGE_CURRENCY;+ const displayedEstimate =+ estimatedValueMoney?.estimateReasons?.includes('legacy-usd') &&+ estimatedValueMoney.currency !== legacyCurrency+ ? null+ : estimatedValueMoney;+ // 零费用只是占位,不能用它的区域币种过滤实际存在的订阅估值。+ // 异币种保留各自金额供 UI 分别展示,不换算、不伪造合计。+ const values = [actualMoney, displayedEstimate].filter((money): money is RegionalMoney =>+ Boolean(money && money.amount > 0),);+ const currency = values[0]?.currency;return {actualMoney,- estimatedValueMoney: compatibleEstimatedValueMoney,+ estimatedValueMoney: displayedEstimate,totalMoney:- values.length > 0- ? addCompatibleRegionalMoney(values, preferredCurrency)+ currency && values.every((money) => money.currency === currency)+ ? addCompatibleRegionalMoney(values, currency): null,};}