Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 聚合同一用户轮的用量明细 (#1830)
Chris Zhang5a8f1100c81f
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.tsindex a732901f35..f38ee22048 100644--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts@@ -26,16 +26,17 @@ const localeSources = ['en', 'zh-CN', 'ja', 'ko'].map((locale) =>);describe('TodaySpendChip dashboard routing', () => {- it('separates the latest user-round total from final-segment token details', () => {+ it('keeps the latest user-round total separate while aggregating token/model details', () => {expect(source).toContain('message.userTurnMoney?.amount');expect(source).toContain('const userTurnCostUsd = typeof message.userTurnCostUsd');expect(source).toContain('? { money: userTurnMoney }');expect(source).toContain('isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null)');expect(source).toContain("'todaySpend.tooltip.latestUserTurnTitle'");- expect(source).toContain('segmentMoney: message.turnMoney');- expect(source).toContain('segmentCostUsd: message.turnCostUsd');- expect(source).toContain('money: summary.isUserTurnTotal ? summary.segmentMoney : summary.money');- expect(source).toContain("'chat.messageActionBar.userTurnCostDetailsTitle'");+ expect(source).toContain('aggregateAssistantTurnUsageDetails(messages, message.clientId)');+ expect(source).toContain('Amount and token/model detail now describe the same visible user turn');+ expect(source).toContain('money: summary.money');+ expect(source).not.toContain('segmentMoney: message.turnMoney');+ expect(source).not.toContain('segmentCostUsd: message.turnCostUsd');expect(source).toContain('inputTokensText: formatCompactTokens(details.inputTokens)');expect(source).toContain('outputTokensText: formatCompactTokens(details.outputTokens)');});diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsxindex e74e212b2f..4b0c3f73ca 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -182,6 +182,8 @@ interface AssistantMessageProps {userTurnCostIsEstimate?: boolean;/** Per-turn token/cache 明细。 */turnUsageDetails?: TurnUsageDetails;+ /** 同一用户轮跨多个 SDK segment 聚合后的 token/cache/model 明细。 */+ userTurnUsageDetails?: TurnUsageDetails;/** 本轮模型降级标记(main turn 结束检测命中时挂到收尾 assistant 上),* 正文下方渲染一条常显的降级提示行。 */modelMismatch?: { selected: string; actual: string };@@ -211,6 +213,7 @@ export const AssistantMessage = memo(function AssistantMessage({userTurnCostUsd,userTurnCostIsEstimate,turnUsageDetails,+ userTurnUsageDetails,modelMismatch,ghostReplyPending,}: AssistantMessageProps) {@@ -376,7 +379,7 @@ export const AssistantMessage = memo(function AssistantMessage({userTurnMoney={userTurnMoney}userTurnCostUsd={userTurnCostUsd}userTurnCostIsEstimate={userTurnCostIsEstimate}- turnUsageDetails={turnUsageDetails}+ turnUsageDetails={userTurnUsageDetails ?? turnUsageDetails}/>)}</div>diff --git a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsxindex 0173e152df..dc0276eed9 100644--- a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx@@ -364,17 +364,11 @@ export function MessageActionBar({const turnCostTooltipNode =displayedMoney && displayedMoney.amount > 0 && turnUsageDetails ? (<span className="whitespace-pre-line">- {isUserTurnTotal &&- `${t('chat.messageActionBar.userTurnCostTotalLine', {- cost: formatTurnCostMoney(displayedMoney),- })}\n`}{buildTurnUsageTooltipLines({details: turnUsageDetails,t,- // Token / model detail is currently scoped to this final SDK segment;- // never pair it with the user-turn cumulative total above.- money: isUserTurnTotal ? effectiveTurnMoney : displayedMoney,- isEstimate: isUserTurnTotal ? turnCostIsEstimate : displayedCostIsEstimate,+ money: displayedMoney,+ isEstimate: displayedCostIsEstimate,...(isUserTurnTotal ? { title: t('chat.messageActionBar.userTurnCostDetailsTitle') } : {}),}).join('\n')}</span>diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 5ce12ede54..3d9cec35ea 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -209,6 +209,8 @@ import {} from './autoFollowIntent';import { useNavigationKeyListener } from './useNavigationKeyListener';import { suppressScrollbarActivation } from '@/lib/scrollbarAutoHide';+import { collectAssistantTurnUsageDetails } from '@/lib/userTurnUsage';+import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';interface MessageStreamProps {/** Active session id — used to reset scroll state on session switch. */@@ -2073,6 +2075,7 @@ function renderWorkGroupChild(assistantsWithFollowingUserBoundary: ReadonlySet<string>;turnFinalAssistantClientIds: ReadonlySet<string>;subagentModelByToolUseId: ReadonlyMap<string, string>;+ userTurnUsageDetailsByAssistantId: ReadonlyMap<string, TurnUsageDetails>;},): ReactNode {if (item.type === 'agent_task') {@@ -2107,6 +2110,7 @@ function renderWorkGroupChild(props.assistantsWithFollowingUserBoundary,)}assistantIsTurnFinal={props.turnFinalAssistantClientIds.has(item.message.clientId)}+ userTurnUsageDetails={props.userTurnUsageDetailsByAssistantId.get(item.message.clientId)}isFirstUserMessage={item.message.clientId === props.firstUserMessageClientId}isLastUserMessage={item.message.clientId === props.lastUserMessageClientId}isLastUserInput={item.message.clientId === props.lastUserInputClientId}@@ -3572,6 +3576,10 @@ export function MessageStream({// 含合成行的"最后一条用户侧输入":自愈重连行据此判断自己是不是仍在飞(见 helper 注释)。const lastUserInputClientId = useMemo(() => findLastUserInputClientId(messages), [messages]);+ const userTurnUsageDetailsByAssistantId = useMemo(() => {+ return collectAssistantTurnUsageDetails(messages, turnFinalAssistantClientIds);+ }, [messages, turnFinalAssistantClientIds]);+// error-tail-banner:尾部未忽略的 error 行由输入框上方红条独家承载,流内需要// 知道"是不是最后一条"来跳过重复渲染。const lastMessageClientId =@@ -3734,6 +3742,7 @@ export function MessageStream({assistantsWithFollowingUserBoundary,turnFinalAssistantClientIds,subagentModelByToolUseId,+ userTurnUsageDetailsByAssistantId,}),};};@@ -3846,6 +3855,7 @@ export function MessageStream({assistantsWithFollowingUserBoundary,)}assistantIsTurnFinal={turnFinalAssistantClientIds.has(msg.clientId)}+ userTurnUsageDetails={userTurnUsageDetailsByAssistantId.get(msg.clientId)}isFirstUserMessage={msg.clientId === firstUserMessageClientId}isLastUserMessage={msg.clientId === lastUserMessageClientId}isLastUserInput={msg.clientId === lastUserInputClientId}@@ -3940,6 +3950,7 @@ const MessageItem = memo(function MessageItem({sessionRunning,assistantForkBlocked,assistantIsTurnFinal,+ userTurnUsageDetails,isFirstUserMessage,isLastUserMessage,isLastUserInput,@@ -3970,6 +3981,8 @@ const MessageItem = memo(function MessageItem({* (collectTurnFinalAssistantClientIds). Gates the hover action bar —* mid-turn texts don't mount it, keeping the stream compact. */assistantIsTurnFinal?: boolean;+ /** Aggregated token/cache/model details for this assistant's visible user turn. */+ userTurnUsageDetails?: TurnUsageDetails;/** True iff this message is the first user message in the visible list.* UserMessage hides the Rewind button for it (no prior assistant to* resumeSessionAt anchor on — backend would throw NO_PRIOR_ASSISTANT). */@@ -4077,6 +4090,7 @@ const MessageItem = memo(function MessageItem({userTurnCostUsd={message.userTurnCostUsd}userTurnCostIsEstimate={message.userTurnCostIsEstimate}turnUsageDetails={message.turnUsageDetails}+ userTurnUsageDetails={userTurnUsageDetails}modelMismatch={message.modelMismatch}ghostReplyPending={message.ghostReplyPending}/>diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MessageActionBar.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MessageActionBar.test.tsxindex 5131b439e4..61bc997bb2 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/MessageActionBar.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/MessageActionBar.test.tsx@@ -217,7 +217,7 @@ describe('MessageActionBar', () => {await waitFor(() => expect(document.activeElement).toBe(trigger));});- it('renders the user-turn total and SDK segment details on separate lines', () => {+ it('renders the user-turn total and aggregated details on separate lines', () => {render(<MessageActionBarcopyText="message body"@@ -242,6 +242,17 @@ describe('MessageActionBar', () => {cacheCreateTokens: 0,totalTokens: 15,cacheHitRate: 0,+ models: ['claude-fable-5[1m]', 'claude-opus-5[1m]'],+ perModelCost: [+ {+ model: 'claude-fable-5',+ money: { amount: 0.75, currency: 'CNY', approximate: false, kind: 'actual-cost' },+ },+ {+ model: 'claude-opus-5',+ money: { amount: 1.25, currency: 'CNY', approximate: false, kind: 'actual-cost' },+ },+ ],}}/>,);@@ -249,13 +260,15 @@ describe('MessageActionBar', () => {const tooltip = screen.getByText((_, element) =>element?.classList.contains('whitespace-pre-line') === true &&- element.textContent?.includes('chat.messageActionBar.userTurnCostTotalLine') === true,+ element.textContent?.includes('chat.messageActionBar.userTurnCostDetailsTitle') === true,);expect(tooltip.textContent).toBe([- 'chat.messageActionBar.userTurnCostTotalLine','chat.messageActionBar.userTurnCostDetailsTitle','usageDetails.costLine',+ 'usageDetails.costBreakdownHeader',+ 'usageDetails.modelCostLine',+ 'usageDetails.modelCostLine','usageDetails.tokenLine','usageDetails.cacheLine',].join('\n'),diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsxindex e03e05afe6..9a432ce5a9 100644--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx@@ -19,10 +19,6 @@ export interface QuotaHoverCardTurnUsage {costText?: string | null;costIsEstimate?: boolean;isUserTurnTotal?: boolean;- finalSegment?: {- costText?: string | null;- costIsEstimate?: boolean;- } | null;totalTokensText?: string | null;inputTokensText?: string | null;outputTokensText?: string | null;@@ -238,21 +234,6 @@ function TurnUsageSection({ turnUsage, t }: { turnUsage: QuotaHoverCardTurnUsage)}</div>- {turnUsage.finalSegment ? (- <div className="mt-2">- <div className="mb-[3px] text-xs font-medium text-[var(--text-secondary)]">- {t('chat.messageActionBar.userTurnCostDetailsTitle')}- </div>- <div className="tabular-nums">- {renderCostLine(- turnUsage.finalSegment.costText,- turnUsage.finalSegment.costIsEstimate,- 'quotaCard.noBilledCost',- )}- </div>- </div>- ) : null}-{showModelCostBreakdown ? (<div data-testid="quota-model-cost-breakdown" className="mt-2"><div className="mb-[3px] text-xs font-medium text-[var(--text-secondary)]">diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 0708968f55..e11a6433a5 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -92,6 +92,7 @@ import {buildTurnUsageTooltipLines,getTurnUsageSuggestion,} from '@/lib/turnUsageTooltip';+import { aggregateAssistantTurnUsageDetails } from '@/lib/userTurnUsage';import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';import {DEFAULT_USAGE_CURRENCY,@@ -685,9 +686,6 @@ interface LatestTurnUsageSummary {money?: RegionalMoney;costUsd?: number;isEstimate?: boolean;- segmentMoney?: RegionalMoney;- segmentCostUsd?: number;- segmentIsEstimate?: boolean;isUserTurnTotal: boolean;details: TurnUsageDetails;}@@ -737,26 +735,11 @@ function toQuotaHoverCardTurnUsage(: summary.costUsd != null? formatTurnCostUsd(summary.costUsd): null;- const finalSegmentCostText = summary.segmentMoney- ? formatTurnCostMoney(summary.segmentMoney)- : summary.segmentCostUsd != null- ? formatTurnCostUsd(summary.segmentCostUsd)- : null;return {costText,costIsEstimate: summary.isEstimate,isUserTurnTotal: summary.isUserTurnTotal,- // userTurnMoney 是用户轮累计,而 turnUsageDetails 始终只描述收尾 SDK 分段。- // 两笔金额可能因前段无报价而恰好相等,不能用金额相等反推只有一个分段。- ...(summary.isUserTurnTotal- ? {- finalSegment: {- costText: finalSegmentCostText,- costIsEstimate: summary.segmentIsEstimate,- },- }- : {}),totalTokensText: formatCompactTokens(Math.max(0, Math.floor(details.totalTokens))),inputTokensText: formatCompactTokens(details.inputTokens),outputTokensText: formatCompactTokens(details.outputTokens),@@ -825,21 +808,13 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSum|| displayedMoney?.kind === 'value-estimate'? { isEstimate: true }: {}),- ...((userTurnMoney || userTurnCostUsd != null) && message.turnMoney?.amount- ? {- segmentMoney: message.turnMoney,- segmentIsEstimate:- message.turnCostIsEstimate === true- || message.turnMoney.kind === 'value-estimate',- }- : userTurnCostUsd != null && typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0- ? {- segmentCostUsd: message.turnCostUsd,- segmentIsEstimate: message.turnCostIsEstimate === true,- }- : {}),isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null),- details: message.turnUsageDetails,+ // Amount and token/model detail now describe the same visible user turn.+ // Raw segment costs remain persisted for billing and analytics, but are+ // an implementation detail rather than a second user-facing total.+ details:+ aggregateAssistantTurnUsageDetails(messages, message.clientId) ??+ message.turnUsageDetails,};}return null;@@ -879,28 +854,17 @@ function appendLatestTurnUsageLines(): void {if (!summary) return;if (lines.length > 0) lines.push('');- if (- summary.isUserTurnTotal &&- (summary.money?.amount || summary.costUsd != null)- ) {- lines.push(t('todaySpend.tooltip.latestUserTurnTitle'));- lines.push(t(summary.isEstimate ? 'usageDetails.valueLine' : 'usageDetails.costLine', {- cost: summary.money- ? formatTurnCostMoney(summary.money)- : formatTurnCostUsd(summary.costUsd ?? 0),- }));- }lines.push(...buildTurnUsageTooltipLines({details: summary.details,t,- // Token / model detail remains scoped to the final SDK segment. Keep its- // cost line separate from the user-turn total shown above.- money: summary.isUserTurnTotal ? summary.segmentMoney : summary.money,- costUsd: summary.isUserTurnTotal ? summary.segmentCostUsd : summary.costUsd,- isEstimate: summary.isUserTurnTotal ? summary.segmentIsEstimate : summary.isEstimate,- title: t(summary.isUserTurnTotal- ? 'chat.messageActionBar.userTurnCostDetailsTitle'- : 'todaySpend.tooltip.latestTurnTitle'),+ money: summary.money,+ costUsd: summary.costUsd,+ isEstimate: summary.isEstimate,+ title: t(+ summary.isUserTurnTotal+ ? 'todaySpend.tooltip.latestUserTurnTitle'+ : 'todaySpend.tooltip.latestTurnTitle',+ ),}));}diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsxindex e861d3b506..0be5c630e2 100644--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx@@ -30,7 +30,7 @@ vi.mock('react-i18next', () => ({if (key === 'usageDetails.modelCostLine') return `· ${options.model} ${options.cost}`;if (key === 'quotaCard.turnCostUnavailable') return '本轮费用暂无法估算';if (key === 'quotaCard.latestMessageTitle') return '最近一轮用户请求累计';- if (key === 'chat.messageActionBar.userTurnCostDetailsTitle') return '最后一个 SDK 分段';+ if (key === 'chat.messageActionBar.userTurnCostDetailsTitle') return '本轮明细';if (key === 'quotaCard.staleData') return `quotaCard.staleData:${options.minutes}`;return key;},@@ -341,7 +341,7 @@ describe('QuotaHoverCard', () => {expect(screen.getByText('本任务价值 $0.50')).toBeTruthy();});- it('marks estimated value and separates cumulative totals from final-segment details', () => {+ it('marks estimated value and labels user-turn totals without exposing SDK segments', () => {const { rerender } = render(<QuotaHoverCardsnapshot={null}@@ -355,7 +355,7 @@ describe('QuotaHoverCard', () => {);expect(screen.getByText('本轮 token 价值:$0.46')).toBeTruthy();- expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();+ expect(screen.queryByText('本轮明细')).toBeNull();rerender(<QuotaHoverCard@@ -364,7 +364,6 @@ describe('QuotaHoverCard', () => {turnUsage={{costText: '$0.70',isUserTurnTotal: true,- finalSegment: { costText: '$0.20' },totalTokensText: '74.1K',}}/>,@@ -372,8 +371,7 @@ describe('QuotaHoverCard', () => {expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();- expect(screen.getByText('最后一个 SDK 分段')).toBeTruthy();- expect(screen.getByText('本轮消耗:$0.20')).toBeTruthy();+ expect(screen.queryByText('本轮明细')).toBeNull();});it('多模型分段逐模型展示费用,不再重复笼统模型行', () => {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 82a6e94a9c..2662335eff 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@@ -48,7 +48,7 @@ vi.mock('react-i18next', () => ({'quotaCard.modelLabel': '模型','quotaCard.waiting': '等待额度数据','quotaCard.latestMessageTitle': '最近一轮用户请求累计',- 'chat.messageActionBar.userTurnCostDetailsTitle': '最后一个 SDK 分段',+ 'chat.messageActionBar.userTurnCostDetailsTitle': '本轮明细','quotaCard.costLine': '本轮消耗:{{cost}}','quotaCard.valueLine': '本轮 token 价值:{{cost}}','quotaCard.noBilledCost': '本轮费用暂不可用,仅显示用量',@@ -137,6 +137,7 @@ function usdMoney(function setLatestUsageMessage(overrides: Record<string, unknown> = {}) {mocks.displaySnapshot.messages = [{+ clientId: 'assistant-1',role: 'assistant',turnMoney: usdMoney(0.46),turnUsageDetails: TURN_USAGE_DETAILS,@@ -476,7 +477,7 @@ describe('TodaySpendChip Claude subscription popover', () => {expect(within(sessionSection).queryByText('本任务已用 $0.50')).toBeNull();});- it('等额累计投影仍分开用户轮累计与最后分段明细', () => {+ it('等额累计投影仍只展示一份用户轮明细', () => {setLatestUsageMessage({turnMoney: usdMoney(0.46, 'value-estimate'),userTurnMoney: usdMoney(0.46, 'value-estimate'),@@ -486,8 +487,8 @@ describe('TodaySpendChip Claude subscription popover', () => {const equalAmount = renderClaudeSubscriptionChip();openCardFromHover();expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();- expect(screen.getByText('最后一个 SDK 分段')).toBeTruthy();- expect(screen.getAllByText('本轮 token 价值:$0.46')).toHaveLength(2);+ expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();+ expect(screen.getAllByText('本轮 token 价值:$0.46')).toHaveLength(1);equalAmount.unmount();vi.clearAllTimers();@@ -501,11 +502,72 @@ describe('TodaySpendChip Claude subscription popover', () => {openCardFromHover();expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();- expect(screen.getByText('最后一个 SDK 分段')).toBeTruthy();- expect(screen.getByText('本轮消耗:$0.20')).toBeTruthy();+ expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();expect(screen.getByText(/^74\.0k/)).toBeTruthy();});+ it('聚合自动续跑前后的 Token 与逐模型费用', () => {+ mocks.displaySnapshot.messages = [+ {+ clientId: 'user-1',+ role: 'user',+ delivery: 'turn',+ content: '开始任务',+ },+ {+ clientId: 'assistant-fable',+ role: 'assistant',+ content: '第一段',+ turnMoney: usdMoney(0.2),+ turnUsageDetails: {+ inputTokens: 50,+ outputTokens: 20,+ cacheReadTokens: 60,+ cacheCreateTokens: 5,+ totalTokens: 135,+ cacheHitRate: 60 / 115,+ model: 'claude-fable-5',+ perModelCost: [{ model: 'claude-fable-5', money: usdMoney(0.2) }],+ },+ },+ {+ clientId: 'auto-resume-1',+ role: 'user',+ delivery: 'turn',+ systemCardType: 'auto-resume',+ content: '',+ },+ {+ clientId: 'assistant-opus',+ role: 'assistant',+ content: '第二段',+ turnMoney: usdMoney(0.5),+ userTurnMoney: usdMoney(0.7),+ turnUsageDetails: {+ inputTokens: 30,+ outputTokens: 12,+ cacheReadTokens: 15,+ cacheCreateTokens: 5,+ totalTokens: 62,+ cacheHitRate: 0.3,+ model: 'claude-opus-5',+ perModelCost: [{ model: 'claude-opus-5', money: usdMoney(0.5) }],+ },+ },+ ];++ renderClaudeSubscriptionChip();+ openCardFromHover();++ expect(screen.getByText('最近一轮用户请求累计')).toBeTruthy();+ expect(screen.getByText('本轮消耗:$0.70')).toBeTruthy();+ expect(screen.getByText(/^197/)).toBeTruthy();+ expect(screen.getByText('按模型拆分:')).toBeTruthy();+ expect(screen.getByText('· claude-fable-5 $0.20')).toBeTruthy();+ expect(screen.getByText('· claude-opus-5 $0.50')).toBeTruthy();+ expect(screen.queryByText('最后一个 SDK 分段')).toBeNull();+ });+it('无报价时说明费用不可用并保留 Token、缓存和模型明细', () => {setLatestUsageMessage({ turnMoney: undefined });renderClaudeSubscriptionChip();@@ -517,7 +579,7 @@ describe('TodaySpendChip Claude subscription popover', () => {expect(screen.getByText('claude-opus-5[1m]')).toBeTruthy();});- it('保留最后 SDK 分段的逐模型费用拆分', () => {+ it('保留用户轮的逐模型费用拆分', () => {setLatestUsageMessage({turnUsageDetails: {...TURN_USAGE_DETAILS,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ecd9ea6735..a5b5330eed 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5633,8 +5633,7 @@"turnCostEstimated": "Token value this turn (API-price equivalent)","turnCostEstimatedValue": "Worth {{cost}}","turnTokens": "{{tokens}} tokens",- "userTurnCostTotalLine": "User-turn total: {{cost}}",- "userTurnCostDetailsTitle": "Final SDK segment"+ "userTurnCostDetailsTitle": "Request details"},"errorBanner": {"retryTitle": "Resend the last message",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 8911ee09c4..80a05291e2 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5631,8 +5631,7 @@"turnCostEstimated": "このターンの token 価値(API 単価換算)","turnCostEstimatedValue": "価値 {{cost}}","turnTokens": "{{tokens}} tokens",- "userTurnCostTotalLine": "このユーザーターンの合計: {{cost}}",- "userTurnCostDetailsTitle": "最終 SDK セグメント"+ "userTurnCostDetailsTitle": "リクエストの明細"},"errorBanner": {"retryTitle": "最後のメッセージを再送信",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 2f32c79b27..f72ebb89ad 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5631,8 +5631,7 @@"turnCostEstimated": "이번 턴 토큰 가치(API 단가 환산)","turnCostEstimatedValue": "가치 {{cost}}","turnTokens": "{{tokens}} tokens",- "userTurnCostTotalLine": "이번 사용자 턴 합계: {{cost}}",- "userTurnCostDetailsTitle": "마지막 SDK 세그먼트"+ "userTurnCostDetailsTitle": "이번 요청 상세"},"errorBanner": {"retryTitle": "마지막 메시지 다시 보내기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 88e5145cca..77decfdc58 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5631,8 +5631,7 @@"turnCostEstimated": "本轮 token 价值(按 API 单价折算)","turnCostEstimatedValue": "价值 {{cost}}","turnTokens": "{{tokens}} tokens",- "userTurnCostTotalLine": "本轮累计:{{cost}}",- "userTurnCostDetailsTitle": "最后一个 SDK 分段"+ "userTurnCostDetailsTitle": "本轮明细"},"errorBanner": {"retryTitle": "重新发送最后一条消息",diff --git a/apps/desktop/src/renderer/lib/__tests__/userTurnUsage.test.ts b/apps/desktop/src/renderer/lib/__tests__/userTurnUsage.test.tsnew file mode 100644index 0000000000..5b21072052--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/userTurnUsage.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';++import type { ChatMessage } from '../makerChatStore';+import {+ aggregateAssistantTurnUsageDetails,+ collectAssistantTurnUsageDetails,+} from '../userTurnUsage';+import { buildTurnUsageDetails } from '../../../shared/turnUsageDetails';+import { usdMoney } from '../../../shared/regionalMoney';++function assistant(+ clientId: string,+ turnUsageDetails: ChatMessage['turnUsageDetails'],+): ChatMessage {+ return {+ clientId,+ role: 'assistant',+ content: clientId,+ turnUsageDetails,+ };+}++function user(clientId: string, systemCardType?: ChatMessage['systemCardType']): ChatMessage {+ return {+ clientId,+ role: 'user',+ content: clientId,+ delivery: 'turn',+ ...(systemCardType ? { systemCardType } : {}),+ };+}++describe('aggregateAssistantTurnUsageDetails', () => {+ it('merges every SDK segment after the latest real user boundary', () => {+ const first = buildTurnUsageDetails({+ inputTokens: 10,+ outputTokens: 20,+ cacheReadTokens: 100,+ cacheCreateTokens: 5,+ perModelCost: [{ model: 'claude-fable-5', money: usdMoney(2) }],+ });+ const final = buildTurnUsageDetails({+ inputTokens: 3,+ outputTokens: 7,+ cacheReadTokens: 50,+ cacheCreateTokens: 2,+ perModelCost: [{ model: 'claude-opus-5', money: usdMoney(4) }],+ });+ const details = aggregateAssistantTurnUsageDetails(+ [+ user('u1'),+ assistant('a1', first ?? undefined),+ user('resume', 'auto-resume'),+ assistant('a2', final ?? undefined),+ ],+ 'a2',+ );++ expect(details?.totalTokens).toBe(197);+ expect(details?.perModelCost).toEqual([+ { model: 'claude-fable-5', money: usdMoney(2) },+ { model: 'claude-opus-5', money: usdMoney(4) },+ ]);+ });++ it('does not merge into an older turn when the loaded history has no boundary', () => {+ const old = buildTurnUsageDetails({ inputTokens: 1, outputTokens: 1 });+ const current = buildTurnUsageDetails({ inputTokens: 2, outputTokens: 2 });+ const details = aggregateAssistantTurnUsageDetails(+ [assistant('old', old ?? undefined), assistant('current', current ?? undefined)],+ 'current',+ );+ expect(details).toBe(current);+ });++ it('collects selected final assistants in one pass without crossing user turns', () => {+ const first = buildTurnUsageDetails({ inputTokens: 10, outputTokens: 5 })!;+ const resumed = buildTurnUsageDetails({ inputTokens: 4, outputTokens: 1 })!;+ const next = buildTurnUsageDetails({ inputTokens: 3, outputTokens: 2 })!;+ const messages = [+ user('u1'),+ assistant('a1', first),+ user('resume', 'auto-resume'),+ assistant('a2', resumed),+ user('u2'),+ assistant('a3', next),+ ];++ const details = collectAssistantTurnUsageDetails(messages, new Set(['a2', 'a3']));+ expect(details.get('a2')?.totalTokens).toBe(20);+ expect(details.get('a3')).toBe(next);+ expect(details.has('a1')).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/lib/userTurnUsage.ts b/apps/desktop/src/renderer/lib/userTurnUsage.tsnew file mode 100644index 0000000000..0ff73febf2--- /dev/null+++ b/apps/desktop/src/renderer/lib/userTurnUsage.ts@@ -0,0 +1,74 @@+import type { ChatMessage } from './makerChatStore';+import { aggregateTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails';++function isUserTurnBoundary(message: ChatMessage): boolean {+ return (+ message.role === 'user' &&+ message.delivery !== 'steer' &&+ message.systemCardType !== 'auto-resume'+ );+}++/**+ * Return the token/model details for the visible user turn containing an+ * assistant message. If the loaded history starts in the middle of a turn,+ * keep the target segment only instead of accidentally merging an older turn.+ */+export function aggregateAssistantTurnUsageDetails(+ messages: readonly ChatMessage[],+ assistantClientId: string,+): TurnUsageDetails | null {+ const targetIndex = messages.findIndex((message) => message.clientId === assistantClientId);+ if (targetIndex < 0 || messages[targetIndex].role !== 'assistant') return null;++ const segments: TurnUsageDetails[] = [];+ let foundBoundary = false;+ for (let index = targetIndex; index >= 0; index -= 1) {+ const message = messages[index];+ if (isUserTurnBoundary(message)) {+ foundBoundary = true;+ break;+ }+ if (message.role === 'assistant' && message.turnUsageDetails) {+ segments.push(message.turnUsageDetails);+ }+ }++ const targetDetails = messages[targetIndex].turnUsageDetails;+ if (!targetDetails) return null;+ if (!foundBoundary || segments.length <= 1) return targetDetails;+ return aggregateTurnUsageDetails(segments.reverse()) ?? targetDetails;+}++/**+ * Build user-turn usage for selected assistant messages in one linear pass.+ * MessageStream calls this while tokens stream, so repeated backward scans+ * would make long histories quadratic even though only final answers consume it.+ */+export function collectAssistantTurnUsageDetails(+ messages: readonly ChatMessage[],+ assistantClientIds: ReadonlySet<string>,+): Map<string, TurnUsageDetails> {+ const out = new Map<string, TurnUsageDetails>();+ let hasBoundary = false;+ let segments: TurnUsageDetails[] = [];++ for (const message of messages) {+ if (isUserTurnBoundary(message)) {+ hasBoundary = true;+ segments = [];+ continue;+ }+ if (message.role !== 'assistant' || !message.turnUsageDetails) continue;+ segments.push(message.turnUsageDetails);+ if (!assistantClientIds.has(message.clientId)) continue;++ const details =+ hasBoundary && segments.length > 1+ ? aggregateTurnUsageDetails(segments)+ : message.turnUsageDetails;+ out.set(message.clientId, details ?? message.turnUsageDetails);+ }++ return out;+}diff --git a/apps/desktop/src/shared/__tests__/turnUsageDetails.test.ts b/apps/desktop/src/shared/__tests__/turnUsageDetails.test.tsnew file mode 100644index 0000000000..4a19d27dd4--- /dev/null+++ b/apps/desktop/src/shared/__tests__/turnUsageDetails.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';++import { aggregateTurnUsageDetails, buildTurnUsageDetails } from '../turnUsageDetails';+import { DEFAULT_USAGE_CURRENCY, gatewayMoney, usdMoney } from '../regionalMoney';++describe('aggregateTurnUsageDetails', () => {+ it('sums token/cache fields and merges per-model costs across segments', () => {+ const first = buildTurnUsageDetails({+ inputTokens: 10,+ outputTokens: 20,+ cacheReadTokens: 100,+ cacheCreateTokens: 5,+ model: 'claude-fable-5[1m]',+ perModelCost: [{ model: 'claude-fable-5', money: usdMoney(2.5) }],+ });+ const second = buildTurnUsageDetails({+ inputTokens: 3,+ outputTokens: 7,+ cacheReadTokens: 50,+ cacheCreateTokens: 2,+ models: ['claude-fable-5[1m]', 'claude-opus-5[1m]'],+ perModelCost: [+ { model: 'claude-fable-5', money: usdMoney(1.25) },+ { model: 'claude-opus-5', money: usdMoney(4) },+ ],+ });++ const aggregated = aggregateTurnUsageDetails([first, second]);+ expect(aggregated).toMatchObject({+ inputTokens: 13,+ outputTokens: 27,+ cacheReadTokens: 150,+ cacheCreateTokens: 7,+ totalTokens: 197,+ models: ['claude-fable-5[1m]', 'claude-opus-5[1m]'],+ });+ expect(aggregated?.perModelCost).toEqual([+ { model: 'claude-fable-5', money: usdMoney(3.75) },+ { model: 'claude-opus-5', money: usdMoney(4) },+ ]);+ expect(aggregated?.cacheHitRate).toBeCloseTo(150 / 170);+ });++ it('uses the default usage currency when the same model has mixed segment currencies', () => {+ const staleCurrency = DEFAULT_USAGE_CURRENCY === 'USD' ? 'CNY' : 'USD';+ const first = buildTurnUsageDetails({+ inputTokens: 1,+ perModelCost: [{ model: 'claude-fable-5', money: gatewayMoney(4, staleCurrency) }],+ });+ const second = buildTurnUsageDetails({+ outputTokens: 1,+ perModelCost: [+ {+ model: 'claude-fable-5',+ money: gatewayMoney(6, DEFAULT_USAGE_CURRENCY),+ },+ ],+ });++ expect(aggregateTurnUsageDetails([first, second])?.perModelCost).toEqual([+ {+ model: 'claude-fable-5',+ money: gatewayMoney(6, DEFAULT_USAGE_CURRENCY),+ },+ ]);+ });++ it('ignores empty details and returns null when no segment has usage', () => {+ expect(aggregateTurnUsageDetails([null, undefined])).toBeNull();+ expect(+ aggregateTurnUsageDetails([+ {+ inputTokens: 0,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ totalTokens: 0,+ cacheHitRate: null,+ },+ ]),+ ).toBeNull();+ });+});diff --git a/apps/desktop/src/shared/turnUsageDetails.ts b/apps/desktop/src/shared/turnUsageDetails.tsindex 972c949f54..2d87fdda7d 100644--- a/apps/desktop/src/shared/turnUsageDetails.ts+++ b/apps/desktop/src/shared/turnUsageDetails.ts@@ -107,6 +107,51 @@ function sanitizePerModelCost(: undefined;}+/**+ * 合并同一用户轮里多个 SDK segment 的用量明细。+ *+ * Claude Code 的一次可见回答可能跨多个 SDK segment(例如并行 Task/+ * subagent 先后结束)。金额账本按 segment 保存,但 tooltip 需要把 token、模型+ * 和按模型成本投影成同一轮,避免只展示最后一个 segment 而藏掉子 agent。+ */+export function aggregateTurnUsageDetails(+ detailsList: readonly (TurnUsageDetails | null | undefined)[],+): TurnUsageDetails | null {+ const details = detailsList.filter(+ (item): item is TurnUsageDetails => Boolean(item && item.totalTokens > 0),+ );+ if (details.length === 0) return null;++ const modelNames: string[] = [];+ const addModel = (model: string | undefined) => {+ if (model && !modelNames.includes(model)) modelNames.push(model);+ };+ const perModel = new Map<string, RegionalMoney>();+ for (const detail of details) {+ addModel(detail.model);+ for (const model of detail.models ?? []) addModel(model);+ for (const item of detail.perModelCost ?? []) {+ const current = perModel.get(item.model);+ perModel.set(+ item.model,+ current+ ? (addCompatibleRegionalMoney([current, item.money]) ?? item.money)+ : item.money,+ );+ }+ }++ return buildTurnUsageDetails({+ inputTokens: details.reduce((sum, item) => sum + item.inputTokens, 0),+ outputTokens: details.reduce((sum, item) => sum + item.outputTokens, 0),+ cacheReadTokens: details.reduce((sum, item) => sum + item.cacheReadTokens, 0),+ cacheCreateTokens: details.reduce((sum, item) => sum + item.cacheCreateTokens, 0),+ model: modelNames.length === 1 ? modelNames[0] : undefined,+ models: modelNames,+ perModelCost: [...perModel.entries()].map(([model, money]) => ({ model, money })),+ });+}+/** Build a normalized usage detail object. Returns null when all token counts are 0. */export function buildTurnUsageDetails(input: BuildTurnUsageDetailsInput): TurnUsageDetails | null {const inputTokens = sanitizeToken(input.inputTokens);